diff --git a/local-test-curl-delta-01/afc-curl/CMake/Platforms/WindowsCache.cmake b/local-test-curl-delta-01/afc-curl/CMake/Platforms/WindowsCache.cmake new file mode 100644 index 0000000000000000000000000000000000000000..077bed228e95e3fcbfbfece5abf6005492b98972 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/CMake/Platforms/WindowsCache.cmake @@ -0,0 +1,194 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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) + set(HAVE_STRINGS_H 1) # wrapper to string.h + set(HAVE_UTIME_H 1) # wrapper to sys/utime.h + set(HAVE_DIRENT_H 1) + set(HAVE_OPENDIR 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) + set(HAVE_STRINGS_H 0) + set(HAVE_UTIME_H 0) + set(HAVE_DIRENT_H 0) + set(HAVE_OPENDIR 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_SENDMMSG 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_EVENTFD 0) +set(HAVE_IF_NAMETOINDEX 0) +set(HAVE_GETRLIMIT 0) +set(HAVE_SETRLIMIT 0) +set(HAVE_FSETXATTR 0) +set(HAVE_SETLOCALE 1) +set(HAVE_SETMODE 1) +set(HAVE__SETMODE 1) +set(HAVE_GETPEERNAME 1) +set(HAVE_GETSOCKNAME 1) +set(HAVE_GETHOSTNAME 1) + +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_IN6_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 0) +set(HAVE_PWD_H 0) +set(HAVE_SYS_EVENTFD_H 0) +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_LINUX_TCP_H 0) + +set(HAVE_FSEEKO 0) # mingw-w64 2.0.0 and newer has it +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_GLIBC_STRERROR_R 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_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/local-test-curl-delta-01/afc-curl/docs/examples/.checksrc b/local-test-curl-delta-01/afc-curl/docs/examples/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..dea90aaa1d1122d49625ab09cbcf8a5de6ad5a30 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/.checksrc @@ -0,0 +1,3 @@ +disable TYPEDEFSTRUCT +disable SNPRINTF +disable BANNEDFUNC diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/.gitignore b/local-test-curl-delta-01/afc-curl/docs/examples/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..68f96939aa993aff51fd8088490d36a56abd7751 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/.gitignore @@ -0,0 +1,120 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +10-at-a-time +address-scope +altsvc +anyauthput +certinfo +chkspeed +connect-to +cookie_interface +debug +default-scheme +externalsocket +fileupload +fopen +ftp-wildcard +ftpget +ftpgetinfo +ftpgetresp +ftpsget +ftpupload +ftpuploadfrommem +ftpuploadresume +getinfo +getinmemory +getredirect +getreferrer +headerapi +hsts-preload +http-options +http-post +http2-download +http2-pushinmemory +http2-serverpush +http2-upload +http3 +http3-present +httpcustomheader +httpput +httpput-postfields +https +imap-append +imap-authzid +imap-copy +imap-create +imap-delete +imap-examine +imap-fetch +imap-list +imap-lsub +imap-multi +imap-noop +imap-search +imap-ssl +imap-store +imap-tls +interface +ipv6 +keepalive +localport +maxconnects +multi-app +multi-debugcallback +multi-double +multi-formadd +multi-legacy +multi-poll +multi-post +multi-single +netrc +new-gitignore +parseurl +persistent +pop3-authzid +pop3-dele +pop3-list +pop3-multi +pop3-noop +pop3-retr +pop3-ssl +pop3-stat +pop3-tls +pop3-top +pop3-uidl +post-callback +postinmemory +postit2 +postit2-formadd +progressfunc +protofeats +range +resolve +rtsp +rtsp-options +sendrecv +sepheaders +sftpget +sftpuploadresume +shared-connection-cache +simple +simplepost +simplessl +smtp-authzid +smtp-expn +smtp-mail +smtp-mime +smtp-multi +smtp-ssl +smtp-tls +smtp-vrfy +sslbackend +unixsocket +url2file +urlapi +usercertinmem +websocket +websocket-cb +xmlstream diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/10-at-a-time.c b/local-test-curl-delta-01/afc-curl/docs/examples/10-at-a-time.c new file mode 100644 index 0000000000000000000000000000000000000000..38a0f24ac62f28455059dbee9cb827a410cad2d2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/10-at-a-time.c @@ -0,0 +1,153 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Download many files in parallel, in the same thread. + * + */ + +#include +#include +#include + +static const char *urls[] = { + "https://www.microsoft.com", + "https://opensource.org", + "https://www.google.com", + "https://www.yahoo.com", + "https://www.ibm.com", + "https://www.mysql.com", + "https://www.oracle.com", + "https://www.ripe.net", + "https://www.iana.org", + "https://www.amazon.com", + "https://www.netcraft.com", + "https://www.heise.de", + "https://www.chip.de", + "https://www.ca.com", + "https://www.cnet.com", + "https://www.mozilla.org", + "https://www.cnn.com", + "https://www.wikipedia.org", + "https://www.dell.com", + "https://www.hp.com", + "https://www.cert.org", + "https://www.mit.edu", + "https://www.nist.gov", + "https://www.ebay.com", + "https://www.playstation.com", + "https://www.uefa.com", + "https://www.ieee.org", + "https://www.apple.com", + "https://www.symantec.com", + "https://www.zdnet.com", + "https://www.fujitsu.com/global/", + "https://www.supermicro.com", + "https://www.hotmail.com", + "https://www.ietf.org", + "https://www.bbc.co.uk", + "https://news.google.com", + "https://www.foxnews.com", + "https://www.msn.com", + "https://www.wired.com", + "https://www.sky.com", + "https://www.usatoday.com", + "https://www.cbs.com", + "https://www.nbc.com/", + "https://slashdot.org", + "https://www.informationweek.com", + "https://apache.org", + "https://www.un.org", +}; + +#define MAX_PARALLEL 10 /* number of simultaneous transfers */ +#define NUM_URLS sizeof(urls)/sizeof(char *) + +static size_t write_cb(char *data, size_t n, size_t l, void *userp) +{ + /* take care of the data here, ignored in this example */ + (void)data; + (void)userp; + return n*l; +} + +static void add_transfer(CURLM *cm, unsigned int i, int *left) +{ + CURL *eh = curl_easy_init(); + curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(eh, CURLOPT_URL, urls[i]); + curl_easy_setopt(eh, CURLOPT_PRIVATE, urls[i]); + curl_multi_add_handle(cm, eh); + (*left)++; +} + +int main(void) +{ + CURLM *cm; + CURLMsg *msg; + unsigned int transfers = 0; + int msgs_left = -1; + int left = 0; + + curl_global_init(CURL_GLOBAL_ALL); + cm = curl_multi_init(); + + /* Limit the amount of simultaneous connections curl should allow: */ + curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long)MAX_PARALLEL); + + for(transfers = 0; transfers < MAX_PARALLEL && transfers < NUM_URLS; + transfers++) + add_transfer(cm, transfers, &left); + + do { + int still_alive = 1; + curl_multi_perform(cm, &still_alive); + + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(cm, &msgs_left)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + char *url; + CURL *e = msg->easy_handle; + curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &url); + fprintf(stderr, "R: %d - %s <%s>\n", + msg->data.result, curl_easy_strerror(msg->data.result), url); + curl_multi_remove_handle(cm, e); + curl_easy_cleanup(e); + left--; + } + else { + fprintf(stderr, "E: CURLMsg (%d)\n", msg->msg); + } + if(transfers < NUM_URLS) + add_transfer(cm, transfers++, &left); + } + if(left) + curl_multi_wait(cm, NULL, 0, 1000, NULL); + + } while(left); + + curl_multi_cleanup(cm); + curl_global_cleanup(); + + return EXIT_SUCCESS; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/docs/examples/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..21c427d12bf577e21d72edaa8055a29aa8192b45 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/CMakeLists.txt @@ -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 +# +########################################################################### + +add_custom_target(curl-examples) + +# Get 'check_PROGRAMS' variable +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + +foreach(_target IN LISTS check_PROGRAMS) + set(_target_name "curl-example-${_target}") + add_executable(${_target_name} EXCLUDE_FROM_ALL "${_target}.c") + add_dependencies(curl-examples ${_target_name}) + target_link_libraries(${_target_name} ${LIB_SELECTED} ${CURL_LIBS}) + target_compile_definitions(${_target_name} PRIVATE "CURL_NO_OLDIES") + if(LIB_SELECTED STREQUAL LIB_STATIC AND WIN32) + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB") + endif() + set_target_properties(${_target_name} PROPERTIES + OUTPUT_NAME "${_target}" UNITY_BUILD OFF + PROJECT_LABEL "Example ${_target}") +endforeach() diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.am b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..e5ff9ffdcf0e89c804d2c93027d18557937badbc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.am @@ -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 +# +########################################################################### + +AUTOMAKE_OPTIONS = foreign nostdinc + +EXTRA_DIST = README.md Makefile.example Makefile.mk CMakeLists.txt \ + $(COMPLICATED_EXAMPLES) .checksrc + +# 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 + +AM_CPPFLAGS = -I$(top_srcdir)/include + +LIBDIR = $(top_builddir)/lib + +# Avoid libcurl obsolete stuff +AM_CPPFLAGS += -DCURL_NO_OLDIES + +if USE_CPPFLAG_CURL_STATICLIB +AM_CPPFLAGS += -DCURL_STATICLIB +endif + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +# Dependencies +LDADD = $(LIBDIR)/libcurl.la @LIBCURL_PC_LIBS_PRIVATE@ + +# This might hold -Werror +CFLAGS += @CURL_CFLAG_EXTRAS@ + +# Makefile.inc provides the check_PROGRAMS and COMPLICATED_EXAMPLES defines +include Makefile.inc + +all: $(check_PROGRAMS) + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(srcdir)/*.c) diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.example b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.example new file mode 100644 index 0000000000000000000000000000000000000000..cfb59c94ef10ae4462aaddcca22c133e3adcb24f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.example @@ -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 +# +########################################################################### + +# What to call the final executable +TARGET = example + +# Which object files that the executable consists of +OBJS= ftpget.o + +# What compiler to use +CC = gcc + +# Compiler flags, -g for debug, -c to make an object file +CFLAGS = -c -g + +# This should point to a directory that holds libcurl, if it is not +# in the system's standard lib dir +# We also set a -L to include the directory where we have the OpenSSL +# libraries +LDFLAGS = -L/home/dast/lib -L/usr/local/ssl/lib + +# We need -lcurl for the curl stuff +# We need -lsocket and -lnsl when on Solaris +# We need -lssl and -lcrypto when using libcurl with SSL support +# We need -lpthread for the pthread example +LIBS = -lcurl -lsocket -lnsl -lssl -lcrypto + +# Link the target with all objects and libraries +$(TARGET) : $(OBJS) + $(CC) -o $(TARGET) $(OBJS) $(LDFLAGS) $(LIBS) + +# Compile the source files into object files +ftpget.o : ftpget.c + $(CC) $(CFLAGS) $< diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.inc b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..71dac0bf43656f9fba383febf6ecba1c3e2d7f74 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.inc @@ -0,0 +1,159 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 are all libcurl example programs to be test compiled +check_PROGRAMS = \ + 10-at-a-time \ + address-scope \ + altsvc \ + anyauthput \ + certinfo \ + chkspeed \ + connect-to \ + cookie_interface \ + debug \ + default-scheme \ + externalsocket \ + fileupload \ + ftp-wildcard \ + ftpget \ + ftpgetinfo \ + ftpgetresp \ + ftpsget \ + ftpupload \ + ftpuploadfrommem \ + ftpuploadresume \ + getinfo \ + getinmemory \ + getredirect \ + getreferrer \ + headerapi \ + hsts-preload \ + http-options \ + http-post \ + http2-download \ + http2-pushinmemory \ + http2-serverpush \ + http2-upload \ + http3 \ + http3-present \ + httpcustomheader \ + httpput \ + httpput-postfields \ + https \ + imap-append \ + imap-authzid \ + imap-copy \ + imap-create \ + imap-delete \ + imap-examine \ + imap-fetch \ + imap-list \ + imap-lsub \ + imap-multi \ + imap-noop \ + imap-search \ + imap-ssl \ + imap-store \ + imap-tls \ + interface \ + ipv6 \ + keepalive \ + localport \ + maxconnects \ + multi-app \ + multi-debugcallback \ + multi-double \ + multi-formadd \ + multi-legacy \ + multi-post \ + multi-single \ + netrc \ + parseurl \ + persistent \ + pop3-authzid \ + pop3-dele \ + pop3-list \ + pop3-multi \ + pop3-noop \ + pop3-retr \ + pop3-ssl \ + pop3-stat \ + pop3-tls \ + pop3-top \ + pop3-uidl \ + post-callback \ + postinmemory \ + postit2 \ + postit2-formadd \ + progressfunc \ + protofeats \ + range \ + resolve \ + rtsp-options \ + sendrecv \ + sepheaders \ + sftpget \ + sftpuploadresume \ + shared-connection-cache \ + simple \ + simplepost \ + simplessl \ + smtp-authzid \ + smtp-expn \ + smtp-mail \ + smtp-mime \ + smtp-multi \ + smtp-ssl \ + smtp-tls \ + smtp-vrfy \ + sslbackend \ + unixsocket \ + url2file \ + urlapi \ + websocket \ + websocket-cb + +# These examples require external dependencies that may not be commonly +# available on POSIX systems, so do not bother attempting to compile them here. +COMPLICATED_EXAMPLES = \ + cacertinmem.c \ + crawler.c \ + ephiperfifo.c \ + evhiperfifo.c \ + ghiper.c \ + hiperfifo.c \ + href_extractor.c \ + htmltidy.c \ + htmltitle.cpp \ + multi-event.c \ + multi-uv.c \ + multithread.c \ + sessioninfo.c \ + smooth-gtk-thread.c \ + synctime.c \ + threaded-ssl.c \ + usercertinmem.c \ + version-check.pl \ + xmlstream.c diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.mk b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.mk new file mode 100644 index 0000000000000000000000000000000000000000..5a5372dd3def9291e8a4da9087184a92beaaba69 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/Makefile.mk @@ -0,0 +1,52 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# Build libcurl via lib/Makefile.mk first. + +PROOT := ../.. + +### Common + +include $(PROOT)/lib/Makefile.mk + +### Local + +CPPFLAGS += -DCURL_NO_OLDIES +LDFLAGS += -L$(PROOT)/lib +LIBS := -lcurl $(LIBS) + +### Sources and targets + +# Provides check_PROGRAMS +include Makefile.inc + +TARGETS := $(patsubst %,%$(BIN_EXT),$(strip $(check_PROGRAMS))) +TOCLEAN := $(TARGETS) + +### Rules + +%$(BIN_EXT): %.c $(PROOT)/lib/libcurl.a + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $< -o $@ $(LIBS) + +all: $(TARGETS) diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/README.md b/local-test-curl-delta-01/afc-curl/docs/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a6a31c9388a091c6571f76d8c5778579dc17debf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/README.md @@ -0,0 +1,41 @@ + + +# libcurl examples + +This directory is for libcurl programming examples. They are meant to show +some simple steps on how you can build your own application to take full +advantage of libcurl. + +If you end up with other small but still useful example sources, please mail +them for submission in future packages and on the website. + +## Building + +The `Makefile.example` is an example Makefile that could be used to build +these examples. Just edit the file according to your system and requirements +first. + +Most examples should build fine using a command line like this: + + `curl-config --cc --cflags --libs` -o example-my example.c + +Some compilers do not like having the arguments in this order but instead +want you do reorganize them like: + + `curl-config --cc` -o example-my example.c `curl-config --cflags --libs` + +**Please** do not use the `curl.se` site as a test target for your libcurl +applications/experiments. Even if some of the examples use that site as a URL +at some places, it does not mean that the URLs work or that we expect you to +actually torture our website with your tests. Thanks. + +## Examples + +Each example source code file is designed to be and work stand-alone and +rather self-explanatory. The examples may at times lack the level of error +checks you need in a real world, but that is then only for the sake of +readability: to make the code smaller and easier to follow. diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/adddocsref.pl b/local-test-curl-delta-01/afc-curl/docs/examples/adddocsref.pl new file mode 100644 index 0000000000000000000000000000000000000000..01be96a841f836fce0bd9276dd834159848e8684 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/adddocsref.pl @@ -0,0 +1,58 @@ +#!/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 +# +########################################################################### + +# pass files as argument(s) + +my $docroot="https://curl.se/libcurl/c"; + +for $f (@ARGV) { + open(NEW, ">$f.new"); + open(F, "<$f"); + while() { + my $l = $_; + if($l =~ /\/* $docroot/) { + # just ignore preciously added refs + } + elsif($l =~ /^( *).*curl_easy_setopt\([^,]*, *([^ ,]*) *,/) { + my ($prefix, $anc) = ($1, $2); + $anc =~ s/_//g; + print NEW "$prefix/* $docroot/curl_easy_setopt.html#$anc */\n"; + print NEW $l; + } + elsif($l =~ /^( *).*(curl_([^\(]*))\(/) { + my ($prefix, $func) = ($1, $2); + print NEW "$prefix/* $docroot/$func.html */\n"; + print NEW $l; + } + else { + print NEW $l; + } + } + close(F); + close(NEW); + + system("mv $f $f.org"); + system("mv $f.new $f"); +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/address-scope.c b/local-test-curl-delta-01/afc-curl/docs/examples/address-scope.c new file mode 100644 index 0000000000000000000000000000000000000000..a4ae26539172bbc9f9bbf41de01fa0d347e52de0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/address-scope.c @@ -0,0 +1,62 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP GET to an IPv6 address with specific scope + * + */ +#include +#include + +#ifndef _WIN32 +#include +#endif + +int main(void) +{ +#ifndef _WIN32 + /* Windows users need to find how to use if_nametoindex() */ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + long my_scope_id; + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + + my_scope_id = (long)if_nametoindex("eth0"); + curl_easy_setopt(curl, CURLOPT_ADDRESS_SCOPE, my_scope_id); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } +#endif + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/altsvc.c b/local-test-curl-delta-01/afc-curl/docs/examples/altsvc.c new file mode 100644 index 0000000000000000000000000000000000000000..2f70d05e1ab2940a19551232d613928b6e0054d6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/altsvc.c @@ -0,0 +1,58 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP with Alt-Svc support + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + + /* cache the alternatives in this file */ + curl_easy_setopt(curl, CURLOPT_ALTSVC, "altsvc.txt"); + + /* restrict which HTTP versions to use alternatives */ + curl_easy_setopt(curl, CURLOPT_ALTSVC_CTRL, (long) + CURLALTSVC_H1|CURLALTSVC_H2|CURLALTSVC_H3); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/anyauthput.c b/local-test-curl-delta-01/afc-curl/docs/examples/anyauthput.c new file mode 100644 index 0000000000000000000000000000000000000000..3bbc056c0b453592c1a7120b450826c0c807b544 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/anyauthput.c @@ -0,0 +1,155 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP PUT upload with authentication using "any" method. libcurl picks the + * one the server supports/wants. + * + */ +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +# define FILENO(fp) _fileno(fp) +#else +# define FILENO(fp) fileno(fp) +#endif + +#if LIBCURL_VERSION_NUM < 0x070c03 +#error "upgrade your libcurl to no less than 7.12.3" +#endif + +/* + * This example shows an HTTP PUT operation with authentication using "any" + * type. It PUTs a file given as a command line argument to the URL also given + * on the command line. + * + * Since libcurl 7.12.3, using "any" auth and POST/PUT requires a set seek + * function. + * + * This example also uses its own read callback. + */ + +/* seek callback function */ +static int my_seek(void *userp, curl_off_t offset, int origin) +{ + FILE *fp = (FILE *) userp; + + if(-1 == fseek(fp, (long) offset, origin)) + /* could not seek */ + return CURL_SEEKFUNC_CANTSEEK; + + return CURL_SEEKFUNC_OK; /* success! */ +} + +/* read callback function, fread() look alike */ +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t nread; + + nread = fread(ptr, size, nmemb, stream); + + if(nread > 0) { + fprintf(stderr, "*** We read %lu bytes from file\n", (unsigned long)nread); + } + + return nread; +} + +int main(int argc, char **argv) +{ + CURL *curl; + CURLcode res; + FILE *fp; + struct stat file_info; + + char *file; + char *url; + + if(argc < 3) + return 1; + + file = argv[1]; + url = argv[2]; + + /* get the file size of the local file */ + fp = fopen(file, "rb"); + fstat(FILENO(fp), &file_info); + + /* In Windows, this inits the Winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + /* we want to use our own read function */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* which file to upload */ + curl_easy_setopt(curl, CURLOPT_READDATA, (void *) fp); + + /* set the seek function */ + curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, my_seek); + + /* pass the file descriptor to the seek callback as well */ + curl_easy_setopt(curl, CURLOPT_SEEKDATA, (void *) fp); + + /* enable "uploading" (which means PUT when doing HTTP) */ + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target URL, and note that this URL should also include a file + name, not only a directory (as you can do with GTP uploads) */ + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* and give the size of the upload, this supports large file sizes + on systems that have general support for it */ + curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, + (curl_off_t)file_info.st_size); + + /* tell libcurl we can use "any" auth, which lets the lib pick one, but it + also costs one extra round-trip and possibly sending of all the PUT + data twice!!! */ + curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY); + + /* set user name and password for the authentication */ + curl_easy_setopt(curl, CURLOPT_USERPWD, "user:password"); + + /* Now run off and do what you have been told! */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + fclose(fp); /* close the local file */ + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/cacertinmem.c b/local-test-curl-delta-01/afc-curl/docs/examples/cacertinmem.c new file mode 100644 index 0000000000000000000000000000000000000000..ff748db4b4c8dce4d3fa6c89068122e7b7f17ba3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/cacertinmem.c @@ -0,0 +1,182 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * CA cert in memory with OpenSSL to get an HTTPS page. + * + */ + +#include +#include +#include +#include + +static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) +{ + fwrite(ptr, size, nmemb, (FILE *)stream); + return (nmemb*size); +} + +static CURLcode sslctx_function(CURL *curl, void *sslctx, void *parm) +{ + CURLcode rv = CURLE_ABORTED_BY_CALLBACK; + + /** This example uses two (fake) certificates **/ + static const char mypem[] = + "-----BEGIN CERTIFICATE-----\n" + "MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE\n" + "AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw\n" + "CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ\n" + "BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND\n" + "VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb\n" + "qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY\n" + "HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo\n" + "G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA\n" + "0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH\n" + "k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47\n" + "JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m\n" + "AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD\n" + "vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms\n" + "tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH\n" + "7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h\n" + "I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA\n" + "h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF\n" + "d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H\n" + "pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7\n" + "-----END CERTIFICATE-----\n" + "-----BEGIN CERTIFICATE-----\n" + "MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UE\n" + "AwwNQUNFRElDT00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00x\n" + "CzAJBgNVBAYTAkVTMB4XDTA4MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEW\n" + "MBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZF\n" + "RElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKC\n" + "AgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHkWLn7\n" + "09gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7\n" + "XBZXehuDYAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5P\n" + "gvoFNTPhNahXwOf9jU8/kzJPeGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKe\n" + "I6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1PwkzQSulgUV1qzOMPPKC8W64iLgpq0i\n" + "5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1ThCojz2GuHURwCRi\n" + "ipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oIKiMn\n" + "MCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZ\n" + "o5NjEFIqnxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6\n" + "zqylfDJKZ0DcMDQj3dcEI2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacN\n" + "GHk0vFQYXlPKNFHtRQrmjseCNj6nOGOpMCwXEGCSn1WHElkQwg9naRHMTh5+Spqt\n" + "r0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3otkYNbn5XOmeUwssfnHdK\n" + "Z05phkOTOPu220+DkdRgfks+KzgHVZhepA==\n" + "-----END CERTIFICATE-----\n"; + + BIO *cbio = BIO_new_mem_buf(mypem, sizeof(mypem)); + X509_STORE *cts = SSL_CTX_get_cert_store((SSL_CTX *)sslctx); + int i; + STACK_OF(X509_INFO) *inf; + (void)curl; + (void)parm; + + if(!cts || !cbio) { + return rv; + } + + inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL); + + if(!inf) { + BIO_free(cbio); + return rv; + } + + for(i = 0; i < sk_X509_INFO_num(inf); i++) { + X509_INFO *itmp = sk_X509_INFO_value(inf, i); + if(itmp->x509) { + X509_STORE_add_cert(cts, itmp->x509); + } + if(itmp->crl) { + X509_STORE_add_crl(cts, itmp->crl); + } + } + + sk_X509_INFO_pop_free(inf, X509_INFO_free); + BIO_free(cbio); + + rv = CURLE_OK; + return rv; +} + +int main(void) +{ + CURL *ch; + CURLcode rv; + + curl_global_init(CURL_GLOBAL_ALL); + ch = curl_easy_init(); + curl_easy_setopt(ch, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(ch, CURLOPT_HEADER, 0L); + curl_easy_setopt(ch, CURLOPT_NOPROGRESS, 1L); + curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, writefunction); + curl_easy_setopt(ch, CURLOPT_WRITEDATA, stdout); + curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, writefunction); + curl_easy_setopt(ch, CURLOPT_HEADERDATA, stderr); + curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM"); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 1L); + curl_easy_setopt(ch, CURLOPT_URL, "https://www.example.com/"); + + /* Turn off the default CA locations, otherwise libcurl loads CA + * certificates from the locations that were detected/specified at + * build-time + */ + curl_easy_setopt(ch, CURLOPT_CAINFO, NULL); + curl_easy_setopt(ch, CURLOPT_CAPATH, NULL); + + /* first try: retrieve page without ca certificates -> should fail + * unless libcurl was built --with-ca-fallback enabled at build-time + */ + rv = curl_easy_perform(ch); + if(rv == CURLE_OK) + printf("*** transfer succeeded ***\n"); + else + printf("*** transfer failed ***\n"); + + /* use a fresh connection (optional) this option seriously impacts + * performance of multiple transfers but it is necessary order to + * demonstrate this example. recall that the ssl ctx callback is only called + * _before_ an SSL connection is established, therefore it does not affect + * existing verified SSL connections already in the connection cache + * associated with this handle. normally you would set the ssl ctx function + * before making any transfers, and not use this option. + */ + curl_easy_setopt(ch, CURLOPT_FRESH_CONNECT, 1L); + + /* second try: retrieve page using cacerts' certificate -> succeeds to load + * the certificate by installing a function doing the necessary + * "modifications" to the SSL CONTEXT just before link init + */ + curl_easy_setopt(ch, CURLOPT_SSL_CTX_FUNCTION, sslctx_function); + rv = curl_easy_perform(ch); + if(rv == CURLE_OK) + printf("*** transfer succeeded ***\n"); + else + printf("*** transfer failed ***\n"); + + curl_easy_cleanup(ch); + curl_global_cleanup(); + return rv; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/certinfo.c b/local-test-curl-delta-01/afc-curl/docs/examples/certinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..795be6c3d19db12e9eaac40ebbd49f05a5b96bc4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/certinfo.c @@ -0,0 +1,87 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Extract lots of TLS certificate info. + * + */ +#include + +#include + +static size_t wrfu(void *ptr, size_t size, size_t nmemb, void *stream) +{ + (void)stream; + (void)ptr; + return size * nmemb; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/"); + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wrfu); + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L); + + res = curl_easy_perform(curl); + + if(!res) { + struct curl_certinfo *certinfo; + + res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &certinfo); + + if(!res && certinfo) { + int i; + + printf("%d certs!\n", certinfo->num_of_certs); + + for(i = 0; i < certinfo->num_of_certs; i++) { + struct curl_slist *slist; + + for(slist = certinfo->certinfo[i]; slist; slist = slist->next) + printf("%s\n", slist->data); + + } + } + + } + + curl_easy_cleanup(curl); + } + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/chkspeed.c b/local-test-curl-delta-01/afc-curl/docs/examples/chkspeed.c new file mode 100644 index 0000000000000000000000000000000000000000..687b264b9bb2475e79a2060ed594e95f2725d6c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/chkspeed.c @@ -0,0 +1,224 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Show transfer timing info after download completes. + * + */ +/* Example source code to show how the callback function can be used to + * download data into a chunk of memory instead of storing it in a file. + * After successful download we use curl_easy_getinfo() calls to get the + * amount of downloaded bytes, the time used for the whole download, and + * the average download speed. + * On Linux you can create the download test files with: + * dd if=/dev/urandom of=file_1M.bin bs=1M count=1 + * + */ + +#include +#include +#include + +#include + +#define URL_BASE "http://speedtest.your.domain/" +#define URL_1M URL_BASE "file_1M.bin" +#define URL_2M URL_BASE "file_2M.bin" +#define URL_5M URL_BASE "file_5M.bin" +#define URL_10M URL_BASE "file_10M.bin" +#define URL_20M URL_BASE "file_20M.bin" +#define URL_50M URL_BASE "file_50M.bin" +#define URL_100M URL_BASE "file_100M.bin" + +#define CHKSPEED_VERSION "1.0" + +static size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *data) +{ + /* we are not interested in the downloaded bytes itself, + so we only return the size we would have saved ... */ + (void)ptr; /* unused */ + (void)data; /* unused */ + return (size_t)(size * nmemb); +} + +int main(int argc, char *argv[]) +{ + CURL *curl_handle; + CURLcode res; + int prtall = 0, prtsep = 0, prttime = 0; + const char *url = URL_1M; + char *appname = argv[0]; + + if(argc > 1) { + /* parse input parameters */ + for(argc--, argv++; *argv; argc--, argv++) { + if(argv[0][0] == '-') { + switch(argv[0][1]) { + case 'h': + case 'H': + fprintf(stderr, + "\rUsage: %s [-m=1|2|5|10|20|50|100] [-t] [-x] [url]\n", + appname); + exit(1); + case 'v': + case 'V': + fprintf(stderr, "\r%s %s - %s\n", + appname, CHKSPEED_VERSION, curl_version()); + exit(1); + case 'a': + case 'A': + prtall = 1; + break; + case 'x': + case 'X': + prtsep = 1; + break; + case 't': + case 'T': + prttime = 1; + break; + case 'm': + case 'M': + if(argv[0][2] == '=') { + long m = strtol((*argv) + 3, NULL, 10); + switch(m) { + case 1: + url = URL_1M; + break; + case 2: + url = URL_2M; + break; + case 5: + url = URL_5M; + break; + case 10: + url = URL_10M; + break; + case 20: + url = URL_20M; + break; + case 50: + url = URL_50M; + break; + case 100: + url = URL_100M; + break; + default: + fprintf(stderr, "\r%s: invalid parameter %s\n", + appname, *argv + 3); + return 1; + } + break; + } + fprintf(stderr, "\r%s: invalid or unknown option %s\n", + appname, *argv); + return 1; + default: + fprintf(stderr, "\r%s: invalid or unknown option %s\n", + appname, *argv); + return 1; + } + } + else { + url = *argv; + } + } + } + + /* print separator line */ + if(prtsep) { + printf("-------------------------------------------------\n"); + } + /* print localtime */ + if(prttime) { + time_t t = time(NULL); + printf("Localtime: %s", ctime(&t)); + } + + /* init libcurl */ + curl_global_init(CURL_GLOBAL_ALL); + + /* init the curl session */ + curl_handle = curl_easy_init(); + + /* specify URL to get */ + curl_easy_setopt(curl_handle, CURLOPT_URL, url); + + /* send all data to this function */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteCallback); + + /* some servers do not like requests that are made without a user-agent + field, so we provide one */ + curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, + "libcurl-speedchecker/" CHKSPEED_VERSION); + + /* get it! */ + res = curl_easy_perform(curl_handle); + + if(CURLE_OK == res) { + curl_off_t val; + + /* check for bytes downloaded */ + res = curl_easy_getinfo(curl_handle, CURLINFO_SIZE_DOWNLOAD_T, &val); + if((CURLE_OK == res) && (val > 0)) + printf("Data downloaded: %lu bytes.\n", (unsigned long)val); + + /* check for total download time */ + res = curl_easy_getinfo(curl_handle, CURLINFO_TOTAL_TIME_T, &val); + if((CURLE_OK == res) && (val > 0)) + printf("Total download time: %lu.%06lu sec.\n", + (unsigned long)(val / 1000000), (unsigned long)(val % 1000000)); + + /* check for average download speed */ + res = curl_easy_getinfo(curl_handle, CURLINFO_SPEED_DOWNLOAD_T, &val); + if((CURLE_OK == res) && (val > 0)) + printf("Average download speed: %lu kbyte/sec.\n", + (unsigned long)(val / 1024)); + + if(prtall) { + /* check for name resolution time */ + res = curl_easy_getinfo(curl_handle, CURLINFO_NAMELOOKUP_TIME_T, &val); + if((CURLE_OK == res) && (val > 0)) + printf("Name lookup time: %lu.%06lu sec.\n", + (unsigned long)(val / 1000000), (unsigned long)(val % 1000000)); + + /* check for connect time */ + res = curl_easy_getinfo(curl_handle, CURLINFO_CONNECT_TIME_T, &val); + if((CURLE_OK == res) && (val > 0)) + printf("Connect time: %lu.%06lu sec.\n", + (unsigned long)(val / 1000000), (unsigned long)(val % 1000000)); + } + } + else { + fprintf(stderr, "Error while fetching '%s' : %s\n", + url, curl_easy_strerror(res)); + } + + /* cleanup curl stuff */ + curl_easy_cleanup(curl_handle); + + /* we are done with libcurl, so clean it up */ + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/connect-to.c b/local-test-curl-delta-01/afc-curl/docs/examples/connect-to.c new file mode 100644 index 0000000000000000000000000000000000000000..ad1e304649648af08af631b49bcdf893f66f50c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/connect-to.c @@ -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 + * + ***************************************************************************/ +/* + * Use CURLOPT_CONNECT_TO to connect to "wrong" hostname + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + /* + Each single string should be written using the format + HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT where HOST is the host of the + request, PORT is the port of the request, CONNECT-TO-HOST is the host name + to connect to, and CONNECT-TO-PORT is the port to connect to. + */ + /* instead of curl.se:443, it resolves and uses example.com:443 but in other + aspects work as if it still is curl.se */ + struct curl_slist *host = curl_slist_append(NULL, + "curl.se:443:example.com:443"); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_CONNECT_TO, host); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + /* since this connects to the wrong host, checking the host name in the + server certificate fails, so unless we disable the check libcurl + returns CURLE_PEER_FAILED_VERIFICATION */ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + /* Letting the wrong host name in the certificate be okay, the transfer + goes through but (most likely) causes a 404 or similar because it sends + an unknown name in the Host: header field */ + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + curl_slist_free_all(host); + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/cookie_interface.c b/local-test-curl-delta-01/afc-curl/docs/examples/cookie_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..396aeca97e1845dd48dc276610e463bb282d833b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/cookie_interface.c @@ -0,0 +1,138 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Import and export cookies with COOKIELIST. + * + */ + +#include +#include +#include +#include + +#include +#include + +static void +print_cookies(CURL *curl) +{ + CURLcode res; + struct curl_slist *cookies; + struct curl_slist *nc; + int i; + + printf("Cookies, curl knows:\n"); + res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies); + if(res != CURLE_OK) { + fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n", + curl_easy_strerror(res)); + exit(1); + } + nc = cookies; + i = 1; + while(nc) { + printf("[%d]: %s\n", i, nc->data); + nc = nc->next; + i++; + } + if(i == 1) { + printf("(none)\n"); + } + curl_slist_free_all(cookies); +} + +int +main(void) +{ + CURL *curl; + CURLcode res; + + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + char nline[512]; + + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); /* start cookie engine */ + res = curl_easy_perform(curl); + if(res != CURLE_OK) { + fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res)); + return 1; + } + + print_cookies(curl); + + printf("Erasing curl's knowledge of cookies!\n"); + curl_easy_setopt(curl, CURLOPT_COOKIELIST, "ALL"); + + print_cookies(curl); + + printf("-----------------------------------------------\n" + "Setting a cookie \"PREF\" via cookie interface:\n"); + /* Netscape format cookie */ + curl_msnprintf(nline, sizeof(nline), "%s\t%s\t%s\t%s\t%.0f\t%s\t%s", + ".example.com", "TRUE", "/", "FALSE", + difftime(time(NULL) + 31337, (time_t)0), + "PREF", "hello example, i like you!"); + res = curl_easy_setopt(curl, CURLOPT_COOKIELIST, nline); + if(res != CURLE_OK) { + fprintf(stderr, "Curl curl_easy_setopt failed: %s\n", + curl_easy_strerror(res)); + return 1; + } + + /* HTTP-header style cookie. If you use the Set-Cookie format and do not + specify a domain then the cookie is sent for any domain and is not + modified, likely not what you intended. For more information refer to + the CURLOPT_COOKIELIST documentation. + */ + curl_msnprintf(nline, sizeof(nline), + "Set-Cookie: OLD_PREF=3d141414bf4209321; " + "expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.example.com"); + res = curl_easy_setopt(curl, CURLOPT_COOKIELIST, nline); + if(res != CURLE_OK) { + fprintf(stderr, "Curl curl_easy_setopt failed: %s\n", + curl_easy_strerror(res)); + return 1; + } + + print_cookies(curl); + + res = curl_easy_perform(curl); + if(res != CURLE_OK) { + fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res)); + return 1; + } + + curl_easy_cleanup(curl); + } + else { + fprintf(stderr, "Curl init failed!\n"); + return 1; + } + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/crawler.c b/local-test-curl-delta-01/afc-curl/docs/examples/crawler.c new file mode 100644 index 0000000000000000000000000000000000000000..2ff4ae71459d81f575ae04c43bece5af946e0590 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/crawler.c @@ -0,0 +1,237 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Jeroen Ooms + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * To compile: + * gcc crawler.c $(pkg-config --cflags --libs libxml-2.0 libcurl) + * + */ +/* + * Web crawler based on curl and libxml2 to stress-test curl with + * hundreds of concurrent connections to various servers. + * + */ + +/* Parameters */ +int max_con = 200; +int max_total = 20000; +int max_requests = 500; +int max_link_per_page = 5; +int follow_relative_links = 0; +char *start_page = "https://www.reuters.com"; + +#include +#include +#include +#include +#include +#include +#include +#include + +int pending_interrupt = 0; +void sighandler(int dummy) +{ + pending_interrupt = 1; +} + +/* resizable buffer */ +typedef struct { + char *buf; + size_t size; +} memory; + +size_t grow_buffer(void *contents, size_t sz, size_t nmemb, void *ctx) +{ + size_t realsize = sz * nmemb; + memory *mem = (memory*) ctx; + char *ptr = realloc(mem->buf, mem->size + realsize); + if(!ptr) { + /* out of memory */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + mem->buf = ptr; + memcpy(&(mem->buf[mem->size]), contents, realsize); + mem->size += realsize; + return realsize; +} + +CURL *make_handle(char *url) +{ + CURL *handle = curl_easy_init(); + + /* Important: use HTTP2 over HTTPS */ + curl_easy_setopt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS); + curl_easy_setopt(handle, CURLOPT_URL, url); + + /* buffer body */ + memory *mem = malloc(sizeof(memory)); + mem->size = 0; + mem->buf = malloc(1); + curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, grow_buffer); + curl_easy_setopt(handle, CURLOPT_WRITEDATA, mem); + curl_easy_setopt(handle, CURLOPT_PRIVATE, mem); + + /* For completeness */ + curl_easy_setopt(handle, CURLOPT_ACCEPT_ENCODING, ""); + curl_easy_setopt(handle, CURLOPT_TIMEOUT, 5L); + curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); + /* only allow redirects to HTTP and HTTPS URLs */ + curl_easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS_STR, "http,https"); + curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1L); + curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 10L); + /* each transfer needs to be done within 20 seconds! */ + curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, 20000L); + /* connect fast or fail */ + curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT_MS, 2000L); + /* skip files larger than a gigabyte */ + curl_easy_setopt(handle, CURLOPT_MAXFILESIZE_LARGE, + (curl_off_t)1024*1024*1024); + curl_easy_setopt(handle, CURLOPT_COOKIEFILE, ""); + curl_easy_setopt(handle, CURLOPT_FILETIME, 1L); + curl_easy_setopt(handle, CURLOPT_USERAGENT, "mini crawler"); + curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + curl_easy_setopt(handle, CURLOPT_UNRESTRICTED_AUTH, 1L); + curl_easy_setopt(handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); + curl_easy_setopt(handle, CURLOPT_EXPECT_100_TIMEOUT_MS, 0L); + return handle; +} + +/* HREF finder implemented in libxml2 but could be any HTML parser */ +size_t follow_links(CURLM *multi_handle, memory *mem, char *url) +{ + int opts = HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | \ + HTML_PARSE_NOWARNING | HTML_PARSE_NONET; + htmlDocPtr doc = htmlReadMemory(mem->buf, mem->size, url, NULL, opts); + if(!doc) + return 0; + xmlChar *xpath = (xmlChar*) "//a/@href"; + xmlXPathContextPtr context = xmlXPathNewContext(doc); + xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context); + xmlXPathFreeContext(context); + if(!result) + return 0; + xmlNodeSetPtr nodeset = result->nodesetval; + if(xmlXPathNodeSetIsEmpty(nodeset)) { + xmlXPathFreeObject(result); + return 0; + } + size_t count = 0; + int i; + for(i = 0; i < nodeset->nodeNr; i++) { + double r = rand(); + int x = r * nodeset->nodeNr / RAND_MAX; + const xmlNode *node = nodeset->nodeTab[x]->xmlChildrenNode; + xmlChar *href = xmlNodeListGetString(doc, node, 1); + if(follow_relative_links) { + xmlChar *orig = href; + href = xmlBuildURI(href, (xmlChar *) url); + xmlFree(orig); + } + char *link = (char *) href; + if(!link || strlen(link) < 20) + continue; + if(!strncmp(link, "http://", 7) || !strncmp(link, "https://", 8)) { + curl_multi_add_handle(multi_handle, make_handle(link)); + if(count++ == max_link_per_page) + break; + } + xmlFree(link); + } + xmlXPathFreeObject(result); + return count; +} + +int is_html(char *ctype) +{ + return ctype != NULL && strlen(ctype) > 10 && strstr(ctype, "text/html"); +} + +int main(void) +{ + signal(SIGINT, sighandler); + LIBXML_TEST_VERSION; + curl_global_init(CURL_GLOBAL_DEFAULT); + CURLM *multi_handle = curl_multi_init(); + curl_multi_setopt(multi_handle, CURLMOPT_MAX_TOTAL_CONNECTIONS, max_con); + curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, 6L); + + /* enables http/2 if available */ +#ifdef CURLPIPE_MULTIPLEX + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); +#endif + + /* sets html start page */ + curl_multi_add_handle(multi_handle, make_handle(start_page)); + + int msgs_left; + int pending = 0; + int complete = 0; + int still_running = 1; + while(still_running && !pending_interrupt) { + int numfds; + curl_multi_wait(multi_handle, NULL, 0, 1000, &numfds); + curl_multi_perform(multi_handle, &still_running); + + /* See how the transfers went */ + CURLMsg *m = NULL; + while((m = curl_multi_info_read(multi_handle, &msgs_left))) { + if(m->msg == CURLMSG_DONE) { + CURL *handle = m->easy_handle; + char *url; + memory *mem; + curl_easy_getinfo(handle, CURLINFO_PRIVATE, &mem); + curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &url); + if(m->data.result == CURLE_OK) { + long res_status; + curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res_status); + if(res_status == 200) { + char *ctype; + curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &ctype); + printf("[%d] HTTP 200 (%s): %s\n", complete, ctype, url); + if(is_html(ctype) && mem->size > 100) { + if(pending < max_requests && (complete + pending) < max_total) { + pending += follow_links(multi_handle, mem, url); + still_running = 1; + } + } + } + else { + printf("[%d] HTTP %d: %s\n", complete, (int) res_status, url); + } + } + else { + printf("[%d] Connection failure: %s\n", complete, url); + } + curl_multi_remove_handle(multi_handle, handle); + curl_easy_cleanup(handle); + free(mem->buf); + free(mem); + complete++; + pending--; + } + } + } + curl_multi_cleanup(multi_handle); + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/debug.c b/local-test-curl-delta-01/afc-curl/docs/examples/debug.c new file mode 100644 index 0000000000000000000000000000000000000000..2bd8b971ac73c7fda12984fc3a398386ac83eece --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/debug.c @@ -0,0 +1,155 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Show how CURLOPT_DEBUGFUNCTION can be used. + * + */ +#include +#include + +struct data { + char trace_ascii; /* 1 or 0 */ +}; + +static +void dump(const char *text, + FILE *stream, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stream, "%s, %10.10lu bytes (0x%8.8lx)\n", + text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stream, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stream, "%02x ", ptr[i + c]); + else + fputs(" ", stream); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stream, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stream); /* newline */ + } + fflush(stream); +} + +static +int my_trace(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userp) +{ + struct data *config = (struct data *)userp; + const char *text; + (void)handle; /* prevent compiler warning */ + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "== Info: %s", data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, stderr, (unsigned char *)data, size, config->trace_ascii); + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + struct data config; + + config.trace_ascii = 1; /* enable ASCII tracing */ + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, my_trace); + curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &config); + + /* the DEBUGFUNCTION has no effect until we enable VERBOSE */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* example.com is redirected, so we tell libcurl to follow redirection */ + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/"); + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/default-scheme.c b/local-test-curl-delta-01/afc-curl/docs/examples/default-scheme.c new file mode 100644 index 0000000000000000000000000000000000000000..13e1e08fcb3e6ab6d504f27c1a79e070b257ee72 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/default-scheme.c @@ -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 + * + ***************************************************************************/ +/* + * Change default scheme when none is provided in the URL + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "example.com"); + + /* Change the default protocol (scheme) for schemeless URLs from plain + "http" to use a secure one instead. */ + curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https"); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ephiperfifo.c b/local-test-curl-delta-01/afc-curl/docs/examples/ephiperfifo.c new file mode 100644 index 0000000000000000000000000000000000000000..8edcd2015d45b0aa004afd7c39e32c4e2c451fbb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ephiperfifo.c @@ -0,0 +1,547 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * multi socket API usage with epoll and timerfd + * + */ +/* Example application source code using the multi socket interface to + * download many files at once. + * + * This example features the same basic functionality as hiperfifo.c does, + * but this uses epoll and timerfd instead of libevent. + * + * Written by Jeff Pohlmeyer, converted to use epoll by Josh Bialkowski + +Requires a Linux system with epoll + +When running, the program creates the named pipe "hiper.fifo" + +Whenever there is input into the fifo, the program reads the input as a list +of URL's and creates some new easy handles to fetch each URL via the +curl_multi "hiper" API. + + +Thus, you can try a single URL: + % echo http://www.yahoo.com > hiper.fifo + +Or a whole bunch of them: + % cat my-url-list > hiper.fifo + +The fifo buffer is handled almost instantly, so you can even add more URL's +while the previous requests are still being downloaded. + +Note: + For the sake of simplicity, URL length is limited to 1023 char's ! + +This is purely a demo app, all retrieved data is simply discarded by the write +callback. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */ + + +/* Global information, common to all connections */ +typedef struct _GlobalInfo +{ + int epfd; /* epoll filedescriptor */ + int tfd; /* timer filedescriptor */ + int fifofd; /* fifo filedescriptor */ + CURLM *multi; + int still_running; + FILE *input; +} GlobalInfo; + + +/* Information associated with a specific easy handle */ +typedef struct _ConnInfo +{ + CURL *easy; + char *url; + GlobalInfo *global; + char error[CURL_ERROR_SIZE]; +} ConnInfo; + + +/* Information associated with a specific socket */ +typedef struct _SockInfo +{ + curl_socket_t sockfd; + CURL *easy; + int action; + long timeout; + GlobalInfo *global; +} SockInfo; + +#define mycase(code) \ + case code: s = __STRING(code) + +/* Die if we get a bad CURLMcode somewhere */ +static void mcode_or_die(const char *where, CURLMcode code) +{ + if(CURLM_OK != code) { + const char *s; + switch(code) { + mycase(CURLM_BAD_HANDLE); break; + mycase(CURLM_BAD_EASY_HANDLE); break; + mycase(CURLM_OUT_OF_MEMORY); break; + mycase(CURLM_INTERNAL_ERROR); break; + mycase(CURLM_UNKNOWN_OPTION); break; + mycase(CURLM_LAST); break; + default: s = "CURLM_unknown"; break; + mycase(CURLM_BAD_SOCKET); + fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s); + /* ignore this error */ + return; + } + fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s); + exit(code); + } +} + +static void timer_cb(GlobalInfo* g, int revents); + +/* Update the timer after curl_multi library does its thing. Curl informs the + * application through this callback what it wants the new timeout to be, + * after it does some work. */ +static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g) +{ + struct itimerspec its; + + fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms); + + if(timeout_ms > 0) { + its.it_interval.tv_sec = 0; + its.it_interval.tv_nsec = 0; + its.it_value.tv_sec = timeout_ms / 1000; + its.it_value.tv_nsec = (timeout_ms % 1000) * 1000 * 1000; + } + else if(timeout_ms == 0) { + /* libcurl wants us to timeout now, however setting both fields of + * new_value.it_value to zero disarms the timer. The closest we can + * do is to schedule the timer to fire in 1 ns. */ + its.it_interval.tv_sec = 0; + its.it_interval.tv_nsec = 0; + its.it_value.tv_sec = 0; + its.it_value.tv_nsec = 1; + } + else { + memset(&its, 0, sizeof(struct itimerspec)); + } + + timerfd_settime(g->tfd, /* flags= */0, &its, NULL); + return 0; +} + + +/* Check for completed transfers, and remove their easy handles */ +static void check_multi_info(GlobalInfo *g) +{ + char *eff_url; + CURLMsg *msg; + int msgs_left; + ConnInfo *conn; + CURL *easy; + CURLcode res; + + fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running); + while((msg = curl_multi_info_read(g->multi, &msgs_left))) { + if(msg->msg == CURLMSG_DONE) { + easy = msg->easy_handle; + res = msg->data.result; + curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn); + curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url); + fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error); + curl_multi_remove_handle(g->multi, easy); + free(conn->url); + curl_easy_cleanup(easy); + free(conn); + } + } +} + +/* Called by libevent when we get action on a multi socket filedescriptor */ +static void event_cb(GlobalInfo *g, int fd, int revents) +{ + CURLMcode rc; + struct itimerspec its; + + int action = ((revents & EPOLLIN) ? CURL_CSELECT_IN : 0) | + ((revents & EPOLLOUT) ? CURL_CSELECT_OUT : 0); + + rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running); + mcode_or_die("event_cb: curl_multi_socket_action", rc); + + check_multi_info(g); + if(g->still_running <= 0) { + fprintf(MSG_OUT, "last transfer done, kill timeout\n"); + memset(&its, 0, sizeof(struct itimerspec)); + timerfd_settime(g->tfd, 0, &its, NULL); + } +} + +/* Called by main loop when our timeout expires */ +static void timer_cb(GlobalInfo* g, int revents) +{ + CURLMcode rc; + uint64_t count = 0; + ssize_t err = 0; + + err = read(g->tfd, &count, sizeof(uint64_t)); + if(err == -1) { + /* Note that we may call the timer callback even if the timerfd is not + * readable. It's possible that there are multiple events stored in the + * epoll buffer (i.e. the timer may have fired multiple times). The event + * count is cleared after the first call so future events in the epoll + * buffer fails to read from the timer. */ + if(errno == EAGAIN) { + fprintf(MSG_OUT, "EAGAIN on tfd %d\n", g->tfd); + return; + } + } + if(err != sizeof(uint64_t)) { + fprintf(stderr, "read(tfd) == %ld", err); + perror("read(tfd)"); + } + + rc = curl_multi_socket_action(g->multi, + CURL_SOCKET_TIMEOUT, 0, &g->still_running); + mcode_or_die("timer_cb: curl_multi_socket_action", rc); + check_multi_info(g); +} + + + +/* Clean up the SockInfo structure */ +static void remsock(SockInfo *f, GlobalInfo* g) +{ + if(f) { + if(f->sockfd) { + if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL)) + fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n", + f->sockfd, strerror(errno)); + } + free(f); + } +} + + + +/* Assign information to a SockInfo structure */ +static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act, + GlobalInfo *g) +{ + struct epoll_event ev; + int kind = ((act & CURL_POLL_IN) ? EPOLLIN : 0) | + ((act & CURL_POLL_OUT) ? EPOLLOUT : 0); + + if(f->sockfd) { + if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL)) + fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n", + f->sockfd, strerror(errno)); + } + + f->sockfd = s; + f->action = act; + f->easy = e; + + ev.events = kind; + ev.data.fd = s; + if(epoll_ctl(g->epfd, EPOLL_CTL_ADD, s, &ev)) + fprintf(stderr, "EPOLL_CTL_ADD failed for fd: %d : %s\n", + s, strerror(errno)); +} + + + +/* Initialize a new SockInfo structure */ +static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g) +{ + SockInfo *fdp = (SockInfo*)calloc(1, sizeof(SockInfo)); + + fdp->global = g; + setsock(fdp, s, easy, action, g); + curl_multi_assign(g->multi, s, fdp); +} + +/* CURLMOPT_SOCKETFUNCTION */ +static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp) +{ + GlobalInfo *g = (GlobalInfo*) cbp; + SockInfo *fdp = (SockInfo*) sockp; + const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" }; + + fprintf(MSG_OUT, + "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]); + if(what == CURL_POLL_REMOVE) { + fprintf(MSG_OUT, "\n"); + remsock(fdp, g); + } + else { + if(!fdp) { + fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]); + addsock(s, e, what, g); + } + else { + fprintf(MSG_OUT, + "Changing action from %s to %s\n", + whatstr[fdp->action], whatstr[what]); + setsock(fdp, s, e, what, g); + } + } + return 0; +} + + + +/* CURLOPT_WRITEFUNCTION */ +static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data) +{ + (void)ptr; + (void)data; + return size * nmemb; +} + + +/* CURLOPT_PROGRESSFUNCTION */ +static int prog_cb(void *p, double dltotal, double dlnow, double ult, + double uln) +{ + ConnInfo *conn = (ConnInfo *)p; + (void)ult; + (void)uln; + + fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal); + return 0; +} + + +/* Create a new easy handle, and add it to the global curl_multi */ +static void new_conn(char *url, GlobalInfo *g) +{ + ConnInfo *conn; + CURLMcode rc; + + conn = (ConnInfo*)calloc(1, sizeof(ConnInfo)); + conn->error[0]='\0'; + + conn->easy = curl_easy_init(); + if(!conn->easy) { + fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n"); + exit(2); + } + conn->global = g; + conn->url = strdup(url); + curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url); + curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn); + curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error); + curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn); + curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn); + curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L); + fprintf(MSG_OUT, + "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url); + rc = curl_multi_add_handle(g->multi, conn->easy); + mcode_or_die("new_conn: curl_multi_add_handle", rc); + + /* note that the add_handle() sets a timeout to trigger soon so that the + * necessary socket_action() call gets called by this app */ +} + +/* This gets called whenever data is received from the fifo */ +static void fifo_cb(GlobalInfo* g, int revents) +{ + char s[1024]; + long int rv = 0; + int n = 0; + + do { + s[0]='\0'; + rv = fscanf(g->input, "%1023s%n", s, &n); + s[n]='\0'; + if(n && s[0]) { + new_conn(s, g); /* if we read a URL, go get it! */ + } + else + break; + } while(rv != EOF); +} + +/* Create a named pipe and tell libevent to monitor it */ +static const char *fifo = "hiper.fifo"; +static int init_fifo(GlobalInfo *g) +{ + struct stat st; + curl_socket_t sockfd; + struct epoll_event epev; + + fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo); + if(lstat (fifo, &st) == 0) { + if((st.st_mode & S_IFMT) == S_IFREG) { + errno = EEXIST; + perror("lstat"); + exit(1); + } + } + unlink(fifo); + if(mkfifo (fifo, 0600) == -1) { + perror("mkfifo"); + exit(1); + } + sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0); + if(sockfd == -1) { + perror("open"); + exit(1); + } + + g->fifofd = sockfd; + g->input = fdopen(sockfd, "r"); + + epev.events = EPOLLIN; + epev.data.fd = sockfd; + epoll_ctl(g->epfd, EPOLL_CTL_ADD, sockfd, &epev); + + fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo); + return 0; +} + +static void clean_fifo(GlobalInfo *g) +{ + epoll_ctl(g->epfd, EPOLL_CTL_DEL, g->fifofd, NULL); + fclose(g->input); + unlink(fifo); +} + + +int g_should_exit_ = 0; + +void sigint_handler(int signo) +{ + g_should_exit_ = 1; +} + +int main(int argc, char **argv) +{ + GlobalInfo g; + struct itimerspec its; + struct epoll_event ev; + struct epoll_event events[10]; + (void)argc; + (void)argv; + + g_should_exit_ = 0; + signal(SIGINT, sigint_handler); + + memset(&g, 0, sizeof(GlobalInfo)); + g.epfd = epoll_create1(EPOLL_CLOEXEC); + if(g.epfd == -1) { + perror("epoll_create1 failed"); + exit(1); + } + + g.tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + if(g.tfd == -1) { + perror("timerfd_create failed"); + exit(1); + } + + memset(&its, 0, sizeof(struct itimerspec)); + its.it_interval.tv_sec = 0; + its.it_value.tv_sec = 1; + timerfd_settime(g.tfd, 0, &its, NULL); + + ev.events = EPOLLIN; + ev.data.fd = g.tfd; + epoll_ctl(g.epfd, EPOLL_CTL_ADD, g.tfd, &ev); + + init_fifo(&g); + g.multi = curl_multi_init(); + + /* setup the generic multi interface options we want */ + curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb); + curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g); + curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb); + curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g); + + /* we do not call any curl_multi_socket*() function yet as we have no handles + added! */ + + fprintf(MSG_OUT, "Entering wait loop\n"); + fflush(MSG_OUT); + while(!g_should_exit_) { + int idx; + int err = epoll_wait(g.epfd, events, + sizeof(events)/sizeof(struct epoll_event), 10000); + if(err == -1) { + if(errno == EINTR) { + fprintf(MSG_OUT, "note: wait interrupted\n"); + continue; + } + else { + perror("epoll_wait"); + exit(1); + } + } + + for(idx = 0; idx < err; ++idx) { + if(events[idx].data.fd == g.fifofd) { + fifo_cb(&g, events[idx].events); + } + else if(events[idx].data.fd == g.tfd) { + timer_cb(&g, events[idx].events); + } + else { + event_cb(&g, events[idx].data.fd, events[idx].events); + } + } + } + + fprintf(MSG_OUT, "Exiting normally.\n"); + fflush(MSG_OUT); + + curl_multi_cleanup(g.multi); + clean_fifo(&g); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/evhiperfifo.c b/local-test-curl-delta-01/afc-curl/docs/examples/evhiperfifo.c new file mode 100644 index 0000000000000000000000000000000000000000..8997dff11de62e64a4aabe9df4232cdcbefafd9f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/evhiperfifo.c @@ -0,0 +1,450 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * multi socket interface together with libev + * + */ +/* Example application source code using the multi socket interface to + * download many files at once. + * + * This example features the same basic functionality as hiperfifo.c does, + * but this uses libev instead of libevent. + * + * Written by Jeff Pohlmeyer, converted to use libev by Markus Koetter + +Requires libev and a (POSIX?) system that has mkfifo(). + +This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c" +sample programs. + +When running, the program creates the named pipe "hiper.fifo" + +Whenever there is input into the fifo, the program reads the input as a list +of URL's and creates some new easy handles to fetch each URL via the +curl_multi "hiper" API. + + +Thus, you can try a single URL: + % echo http://www.yahoo.com > hiper.fifo + +Or a whole bunch of them: + % cat my-url-list > hiper.fifo + +The fifo buffer is handled almost instantly, so you can even add more URL's +while the previous requests are still being downloaded. + +Note: + For the sake of simplicity, URL length is limited to 1023 char's ! + +This is purely a demo app, all retrieved data is simply discarded by the write +callback. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DPRINT(x...) printf(x) + +#define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */ + + +/* Global information, common to all connections */ +typedef struct _GlobalInfo +{ + struct ev_loop *loop; + struct ev_io fifo_event; + struct ev_timer timer_event; + CURLM *multi; + int still_running; + FILE *input; +} GlobalInfo; + + +/* Information associated with a specific easy handle */ +typedef struct _ConnInfo +{ + CURL *easy; + char *url; + GlobalInfo *global; + char error[CURL_ERROR_SIZE]; +} ConnInfo; + + +/* Information associated with a specific socket */ +typedef struct _SockInfo +{ + curl_socket_t sockfd; + CURL *easy; + int action; + long timeout; + struct ev_io ev; + int evset; + GlobalInfo *global; +} SockInfo; + +static void timer_cb(EV_P_ struct ev_timer *w, int revents); + +/* Update the event timer after curl_multi library calls */ +static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g) +{ + DPRINT("%s %li\n", __PRETTY_FUNCTION__, timeout_ms); + ev_timer_stop(g->loop, &g->timer_event); + if(timeout_ms >= 0) { + /* -1 means delete, other values are timeout times in milliseconds */ + double t = timeout_ms / 1000; + ev_timer_init(&g->timer_event, timer_cb, t, 0.); + ev_timer_start(g->loop, &g->timer_event); + } + return 0; +} + +/* Die if we get a bad CURLMcode somewhere */ +static void mcode_or_die(const char *where, CURLMcode code) +{ + if(CURLM_OK != code) { + const char *s; + switch(code) { + case CURLM_BAD_HANDLE: + s = "CURLM_BAD_HANDLE"; + break; + case CURLM_BAD_EASY_HANDLE: + s = "CURLM_BAD_EASY_HANDLE"; + break; + case CURLM_OUT_OF_MEMORY: + s = "CURLM_OUT_OF_MEMORY"; + break; + case CURLM_INTERNAL_ERROR: + s = "CURLM_INTERNAL_ERROR"; + break; + case CURLM_UNKNOWN_OPTION: + s = "CURLM_UNKNOWN_OPTION"; + break; + case CURLM_LAST: + s = "CURLM_LAST"; + break; + default: + s = "CURLM_unknown"; + break; + case CURLM_BAD_SOCKET: + s = "CURLM_BAD_SOCKET"; + fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s); + /* ignore this error */ + return; + } + fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s); + exit(code); + } +} + + + +/* Check for completed transfers, and remove their easy handles */ +static void check_multi_info(GlobalInfo *g) +{ + char *eff_url; + CURLMsg *msg; + int msgs_left; + ConnInfo *conn; + CURL *easy; + CURLcode res; + + fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running); + while((msg = curl_multi_info_read(g->multi, &msgs_left))) { + if(msg->msg == CURLMSG_DONE) { + easy = msg->easy_handle; + res = msg->data.result; + curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn); + curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url); + fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error); + curl_multi_remove_handle(g->multi, easy); + free(conn->url); + curl_easy_cleanup(easy); + free(conn); + } + } +} + + + +/* Called by libevent when we get action on a multi socket */ +static void event_cb(EV_P_ struct ev_io *w, int revents) +{ + DPRINT("%s w %p revents %i\n", __PRETTY_FUNCTION__, w, revents); + GlobalInfo *g = (GlobalInfo*) w->data; + CURLMcode rc; + + int action = ((revents & EV_READ) ? CURL_POLL_IN : 0) | + ((revents & EV_WRITE) ? CURL_POLL_OUT : 0); + rc = curl_multi_socket_action(g->multi, w->fd, action, &g->still_running); + mcode_or_die("event_cb: curl_multi_socket_action", rc); + check_multi_info(g); + if(g->still_running <= 0) { + fprintf(MSG_OUT, "last transfer done, kill timeout\n"); + ev_timer_stop(g->loop, &g->timer_event); + } +} + +/* Called by libevent when our timeout expires */ +static void timer_cb(EV_P_ struct ev_timer *w, int revents) +{ + DPRINT("%s w %p revents %i\n", __PRETTY_FUNCTION__, w, revents); + + GlobalInfo *g = (GlobalInfo *)w->data; + CURLMcode rc; + + rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, + &g->still_running); + mcode_or_die("timer_cb: curl_multi_socket_action", rc); + check_multi_info(g); +} + +/* Clean up the SockInfo structure */ +static void remsock(SockInfo *f, GlobalInfo *g) +{ + printf("%s \n", __PRETTY_FUNCTION__); + if(f) { + if(f->evset) + ev_io_stop(g->loop, &f->ev); + free(f); + } +} + + + +/* Assign information to a SockInfo structure */ +static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act, + GlobalInfo *g) +{ + printf("%s \n", __PRETTY_FUNCTION__); + + int kind = ((act & CURL_POLL_IN) ? EV_READ : 0) | + ((act & CURL_POLL_OUT) ? EV_WRITE : 0); + + f->sockfd = s; + f->action = act; + f->easy = e; + if(f->evset) + ev_io_stop(g->loop, &f->ev); + ev_io_init(&f->ev, event_cb, f->sockfd, kind); + f->ev.data = g; + f->evset = 1; + ev_io_start(g->loop, &f->ev); +} + + + +/* Initialize a new SockInfo structure */ +static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g) +{ + SockInfo *fdp = calloc(1, sizeof(SockInfo)); + + fdp->global = g; + setsock(fdp, s, easy, action, g); + curl_multi_assign(g->multi, s, fdp); +} + +/* CURLMOPT_SOCKETFUNCTION */ +static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp) +{ + DPRINT("%s e %p s %i what %i cbp %p sockp %p\n", + __PRETTY_FUNCTION__, e, s, what, cbp, sockp); + + GlobalInfo *g = (GlobalInfo*) cbp; + SockInfo *fdp = (SockInfo*) sockp; + const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE"}; + + fprintf(MSG_OUT, + "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]); + if(what == CURL_POLL_REMOVE) { + fprintf(MSG_OUT, "\n"); + remsock(fdp, g); + } + else { + if(!fdp) { + fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]); + addsock(s, e, what, g); + } + else { + fprintf(MSG_OUT, + "Changing action from %s to %s\n", + whatstr[fdp->action], whatstr[what]); + setsock(fdp, s, e, what, g); + } + } + return 0; +} + + +/* CURLOPT_WRITEFUNCTION */ +static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data) +{ + size_t realsize = size * nmemb; + ConnInfo *conn = (ConnInfo*) data; + (void)ptr; + (void)conn; + return realsize; +} + + +/* CURLOPT_PROGRESSFUNCTION */ +static int prog_cb(void *p, double dltotal, double dlnow, double ult, + double uln) +{ + ConnInfo *conn = (ConnInfo *)p; + (void)ult; + (void)uln; + + fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal); + return 0; +} + + +/* Create a new easy handle, and add it to the global curl_multi */ +static void new_conn(char *url, GlobalInfo *g) +{ + ConnInfo *conn; + CURLMcode rc; + + conn = calloc(1, sizeof(ConnInfo)); + conn->error[0]='\0'; + + conn->easy = curl_easy_init(); + if(!conn->easy) { + fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n"); + exit(2); + } + conn->global = g; + conn->url = strdup(url); + curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url); + curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn); + curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error); + curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn); + curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L); + + fprintf(MSG_OUT, + "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url); + rc = curl_multi_add_handle(g->multi, conn->easy); + mcode_or_die("new_conn: curl_multi_add_handle", rc); + + /* note that add_handle() sets a timeout to trigger soon so that the + necessary socket_action() gets called */ +} + +/* This gets called whenever data is received from the fifo */ +static void fifo_cb(EV_P_ struct ev_io *w, int revents) +{ + char s[1024]; + long int rv = 0; + int n = 0; + GlobalInfo *g = (GlobalInfo *)w->data; + + do { + s[0]='\0'; + rv = fscanf(g->input, "%1023s%n", s, &n); + s[n]='\0'; + if(n && s[0]) { + new_conn(s, g); /* if we read a URL, go get it! */ + } + else + break; + } while(rv != EOF); +} + +/* Create a named pipe and tell libevent to monitor it */ +static int init_fifo(GlobalInfo *g) +{ + struct stat st; + static const char *fifo = "hiper.fifo"; + curl_socket_t sockfd; + + fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo); + if(lstat (fifo, &st) == 0) { + if((st.st_mode & S_IFMT) == S_IFREG) { + errno = EEXIST; + perror("lstat"); + exit(1); + } + } + unlink(fifo); + if(mkfifo (fifo, 0600) == -1) { + perror("mkfifo"); + exit(1); + } + sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0); + if(sockfd == -1) { + perror("open"); + exit(1); + } + g->input = fdopen(sockfd, "r"); + + fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo); + ev_io_init(&g->fifo_event, fifo_cb, sockfd, EV_READ); + ev_io_start(g->loop, &g->fifo_event); + return (0); +} + +int main(int argc, char **argv) +{ + GlobalInfo g; + (void)argc; + (void)argv; + + memset(&g, 0, sizeof(GlobalInfo)); + g.loop = ev_default_loop(0); + + init_fifo(&g); + g.multi = curl_multi_init(); + + ev_timer_init(&g.timer_event, timer_cb, 0., 0.); + g.timer_event.data = &g; + g.fifo_event.data = &g; + curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb); + curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g); + curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb); + curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g); + + /* we do not call any curl_multi_socket*() function yet as we have no handles + added! */ + + ev_loop(g.loop, 0); + curl_multi_cleanup(g.multi); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/externalsocket.c b/local-test-curl-delta-01/afc-curl/docs/examples/externalsocket.c new file mode 100644 index 0000000000000000000000000000000000000000..010654298d4358bded0d08a6a10e188f1d2758c1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/externalsocket.c @@ -0,0 +1,178 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Pass in a custom socket for libcurl to use. + * + */ +#ifdef _WIN32 +#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS +#define _WINSOCK_DEPRECATED_NO_WARNINGS /* for inet_addr() */ +#endif +#endif + +#include +#include +#include +#include + +#ifdef _WIN32 +#define close closesocket +#else +#include /* socket types */ +#include /* socket definitions */ +#include +#include /* inet (3) functions */ +#include /* misc. Unix functions */ +#endif + +#include + +/* The IP address and port number to connect to */ +#define IPADDR "127.0.0.1" +#define PORTNUM 80 + +#ifndef INADDR_NONE +#define INADDR_NONE 0xffffffff +#endif + +static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); + return written; +} + +static int closecb(void *clientp, curl_socket_t item) +{ + (void)clientp; + printf("libcurl wants to close %d now\n", (int)item); + return 0; +} + +static curl_socket_t opensocket(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address) +{ + curl_socket_t sockfd; + (void)purpose; + (void)address; + sockfd = *(curl_socket_t *)clientp; + /* the actual externally set socket is passed in via the OPENSOCKETDATA + option */ + return sockfd; +} + +static int sockopt_callback(void *clientp, curl_socket_t curlfd, + curlsocktype purpose) +{ + (void)clientp; + (void)curlfd; + (void)purpose; + /* This return code was added in libcurl 7.21.5 */ + return CURL_SOCKOPT_ALREADY_CONNECTED; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + struct sockaddr_in servaddr; /* socket address structure */ + curl_socket_t sockfd; + +#ifdef _WIN32 + WSADATA wsaData; + int initwsa = WSAStartup(MAKEWORD(2, 2), &wsaData); + if(initwsa) { + printf("WSAStartup failed: %d\n", initwsa); + return 1; + } +#endif + + curl = curl_easy_init(); + if(curl) { + /* + * Note that libcurl internally thinks that you connect to the host and + * port that you specify in the URL option. + */ + curl_easy_setopt(curl, CURLOPT_URL, "http://99.99.99.99:9999"); + + /* Create the socket "manually" */ + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if(sockfd == CURL_SOCKET_BAD) { + printf("Error creating listening socket.\n"); + return 3; + } + + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(PORTNUM); + + servaddr.sin_addr.s_addr = inet_addr(IPADDR); + if(INADDR_NONE == servaddr.sin_addr.s_addr) { + close(sockfd); + return 2; + } + + if(connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == + -1) { + close(sockfd); + printf("client error: connect: %s\n", strerror(errno)); + return 1; + } + + /* no progress meter please */ + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); + + /* send all data to this function */ + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); + + /* call this function to get a socket */ + curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket); + curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sockfd); + + /* call this function to close sockets */ + curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closecb); + curl_easy_setopt(curl, CURLOPT_CLOSESOCKETDATA, &sockfd); + + /* call this function to set options for the socket */ + curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); + + res = curl_easy_perform(curl); + + curl_easy_cleanup(curl); + + close(sockfd); + + if(res) { + printf("libcurl error: %d\n", res); + return 4; + } + } + +#ifdef _WIN32 + WSACleanup(); +#endif + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ftp-wildcard.c b/local-test-curl-delta-01/afc-curl/docs/examples/ftp-wildcard.c new file mode 100644 index 0000000000000000000000000000000000000000..53fb76e375226327ce13011557a8638791ada0f5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ftp-wildcard.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 + * + ***************************************************************************/ +/* + * FTP wildcard pattern matching + * + */ +#include +#include + +struct callback_data { + FILE *output; +}; + +static long file_is_coming(struct curl_fileinfo *finfo, + struct callback_data *data, + int remains); + +static long file_is_downloaded(struct callback_data *data); + +static size_t write_it(char *buff, size_t size, size_t nmemb, + void *cb_data); + +int main(int argc, char **argv) +{ + /* curl easy handle */ + CURL *handle; + + /* help data */ + struct callback_data data = { 0 }; + + /* global initialization */ + CURLcode rc = curl_global_init(CURL_GLOBAL_ALL); + if(rc) + return (int)rc; + + /* initialization of easy handle */ + handle = curl_easy_init(); + if(!handle) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + + /* turn on wildcard matching */ + curl_easy_setopt(handle, CURLOPT_WILDCARDMATCH, 1L); + + /* callback is called before download of concrete file started */ + curl_easy_setopt(handle, CURLOPT_CHUNK_BGN_FUNCTION, file_is_coming); + + /* callback is called after data from the file have been transferred */ + curl_easy_setopt(handle, CURLOPT_CHUNK_END_FUNCTION, file_is_downloaded); + + /* this callback writes contents into files */ + curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_it); + + /* put transfer data into callbacks */ + curl_easy_setopt(handle, CURLOPT_CHUNK_DATA, &data); + curl_easy_setopt(handle, CURLOPT_WRITEDATA, &data); + + /* curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L); */ + + /* set a URL containing wildcard pattern (only in the last part) */ + if(argc == 2) + curl_easy_setopt(handle, CURLOPT_URL, argv[1]); + else + curl_easy_setopt(handle, CURLOPT_URL, "ftp://example.com/test/*"); + + /* and start transfer! */ + rc = curl_easy_perform(handle); + + curl_easy_cleanup(handle); + curl_global_cleanup(); + return (int)rc; +} + +static long file_is_coming(struct curl_fileinfo *finfo, + struct callback_data *data, + int remains) +{ + printf("%3d %40s %10luB ", remains, finfo->filename, + (unsigned long)finfo->size); + + switch(finfo->filetype) { + case CURLFILETYPE_DIRECTORY: + printf(" DIR\n"); + break; + case CURLFILETYPE_FILE: + printf("FILE "); + break; + default: + printf("OTHER\n"); + break; + } + + if(finfo->filetype == CURLFILETYPE_FILE) { + /* do not transfer files >= 50B */ + if(finfo->size > 50) { + printf("SKIPPED\n"); + return CURL_CHUNK_BGN_FUNC_SKIP; + } + + data->output = fopen(finfo->filename, "wb"); + if(!data->output) { + return CURL_CHUNK_BGN_FUNC_FAIL; + } + } + + return CURL_CHUNK_BGN_FUNC_OK; +} + +static long file_is_downloaded(struct callback_data *data) +{ + if(data->output) { + printf("DOWNLOADED\n"); + fclose(data->output); + data->output = 0x0; + } + return CURL_CHUNK_END_FUNC_OK; +} + +static size_t write_it(char *buff, size_t size, size_t nmemb, + void *cb_data) +{ + struct callback_data *data = cb_data; + size_t written = 0; + if(data->output) + written = fwrite(buff, size, nmemb, data->output); + else + /* listing output */ + written = fwrite(buff, size, nmemb, stdout); + return written; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ftpget.c b/local-test-curl-delta-01/afc-curl/docs/examples/ftpget.c new file mode 100644 index 0000000000000000000000000000000000000000..95369c1c02bd745b33640fadfeb3a43bafcda0a7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ftpget.c @@ -0,0 +1,94 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 + +/* + * Get a single file from an FTP server. + * + */ + +struct FtpFile { + const char *filename; + FILE *stream; +}; + +static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream) +{ + struct FtpFile *out = (struct FtpFile *)stream; + if(!out->stream) { + /* open file for writing */ + out->stream = fopen(out->filename, "wb"); + if(!out->stream) + return 0; /* failure, cannot open file to write */ + } + return fwrite(buffer, size, nmemb, out->stream); +} + + +int main(void) +{ + CURL *curl; + CURLcode res; + struct FtpFile ftpfile = { + "curl.tar.gz", /* name to store the file as if successful */ + NULL + }; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + /* + * You better replace the URL with one that works! + */ + curl_easy_setopt(curl, CURLOPT_URL, + "ftp://ftp.example.com/curl/curl-7.9.2.tar.gz"); + /* Define our callback to get called when there is data to be written */ + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite); + /* Set a pointer to our struct to pass to the callback */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); + + /* Switch on full protocol/debug output */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + + if(CURLE_OK != res) { + /* we failed */ + fprintf(stderr, "curl told us %d\n", res); + } + } + + if(ftpfile.stream) + fclose(ftpfile.stream); /* close the local file */ + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ftpgetresp.c b/local-test-curl-delta-01/afc-curl/docs/examples/ftpgetresp.c new file mode 100644 index 0000000000000000000000000000000000000000..256998d8c56137c638d655abaa63bc4d30955dd3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ftpgetresp.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 + +#include + +/* + * Similar to ftpget.c but also stores the received response-lines + * in a separate file using our own callback! + * + */ +static size_t +write_response(void *ptr, size_t size, size_t nmemb, void *data) +{ + FILE *writehere = (FILE *)data; + return fwrite(ptr, size, nmemb, writehere); +} + +#define FTPBODY "ftp-list" +#define FTPHEADERS "ftp-responses" + +int main(void) +{ + CURL *curl; + CURLcode res; + FILE *ftpfile; + FILE *respfile; + + /* local filename to store the file as */ + ftpfile = fopen(FTPBODY, "wb"); /* b is binary, needed on Windows */ + + /* local filename to store the FTP server's response lines in */ + respfile = fopen(FTPHEADERS, "wb"); /* b is binary, needed on Windows */ + + curl = curl_easy_init(); + if(curl) { + /* Get a file listing from sunet */ + curl_easy_setopt(curl, CURLOPT_URL, "ftp://ftp.example.com/"); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, ftpfile); + /* If you intend to use this on Windows with a libcurl DLL, you must use + CURLOPT_WRITEFUNCTION as well */ + curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_response); + curl_easy_setopt(curl, CURLOPT_HEADERDATA, respfile); + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + fclose(ftpfile); /* close the local file */ + fclose(respfile); /* close the response file */ + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ftpsget.c b/local-test-curl-delta-01/afc-curl/docs/examples/ftpsget.c new file mode 100644 index 0000000000000000000000000000000000000000..dfe80b9f8bc928a956e0cd7a89af31444d6f8699 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ftpsget.c @@ -0,0 +1,101 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 + +/* + * Get a single file from an FTPS server. + * + */ + +struct FtpFile { + const char *filename; + FILE *stream; +}; + +static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, + void *stream) +{ + struct FtpFile *out = (struct FtpFile *)stream; + if(!out->stream) { + /* open file for writing */ + out->stream = fopen(out->filename, "wb"); + if(!out->stream) + return 0; /* failure, cannot open file to write */ + } + return fwrite(buffer, size, nmemb, out->stream); +} + + +int main(void) +{ + CURL *curl; + CURLcode res; + struct FtpFile ftpfile = { + "yourfile.bin", /* name to store the file as if successful */ + NULL + }; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + /* + * You better replace the URL with one that works! Note that we use an + * FTP:// URL with standard explicit FTPS. You can also do FTPS:// URLs if + * you want to do the rarer kind of transfers: implicit. + */ + curl_easy_setopt(curl, CURLOPT_URL, + "ftp://user@server/home/user/file.txt"); + /* Define our callback to get called when there is data to be written */ + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite); + /* Set a pointer to our struct to pass to the callback */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); + + /* We activate SSL and we require it for both control and data */ + curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL); + + /* Switch on full protocol/debug output */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + + if(CURLE_OK != res) { + /* we failed */ + fprintf(stderr, "curl told us %d\n", res); + } + } + + if(ftpfile.stream) + fclose(ftpfile.stream); /* close the local file */ + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ftpuploadresume.c b/local-test-curl-delta-01/afc-curl/docs/examples/ftpuploadresume.c new file mode 100644 index 0000000000000000000000000000000000000000..d4063925dd4175f59a43076d944d7b4147cb1ff4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ftpuploadresume.c @@ -0,0 +1,165 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Upload to FTP, resuming failed transfers. Active mode. + * + */ + +#include +#include +#include + +/* parse headers for Content-Length */ +static size_t getcontentlengthfunc(void *ptr, size_t size, size_t nmemb, + void *stream) +{ + int r; + long len = 0; + + r = sscanf(ptr, "Content-Length: %ld\n", &len); + if(r) + *((long *) stream) = len; + + return size * nmemb; +} + +/* discard downloaded data */ +static size_t discardfunc(void *ptr, size_t size, size_t nmemb, void *stream) +{ + (void)ptr; + (void)stream; + return size * nmemb; +} + +/* read data to upload */ +static size_t readfunc(char *ptr, size_t size, size_t nmemb, void *stream) +{ + FILE *f = stream; + size_t n; + + if(ferror(f)) + return CURL_READFUNC_ABORT; + + n = fread(ptr, size, nmemb, f) * size; + + return n; +} + + +static int upload(CURL *curlhandle, const char *remotepath, + const char *localpath, long timeout, long tries) +{ + FILE *f; + long uploaded_len = 0; + CURLcode r = CURLE_GOT_NOTHING; + int c; + + f = fopen(localpath, "rb"); + if(!f) { + perror(NULL); + return 0; + } + + curl_easy_setopt(curlhandle, CURLOPT_UPLOAD, 1L); + + curl_easy_setopt(curlhandle, CURLOPT_URL, remotepath); + + if(timeout) + curl_easy_setopt(curlhandle, CURLOPT_SERVER_RESPONSE_TIMEOUT, timeout); + + curl_easy_setopt(curlhandle, CURLOPT_HEADERFUNCTION, getcontentlengthfunc); + curl_easy_setopt(curlhandle, CURLOPT_HEADERDATA, &uploaded_len); + + curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, discardfunc); + + curl_easy_setopt(curlhandle, CURLOPT_READFUNCTION, readfunc); + curl_easy_setopt(curlhandle, CURLOPT_READDATA, f); + + /* enable active mode */ + curl_easy_setopt(curlhandle, CURLOPT_FTPPORT, "-"); + + /* allow the server no more than 7 seconds to connect back */ + curl_easy_setopt(curlhandle, CURLOPT_ACCEPTTIMEOUT_MS, 7000L); + + curl_easy_setopt(curlhandle, CURLOPT_FTP_CREATE_MISSING_DIRS, 1L); + + curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1L); + + for(c = 0; (r != CURLE_OK) && (c < tries); c++) { + /* are we resuming? */ + if(c) { /* yes */ + /* determine the length of the file already written */ + + /* + * With NOBODY and NOHEADER, libcurl issues a SIZE command, but the only + * way to retrieve the result is to parse the returned Content-Length + * header. Thus, getcontentlengthfunc(). We need discardfunc() above + * because HEADER dumps the headers to stdout without it. + */ + curl_easy_setopt(curlhandle, CURLOPT_NOBODY, 1L); + curl_easy_setopt(curlhandle, CURLOPT_HEADER, 1L); + + r = curl_easy_perform(curlhandle); + if(r != CURLE_OK) + continue; + + curl_easy_setopt(curlhandle, CURLOPT_NOBODY, 0L); + curl_easy_setopt(curlhandle, CURLOPT_HEADER, 0L); + + fseek(f, uploaded_len, SEEK_SET); + + curl_easy_setopt(curlhandle, CURLOPT_APPEND, 1L); + } + else { /* no */ + curl_easy_setopt(curlhandle, CURLOPT_APPEND, 0L); + } + + r = curl_easy_perform(curlhandle); + } + + fclose(f); + + if(r == CURLE_OK) + return 1; + else { + fprintf(stderr, "%s\n", curl_easy_strerror(r)); + return 0; + } +} + +int main(void) +{ + CURL *curlhandle = NULL; + + curl_global_init(CURL_GLOBAL_ALL); + curlhandle = curl_easy_init(); + + upload(curlhandle, "ftp://user:pass@example.com/path/file", "C:\\file", + 0, 3); + + curl_easy_cleanup(curlhandle); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/getinfo.c b/local-test-curl-delta-01/afc-curl/docs/examples/getinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..9c178c2c8ce3ae5870ee4b7c1948a2976763cfea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/getinfo.c @@ -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 + * + ***************************************************************************/ +/* + * Use getinfo to get content-type after completed transfer. + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/"); + res = curl_easy_perform(curl); + + if(CURLE_OK == res) { + char *ct; + /* ask for the content-type */ + res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); + + if((CURLE_OK == res) && ct) + printf("We received Content-Type: %s\n", ct); + } + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/getinmemory.c b/local-test-curl-delta-01/afc-curl/docs/examples/getinmemory.c new file mode 100644 index 0000000000000000000000000000000000000000..173247d91520835602189e6cec7ad2e574b00636 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/getinmemory.c @@ -0,0 +1,118 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Shows how the write callback function can be used to download data into a + * chunk of memory instead of storing it in a file. + * + */ + +#include +#include +#include + +#include + +struct MemoryStruct { + char *memory; + size_t size; +}; + +static size_t +WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) +{ + size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)userp; + + char *ptr = realloc(mem->memory, mem->size + realsize + 1); + if(!ptr) { + /* out of memory! */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + + mem->memory = ptr; + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; +} + +int main(void) +{ + CURL *curl_handle; + CURLcode res; + + struct MemoryStruct chunk; + + chunk.memory = malloc(1); /* grown as needed by the realloc above */ + chunk.size = 0; /* no data at this point */ + + curl_global_init(CURL_GLOBAL_ALL); + + /* init the curl session */ + curl_handle = curl_easy_init(); + + /* specify URL to get */ + curl_easy_setopt(curl_handle, CURLOPT_URL, "https://www.example.com/"); + + /* send all data to this function */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + + /* we pass our 'chunk' struct to the callback function */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); + + /* some servers do not like requests that are made without a user-agent + field, so we provide one */ + curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); + + /* get it! */ + res = curl_easy_perform(curl_handle); + + /* check for errors */ + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + } + else { + /* + * Now, our chunk.memory points to a memory block that is chunk.size + * bytes big and contains the remote file. + * + * Do something nice with it! + */ + + printf("%lu bytes retrieved\n", (unsigned long)chunk.size); + } + + /* cleanup curl stuff */ + curl_easy_cleanup(curl_handle); + + free(chunk.memory); + + /* we are done with libcurl, so clean it up */ + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/getredirect.c b/local-test-curl-delta-01/afc-curl/docs/examples/getredirect.c new file mode 100644 index 0000000000000000000000000000000000000000..91c778d3c1b8e8158e35d29ce486871e169bbdfe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/getredirect.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Show how to extract Location: header and URL to redirect to. + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + char *location; + long response_code; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + + /* example.com is redirected, figure out the redirection! */ + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + else { + res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); + if((res == CURLE_OK) && + ((response_code / 100) != 3)) { + /* a redirect implies a 3xx response code */ + fprintf(stderr, "Not a redirect.\n"); + } + else { + res = curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &location); + + if((res == CURLE_OK) && location) { + /* This is the new absolute URL that you could redirect to, even if + * the Location: response header may have been a relative URL. */ + printf("Redirected to: %s\n", location); + } + } + } + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/getreferrer.c b/local-test-curl-delta-01/afc-curl/docs/examples/getreferrer.c new file mode 100644 index 0000000000000000000000000000000000000000..c46f7825a0aa96a34f42b7b4e993fb69c726bd79 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/getreferrer.c @@ -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 + * + ***************************************************************************/ +/* + * Show how to extract referrer header. + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + + curl = curl_easy_init(); + if(curl) { + CURLcode res; + + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + curl_easy_setopt(curl, CURLOPT_REFERER, "https://example.org/referrer"); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + else { + char *hdr; + res = curl_easy_getinfo(curl, CURLINFO_REFERER, &hdr); + if((res == CURLE_OK) && hdr) + printf("Referrer header: %s\n", hdr); + } + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ghiper.c b/local-test-curl-delta-01/afc-curl/docs/examples/ghiper.c new file mode 100644 index 0000000000000000000000000000000000000000..57047edddf0fb3eb793c6ddde353a348b50a7a60 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ghiper.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 + * + ***************************************************************************/ +/* + * multi socket API usage together with glib2 + * + */ +/* Example application source code using the multi socket interface to + * download many files at once. + * + * Written by Jeff Pohlmeyer + + Requires glib-2.x and a (POSIX?) system that has mkfifo(). + + This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c" + sample programs, adapted to use glib's g_io_channel in place of libevent. + + When running, the program creates the named pipe "hiper.fifo" + + Whenever there is input into the fifo, the program reads the input as a list + of URL's and creates some new easy handles to fetch each URL via the + curl_multi "hiper" API. + + + Thus, you can try a single URL: + % echo http://www.yahoo.com > hiper.fifo + + Or a whole bunch of them: + % cat my-url-list > hiper.fifo + + The fifo buffer is handled almost instantly, so you can even add more URL's + while the previous requests are still being downloaded. + + This is purely a demo app, all retrieved data is simply discarded by the write + callback. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define MSG_OUT g_print /* Change to "g_error" to write to stderr */ +#define SHOW_VERBOSE 0 /* Set to non-zero for libcurl messages */ +#define SHOW_PROGRESS 0 /* Set to non-zero to enable progress callback */ + +/* Global information, common to all connections */ +typedef struct _GlobalInfo { + CURLM *multi; + guint timer_event; + int still_running; +} GlobalInfo; + +/* Information associated with a specific easy handle */ +typedef struct _ConnInfo { + CURL *easy; + char *url; + GlobalInfo *global; + char error[CURL_ERROR_SIZE]; +} ConnInfo; + +/* Information associated with a specific socket */ +typedef struct _SockInfo { + curl_socket_t sockfd; + CURL *easy; + int action; + long timeout; + GIOChannel *ch; + guint ev; + GlobalInfo *global; +} SockInfo; + +/* Die if we get a bad CURLMcode somewhere */ +static void mcode_or_die(const char *where, CURLMcode code) +{ + if(CURLM_OK != code) { + const char *s; + switch(code) { + case CURLM_BAD_HANDLE: s = "CURLM_BAD_HANDLE"; break; + case CURLM_BAD_EASY_HANDLE: s = "CURLM_BAD_EASY_HANDLE"; break; + case CURLM_OUT_OF_MEMORY: s = "CURLM_OUT_OF_MEMORY"; break; + case CURLM_INTERNAL_ERROR: s = "CURLM_INTERNAL_ERROR"; break; + case CURLM_BAD_SOCKET: s = "CURLM_BAD_SOCKET"; break; + case CURLM_UNKNOWN_OPTION: s = "CURLM_UNKNOWN_OPTION"; break; + case CURLM_LAST: s = "CURLM_LAST"; break; + default: s = "CURLM_unknown"; + } + MSG_OUT("ERROR: %s returns %s\n", where, s); + exit(code); + } +} + +/* Check for completed transfers, and remove their easy handles */ +static void check_multi_info(GlobalInfo *g) +{ + char *eff_url; + CURLMsg *msg; + int msgs_left; + ConnInfo *conn; + CURL *easy; + CURLcode res; + + MSG_OUT("REMAINING: %d\n", g->still_running); + while((msg = curl_multi_info_read(g->multi, &msgs_left))) { + if(msg->msg == CURLMSG_DONE) { + easy = msg->easy_handle; + res = msg->data.result; + curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn); + curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url); + MSG_OUT("DONE: %s => (%d) %s\n", eff_url, res, conn->error); + curl_multi_remove_handle(g->multi, easy); + free(conn->url); + curl_easy_cleanup(easy); + free(conn); + } + } +} + +/* Called by glib when our timeout expires */ +static gboolean timer_cb(gpointer data) +{ + GlobalInfo *g = (GlobalInfo *)data; + CURLMcode rc; + + rc = curl_multi_socket_action(g->multi, + CURL_SOCKET_TIMEOUT, 0, &g->still_running); + mcode_or_die("timer_cb: curl_multi_socket_action", rc); + check_multi_info(g); + return FALSE; +} + +/* Update the event timer after curl_multi library calls */ +static int update_timeout_cb(CURLM *multi, long timeout_ms, void *userp) +{ + struct timeval timeout; + GlobalInfo *g = (GlobalInfo *)userp; + timeout.tv_sec = timeout_ms/1000; + timeout.tv_usec = (timeout_ms%1000)*1000; + + MSG_OUT("*** update_timeout_cb %ld => %ld:%ld ***\n", + timeout_ms, timeout.tv_sec, timeout.tv_usec); + + /* + * if timeout_ms is -1, just delete the timer + * + * For other values of timeout_ms, this should set or *update* the timer to + * the new value + */ + if(timeout_ms >= 0) + g->timer_event = g_timeout_add(timeout_ms, timer_cb, g); + return 0; +} + +/* Called by glib when we get action on a multi socket */ +static gboolean event_cb(GIOChannel *ch, GIOCondition condition, gpointer data) +{ + GlobalInfo *g = (GlobalInfo*) data; + CURLMcode rc; + int fd = g_io_channel_unix_get_fd(ch); + + int action = + ((condition & G_IO_IN) ? CURL_CSELECT_IN : 0) | + ((condition & G_IO_OUT) ? CURL_CSELECT_OUT : 0); + + rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running); + mcode_or_die("event_cb: curl_multi_socket_action", rc); + + check_multi_info(g); + if(g->still_running) { + return TRUE; + } + else { + MSG_OUT("last transfer done, kill timeout\n"); + if(g->timer_event) { + g_source_remove(g->timer_event); + } + return FALSE; + } +} + +/* Clean up the SockInfo structure */ +static void remsock(SockInfo *f) +{ + if(!f) { + return; + } + if(f->ev) { + g_source_remove(f->ev); + } + g_free(f); +} + +/* Assign information to a SockInfo structure */ +static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act, + GlobalInfo *g) +{ + GIOCondition kind = + ((act & CURL_POLL_IN) ? G_IO_IN : 0) | + ((act & CURL_POLL_OUT) ? G_IO_OUT : 0); + + f->sockfd = s; + f->action = act; + f->easy = e; + if(f->ev) { + g_source_remove(f->ev); + } + f->ev = g_io_add_watch(f->ch, kind, event_cb, g); +} + +/* Initialize a new SockInfo structure */ +static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g) +{ + SockInfo *fdp = g_malloc0(sizeof(SockInfo)); + + fdp->global = g; + fdp->ch = g_io_channel_unix_new(s); + setsock(fdp, s, easy, action, g); + curl_multi_assign(g->multi, s, fdp); +} + +/* CURLMOPT_SOCKETFUNCTION */ +static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp) +{ + GlobalInfo *g = (GlobalInfo*) cbp; + SockInfo *fdp = (SockInfo*) sockp; + static const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" }; + + MSG_OUT("socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]); + if(what == CURL_POLL_REMOVE) { + MSG_OUT("\n"); + remsock(fdp); + } + else { + if(!fdp) { + MSG_OUT("Adding data: %s%s\n", + (what & CURL_POLL_IN) ? "READ" : "", + (what & CURL_POLL_OUT) ? "WRITE" : ""); + addsock(s, e, what, g); + } + else { + MSG_OUT( + "Changing action from %d to %d\n", fdp->action, what); + setsock(fdp, s, e, what, g); + } + } + return 0; +} + +/* CURLOPT_WRITEFUNCTION */ +static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data) +{ + size_t realsize = size * nmemb; + ConnInfo *conn = (ConnInfo*) data; + (void)ptr; + (void)conn; + return realsize; +} + +/* CURLOPT_PROGRESSFUNCTION */ +static int prog_cb(void *p, double dltotal, double dlnow, double ult, + double uln) +{ + ConnInfo *conn = (ConnInfo *)p; + MSG_OUT("Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal); + return 0; +} + +/* Create a new easy handle, and add it to the global curl_multi */ +static void new_conn(char *url, GlobalInfo *g) +{ + ConnInfo *conn; + CURLMcode rc; + + conn = g_malloc0(sizeof(ConnInfo)); + conn->error[0]='\0'; + conn->easy = curl_easy_init(); + if(!conn->easy) { + MSG_OUT("curl_easy_init() failed, exiting!\n"); + exit(2); + } + conn->global = g; + conn->url = g_strdup(url); + curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url); + curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn); + curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, (long)SHOW_VERBOSE); + curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error); + curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn); + curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, SHOW_PROGRESS ? 0L : 1L); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb); + curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn); + curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(conn->easy, CURLOPT_CONNECTTIMEOUT, 30L); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 1L); + curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 30L); + + MSG_OUT("Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url); + rc = curl_multi_add_handle(g->multi, conn->easy); + mcode_or_die("new_conn: curl_multi_add_handle", rc); + + /* note that add_handle() sets a timeout to trigger soon so that the + necessary socket_action() gets called */ +} + +/* This gets called by glib whenever data is received from the fifo */ +static gboolean fifo_cb(GIOChannel *ch, GIOCondition condition, gpointer data) +{ +#define BUF_SIZE 1024 + gsize len, tp; + gchar *buf, *tmp, *all = NULL; + GIOStatus rv; + + do { + GError *err = NULL; + rv = g_io_channel_read_line(ch, &buf, &len, &tp, &err); + if(buf) { + if(tp) { + buf[tp]='\0'; + } + new_conn(buf, (GlobalInfo*)data); + g_free(buf); + } + else { + buf = g_malloc(BUF_SIZE + 1); + while(TRUE) { + buf[BUF_SIZE]='\0'; + g_io_channel_read_chars(ch, buf, BUF_SIZE, &len, &err); + if(len) { + buf[len]='\0'; + if(all) { + tmp = all; + all = g_strdup_printf("%s%s", tmp, buf); + g_free(tmp); + } + else { + all = g_strdup(buf); + } + } + else { + break; + } + } + if(all) { + new_conn(all, (GlobalInfo*)data); + g_free(all); + } + g_free(buf); + } + if(err) { + g_error("fifo_cb: %s", err->message); + g_free(err); + break; + } + } while((len) && (rv == G_IO_STATUS_NORMAL)); + return TRUE; +} + +int init_fifo(void) +{ + struct stat st; + const char *fifo = "hiper.fifo"; + int socket; + + if(lstat (fifo, &st) == 0) { + if((st.st_mode & S_IFMT) == S_IFREG) { + errno = EEXIST; + perror("lstat"); + exit(1); + } + } + + unlink(fifo); + if(mkfifo (fifo, 0600) == -1) { + perror("mkfifo"); + exit(1); + } + + socket = open(fifo, O_RDWR | O_NONBLOCK, 0); + + if(socket == -1) { + perror("open"); + exit(1); + } + MSG_OUT("Now, pipe some URL's into > %s\n", fifo); + + return socket; +} + +int main(int argc, char **argv) +{ + GlobalInfo *g; + GMainLoop*gmain; + int fd; + GIOChannel* ch; + g = g_malloc0(sizeof(GlobalInfo)); + + fd = init_fifo(); + ch = g_io_channel_unix_new(fd); + g_io_add_watch(ch, G_IO_IN, fifo_cb, g); + gmain = g_main_loop_new(NULL, FALSE); + g->multi = curl_multi_init(); + curl_multi_setopt(g->multi, CURLMOPT_SOCKETFUNCTION, sock_cb); + curl_multi_setopt(g->multi, CURLMOPT_SOCKETDATA, g); + curl_multi_setopt(g->multi, CURLMOPT_TIMERFUNCTION, update_timeout_cb); + curl_multi_setopt(g->multi, CURLMOPT_TIMERDATA, g); + + /* we do not call any curl_multi_socket*() function yet as we have no handles + added! */ + + g_main_loop_run(gmain); + curl_multi_cleanup(g->multi); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/href_extractor.c b/local-test-curl-delta-01/afc-curl/docs/examples/href_extractor.c new file mode 100644 index 0000000000000000000000000000000000000000..5c92b0c23f99a6e970d7ca9c494e56a355bf2405 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/href_extractor.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 + * + ***************************************************************************/ + +/* + * Uses the "Streaming HTML parser" to extract the href pieces in a streaming + * manner from a downloaded HTML. + * + */ +/* + * The HTML parser is found at https://github.com/arjunc77/htmlstreamparser + */ + +#include +#include +#include + + +static size_t write_callback(void *buffer, size_t size, size_t nmemb, + void *hsp) +{ + size_t realsize = size * nmemb, p; + for(p = 0; p < realsize; p++) { + html_parser_char_parse(hsp, ((char *)buffer)[p]); + if(html_parser_cmp_tag(hsp, "a", 1)) + if(html_parser_cmp_attr(hsp, "href", 4)) + if(html_parser_is_in(hsp, HTML_VALUE_ENDED)) { + html_parser_val(hsp)[html_parser_val_length(hsp)] = '\0'; + printf("%s\n", html_parser_val(hsp)); + } + } + return realsize; +} + +int main(int argc, char *argv[]) +{ + char tag[1], attr[4], val[128]; + CURL *curl; + HTMLSTREAMPARSER *hsp; + + if(argc != 2) { + printf("Usage: %s URL\n", argv[0]); + return EXIT_FAILURE; + } + + curl = curl_easy_init(); + + hsp = html_parser_init(); + + html_parser_set_tag_to_lower(hsp, 1); + html_parser_set_attr_to_lower(hsp, 1); + html_parser_set_tag_buffer(hsp, tag, sizeof(tag)); + html_parser_set_attr_buffer(hsp, attr, sizeof(attr)); + html_parser_set_val_buffer(hsp, val, sizeof(val)-1); + + curl_easy_setopt(curl, CURLOPT_URL, argv[1]); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, hsp); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + + curl_easy_perform(curl); + + curl_easy_cleanup(curl); + + html_parser_cleanup(hsp); + + return EXIT_SUCCESS; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/hsts-preload.c b/local-test-curl-delta-01/afc-curl/docs/examples/hsts-preload.c new file mode 100644 index 0000000000000000000000000000000000000000..a25773f42dd7a90d8faa1c1bd67e438a08401b02 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/hsts-preload.c @@ -0,0 +1,118 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Preload domains to HSTS + * + */ +#include +#include +#include + +struct entry { + const char *name; + const char *exp; +}; + +static const struct entry preload_hosts[] = { + { "example.com", "20370320 01:02:03" }, + { "curl.se", "20370320 03:02:01" }, + { NULL, NULL } /* end of list marker */ +}; + +struct state { + int index; +}; + +/* "read" is from the point of the library, it wants data from us. One domain + entry per invoke. */ +static CURLSTScode hstsread(CURL *easy, struct curl_hstsentry *e, + void *userp) +{ + const char *host; + const char *expire; + struct state *s = (struct state *)userp; + (void)easy; + host = preload_hosts[s->index].name; + expire = preload_hosts[s->index++].exp; + + if(host && (strlen(host) < e->namelen)) { + strcpy(e->name, host); + e->includeSubDomains = 0; + strcpy(e->expire, expire); + fprintf(stderr, "HSTS preload '%s' until '%s'\n", host, expire); + } + else + return CURLSTS_DONE; + return CURLSTS_OK; +} + +static CURLSTScode hstswrite(CURL *easy, struct curl_hstsentry *e, + struct curl_index *i, void *userp) +{ + (void)easy; + (void)userp; /* we have no custom input */ + printf("[%u/%u] %s %s\n", (unsigned int)i->index, (unsigned int)i->total, + e->name, e->expire); + return CURLSTS_OK; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + struct state st = {0}; + + /* enable HSTS for this handle */ + curl_easy_setopt(curl, CURLOPT_HSTS_CTRL, (long)CURLHSTS_ENABLE); + + /* function to call at first to populate the cache before the transfer */ + curl_easy_setopt(curl, CURLOPT_HSTSREADFUNCTION, hstsread); + curl_easy_setopt(curl, CURLOPT_HSTSREADDATA, &st); + + /* function to call after transfer to store the new state of the HSTS + cache */ + curl_easy_setopt(curl, CURLOPT_HSTSWRITEFUNCTION, hstswrite); + curl_easy_setopt(curl, CURLOPT_HSTSWRITEDATA, NULL); + + /* use the domain with HTTP but due to the preload, it should do the + transfer using HTTPS */ + curl_easy_setopt(curl, CURLOPT_URL, "http://curl.se"); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/htmltidy.c b/local-test-curl-delta-01/afc-curl/docs/examples/htmltidy.c new file mode 100644 index 0000000000000000000000000000000000000000..498bb85bdc8a20e9408417d3572e8d61c096884c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/htmltidy.c @@ -0,0 +1,130 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Download a document and use libtidy to parse the HTML. + * + */ +/* + * LibTidy => https://www.html-tidy.org/ + */ + +#include +#include +#include +#include + +/* curl write callback, to fill tidy's input buffer... */ +uint write_cb(char *in, uint size, uint nmemb, TidyBuffer *out) +{ + uint r; + r = size * nmemb; + tidyBufAppend(out, in, r); + return r; +} + +/* Traverse the document tree */ +void dumpNode(TidyDoc doc, TidyNode tnod, int indent) +{ + TidyNode child; + for(child = tidyGetChild(tnod); child; child = tidyGetNext(child) ) { + ctmbstr name = tidyNodeGetName(child); + if(name) { + /* if it has a name, then it's an HTML tag ... */ + TidyAttr attr; + printf("%*.*s%s ", indent, indent, "<", name); + /* walk the attribute list */ + for(attr = tidyAttrFirst(child); attr; attr = tidyAttrNext(attr) ) { + printf("%s", tidyAttrName(attr)); + tidyAttrValue(attr) ? printf("=\"%s\" ", + tidyAttrValue(attr)) : printf(" "); + } + printf(">\n"); + } + else { + /* if it does not have a name, then it's probably text, cdata, etc... */ + TidyBuffer buf; + tidyBufInit(&buf); + tidyNodeGetText(doc, child, &buf); + printf("%*.*s\n", indent, indent, buf.bp ? (char *)buf.bp : ""); + tidyBufFree(&buf); + } + dumpNode(doc, child, indent + 4); /* recursive */ + } +} + + +int main(int argc, char **argv) +{ + if(argc == 2) { + CURL *curl; + char curl_errbuf[CURL_ERROR_SIZE]; + TidyDoc tdoc; + TidyBuffer docbuf = {0}; + TidyBuffer tidy_errbuf = {0}; + int err; + + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, argv[1]); + curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errbuf); + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb); + + tdoc = tidyCreate(); + tidyOptSetBool(tdoc, TidyForceOutput, yes); /* try harder */ + tidyOptSetInt(tdoc, TidyWrapLen, 4096); + tidySetErrorBuffer(tdoc, &tidy_errbuf); + tidyBufInit(&docbuf); + + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &docbuf); + err = curl_easy_perform(curl); + if(!err) { + err = tidyParseBuffer(tdoc, &docbuf); /* parse the input */ + if(err >= 0) { + err = tidyCleanAndRepair(tdoc); /* fix any problems */ + if(err >= 0) { + err = tidyRunDiagnostics(tdoc); /* load tidy error buffer */ + if(err >= 0) { + dumpNode(tdoc, tidyGetRoot(tdoc), 0); /* walk the tree */ + fprintf(stderr, "%s\n", tidy_errbuf.bp); /* show errors */ + } + } + } + } + else + fprintf(stderr, "%s\n", curl_errbuf); + + /* clean-up */ + curl_easy_cleanup(curl); + tidyBufFree(&docbuf); + tidyBufFree(&tidy_errbuf); + tidyRelease(tdoc); + return err; + + } + else + printf("usage: %s \n", argv[0]); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/htmltitle.cpp b/local-test-curl-delta-01/afc-curl/docs/examples/htmltitle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee3e023a2c2883ca62d6d0a21e04645f4c1a90d6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/htmltitle.cpp @@ -0,0 +1,296 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Get a web page, extract the title with libxml. + * + + Written by Lars Nilsson + + GNU C++ compile command line suggestion (edit paths accordingly): + + g++ -Wall -I/opt/curl/include -I/opt/libxml/include/libxml2 htmltitle.cpp \ + -o htmltitle -L/opt/curl/lib -L/opt/libxml/lib -lcurl -lxml2 +*/ +#include +#include +#include +#include +#include +#include + +// +// Case-insensitive string comparison +// + +#ifdef _MSC_VER +#define COMPARE(a, b) (!_stricmp((a), (b))) +#else +#define COMPARE(a, b) (!strcasecmp((a), (b))) +#endif + +// +// libxml callback context structure +// + +struct Context +{ + Context(): addTitle(false) { } + + bool addTitle; + std::string title; +}; + +// +// libcurl variables for error strings and returned data + +static char errorBuffer[CURL_ERROR_SIZE]; +static std::string buffer; + +// +// libcurl write callback function +// + +static int writer(char *data, size_t size, size_t nmemb, + std::string *writerData) +{ + if(writerData == NULL) + return 0; + + writerData->append(data, size*nmemb); + + return size * nmemb; +} + +// +// libcurl connection initialization +// + +static bool init(CURL *&conn, char *url) +{ + CURLcode code; + + conn = curl_easy_init(); + + if(conn == NULL) { + fprintf(stderr, "Failed to create CURL connection\n"); + exit(EXIT_FAILURE); + } + + code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, errorBuffer); + if(code != CURLE_OK) { + fprintf(stderr, "Failed to set error buffer [%d]\n", code); + return false; + } + + code = curl_easy_setopt(conn, CURLOPT_URL, url); + if(code != CURLE_OK) { + fprintf(stderr, "Failed to set URL [%s]\n", errorBuffer); + return false; + } + + code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1L); + if(code != CURLE_OK) { + fprintf(stderr, "Failed to set redirect option [%s]\n", errorBuffer); + return false; + } + + code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer); + if(code != CURLE_OK) { + fprintf(stderr, "Failed to set writer [%s]\n", errorBuffer); + return false; + } + + code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, &buffer); + if(code != CURLE_OK) { + fprintf(stderr, "Failed to set write data [%s]\n", errorBuffer); + return false; + } + + return true; +} + +// +// libxml start element callback function +// + +static void StartElement(void *voidContext, + const xmlChar *name, + const xmlChar **attributes) +{ + Context *context = static_cast(voidContext); + + if(COMPARE(reinterpret_cast(name), "TITLE")) { + context->title = ""; + context->addTitle = true; + } + (void) attributes; +} + +// +// libxml end element callback function +// + +static void EndElement(void *voidContext, + const xmlChar *name) +{ + Context *context = static_cast(voidContext); + + if(COMPARE(reinterpret_cast(name), "TITLE")) + context->addTitle = false; +} + +// +// Text handling helper function +// + +static void handleCharacters(Context *context, + const xmlChar *chars, + int length) +{ + if(context->addTitle) + context->title.append(reinterpret_cast(chars), length); +} + +// +// libxml PCDATA callback function +// + +static void Characters(void *voidContext, + const xmlChar *chars, + int length) +{ + Context *context = static_cast(voidContext); + + handleCharacters(context, chars, length); +} + +// +// libxml CDATA callback function +// + +static void cdata(void *voidContext, + const xmlChar *chars, + int length) +{ + Context *context = static_cast(voidContext); + + handleCharacters(context, chars, length); +} + +// +// libxml SAX callback structure +// + +static htmlSAXHandler saxHandler = +{ + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + StartElement, + EndElement, + NULL, + Characters, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + cdata, + NULL +}; + +// +// Parse given (assumed to be) HTML text and return the title +// + +static void parseHtml(const std::string &html, + std::string &title) +{ + htmlParserCtxtPtr ctxt; + Context context; + + ctxt = htmlCreatePushParserCtxt(&saxHandler, &context, "", 0, "", + XML_CHAR_ENCODING_NONE); + + htmlParseChunk(ctxt, html.c_str(), html.size(), 0); + htmlParseChunk(ctxt, "", 0, 1); + + htmlFreeParserCtxt(ctxt); + + title = context.title; +} + +int main(int argc, char *argv[]) +{ + CURL *conn = NULL; + CURLcode code; + std::string title; + + // Ensure one argument is given + + if(argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + curl_global_init(CURL_GLOBAL_DEFAULT); + + // Initialize CURL connection + + if(!init(conn, argv[1])) { + fprintf(stderr, "Connection initialization failed\n"); + exit(EXIT_FAILURE); + } + + // Retrieve content for the URL + + code = curl_easy_perform(conn); + curl_easy_cleanup(conn); + + if(code != CURLE_OK) { + fprintf(stderr, "Failed to get '%s' [%s]\n", argv[1], errorBuffer); + exit(EXIT_FAILURE); + } + + // Parse the (assumed) HTML code + parseHtml(buffer, title); + + // Display the extracted title + printf("Title: %s\n", title.c_str()); + + return EXIT_SUCCESS; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http-options.c b/local-test-curl-delta-01/afc-curl/docs/examples/http-options.c new file mode 100644 index 0000000000000000000000000000000000000000..586b55f12a51271f6d07f73783d2a3c49a796d52 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http-options.c @@ -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 + * + ***************************************************************************/ +/* + * Issue an HTTP 'OPTIONS *' request + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + + /* issue an OPTIONS * request (no leading slash) */ + curl_easy_setopt(curl, CURLOPT_REQUEST_TARGET, "*"); + + /* if this operation fails, allow risking a memory leak and do quick exit + from libcurl as this exits anyway */ + curl_easy_setopt(curl, CURLOPT_QUICK_EXIT, 1L); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http-post.c b/local-test-curl-delta-01/afc-curl/docs/examples/http-post.c new file mode 100644 index 0000000000000000000000000000000000000000..901ee1e3f041b606ad53d5faa2a7e538f05f9b0e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http-post.c @@ -0,0 +1,61 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * simple HTTP POST using the easy interface + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + /* In Windows, this inits the Winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + /* First set the URL that is about to receive our POST. This URL can + just as well be an https:// URL if that is what should receive the + data. */ + curl_easy_setopt(curl, CURLOPT_URL, "http://postit.example.com/moo.cgi"); + /* Now specify the POST data */ + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl"); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http2-download.c b/local-test-curl-delta-01/afc-curl/docs/examples/http2-download.c new file mode 100644 index 0000000000000000000000000000000000000000..ff74efb8ce867eb704e1e290a787fa8a167998ed --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http2-download.c @@ -0,0 +1,230 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Multiplexed HTTP/2 downloads over a single connection + * + */ +#include +#include +#include +#include + +/* curl stuff */ +#include +#include + +#ifndef CURLPIPE_MULTIPLEX +/* This little trick makes sure that we do not enable pipelining for libcurls + old enough to not have this symbol. It is _not_ defined to zero in a recent + libcurl header. */ +#define CURLPIPE_MULTIPLEX 0 +#endif + +struct transfer { + CURL *easy; + unsigned int num; + FILE *out; +}; + +#define NUM_HANDLES 1000 + +static +void dump(const char *text, unsigned int num, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stderr, "%u %s, %lu bytes (0x%lx)\n", + num, text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stderr, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stderr, "%02x ", ptr[i + c]); + else + fputs(" ", stderr); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stderr, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stderr); /* newline */ + } +} + +static +int my_trace(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userp) +{ + const char *text; + struct transfer *t = (struct transfer *)userp; + unsigned int num = t->num; + (void)handle; /* prevent compiler warning */ + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "== %u Info: %s", num, data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, num, (unsigned char *)data, size, 1); + return 0; +} + +static void setup(struct transfer *t, int num) +{ + char filename[128]; + CURL *hnd; + + hnd = t->easy = curl_easy_init(); + + curl_msnprintf(filename, 128, "dl-%d", num); + + t->out = fopen(filename, "wb"); + if(!t->out) { + fprintf(stderr, "error: could not open file %s for writing: %s\n", + filename, strerror(errno)); + exit(1); + } + + /* write to this file */ + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, t->out); + + /* set the same URL */ + curl_easy_setopt(hnd, CURLOPT_URL, "https://localhost:8443/index.html"); + + /* please be verbose */ + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace); + curl_easy_setopt(hnd, CURLOPT_DEBUGDATA, t); + + /* enlarge the receive buffer for potentially higher transfer speeds */ + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 100000L); + + /* HTTP/2 please */ + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + +#if (CURLPIPE_MULTIPLEX > 0) + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +#endif +} + +/* + * Download many transfers over HTTP/2, using the same connection! + */ +int main(int argc, char **argv) +{ + struct transfer trans[NUM_HANDLES]; + CURLM *multi_handle; + int i; + int still_running = 0; /* keep number of running handles */ + int num_transfers; + if(argc > 1) { + /* if given a number, do that many transfers */ + num_transfers = atoi(argv[1]); + if((num_transfers < 1) || (num_transfers > NUM_HANDLES)) + num_transfers = 3; /* a suitable low default */ + } + else + num_transfers = 3; /* suitable default */ + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + for(i = 0; i < num_transfers; i++) { + setup(&trans[i], i); + + /* add the individual transfer */ + curl_multi_add_handle(multi_handle, trans[i].easy); + } + + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + } while(still_running); + + for(i = 0; i < num_transfers; i++) { + curl_multi_remove_handle(multi_handle, trans[i].easy); + curl_easy_cleanup(trans[i].easy); + } + + curl_multi_cleanup(multi_handle); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http2-pushinmemory.c b/local-test-curl-delta-01/afc-curl/docs/examples/http2-pushinmemory.c new file mode 100644 index 0000000000000000000000000000000000000000..53c368e0127b199652f5de0e310afbad99f2d28d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http2-pushinmemory.c @@ -0,0 +1,186 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP/2 server push. Receive all data in memory. + * + */ +#include +#include +#include + +/* curl stuff */ +#include + +struct Memory { + char *memory; + size_t size; +}; + +static size_t +write_cb(void *contents, size_t size, size_t nmemb, void *userp) +{ + size_t realsize = size * nmemb; + struct Memory *mem = (struct Memory *)userp; + char *ptr = realloc(mem->memory, mem->size + realsize + 1); + if(!ptr) { + /* out of memory! */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + + mem->memory = ptr; + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; +} + +#define MAX_FILES 10 +static struct Memory files[MAX_FILES]; +static int pushindex = 1; + +static void init_memory(struct Memory *chunk) +{ + chunk->memory = malloc(1); /* grown as needed with realloc */ + chunk->size = 0; /* no data at this point */ +} + +static void setup(CURL *hnd) +{ + /* set the same URL */ + curl_easy_setopt(hnd, CURLOPT_URL, "https://localhost:8443/index.html"); + + /* HTTP/2 please */ + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + /* we use a self-signed test server, skip verification during debugging */ + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); + + /* write data to a struct */ + curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, write_cb); + init_memory(&files[0]); + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &files[0]); + + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +} + +/* called when there is an incoming push */ +static int server_push_callback(CURL *parent, + CURL *easy, + size_t num_headers, + struct curl_pushheaders *headers, + void *userp) +{ + char *headp; + int *transfers = (int *)userp; + (void)parent; /* we have no use for this */ + (void)num_headers; /* unused */ + + if(pushindex == MAX_FILES) + /* cannot fit anymore */ + return CURL_PUSH_DENY; + + /* write to this buffer */ + init_memory(&files[pushindex]); + curl_easy_setopt(easy, CURLOPT_WRITEDATA, &files[pushindex]); + pushindex++; + + headp = curl_pushheader_byname(headers, ":path"); + if(headp) + fprintf(stderr, "* Pushed :path '%s'\n", headp /* skip :path + colon */); + + (*transfers)++; /* one more */ + return CURL_PUSH_OK; +} + + +/* + * Download a file over HTTP/2, take care of server push. + */ +int main(void) +{ + CURL *easy; + CURLM *multi; + int still_running; /* keep number of running handles */ + int transfers = 1; /* we start with one */ + int i; + struct CURLMsg *m; + + /* init a multi stack */ + multi = curl_multi_init(); + + easy = curl_easy_init(); + + /* set options */ + setup(easy); + + /* add the easy transfer */ + curl_multi_add_handle(multi, easy); + + curl_multi_setopt(multi, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + curl_multi_setopt(multi, CURLMOPT_PUSHFUNCTION, server_push_callback); + curl_multi_setopt(multi, CURLMOPT_PUSHDATA, &transfers); + + while(transfers) { + int rc; + CURLMcode mcode = curl_multi_perform(multi, &still_running); + if(mcode) + break; + + mcode = curl_multi_wait(multi, NULL, 0, 1000, &rc); + if(mcode) + break; + + + /* + * When doing server push, libcurl itself created and added one or more + * easy handles but *we* need to clean them up when they are done. + */ + do { + int msgq = 0; + m = curl_multi_info_read(multi, &msgq); + if(m && (m->msg == CURLMSG_DONE)) { + CURL *e = m->easy_handle; + transfers--; + curl_multi_remove_handle(multi, e); + curl_easy_cleanup(e); + } + } while(m); + + } + + + curl_multi_cleanup(multi); + + /* 'pushindex' is now the number of received transfers */ + for(i = 0; i < pushindex; i++) { + /* do something fun with the data, and then free it when done */ + free(files[i].memory); + } + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http2-upload.c b/local-test-curl-delta-01/afc-curl/docs/examples/http2-upload.c new file mode 100644 index 0000000000000000000000000000000000000000..e804fb76a97f97f2ee622e52f7429ce749e14824 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http2-upload.c @@ -0,0 +1,326 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Multiplexed HTTP/2 uploads over a single connection + * + */ +#include +#include +#include +#include +#include +#include + +/* somewhat Unix-specific */ +#ifndef _MSC_VER +#include +#include +#endif + +/* curl stuff */ +#include +#include + +#ifndef CURLPIPE_MULTIPLEX +/* This little trick makes sure that we do not enable pipelining for libcurls + old enough to not have this symbol. It is _not_ defined to zero in a recent + libcurl header. */ +#define CURLPIPE_MULTIPLEX 0 +#endif + +#define NUM_HANDLES 1000 + +#ifdef _MSC_VER +#define gettimeofday(a, b) my_gettimeofday((a), (b)) +static +int my_gettimeofday(struct timeval *tp, void *tzp) +{ + (void)tzp; + if(tp) { + /* Offset between 1601-01-01 and 1970-01-01 in 100 nanosec units */ + #define _WIN32_FT_OFFSET (116444736000000000) + union { + CURL_TYPEOF_CURL_OFF_T ns100; /* time since 1 Jan 1601 in 100ns units */ + FILETIME ft; + } _now; + GetSystemTimeAsFileTime(&_now.ft); + tp->tv_usec = (long)((_now.ns100 / 10) % 1000000); + tp->tv_sec = (long)((_now.ns100 - _WIN32_FT_OFFSET) / 10000000); + } + return 0; +} +#endif + +struct input { + FILE *in; + size_t bytes_read; /* count up */ + CURL *hnd; + int num; +}; + +static +void dump(const char *text, int num, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stderr, "%d %s, %lu bytes (0x%lx)\n", + num, text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stderr, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stderr, "%02x ", ptr[i + c]); + else + fputs(" ", stderr); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stderr, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stderr); /* newline */ + } +} + +static +int my_trace(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userp) +{ + char timebuf[60]; + const char *text; + struct input *i = (struct input *)userp; + int num = i->num; + static time_t epoch_offset; + static int known_offset; + struct timeval tv; + time_t secs; + struct tm *now; + (void)handle; /* prevent compiler warning */ + + gettimeofday(&tv, NULL); + if(!known_offset) { + epoch_offset = time(NULL) - tv.tv_sec; + known_offset = 1; + } + secs = epoch_offset + tv.tv_sec; + now = localtime(&secs); /* not thread safe but we do not care */ + curl_msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld", + now->tm_hour, now->tm_min, now->tm_sec, (long)tv.tv_usec); + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "%s [%d] Info: %s", timebuf, num, data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, num, (unsigned char *)data, size, 1); + return 0; +} + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct input *i = userp; + size_t retcode = fread(ptr, size, nmemb, i->in); + i->bytes_read += retcode; + return retcode; +} + +static void setup(struct input *i, int num, const char *upload) +{ + FILE *out; + char url[256]; + char filename[128]; + struct stat file_info; + curl_off_t uploadsize; + CURL *hnd; + + hnd = i->hnd = curl_easy_init(); + i->num = num; + curl_msnprintf(filename, 128, "dl-%d", num); + out = fopen(filename, "wb"); + if(!out) { + fprintf(stderr, "error: could not open file %s for writing: %s\n", upload, + strerror(errno)); + exit(1); + } + + curl_msnprintf(url, 256, "https://localhost:8443/upload-%d", num); + + /* get the file size of the local file */ + if(stat(upload, &file_info)) { + fprintf(stderr, "error: could not stat file %s: %s\n", upload, + strerror(errno)); + exit(1); + } + + uploadsize = file_info.st_size; + + i->in = fopen(upload, "rb"); + if(!i->in) { + fprintf(stderr, "error: could not open file %s for reading: %s\n", upload, + strerror(errno)); + exit(1); + } + + /* write to this file */ + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, out); + + /* we want to use our own read function */ + curl_easy_setopt(hnd, CURLOPT_READFUNCTION, read_callback); + /* read from this file */ + curl_easy_setopt(hnd, CURLOPT_READDATA, i); + /* provide the size of the upload */ + curl_easy_setopt(hnd, CURLOPT_INFILESIZE_LARGE, uploadsize); + + /* send in the URL to store the upload as */ + curl_easy_setopt(hnd, CURLOPT_URL, url); + + /* upload please */ + curl_easy_setopt(hnd, CURLOPT_UPLOAD, 1L); + + /* please be verbose */ + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace); + curl_easy_setopt(hnd, CURLOPT_DEBUGDATA, i); + + /* HTTP/2 please */ + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + /* we use a self-signed test server, skip verification during debugging */ + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); + +#if (CURLPIPE_MULTIPLEX > 0) + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +#endif +} + +/* + * Upload all files over HTTP/2, using the same physical connection! + */ +int main(int argc, char **argv) +{ + struct input trans[NUM_HANDLES]; + CURLM *multi_handle; + int i; + int still_running = 0; /* keep number of running handles */ + const char *filename = "index.html"; + int num_transfers; + + if(argc > 1) { + /* if given a number, do that many transfers */ + num_transfers = atoi(argv[1]); + + if(!num_transfers || (num_transfers > NUM_HANDLES)) + num_transfers = 3; /* a suitable low default */ + + if(argc > 2) + /* if given a file name, upload this! */ + filename = argv[2]; + } + else + num_transfers = 3; + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + for(i = 0; i < num_transfers; i++) { + setup(&trans[i], i, filename); + + /* add the individual transfer */ + curl_multi_add_handle(multi_handle, trans[i].hnd); + } + + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + + /* We do HTTP/2 so let's stick to one connection per host */ + curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, 1L); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + + } while(still_running); + + curl_multi_cleanup(multi_handle); + + for(i = 0; i < num_transfers; i++) { + curl_multi_remove_handle(multi_handle, trans[i].hnd); + curl_easy_cleanup(trans[i].hnd); + } + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/http3-present.c b/local-test-curl-delta-01/afc-curl/docs/examples/http3-present.c new file mode 100644 index 0000000000000000000000000000000000000000..56ba0f572474e2ae5e5077d167cec39716cd4486 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/http3-present.c @@ -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 + * + ***************************************************************************/ +/* + * Checks if HTTP/3 support is present in libcurl. + * + */ +#include +#include + +int main(void) +{ + curl_version_info_data *ver; + + curl_global_init(CURL_GLOBAL_ALL); + + ver = curl_version_info(CURLVERSION_NOW); + if(ver->features & CURL_VERSION_HTTP2) + printf("HTTP/2 support is present\n"); + + if(ver->features & CURL_VERSION_HTTP3) + printf("HTTP/3 support is present\n"); + + if(ver->features & CURL_VERSION_ALTSVC) + printf("Alt-svc support is present\n"); + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/httpcustomheader.c b/local-test-curl-delta-01/afc-curl/docs/examples/httpcustomheader.c new file mode 100644 index 0000000000000000000000000000000000000000..a3881674c1bd520e8afa4089098c19bcf9253695 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/httpcustomheader.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP request with custom modified, removed and added headers + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + struct curl_slist *chunk = NULL; + + /* Remove a header curl would otherwise add by itself */ + chunk = curl_slist_append(chunk, "Accept:"); + + /* Add a custom header */ + chunk = curl_slist_append(chunk, "Another: yes"); + + /* Modify a header curl otherwise adds differently */ + chunk = curl_slist_append(chunk, "Host: example.com"); + + /* Add a header with "blank" contents to the right of the colon. Note that + we are then using a semicolon in the string we pass to curl! */ + chunk = curl_slist_append(chunk, "X-silly-header;"); + + /* set our custom set of headers */ + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); + + curl_easy_setopt(curl, CURLOPT_URL, "localhost"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* free the custom headers */ + curl_slist_free_all(chunk); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/httpput-postfields.c b/local-test-curl-delta-01/afc-curl/docs/examples/httpput-postfields.c new file mode 100644 index 0000000000000000000000000000000000000000..c0436749fd5e5be450841ccd1d7ccfb4059fb26b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/httpput-postfields.c @@ -0,0 +1,105 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP PUT using CURLOPT_POSTFIELDS + * + */ +#include +#include +#include +#include + +static const char olivertwist[]= + "Among other public buildings in a certain town, which for many reasons " + "it will be prudent to refrain from mentioning, and to which I will assign " + "no fictitious name, there is one anciently common to most towns, great or " + "small: to wit, a workhouse; and in this workhouse was born; on a day and " + "date which I need not trouble myself to repeat, inasmuch as it can be of " + "no possible consequence to the reader, in this stage of the business at " + "all events; the item of mortality whose name is prefixed"; + +/* ... to the head of this chapter. String cut off to stick within the C90 + 509 byte limit. */ + +/* + * This example shows an HTTP PUT operation that sends a fixed buffer with + * CURLOPT_POSTFIELDS to the URL given as an argument. + */ + +int main(int argc, char **argv) +{ + CURL *curl; + CURLcode res; + char *url; + + if(argc < 2) + return 1; + + url = argv[1]; + + /* In Windows, this inits the Winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + struct curl_slist *headers = NULL; + + /* default type with postfields is application/x-www-form-urlencoded, + change it if you want */ + headers = curl_slist_append(headers, "Content-Type: literature/classic"); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + + /* pass on content in request body. When CURLOPT_POSTFIELDSIZE is not used, + curl does strlen to get the size. */ + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, olivertwist); + + /* override the POST implied by CURLOPT_POSTFIELDS + * + * Warning: CURLOPT_CUSTOMREQUEST is problematic, especially if you want + * to follow redirects. Be aware. + */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); + + /* specify target URL, and note that this URL should include a file + name, not only a directory */ + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* Now run off and do what you have been told! */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* free headers */ + curl_slist_free_all(headers); + } + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/httpput.c b/local-test-curl-delta-01/afc-curl/docs/examples/httpput.c new file mode 100644 index 0000000000000000000000000000000000000000..ebd2b7696c3325c39d71942c34bfded0fe37e178 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/httpput.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 + * + ***************************************************************************/ +/* + * HTTP PUT with easy interface and read callback + * + */ +#include +#include +#include +#include + +/* + * This example shows an HTTP PUT operation. PUTs a file given as a command + * line argument to the URL also given on the command line. + * + * This example also uses its own read callback. + * + * Here's an article on how to setup a PUT handler for Apache: + * http://www.apacheweek.com/features/put + */ + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t retcode; + unsigned long nread; + + /* in real-world cases, this would probably get this data differently + as this fread() stuff is exactly what the library already would do + by default internally */ + retcode = fread(ptr, size, nmemb, stream); + + if(retcode > 0) { + nread = (unsigned long)retcode; + fprintf(stderr, "*** We read %lu bytes from file\n", nread); + } + + return retcode; +} + +int main(int argc, char **argv) +{ + CURL *curl; + CURLcode res; + FILE * hd_src; + struct stat file_info; + + char *file; + char *url; + + if(argc < 3) + return 1; + + file = argv[1]; + url = argv[2]; + + /* get the file size of the local file */ + stat(file, &file_info); + + /* get a FILE * of the same file, could also be made with + fdopen() from the previous descriptor, but hey this is just + an example! */ + hd_src = fopen(file, "rb"); + + /* In Windows, this inits the Winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + /* we want to use our own read function */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* enable uploading (implies PUT over HTTP) */ + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target URL, and note that this URL should include a file + name, not only a directory */ + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* now specify which file to upload */ + curl_easy_setopt(curl, CURLOPT_READDATA, hd_src); + + /* provide the size of the upload, we typecast the value to curl_off_t + since we must be sure to use the correct data size */ + curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, + (curl_off_t)file_info.st_size); + + /* Now run off and do what you have been told! */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + fclose(hd_src); /* close the local file */ + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/https.c b/local-test-curl-delta-01/afc-curl/docs/examples/https.c new file mode 100644 index 0000000000000000000000000000000000000000..c1cba877df615507e6edd9807d9c5c54ce03c283 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/https.c @@ -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 + * + ***************************************************************************/ +/* + * Simple HTTPS GET + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/"); + +#ifdef SKIP_PEER_VERIFICATION + /* + * If you want to connect to a site who is not using a certificate that is + * signed by one of the certs in the CA bundle you have, you can skip the + * verification of the server's certificate. This makes the connection + * A LOT LESS SECURE. + * + * If you have a CA cert for the server stored someplace else than in the + * default bundle, then the CURLOPT_CAPATH option might come handy for + * you. + */ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); +#endif + +#ifdef SKIP_HOSTNAME_VERIFICATION + /* + * If the site you are connecting to uses a different host name that what + * they have mentioned in their server certificate's commonName (or + * subjectAltName) fields, libcurl refuses to connect. You can skip this + * check, but it makes the connection insecure. + */ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); +#endif + + /* cache the CA cert bundle in memory for a week */ + curl_easy_setopt(curl, CURLOPT_CA_CACHE_TIMEOUT, 604800L); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-append.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-append.c new file mode 100644 index 0000000000000000000000000000000000000000..1839deac1dd6c3f4dd6a0511ca468092908cd70f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-append.c @@ -0,0 +1,130 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Send email with IMAP + * + */ + +#include +#include +#include + +/* This is a simple example showing how to send mail using libcurl's IMAP + * capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +#define FROM "" +#define TO "" +#define CC "" + +static const char *payload_text = + "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n" + "To: " TO "\r\n" + "From: " FROM "(Example User)\r\n" + "Cc: " CC "(Another example User)\r\n" + "Message-ID: " + "\r\n" + "Subject: IMAP example message\r\n" + "\r\n" /* empty line to divide headers from body, see RFC 5322 */ + "The body of the message starts here.\r\n" + "\r\n" + "It could be a lot of lines, could be MIME encoded, whatever.\r\n" + "Check RFC 5322.\r\n"; + +struct upload_status { + size_t bytes_read; +}; + +static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + size_t room = size * nmemb; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = &payload_text[upload_ctx->bytes_read]; + + if(*data) { + size_t len = strlen(data); + if(room < len) + len = room; + memcpy(ptr, data, len); + upload_ctx->bytes_read += len; + + return len; + } + + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + size_t filesize; + long infilesize = LONG_MAX; + struct upload_status upload_ctx = { 0 }; + + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This creates a new message in folder "Sent". */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/Sent"); + + /* In this case, we are using a callback function to specify the data. You + * could just use the CURLOPT_READDATA option to specify a FILE pointer to + * read from. */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); + curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + filesize = strlen(payload_text); + if(filesize <= LONG_MAX) + infilesize = (long)filesize; + curl_easy_setopt(curl, CURLOPT_INFILESIZE, infilesize); + + /* Perform the append */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-authzid.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-authzid.c new file mode 100644 index 0000000000000000000000000000000000000000..eb615c6f3d5cdaebd453f8ece1e3e88c34fde8b9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-authzid.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 + * + ***************************************************************************/ + +/* + * Retrieve emails from a shared IMAP mailbox + * + */ + +#include +#include + +/* This is a simple example showing how to fetch mail using libcurl's IMAP + * capabilities. + * + * Note that this example requires libcurl 7.66.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set the username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* Set the authorization identity (identity to act as) */ + curl_easy_setopt(curl, CURLOPT_SASL_AUTHZID, "shared-mailbox"); + + /* Force PLAIN authentication */ + curl_easy_setopt(curl, CURLOPT_LOGIN_OPTIONS, "AUTH=PLAIN"); + + /* This fetches message 1 from the user's inbox */ + curl_easy_setopt(curl, CURLOPT_URL, + "imap://imap.example.com/INBOX/;UID=1"); + + /* Perform the fetch */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-copy.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-copy.c new file mode 100644 index 0000000000000000000000000000000000000000..a221be0ca8de2869ac0d93df17079dd227a39c81 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-copy.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 + * + ***************************************************************************/ + +/* + * Copy an email from one IMAP folder to another + * + */ + +#include +#include + +/* This is a simple example showing how to copy a mail from one mailbox folder + * to another using libcurl's IMAP capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is source mailbox folder to select */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/INBOX"); + + /* Set the COPY command specifying the message ID and destination folder */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "COPY 1 FOLDER"); + + /* Note that to perform a move operation you need to perform the copy, + * then mark the original mail as Deleted and EXPUNGE or CLOSE. Please see + * imap-store.c for more information on deleting messages. */ + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-create.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-create.c new file mode 100644 index 0000000000000000000000000000000000000000..6a9b565345a9c38a02f1633a267accabd46a25b5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-create.c @@ -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 + * + ***************************************************************************/ + +/* + * Create a new IMAP folder + * + */ + +#include +#include + +/* This is a simple example showing how to create a new mailbox folder using + * libcurl's IMAP capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com"); + + /* Set the CREATE command specifying the new folder name */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "CREATE FOLDER"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-delete.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-delete.c new file mode 100644 index 0000000000000000000000000000000000000000..e43ab2e9824fdcfe4f5fac0f005aec7393896072 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-delete.c @@ -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 + * + ***************************************************************************/ + +/* + * Delete an IMAP folder + * + */ + +#include +#include + +/* This is a simple example showing how to delete an existing mailbox folder + * using libcurl's IMAP capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com"); + + /* Set the DELETE command specifying the existing folder */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE FOLDER"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-fetch.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-fetch.c new file mode 100644 index 0000000000000000000000000000000000000000..416fe88096846e7eda3b06935d799c20e65b4333 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-fetch.c @@ -0,0 +1,67 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Retrieve IMAP emails + * + */ + +#include +#include + +/* This is a simple example showing how to fetch mail using libcurl's IMAP + * capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This fetches message 1 from the user's inbox */ + curl_easy_setopt(curl, CURLOPT_URL, + "imap://imap.example.com/INBOX/;UID=1"); + + /* Perform the fetch */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-list.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-list.c new file mode 100644 index 0000000000000000000000000000000000000000..0253b543e6facd98d7e5c8ef80b6c04128374cb1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-list.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 + * + ***************************************************************************/ + +/* + * List the folders within an IMAP mailbox + * + */ + +#include +#include + +/* This is a simple example showing how to list the folders within an IMAP + * mailbox. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This lists the folders within the user's mailbox. If you want to list + * the folders within a specific folder, for example the inbox, then + * specify the folder as a path in the URL such as /INBOX */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com"); + + /* Perform the list */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-multi.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-multi.c new file mode 100644 index 0000000000000000000000000000000000000000..42fa7381cd2131edecfa162f303fcb73720cf4f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-multi.c @@ -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 + * + ***************************************************************************/ + +/* + * Get IMAP email with the multi interface + * + */ + +#include +#include +#include + +/* This is a simple example showing how to fetch mail using libcurl's IMAP + * capabilities. It builds on the imap-fetch.c example to demonstrate how to + * use libcurl's multi interface. + */ + +int main(void) +{ + CURL *curl; + CURLM *mcurl; + int still_running = 1; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(!curl) + return 1; + + mcurl = curl_multi_init(); + if(!mcurl) + return 2; + + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This fetches message 1 from the user's inbox */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/INBOX/;UID=1"); + + /* Tell the multi stack about our easy handle */ + curl_multi_add_handle(mcurl, curl); + + do { + CURLMcode mc = curl_multi_perform(mcurl, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(mcurl, NULL, 0, 1000, NULL); + + if(mc) + break; + } while(still_running); + + /* Always cleanup */ + curl_multi_remove_handle(mcurl, curl); + curl_multi_cleanup(mcurl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-noop.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-noop.c new file mode 100644 index 0000000000000000000000000000000000000000..9e5a3da2d5278a59f7cba47aa78eaff154c77765 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-noop.c @@ -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 + * + ***************************************************************************/ + +/* + * Perform an IMAP noop + * + */ + +#include +#include + +/* This is a simple example showing how to perform a noop using libcurl's IMAP + * capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com"); + + /* Set the NOOP command */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "NOOP"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-search.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-search.c new file mode 100644 index 0000000000000000000000000000000000000000..141b06f649db51cadd703d9afbb1461d3d3ba5c7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-search.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 + * + ***************************************************************************/ + +/* + * Search for new IMAP emails + * + */ + +#include +#include + +/* This is a simple example showing how to search for new messages using + * libcurl's IMAP capabilities. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is mailbox folder to select */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/INBOX"); + + /* Set the SEARCH command specifying what we want to search for. Note that + * this can contain a message sequence set and a number of search criteria + * keywords including flags such as ANSWERED, DELETED, DRAFT, FLAGGED, NEW, + * RECENT and SEEN. For more information about the search criteria please + * see RFC-3501 section 6.4.4. */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "SEARCH NEW"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/imap-store.c b/local-test-curl-delta-01/afc-curl/docs/examples/imap-store.c new file mode 100644 index 0000000000000000000000000000000000000000..d04a6072cc4e88e522ddda7f0766c78424a60bda --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/imap-store.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 + * + ***************************************************************************/ + +/* + * Modify the properties of an email over IMAP + * + */ + +#include +#include + +/* This is a simple example showing how to modify an existing mail using + * libcurl's IMAP capabilities with the STORE command. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is the mailbox folder to select */ + curl_easy_setopt(curl, CURLOPT_URL, "imap://imap.example.com/INBOX"); + + /* Set the STORE command with the Deleted flag for message 1. Note that + * you can use the STORE command to set other flags such as Seen, Answered, + * Flagged, Draft and Recent. */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "STORE 1 +Flags \\Deleted"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + else { + /* Set the EXPUNGE command, although you can use the CLOSE command if you + * do not want to know the result of the STORE */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "EXPUNGE"); + + /* Perform the second custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + } + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/ipv6.c b/local-test-curl-delta-01/afc-curl/docs/examples/ipv6.c new file mode 100644 index 0000000000000000000000000000000000000000..1b698705d0ccf29fab1780a5c7ffd5c06de82d01 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/ipv6.c @@ -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 + * + ***************************************************************************/ +/* + * HTTPS GET using IPv6 only + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); + + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + res = curl_easy_perform(curl); + + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/keepalive.c b/local-test-curl-delta-01/afc-curl/docs/examples/keepalive.c new file mode 100644 index 0000000000000000000000000000000000000000..e06d7ff37b7bba8897bab783feb758b8ac274afd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/keepalive.c @@ -0,0 +1,58 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 the TCP keep-alive options + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* enable TCP keep-alive for this transfer */ + curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); + + /* keep-alive idle time to 120 seconds */ + curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 120L); + + /* interval time between keep-alive probes: 60 seconds */ + curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 60L); + + /* maximum number of keep-alive probes: 3 */ + curl_easy_setopt(curl, CURLOPT_TCP_KEEPCNT, 3L); + + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + res = curl_easy_perform(curl); + + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/localport.c b/local-test-curl-delta-01/afc-curl/docs/examples/localport.c new file mode 100644 index 0000000000000000000000000000000000000000..7e88ce48a7c44bdd449642a28a7fefd2ab8f0e88 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/localport.c @@ -0,0 +1,53 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 CURLOPT_LOCALPORT to control local port number + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Try to use a local port number between 20000-20009 */ + curl_easy_setopt(curl, CURLOPT_LOCALPORT, 20000L); + /* 10 means number of attempts, which starts with the number set in + CURLOPT_LOCALPORT. The lower value set, the smaller the chance it + works. */ + curl_easy_setopt(curl, CURLOPT_LOCALPORTRANGE, 10L); + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/maxconnects.c b/local-test-curl-delta-01/afc-curl/docs/examples/maxconnects.c new file mode 100644 index 0000000000000000000000000000000000000000..2e8e5b50a82cde54e507aece441785c453d3a8ed --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/maxconnects.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) James Fuller, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 maximum number of persistent connections to 1. + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + const char *urls[] = { "https://example.com", + "https://curl.se", + "https://www.example/", + NULL /* end of list */ + }; + int i = 0; + + /* Change the maximum number of persistent connection */ + curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 1L); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* loop over the URLs */ + while(urls[i]) { + curl_easy_setopt(curl, CURLOPT_URL, urls[i]); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + i++; + } + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-app.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-app.c new file mode 100644 index 0000000000000000000000000000000000000000..bb0f73db7b827dec02d62963d97acf1359f83e89 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-app.c @@ -0,0 +1,115 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 basic application source code using the multi interface doing two + * transfers in parallel. + * + */ + +#include +#include + +/* curl stuff */ +#include + +/* + * Download an HTTP file and upload an FTP file simultaneously. + */ + +#define HANDLECOUNT 2 /* Number of simultaneous transfers */ +#define HTTP_HANDLE 0 /* Index for the HTTP transfer */ +#define FTP_HANDLE 1 /* Index for the FTP transfer */ + +int main(void) +{ + CURL *handles[HANDLECOUNT]; + CURLM *multi_handle; + + int still_running = 1; /* keep number of running handles */ + int i; + + CURLMsg *msg; /* for picking up messages with the transfer status */ + int msgs_left; /* how many messages are left */ + + /* Allocate one CURL handle per transfer */ + for(i = 0; i < HANDLECOUNT; i++) + handles[i] = curl_easy_init(); + + /* set the options (I left out a few, you get the point anyway) */ + curl_easy_setopt(handles[HTTP_HANDLE], CURLOPT_URL, "https://example.com"); + + curl_easy_setopt(handles[FTP_HANDLE], CURLOPT_URL, "ftp://example.com"); + curl_easy_setopt(handles[FTP_HANDLE], CURLOPT_UPLOAD, 1L); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfers */ + for(i = 0; i < HANDLECOUNT; i++) + curl_multi_add_handle(multi_handle, handles[i]); + + while(still_running) { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + } + /* See how the transfers went */ + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(multi_handle, &msgs_left)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + int idx; + + /* Find out which handle this message is about */ + for(idx = 0; idx < HANDLECOUNT; idx++) { + int found = (msg->easy_handle == handles[idx]); + if(found) + break; + } + + switch(idx) { + case HTTP_HANDLE: + printf("HTTP transfer completed with status %d\n", msg->data.result); + break; + case FTP_HANDLE: + printf("FTP transfer completed with status %d\n", msg->data.result); + break; + } + } + } + + /* remove the transfers and cleanup the handles */ + for(i = 0; i < HANDLECOUNT; i++) { + curl_multi_remove_handle(multi_handle, handles[i]); + curl_easy_cleanup(handles[i]); + } + + curl_multi_cleanup(multi_handle); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-debugcallback.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-debugcallback.c new file mode 100644 index 0000000000000000000000000000000000000000..79123ca224367b5a4b8885d7d50ea6471ec0f6d8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-debugcallback.c @@ -0,0 +1,161 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * multi interface and debug callback + * + */ + +#include +#include + +/* curl stuff */ +#include + +#define TRUE 1 + +static void dump(const char *text, FILE *stream, unsigned char *ptr, + size_t size, char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stream, "%s, %10.10lu bytes (0x%8.8lx)\n", + text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stream, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stream, "%02x ", ptr[i + c]); + else + fputs(" ", stream); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stream, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stream); /* newline */ + } + fflush(stream); +} + +static +int my_trace(CURL *handle, curl_infotype type, + unsigned char *data, size_t size, + void *userp) +{ + const char *text; + + (void)userp; + (void)handle; /* prevent compiler warning */ + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "== Info: %s", data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, stderr, data, size, TRUE); + return 0; +} + +/* + * Simply download an HTTP file. + */ +int main(void) +{ + CURL *http_handle; + CURLM *multi_handle; + + int still_running = 0; /* keep number of running handles */ + + http_handle = curl_easy_init(); + + /* set the options (I left out a few, you get the point anyway) */ + curl_easy_setopt(http_handle, CURLOPT_URL, "https://www.example.com/"); + + curl_easy_setopt(http_handle, CURLOPT_DEBUGFUNCTION, my_trace); + curl_easy_setopt(http_handle, CURLOPT_VERBOSE, 1L); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfers */ + curl_multi_add_handle(multi_handle, http_handle); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + + } while(still_running); + + curl_multi_cleanup(multi_handle); + + curl_easy_cleanup(http_handle); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-double.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-double.c new file mode 100644 index 0000000000000000000000000000000000000000..99bd736a9ce3ccc7271d7ed658d1a91ee9cfa49b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-double.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * multi interface code doing two parallel HTTP transfers + * + */ +#include +#include + +/* curl stuff */ +#include + +/* + * Simply download two HTTP files! + */ +int main(void) +{ + CURL *http_handle; + CURL *http_handle2; + CURLM *multi_handle; + + int still_running = 1; /* keep number of running handles */ + + http_handle = curl_easy_init(); + http_handle2 = curl_easy_init(); + + /* set options */ + curl_easy_setopt(http_handle, CURLOPT_URL, "https://www.example.com/"); + + /* set options */ + curl_easy_setopt(http_handle2, CURLOPT_URL, "http://localhost/"); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfers */ + curl_multi_add_handle(multi_handle, http_handle); + curl_multi_add_handle(multi_handle, http_handle2); + + while(still_running) { + CURLMsg *msg; + int queued; + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + + do { + msg = curl_multi_info_read(multi_handle, &queued); + if(msg) { + if(msg->msg == CURLMSG_DONE) { + /* a transfer ended */ + fprintf(stderr, "Transfer completed\n"); + } + } + } while(msg); + } + + curl_multi_remove_handle(multi_handle, http_handle); + curl_multi_remove_handle(multi_handle, http_handle2); + + curl_multi_cleanup(multi_handle); + + curl_easy_cleanup(http_handle); + curl_easy_cleanup(http_handle2); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-event.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-event.c new file mode 100644 index 0000000000000000000000000000000000000000..44e9203e5d0e32ed9ef1d74f4c60e7dbbd3f94cc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-event.c @@ -0,0 +1,241 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * multi_socket API using libevent + * + */ + +#include +#include +#include +#include + +struct event_base *base; +CURLM *curl_handle; +struct event *timeout; + +typedef struct curl_context_s { + struct event *event; + curl_socket_t sockfd; +} curl_context_t; + +static void curl_perform(int fd, short event, void *arg); + +static curl_context_t *create_curl_context(curl_socket_t sockfd) +{ + curl_context_t *context; + + context = (curl_context_t *) malloc(sizeof(*context)); + + context->sockfd = sockfd; + + context->event = event_new(base, sockfd, 0, curl_perform, context); + + return context; +} + +static void destroy_curl_context(curl_context_t *context) +{ + event_del(context->event); + event_free(context->event); + free(context); +} + +static void add_download(const char *url, int num) +{ + char filename[50]; + FILE *file; + CURL *handle; + + snprintf(filename, 50, "%d.download", num); + + file = fopen(filename, "wb"); + if(!file) { + fprintf(stderr, "Error opening %s\n", filename); + return; + } + + handle = curl_easy_init(); + curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); + curl_easy_setopt(handle, CURLOPT_PRIVATE, file); + curl_easy_setopt(handle, CURLOPT_URL, url); + curl_multi_add_handle(curl_handle, handle); + fprintf(stderr, "Added download %s -> %s\n", url, filename); +} + +static void check_multi_info(void) +{ + char *done_url; + CURLMsg *message; + int pending; + CURL *easy_handle; + FILE *file; + + while((message = curl_multi_info_read(curl_handle, &pending))) { + switch(message->msg) { + case CURLMSG_DONE: + /* Do not use message data after calling curl_multi_remove_handle() and + curl_easy_cleanup(). As per curl_multi_info_read() docs: + "WARNING: The data the returned pointer points to does not survive + calling curl_multi_cleanup, curl_multi_remove_handle or + curl_easy_cleanup." */ + easy_handle = message->easy_handle; + + curl_easy_getinfo(easy_handle, CURLINFO_EFFECTIVE_URL, &done_url); + curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &file); + printf("%s DONE\n", done_url); + + curl_multi_remove_handle(curl_handle, easy_handle); + curl_easy_cleanup(easy_handle); + if(file) { + fclose(file); + } + break; + + default: + fprintf(stderr, "CURLMSG default\n"); + break; + } + } +} + +static void curl_perform(int fd, short event, void *arg) +{ + int running_handles; + int flags = 0; + curl_context_t *context; + + if(event & EV_READ) + flags |= CURL_CSELECT_IN; + if(event & EV_WRITE) + flags |= CURL_CSELECT_OUT; + + context = (curl_context_t *) arg; + + curl_multi_socket_action(curl_handle, context->sockfd, flags, + &running_handles); + + check_multi_info(); +} + +static void on_timeout(evutil_socket_t fd, short events, void *arg) +{ + int running_handles; + curl_multi_socket_action(curl_handle, CURL_SOCKET_TIMEOUT, 0, + &running_handles); + check_multi_info(); +} + +static int start_timeout(CURLM *multi, long timeout_ms, void *userp) +{ + if(timeout_ms < 0) { + evtimer_del(timeout); + } + else { + if(timeout_ms == 0) + timeout_ms = 1; /* 0 means call socket_action asap */ + struct timeval tv; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + evtimer_del(timeout); + evtimer_add(timeout, &tv); + } + return 0; +} + +static int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, + void *socketp) +{ + curl_context_t *curl_context; + int events = 0; + + switch(action) { + case CURL_POLL_IN: + case CURL_POLL_OUT: + case CURL_POLL_INOUT: + curl_context = socketp ? + (curl_context_t *) socketp : create_curl_context(s); + + curl_multi_assign(curl_handle, s, (void *) curl_context); + + if(action != CURL_POLL_IN) + events |= EV_WRITE; + if(action != CURL_POLL_OUT) + events |= EV_READ; + + events |= EV_PERSIST; + + event_del(curl_context->event); + event_assign(curl_context->event, base, curl_context->sockfd, events, + curl_perform, curl_context); + event_add(curl_context->event, NULL); + + break; + case CURL_POLL_REMOVE: + if(socketp) { + event_del(((curl_context_t*) socketp)->event); + destroy_curl_context((curl_context_t*) socketp); + curl_multi_assign(curl_handle, s, NULL); + } + break; + default: + abort(); + } + + return 0; +} + +int main(int argc, char **argv) +{ + if(argc <= 1) + return 0; + + if(curl_global_init(CURL_GLOBAL_ALL)) { + fprintf(stderr, "Could not init curl\n"); + return 1; + } + + base = event_base_new(); + timeout = evtimer_new(base, on_timeout, NULL); + + curl_handle = curl_multi_init(); + curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket); + curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout); + + while(argc-- > 1) { + add_download(argv[argc], argc); + } + + event_base_dispatch(base); + + curl_multi_cleanup(curl_handle); + event_free(timeout); + event_base_free(base); + + libevent_global_shutdown(); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-formadd.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-formadd.c new file mode 100644 index 0000000000000000000000000000000000000000..58c7e641c4a1a3b4e46a9c6d38e4edad3cf1293e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-formadd.c @@ -0,0 +1,120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * using the multi interface to do a multipart formpost without blocking + * + */ + +/* + * Warning: this example uses the deprecated form api. See "multi-post.c" + * for a similar example using the mime api. + */ + +#include +#include + +#include + +int main(void) +{ + CURL *curl; + + CURLM *multi_handle; + int still_running = 0; + + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + struct curl_slist *headerlist = NULL; + static const char buf[] = "Expect:"; + + CURL_IGNORE_DEPRECATION( + /* Fill in the file upload field. This makes libcurl load data from + the given file name when curl_easy_perform() is called. */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "sendfile", + CURLFORM_FILE, "multi-formadd.c", + CURLFORM_END); + + /* Fill in the filename field */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "filename", + CURLFORM_COPYCONTENTS, "multi-formadd.c", + CURLFORM_END); + + /* Fill in the submit field too, even if this is rarely needed */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "submit", + CURLFORM_COPYCONTENTS, "send", + CURLFORM_END); + ) + + curl = curl_easy_init(); + multi_handle = curl_multi_init(); + + /* initialize custom header list (stating that Expect: 100-continue is not + wanted */ + headerlist = curl_slist_append(headerlist, buf); + if(curl && multi_handle) { + + /* what URL that receives this POST */ + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/upload.cgi"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); + CURL_IGNORE_DEPRECATION( + curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); + ) + + curl_multi_add_handle(multi_handle, curl); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + + } while(still_running); + + curl_multi_cleanup(multi_handle); + + /* always cleanup */ + curl_easy_cleanup(curl); + + CURL_IGNORE_DEPRECATION( + /* then cleanup the formpost chain */ + curl_formfree(formpost); + ) + + /* free slist */ + curl_slist_free_all(headerlist); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-legacy.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-legacy.c new file mode 100644 index 0000000000000000000000000000000000000000..3e7714f40c55b0e0cf5ecfcab381adccd7245a56 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-legacy.c @@ -0,0 +1,182 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 basic application source code using the multi interface doing two + * transfers in parallel without curl_multi_wait/poll. + * + */ + +#include +#include + +/* somewhat Unix-specific */ +#ifndef _WIN32 +#include +#include +#endif + +/* curl stuff */ +#include + +/* + * Download an HTTP file and upload an FTP file simultaneously. + */ + +#define HANDLECOUNT 2 /* Number of simultaneous transfers */ +#define HTTP_HANDLE 0 /* Index for the HTTP transfer */ +#define FTP_HANDLE 1 /* Index for the FTP transfer */ + +int main(void) +{ + CURL *handles[HANDLECOUNT]; + CURLM *multi_handle; + + int still_running = 0; /* keep number of running handles */ + int i; + + CURLMsg *msg; /* for picking up messages with the transfer status */ + int msgs_left; /* how many messages are left */ + + /* Allocate one CURL handle per transfer */ + for(i = 0; i < HANDLECOUNT; i++) + handles[i] = curl_easy_init(); + + /* set the options (I left out a few, you get the point anyway) */ + curl_easy_setopt(handles[HTTP_HANDLE], CURLOPT_URL, "https://example.com"); + + curl_easy_setopt(handles[FTP_HANDLE], CURLOPT_URL, "ftp://example.com"); + curl_easy_setopt(handles[FTP_HANDLE], CURLOPT_UPLOAD, 1L); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfers */ + for(i = 0; i < HANDLECOUNT; i++) + curl_multi_add_handle(multi_handle, handles[i]); + + /* we start some action by calling perform right away */ + curl_multi_perform(multi_handle, &still_running); + + while(still_running) { + struct timeval timeout; + int rc; /* select() return code */ + CURLMcode mc; /* curl_multi_fdset() return code */ + + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -1; + + long curl_timeo = -1; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + /* set a suitable timeout to play around with */ + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + curl_multi_timeout(multi_handle, &curl_timeo); + if(curl_timeo >= 0) { + timeout.tv_sec = curl_timeo / 1000; + if(timeout.tv_sec > 1) + timeout.tv_sec = 1; + else + timeout.tv_usec = (int)(curl_timeo % 1000) * 1000; + } + + /* get file descriptors from the transfers */ + mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc); + break; + } + + /* On success the value of maxfd is guaranteed to be >= -1. We call + select(maxfd + 1, ...); specially in case of (maxfd == -1) there are + no fds ready yet so we call select(0, ...) --or Sleep() on Windows-- + to sleep 100ms, which is the minimum suggested value in the + curl_multi_fdset() doc. */ + + if(maxfd == -1) { +#ifdef _WIN32 + Sleep(100); + rc = 0; +#else + /* Portable sleep for platforms other than Windows. */ + struct timeval wait = { 0, 100 * 1000 }; /* 100ms */ + rc = select(0, NULL, NULL, NULL, &wait); +#endif + } + else { + /* Note that on some platforms 'timeout' may be modified by select(). + If you need access to the original value save a copy beforehand. */ + rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + } + + switch(rc) { + case -1: + /* select error */ + break; + case 0: /* timeout */ + default: /* action */ + curl_multi_perform(multi_handle, &still_running); + break; + } + } + + /* See how the transfers went */ + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(multi_handle, &msgs_left)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + int idx; + + /* Find out which handle this message is about */ + for(idx = 0; idx < HANDLECOUNT; idx++) { + int found = (msg->easy_handle == handles[idx]); + if(found) + break; + } + + switch(idx) { + case HTTP_HANDLE: + printf("HTTP transfer completed with status %d\n", msg->data.result); + break; + case FTP_HANDLE: + printf("FTP transfer completed with status %d\n", msg->data.result); + break; + } + } + } + + curl_multi_cleanup(multi_handle); + + /* Free the CURL handles */ + for(i = 0; i < HANDLECOUNT; i++) + curl_easy_cleanup(handles[i]); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-post.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-post.c new file mode 100644 index 0000000000000000000000000000000000000000..84af48f4bfb55540ead417180fef818f3551970c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-post.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 + * + ***************************************************************************/ +/* + * using the multi interface to do a multipart formpost without blocking + * + */ + +#include +#include + +#include + +int main(void) +{ + CURL *curl; + + CURLM *multi_handle; + int still_running = 0; + + curl_mime *form = NULL; + curl_mimepart *field = NULL; + struct curl_slist *headerlist = NULL; + static const char buf[] = "Expect:"; + + curl = curl_easy_init(); + multi_handle = curl_multi_init(); + + if(curl && multi_handle) { + /* Create the form */ + form = curl_mime_init(curl); + + /* Fill in the file upload field */ + field = curl_mime_addpart(form); + curl_mime_name(field, "sendfile"); + curl_mime_filedata(field, "multi-post.c"); + + /* Fill in the filename field */ + field = curl_mime_addpart(form); + curl_mime_name(field, "filename"); + curl_mime_data(field, "multi-post.c", CURL_ZERO_TERMINATED); + + /* Fill in the submit field too, even if this is rarely needed */ + field = curl_mime_addpart(form); + curl_mime_name(field, "submit"); + curl_mime_data(field, "send", CURL_ZERO_TERMINATED); + + /* initialize custom header list (stating that Expect: 100-continue is not + wanted */ + headerlist = curl_slist_append(headerlist, buf); + + /* what URL that receives this POST */ + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/upload.cgi"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); + curl_easy_setopt(curl, CURLOPT_MIMEPOST, form); + + curl_multi_add_handle(multi_handle, curl); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + } while(still_running); + + curl_multi_cleanup(multi_handle); + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* then cleanup the form */ + curl_mime_free(form); + + /* free slist */ + curl_slist_free_all(headerlist); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-single.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-single.c new file mode 100644 index 0000000000000000000000000000000000000000..0ead96f4871fdbd1c0fe44fdc963ffb2310831dd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-single.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 + * + ***************************************************************************/ +/* + * using the multi interface to do a single download + * + */ + +#include +#include + +/* curl stuff */ +#include + +/* + * Simply download an HTTP file. + */ +int main(void) +{ + CURL *http_handle; + CURLM *multi_handle; + int still_running = 1; /* keep number of running handles */ + + curl_global_init(CURL_GLOBAL_DEFAULT); + + http_handle = curl_easy_init(); + + /* set the options (I left out a few, you get the point anyway) */ + curl_easy_setopt(http_handle, CURLOPT_URL, "https://www.example.com/"); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfers */ + curl_multi_add_handle(multi_handle, http_handle); + + do { + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(!mc) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) { + fprintf(stderr, "curl_multi_poll() failed, code %d.\n", (int)mc); + break; + } + + } while(still_running); + + curl_multi_remove_handle(multi_handle, http_handle); + + curl_easy_cleanup(http_handle); + + curl_multi_cleanup(multi_handle); + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multi-uv.c b/local-test-curl-delta-01/afc-curl/docs/examples/multi-uv.c new file mode 100644 index 0000000000000000000000000000000000000000..27a0731943e55a08d6c54e575f2185f5a6b16457 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multi-uv.c @@ -0,0 +1,254 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * multi_socket API using libuv + * + */ +/* Use the socket_action interface to download multiple files in parallel, + powered by libuv. + + Requires libuv and (of course) libcurl. + + See https://docs.libuv.org/en/v1.x/index.html libuv API documentation +*/ + +#include +#include +#include +#include + +/* object to pass to the callbacks */ +struct datauv { + uv_timer_t timeout; + uv_loop_t *loop; + CURLM *multi; +}; + +typedef struct curl_context_s { + uv_poll_t poll_handle; + curl_socket_t sockfd; + struct datauv *uv; +} curl_context_t; + +static curl_context_t *create_curl_context(curl_socket_t sockfd, + struct datauv *uv) +{ + curl_context_t *context; + + context = (curl_context_t *) malloc(sizeof(*context)); + + context->sockfd = sockfd; + context->uv = uv; + + uv_poll_init_socket(uv->loop, &context->poll_handle, sockfd); + context->poll_handle.data = context; + + return context; +} + +static void curl_close_cb(uv_handle_t *handle) +{ + curl_context_t *context = (curl_context_t *) handle->data; + free(context); +} + +static void destroy_curl_context(curl_context_t *context) +{ + uv_close((uv_handle_t *) &context->poll_handle, curl_close_cb); +} + +static void add_download(const char *url, int num, CURLM *multi) +{ + char filename[50]; + FILE *file; + CURL *handle; + + snprintf(filename, 50, "%d.download", num); + + file = fopen(filename, "wb"); + if(!file) { + fprintf(stderr, "Error opening %s\n", filename); + return; + } + + handle = curl_easy_init(); + curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); + curl_easy_setopt(handle, CURLOPT_PRIVATE, file); + curl_easy_setopt(handle, CURLOPT_URL, url); + curl_multi_add_handle(multi, handle); + fprintf(stderr, "Added download %s -> %s\n", url, filename); +} + +static void check_multi_info(curl_context_t *context) +{ + char *done_url; + CURLMsg *message; + int pending; + CURL *easy_handle; + FILE *file; + + while((message = curl_multi_info_read(context->uv->multi, &pending))) { + switch(message->msg) { + case CURLMSG_DONE: + /* Do not use message data after calling curl_multi_remove_handle() and + curl_easy_cleanup(). As per curl_multi_info_read() docs: + "WARNING: The data the returned pointer points to does not survive + calling curl_multi_cleanup, curl_multi_remove_handle or + curl_easy_cleanup." */ + easy_handle = message->easy_handle; + + curl_easy_getinfo(easy_handle, CURLINFO_EFFECTIVE_URL, &done_url); + curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &file); + printf("%s DONE\n", done_url); + + curl_multi_remove_handle(context->uv->multi, easy_handle); + curl_easy_cleanup(easy_handle); + if(file) { + fclose(file); + } + break; + + default: + fprintf(stderr, "CURLMSG default\n"); + break; + } + } +} + +/* callback from libuv on socket activity */ +static void on_uv_socket(uv_poll_t *req, int status, int events) +{ + int running_handles; + int flags = 0; + curl_context_t *context = (curl_context_t *) req->data; + (void)status; + if(events & UV_READABLE) + flags |= CURL_CSELECT_IN; + if(events & UV_WRITABLE) + flags |= CURL_CSELECT_OUT; + + curl_multi_socket_action(context->uv->multi, context->sockfd, flags, + &running_handles); + check_multi_info(context); +} + +/* callback from libuv when timeout expires */ +static void on_uv_timeout(uv_timer_t *req) +{ + curl_context_t *context = (curl_context_t *) req->data; + if(context) { + int running_handles; + curl_multi_socket_action(context->uv->multi, CURL_SOCKET_TIMEOUT, 0, + &running_handles); + check_multi_info(context); + } +} + +/* callback from libcurl to update the timeout expiry */ +static int cb_timeout(CURLM *multi, long timeout_ms, + struct datauv *uv) +{ + (void)multi; + if(timeout_ms < 0) + uv_timer_stop(&uv->timeout); + else { + if(timeout_ms == 0) + timeout_ms = 1; /* 0 means call curl_multi_socket_action asap but NOT + within the callback itself */ + uv_timer_start(&uv->timeout, on_uv_timeout, timeout_ms, + 0); /* do not repeat */ + } + return 0; +} + +/* callback from libcurl to update socket activity to wait for */ +static int cb_socket(CURL *easy, curl_socket_t s, int action, + struct datauv *uv, + void *socketp) +{ + curl_context_t *curl_context; + int events = 0; + (void)easy; + + switch(action) { + case CURL_POLL_IN: + case CURL_POLL_OUT: + case CURL_POLL_INOUT: + curl_context = socketp ? + (curl_context_t *) socketp : create_curl_context(s, uv); + + curl_multi_assign(uv->multi, s, (void *) curl_context); + + if(action != CURL_POLL_IN) + events |= UV_WRITABLE; + if(action != CURL_POLL_OUT) + events |= UV_READABLE; + + uv_poll_start(&curl_context->poll_handle, events, on_uv_socket); + break; + case CURL_POLL_REMOVE: + if(socketp) { + uv_poll_stop(&((curl_context_t*)socketp)->poll_handle); + destroy_curl_context((curl_context_t*) socketp); + curl_multi_assign(uv->multi, s, NULL); + } + break; + default: + abort(); + } + + return 0; +} + +int main(int argc, char **argv) +{ + struct datauv uv = { 0 }; + int running_handles; + + if(argc <= 1) + return 0; + + curl_global_init(CURL_GLOBAL_ALL); + + uv.loop = uv_default_loop(); + uv_timer_init(uv.loop, &uv.timeout); + + uv.multi = curl_multi_init(); + curl_multi_setopt(uv.multi, CURLMOPT_SOCKETFUNCTION, cb_socket); + curl_multi_setopt(uv.multi, CURLMOPT_SOCKETDATA, &uv); + curl_multi_setopt(uv.multi, CURLMOPT_TIMERFUNCTION, cb_timeout); + curl_multi_setopt(uv.multi, CURLMOPT_TIMERDATA, &uv); + + while(argc-- > 1) { + add_download(argv[argc], argc, uv.multi); + } + + /* kickstart the thing */ + curl_multi_socket_action(uv.multi, CURL_SOCKET_TIMEOUT, 0, &running_handles); + uv_run(uv.loop, UV_RUN_DEFAULT); + curl_multi_cleanup(uv.multi); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/multithread.c b/local-test-curl-delta-01/afc-curl/docs/examples/multithread.c new file mode 100644 index 0000000000000000000000000000000000000000..299edd57a719fb2d215b41dc3c88141f3b9fa5ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/multithread.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 + * + ***************************************************************************/ +/* + * A multi-threaded program using pthreads to fetch several files at once + * + */ + +#include +#include +#include + +#define NUMT 4 + +/* + List of URLs to fetch. + + If you intend to use a SSL-based protocol here you might need to setup TLS + library mutex callbacks as described here: + + https://curl.se/libcurl/c/threadsafe.html + +*/ +const char * const urls[NUMT]= { + "https://curl.se/", + "ftp://example.com/", + "https://example.net/", + "www.example" +}; + +static void *pull_one_url(void *url) +{ + CURL *curl; + + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_perform(curl); /* ignores error */ + curl_easy_cleanup(curl); + + return NULL; +} + + +/* + int pthread_create(pthread_t *new_thread_ID, + const pthread_attr_t *attr, + void * (*start_func)(void *), void *arg); +*/ + +int main(int argc, char **argv) +{ + pthread_t tid[NUMT]; + int i; + + /* Must initialize libcurl before any threads are started */ + curl_global_init(CURL_GLOBAL_ALL); + + for(i = 0; i < NUMT; i++) { + int error = pthread_create(&tid[i], + NULL, /* default attributes please */ + pull_one_url, + (void *)urls[i]); + if(0 != error) + fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error); + else + fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]); + } + + /* now wait for all threads to terminate */ + for(i = 0; i < NUMT; i++) { + pthread_join(tid[i], NULL); + fprintf(stderr, "Thread %d terminated\n", i); + } + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/netrc.c b/local-test-curl-delta-01/afc-curl/docs/examples/netrc.c new file mode 100644 index 0000000000000000000000000000000000000000..42e1b6341e50bff1446c735be820a4214fe67c82 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/netrc.c @@ -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 + * + ***************************************************************************/ +/* + * Use credentials from .netrc + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_NETRC, CURL_NETRC_OPTIONAL); + curl_easy_setopt(curl, CURLOPT_NETRC_FILE, + "/home/daniel/s3cr3ts.txt"); + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + res = curl_easy_perform(curl); + + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/persistent.c b/local-test-curl-delta-01/afc-curl/docs/examples/persistent.c new file mode 100644 index 0000000000000000000000000000000000000000..be5e8c33e667e7b3529c052318a092dbf6e291ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/persistent.c @@ -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 + * + ***************************************************************************/ +/* + * reusing handles to do HTTP persistent connections + * + */ +#include + +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_HEADER, 1L); + + /* get the first document */ + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/"); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* get another document from the same server using the same + connection */ + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/docs/"); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-authzid.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-authzid.c new file mode 100644 index 0000000000000000000000000000000000000000..3281b322bb9c2595934a72ea207f55c5e241639e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-authzid.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Retrieve emails from a shared POP3 mailbox + * + */ + +#include +#include + +/* This is a simple example showing how to retrieve mail using libcurl's POP3 + * capabilities. + * + * Note that this example requires libcurl 7.66.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set the username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* Set the authorization identity (identity to act as) */ + curl_easy_setopt(curl, CURLOPT_SASL_AUTHZID, "shared-mailbox"); + + /* Force PLAIN authentication */ + curl_easy_setopt(curl, CURLOPT_LOGIN_OPTIONS, "AUTH=PLAIN"); + + /* This retrieves message 1 from the user's mailbox */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1"); + + /* Perform the retr */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-dele.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-dele.c new file mode 100644 index 0000000000000000000000000000000000000000..fe3795c245ae1b6044b08449a3d069398eb409d8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-dele.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Delete POP3 emails + * + */ + +#include +#include + +/* This is a simple example showing how to delete an existing mail using + * libcurl's POP3 capabilities. + * + * Note that this example requires libcurl 7.26.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* You can specify the message either in the URL or DELE command */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1"); + + /* Set the DELE command */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELE"); + + /* Do not perform a transfer as DELE returns no data */ + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-list.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-list.c new file mode 100644 index 0000000000000000000000000000000000000000..2cd44e41cdb14ab4172b955ac3e1c93a8e9de910 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-list.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * List the contents of a POP3 mailbox + * + */ + +#include +#include + +/* This is a simple example using libcurl's POP3 capabilities to list the + * contents of a mailbox. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This lists every message of the given mailbox */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com"); + + /* Perform the list */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-multi.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-multi.c new file mode 100644 index 0000000000000000000000000000000000000000..54eb7ecc324364124d4515e87c43770cd1558ef2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-multi.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 + * + ***************************************************************************/ + +/* + * Get POP3 email using the multi interface + * + */ + +#include +#include +#include + +/* This is a simple example showing how to retrieve mail using libcurl's POP3 + * capabilities. It builds on the pop3-retr.c example to demonstrate how to use + * libcurl's multi interface. + */ + +int main(void) +{ + CURL *curl; + CURLM *mcurl; + int still_running = 1; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(!curl) + return 1; + + mcurl = curl_multi_init(); + if(!mcurl) + return 2; + + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This retrieves message 1 from the user's mailbox */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1"); + + /* Tell the multi stack about our easy handle */ + curl_multi_add_handle(mcurl, curl); + + do { + CURLMcode mc = curl_multi_perform(mcurl, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(mcurl, NULL, 0, 1000, NULL); + + if(mc) + break; + + } while(still_running); + + /* Always cleanup */ + curl_multi_remove_handle(mcurl, curl); + curl_multi_cleanup(mcurl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-noop.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-noop.c new file mode 100644 index 0000000000000000000000000000000000000000..16181d2875ef5f4d031fd1734a1567e144a7953d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-noop.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Perform a POP3 noop + * + */ + +#include +#include + +/* This is a simple example showing how to perform a noop using libcurl's POP3 + * capabilities. + * + * Note that this example requires libcurl 7.26.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com"); + + /* Set the NOOP command */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "NOOP"); + + /* Do not perform a transfer as NOOP returns no data */ + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-retr.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-retr.c new file mode 100644 index 0000000000000000000000000000000000000000..8e690f972f2b5e7b78bb5fa7965baafe792b5923 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-retr.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Retrieve POP3 email + * + */ + +#include +#include + +/* This is a simple example showing how to retrieve mail using libcurl's POP3 + * capabilities. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This retrieves message 1 from the user's mailbox */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1"); + + /* Perform the retr */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-ssl.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-ssl.c new file mode 100644 index 0000000000000000000000000000000000000000..dcc7992e418ff95ac9165989cc1534425727deeb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-ssl.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Get POP3 email using implicit SSL + * + */ + +#include +#include + +/* This is a simple example showing how to retrieve mail using libcurl's POP3 + * capabilities. It builds on the pop3-retr.c example adding transport + * security to protect the authentication details from being snooped. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This retrieves message 1 from the user's mailbox. Note the use of + * pop3s:// rather than pop3:// to request a SSL based connection. */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3s://pop.example.com/1"); + + /* If you want to connect to a site who is not using a certificate that is + * signed by one of the certs in the CA bundle you have, you can skip the + * verification of the server's certificate. This makes the connection + * A LOT LESS SECURE. + * + * If you have a CA cert for the server stored someplace else than in the + * default bundle, then the CURLOPT_CAPATH option might come handy for + * you. */ +#ifdef SKIP_PEER_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); +#endif + + /* If the site you are connecting to uses a different host name that what + * they have mentioned in their server certificate's commonName (or + * subjectAltName) fields, libcurl refuses to connect. You can skip this + * check, but it makes the connection insecure. */ +#ifdef SKIP_HOSTNAME_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); +#endif + + /* Since the traffic is encrypted, it is useful to turn on debug + * information within libcurl to see what is happening during the + * transfer */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the retr */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-stat.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-stat.c new file mode 100644 index 0000000000000000000000000000000000000000..419859bfa6db1487b5bf837c562cb28dd8b9cee4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-stat.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Obtain POP3 message statistics + * + */ + +#include +#include + +/* This is a simple example showing how to obtain message statistics using + * libcurl's POP3 capabilities. + * + * Note that this example requires libcurl 7.26.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com"); + + /* Set the STAT command */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "STAT"); + + /* Do not perform a transfer as the data is in the response */ + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-tls.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-tls.c new file mode 100644 index 0000000000000000000000000000000000000000..7c2d824d043e78e787b6bdea3feecb34d14f18b2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-tls.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * POP3 using TLS + * + */ + +#include +#include + +/* This is a simple example showing how to retrieve mail using libcurl's POP3 + * capabilities. It builds on the pop3-retr.c example adding transport + * security to protect the authentication details from being snooped. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This retrieves message 1 from the user's mailbox */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1"); + + /* In this example, we start with a plain text connection, and upgrade to + * Transport Layer Security (TLS) using the STLS command. Be careful of + * using CURLUSESSL_TRY here, because if TLS upgrade fails, the transfer + * continues anyway - see the security discussion in the libcurl tutorial + * for more details. */ + curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); + + /* If your server does not have a valid certificate, then you can disable + * part of the Transport Layer Security protection by setting the + * CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false). + * curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + * curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + * + * That is, in general, a bad idea. It is still better than sending your + * authentication details in plain text though. Instead, you should get + * the issuer certificate (or the host certificate if the certificate is + * self-signed) and add it to the set of certificates that are known to + * libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See docs/SSLCERTS + * for more information. */ + curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem"); + + /* Since the traffic is encrypted, it is useful to turn on debug + * information within libcurl to see what is happening during the + * transfer */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the retr */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-top.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-top.c new file mode 100644 index 0000000000000000000000000000000000000000..7ceba881b295c899eb4d5f37d32d220dbbc98f2e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-top.c @@ -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 + * + ***************************************************************************/ + +/* + * POP3 example showing how to retrieve only the headers of an email + * + */ + +#include +#include + +/* This is a simple example showing how to retrieve only the headers of a mail + * using libcurl's POP3 capabilities. + * + * Note that this example requires libcurl 7.26.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com"); + + /* Set the TOP command for message 1 to only include the headers */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "TOP 1 0"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/pop3-uidl.c b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-uidl.c new file mode 100644 index 0000000000000000000000000000000000000000..496e5b08d45ecbf84d567467e05bfb3f7e71acb9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/pop3-uidl.c @@ -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 + * + ***************************************************************************/ + +/* + * List the contents of a POP3 mailbox by unique ID + * + */ + +#include +#include + +/* This is a simple example using libcurl's POP3 capabilities to list the + * contents of a mailbox by unique ID. + * + * Note that this example requires libcurl 7.26.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is just the server URL */ + curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com"); + + /* Set the UIDL command */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "UIDL"); + + /* Perform the custom request */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/postinmemory.c b/local-test-curl-delta-01/afc-curl/docs/examples/postinmemory.c new file mode 100644 index 0000000000000000000000000000000000000000..cbdc77f75c72ea24bd618a12b75590aa8c2ac719 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/postinmemory.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 + * + ***************************************************************************/ +/* + * Make an HTTP POST with data from memory and receive response in memory. + * + */ +#include +#include +#include +#include + +struct MemoryStruct { + char *memory; + size_t size; +}; + +static size_t +WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) +{ + size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)userp; + + char *ptr = realloc(mem->memory, mem->size + realsize + 1); + if(!ptr) { + /* out of memory! */ + printf("not enough memory (realloc returned NULL)\n"); + return 0; + } + + mem->memory = ptr; + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + struct MemoryStruct chunk; + static const char *postthis = "Field=1&Field=2&Field=3"; + + chunk.memory = malloc(1); /* grown as needed by realloc above */ + chunk.size = 0; /* no data at this point */ + + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.org/"); + + /* send all data to this function */ + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + + /* we pass our 'chunk' struct to the callback function */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + + /* some servers do not like requests that are made without a user-agent + field, so we provide one */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); + + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis); + + /* if we do not provide POSTFIELDSIZE, libcurl calls strlen() by itself */ + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis)); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + } + else { + /* + * Now, our chunk.memory points to a memory block that is chunk.size + * bytes big and contains the remote file. + * + * Do something nice with it! + */ + printf("%s\n",chunk.memory); + } + + /* always cleanup */ + curl_easy_cleanup(curl); + } + + free(chunk.memory); + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/postit2-formadd.c b/local-test-curl-delta-01/afc-curl/docs/examples/postit2-formadd.c new file mode 100644 index 0000000000000000000000000000000000000000..0d9034612a56b60d4e9f5a4b74153a4a9d048fe2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/postit2-formadd.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP Multipart formpost with file upload and two additional parts. + * + */ + +/* + * Example code that uploads a filename 'foo' to a remote script that accepts + * "HTML form based" (as described in RFC 1738) uploads using HTTP POST. + * + * Warning: this example uses the deprecated form api. See "postit2.c" + * for a similar example using the mime api. + * + * The imaginary form we fill in looks like: + * + *
+ * Enter file: + * Enter filename: + * + *
+ */ + +#include +#include + +#include + +int main(int argc, char *argv[]) +{ + CURL *curl; + CURLcode res; + + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + struct curl_slist *headerlist = NULL; + static const char buf[] = "Expect:"; + + curl_global_init(CURL_GLOBAL_ALL); + + CURL_IGNORE_DEPRECATION( + /* Fill in the file upload field */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "sendfile", + CURLFORM_FILE, "postit2-formadd.c", + CURLFORM_END); + + /* Fill in the filename field */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "filename", + CURLFORM_COPYCONTENTS, "postit2-formadd.c", + CURLFORM_END); + + + /* Fill in the submit field too, even if this is rarely needed */ + curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "submit", + CURLFORM_COPYCONTENTS, "send", + CURLFORM_END); + ) + + curl = curl_easy_init(); + /* initialize custom header list (stating that Expect: 100-continue is not + wanted */ + headerlist = curl_slist_append(headerlist, buf); + if(curl) { + /* what URL that receives this POST */ + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/examplepost.cgi"); + if((argc == 2) && (!strcmp(argv[1], "noexpectheader"))) + /* only disable 100-continue header if explicitly requested */ + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); + CURL_IGNORE_DEPRECATION( + curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); + ) + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + + CURL_IGNORE_DEPRECATION( + /* then cleanup the formpost chain */ + curl_formfree(formpost); + ) + + /* free slist */ + curl_slist_free_all(headerlist); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/progressfunc.c b/local-test-curl-delta-01/afc-curl/docs/examples/progressfunc.c new file mode 100644 index 0000000000000000000000000000000000000000..e164f03ca5c57720b70dbc3c191c1d42f85b1080 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/progressfunc.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 + * + ***************************************************************************/ +/* + * Use the progress callbacks, old and/or new one depending on available + * libcurl version. + * + */ +#include +#include + +#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 3000000 +#define STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES 6000 + +struct myprogress { + curl_off_t lastruntime; /* type depends on version, see above */ + CURL *curl; +}; + +/* this is how the CURLOPT_XFERINFOFUNCTION callback works */ +static int xferinfo(void *p, + curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + struct myprogress *myp = (struct myprogress *)p; + CURL *curl = myp->curl; + curl_off_t curtime = 0; + + curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME_T, &curtime); + + /* under certain circumstances it may be desirable for certain functionality + to only run every N seconds, in order to do this the transaction time can + be used */ + if((curtime - myp->lastruntime) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) { + myp->lastruntime = curtime; + fprintf(stderr, "TOTAL TIME: %lu.%06lu\r\n", + (unsigned long)(curtime / 1000000), + (unsigned long)(curtime % 1000000)); + } + + fprintf(stderr, "UP: %lu of %lu DOWN: %lu of %lu\r\n", + (unsigned long)ulnow, (unsigned long)ultotal, + (unsigned long)dlnow, (unsigned long)dltotal); + + if(dlnow > STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES) + return 1; + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct myprogress prog; + + curl = curl_easy_init(); + if(curl) { + prog.lastruntime = 0; + prog.curl = curl; + + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/"); + + curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferinfo); + /* pass the struct pointer into the xferinfo function */ + curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &prog); + + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); + res = curl_easy_perform(curl); + + if(res != CURLE_OK) + fprintf(stderr, "%s\n", curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/protofeats.c b/local-test-curl-delta-01/afc-curl/docs/examples/protofeats.c new file mode 100644 index 0000000000000000000000000000000000000000..3e762218ae2499d9d218ce291f0ef3c28c1e59da --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/protofeats.c @@ -0,0 +1,52 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Outputs all protocols and features supported + * + */ +#include +#include + +#if !CURL_AT_LEAST_VERSION(7,87,0) +#error "too old libcurl" +#endif + +int main(void) +{ + curl_version_info_data *ver; + const char *const *ptr; + + curl_global_init(CURL_GLOBAL_ALL); + + ver = curl_version_info(CURLVERSION_NOW); + printf("Protocols:\n"); + for(ptr = ver->protocols; *ptr; ++ptr) + printf(" %s\n", *ptr); + printf("Features:\n"); + for(ptr = ver->feature_names; *ptr; ++ptr) + printf(" %s\n", *ptr); + + curl_global_cleanup(); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/rtsp-options.c b/local-test-curl-delta-01/afc-curl/docs/examples/rtsp-options.c new file mode 100644 index 0000000000000000000000000000000000000000..d1ddbf01ff24076b84d6b3d52eb0212dd1e24d99 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/rtsp-options.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 + * + ***************************************************************************/ +/* + * Very simple RTSP request sending OPTIONS. + * + */ +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "rtsp://example.com/"); + + curl_easy_setopt(curl, CURLOPT_RTSP_SESSION_ID, "12345"); + + curl_easy_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/sepheaders.c b/local-test-curl-delta-01/afc-curl/docs/examples/sepheaders.c new file mode 100644 index 0000000000000000000000000000000000000000..31a320124168a001e4e5eee6cdce1914c772f705 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/sepheaders.c @@ -0,0 +1,95 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Simple HTTP GET that stores the headers in a separate file + * + */ +#include +#include + +#include + +static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); + return written; +} + +int main(void) +{ + CURL *curl_handle; + static const char *headerfilename = "head.out"; + FILE *headerfile; + static const char *bodyfilename = "body.out"; + FILE *bodyfile; + + curl_global_init(CURL_GLOBAL_ALL); + + /* init the curl session */ + curl_handle = curl_easy_init(); + + /* set URL to get */ + curl_easy_setopt(curl_handle, CURLOPT_URL, "https://example.com"); + + /* no progress meter please */ + curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L); + + /* send all data to this function */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data); + + /* open the header file */ + headerfile = fopen(headerfilename, "wb"); + if(!headerfile) { + curl_easy_cleanup(curl_handle); + return -1; + } + + /* open the body file */ + bodyfile = fopen(bodyfilename, "wb"); + if(!bodyfile) { + curl_easy_cleanup(curl_handle); + fclose(headerfile); + return -1; + } + + /* we want the headers be written to this file handle */ + curl_easy_setopt(curl_handle, CURLOPT_HEADERDATA, headerfile); + + /* we want the body be written to this file handle instead of stdout */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, bodyfile); + + /* get it! */ + curl_easy_perform(curl_handle); + + /* close the header file */ + fclose(headerfile); + + /* close the body file */ + fclose(bodyfile); + + /* cleanup curl stuff */ + curl_easy_cleanup(curl_handle); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/sessioninfo.c b/local-test-curl-delta-01/afc-curl/docs/examples/sessioninfo.c new file mode 100644 index 0000000000000000000000000000000000000000..befb8f3c0bc81abc281ce3565c4a7693638f9bea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/sessioninfo.c @@ -0,0 +1,112 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Uses the CURLINFO_TLS_SESSION data. + * + */ + +/* Note that this example currently requires curl to be linked against + GnuTLS (and this program must also be linked against -lgnutls). */ + +#include + +#include +#include +#include + +static CURL *curl; + +static size_t wrfu(void *ptr, size_t size, size_t nmemb, void *stream) +{ + const struct curl_tlssessioninfo *info; + unsigned int cert_list_size; + const gnutls_datum_t *chainp; + CURLcode res; + + (void)stream; + (void)ptr; + + res = curl_easy_getinfo(curl, CURLINFO_TLS_SESSION, &info); + + if(!res) { + switch(info->backend) { + case CURLSSLBACKEND_GNUTLS: + /* info->internals is now the gnutls_session_t */ + chainp = gnutls_certificate_get_peers(info->internals, &cert_list_size); + if((chainp) && (cert_list_size)) { + unsigned int i; + + for(i = 0; i < cert_list_size; i++) { + gnutls_x509_crt_t cert; + gnutls_datum_t dn; + + if(GNUTLS_E_SUCCESS == gnutls_x509_crt_init(&cert)) { + if(GNUTLS_E_SUCCESS == + gnutls_x509_crt_import(cert, &chainp[i], GNUTLS_X509_FMT_DER)) { + if(GNUTLS_E_SUCCESS == + gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &dn)) { + fprintf(stderr, "Certificate #%u: %.*s", i, dn.size, dn.data); + + gnutls_free(dn.data); + } + } + + gnutls_x509_crt_deinit(cert); + } + } + } + break; + case CURLSSLBACKEND_NONE: + default: + break; + } + } + + return size * nmemb; +} + +int main(void) +{ + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com/"); + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wrfu); + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); + + (void) curl_easy_perform(curl); + + curl_easy_cleanup(curl); + } + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/sftpget.c b/local-test-curl-delta-01/afc-curl/docs/examples/sftpget.c new file mode 100644 index 0000000000000000000000000000000000000000..4d33939a40bf8781e701d41c2b477abda973c471 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/sftpget.c @@ -0,0 +1,112 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Gets a file using an SFTP URL. + * + */ + +#include + +#include + +/* define this to switch off the use of ssh-agent in this program */ +#undef DISABLE_SSH_AGENT + +/* + * This is an example showing how to get a single file from an SFTP server. It + * delays the actual destination file creation until the first write callback + * so that it does not create an empty file in case the remote file does not + * exist or something else fails. + */ + +struct FtpFile { + const char *filename; + FILE *stream; +}; + +static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, + void *stream) +{ + struct FtpFile *out = (struct FtpFile *)stream; + if(!out->stream) { + /* open file for writing */ + out->stream = fopen(out->filename, "wb"); + if(!out->stream) + return 0; /* failure, cannot open file to write */ + } + return fwrite(buffer, size, nmemb, out->stream); +} + + +int main(void) +{ + CURL *curl; + CURLcode res; + struct FtpFile ftpfile = { + "yourfile.bin", /* name to store the file as if successful */ + NULL + }; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + /* + * You better replace the URL with one that works! + */ + curl_easy_setopt(curl, CURLOPT_URL, + "sftp://user@server/home/user/file.txt"); + /* Define our callback to get called when there is data to be written */ + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite); + /* Set a pointer to our struct to pass to the callback */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); + +#ifndef DISABLE_SSH_AGENT + /* We activate ssh agent. For this to work you need + to have ssh-agent running (type set | grep SSH_AGENT to check) or + pageant on Windows (there is an icon in systray if so) */ + curl_easy_setopt(curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_AGENT); +#endif + + /* Switch on full protocol/debug output */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + + if(CURLE_OK != res) { + /* we failed */ + fprintf(stderr, "curl told us %d\n", res); + } + } + + if(ftpfile.stream) + fclose(ftpfile.stream); /* close the local file */ + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/sftpuploadresume.c b/local-test-curl-delta-01/afc-curl/docs/examples/sftpuploadresume.c new file mode 100644 index 0000000000000000000000000000000000000000..aabe5c39535b372f11a968ba41f2b25d14dbdce8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/sftpuploadresume.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 + * + ***************************************************************************/ +/* + * Upload to SFTP, resuming a previously aborted transfer. + * + */ + +#include +#include +#include + +/* read data to upload */ +static size_t readfunc(char *ptr, size_t size, size_t nmemb, void *stream) +{ + FILE *f = (FILE *)stream; + size_t n; + + if(ferror(f)) + return CURL_READFUNC_ABORT; + + n = fread(ptr, size, nmemb, f) * size; + + return n; +} + +/* + * sftpGetRemoteFileSize returns the remote file size in byte; -1 on error + */ +static curl_off_t sftpGetRemoteFileSize(const char *i_remoteFile) +{ + CURLcode result = CURLE_GOT_NOTHING; + curl_off_t remoteFileSizeByte = -1; + CURL *curlHandlePtr = curl_easy_init(); + + curl_easy_setopt(curlHandlePtr, CURLOPT_VERBOSE, 1L); + + curl_easy_setopt(curlHandlePtr, CURLOPT_URL, i_remoteFile); + curl_easy_setopt(curlHandlePtr, CURLOPT_NOPROGRESS, 1); + curl_easy_setopt(curlHandlePtr, CURLOPT_NOBODY, 1); + curl_easy_setopt(curlHandlePtr, CURLOPT_HEADER, 1); + curl_easy_setopt(curlHandlePtr, CURLOPT_FILETIME, 1); + + result = curl_easy_perform(curlHandlePtr); + if(CURLE_OK == result) { + result = curl_easy_getinfo(curlHandlePtr, + CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, + &remoteFileSizeByte); + if(result) + return -1; + printf("filesize: %lu\n", (unsigned long)remoteFileSizeByte); + } + curl_easy_cleanup(curlHandlePtr); + + return remoteFileSizeByte; +} + + +static int sftpResumeUpload(CURL *curlhandle, const char *remotepath, + const char *localpath) +{ + FILE *f = NULL; + CURLcode result = CURLE_GOT_NOTHING; + + curl_off_t remoteFileSizeByte = sftpGetRemoteFileSize(remotepath); + if(-1 == remoteFileSizeByte) { + printf("Error reading the remote file size: unable to resume upload\n"); + return -1; + } + + f = fopen(localpath, "rb"); + if(!f) { + perror(NULL); + return 0; + } + + curl_easy_setopt(curlhandle, CURLOPT_UPLOAD, 1L); + curl_easy_setopt(curlhandle, CURLOPT_URL, remotepath); + curl_easy_setopt(curlhandle, CURLOPT_READFUNCTION, readfunc); + curl_easy_setopt(curlhandle, CURLOPT_READDATA, f); + +#ifdef _WIN32 + _fseeki64(f, remoteFileSizeByte, SEEK_SET); +#else + fseek(f, (long)remoteFileSizeByte, SEEK_SET); +#endif + curl_easy_setopt(curlhandle, CURLOPT_APPEND, 1L); + result = curl_easy_perform(curlhandle); + + fclose(f); + + if(result == CURLE_OK) + return 1; + else { + fprintf(stderr, "%s\n", curl_easy_strerror(result)); + return 0; + } +} + +int main(void) +{ + const char *remote = "sftp://user:pass@example.com/path/filename"; + const char *filename = "filename"; + CURL *curlhandle = NULL; + + curl_global_init(CURL_GLOBAL_ALL); + curlhandle = curl_easy_init(); + + if(!sftpResumeUpload(curlhandle, remote, filename)) { + printf("resumed upload using curl %s failed\n", curl_version()); + } + + curl_easy_cleanup(curlhandle); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/shared-connection-cache.c b/local-test-curl-delta-01/afc-curl/docs/examples/shared-connection-cache.c new file mode 100644 index 0000000000000000000000000000000000000000..dc6805a9f19e8d59a084b15cbf821002d0621376 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/shared-connection-cache.c @@ -0,0 +1,87 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Connection cache shared between easy handles with the share interface + * + */ +#include +#include + +static void my_lock(CURL *handle, curl_lock_data data, + curl_lock_access laccess, void *useptr) +{ + (void)handle; + (void)data; + (void)laccess; + (void)useptr; + fprintf(stderr, "-> Mutex lock\n"); +} + +static void my_unlock(CURL *handle, curl_lock_data data, void *useptr) +{ + (void)handle; + (void)data; + (void)useptr; + fprintf(stderr, "<- Mutex unlock\n"); +} + +int main(void) +{ + CURLSH *share; + int i; + + share = curl_share_init(); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT); + + curl_share_setopt(share, CURLSHOPT_LOCKFUNC, my_lock); + curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, my_unlock); + + /* Loop the transfer and cleanup the handle properly every lap. This still + reuses connections since the pool is in the shared object! */ + + for(i = 0; i < 3; i++) { + CURL *curl = curl_easy_init(); + if(curl) { + CURLcode res; + + curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/"); + + /* use the share object */ + curl_easy_setopt(curl, CURLOPT_SHARE, share); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + } + + curl_share_cleanup(share); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/simplepost.c b/local-test-curl-delta-01/afc-curl/docs/examples/simplepost.c new file mode 100644 index 0000000000000000000000000000000000000000..7ced982fe010ffc33bfaa77eb1eb7bc453207bfb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/simplepost.c @@ -0,0 +1,58 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Very simple HTTP POST + * + */ +#include +#include +#include + +int main(void) +{ + CURL *curl; + CURLcode res; + + static const char *postthis = "moo mooo moo moo"; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "https://example.com"); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis); + + /* if we do not provide POSTFIELDSIZE, libcurl calls strlen() by itself */ + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis)); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/simplessl.c b/local-test-curl-delta-01/afc-curl/docs/examples/simplessl.c new file mode 100644 index 0000000000000000000000000000000000000000..fcbb5a4607edc0df87a780f0c198ecc606aeb6ca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/simplessl.c @@ -0,0 +1,150 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Shows HTTPS usage with client certs and optional ssl engine use. + * + */ +#include + +#include + +/* some requirements for this to work: + 1. set pCertFile to the file with the client certificate + 2. if the key is passphrase protected, set pPassphrase to the + passphrase you use + 3. if you are using a crypto engine: + 3.1. set a #define USE_ENGINE + 3.2. set pEngine to the name of the crypto engine you use + 3.3. set pKeyName to the key identifier you want to use + 4. if you do not use a crypto engine: + 4.1. set pKeyName to the filename of your client key + 4.2. if the format of the key file is DER, set pKeyType to "DER" + + !! verify of the server certificate is not implemented here !! + + **** This example only works with libcurl 7.9.3 and later! **** + +*/ + +int main(void) +{ + CURL *curl; + CURLcode res; + FILE *headerfile; + const char *pPassphrase = NULL; + + static const char *pCertFile = "testcert.pem"; + static const char *pCACertFile = "cacert.pem"; + static const char *pHeaderFile = "dumpit"; + + const char *pKeyName; + const char *pKeyType; + + const char *pEngine; + +#ifdef USE_ENGINE + pKeyName = "rsa_test"; + pKeyType = "ENG"; + pEngine = "chil"; /* for nChiper HSM... */ +#else + pKeyName = "testkey.pem"; + pKeyType = "PEM"; + pEngine = NULL; +#endif + + headerfile = fopen(pHeaderFile, "wb"); + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(curl) { + /* what call to write: */ + curl_easy_setopt(curl, CURLOPT_URL, "HTTPS://your.favourite.ssl.site"); + curl_easy_setopt(curl, CURLOPT_HEADERDATA, headerfile); + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4127) /* conditional expression is constant */ +#endif + do { /* dummy loop, just to break out from */ + if(pEngine) { + /* use crypto engine */ + if(curl_easy_setopt(curl, CURLOPT_SSLENGINE, pEngine) != CURLE_OK) { + /* load the crypto engine */ + fprintf(stderr, "cannot set crypto engine\n"); + break; + } + if(curl_easy_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1L) != CURLE_OK) { + /* set the crypto engine as default */ + /* only needed for the first time you load + an engine in a curl object... */ + fprintf(stderr, "cannot set crypto engine as default\n"); + break; + } + } + /* cert is stored PEM coded in file... */ + /* since PEM is default, we needn't set it for PEM */ + curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM"); + + /* set the cert for client authentication */ + curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile); + + /* sorry, for engine we must set the passphrase + (if the key has one...) */ + if(pPassphrase) + curl_easy_setopt(curl, CURLOPT_KEYPASSWD, pPassphrase); + + /* if we use a key stored in a crypto engine, + we must set the key type to "ENG" */ + curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, pKeyType); + + /* set the private key (file or ID in engine) */ + curl_easy_setopt(curl, CURLOPT_SSLKEY, pKeyName); + + /* set the file with the certs validating the server */ + curl_easy_setopt(curl, CURLOPT_CAINFO, pCACertFile); + + /* disconnect if we cannot validate server's cert */ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* we are done... */ + } while(0); +#ifdef _MSC_VER +#pragma warning(pop) +#endif + /* always cleanup */ + curl_easy_cleanup(curl); + } + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smooth-gtk-thread.c b/local-test-curl-delta-01/afc-curl/docs/examples/smooth-gtk-thread.c new file mode 100644 index 0000000000000000000000000000000000000000..c53951262afe580e395cf9f297cd551dbf5a1b7b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smooth-gtk-thread.c @@ -0,0 +1,218 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 multi threaded application that uses a progress bar to show + * status. It uses Gtk+ to make a smooth pulse. + * + */ +/* + * Written by Jud Bishop after studying the other examples provided with + * libcurl. + * + * To compile (on a single line): + * gcc -ggdb `pkg-config --cflags --libs gtk+-2.0` -lcurl -lssl -lcrypto + * -lgthread-2.0 -dl smooth-gtk-thread.c -o smooth-gtk-thread + */ + +#include +#include +#include +#include +#include + +#include + +#define NUMT 4 + +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +int j = 0; +gint num_urls = 9; /* Just make sure this is less than urls[]*/ +const char * const urls[]= { + "90022", + "90023", + "90024", + "90025", + "90026", + "90027", + "90028", + "90029", + "90030" +}; + +size_t write_file(void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + return fwrite(ptr, size, nmemb, stream); +} + +static void run_one(gchar *http, int j) +{ + FILE *outfile = fopen(urls[j], "wb"); + CURL *curl; + + curl = curl_easy_init(); + if(curl) { + printf("j = %d\n", j); + + /* Set the URL and transfer type */ + curl_easy_setopt(curl, CURLOPT_URL, http); + + /* Write to the file */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_file); + curl_easy_perform(curl); + + fclose(outfile); + curl_easy_cleanup(curl); + } +} + +void *pull_one_url(void *NaN) +{ + /* protect the reading and increasing of 'j' with a mutex */ + pthread_mutex_lock(&lock); + while(j < num_urls) { + int i = j; + j++; + pthread_mutex_unlock(&lock); + http = g_strdup_printf("https://example.com/%s", urls[i]); + if(http) { + run_one(http, i); + g_free(http); + } + pthread_mutex_lock(&lock); + } + pthread_mutex_unlock(&lock); + return NULL; +} + + +gboolean pulse_bar(gpointer data) +{ + gdk_threads_enter(); + gtk_progress_bar_pulse(GTK_PROGRESS_BAR (data)); + gdk_threads_leave(); + + /* Return true so the function is called again; returning false removes this + * timeout function. + */ + return TRUE; +} + +void *create_thread(void *progress_bar) +{ + pthread_t tid[NUMT]; + int i; + + /* Make sure I do not create more threads than urls. */ + for(i = 0; i < NUMT && i < num_urls ; i++) { + int error = pthread_create(&tid[i], + NULL, /* default attributes please */ + pull_one_url, + NULL); + if(0 != error) + fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error); + else + fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]); + } + + /* Wait for all threads to terminate. */ + for(i = 0; i < NUMT && i < num_urls; i++) { + pthread_join(tid[i], NULL); + fprintf(stderr, "Thread %d terminated\n", i); + } + + /* This stops the pulsing if you have it turned on in the progress bar + section */ + g_source_remove(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(progress_bar), + "pulse_id"))); + + /* This destroys the progress bar */ + gtk_widget_destroy(progress_bar); + + /* [Un]Comment this out to kill the program rather than pushing close. */ + /* gtk_main_quit(); */ + + + return NULL; + +} + +static gboolean cb_delete(GtkWidget *window, gpointer data) +{ + gtk_main_quit(); + return FALSE; +} + +int main(int argc, char **argv) +{ + GtkWidget *top_window, *outside_frame, *inside_frame, *progress_bar; + + /* Must initialize libcurl before any threads are started */ + curl_global_init(CURL_GLOBAL_ALL); + + /* Init thread */ + g_thread_init(NULL); + gdk_threads_init(); + gdk_threads_enter(); + + gtk_init(&argc, &argv); + + /* Base window */ + top_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + + /* Frame */ + outside_frame = gtk_frame_new(NULL); + gtk_frame_set_shadow_type(GTK_FRAME(outside_frame), GTK_SHADOW_OUT); + gtk_container_add(GTK_CONTAINER(top_window), outside_frame); + + /* Frame */ + inside_frame = gtk_frame_new(NULL); + gtk_frame_set_shadow_type(GTK_FRAME(inside_frame), GTK_SHADOW_IN); + gtk_container_set_border_width(GTK_CONTAINER(inside_frame), 5); + gtk_container_add(GTK_CONTAINER(outside_frame), inside_frame); + + /* Progress bar */ + progress_bar = gtk_progress_bar_new(); + gtk_progress_bar_pulse(GTK_PROGRESS_BAR (progress_bar)); + /* Make uniform pulsing */ + gint pulse_ref = g_timeout_add(300, pulse_bar, progress_bar); + g_object_set_data(G_OBJECT(progress_bar), "pulse_id", + GINT_TO_POINTER(pulse_ref)); + gtk_container_add(GTK_CONTAINER(inside_frame), progress_bar); + + gtk_widget_show_all(top_window); + printf("gtk_widget_show_all\n"); + + g_signal_connect(G_OBJECT (top_window), "delete-event", + G_CALLBACK(cb_delete), NULL); + + if(!g_thread_create(&create_thread, progress_bar, FALSE, NULL) != 0) + g_warning("cannot create the thread"); + + gtk_main(); + gdk_threads_leave(); + printf("gdk_threads_leave\n"); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smtp-mime.c b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-mime.c new file mode 100644 index 0000000000000000000000000000000000000000..7a2a9c618b03314e4e01826db13e93d8284fc56b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-mime.c @@ -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 + * + ***************************************************************************/ + +/* + * Send SMTP mime emails + * + */ + +#include +#include +#include + +/* This is a simple example showing how to send mime mail using libcurl's SMTP + * capabilities. For an example of using the multi interface please see + * smtp-multi.c. + * + * Note that this example requires libcurl 7.56.0 or above. + */ + +#define FROM "" +#define TO "" +#define CC "" + +static const char *headers_text[] = { + "Date: Tue, 22 Aug 2017 14:08:43 +0100", + "To: " TO, + "From: " FROM " (Example User)", + "Cc: " CC " (Another example User)", + "Message-ID: ", + "Subject: example sending a MIME-formatted message", + NULL +}; + +static const char inline_text[] = + "This is the inline text message of the email.\r\n" + "\r\n" + " It could be a lot of lines that would be displayed in an email\r\n" + "viewer that is not able to handle HTML.\r\n"; + +static const char inline_html[] = + "\r\n" + "

This is the inline HTML message of the email.

" + "
\r\n" + "

It could be a lot of HTML data that would be displayed by " + "email viewers able to handle HTML.

" + "\r\n"; + + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + struct curl_slist *headers = NULL; + struct curl_slist *recipients = NULL; + struct curl_slist *slist = NULL; + curl_mime *mime; + curl_mime *alt; + curl_mimepart *part; + const char **cpp; + + /* This is the URL for your mailserver */ + curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com"); + + /* Note that this option is not strictly required, omitting it results in + * libcurl sending the MAIL FROM command with empty sender data. All + * autoresponses should have an empty reverse-path, and should be directed + * to the address in the reverse-path which triggered them. Otherwise, + * they could cause an endless loop. See RFC 5321 Section 4.5.5 for more + * details. + */ + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM); + + /* Add two recipients, in this particular case they correspond to the + * To: and Cc: addressees in the header, but they could be any kind of + * recipient. */ + recipients = curl_slist_append(recipients, TO); + recipients = curl_slist_append(recipients, CC); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* allow one of the recipients to fail and still consider it okay */ + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT_ALLOWFAILS, 1L); + + /* Build and set the message header list. */ + for(cpp = headers_text; *cpp; cpp++) + headers = curl_slist_append(headers, *cpp); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + + /* Build the mime message. */ + mime = curl_mime_init(curl); + + /* The inline part is an alternative proposing the html and the text + versions of the email. */ + alt = curl_mime_init(curl); + + /* HTML message. */ + part = curl_mime_addpart(alt); + curl_mime_data(part, inline_html, CURL_ZERO_TERMINATED); + curl_mime_type(part, "text/html"); + + /* Text message. */ + part = curl_mime_addpart(alt); + curl_mime_data(part, inline_text, CURL_ZERO_TERMINATED); + + /* Create the inline part. */ + part = curl_mime_addpart(mime); + curl_mime_subparts(part, alt); + curl_mime_type(part, "multipart/alternative"); + slist = curl_slist_append(NULL, "Content-Disposition: inline"); + curl_mime_headers(part, slist, 1); + + /* Add the current source program as an attachment. */ + part = curl_mime_addpart(mime); + curl_mime_filedata(part, "smtp-mime.c"); + curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime); + + /* Send the message */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Free lists. */ + curl_slist_free_all(recipients); + curl_slist_free_all(headers); + + /* curl does not send the QUIT command until you call cleanup, so you + * should be able to reuse this connection for additional messages + * (setting CURLOPT_MAIL_FROM and CURLOPT_MAIL_RCPT as required, and + * calling curl_easy_perform() again. It may not be a good idea to keep + * the connection open for a long time though (more than a few minutes may + * result in the server timing out the connection), and you do want to + * clean up in the end. + */ + curl_easy_cleanup(curl); + + /* Free multipart message. */ + curl_mime_free(mime); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smtp-multi.c b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-multi.c new file mode 100644 index 0000000000000000000000000000000000000000..8837c57fd87fcdc20f735f8771c7e9acdb448acd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-multi.c @@ -0,0 +1,153 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Send SMTP email with the multi interface + * + */ + +#include +#include + +/* This is an example showing how to send mail using libcurl's SMTP + * capabilities. It builds on the smtp-mail.c example to demonstrate how to use + * libcurl's multi interface. + */ + +#define FROM_MAIL "" +#define TO_MAIL "" +#define CC_MAIL "" + +static const char *payload_text = + "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n" + "To: " TO_MAIL "\r\n" + "From: " FROM_MAIL "\r\n" + "Cc: " CC_MAIL "\r\n" + "Message-ID: \r\n" + "Subject: SMTP example message\r\n" + "\r\n" /* empty line to divide headers from body, see RFC 5322 */ + "The body of the message starts here.\r\n" + "\r\n" + "It could be a lot of lines, could be MIME encoded, whatever.\r\n" + "Check RFC 5322.\r\n"; + +struct upload_status { + size_t bytes_read; +}; + +static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + size_t room = size * nmemb; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = &payload_text[upload_ctx->bytes_read]; + + if(data) { + size_t len = strlen(data); + if(room < len) + len = room; + memcpy(ptr, data, len); + upload_ctx->bytes_read += len; + + return len; + } + + return 0; +} + +int main(void) +{ + CURL *curl; + CURLM *mcurl; + int still_running = 1; + struct curl_slist *recipients = NULL; + struct upload_status upload_ctx = { 0 }; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + curl = curl_easy_init(); + if(!curl) + return 1; + + mcurl = curl_multi_init(); + if(!mcurl) + return 2; + + /* This is the URL for your mailserver */ + curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com"); + + /* Note that this option is not strictly required, omitting it results in + * libcurl sending the MAIL FROM command with empty sender data. All + * autoresponses should have an empty reverse-path, and should be directed + * to the address in the reverse-path which triggered them. Otherwise, they + * could cause an endless loop. See RFC 5321 Section 4.5.5 for more details. + */ + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_MAIL); + + /* Add two recipients, in this particular case they correspond to the + * To: and Cc: addressees in the header, but they could be any kind of + * recipient. */ + recipients = curl_slist_append(recipients, TO_MAIL); + recipients = curl_slist_append(recipients, CC_MAIL); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* We are using a callback function to specify the payload (the headers and + * body of the message). You could just use the CURLOPT_READDATA option to + * specify a FILE pointer to read from. */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); + curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* Tell the multi stack about our easy handle */ + curl_multi_add_handle(mcurl, curl); + + do { + CURLMcode mc = curl_multi_perform(mcurl, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(mcurl, NULL, 0, 1000, NULL); + + if(mc) + break; + + } while(still_running); + + /* Free the list of recipients */ + curl_slist_free_all(recipients); + + /* Always cleanup */ + curl_multi_remove_handle(mcurl, curl); + curl_multi_cleanup(mcurl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smtp-ssl.c b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-ssl.c new file mode 100644 index 0000000000000000000000000000000000000000..150de9ceab32b9d862e791082a7b5dfa09ce56e4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-ssl.c @@ -0,0 +1,170 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Send SMTP email using implicit SSL + * + */ + +#include +#include +#include + +/* This is a simple example showing how to send mail using libcurl's SMTP + * capabilities. It builds on the smtp-mail.c example to add authentication + * and, more importantly, transport security to protect the authentication + * details from being snooped. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +#define FROM_MAIL "" +#define TO_MAIL "" +#define CC_MAIL "" + +static const char *payload_text = + "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n" + "To: " TO_MAIL "\r\n" + "From: " FROM_MAIL "\r\n" + "Cc: " CC_MAIL "\r\n" + "Message-ID: \r\n" + "Subject: SMTP example message\r\n" + "\r\n" /* empty line to divide headers from body, see RFC 5322 */ + "The body of the message starts here.\r\n" + "\r\n" + "It could be a lot of lines, could be MIME encoded, whatever.\r\n" + "Check RFC 5322.\r\n"; + +struct upload_status { + size_t bytes_read; +}; + +static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + size_t room = size * nmemb; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = &payload_text[upload_ctx->bytes_read]; + + if(data) { + size_t len = strlen(data); + if(room < len) + len = room; + memcpy(ptr, data, len); + upload_ctx->bytes_read += len; + + return len; + } + + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *recipients = NULL; + struct upload_status upload_ctx = { 0 }; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is the URL for your mailserver. Note the use of smtps:// rather + * than smtp:// to request a SSL based connection. */ + curl_easy_setopt(curl, CURLOPT_URL, "smtps://mainserver.example.net"); + + /* If you want to connect to a site who is not using a certificate that is + * signed by one of the certs in the CA bundle you have, you can skip the + * verification of the server's certificate. This makes the connection + * A LOT LESS SECURE. + * + * If you have a CA cert for the server stored someplace else than in the + * default bundle, then the CURLOPT_CAPATH option might come handy for + * you. */ +#ifdef SKIP_PEER_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); +#endif + + /* If the site you are connecting to uses a different host name that what + * they have mentioned in their server certificate's commonName (or + * subjectAltName) fields, libcurl refuses to connect. You can skip this + * check, but it makes the connection insecure. */ +#ifdef SKIP_HOSTNAME_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); +#endif + + /* Note that this option is not strictly required, omitting it results in + * libcurl sending the MAIL FROM command with empty sender data. All + * autoresponses should have an empty reverse-path, and should be directed + * to the address in the reverse-path which triggered them. Otherwise, + * they could cause an endless loop. See RFC 5321 Section 4.5.5 for more + * details. + */ + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_MAIL); + + /* Add two recipients, in this particular case they correspond to the + * To: and Cc: addressees in the header, but they could be any kind of + * recipient. */ + recipients = curl_slist_append(recipients, TO_MAIL); + recipients = curl_slist_append(recipients, CC_MAIL); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* We are using a callback function to specify the payload (the headers and + * body of the message). You could just use the CURLOPT_READDATA option to + * specify a FILE pointer to read from. */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); + curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* Since the traffic is encrypted, it is useful to turn on debug + * information within libcurl to see what is happening during the + * transfer */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Send the message */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Free the list of recipients */ + curl_slist_free_all(recipients); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smtp-tls.c b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-tls.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4e385023a5f76139b487b01fe813cbb324cec5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-tls.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 + * + ***************************************************************************/ + +/* + * Send SMTP email using implicit TLS + * + */ + +#include +#include +#include + +/* This is a simple example showing how to send mail using libcurl's SMTP + * capabilities. It builds on the smtp-mail.c example to add authentication + * and, more importantly, transport security to protect the authentication + * details from being snooped. + * + * Note that this example requires libcurl 7.20.0 or above. + */ + +#define FROM_MAIL "" +#define TO_MAIL "" +#define CC_MAIL "" + +static const char *payload_text = + "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n" + "To: " TO_MAIL "\r\n" + "From: " FROM_MAIL "\r\n" + "Cc: " CC_MAIL "\r\n" + "Message-ID: \r\n" + "Subject: SMTP example message\r\n" + "\r\n" /* empty line to divide headers from body, see RFC 5322 */ + "The body of the message starts here.\r\n" + "\r\n" + "It could be a lot of lines, could be MIME encoded, whatever.\r\n" + "Check RFC 5322.\r\n"; + +struct upload_status { + size_t bytes_read; +}; + +static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + size_t room = size * nmemb; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = &payload_text[upload_ctx->bytes_read]; + + if(data) { + size_t len = strlen(data); + if(room < len) + len = room; + memcpy(ptr, data, len); + upload_ctx->bytes_read += len; + + return len; + } + + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *recipients = NULL; + struct upload_status upload_ctx = { 0 }; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This is the URL for your mailserver. Note the use of port 587 here, + * instead of the normal SMTP port (25). Port 587 is commonly used for + * secure mail submission (see RFC 4403), but you should use whatever + * matches your server configuration. */ + curl_easy_setopt(curl, CURLOPT_URL, "smtp://mainserver.example.net:587"); + + /* In this example, we start with a plain text connection, and upgrade to + * Transport Layer Security (TLS) using the STARTTLS command. Be careful + * of using CURLUSESSL_TRY here, because if TLS upgrade fails, the + * transfer continues anyway - see the security discussion in the libcurl + * tutorial for more details. */ + curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); + + /* If your server does not have a valid certificate, then you can disable + * part of the Transport Layer Security protection by setting the + * CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false). + * curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + * curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + * That is, in general, a bad idea. It is still better than sending your + * authentication details in plain text though. Instead, you should get + * the issuer certificate (or the host certificate if the certificate is + * self-signed) and add it to the set of certificates that are known to + * libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See docs/SSLCERTS + * for more information. */ + curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem"); + + /* Note that this option is not strictly required, omitting it results in + * libcurl sending the MAIL FROM command with empty sender data. All + * autoresponses should have an empty reverse-path, and should be directed + * to the address in the reverse-path which triggered them. Otherwise, + * they could cause an endless loop. See RFC 5321 Section 4.5.5 for more + * details. + */ + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_MAIL); + + /* Add two recipients, in this particular case they correspond to the + * To: and Cc: addressees in the header, but they could be any kind of + * recipient. */ + recipients = curl_slist_append(recipients, TO_MAIL); + recipients = curl_slist_append(recipients, CC_MAIL); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* We are using a callback function to specify the payload (the headers and + * body of the message). You could just use the CURLOPT_READDATA option to + * specify a FILE pointer to read from. */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); + curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* Since the traffic is encrypted, it is useful to turn on debug + * information within libcurl to see what is happening during the + * transfer. + */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Send the message */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Free the list of recipients */ + curl_slist_free_all(recipients); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/smtp-vrfy.c b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-vrfy.c new file mode 100644 index 0000000000000000000000000000000000000000..0135efef2df0cc7ad0e27beb11d95be09b6d9589 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/smtp-vrfy.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 + * + ***************************************************************************/ + +/* + * Verify an SMTP email address + * + */ + +#include +#include +#include + +/* This is a simple example showing how to verify an email address from an + * SMTP server. + * + * Notes: + * + * 1) This example requires libcurl 7.34.0 or above. + * 2) Not all email servers support this command and even if your email server + * does support it, it may respond with a 252 response code even though the + * address does not exist. + */ + +int main(void) +{ + CURL *curl; + CURLcode res; + struct curl_slist *recipients = NULL; + + curl = curl_easy_init(); + if(curl) { + /* This is the URL for your mailserver */ + curl_easy_setopt(curl, CURLOPT_URL, "smtp://mail.example.com"); + + /* Note that the CURLOPT_MAIL_RCPT takes a list, not a char array */ + recipients = curl_slist_append(recipients, ""); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* Perform the VRFY */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Free the list of recipients */ + curl_slist_free_all(recipients); + + /* curl does not send the QUIT command until you call cleanup, so you + * should be able to reuse this connection for additional requests. It may + * not be a good idea to keep the connection open for a long time though + * (more than a few minutes may result in the server timing out the + * connection) and you do want to clean up in the end. + */ + curl_easy_cleanup(curl); + } + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/synctime.c b/local-test-curl-delta-01/afc-curl/docs/examples/synctime.c new file mode 100644 index 0000000000000000000000000000000000000000..6c495f4ae9175fd02d1581161387fdeaeb3e16f7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/synctime.c @@ -0,0 +1,377 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 your system time from a remote HTTP server's Date: header. + * + */ +/* This example code only builds as-is on Windows. + * + * While Unix/Linux user, you do not need this software. + * You can achieve the same result as synctime using curl, awk and date. + * Set proxy as according to your network, but beware of proxy Cache-Control. + * + * To set your system clock, root access is required. + * # date -s "`curl -sI https://nist.time.gov/timezone.cgi?UTC/s/0 \ + * | awk -F': ' '/Date: / {print $2}'`" + * + * To view remote webserver date and time. + * $ curl -sI https://nist.time.gov/timezone.cgi?UTC/s/0 \ + * | awk -F': ' '/Date: / {print $2}' + * + * Synchronising your computer clock via Internet time server usually relies + * on DAYTIME, TIME, or NTP protocols. These protocols provide good accurate + * time synchronization but it does not work well through a + * firewall/proxy. Some adjustment has to be made to the firewall/proxy for + * these protocols to work properly. + * + * There is an indirect method. Since most webserver provide server time in + * their HTTP header, therefore you could synchronise your computer clock + * using HTTP protocol which has no problem with firewall/proxy. + * + * For this software to work, you should take note of these items. + * 1. Your firewall/proxy must allow your computer to surf Internet. + * 2. Webserver system time must in sync with the NTP time server, + * or at least provide an accurate time keeping. + * 3. Webserver HTTP header does not provide the milliseconds units, + * so there is no way to get an accurate time. + * 4. This software could only provide an accuracy of +- a few seconds, + * as Round-Trip delay time is not taken into consideration. + * Compensation of network, firewall/proxy delay cannot be simply divide + * the Round-Trip delay time by half. + * 5. Win32 SetSystemTime() API sets your computer clock according to + * GMT/UTC time. Therefore your computer timezone must be properly set. + * 6. Webserver data should not be cached by the proxy server. Some + * webserver provide Cache-Control to prevent caching. + * + * References: + * https://web.archive.org/web/20100228012139/ \ + * tf.nist.gov/timefreq/service/its.htm + * https://web.archive.org/web/20100409024302/ \ + * tf.nist.gov/timefreq/service/firewall.htm + * + * Usage: + * This software synchronises your computer clock only when you issue + * it with --synctime. By default, it only display the webserver's clock. + * + * Written by: Frank (contributed to libcurl) + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL THE AUTHOR OF THIS SOFTWARE BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + * + */ + +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + + +#define MAX_STRING 256 +#define MAX_STRING1 MAX_STRING + 1 + +#define SYNCTIME_UA "synctime/1.0" + +typedef struct +{ + char http_proxy[MAX_STRING1]; + char proxy_user[MAX_STRING1]; + char timeserver[MAX_STRING1]; +} conf_t; + +const char DefaultTimeServer[3][MAX_STRING1] = +{ + "https://nist.time.gov/", + "https://www.google.com/" +}; + +const char *DayStr[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; +const char *MthStr[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + +int ShowAllHeader; +int AutoSyncTime; +SYSTEMTIME SYSTime; +SYSTEMTIME LOCALTime; + +#define HTTP_COMMAND_HEAD 0 +#define HTTP_COMMAND_GET 1 + + +size_t SyncTime_CURL_WriteOutput(void *ptr, size_t size, size_t nmemb, + void *stream) +{ + fwrite(ptr, size, nmemb, stream); + return (nmemb*size); +} + +size_t SyncTime_CURL_WriteHeader(void *ptr, size_t size, size_t nmemb, + void *stream) +{ + char TmpStr1[26], TmpStr2[26]; + + (void)stream; + + if(ShowAllHeader == 1) + fprintf(stderr, "%s", (char *)(ptr)); + + if(strncmp((char *)(ptr), "Date:", 5) == 0) { + if(ShowAllHeader == 0) + fprintf(stderr, "HTTP Server. %s", (char *)(ptr)); + + if(AutoSyncTime == 1) { + *TmpStr1 = 0; + *TmpStr2 = 0; + if(strlen((char *)(ptr)) > 50) /* Can prevent buffer overflow to + TmpStr1 & 2? */ + AutoSyncTime = 0; + else { + int RetVal = sscanf((char *)(ptr), "Date: %25s %hu %s %hu %hu:%hu:%hu", + TmpStr1, &SYSTime.wDay, TmpStr2, &SYSTime.wYear, + &SYSTime.wHour, &SYSTime.wMinute, + &SYSTime.wSecond); + + if(RetVal == 7) { + int i; + SYSTime.wMilliseconds = 500; /* adjust to midpoint, 0.5 sec */ + for(i = 0; i < 12; i++) { + if(strcmp(MthStr[i], TmpStr2) == 0) { + SYSTime.wMonth = i + 1; + break; + } + } + AutoSyncTime = 3; /* Computer clock is adjusted */ + } + else { + AutoSyncTime = 0; /* Error in sscanf() fields conversion */ + } + } + } + } + + if(strncmp((char *)(ptr), "X-Cache: HIT", 12) == 0) { + fprintf(stderr, "ERROR: HTTP Server data is cached." + " Server Date is no longer valid.\n"); + AutoSyncTime = 0; + } + return (nmemb*size); +} + +void SyncTime_CURL_Init(CURL *curl, char *proxy_port, + char *proxy_user_password) +{ + if(strlen(proxy_port) > 0) + curl_easy_setopt(curl, CURLOPT_PROXY, proxy_port); + + if(strlen(proxy_user_password) > 0) + curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_user_password); + +#ifdef SYNCTIME_UA + curl_easy_setopt(curl, CURLOPT_USERAGENT, SYNCTIME_UA); +#endif + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, SyncTime_CURL_WriteOutput); + curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, SyncTime_CURL_WriteHeader); +} + +int SyncTime_CURL_Fetch(CURL *curl, char *URL_Str, char *OutFileName, + int HttpGetBody) +{ + FILE *outfile; + CURLcode res; + + outfile = NULL; + if(HttpGetBody == HTTP_COMMAND_HEAD) + curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); + else { + outfile = fopen(OutFileName, "wb"); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile); + } + + curl_easy_setopt(curl, CURLOPT_URL, URL_Str); + res = curl_easy_perform(curl); + if(outfile) + fclose(outfile); + return res; /* (CURLE_OK) */ +} + +void showUsage(void) +{ + fprintf(stderr, "SYNCTIME: Synchronising computer clock with time server" + " using HTTP protocol.\n"); + fprintf(stderr, "Usage : SYNCTIME [Option]\n"); + fprintf(stderr, "Options :\n"); + fprintf(stderr, " --server=WEBSERVER Use this time server instead" + " of default.\n"); + fprintf(stderr, " --showall Show all HTTP header.\n"); + fprintf(stderr, " --synctime Synchronising computer clock" + " with time server.\n"); + fprintf(stderr, " --proxy-user=USER[:PASS] Set proxy username and" + " password.\n"); + fprintf(stderr, " --proxy=HOST[:PORT] Use HTTP proxy on given" + " port.\n"); + fprintf(stderr, " --help Print this help.\n"); + fprintf(stderr, "\n"); + return; +} + +int conf_init(conf_t *conf) +{ + int i; + + *conf->http_proxy = 0; + for(i = 0; i < MAX_STRING1; i++) + conf->proxy_user[i] = 0; /* Clean up password from memory */ + *conf->timeserver = 0; + return 1; +} + +int main(int argc, char *argv[]) +{ + CURL *curl; + conf_t conf[1]; + int RetValue; + + ShowAllHeader = 0; /* Do not show HTTP Header */ + AutoSyncTime = 0; /* Do not synchronise computer clock */ + RetValue = 0; /* Successful Exit */ + conf_init(conf); + + if(argc > 1) { + int OptionIndex = 0; + while(OptionIndex < argc) { + if(strncmp(argv[OptionIndex], "--server=", 9) == 0) + snprintf(conf->timeserver, MAX_STRING, "%s", &argv[OptionIndex][9]); + + if(strcmp(argv[OptionIndex], "--showall") == 0) + ShowAllHeader = 1; + + if(strcmp(argv[OptionIndex], "--synctime") == 0) + AutoSyncTime = 1; + + if(strncmp(argv[OptionIndex], "--proxy-user=", 13) == 0) + snprintf(conf->proxy_user, MAX_STRING, "%s", &argv[OptionIndex][13]); + + if(strncmp(argv[OptionIndex], "--proxy=", 8) == 0) + snprintf(conf->http_proxy, MAX_STRING, "%s", &argv[OptionIndex][8]); + + if((strcmp(argv[OptionIndex], "--help") == 0) || + (strcmp(argv[OptionIndex], "/?") == 0)) { + showUsage(); + return 0; + } + OptionIndex++; + } + } + + if(*conf->timeserver == 0) /* Use default server for time information */ + snprintf(conf->timeserver, MAX_STRING, "%s", DefaultTimeServer[0]); + + /* Init CURL before usage */ + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + struct tm *lt; + struct tm *gmt; + time_t tt; + time_t tt_local; + time_t tt_gmt; + double tzonediffFloat; + int tzonediffWord; + char timeBuf[61]; + char tzoneBuf[16]; + + SyncTime_CURL_Init(curl, conf->http_proxy, conf->proxy_user); + + /* Calculating time diff between GMT and localtime */ + tt = time(0); + lt = localtime(&tt); + tt_local = mktime(lt); + gmt = gmtime(&tt); + tt_gmt = mktime(gmt); + tzonediffFloat = difftime(tt_local, tt_gmt); + tzonediffWord = (int)(tzonediffFloat/3600.0); + + if((double)(tzonediffWord * 3600) == tzonediffFloat) + snprintf(tzoneBuf, 15, "%+03d'00'", tzonediffWord); + else + snprintf(tzoneBuf, 15, "%+03d'30'", tzonediffWord); + + /* Get current system time and local time */ + GetSystemTime(&SYSTime); + GetLocalTime(&LOCALTime); + snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ", + DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay, + MthStr[LOCALTime.wMonth-1], LOCALTime.wYear, + LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond, + LOCALTime.wMilliseconds); + + fprintf(stderr, "Fetch: %s\n\n", conf->timeserver); + fprintf(stderr, "Before HTTP. Date: %s%s\n\n", timeBuf, tzoneBuf); + + /* HTTP HEAD command to the Webserver */ + SyncTime_CURL_Fetch(curl, conf->timeserver, "index.htm", + HTTP_COMMAND_HEAD); + + GetLocalTime(&LOCALTime); + snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ", + DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay, + MthStr[LOCALTime.wMonth-1], LOCALTime.wYear, + LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond, + LOCALTime.wMilliseconds); + fprintf(stderr, "\nAfter HTTP. Date: %s%s\n", timeBuf, tzoneBuf); + + if(AutoSyncTime == 3) { + /* Synchronising computer clock */ + if(!SetSystemTime(&SYSTime)) { /* Set system time */ + fprintf(stderr, "ERROR: Unable to set system time.\n"); + RetValue = 1; + } + else { + /* Successfully re-adjusted computer clock */ + GetLocalTime(&LOCALTime); + snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ", + DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay, + MthStr[LOCALTime.wMonth-1], LOCALTime.wYear, + LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond, + LOCALTime.wMilliseconds); + fprintf(stderr, "\nNew System's Date: %s%s\n", timeBuf, tzoneBuf); + } + } + + /* Cleanup before exit */ + conf_init(conf); + curl_easy_cleanup(curl); + } + return RetValue; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/threaded-ssl.c b/local-test-curl-delta-01/afc-curl/docs/examples/threaded-ssl.c new file mode 100644 index 0000000000000000000000000000000000000000..c903fced00434e422cac45223dfe93d2daa367dd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/threaded-ssl.c @@ -0,0 +1,99 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Show the required mutex callback setups for GnuTLS and OpenSSL when using + * libcurl multi-threaded. + * + */ +/* A multi-threaded example that uses pthreads and fetches 4 remote files at + * once over HTTPS. + * + * Recent versions of OpenSSL and GnuTLS are thread safe by design, assuming + * support for the underlying OS threading API is built-in. Older revisions + * of this example demonstrated locking callbacks for the SSL library, which + * are no longer necessary. An older revision with callbacks can be found at + * https://github.com/curl/curl/blob/curl-7_88_1/docs/examples/threaded-ssl.c + */ + +#define USE_OPENSSL /* or USE_GNUTLS accordingly */ + +#include +#include +#include + +#define NUMT 4 + +/* List of URLs to fetch.*/ +const char * const urls[]= { + "https://www.example.com/", + "https://www2.example.com/", + "https://www3.example.com/", + "https://www4.example.com/", +}; + +static void *pull_one_url(void *url) +{ + CURL *curl; + + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, url); + /* this example does not verify the server's certificate, which means we + might be downloading stuff from an impostor */ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_perform(curl); /* ignores error */ + curl_easy_cleanup(curl); + + return NULL; +} + +int main(int argc, char **argv) +{ + pthread_t tid[NUMT]; + int i; + (void)argc; /* we do not use any arguments in this example */ + (void)argv; + + /* Must initialize libcurl before any threads are started */ + curl_global_init(CURL_GLOBAL_ALL); + + for(i = 0; i < NUMT; i++) { + int error = pthread_create(&tid[i], + NULL, /* default attributes please */ + pull_one_url, + (void *)urls[i]); + if(0 != error) + fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error); + else + fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]); + } + + /* now wait for all threads to terminate */ + for(i = 0; i < NUMT; i++) { + pthread_join(tid[i], NULL); + fprintf(stderr, "Thread %d terminated\n", i); + } + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/unixsocket.c b/local-test-curl-delta-01/afc-curl/docs/examples/unixsocket.c new file mode 100644 index 0000000000000000000000000000000000000000..299a121d9d37dd3c00901ed5e0e831b87ccae08c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/unixsocket.c @@ -0,0 +1,67 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Access HTTP server over Unix domain socket + * + */ +#include +#include + +#ifdef USE_ABSTRACT +/* + * The abstract socket namespace is a nonportable Linux extension. The name + * has no connection with filesystem pathnames. + */ +#define ABSTRACT "http-unix-domain" +#else +#define PATH "/tmp/http-unix-domain" +#endif + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); + +#ifdef USE_ABSTRACT + curl_easy_setopt(curl, CURLOPT_ABSTRACT_UNIX_SOCKET, ABSTRACT); +#else + curl_easy_setopt(curl, CURLOPT_UNIX_SOCKET_PATH, PATH); +#endif + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/url2file.c b/local-test-curl-delta-01/afc-curl/docs/examples/url2file.c new file mode 100644 index 0000000000000000000000000000000000000000..9ed7da5a84a637c105eeb7e072b32e7bbc97a019 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/url2file.c @@ -0,0 +1,87 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Download a given URL into a local file named page.out. + * + */ +#include +#include + +#include + +static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); + return written; +} + +int main(int argc, char *argv[]) +{ + CURL *curl_handle; + static const char *pagefilename = "page.out"; + FILE *pagefile; + + if(argc < 2) { + printf("Usage: %s \n", argv[0]); + return 1; + } + + curl_global_init(CURL_GLOBAL_ALL); + + /* init the curl session */ + curl_handle = curl_easy_init(); + + /* set URL to get here */ + curl_easy_setopt(curl_handle, CURLOPT_URL, argv[1]); + + /* Switch on full protocol/debug output while testing */ + curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L); + + /* disable progress meter, set to 0L to enable it */ + curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L); + + /* send all data to this function */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data); + + /* open the file */ + pagefile = fopen(pagefilename, "wb"); + if(pagefile) { + + /* write the page body to this file handle */ + curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile); + + /* get it! */ + curl_easy_perform(curl_handle); + + /* close the header file */ + fclose(pagefile); + } + + /* cleanup curl stuff */ + curl_easy_cleanup(curl_handle); + + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/urlapi.c b/local-test-curl-delta-01/afc-curl/docs/examples/urlapi.c new file mode 100644 index 0000000000000000000000000000000000000000..2ed78eb11fc60ee3ac295b4d06eef378b1c19443 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/urlapi.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 + * + ***************************************************************************/ +/* + * Set working URL with CURLU *. + * + */ +#include +#include + +#if !CURL_AT_LEAST_VERSION(7, 80, 0) +#error "this example requires curl 7.80.0 or later" +#endif + +int main(void) +{ + CURL *curl; + CURLcode res; + + CURLU *urlp; + CURLUcode uc; + + /* get a curl handle */ + curl = curl_easy_init(); + + /* init Curl URL */ + urlp = curl_url(); + uc = curl_url_set(urlp, CURLUPART_URL, + "http://example.com/path/index.html", 0); + + if(uc) { + fprintf(stderr, "curl_url_set() failed: %s", curl_url_strerror(uc)); + goto cleanup; + } + + if(curl) { + /* set urlp to use as working URL */ + curl_easy_setopt(curl, CURLOPT_CURLU, urlp); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* only allow HTTP, TFTP and SFTP */ + curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "http,tftp,sftp"); + + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + goto cleanup; + } + +cleanup: + curl_url_cleanup(urlp); + curl_easy_cleanup(curl); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/usercertinmem.c b/local-test-curl-delta-01/afc-curl/docs/examples/usercertinmem.c new file mode 100644 index 0000000000000000000000000000000000000000..7b338cd98aefc850e54ffae435bb1b2ae90a23e8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/usercertinmem.c @@ -0,0 +1,227 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 an in-memory user certificate and RSA key and retrieve an https page. + * + */ +/* Written by Ishan SinghLevett, based on Theo Borm's cacertinmem.c. + * Note that to maintain simplicity this example does not use a CA certificate + * for peer verification. However, some form of peer verification + * must be used in real circumstances when a secure connection is required. + */ + +#include +#include +#include +#include +#include + +static size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) +{ + fwrite(ptr, size, nmemb, stream); + return (nmemb*size); +} + +static CURLcode sslctx_function(CURL *curl, void *sslctx, void *parm) +{ + X509 *cert = NULL; + BIO *bio = NULL; + BIO *kbio = NULL; + RSA *rsa = NULL; + int ret; + + const char *mypem = /* www.cacert.org */ + "-----BEGIN CERTIFICATE-----\n"\ + "MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290\n"\ + "IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB\n"\ + "IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA\n"\ + "Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO\n"\ + "BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi\n"\ + "MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ\n"\ + "ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC\n"\ + "CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ\n"\ + "8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6\n"\ + "zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y\n"\ + "fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7\n"\ + "w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc\n"\ + "G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k\n"\ + "epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q\n"\ + "laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ\n"\ + "QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU\n"\ + "fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826\n"\ + "YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w\n"\ + "ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY\n"\ + "gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe\n"\ + "MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0\n"\ + "IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy\n"\ + "dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw\n"\ + "czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0\n"\ + "dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl\n"\ + "aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC\n"\ + "AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg\n"\ + "b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB\n"\ + "ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc\n"\ + "nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg\n"\ + "18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c\n"\ + "gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl\n"\ + "Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY\n"\ + "sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T\n"\ + "SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF\n"\ + "CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum\n"\ + "GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk\n"\ + "zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW\n"\ + "omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD\n"\ + "-----END CERTIFICATE-----\n"; + +/* replace the XXX with the actual RSA key */ + const char *mykey = + "-----BEGIN RSA PRIVATE KEY-----\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"\ + "-----END RSA PRIVATE KEY-----\n"; + + (void)curl; /* avoid warnings */ + (void)parm; /* avoid warnings */ + + /* get a BIO */ + bio = BIO_new_mem_buf((char *)mypem, -1); + + if(!bio) { + printf("BIO_new_mem_buf failed\n"); + } + + /* use it to read the PEM formatted certificate from memory into an X509 + * structure that SSL can use + */ + cert = PEM_read_bio_X509(bio, NULL, 0, NULL); + if(!cert) { + printf("PEM_read_bio_X509 failed...\n"); + } + + /* tell SSL to use the X509 certificate */ + ret = SSL_CTX_use_certificate((SSL_CTX*)sslctx, cert); + if(ret != 1) { + printf("Use certificate failed\n"); + } + + /* create a bio for the RSA key */ + kbio = BIO_new_mem_buf((char *)mykey, -1); + if(!kbio) { + printf("BIO_new_mem_buf failed\n"); + } + + /* read the key bio into an RSA object */ + rsa = PEM_read_bio_RSAPrivateKey(kbio, NULL, 0, NULL); + if(!rsa) { + printf("Failed to create key bio\n"); + } + + /* tell SSL to use the RSA key from memory */ + ret = SSL_CTX_use_RSAPrivateKey((SSL_CTX*)sslctx, rsa); + if(ret != 1) { + printf("Use Key failed\n"); + } + + /* free resources that have been allocated by OpenSSL functions */ + if(bio) + BIO_free(bio); + + if(kbio) + BIO_free(kbio); + + if(rsa) + RSA_free(rsa); + + if(cert) + X509_free(cert); + + /* all set to go */ + return CURLE_OK; +} + +int main(void) +{ + CURL *ch; + CURLcode rv; + + curl_global_init(CURL_GLOBAL_ALL); + ch = curl_easy_init(); + curl_easy_setopt(ch, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(ch, CURLOPT_HEADER, 0L); + curl_easy_setopt(ch, CURLOPT_NOPROGRESS, 1L); + curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, writefunction); + curl_easy_setopt(ch, CURLOPT_WRITEDATA, stdout); + curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, writefunction); + curl_easy_setopt(ch, CURLOPT_HEADERDATA, stderr); + curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM"); + + /* both VERIFYPEER and VERIFYHOST are set to 0 in this case because there is + no CA certificate */ + + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(ch, CURLOPT_URL, "https://www.example.com/"); + curl_easy_setopt(ch, CURLOPT_SSLKEYTYPE, "PEM"); + + /* first try: retrieve page without user certificate and key -> fails */ + rv = curl_easy_perform(ch); + if(rv == CURLE_OK) { + printf("*** transfer succeeded ***\n"); + } + else { + printf("*** transfer failed ***\n"); + } + + /* second try: retrieve page using user certificate and key -> succeeds + * load the certificate and key by installing a function doing the necessary + * "modifications" to the SSL CONTEXT just before link init + */ + curl_easy_setopt(ch, CURLOPT_SSL_CTX_FUNCTION, sslctx_function); + rv = curl_easy_perform(ch); + if(rv == CURLE_OK) { + printf("*** transfer succeeded ***\n"); + } + else { + printf("*** transfer failed ***\n"); + } + + curl_easy_cleanup(ch); + curl_global_cleanup(); + return rv; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/version-check.pl b/local-test-curl-delta-01/afc-curl/docs/examples/version-check.pl new file mode 100644 index 0000000000000000000000000000000000000000..932d154bdbc29f0c094992ffad4c63a2b3b91e9d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/version-check.pl @@ -0,0 +1,105 @@ +#!/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 +# +########################################################################### + +# This script accepts a source file as input on the command line. +# +# It first loads the 'symbols-in-versions' document and stores a lookup +# table for all known symbols for which version they were introduced. +# +# It then scans the given source file to dig up all symbols starting with CURL. +# Finally, it sorts the internal list of found symbols (using the version +# number as sort key) and then it outputs the most recent version number and +# the symbols from that version that are used. +# +# Usage: +# +# version-check.pl [source file] +# + +open(S, "<../libcurl/symbols-in-versions") || die; + +my %doc; +my %rem; +while() { + if(/(^CURL[^ \n]*) *(.*)/) { + my ($sym, $rest)=($1, $2); + my @a=split(/ +/, $rest); + + $doc{$sym}=$a[0]; # when it was introduced + + if($a[2]) { + # this symbol is documented to have been present the last time + # in this release + $rem{$sym}=$a[2]; + } + } + +} + +close(S); + +sub age { + my ($ver)=@_; + + my @s=split(/\./, $ver); + return $s[0]*10000+$s[1]*100+$s[2]; +} + +my %used; +open(C, "<$ARGV[0]") || die; + +while() { + if(/\W(CURL[_A-Z0-9v]+)\W/) { + #print "$1\n"; + $used{$1}++; + } +} + +close(C); + +sub sortversions { + my $r = age($doc{$a}) <=> age($doc{$b}); + if(!$r) { + $r = $a cmp $b; + } + return $r; +} + +my @recent = reverse sort sortversions keys %used; + +# the most recent symbol +my $newsym = $recent[0]; +# the most recent version +my $newver = $doc{$newsym}; + +print "The scanned source uses these symbols introduced in $newver:\n"; + +for my $w (@recent) { + if($doc{$w} eq $newver) { + printf " $w\n"; + next; + } + last; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/websocket-cb.c b/local-test-curl-delta-01/afc-curl/docs/examples/websocket-cb.c new file mode 100644 index 0000000000000000000000000000000000000000..09d6c647dd196e3e4460a85439acb1c9103d2bb2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/websocket-cb.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 + * + ***************************************************************************/ +/* + * WebSocket download-only using write callback + * + */ +#include +#include + +static size_t writecb(char *b, size_t size, size_t nitems, void *p) +{ + CURL *easy = p; + size_t i; + const struct curl_ws_frame *frame = curl_ws_meta(easy); + fprintf(stderr, "Type: %s\n", frame->flags & CURLWS_BINARY ? + "binary" : "text"); + fprintf(stderr, "Bytes: %u", (unsigned int)(nitems * size)); + for(i = 0; i < nitems; i++) + fprintf(stderr, "%02x ", (unsigned char)b[i]); + return nitems; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, "wss://example.com"); + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecb); + /* pass the easy handle to the callback */ + curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl); + + /* Perform the request, res gets the return code */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/docs/examples/xmlstream.c b/local-test-curl-delta-01/afc-curl/docs/examples/xmlstream.c new file mode 100644 index 0000000000000000000000000000000000000000..d779e6e7cfacef966e059f2aa1f5c26673839ce4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/docs/examples/xmlstream.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 + * + ***************************************************************************/ +/* + * Stream-parse a document using the streaming Expat parser. + * + */ +/* Written by David Strauss + * + * Expat => https://libexpat.github.io/ + * + * gcc -Wall -I/usr/local/include xmlstream.c -lcurl -lexpat -o xmlstream + * + */ + +#include +#include +#include + +#include +#include + +struct MemoryStruct { + char *memory; + size_t size; +}; + +struct ParserStruct { + int ok; + size_t tags; + size_t depth; + struct MemoryStruct characters; +}; + +static void startElement(void *userData, const XML_Char *name, + const XML_Char **atts) +{ + struct ParserStruct *state = (struct ParserStruct *) userData; + state->tags++; + state->depth++; + + /* Get a clean slate for reading in character data. */ + free(state->characters.memory); + state->characters.memory = NULL; + state->characters.size = 0; +} + +static void characterDataHandler(void *userData, const XML_Char *s, int len) +{ + struct ParserStruct *state = (struct ParserStruct *) userData; + struct MemoryStruct *mem = &state->characters; + + char *ptr = realloc(mem->memory, mem->size + len + 1); + if(!ptr) { + /* Out of memory. */ + fprintf(stderr, "Not enough memory (realloc returned NULL).\n"); + state->ok = 0; + return; + } + + mem->memory = ptr; + memcpy(&(mem->memory[mem->size]), s, len); + mem->size += len; + mem->memory[mem->size] = 0; +} + +static void endElement(void *userData, const XML_Char *name) +{ + struct ParserStruct *state = (struct ParserStruct *) userData; + state->depth--; + + printf("%5lu %10lu %s\n", state->depth, state->characters.size, name); +} + +static size_t parseStreamCallback(void *contents, size_t length, size_t nmemb, + void *userp) +{ + XML_Parser parser = (XML_Parser) userp; + size_t real_size = length * nmemb; + struct ParserStruct *state = (struct ParserStruct *) XML_GetUserData(parser); + + /* Only parse if we are not already in a failure state. */ + if(state->ok && XML_Parse(parser, contents, real_size, 0) == 0) { + int error_code = XML_GetErrorCode(parser); + fprintf(stderr, "Parsing response buffer of length %lu failed" + " with error code %d (%s).\n", + real_size, error_code, XML_ErrorString(error_code)); + state->ok = 0; + } + + return real_size; +} + +int main(void) +{ + CURL *curl_handle; + CURLcode res; + XML_Parser parser; + struct ParserStruct state; + + /* Initialize the state structure for parsing. */ + memset(&state, 0, sizeof(struct ParserStruct)); + state.ok = 1; + + /* Initialize a namespace-aware parser. */ + parser = XML_ParserCreateNS(NULL, '\0'); + XML_SetUserData(parser, &state); + XML_SetElementHandler(parser, startElement, endElement); + XML_SetCharacterDataHandler(parser, characterDataHandler); + + /* Initialize a libcurl handle. */ + curl_global_init(CURL_GLOBAL_DEFAULT); + curl_handle = curl_easy_init(); + curl_easy_setopt(curl_handle, CURLOPT_URL, + "https://www.w3schools.com/xml/simple.xml"); + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, parseStreamCallback); + curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)parser); + + printf("Depth Characters Closing Tag\n"); + + /* Perform the request and any follow-up parsing. */ + res = curl_easy_perform(curl_handle); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + } + else if(state.ok) { + /* Expat requires one final call to finalize parsing. */ + if(XML_Parse(parser, NULL, 0, 1) == 0) { + int error_code = XML_GetErrorCode(parser); + fprintf(stderr, "Finalizing parsing failed with error code %d (%s).\n", + error_code, XML_ErrorString(error_code)); + } + else { + printf(" --------------\n"); + printf(" %lu tags total\n", state.tags); + } + } + + /* Clean up. */ + free(state.characters.memory); + XML_ParserFree(parser); + curl_easy_cleanup(curl_handle); + curl_global_cleanup(); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/lib/vauth/.checksrc b/local-test-curl-delta-01/afc-curl/lib/vauth/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..9066946c890dd2d8a5a3fda9c82fbe2baeed8772 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/.checksrc @@ -0,0 +1,2 @@ +enable STRERROR +enable STRNCPY diff --git a/local-test-curl-delta-01/afc-curl/lib/vauth/cleartext.c b/local-test-curl-delta-01/afc-curl/lib/vauth/cleartext.c new file mode 100644 index 0000000000000000000000000000000000000000..cf8108ac5b6af9c6a9af299cf10c17e4e0dae8e3 --- /dev/null +++ b/local-test-curl-delta-01/afc-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 + * username or password ready for sending to the recipient. + * + * Parameters: + * + * valuep [in] - The username 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 username ready for sending to the recipient. + * + * Parameters: + * + * user [in] - The username. + * 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/local-test-curl-delta-01/afc-curl/lib/vauth/cram.c b/local-test-curl-delta-01/afc-curl/lib/vauth/cram.c new file mode 100644 index 0000000000000000000000000000000000000000..c51c7285b478cf6851a812528e7494c6b5869870 --- /dev/null +++ b/local-test-curl-delta-01/afc-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 username. + * 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/local-test-curl-delta-01/afc-curl/lib/vauth/digest.c b/local-test-curl-delta-01/afc-curl/lib/vauth/digest.c new file mode 100644 index 0000000000000000000000000000000000000000..0acfcace1d13abc343cba03ca42add1066f64f85 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/digest.c @@ -0,0 +1,1035 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 did not 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 + Curl_strtok_r() ruins it. */ + tmp = strdup(options); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = Curl_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 = Curl_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 username. + * 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 Curl_strtok_r() ruins it */ + tmp = strdup(content); + if(!tmp) + return CURLE_OUT_OF_MEMORY; + + token = Curl_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 = Curl_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 are 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 is 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 username. + * 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[12]; + result = Curl_rand_bytes(data, +#ifdef DEBUGBUILD + TRUE, +#endif + (unsigned char *)cnoncebuf, + sizeof(cnoncebuf)); + if(result) + return result; + + result = Curl_base64_encode(cnoncebuf, sizeof(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 do not 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 username. + * 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/local-test-curl-delta-01/afc-curl/lib/vauth/digest.h b/local-test-curl-delta-01/afc-curl/lib/vauth/digest.h new file mode 100644 index 0000000000000000000000000000000000000000..99ce1f9138920ae30007411928a57e8536315eac --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vauth/digest_sspi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/digest_sspi.c new file mode 100644 index 0000000000000000000000000000000000000000..2ae6fb30c93c110314af284a33de3a26002d6e91 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/digest_sspi.c @@ -0,0 +1,676 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 = + Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK); +} + +/* + * 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 username 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 = + Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_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 = Curl_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 = Curl_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) + Curl_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 + + Curl_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 */ + Curl_pSecFn->DeleteSecurityContext(&context); + Curl_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 are 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 is another one now that means we + provided bad credentials in the previous request or it is 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 username 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 = + Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_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) { + Curl_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 = Curl_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); + Curl_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 = Curl_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) { + Curl_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 = Curl_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) + Curl_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 + + Curl_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; + + Curl_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) { + Curl_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/local-test-curl-delta-01/afc-curl/lib/vauth/gsasl.c b/local-test-curl-delta-01/afc-curl/lib/vauth/gsasl.c new file mode 100644 index 0000000000000000000000000000000000000000..ee11b6039d69aa91c1bd98b0ba44c7ac961cdf97 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vauth/krb5_gssapi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/krb5_gssapi.c new file mode 100644 index 0000000000000000000000000000000000000000..e79278283800621f1dcd91841d93e2ff769f5367 --- /dev/null +++ b/local-test-curl-delta-01/afc-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 username. + * passwdp [in] - The user's password. + * service [in] - The service type such as http, smtp, pop or imap. + * host [in[ - The hostname. + * 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 do not 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/local-test-curl-delta-01/afc-curl/lib/vauth/krb5_sspi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/krb5_sspi.c new file mode 100644 index 0000000000000000000000000000000000000000..4af0bd1e134d86ba532d892169d213083cb0a08c --- /dev/null +++ b/local-test-curl-delta-01/afc-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 = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_KERBEROS), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK); +} + +/* + * 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 username 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 hostname. + * 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 = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_KERBEROS), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + krb5->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_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 = Curl_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 = Curl_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))) { + Curl_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 = Curl_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 = Curl_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 */ + Curl_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 do not 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 = Curl_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) { + Curl_pSecFn->DeleteSecurityContext(krb5->context); + free(krb5->context); + krb5->context = NULL; + } + + /* Free our credentials handle */ + if(krb5->credentials) { + Curl_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/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm.c b/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm.c new file mode 100644 index 0000000000000000000000000000000000000000..f8f6aea0e9e25c04c0c813bb1ebadc839d40edb6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm.c @@ -0,0 +1,764 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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" + +#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 username 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 hostname. + * 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" /* hostname offset */ + "%c%c" /* 2 zeroes */ + "%s" /* hostname */ + "%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 username 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 username 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]; + unsigned int lmrespoff; + unsigned char lmresp[24]; /* fixed-size */ + unsigned 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); + /* The fixed hostname we provide, in order to not leak our real local host + name. Copy the name used by Firefox. */ + static const char host[] = "WORKSTATION"; + 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); + hostlen = sizeof(host) - 1; + + 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 &= ~(unsigned int)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 + hostname 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/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm.h b/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm.h new file mode 100644 index 0000000000000000000000000000000000000000..31ce921cd1284f674198a7b3d0c7f263a1e7752b --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm_sspi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/ntlm_sspi.c new file mode 100644 index 0000000000000000000000000000000000000000..a2e5bc102696beab6fdc408fb25020adccd0bb3e --- /dev/null +++ b/local-test-curl-delta-01/afc-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 = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + return (status == SEC_E_OK); +} + +/* + * 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 username 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 hostname. + * 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 = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), + &SecurityPackage); + if(status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + ntlm->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_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 = Curl_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 = Curl_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) + Curl_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 username 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 = Curl_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 = Curl_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) { + Curl_pSecFn->DeleteSecurityContext(ntlm->context); + free(ntlm->context); + ntlm->context = NULL; + } + + /* Free our credentials handle */ + if(ntlm->credentials) { + Curl_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/local-test-curl-delta-01/afc-curl/lib/vauth/oauth2.c b/local-test-curl-delta-01/afc-curl/lib/vauth/oauth2.c new file mode 100644 index 0000000000000000000000000000000000000000..dc94afa365dc3f6e03a4f7186eed624c955cd868 --- /dev/null +++ b/local-test-curl-delta-01/afc-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 username. + * host[in] - The hostname. + * 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 username. + * 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/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_gssapi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_gssapi.c new file mode 100644 index 0000000000000000000000000000000000000000..f48d9b7000b257937b850b6b137fec11cff8b020 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_gssapi.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 + * + * 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 username 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 hostname. + * 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; + gss_channel_bindings_t chan_bindings = GSS_C_NO_CHANNEL_BINDINGS; + struct gss_channel_bindings_struct chan; + + (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 are again here). Exit with an error since we + * cannot 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; + } + + /* Set channel binding data if available */ + if(nego->channel_binding_data.leng > 0) { + memset(&chan, 0, sizeof(struct gss_channel_bindings_struct)); + chan.application_data.length = nego->channel_binding_data.leng; + chan.application_data.value = nego->channel_binding_data.bufr; + chan_bindings = &chan; + } + + /* Generate our challenge-response message */ + major_status = Curl_gss_init_sec_context(data, + &minor_status, + &nego->context, + nego->spn, + &Curl_spnego_mech_oid, + chan_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/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_sspi.c b/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_sspi.c new file mode 100644 index 0000000000000000000000000000000000000000..7a27c298fc11a9d33c945ca3c86ad58354494bd4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/spnego_sspi.c @@ -0,0 +1,365 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_NEGOTIATE), + &SecurityPackage); + + /* Release the package buffer as it is not required anymore */ + if(status == SEC_E_OK) { + Curl_pSecFn->FreeContextBuffer(SecurityPackage); + } + + + return (status == SEC_E_OK); +} + +/* + * 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 username 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 hostname. + * 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 are again here). Exit with an error since we + * cannot 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 = (DWORD)Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *) + TEXT(SP_NAME_NEGOTIATE), + &SecurityPackage); + if(nego->status != SEC_E_OK) { + failf(data, "SSPI: could not get auth info"); + return CURLE_AUTH_ERROR; + } + + nego->token_max = SecurityPackage->cbMaxToken; + + /* Release the package buffer as it is not required anymore */ + Curl_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 = (DWORD) + Curl_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 = (DWORD)Curl_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 = + (DWORD)Curl_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((int)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 = (DWORD)Curl_pSecFn->CompleteAuthToken(nego->context, + &resp_desc); + if(GSS_ERROR(nego->status)) { + char buffer[STRERROR_LEN]; + failf(data, "CompleteAuthToken failed: %s", + Curl_sspi_strerror((int)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) { + Curl_pSecFn->DeleteSecurityContext(nego->context); + free(nego->context); + nego->context = NULL; + } + + /* Free our credentials handle */ + if(nego->credentials) { + Curl_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/local-test-curl-delta-01/afc-curl/lib/vauth/vauth.c b/local-test-curl-delta-01/afc-curl/lib/vauth/vauth.c new file mode 100644 index 0000000000000000000000000000000000000000..a7e7e17f3b236d77b487138d094dbf9186d2f608 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vauth/vauth.c @@ -0,0 +1,162 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 hostname. + * 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 will 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 username 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 username. + * + * 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); + } +#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/local-test-curl-delta-01/afc-curl/lib/vauth/vauth.h b/local-test-curl-delta-01/afc-curl/lib/vauth/vauth.h new file mode 100644 index 0000000000000000000000000000000000000000..7e823484f68dacc2b1af4f1a3b5a27c53e7070bb --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/.checksrc b/local-test-curl-delta-01/afc-curl/lib/vquic/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..9066946c890dd2d8a5a3fda9c82fbe2baeed8772 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/.checksrc @@ -0,0 +1,2 @@ +enable STRERROR +enable STRNCPY diff --git a/local-test-curl-delta-01/afc-curl/lib/vquic/curl_msh3.c b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_msh3.c new file mode 100644 index 0000000000000000000000000000000000000000..fe812f87d2a4bdd57398f335aa92ded702fe2d19 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_msh3.c @@ -0,0 +1,1120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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->mid` to `stream_ctx` */ + /* Flags written by msh3/msquic thread */ + bool handshake_complete; + bool handshake_succeeded; + bool connected; + BIT(initialized); + /* Flags written by curl thread */ + BIT(verbose); + BIT(active); +}; + +static void h3_stream_hash_free(void *stream); + +static void cf_msh3_ctx_init(struct cf_msh3_ctx *ctx, + const struct Curl_addrinfo *ai) +{ + DEBUGASSERT(!ctx->initialized); + Curl_hash_offt_init(&ctx->streams, 63, h3_stream_hash_free); + Curl_sock_assign_addr(&ctx->addr, ai, TRNSPRT_QUIC); + ctx->sock[SP_LOCAL] = CURL_SOCKET_BAD; + ctx->sock[SP_REMOTE] = CURL_SOCKET_BAD; + ctx->initialized = TRUE; +} + +static void cf_msh3_ctx_free(struct cf_msh3_ctx *ctx) +{ + if(ctx && ctx->initialized) { + Curl_hash_destroy(&ctx->streams); + } + free(ctx); +} + +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)->mid) : 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->mid, 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->mid); + } +} + +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 h3_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) + h3_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, bool eos, + 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; + + 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; + } + + 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 does not 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]); + h3_drain_stream(cf, data); + } + else if(stream->req) { + Curl_pollset_add_out(data, ps, ctx->sock[SP_LOCAL]); + h3_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) + h3_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) { + h3_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; + + DEBUGASSERT(ctx->initialized); + conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!conn_config) + return CURLE_FAILED_INIT; + verify = !!conn_config->verifypeer; + + memcpy(&addr, &ctx->addr.curl_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, "cannot 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, "cannot 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], FALSE) < 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->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; + } + + 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); + if(cf->ctx) { + cf_msh3_ctx_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_shutdown, + 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; + } + cf_msh3_ctx_init(ctx, ai); + + result = Curl_cf_create(&cf, &Curl_cft_http3, ctx); + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + Curl_safefree(cf); + cf_msh3_ctx_free(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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_msh3.h b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_msh3.h new file mode 100644 index 0000000000000000000000000000000000000000..33931f59bbcfd2a85b76e2ba7b6911a3ae6f30da --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_ngtcp2.c b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_ngtcp2.c new file mode 100644 index 0000000000000000000000000000000000000000..37009abdc16004e31b03648a96be7cd9020a5c89 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_ngtcp2.c @@ -0,0 +1,2613 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 +#include "vtls/wolfssl.h" +#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. 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 bufc_pool stream_bufcp; /* chunk pool for streams */ + struct dynbuf scratch; /* temp buffer for header construction */ + struct Curl_hash streams; /* hash `data->mid` 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(initialized); + BIT(shutdown_started); /* queued shutdown packets */ +}; + +/* 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 + +static void h3_stream_hash_free(void *stream); + +static void cf_ngtcp2_ctx_init(struct cf_ngtcp2_ctx *ctx) +{ + DEBUGASSERT(!ctx->initialized); + ctx->qlogfd = -1; + 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); + ctx->initialized = TRUE; +} + +static void cf_ngtcp2_ctx_free(struct cf_ngtcp2_ctx *ctx) +{ + if(ctx && ctx->initialized) { + 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); + } + free(ctx); +} + +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" */ + 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)->mid) : 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) + 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->mid, 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, "[%" FMT_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, "[%" FMT_PRId64 "] easy handle is done", + stream->id); + cf_ngtcp2_stream_close(cf, data, stream); + Curl_hash_offt_remove(&ctx->streams, data->mid); + } +} + +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 h3_stream_ctx *stream; + + (void)cf; + stream = H3_STREAM_CTX(ctx, data); + if(stream && stream->id == stream_id) { + *pstream = stream; + return data; + } + else { + struct Curl_llist_node *e; + DEBUGASSERT(data->multi); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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; + 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 = (ngtcp2_tstamp)ctx->q.last_op.tv_sec * NGTCP2_SECONDS + + (ngtcp2_tstamp)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; + 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 = 10 * 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 CURLcode 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, "[%" FMT_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, "[%" FMT_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, (uint64_t)nconsumed); + ngtcp2_conn_extend_max_offset(tconn, (uint64_t)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, "[%" FMT_PRId64 "] quic close(app_error=%" + FMT_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, "[%" FMT_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 %" FMT_PRIu64 + ", used %" FMT_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, "[%" FMT_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; +} + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(push) +# pragma warning(disable:4232) /* MSVC extension, dllimport identity */ +#endif + +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 */ +}; + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(pop) +#endif + +/** + * 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, (timediff_t)(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_send && !Curl_bufq_is_empty(&ctx->q.sendbuf)) + want_send = TRUE; + + 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, "[%" FMT_PRId64 "] RESET: error %" FMT_PRIu64, + stream->id, stream->error3); + } + else { + CURL_TRC_CF(data, cf, "[%" FMT_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, "[%"FMT_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, "[%"FMT_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, "[%" FMT_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, "[%" FMT_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 have received some headers */ + h3_xfer_write_resp_hd(cf, data, stream, STRCONST("\r\n"), stream->closed); + + CURL_TRC_CF(data, cf, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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 NGHTTP3_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, "[%" FMT_PRId64 "] reset -> %d", stream_id, rv); + if(rv && rv != NGTCP2_ERR_STREAM_NOT_FOUND) { + return NGHTTP3_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 CURLcode 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 %" FMT_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 %" FMT_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->shutdown_started) { + *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, "[%" FMT_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, "[%" FMT_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; + + /* Resume upload processing if we have more data to send */ + if(stream->sendbuf_len_in_flight < Curl_bufq_len(&stream->sendbuf)) { + 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_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, "[%" FMT_PRId64 "] read req body -> AGAIN", + stream->id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" FMT_PRId64 "] read req body -> " + "%d vecs%s with %zu (buffered=%zu, left=%" FMT_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[%" FMT_PRId64 "] failed to send, " + "connection is closing", stream->id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%" FMT_PRId64 "] failed to send -> " + "%d (%s)", stream->id, rc, nghttp3_strerror(rc)); + break; + } + *err = CURLE_SEND_ERROR; + nwritten = -1; + goto out; + } + + if(Curl_trc_is_verbose(data)) { + infof(data, "[HTTP/3] [%" FMT_PRId64 "] OPENED stream for %s", + stream->id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" FMT_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, bool eos, + 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; + + (void)eos; /* TODO: use for stream EOF and block handling */ + result = cf_progress_ingress(cf, data, &pktx); + if(result) { + *err = result; + sent = -1; + } + + if(!stream || stream->id < 0) { + if(ctx->shutdown_started) { + 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, "[%" FMT_PRId64 "] xfer write failed", stream->id); + cf_ngtcp2_stream_close(cf, data, stream); + *err = stream->xfer_result; + sent = -1; + goto out; + } + 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, "[%" FMT_PRId64 "] discarding data" + "on closed stream with response", stream->id); + *err = CURLE_OK; + sent = (ssize_t)len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" FMT_PRId64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + *err = CURLE_HTTP3; + sent = -1; + goto out; + } + else if(ctx->shutdown_started) { + 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, "[%" FMT_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; + } + +out: + result = check_and_set_expiry(cf, data, &pktx); + if(result) { + *err = result; + sent = -1; + } + CURL_TRC_CF(data, cf, "[%" FMT_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; + + 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; + + ngtcp2_addr_init(&path.local, (struct sockaddr *)&ctx->q.local_addr, + (socklen_t)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; + CURLcode result = CURLE_OK; + + if(!pktx) { + pktx_init(&local_pktx, cf, data); + pktx = &local_pktx; + } + + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + return result; + + return vquic_recv_packets(cf, data, &ctx->q, 1000, recv_pkt, pktx); +} + +/** + * 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, "[%" FMT_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 will 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) - + stream->sendbuf_len_in_flight; + (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_close(struct cf_ngtcp2_ctx *ctx) +{ + struct cf_call_data save = ctx->call_data; + + if(!ctx->initialized) + return; + if(ctx->qlogfd != -1) { + close(ctx->qlogfd); + } + ctx->qlogfd = -1; + 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); + ctx->call_data = save; +} + +static CURLcode cf_ngtcp2_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct cf_call_data save; + struct pkt_io_ctx pktx; + CURLcode result = CURLE_OK; + + if(cf->shutdown || !ctx->qconn) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + *done = FALSE; + pktx_init(&pktx, cf, data); + + if(!ctx->shutdown_started) { + char buffer[NGTCP2_MAX_UDP_PAYLOAD_SIZE]; + ngtcp2_ssize nwritten; + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing sendbuf"); + result = cf_progress_egress(cf, data, &pktx); + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "sending shutdown packets blocked"); + result = CURLE_OK; + goto out; + } + else if(result) { + CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf", result); + *done = TRUE; + goto out; + } + } + + ctx->shutdown_started = TRUE; + nwritten = 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, "start shutdown(err_type=%d, err_code=%" + FMT_PRIu64 ") -> %d", ctx->last_error.type, + (curl_uint64_t)ctx->last_error.error_code, (int)nwritten); + if(nwritten > 0) { + Curl_bufq_write(&ctx->q.sendbuf, (const unsigned char *)buffer, + (size_t)nwritten, &result); + if(result) { + CURL_TRC_CF(data, cf, "error %d adding shutdown packets to sendbuf, " + "aborting shutdown", result); + goto out; + } + ctx->q.no_gso = TRUE; + ctx->q.gsolen = (size_t)nwritten; + ctx->q.split_len = 0; + } + } + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing egress"); + result = vquic_flush(cf, data, &ctx->q); + if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "sending shutdown packets blocked"); + result = CURLE_OK; + goto out; + } + else if(result) { + CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf", result); + *done = TRUE; + goto out; + } + } + + if(Curl_bufq_is_empty(&ctx->q.sendbuf)) { + /* Sent everything off. ngtcp2 seems to have no support for graceful + * shutdowns. So, we are done. */ + CURL_TRC_CF(data, cf, "shutdown completely sent off, done"); + *done = TRUE; + result = CURLE_OK; + } +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +static void cf_ngtcp2_conn_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + bool done; + cf_ngtcp2_shutdown(cf, data, &done); +} + +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_close(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) +{ + CURL_TRC_CF(data, cf, "destroy"); + if(cf->ctx) { + cf_ngtcp2_ctx_free(cf->ctx); + cf->ctx = NULL; + } +} + +#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 */ + +#ifdef USE_GNUTLS +static int quic_gtls_handshake_cb(gnutls_session_t session, unsigned int htype, + unsigned when, unsigned int incoming, + const gnutls_datum_t *msg) +{ + ngtcp2_crypto_conn_ref *conn_ref = gnutls_session_get_ptr(session); + struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL; + struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL; + + (void)msg; + (void)incoming; + if(when && cf && ctx) { /* after message has been processed */ + struct Curl_easy *data = CF_DATA_CURRENT(cf); + DEBUGASSERT(data); + if(data) { + CURL_TRC_CF(data, cf, "handshake: %s message type %d", + incoming ? "incoming" : "outgoing", htype); + } + switch(htype) { + case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: { + (void)Curl_gtls_update_session_id(cf, data, session, &ctx->peer, "h3"); + break; + } + default: + break; + } + } + return 0; +} +#endif /* USE_GNUTLS */ + +#ifdef USE_WOLFSSL +static int wssl_quic_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) +{ + ngtcp2_crypto_conn_ref *conn_ref = wolfSSL_get_app_data(ssl); + struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL; + + DEBUGASSERT(cf != NULL); + if(cf && session) { + struct cf_ngtcp2_ctx *ctx = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + DEBUGASSERT(data); + if(data && ctx) { + (void)wssl_cache_session(cf, data, &ctx->peer, session); + } + } + return 0; +} +#endif /* USE_WOLFSSL */ + +static CURLcode tls_ctx_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + void *user_data) +{ + struct curl_tls_ctx *ctx = user_data; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + +#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 */ + if(ssl_config->primary.cache_session) { + /* Enable the session cache because it is 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; + } + if(ssl_config->primary.cache_session) { + gnutls_handshake_set_hook_function(ctx->gtls.session, + GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST, + quic_gtls_handshake_cb); + } + +#elif defined(USE_WOLFSSL) + if(ngtcp2_crypto_wolfssl_configure_client_context(ctx->wssl.ctx) != 0) { + failf(data, "ngtcp2_crypto_wolfssl_configure_client_context failed"); + return CURLE_FAILED_INIT; + } + if(ssl_config->primary.cache_session) { + /* Register to get notified when a new session is received */ + wolfSSL_CTX_sess_set_new_cb(ctx->wssl.ctx, wssl_quic_new_session_cb); + } +#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; + + DEBUGASSERT(ctx->initialized); + 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->curl_sa_addr, (socklen_t)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); +#elif defined(USE_WOLFSSL) + ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.wssl.handle); +#else + #error "ngtcp2 TLS backend not defined" +#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->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->shutdown_started) { + *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 = (int)Curl_multi_max_concurrent_streams(data->multi); + CURL_TRC_CF(data, cf, "query conn[%" FMT_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->shutdown_started) + 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 have sent off a request and the connection is + not in use by any other transfer, there should not 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, + cf_ngtcp2_shutdown, + 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; + } + cf_ngtcp2_ctx_init(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); + cf_ngtcp2_ctx_free(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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_ngtcp2.h b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_ngtcp2.h new file mode 100644 index 0000000000000000000000000000000000000000..db3e611bd0c84e273271238702b99e3077d13a17 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_osslq.c b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_osslq.c new file mode 100644 index 0000000000000000000000000000000000000000..e5f737f8f0ab12bc6a46bd8f50742da3a67699b2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_osslq.c @@ -0,0 +1,2397 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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. 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->curl_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->curl_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 = (curl_int64_t)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 bufc_pool stream_bufcp; /* chunk pool for streams */ + struct Curl_hash streams; /* hash `data->mid` 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(initialized); + BIT(got_first_byte); /* if first byte was received */ + BIT(x509_store_setup); /* if x509 store has been set up */ + BIT(protocol_shutdown); /* QUIC connection is shut down */ + BIT(need_recv); /* QUIC connection needs to receive */ + BIT(need_send); /* QUIC connection needs to send */ +}; + +static void h3_stream_hash_free(void *stream); + +static void cf_osslq_ctx_init(struct cf_osslq_ctx *ctx) +{ + DEBUGASSERT(!ctx->initialized); + 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->initialized = TRUE; +} + +static void cf_osslq_ctx_free(struct cf_osslq_ctx *ctx) +{ + if(ctx && ctx->initialized) { + Curl_bufcp_free(&ctx->stream_bufcp); + Curl_hash_clean(&ctx->streams); + Curl_hash_destroy(&ctx->streams); + Curl_ssl_peer_cleanup(&ctx->peer); + } + free(ctx); +} + +static void cf_osslq_ctx_close(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); + ctx->call_data = save; +} + +static CURLcode cf_osslq_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_osslq_ctx *ctx = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + int rc; + + CF_DATA_SAVE(save, cf, data); + + if(cf->shutdown || ctx->protocol_shutdown) { + *done = TRUE; + return CURLE_OK; + } + + CF_DATA_SAVE(save, cf, data); + *done = FALSE; + ctx->need_send = FALSE; + ctx->need_recv = FALSE; + + rc = SSL_shutdown_ex(ctx->tls.ossl.ssl, + SSL_SHUTDOWN_FLAG_NO_BLOCK, NULL, 0); + if(rc == 0) { /* ongoing */ + CURL_TRC_CF(data, cf, "shutdown ongoing"); + ctx->need_recv = TRUE; + goto out; + } + else if(rc == 1) { /* done */ + CURL_TRC_CF(data, cf, "shutdown finished"); + *done = TRUE; + goto out; + } + else { + long sslerr; + char err_buffer[256]; + int err = SSL_get_error(ctx->tls.ossl.ssl, rc); + + switch(err) { + case SSL_ERROR_NONE: + case SSL_ERROR_ZERO_RETURN: + CURL_TRC_CF(data, cf, "shutdown not received, but closed"); + *done = TRUE; + goto out; + 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, "shutdown sent, want receive"); + ctx->need_recv = TRUE; + goto out; + case SSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "shutdown send blocked"); + ctx->need_send = TRUE; + goto out; + default: + /* We give up on this. */ + sslerr = ERR_get_error(); + CURL_TRC_CF(data, cf, "shutdown, ignore recv error: '%s', errno %d", + (sslerr ? + osslq_strerror(sslerr, err_buffer, sizeof(err_buffer)) : + osslq_SSL_ERROR_to_str(err)), + SOCKERRNO); + *done = TRUE; + result = CURLE_OK; + goto out; + } + } +out: + CF_DATA_RESTORE(cf, save); + return result; +} + +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) { + CURL_TRC_CF(data, cf, "cf_osslq_close()"); + if(!cf->shutdown && !ctx->protocol_shutdown) { + /* last best effort, which OpenSSL calls a "rapid" shutdown. */ + SSL_shutdown_ex(ctx->tls.ossl.ssl, + (SSL_SHUTDOWN_FLAG_NO_BLOCK | SSL_SHUTDOWN_FLAG_RAPID), + NULL, 0); + } + cf_osslq_ctx_close(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()"); + if(ctx->tls.ossl.ssl) + cf_osslq_ctx_close(ctx); + cf_osslq_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; + curl_int64_t stream_id = (curl_int64_t)SSL_get_stream_id(stream_ssl); + + if(h3->remote_ctrl_n >= ARRAYSIZE(h3->remote_ctrl)) { + /* rejected, we are full */ + CURL_TRC_CF(data, cf, "[%" FMT_PRId64 "] rejecting remote stream", + 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, "[%" FMT_PRId64 "] accepted remote uni stream", + stream_id); + break; + } + default: + CURL_TRC_CF(data, cf, "[%" FMT_PRId64 "] reject remote non-uni-read" + " stream", 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 does not 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; + + 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 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)->mid) : 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) + 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->mid, 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, "[%"FMT_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->mid); + } +} + +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); + + 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 { + struct Curl_llist_node *e; + DEBUGASSERT(data->multi); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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, "[%" FMT_PRId64 "] RESET: error %" FMT_PRIu64, + stream->s.id, stream->error3); + } + else { + CURL_TRC_CF(data, cf, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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 have received some headers */ + result = write_resp_raw(cf, data, "\r\n", 2, FALSE); + if(result) { + return -1; + } + + CURL_TRC_CF(data, cf, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_PRId64 "] read req body -> AGAIN", + stream->s.id); + return NGHTTP3_ERR_WOULDBLOCK; + } + + CURL_TRC_CF(data, cf, "[%" FMT_PRId64 "] read req body -> " + "%d vecs%s with %zu (buffered=%zu, left=%" FMT_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; + + /* Resume upload processing if we have more data to send */ + if(stream->sendbuf_len_in_flight < Curl_bufq_len(&stream->sendbuf)) { + 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; + + DEBUGASSERT(ctx->initialized); + 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, "[%" FMT_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, "[%" FMT_PRId64 "] h3_quic_recv -> RESET, " + "rv=%d, app_err=%" FMT_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; + bool 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, "[%" FMT_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) { + int rv; + 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, "[%" FMT_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, "[%" FMT_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_llist_node *e; + struct h3_stream_ctx *stream; + /* PULL all open streams */ + DEBUGASSERT(data->multi); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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 h3_stream_ctx *stream; + + if(ctx->h3.conn) { + struct Curl_llist_node *e; + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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 %" + FMT_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. */ + 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; + if(ok) { + /* As OpenSSL buffers the data, we count this as acknowledged + * from nghttp3's point of view */ + CURL_TRC_CF(data, cf, "[%" FMT_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, "[%"FMT_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, "[%"FMT_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, "[%" FMT_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, "[%" FMT_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 = 1; + + 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->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(); + } + } + + /* Since OpenSSL does its own send/recv internally, we may miss the + * moment to populate the x509 store right before the server response. + * Do it instead before we start the handshake, at the loss of the + * time to set this up. */ + result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data); + if(result) + goto out; + + 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"); + 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, "cannot 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[%"FMT_PRId64"] failed to send, " + "connection is closing", stream->s.id); + break; + default: + CURL_TRC_CF(data, cf, "h3sid[%"FMT_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] [%" FMT_PRId64 "] OPENED stream for %s", + stream->s.id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" FMT_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, bool eos, + 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; + + (void)eos; /* TODO: use to end stream */ + 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->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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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; + } + +out: + result = check_and_set_expiry(cf, data); + CURL_TRC_CF(data, cf, "[%" FMT_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 %" FMT_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 %" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_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) - + stream->sendbuf_len_in_flight; + (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 have sent off a request and the connection is + not in use by any other transfer, there should not 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)); + } + else if(ctx->need_recv || ctx->need_send) { + Curl_pollset_set(data, ps, ctx->q.sockfd, + ctx->need_recv, ctx->need_send); + } + } +} + +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, + cf_osslq_shutdown, + 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_init(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); + cf_osslq_ctx_free(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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_osslq.h b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_osslq.h new file mode 100644 index 0000000000000000000000000000000000000000..0e12d7023e0b18a9b044a74d5fdd423b379217a1 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_quiche.c b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_quiche.c new file mode 100644 index 0000000000000000000000000000000000000000..304849892ce84f8a43c9912cadaf7d4275aa7b35 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_quiche.c @@ -0,0 +1,1698 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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. 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 bufc_pool stream_bufcp; /* chunk pool for streams */ + struct Curl_hash streams; /* hash `data->mid` to `stream_ctx` */ + curl_off_t data_recvd; + BIT(initialized); + BIT(goaway); /* got GOAWAY from server */ + BIT(x509_store_setup); /* if x509 store has been set up */ + BIT(shutdown_started); /* queued shutdown packets */ +}; + +#ifdef DEBUG_QUICHE +/* initialize debug log callback only once */ +static int debug_log_init = 0; +static void quiche_debug_log(const char *line, void *argp) +{ + (void)argp; + fprintf(stderr, "%s\n", line); +} +#endif + +static void h3_stream_hash_free(void *stream); + +static void cf_quiche_ctx_init(struct cf_quiche_ctx *ctx) +{ + DEBUGASSERT(!ctx->initialized); +#ifdef DEBUG_QUICHE + 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; + ctx->initialized = TRUE; +} + +static void cf_quiche_ctx_free(struct cf_quiche_ctx *ctx) +{ + if(ctx && ctx->initialized) { + /* 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); + } + free(ctx); +} + +static void cf_quiche_ctx_close(struct cf_quiche_ctx *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); +} + +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 */ + 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)->mid) : 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_llist_node *e; + + DEBUGASSERT(data->multi); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + if(sdata->conn == data->conn) { + struct stream_ctx *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, "[%"FMT_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->mid, 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, "[%"FMT_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->mid); + } +} + +static void h3_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) + 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 stream_ctx *stream; + + (void)cf; + stream = H3_STREAM_CTX(ctx, data); + if(stream && stream->id == stream_id) { + *pstream = stream; + return data; + } + else { + struct Curl_llist_node *e; + DEBUGASSERT(data->multi); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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_llist_node *e; + + DEBUGASSERT(data->multi); + CURL_TRC_CF(data, cf, "conn closed, expire all transfers"); + for(e = Curl_llist_head(&data->multi->process); e; e = Curl_node_next(e)) { + struct Curl_easy *sdata = Curl_node_elem(e); + 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, "[%" FMT_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, "[%" FMT_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, "[%"FMT_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, "[%"FMT_PRIu64"] recv_body error %zd", + stream->id, nwritten); + failf(data, "Error %d in HTTP/3 response body for stream[%"FMT_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[%" + FMT_PRIu64"]", rc, stream->id); + return CURLE_RECV_ERROR; + } + CURL_TRC_CF(data, cf, "[%"FMT_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, "[%"FMT_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, "[%"FMT_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, "[%"FMT_PRIu64"] <- [GOAWAY]", stream->id); + break; + + default: + CURL_TRC_CF(data, cf, "[%"FMT_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: %"FMT_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 [%"FMT_PRId64"]", + cf_ev_name(ev), stream3_id); + } + else { + result = h3_process_event(cf, sdata, stream, ev); + h3_drain_stream(cf, sdata); + if(result) { + CURL_TRC_CF(data, cf, "error processing event %s " + "for [%"FMT_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 %" FMT_PRIu64 " reset by server", stream->id); + *err = data->req.bytecount ? CURLE_PARTIAL_FILE : CURLE_HTTP3; + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] cf_recv, was reset -> %d", + stream->id, *err); + } + else if(!stream->resp_got_header) { + failf(data, + "HTTP/3 stream %" FMT_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, "[%" FMT_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, "[%" FMT_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, "[%" FMT_PRIu64 "] read recvbuf(len=%zu) " + "-> %zd, %d", stream->id, len, nread, *err); + if(nread < 0) + goto out; + } + + if(nread > 0) { + if(stream->closed) + h3_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, "[%"FMT_PRIu64"] cf_recv(total=%" + FMT_OFF_T ") -> %zd, %d", + stream->id, ctx->data_recvd, nread, *err); + return nread; +} + +static ssize_t cf_quiche_send_body(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct stream_ctx *stream, + const void *buf, size_t len, bool eos, + CURLcode *err) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + ssize_t nwritten; + + nwritten = quiche_h3_send_body(ctx->h3c, ctx->qconn, stream->id, + (uint8_t *)buf, len, eos); + 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, "[%" FMT_PRIu64 "] send_body(len=%zu) " + "-> window exhausted", stream->id, len); + stream->quic_flow_blocked = TRUE; + } + *err = CURLE_AGAIN; + return -1; + } + else if(nwritten == QUICHE_H3_TRANSPORT_ERR_INVALID_STREAM_STATE) { + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] send_body(len=%zu) " + "-> invalid stream state", stream->id, len); + *err = CURLE_HTTP3; + return -1; + } + else if(nwritten == QUICHE_H3_TRANSPORT_ERR_FINAL_SIZE) { + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] send_body(len=%zu) " + "-> exceeds size", stream->id, len); + *err = CURLE_SEND_ERROR; + return -1; + } + else if(nwritten < 0) { + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] send_body(len=%zu) " + "-> quiche err %zd", stream->id, len, nwritten); + *err = CURLE_SEND_ERROR; + return -1; + } + else { + if(eos && (len == (size_t)nwritten)) + stream->send_closed = TRUE; + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] send body(len=%zu, " + "eos=%d) -> %zd", + stream->id, len, stream->send_closed, nwritten); + *err = CURLE_OK; + return nwritten; + } +} + +/* 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 char *buf, size_t len, bool eos, + 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; + } + + if(eos && ((size_t)nwritten == len)) + 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, "[%"FMT_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) -> %" FMT_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] [%" FMT_PRIu64 "] OPENED stream for %s", + stream->id, data->state.url); + for(i = 0; i < nheader; ++i) { + infof(data, "[HTTP/3] [%" FMT_PRIu64 "] [%.*s: %.*s]", stream->id, + (int)nva[i].name_len, nva[i].name, + (int)nva[i].value_len, nva[i].value); + } + } + + if(nwritten > 0 && ((size_t)nwritten < len)) { + /* after the headers, there was request BODY data */ + size_t hds_len = (size_t)nwritten; + ssize_t bwritten; + + bwritten = cf_quiche_send_body(cf, data, stream, + buf + hds_len, len - hds_len, eos, err); + if((bwritten < 0) && (CURLE_AGAIN != *err)) { + /* real error, fail */ + nwritten = -1; + } + else if(bwritten > 0) { + nwritten += bwritten; + } + } + +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, bool eos, + 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, eos, 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, "[%" FMT_PRIu64 "] discarding data" + "on closed stream with response", stream->id); + *err = CURLE_OK; + nwritten = (ssize_t)len; + goto out; + } + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] send_body(len=%zu) " + "-> stream closed", stream->id, len); + *err = CURLE_HTTP3; + nwritten = -1; + goto out; + } + else { + nwritten = cf_quiche_send_body(cf, data, stream, buf, len, eos, err); + } + +out: + result = cf_flush_egress(cf, data); + if(result) { + *err = result; + nwritten = -1; + } + CURL_TRC_CF(data, cf, "[%" FMT_PRIu64 "] cf_send(len=%zu) -> %zd, %d", + stream ? stream->id : (curl_uint64_t)~0, 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) { + h3_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; + body[0] = 'X'; + sent = cf_quiche_send(cf, data, body, 0, TRUE, &result); + CURL_TRC_CF(data, cf, "[%"FMT_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_quiche_ctx_open(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); + DEBUGASSERT(ctx->initialized); + + 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, "cannot 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->curl_sa_addr, + sockaddr->addrlen, + ctx->cfg, ctx->tls.ossl.ssl, FALSE); + if(!ctx->qconn) { + failf(data, "cannot 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; + + 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->qconn) { + result = cf_quiche_ctx_open(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 CURLcode cf_quiche_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done) +{ + struct cf_quiche_ctx *ctx = cf->ctx; + CURLcode result = CURLE_OK; + + if(cf->shutdown || !ctx || !ctx->qconn) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(!ctx->shutdown_started) { + int err; + + ctx->shutdown_started = TRUE; + vquic_ctx_update_time(&ctx->q); + err = quiche_conn_close(ctx->qconn, TRUE, 0, NULL, 0); + if(err) { + CURL_TRC_CF(data, cf, "error %d adding shutdown packet, " + "aborting shutdown", err); + result = CURLE_SEND_ERROR; + goto out; + } + } + + if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) { + CURL_TRC_CF(data, cf, "shutdown, flushing sendbuf"); + result = cf_flush_egress(cf, data); + if(result) + goto out; + } + + if(Curl_bufq_is_empty(&ctx->q.sendbuf)) { + /* sent everything, quiche does not seem to support a graceful + * shutdown waiting for a reply, so ware done. */ + CURL_TRC_CF(data, cf, "shutdown completely sent off, done"); + *done = TRUE; + } + else { + CURL_TRC_CF(data, cf, "shutdown sending blocked"); + } + +out: + return result; +} + +static void cf_quiche_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + if(cf->ctx) { + bool done; + (void)cf_quiche_shutdown(cf, data, &done); + cf_quiche_ctx_close(cf->ctx); + } +} + +static void cf_quiche_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + (void)data; + if(cf->ctx) { + cf_quiche_ctx_free(cf->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[%" FMT_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 have sent off a request and the connection is + not in use by any other transfer, there should not 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, + cf_quiche_shutdown, + 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; + } + cf_quiche_ctx_init(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; + + 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); + cf_quiche_ctx_free(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/local-test-curl-delta-01/afc-curl/lib/vquic/curl_quiche.h b/local-test-curl-delta-01/afc-curl/lib/vquic/curl_quiche.h new file mode 100644 index 0000000000000000000000000000000000000000..bce781c1bccc0f1e019524305e50317f0528d1d4 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.c b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.c new file mode 100644 index 0000000000000000000000000000000000000000..580e5707a8deb69cfe5d6b06b6d1d40fbd1ca98c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.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" + +#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 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->wssl.ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); + if(!ctx->wssl.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->wssl.ctx); + + if(wolfSSL_CTX_set_cipher_list(ctx->wssl.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->wssl.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->wssl.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->wssl.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->wssl.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 will not work so + use wolfSSL's built-in default as fallback */ + wolfSSL_CTX_set_default_verify_paths(ctx->wssl.ctx); + } +#endif + } + else { + wolfSSL_CTX_set_verify(ctx->wssl.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->wssl.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->wssl.ctx) { + SSL_CTX_free(ctx->wssl.ctx); + ctx->wssl.ctx = NULL; + } + return result; +} + +/** SSL callbacks ***/ + +static CURLcode wssl_init_ssl(struct curl_tls_ctx *ctx, + struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + const char *alpn, size_t alpn_len, + void *user_data) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + + DEBUGASSERT(!ctx->wssl.handle); + DEBUGASSERT(ctx->wssl.ctx); + ctx->wssl.handle = wolfSSL_new(ctx->wssl.ctx); + + wolfSSL_set_app_data(ctx->wssl.handle, user_data); + wolfSSL_set_connect_state(ctx->wssl.handle); + wolfSSL_set_quic_use_legacy_codepoint(ctx->wssl.handle, 0); + + if(alpn) + wolfSSL_set_alpn_protos(ctx->wssl.handle, (const unsigned char *)alpn, + (unsigned int)alpn_len); + + if(peer->sni) { + wolfSSL_UseSNI(ctx->wssl.handle, WOLFSSL_SNI_HOST_NAME, + peer->sni, (unsigned short)strlen(peer->sni)); + } + + if(ssl_config->primary.cache_session) { + (void)wssl_setup_session(cf, data, &ctx->wssl, peer); + } + + 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, NULL, + cb_setup, cb_user_data, ssl_user_data); +#elif defined(USE_WOLFSSL) + result = wssl_init_ctx(ctx, cf, data, cb_setup, cb_user_data); + if(result) + return result; + + return wssl_init_ssl(ctx, cf, 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.session) + gnutls_deinit(ctx->gtls.session); + Curl_gtls_shared_creds_free(&ctx->gtls.shared_creds); +#elif defined(USE_WOLFSSL) + if(ctx->wssl.handle) + wolfSSL_free(ctx->wssl.handle); + if(ctx->wssl.ctx) + wolfSSL_CTX_free(ctx->wssl.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_WOLFSSL) + if(!ctx->wssl.x509_store_setup) { + CURLcode result = Curl_wssl_setup_x509_store(cf, data, &ctx->wssl); + if(result) + return result; + } +#elif defined(USE_GNUTLS) + if(!ctx->gtls.shared_creds->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->wssl.handle); + 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/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.h b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.h new file mode 100644 index 0000000000000000000000000000000000000000..969acad41efcab7dce3cc85b67ea1eac3748a10b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic-tls.h @@ -0,0 +1,100 @@ +#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)) + +#include "vtls/wolfssl.h" + +struct curl_tls_ctx { +#ifdef USE_OPENSSL + struct ossl_ctx ossl; +#elif defined(USE_GNUTLS) + struct gtls_ctx gtls; +#elif defined(USE_WOLFSSL) + struct wolfssl_ctx wssl; +#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 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/local-test-curl-delta-01/afc-curl/lib/vquic/vquic.c b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic.c new file mode 100644 index 0000000000000000000000000000000000000000..20ff6a640b7ec46b7482e7c5b2c50060e74831f8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic.c @@ -0,0 +1,752 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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_UDP_H +#include +#endif +#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 "multiif.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(int))); + msg.msg_controllen = CMSG_SPACE(sizeof(int)); + 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); +} + +#if defined(HAVE_SENDMMSG) || defined(HAVE_SENDMSG) +static size_t vquic_msghdr_get_udp_gro(struct msghdr *msg) +{ + int gso_size = 0; +#if defined(__linux__) && defined(UDP_GRO) + struct cmsghdr *cmsg; + + /* Workaround musl CMSG_NXTHDR issue */ +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wcast-align" +#endif + for(cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { +#if defined(__clang__) && !defined(__GLIBC__) +#pragma clang diagnostic pop +#endif + if(cmsg->cmsg_level == SOL_UDP && cmsg->cmsg_type == UDP_GRO) { + memcpy(&gso_size, CMSG_DATA(cmsg), sizeof(gso_size)); + + break; + } + } +#endif + (void)msg; + + return (size_t)gso_size; +} +#endif + +#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 16 + struct iovec msg_iov[MMSG_NUM]; + struct mmsghdr mmsg[MMSG_NUM]; + uint8_t msg_ctrl[MMSG_NUM * CMSG_SPACE(sizeof(int))]; + struct sockaddr_storage remote_addr[MMSG_NUM]; + size_t total_nread = 0, pkts; + int mcount, i, n; + char errstr[STRERROR_LEN]; + CURLcode result = CURLE_OK; + size_t gso_size; + size_t pktlen; + size_t offset, to; + char *sockbuf = NULL; + uint8_t (*bufs)[64*1024] = NULL; + + DEBUGASSERT(max_pkts > 0); + result = Curl_multi_xfer_sockbuf_borrow(data, MMSG_NUM * sizeof(bufs[0]), + &sockbuf); + if(result) + goto out; + bufs = (uint8_t (*)[64*1024])sockbuf; + + 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]); + mmsg[i].msg_hdr.msg_control = &msg_ctrl[i * CMSG_SPACE(sizeof(int))]; + mmsg[i].msg_hdr.msg_controllen = CMSG_SPACE(sizeof(int)); + } + + 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); + for(i = 0; i < mcount; ++i) { + total_nread += mmsg[i].msg_len; + + gso_size = vquic_msghdr_get_udp_gro(&mmsg[i].msg_hdr); + if(gso_size == 0) { + gso_size = mmsg[i].msg_len; + } + + for(offset = 0; offset < mmsg[i].msg_len; offset = to) { + ++pkts; + + to = offset + gso_size; + if(to > mmsg[i].msg_len) { + pktlen = mmsg[i].msg_len - offset; + } + else { + pktlen = gso_size; + } + + result = recv_cb(bufs[i] + offset, pktlen, 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); + Curl_multi_xfer_sockbuf_release(data, sockbuf); + 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; + uint8_t msg_ctrl[CMSG_SPACE(sizeof(int))]; + size_t gso_size; + size_t pktlen; + size_t offset, to; + + 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; + msg.msg_control = msg_ctrl; + + DEBUGASSERT(max_pkts > 0); + for(pkts = 0, total_nread = 0; pkts < max_pkts;) { + msg.msg_name = &remote_addr; + msg.msg_namelen = sizeof(remote_addr); + msg.msg_controllen = sizeof(msg_ctrl); + 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; + } + + total_nread += (size_t)nread; + + gso_size = vquic_msghdr_get_udp_gro(&msg); + if(gso_size == 0) { + gso_size = (size_t)nread; + } + + for(offset = 0; offset < (size_t)nread; offset = to) { + ++pkts; + + to = offset + gso_size; + if(to > (size_t)nread) { + pktlen = (size_t)nread - offset; + } + else { + pktlen = gso_size; + } + + result = + recv_cb(buf + offset, pktlen, 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 an 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/local-test-curl-delta-01/afc-curl/lib/vquic/vquic.h b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic.h new file mode 100644 index 0000000000000000000000000000000000000000..c1ca1df6aa0c1a6376c8404d2798a9a9321728cc --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vquic/vquic_int.h b/local-test-curl-delta-01/afc-curl/lib/vquic/vquic_int.h new file mode 100644 index 0000000000000000000000000000000000000000..754e1f5910fbd3c6920b6e2d1133493367e283ee --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vssh/.checksrc b/local-test-curl-delta-01/afc-curl/lib/vssh/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..9066946c890dd2d8a5a3fda9c82fbe2baeed8772 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/.checksrc @@ -0,0 +1,2 @@ +enable STRERROR +enable STRNCPY diff --git a/local-test-curl-delta-01/afc-curl/lib/vssh/curl_path.c b/local-test-curl-delta-01/afc-curl/lib/vssh/curl_path.c new file mode 100644 index 0000000000000000000000000000000000000000..61452a42527c2d288c6e1c11c33f585adca4f1c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/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 "curl_path.h" +#include +#include "curl_memory.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/local-test-curl-delta-01/afc-curl/lib/vssh/curl_path.h b/local-test-curl-delta-01/afc-curl/lib/vssh/curl_path.h new file mode 100644 index 0000000000000000000000000000000000000000..8e984174d79c5ca1364e893334749b3ad6203c6c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/curl_path.h @@ -0,0 +1,36 @@ +#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" + +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/local-test-curl-delta-01/afc-curl/lib/vssh/libssh.c b/local-test-curl-delta-01/afc-curl/lib/vssh/libssh.c new file mode 100644 index 0000000000000000000000000000000000000000..6bae061ac4ec9ed4ca2edb314b2a46cc4b389b73 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/libssh.c @@ -0,0 +1,3002 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 + +#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 void myssh_block2waitfor(struct connectdata *conn, bool block); + +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.str[STRING_SSH_KNOWNHOSTS]) { + +#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 are 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); + + myssh_block2waitfor(conn, (rc == SSH_AGAIN)); + if(rc == SSH_AGAIN) { + DEBUGF(infof(data, "ssh_connect -> EAGAIN")); + 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 = + (unsigned int)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 (%" FMT_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 (cannot 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_setup1(data, CURL_XFER_SEND, -1, FALSE); + + /* 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 cannot + 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 do not 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); +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + sshc->sftp_send_state = 0; +#endif + 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 was not 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_nop(data); + 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 did not return an error, so maybe the server + * just does not support stat() + * OR the server does not 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 (%" FMT_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 (%" FMT_OFF_T ") was beyond file size (%" + FMT_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 are supposed to download the last abs(from) bytes */ + if((curl_off_t)size < -data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%" + FMT_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 (%" FMT_OFF_T + ") was beyond file size (%" FMT_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_nop(data); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + break; + } + Curl_xfer_setup1(data, CURL_XFER_RECV, data->req.size, FALSE); + + /* 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 */ + ssh_set_blocking(sshc->ssh_session, 0); +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + if(sshc->sftp_aio) { + sftp_aio_free(sshc->sftp_aio); + sshc->sftp_aio = NULL; + } +#endif + + 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_setup1(data, CURL_XFER_SEND, -1, FALSE); + + /* 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 cannot + 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_setup1(data, CURL_XFER_RECV, bytecount, FALSE); + + /* 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 have 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); + + DEBUGF(infof(data, "ssh_getsock -> %x", bitmap)); + return bitmap; +} + +static void myssh_block2waitfor(struct connectdata *conn, bool block) +{ + struct ssh_conn *sshc = &conn->proto.sshc; + + /* If it did not 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); + conn->waitfor = 0; + /* translate the libssh define bits into our own bit defines */ + if(dir & SSH_READ_PENDING) + conn->waitfor |= KEEP_RECV; + 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); + 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, CURL_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; + } + + if(conn->bits.ipv6_ip) { + char ipv6[MAX_IPADR_LEN]; + msnprintf(ipv6, sizeof(ipv6), "[%s]", conn->host.name); + rc = ssh_options_set(ssh->ssh_session, SSH_OPTIONS_HOST, ipv6); + } + else + 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 = FALSE; + 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 is 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, bool eos, CURLcode *err) +{ + int rc; + struct connectdata *conn = data->conn; + (void) sockindex; /* we only support SCP on the fixed known primary socket */ + (void) err; + (void)eos; + + 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)); + + 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)); + 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 is 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, bool eos, + CURLcode *err) +{ + ssize_t nwrite; + struct connectdata *conn = data->conn; + (void)sockindex; + (void)eos; + + /* 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; +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + switch(conn->proto.sshc.sftp_send_state) { + case 0: + sftp_file_set_nonblocking(conn->proto.sshc.sftp_file); + if(sftp_aio_begin_write(conn->proto.sshc.sftp_file, mem, len, + &conn->proto.sshc.sftp_aio) == SSH_ERROR) { + *err = CURLE_SEND_ERROR; + return -1; + } + conn->proto.sshc.sftp_send_state = 1; + FALLTHROUGH(); + case 1: + nwrite = sftp_aio_wait_write(&conn->proto.sshc.sftp_aio); + myssh_block2waitfor(conn, (nwrite == SSH_AGAIN) ? TRUE : FALSE); + if(nwrite == SSH_AGAIN) { + *err = CURLE_AGAIN; + return 0; + } + else if(nwrite < 0) { + *err = CURLE_SEND_ERROR; + return -1; + } + if(conn->proto.sshc.sftp_aio) { + sftp_aio_free(conn->proto.sshc.sftp_aio); + conn->proto.sshc.sftp_aio = NULL; + } + conn->proto.sshc.sftp_send_state = 0; + return nwrite; + default: + /* we never reach here */ + return -1; + } +#else + 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; +#endif +} + +/* + * 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, + (uint32_t)conn->proto.sshc.sftp_file_index); + + myssh_block2waitfor(conn, (nread == SSH_AGAIN)); + + 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 do not 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/local-test-curl-delta-01/afc-curl/lib/vssh/libssh2.c b/local-test-curl-delta-01/afc-curl/lib/vssh/libssh2.c new file mode 100644 index 0000000000000000000000000000000000000000..e19ffefe8b5f16b1fbcf46e696f236f3eb5682fb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/libssh2.c @@ -0,0 +1,3800 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 + +#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; +} + +/* These functions are made to use the libcurl memory functions - NOT the + debugmem functions, as that leads us to trigger on libssh2 memory leaks + that are not ours to care for */ + +static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc) +{ + (void)abstract; /* arg not used */ + return Curl_cmalloc(count); +} + +static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc) +{ + (void)abstract; /* arg not used */ + return Curl_crealloc(ptr, count); +} + +static LIBSSH2_FREE_FUNC(my_libssh2_free) +{ + (void)abstract; /* arg not used */ + if(ptr) /* ssh2 agent sometimes call free with null ptr */ + Curl_cfree(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(CURL *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 did not have the ability to seek to 64-bit + * positions with 32-bit 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 did not do SCP properly beyond 32-bit sizes on + * 32-bit 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_int64_t)d, 0, 0) +#endif + +/* + * libssh2 1.2.8 fixed the problem with 32-bit 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 enum curl_khtype convert_ssh2_keytype(int sshkeytype) +{ + enum curl_khtype 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 are 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 hostname we need to pass in here. + * What hostname 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, cannot 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 does not 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 did not 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 (!), do not 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 (!), do not 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) { + enum curl_khtype keytype = convert_ssh2_keytype(sshkeytype); + Curl_set_in_callback(data, TRUE); + rc = data->set.ssh_hostkeyfunc(data->set.ssh_hostkeyfunc_userp, + (int)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; +} + +static CURLcode sftp_quote(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp) +{ + const char *cp; + CURLcode result = CURLE_OK; + + /* + * 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) + return CURLE_OUT_OF_MEMORY; + 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_NEXT_QUOTE); + return result; + } + + /* + * 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); + return result; + } + + /* + * 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, "Syntax error: Bad first parameter to '%s'", cmd); + return result; + } + + /* + * SFTP is a binary protocol, so we do not 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, "Syntax error in %s: Bad second parameter", cmd); + Curl_safefree(sshc->quote_path1); + return result; + } + memset(&sshp->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES)); + state(data, SSH_SFTP_QUOTE_STAT); + return result; + } + 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, "Syntax error in ln/symlink: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + return result; + } + state(data, SSH_SFTP_QUOTE_SYMLINK); + return result; + } + else if(strncasecompare(cmd, "mkdir ", 6)) { + /* create dir */ + state(data, SSH_SFTP_QUOTE_MKDIR); + return result; + } + 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, "Syntax error in rename: Bad second parameter"); + Curl_safefree(sshc->quote_path1); + return result; + } + state(data, SSH_SFTP_QUOTE_RENAME); + return result; + } + else if(strncasecompare(cmd, "rmdir ", 6)) { + /* delete dir */ + state(data, SSH_SFTP_QUOTE_RMDIR); + return result; + } + else if(strncasecompare(cmd, "rm ", 3)) { + state(data, SSH_SFTP_QUOTE_UNLINK); + return result; + } +#ifdef HAS_STATVFS_SUPPORT + else if(strncasecompare(cmd, "statvfs ", 8)) { + state(data, SSH_SFTP_QUOTE_STATVFS); + return result; + } +#endif + + failf(data, "Unknown SFTP command"); + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + return CURLE_QUOTE_ERROR; +} + +static CURLcode +sftp_upload_init(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + 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) { + int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc) { + data->state.resume_from = 0; + } + else { + curl_off_t size = attrs.filesize; + if(size < 0) { + failf(data, "Bad file size (%" FMT_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, (long)data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + + if(!sshc->sftp_handle) { + unsigned long sftperr; + int rc = libssh2_session_last_errno(sshc->ssh_session); + + if(LIBSSH2_ERROR_EAGAIN == rc) { + *blockp = TRUE; + return CURLE_OK; + } + + 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)); + return CURLE_OK; + } + 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 */ + sshc->secondCreateDirs = 1; + state(data, SSH_SFTP_CREATE_DIRS_INIT); + return CURLE_OK; + } + 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); + return sshc->actualcode; + } + + /* If we have a restart point then we need to seek to the correct + position. */ + if(data->state.resume_from > 0) { + int seekerr = CURL_SEEKFUNC_OK; + /* 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 (cannot 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_setup1(data, CURL_XFER_SEND, -1, FALSE); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + data->conn->sockfd = data->conn->writesockfd; + + /* store this original bitmask setup to use later on if we cannot + 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 do not 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); + return CURLE_OK; +} + +static CURLcode +sftp_pkey_init(struct Curl_easy *data, + struct ssh_conn *sshc) +{ + /* + * 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; + return CURLE_OUT_OF_MEMORY; + } + + 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); + } + return CURLE_OK; +} + +static CURLcode +sftp_quote_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + 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. + */ + int 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) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc && !sshc->acceptfail) { /* get those attributes */ + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + failf(data, "Attempt to get SFTP stats failed: %s", + sftp_libssh2_strerror(sftperr)); + goto fail; + } + } + + /* 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) { + failf(data, "Syntax error: chgrp gid not a number"); + goto fail; + } + } + 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])) { + failf(data, "Syntax error: chmod permissions not a number"); + goto fail; + } + } + 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) { + failf(data, "Syntax error: chown uid not a number"); + goto fail; + } + } + 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' cannot old >32-bit, this date cannot be sent */ + failf(data, "date overflow"); + fail = TRUE; + } +#endif + if(fail) + goto fail; + 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); + return CURLE_OK; +fail: + Curl_safefree(sshc->quote_path1); + Curl_safefree(sshc->quote_path2); + return CURLE_QUOTE_ERROR; +} + +static CURLcode +sftp_download_stat(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + LIBSSH2_SFTP_ATTRIBUTES attrs; + int rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshp->path, + curlx_uztoui(strlen(sshp->path)), + LIBSSH2_SFTP_STAT, &attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return CURLE_OK; + } + if(rc || + !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) || + (attrs.filesize == 0)) { + /* + * libssh2_sftp_open() did not return an error, so maybe the server + * just does not support stat() + * OR the server does not 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 (%" FMT_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 (%" FMT_OFF_T ") was beyond file size (%" + FMT_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 are supposed to download the last abs(from) bytes */ + if((curl_off_t)attrs.filesize < -data->state.resume_from) { + failf(data, "Offset (%" FMT_OFF_T ") was beyond file size (%" + FMT_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 (%" FMT_OFF_T + ") was beyond file size (%" FMT_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_nop(data); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + return CURLE_OK; + } + Curl_xfer_setup1(data, CURL_XFER_RECV, data->req.size, FALSE); + + /* not set by Curl_xfer_setup to preserve keepon bits */ + data->conn->writesockfd = data->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; + state(data, SSH_STOP); + + return CURLE_OK; +} + +static CURLcode sftp_readdir(struct Curl_easy *data, + struct ssh_conn *sshc, + struct SSHPROTO *sshp, + bool *blockp) +{ + CURLcode result = CURLE_OK; + int rc = libssh2_sftp_readdir_ex(sshc->sftp_handle, + sshp->readdir_filename, CURL_PATH_MAX, + sshp->readdir_longentry, CURL_PATH_MAX, + &sshp->readdir_attrs); + if(rc == LIBSSH2_ERROR_EAGAIN) { + *blockp = TRUE; + return result; + } + if(rc > 0) { + size_t 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) + return result; + } + 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, CURL_PATH_MAX); + result = Curl_dyn_addf(&sshp->readdir_link, "%s%s", sshp->path, + sshp->readdir_filename); + state(data, SSH_SFTP_READDIR_LINK); + } + else { + state(data, SSH_SFTP_READDIR_BOTTOM); + } + } + return result; + } + } + else if(rc == 0) { + state(data, SSH_SFTP_READDIR_DONE); + } + else if(rc < 0) { + unsigned long 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)); + state(data, SSH_SFTP_CLOSE); + } + return result; +} +/* + * ssh_statemachine() 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_statemachine(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; + + int rc = LIBSSH2_ERROR_NONE; + *block = 0; /* we are 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, conn->sock[FIRSTSOCKET]); + 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 will not 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; + } + rc = libssh2_session_last_errno(sshc->ssh_session); + if(rc == LIBSSH2_ERROR_EAGAIN) + rc = LIBSSH2_ERROR_EAGAIN; + else { + state(data, SSH_SESSION_FREE); + sshc->actualcode = libssh2_session_error_to_CURLE(rc); + } + break; + } + infof(data, "SSH authentication methods available: %s", + sshc->authlist); + + state(data, SSH_AUTH_PKEY_INIT); + break; + + case SSH_AUTH_PKEY_INIT: + result = sftp_pkey_init(data, sshc); + 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 = conn->sock[FIRSTSOCKET]; + 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: + /* + * Get the "home" directory + */ + rc = sftp_libssh2_realpath(sshc->sftp_session, ".", + sshp->readdir_filename, CURL_PATH_MAX); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc > 0) { + /* It seems that this string is not always NULL terminated */ + sshp->readdir_filename[rc] = '\0'; + sshc->homedir = strdup(sshp->readdir_filename); + 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 */ + unsigned long sftperr = libssh2_sftp_last_error(sshc->sftp_session); + if(sftperr) + result = sftp_libssh2_error_to_CURLE(sftperr); + else + /* in this case, the error was not 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 quote commands */ + result = sftp_quote(data, sshc, sshp); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + 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: + result = sftp_quote_stat(data, sshc, sshp, block); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + 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) { + unsigned long 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) { + unsigned long 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)), + (long)data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + if(rc && !sshc->acceptfail) { + unsigned long 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) { + unsigned long 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) { + unsigned long 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) { + unsigned long 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) { + unsigned long 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 = (time_t)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: + result = sftp_upload_init(data, sshc, sshp, block); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + 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)), + (long)data->set.new_directory_perms); + if(rc == LIBSSH2_ERROR_EAGAIN) { + break; + } + *sshc->slash_pos = '/'; + ++sshc->slash_pos; + if(rc < 0) { + /* + * Abort if failure was not that the dir already exists or the + * permission was denied (creation might succeed further down the + * path) - retry on unspecific FAILURE also + */ + unsigned long 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) { + unsigned long sftperr; + 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; + } + Curl_dyn_init(&sshp->readdir, CURL_PATH_MAX * 2); + state(data, SSH_SFTP_READDIR); + break; + + case SSH_SFTP_READDIR: + result = sftp_readdir(data, sshc, sshp, block); + if(result) { + sshc->actualcode = result; + state(data, SSH_SFTP_CLOSE); + } + break; + + case SSH_SFTP_READDIR_LINK: + rc = + libssh2_sftp_symlink_ex(sshc->sftp_session, + Curl_dyn_ptr(&sshp->readdir_link), + (unsigned int) + Curl_dyn_len(&sshp->readdir_link), + sshp->readdir_filename, + CURL_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) { + 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; + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + 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, (long)data->set.new_file_perms, + LIBSSH2_SFTP_OPENFILE); + if(!sshc->sftp_handle) { + unsigned long sftperr; + 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: + result = sftp_download_stat(data, sshc, sshp, block); + if(result) { + state(data, SSH_SFTP_CLOSE); + sshc->nextstate = SSH_NO_STATE; + sshc->actualcode = result; + } + 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_setup1(data, CURL_XFER_SEND, -1, FALSE); + + /* 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 cannot + 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_setup1(data, CURL_XFER_RECV, bytecount, FALSE); + + /* 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 have 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 _does not_ 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 did not block or libssh2 did not 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_statemachine(data, &block); + *done = (sshc->state == SSH_STOP); + /* if there is no error, it is not done and it did not 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_statemachine(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, FALSE, &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, + (long)(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 = FALSE; + 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 is 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_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, bool eos, 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 */ + (void)eos; + + /* libssh2_channel_write() returns int! */ + nwrite = (ssize_t) libssh2_channel_write(sshc->ssh_channel, mem, len); + + ssh_block2waitfor(data, (nwrite == LIBSSH2_ERROR_EAGAIN)); + + 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)); + 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 is 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, bool eos, CURLcode *err) +{ + ssize_t nwrite; + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + (void)sockindex; + (void)eos; + + nwrite = libssh2_sftp_write(sshc->sftp_handle, mem, len); + + ssh_block2waitfor(data, (nwrite == LIBSSH2_ERROR_EAGAIN)); + + 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)); + + 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/local-test-curl-delta-01/afc-curl/lib/vssh/ssh.h b/local-test-curl-delta-01/afc-curl/lib/vssh/ssh.h new file mode 100644 index 0000000000000000000000000000000000000000..8d8a9b380787027adcab9bb53a3a77e2188045f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/ssh.h @@ -0,0 +1,283 @@ +#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) +/* in 0.10.0 or later, ignore deprecated warnings */ +#define SSH_SUPPRESS_DEPRECATED +#include +#include +#elif defined(USE_WOLFSSH) +#include +#include +#endif + +#include "curl_path.h" + +/**************************************************************************** + * 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; + +#define CURL_PATH_MAX 1024 + +/* 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[CURL_PATH_MAX + 1]; + char readdir_longentry[CURL_PATH_MAX + 1]; + + 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; + unsigned 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 */ +#if LIBSSH_VERSION_INT > SSH_VERSION_INT(0, 11, 0) + sftp_aio sftp_aio; + unsigned sftp_send_state; /* 0 or 1 */ +#endif + 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 runtime if possible */ +#define CURL_LIBSSH2_VERSION libssh2_version(0) +#else +/* use build-time if runtime 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/local-test-curl-delta-01/afc-curl/lib/vssh/wolfssh.c b/local-test-curl-delta-01/afc-curl/lib/vssh/wolfssh.c new file mode 100644 index 0000000000000000000000000000000000000000..5400821129b3ce3c5f74bc20903a1c9ea0f85aa5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vssh/wolfssh.c @@ -0,0 +1,1170 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "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, bool eos, + 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)eos; + (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, bool eos, CURLcode *err) +{ + struct connectdata *conn = data->conn; + struct ssh_conn *sshc = &conn->proto.sshc; + word32 offset[2]; + int rc; + (void)sockindex; + (void)eos; + + 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 %" FMT_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 username"); + 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 are 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 (%" FMT_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 (cannot 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_setup1(data, CURL_XFER_SEND, -1, FALSE); + + /* 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 cannot + 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 do not 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 %" FMT_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_nop(data); + infof(data, "File already completely downloaded"); + state(data, SSH_STOP); + break; + } + Curl_xfer_setup1(data, CURL_XFER_RECV, data->req.size, FALSE); + + /* 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); + /* if there is no error, it is not done and it did not 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 = FALSE; + 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 is 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/local-test-curl-delta-01/afc-curl/lib/vtls/.checksrc b/local-test-curl-delta-01/afc-curl/lib/vtls/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..9066946c890dd2d8a5a3fda9c82fbe2baeed8772 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/.checksrc @@ -0,0 +1,2 @@ +enable STRERROR +enable STRNCPY diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/bearssl.c b/local-test-curl-delta-01/afc-curl/lib/vtls/bearssl.c new file mode 100644 index 0000000000000000000000000000000000000000..53fd4a6bc164ec2b929b2089e090aaa391b6c7f8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/bearssl.c @@ -0,0 +1,1183 @@ +/*************************************************************************** + * _ _ ____ _ + * 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; + BIT(sent_shutdown); +}; + +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 (unsigned)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 CURLcode +bearssl_set_ssl_version_min_max(struct Curl_easy *data, + br_ssl_engine_context *ssl_eng, + struct ssl_primary_config *conn_config) +{ + unsigned version_min, version_max; + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + version_min = BR_TLS10; + break; + case CURL_SSLVERSION_TLSv1_1: + version_min = BR_TLS11; + break; + case CURL_SSLVERSION_TLSv1_2: + version_min = BR_TLS12; + break; + case CURL_SSLVERSION_TLSv1_3: + failf(data, "BearSSL: does not support TLS 1.3"); + return CURLE_SSL_CONNECT_ERROR; + default: + failf(data, "BearSSL: unsupported minimum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: + case CURL_SSLVERSION_MAX_TLSv1_2: + version_max = BR_TLS12; + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + version_max = BR_TLS11; + break; + case CURL_SSLVERSION_MAX_TLSv1_0: + version_max = BR_TLS10; + break; + default: + failf(data, "BearSSL: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + br_ssl_engine_set_versions(ssl_eng, version_min, version_max); + + return CURLE_OK; +} + +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; + int session_set = 0; + + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step1"); + + 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); + + ret = bearssl_set_ssl_version_min_max(data, &backend->ctx.eng, conn_config); + if(ret != CURLE_OK) + return ret; + + 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.cache_session) { + void *sdata; + size_t slen; + const br_ssl_session_parameters *session; + + CURL_TRC_CF(data, cf, "connect_step1, check session cache"); + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, &sdata, &slen, NULL) && + slen == sizeof(*session)) { + session = sdata; + 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 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); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + 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; + default:; + } + failf(data, "BearSSL: connection error 0x%04x", err); + /* 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, FALSE, + &result); + CURL_TRC_CF(data, cf, "ssl_send(len=%zu) -> %zd, %d", len, ret, result); + if(ret <= 0) { + if(result == CURLE_AGAIN) + connssl->io_need |= CURL_SSL_IO_NEED_SEND; + 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) { + if(result == CURLE_AGAIN) + connssl->io_need |= CURL_SSL_IO_NEED_RECV; + 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]; + 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; + int subver = 0; + + 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); + switch(tver) { + case BR_TLS12: + subver = 2; /* 1.2 */ + break; + case BR_TLS11: + subver = 1; /* 1.1 */ + break; + case BR_TLS10: /* 1.0 */ + default: /* unknown, leave it at zero */ + break; + } + 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: TLS v1.%d connection using %s", subver, + 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, connssl, (const unsigned char *)proto, + proto ? strlen(proto) : 0); + } + + if(ssl_config->primary.cache_session) { + 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); + ret = Curl_ssl_set_sessionid(cf, data, &connssl->peer, NULL, + session, sizeof(*session), + 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) { + /* 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 is available. */ + if(connssl->io_need) { + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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. + */ + connssl->io_need = CURL_SSL_IO_NEED_NONE; + ret = bearssl_connect_step2(cf, data); + if(ret || (nonblocking && (ssl_connect_2 == 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 CURLcode bearssl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct bearssl_ssl_backend_data *backend = + (struct bearssl_ssl_backend_data *)connssl->backend; + CURLcode result; + + DEBUGASSERT(backend); + if(!backend->active || cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + + *done = FALSE; + if(!backend->sent_shutdown) { + (void)send_shutdown; /* unknown how to suppress our close notify */ + br_ssl_engine_close(&backend->ctx.eng); + backend->sent_shutdown = TRUE; + } + + result = bearssl_run_until(cf, data, BR_SSL_CLOSED); + if(result == CURLE_OK) { + *done = TRUE; + } + else if(result == CURLE_AGAIN) { + CURL_TRC_CF(data, cf, "shutdown EAGAIN, io_need=%x", connssl->io_need); + result = CURLE_OK; + } + else + CURL_TRC_CF(data, cf, "shutdown error: %d", result); + + cf->shutdown = (result || *done); + return result; +} + +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; + + (void)data; + DEBUGASSERT(backend); + + backend->active = FALSE; + 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 | + SSLSUPP_CIPHER_LIST, + + sizeof(struct bearssl_ssl_backend_data), + + Curl_none_init, /* init */ + Curl_none_cleanup, /* cleanup */ + bearssl_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + bearssl_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 */ + Curl_ssl_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 */ + bearssl_recv, /* recv decrypted data */ + bearssl_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_BEARSSL */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/bearssl.h b/local-test-curl-delta-01/afc-curl/lib/vtls/bearssl.h new file mode 100644 index 0000000000000000000000000000000000000000..b3651b092c135aaf09c8ac72a755c1996b583eb7 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.c b/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.c new file mode 100644 index 0000000000000000000000000000000000000000..a694b14627935d69884595c678e10d2699737d62 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.c @@ -0,0 +1,891 @@ +/*************************************************************************** + * _ _ ____ _ + * 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_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) +#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 +#if defined(USE_SECTRANSP) + "40" "\0" + "ADH" "\0" + "AECDH" "\0" + "anon" "\0" + "DES40" "\0" + "DH" "\0" + "DSS" "\0" + "EDH" "\0" + "EXP" "\0" + "EXPORT" "\0" + "IDEA" "\0" + "RC2" "\0" + "RC4" "\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 +#if defined(USE_SECTRANSP) + CS_TXT_IDX_40, + CS_TXT_IDX_ADH, + CS_TXT_IDX_AECDH, + CS_TXT_IDX_anon, + CS_TXT_IDX_DES40, + CS_TXT_IDX_DH, + CS_TXT_IDX_DSS, + CS_TXT_IDX_EDH, + CS_TXT_IDX_EXP, + CS_TXT_IDX_EXPORT, + CS_TXT_IDX_IDEA, + CS_TXT_IDX_RC2, + CS_TXT_IDX_RC4, +#endif + CS_TXT_LEN, +}; + +#define CS_ZIP_IDX(a, b, c, d, e, f, g, h) \ +{ \ + (uint8_t) ((((a) << 2) & 0xFF) | ((b) & 0x3F) >> 4), \ + (uint8_t) ((((b) << 4) & 0xFF) | ((c) & 0x3F) >> 2), \ + (uint8_t) ((((c) << 6) & 0xFF) | ((d) & 0x3F)), \ + (uint8_t) ((((e) << 2) & 0xFF) | ((f) & 0x3F) >> 4), \ + (uint8_t) ((((f) << 4) & 0xFF) | ((g) & 0x3F) >> 2), \ + (uint8_t) ((((g) << 6) & 0xFF) | ((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 [] = { + /* TLS 1.3 ciphers */ +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_RUSTLS) + 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,,), +#endif + /* TLS 1.2 ciphers */ + 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(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(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_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_BEARSSL) + 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(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(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,,,), +#endif +#if defined(USE_SECTRANSP) || 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(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_SECTRANSP) || 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 +#if defined(USE_MBEDTLS) || defined(USE_BEARSSL) + 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,,,,), +#endif +#if defined(USE_SECTRANSP) + /* entries marked bc are backward compatible aliases for old OpenSSL names */ + CS_ENTRY(0x0003, TLS,RSA,EXPORT,WITH,RC4,40,MD5,), + CS_ENTRY(0x0003, EXP,RC4,MD5,,,,,), + CS_ENTRY(0x0004, TLS,RSA,WITH,RC4,128,MD5,,), + CS_ENTRY(0x0004, RC4,MD5,,,,,,), + CS_ENTRY(0x0005, TLS,RSA,WITH,RC4,128,SHA,,), + CS_ENTRY(0x0005, RC4,SHA,,,,,,), + CS_ENTRY(0x0006, TLS,RSA,EXPORT,WITH,RC2,CBC,40,MD5), + CS_ENTRY(0x0006, EXP,RC2,CBC,MD5,,,,), + CS_ENTRY(0x0007, TLS,RSA,WITH,IDEA,CBC,SHA,,), + CS_ENTRY(0x0007, IDEA,CBC,SHA,,,,,), + CS_ENTRY(0x0008, TLS,RSA,EXPORT,WITH,DES40,CBC,SHA,), + CS_ENTRY(0x0008, EXP,DES,CBC,SHA,,,,), + CS_ENTRY(0x0009, TLS,RSA,WITH,DES,CBC,SHA,,), + CS_ENTRY(0x0009, DES,CBC,SHA,,,,,), + CS_ENTRY(0x000B, TLS,DH,DSS,EXPORT,WITH,DES40,CBC,SHA), + CS_ENTRY(0x000B, EXP,DH,DSS,DES,CBC,SHA,,), + CS_ENTRY(0x000C, TLS,DH,DSS,WITH,DES,CBC,SHA,), + CS_ENTRY(0x000C, DH,DSS,DES,CBC,SHA,,,), + CS_ENTRY(0x000D, TLS,DH,DSS,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x000D, DH,DSS,DES,CBC3,SHA,,,), + CS_ENTRY(0x000E, TLS,DH,RSA,EXPORT,WITH,DES40,CBC,SHA), + CS_ENTRY(0x000E, EXP,DH,RSA,DES,CBC,SHA,,), + CS_ENTRY(0x000F, TLS,DH,RSA,WITH,DES,CBC,SHA,), + CS_ENTRY(0x000F, DH,RSA,DES,CBC,SHA,,,), + CS_ENTRY(0x0010, TLS,DH,RSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x0010, DH,RSA,DES,CBC3,SHA,,,), + CS_ENTRY(0x0011, TLS,DHE,DSS,EXPORT,WITH,DES40,CBC,SHA), + CS_ENTRY(0x0011, EXP,DHE,DSS,DES,CBC,SHA,,), + CS_ENTRY(0x0011, EXP,EDH,DSS,DES,CBC,SHA,,), /* bc */ + CS_ENTRY(0x0012, TLS,DHE,DSS,WITH,DES,CBC,SHA,), + CS_ENTRY(0x0012, DHE,DSS,DES,CBC,SHA,,,), + CS_ENTRY(0x0012, EDH,DSS,DES,CBC,SHA,,,), /* bc */ + CS_ENTRY(0x0013, TLS,DHE,DSS,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x0013, DHE,DSS,DES,CBC3,SHA,,,), + CS_ENTRY(0x0013, EDH,DSS,DES,CBC3,SHA,,,), /* bc */ + CS_ENTRY(0x0014, TLS,DHE,RSA,EXPORT,WITH,DES40,CBC,SHA), + CS_ENTRY(0x0014, EXP,DHE,RSA,DES,CBC,SHA,,), + CS_ENTRY(0x0014, EXP,EDH,RSA,DES,CBC,SHA,,), /* bc */ + CS_ENTRY(0x0015, TLS,DHE,RSA,WITH,DES,CBC,SHA,), + CS_ENTRY(0x0015, DHE,RSA,DES,CBC,SHA,,,), + CS_ENTRY(0x0015, EDH,RSA,DES,CBC,SHA,,,), /* bc */ + CS_ENTRY(0x0016, TLS,DHE,RSA,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x0016, DHE,RSA,DES,CBC3,SHA,,,), + CS_ENTRY(0x0016, EDH,RSA,DES,CBC3,SHA,,,), /* bc */ + CS_ENTRY(0x0017, TLS,DH,anon,EXPORT,WITH,RC4,40,MD5), + CS_ENTRY(0x0017, EXP,ADH,RC4,MD5,,,,), + CS_ENTRY(0x0018, TLS,DH,anon,WITH,RC4,128,MD5,), + CS_ENTRY(0x0018, ADH,RC4,MD5,,,,,), + CS_ENTRY(0x0019, TLS,DH,anon,EXPORT,WITH,DES40,CBC,SHA), + CS_ENTRY(0x0019, EXP,ADH,DES,CBC,SHA,,,), + CS_ENTRY(0x001A, TLS,DH,anon,WITH,DES,CBC,SHA,), + CS_ENTRY(0x001A, ADH,DES,CBC,SHA,,,,), + CS_ENTRY(0x001B, TLS,DH,anon,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x001B, ADH,DES,CBC3,SHA,,,,), + CS_ENTRY(0x0030, TLS,DH,DSS,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0030, DH,DSS,AES128,SHA,,,,), + CS_ENTRY(0x0031, TLS,DH,RSA,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0031, DH,RSA,AES128,SHA,,,,), + CS_ENTRY(0x0032, TLS,DHE,DSS,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0032, DHE,DSS,AES128,SHA,,,,), + CS_ENTRY(0x0034, TLS,DH,anon,WITH,AES,128,CBC,SHA), + CS_ENTRY(0x0034, ADH,AES128,SHA,,,,,), + CS_ENTRY(0x0036, TLS,DH,DSS,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0036, DH,DSS,AES256,SHA,,,,), + CS_ENTRY(0x0037, TLS,DH,RSA,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0037, DH,RSA,AES256,SHA,,,,), + CS_ENTRY(0x0038, TLS,DHE,DSS,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x0038, DHE,DSS,AES256,SHA,,,,), + CS_ENTRY(0x003A, TLS,DH,anon,WITH,AES,256,CBC,SHA), + CS_ENTRY(0x003A, ADH,AES256,SHA,,,,,), + CS_ENTRY(0x003E, TLS,DH,DSS,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x003E, DH,DSS,AES128,SHA256,,,,), + CS_ENTRY(0x003F, TLS,DH,RSA,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x003F, DH,RSA,AES128,SHA256,,,,), + CS_ENTRY(0x0040, TLS,DHE,DSS,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x0040, DHE,DSS,AES128,SHA256,,,,), + CS_ENTRY(0x0068, TLS,DH,DSS,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x0068, DH,DSS,AES256,SHA256,,,,), + CS_ENTRY(0x0069, TLS,DH,RSA,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x0069, DH,RSA,AES256,SHA256,,,,), + CS_ENTRY(0x006A, TLS,DHE,DSS,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x006A, DHE,DSS,AES256,SHA256,,,,), + CS_ENTRY(0x006C, TLS,DH,anon,WITH,AES,128,CBC,SHA256), + CS_ENTRY(0x006C, ADH,AES128,SHA256,,,,,), + CS_ENTRY(0x006D, TLS,DH,anon,WITH,AES,256,CBC,SHA256), + CS_ENTRY(0x006D, ADH,AES256,SHA256,,,,,), + CS_ENTRY(0x008A, TLS,PSK,WITH,RC4,128,SHA,,), + CS_ENTRY(0x008A, PSK,RC4,SHA,,,,,), + CS_ENTRY(0x008B, TLS,PSK,WITH,3DES,EDE,CBC,SHA,), + CS_ENTRY(0x008B, PSK,3DES,EDE,CBC,SHA,,,), + CS_ENTRY(0x008E, TLS,DHE,PSK,WITH,RC4,128,SHA,), + CS_ENTRY(0x008E, DHE,PSK,RC4,SHA,,,,), + CS_ENTRY(0x008F, TLS,DHE,PSK,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x008F, DHE,PSK,3DES,EDE,CBC,SHA,,), + CS_ENTRY(0x0092, TLS,RSA,PSK,WITH,RC4,128,SHA,), + CS_ENTRY(0x0092, RSA,PSK,RC4,SHA,,,,), + CS_ENTRY(0x0093, TLS,RSA,PSK,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0x0093, RSA,PSK,3DES,EDE,CBC,SHA,,), + CS_ENTRY(0x00A0, TLS,DH,RSA,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00A0, DH,RSA,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00A1, TLS,DH,RSA,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00A1, DH,RSA,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00A2, TLS,DHE,DSS,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00A2, DHE,DSS,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00A3, TLS,DHE,DSS,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00A3, DHE,DSS,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00A4, TLS,DH,DSS,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00A4, DH,DSS,AES128,GCM,SHA256,,,), + CS_ENTRY(0x00A5, TLS,DH,DSS,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00A5, DH,DSS,AES256,GCM,SHA384,,,), + CS_ENTRY(0x00A6, TLS,DH,anon,WITH,AES,128,GCM,SHA256), + CS_ENTRY(0x00A6, ADH,AES128,GCM,SHA256,,,,), + CS_ENTRY(0x00A7, TLS,DH,anon,WITH,AES,256,GCM,SHA384), + CS_ENTRY(0x00A7, ADH,AES256,GCM,SHA384,,,,), + CS_ENTRY(0xC002, TLS,ECDH,ECDSA,WITH,RC4,128,SHA,), + CS_ENTRY(0xC002, ECDH,ECDSA,RC4,SHA,,,,), + CS_ENTRY(0xC007, TLS,ECDHE,ECDSA,WITH,RC4,128,SHA,), + CS_ENTRY(0xC007, ECDHE,ECDSA,RC4,SHA,,,,), + CS_ENTRY(0xC00C, TLS,ECDH,RSA,WITH,RC4,128,SHA,), + CS_ENTRY(0xC00C, ECDH,RSA,RC4,SHA,,,,), + CS_ENTRY(0xC011, TLS,ECDHE,RSA,WITH,RC4,128,SHA,), + CS_ENTRY(0xC011, ECDHE,RSA,RC4,SHA,,,,), + CS_ENTRY(0xC015, TLS,ECDH,anon,WITH,NULL,SHA,,), + CS_ENTRY(0xC015, AECDH,NULL,SHA,,,,,), + CS_ENTRY(0xC016, TLS,ECDH,anon,WITH,RC4,128,SHA,), + CS_ENTRY(0xC016, AECDH,RC4,SHA,,,,,), + CS_ENTRY(0xC017, TLS,ECDH,anon,WITH,3DES,EDE,CBC,SHA), + CS_ENTRY(0xC017, AECDH,DES,CBC3,SHA,,,,), + CS_ENTRY(0xC018, TLS,ECDH,anon,WITH,AES,128,CBC,SHA), + CS_ENTRY(0xC018, AECDH,AES128,SHA,,,,,), + CS_ENTRY(0xC019, TLS,ECDH,anon,WITH,AES,256,CBC,SHA), + CS_ENTRY(0xC019, AECDH,AES256,SHA,,,,,), +#endif +#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_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.h b/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.h new file mode 100644 index 0000000000000000000000000000000000000000..6d980103a573d7871e0f3065dd733e47dc5d438d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/cipher_suite.h @@ -0,0 +1,48 @@ +#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_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) +#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_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) */ +#endif /* HEADER_CURL_CIPHER_SUITE_H */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.c b/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.c new file mode 100644 index 0000000000000000000000000000000000000000..af4f0c349f2c3158dbd2b130dd8c14c6e4683bc1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.c @@ -0,0 +1,2295 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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: do not 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 "progress.h" +#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, FALSE, &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.shared_creds->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; + connssl->connecting_state = ssl_connect_2; + + 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 is available. */ + if(connssl->io_need) { + int what; + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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_AGAIN; + else if(timeout_ms) { + /* timeout */ + failf(data, "SSL connection timeout at %ld", (long)timeout_ms); + return CURLE_OPERATION_TIMEDOUT; + } + } + /* socket is readable or writable */ + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + backend->gtls.io_result = CURLE_OK; + rc = gnutls_handshake(session); + + if(!backend->gtls.shared_creds->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->io_need = + gnutls_record_get_direction(session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + continue; + } + else if((rc < 0) && !gnutls_error_is_fatal(rc)) { + const char *strerr = NULL; + + if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) { + gnutls_alert_description_t 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) { + gnutls_alert_description_t 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 gnutls_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 +gnutls_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((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(peer->transport == TRNSPRT_QUIC) { + if((ssl_version_max != CURL_SSLVERSION_MAX_DEFAULT) && + (ssl_version_max < CURL_SSLVERSION_MAX_TLSv1_3)) { + failf(data, "QUIC needs at least TLS version 1.3"); + return CURLE_SSL_CONNECT_ERROR; + } + *prioritylist = QUIC_PRIORITY; + return CURLE_OK; + } + + if(!tls13support) { + /* If the running GnuTLS does not 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_shared_creds_create(struct Curl_easy *data, + struct gtls_shared_creds **pcreds) +{ + struct gtls_shared_creds *shared; + int rc; + + *pcreds = NULL; + shared = calloc(1, sizeof(*shared)); + if(!shared) + return CURLE_OUT_OF_MEMORY; + + rc = gnutls_certificate_allocate_credentials(&shared->creds); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc)); + free(shared); + return CURLE_SSL_CONNECT_ERROR; + } + + shared->refcount = 1; + shared->time = Curl_now(); + *pcreds = shared; + return CURLE_OK; +} + +CURLcode Curl_gtls_shared_creds_up_ref(struct gtls_shared_creds *creds) +{ + DEBUGASSERT(creds); + if(creds->refcount < SIZE_T_MAX) { + ++creds->refcount; + return CURLE_OK; + } + return CURLE_BAD_FUNCTION_ARGUMENT; +} + +void Curl_gtls_shared_creds_free(struct gtls_shared_creds **pcreds) +{ + struct gtls_shared_creds *shared = *pcreds; + *pcreds = NULL; + if(shared) { + --shared->refcount; + if(!shared->refcount) { + gnutls_certificate_free_credentials(shared->creds); + free(shared->CAfile); + free(shared); + } + } +} + +static CURLcode gtls_populate_creds(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_certificate_credentials_t creds) +{ + 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; + + if(config->verifypeer) { + bool imported_native_ca = FALSE; + + if(ssl_config->native_ca_store) { + rc = gnutls_certificate_set_x509_system_trust(creds); + 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(creds, + GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT); + + rc = gnutls_certificate_set_x509_trust_file(creds, + 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(creds, 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(creds, 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); + } + + return CURLE_OK; +} + +/* key to use at `multi->proto_hash` */ +#define MPROTO_GTLS_X509_KEY "tls:gtls:x509:share" + +static bool gtls_shared_creds_expired(const struct Curl_easy *data, + const struct gtls_shared_creds *sc) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + struct curltime now = Curl_now(); + timediff_t elapsed_ms = Curl_timediff(now, sc->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 gtls_shared_creds_different(struct Curl_cfilter *cf, + const struct gtls_shared_creds *sc) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + if(!sc->CAfile || !conn_config->CAfile) + return sc->CAfile != conn_config->CAfile; + + return strcmp(sc->CAfile, conn_config->CAfile); +} + +static struct gtls_shared_creds* +gtls_get_cached_creds(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct gtls_shared_creds *shared_creds; + + if(data->multi) { + shared_creds = Curl_hash_pick(&data->multi->proto_hash, + (void *)MPROTO_GTLS_X509_KEY, + sizeof(MPROTO_GTLS_X509_KEY)-1); + if(shared_creds && shared_creds->creds && + !gtls_shared_creds_expired(data, shared_creds) && + !gtls_shared_creds_different(cf, shared_creds)) { + return shared_creds; + } + } + return NULL; +} + +static void gtls_shared_creds_hash_free(void *key, size_t key_len, void *p) +{ + struct gtls_shared_creds *sc = p; + DEBUGASSERT(key_len == (sizeof(MPROTO_GTLS_X509_KEY)-1)); + DEBUGASSERT(!memcmp(MPROTO_GTLS_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + Curl_gtls_shared_creds_free(&sc); /* down reference */ +} + +static void gtls_set_cached_creds(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_shared_creds *sc) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + + DEBUGASSERT(sc); + DEBUGASSERT(sc->creds); + DEBUGASSERT(!sc->CAfile); + DEBUGASSERT(sc->refcount == 1); + if(!data->multi) + return; + + if(conn_config->CAfile) { + sc->CAfile = strdup(conn_config->CAfile); + if(!sc->CAfile) + return; + } + + if(Curl_gtls_shared_creds_up_ref(sc)) + return; + + if(!Curl_hash_add2(&data->multi->proto_hash, + (void *)MPROTO_GTLS_X509_KEY, + sizeof(MPROTO_GTLS_X509_KEY)-1, + sc, gtls_shared_creds_hash_free)) { + Curl_gtls_shared_creds_free(&sc); /* down reference again */ + return; + } +} + +CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct gtls_ctx *gtls) +{ + 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 gtls_shared_creds *cached_creds = NULL; + bool cache_criteria_met; + CURLcode result; + int rc; + + + /* 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 && + !conn_config->clientcert; /* GnuTLS adds client cert to its credentials! */ + + if(cache_criteria_met) + cached_creds = gtls_get_cached_creds(cf, data); + + if(cached_creds && !Curl_gtls_shared_creds_up_ref(cached_creds)) { + CURL_TRC_CF(data, cf, "using shared trust anchors and CRLs"); + Curl_gtls_shared_creds_free(>ls->shared_creds); + gtls->shared_creds = cached_creds; + rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE, + gtls->shared_creds->creds); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else { + CURL_TRC_CF(data, cf, "loading trust anchors and CRLs"); + result = gtls_populate_creds(cf, data, gtls->shared_creds->creds); + if(result) + return result; + gtls->shared_creds->trust_setup = TRUE; + if(cache_criteria_met) + gtls_set_cached_creds(cf, data, gtls->shared_creds); + } + return CURLE_OK; +} + +static void gtls_sessionid_free(void *sessionid, size_t idsize) +{ + (void)idsize; + free(sessionid); +} + +CURLcode Curl_gtls_update_session_id(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session, + struct ssl_peer *peer, + const char *alpn) +{ + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + void *connect_sessionid; + size_t connect_idsize = 0; + CURLcode result = CURLE_OK; + + if(!ssl_config->primary.cache_session) + return CURLE_OK; + + /* 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. */ + + /* get the session ID data size */ + gnutls_session_get_data(session, NULL, &connect_idsize); + if(!connect_idsize) /* gnutls does this for some version combinations */ + return CURLE_OK; + + connect_sessionid = malloc(connect_idsize); /* get a buffer for it */ + if(!connect_sessionid) + return CURLE_OUT_OF_MEMORY; + + /* extract session ID to the allocated buffer */ + gnutls_session_get_data(session, connect_sessionid, &connect_idsize); + + CURL_TRC_CF(data, cf, "get session id (len=%zu, alpn=%s) and store in cache", + connect_idsize, alpn ? alpn : "-"); + Curl_ssl_sessionid_lock(data); + /* store this session id, takes ownership */ + result = Curl_ssl_set_sessionid(cf, data, peer, alpn, + connect_sessionid, connect_idsize, + gtls_sessionid_free); + Curl_ssl_sessionid_unlock(data); + return result; +} + +static CURLcode cf_gtls_update_session_id(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session) +{ + struct ssl_connect_data *connssl = cf->ctx; + return Curl_gtls_update_session_id(cf, data, session, &connssl->peer, + connssl->alpn_negotiated); +} + +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) { + CURL_TRC_CF(data, cf, "handshake: %s message type %d", + incoming ? "incoming" : "outgoing", htype); + switch(htype) { + case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: { + cf_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 shared creds struct */ + result = Curl_gtls_shared_creds_create(data, >ls->shared_creds); + if(result) + return result; + +#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_TLS12) + init_flags |= GNUTLS_NO_TICKETS_TLS12; +#elif defined(GNUTLS_NO_TICKETS) + /* Disable TLS session tickets for non 1.3 connections */ + if((config->version != CURL_SSLVERSION_TLSv1_3) && + (config->version != CURL_SSLVERSION_DEFAULT)) + init_flags |= GNUTLS_NO_TICKETS; +#endif + +#if defined(GNUTLS_NO_STATUS_REQUEST) + if(!config->verifystatus) + /* Disable the "status_request" TLS extension, enabled by default since + GnuTLS 3.8.0. */ + init_flags |= GNUTLS_NO_STATUS_REQUEST; +#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 runtime 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 = gnutls_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->shared_creds->trust_setup) { + result = Curl_gtls_client_trust_setup(cf, data, gtls); + if(result) + return result; + } + if(ssl_config->cert_type && strcasecompare(ssl_config->cert_type, "P12")) { + rc = gnutls_certificate_set_x509_simple_pkcs12_file( + gtls->shared_creds->creds, config->clientcert, GNUTLS_X509_FMT_DER, + ssl_config->key_passwd ? ssl_config->key_passwd : ""); + if(rc != GNUTLS_E_SUCCESS) { + failf(data, + "error reading X.509 potentially-encrypted key or certificate " + "file: %s", + gnutls_strerror(rc)); + return CURLE_SSL_CONNECT_ERROR; + } + } + else 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->shared_creds->creds, + config->clientcert, + ssl_config->key ? ssl_config->key : config->clientcert, + gnutls_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->shared_creds->creds, + config->clientcert, + ssl_config->key ? ssl_config->key : config->clientcert, + gnutls_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->shared_creds->creds); + 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, + struct ssl_connect_data *connssl, + 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); + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + gnutls_datum_t gtls_alpns[5]; + size_t gtls_alpns_count = 0; + 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); + } + + /* This might be a reconnect, so we check for a session ID in the cache + to speed up things */ + if(conn_config->cache_session) { + void *ssl_sessionid; + size_t ssl_idsize; + char *session_alpn; + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, peer, + &ssl_sessionid, &ssl_idsize, &session_alpn)) { + /* 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, alpn=%s)", + ssl_idsize, session_alpn ? session_alpn : "-"); +#ifdef DEBUGBUILD + if((ssl_config->earlydata || !!getenv("CURL_USE_EARLYDATA")) && +#else + if(ssl_config->earlydata && +#endif + !cf->conn->connect_only && connssl && + (gnutls_protocol_get_version(gctx->session) == GNUTLS_TLS1_3) && + Curl_alpn_contains_proto(connssl->alpn, session_alpn)) { + connssl->earlydata_max = + gnutls_record_get_max_early_data_size(gctx->session); + if((!connssl->earlydata_max || + connssl->earlydata_max == 0xFFFFFFFFUL)) { + /* Seems to be GnuTLS way to signal no EarlyData in session */ + CURL_TRC_CF(data, cf, "TLS session does not allow earlydata"); + } + else { + CURL_TRC_CF(data, cf, "TLS session allows %zu earlydata bytes, " + "reusing ALPN '%s'", + connssl->earlydata_max, session_alpn); + connssl->earlydata_state = ssl_earlydata_use; + connssl->state = ssl_connection_deferred; + result = Curl_alpn_set_negotiated(cf, data, connssl, + (const unsigned char *)session_alpn, + session_alpn ? strlen(session_alpn) : 0); + if(result) + return result; + /* We only try the ALPN protocol the session used before, + * otherwise we might send early data for the wrong protocol */ + gtls_alpns[0].data = (unsigned char *)session_alpn; + gtls_alpns[0].size = (unsigned)strlen(session_alpn); + gtls_alpns_count = 1; + } + } + } + } + Curl_ssl_sessionid_unlock(data); + } + + /* convert the ALPN string from our arguments to a list of strings that + * gnutls wants and will convert internally back to this string for sending + * to the server. nice. */ + if(!gtls_alpns_count && alpn && alpn_len) { + size_t i, alen = alpn_len; + unsigned char *s = (unsigned char *)alpn; + unsigned char slen; + for(i = 0; (i < ARRAYSIZE(gtls_alpns)) && alen; ++i) { + slen = s[0]; + if(slen >= alen) + return CURLE_FAILED_INIT; + gtls_alpns[i].data = s + 1; + gtls_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; + gtls_alpns_count = i; + } + + if(gtls_alpns_count && + gnutls_alpn_set_protocols(gctx->session, + gtls_alpns, (unsigned int)gtls_alpns_count, + GNUTLS_ALPN_MANDATORY)) { + failf(data, "failed setting ALPN"); + return CURLE_SSL_CONNECT_ERROR; + } + + 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, connssl, NULL, NULL, cf); + if(result) + return result; + + if(connssl->alpn && (connssl->state != ssl_connection_deferred)) { + Curl_alpn_to_proto_str(&proto, connssl->alpn); + infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); + } + + 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 was not specified, do not 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; + 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 could not obtain"); + } + + if(data->set.ssl.certinfo && chainp) { + unsigned int i; + + result = Curl_ssl_init_certinfo(data, (int)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, (int)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) { + const char *cause = "certificate error, no details available"; + if(verify_status & GNUTLS_CERT_EXPIRED) + cause = "certificate has expired"; + else if(verify_status & GNUTLS_CERT_SIGNER_NOT_FOUND) + cause = "certificate signer not trusted"; + else if(verify_status & GNUTLS_CERT_INSECURE_ALGORITHM) + cause = "certificate uses insecure algorithm"; + else if(verify_status & GNUTLS_CERT_INVALID_OCSP_STATUS) + cause = "attached OCSP status response is invalid"; + failf(data, "server verification failed: %s. (CAfile: %s " + "CRLfile: %s)", cause, + 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) { + 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); + + 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); + if(status != GNUTLS_OCSP_CERT_GOOD) + return CURLE_SSL_INVALIDCERTSTATUS; + } + 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 = (int)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. */ + + /* This function does not handle trailing dots, so if we have an SNI name + use that and fallback to the hostname only if there is no SNI (like for + IP addresses) */ + rc = (int)gnutls_x509_crt_check_hostname(x509_cert, + peer->sni ? peer->sni : + peer->hostname); +#if GNUTLS_VERSION_NUMBER < 0x030306 + /* Before 3.3.6, gnutls_x509_crt_check_hostname() did not 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 was not 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 hostname '%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((gnutls_pk_algorithm_t)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; + + /* 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 = cf_gtls_update_session_id(cf, data, session); + +out: + return result; +} + +static CURLcode gtls_set_earlydata(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, size_t blen) +{ + struct ssl_connect_data *connssl = cf->ctx; + ssize_t nwritten = 0; + CURLcode result = CURLE_OK; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_use); + DEBUGASSERT(Curl_bufq_is_empty(&connssl->earlydata)); + if(blen) { + if(blen > connssl->earlydata_max) + blen = connssl->earlydata_max; + nwritten = Curl_bufq_write(&connssl->earlydata, buf, blen, &result); + CURL_TRC_CF(data, cf, "gtls_set_earlydata(len=%zu) -> %zd", + blen, nwritten); + if(nwritten < 0) + return result; + } + connssl->earlydata_state = ssl_earlydata_sending; + connssl->earlydata_skip = Curl_bufq_len(&connssl->earlydata); + return CURLE_OK; +} + +static CURLcode gtls_send_earlydata(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; + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen; + ssize_t n; + + DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending); + backend->gtls.io_result = CURLE_OK; + while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) { + n = gnutls_record_send_early_data(backend->gtls.session, buf, blen); + CURL_TRC_CF(data, cf, "gtls_send_earlydata(len=%zu) -> %zd", + blen, n); + if(n < 0) { + if(n == GNUTLS_E_AGAIN) + result = CURLE_AGAIN; + else + result = backend->gtls.io_result ? + backend->gtls.io_result : CURLE_SEND_ERROR; + goto out; + } + else if(!n) { + /* gnutls is buggy, it *SHOULD* return the amount of bytes it took in. + * Instead it returns 0 if everything was written. */ + n = (ssize_t)blen; + } + + Curl_bufq_skip(&connssl->earlydata, (size_t)n); + } + /* sent everything there was */ + infof(data, "SSL sending %" FMT_OFF_T " bytes of early data", + connssl->earlydata_skip); +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' (doing handshake with the server), and + 'ssl_connect_3' (verifying and getting stats). + */ +static CURLcode +gtls_connect_common(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool nonblocking, + bool *done) { + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + + DEBUGASSERT(backend); + + /* Initiate the connection, if not already done */ + if(connssl->connecting_state == ssl_connect_1) { + result = gtls_connect_step1(cf, data); + if(result) + goto out; + connssl->connecting_state = ssl_connect_2; + } + + if(connssl->connecting_state == ssl_connect_2) { + if(connssl->earlydata_state == ssl_earlydata_use) { + goto out; + } + else if(connssl->earlydata_state == ssl_earlydata_sending) { + result = gtls_send_earlydata(cf, data); + if(result) + goto out; + connssl->earlydata_state = ssl_earlydata_sent; + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_pgrsEarlyData(data, (curl_off_t)connssl->earlydata_skip); + } + DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) || + (connssl->earlydata_state == ssl_earlydata_sent)); + + result = handshake(cf, data, TRUE, nonblocking); + if(result) + goto out; + connssl->connecting_state = ssl_connect_3; + } + + /* Finish connecting once the handshake is done */ + if(connssl->connecting_state == ssl_connect_3) { + gnutls_datum_t proto; + int rc; + result = gtls_verifyserver(cf, data, backend->gtls.session); + if(result) + goto out; + + connssl->state = ssl_connection_complete; + connssl->connecting_state = ssl_connect_1; + + rc = gnutls_alpn_get_selected_protocol(backend->gtls.session, &proto); + if(rc) { /* No ALPN from server */ + proto.data = NULL; + proto.size = 0; + } + + result = Curl_alpn_set_negotiated(cf, data, connssl, + proto.data, proto.size); + if(result) + goto out; + + if(connssl->earlydata_state == ssl_earlydata_sent) { + if(gnutls_session_get_flags(backend->gtls.session) & + GNUTLS_SFLAGS_EARLY_DATA) { + connssl->earlydata_state = ssl_earlydata_accepted; + infof(data, "Server accepted %zu bytes of TLS early data.", + connssl->earlydata_skip); + } + else { + connssl->earlydata_state = ssl_earlydata_rejected; + if(!Curl_ssl_cf_is_proxy(cf)) + Curl_pgrsEarlyData(data, -(curl_off_t)connssl->earlydata_skip); + infof(data, "Server rejected TLS early data."); + connssl->earlydata_skip = 0; + } + } + } + +out: + if(result == CURLE_AGAIN) { + *done = FALSE; + return CURLE_OK; + } + *done = ((connssl->connecting_state == ssl_connect_1) || + (connssl->state == ssl_connection_deferred)); + return result; +} + +static CURLcode gtls_connect_nonblocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + if(connssl->state == ssl_connection_deferred) { + /* We refuse to be pushed, we are waiting for someone to send/recv. */ + *done = TRUE; + return CURLE_OK; + } + 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 CURLcode gtls_connect_deferred(struct Curl_cfilter *cf, + struct Curl_easy *data, + const void *buf, + size_t blen, + bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + CURLcode result = CURLE_OK; + + DEBUGASSERT(connssl->state == ssl_connection_deferred); + *done = FALSE; + if(connssl->earlydata_state == ssl_earlydata_use) { + result = gtls_set_earlydata(cf, data, buf, blen); + if(result) + return result; + } + + return gtls_connect_common(cf, data, TRUE, done); +} + +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 *buf, + size_t blen, + 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; + size_t nwritten, total_written = 0; + + DEBUGASSERT(backend); + + if(connssl->state == ssl_connection_deferred) { + bool done = FALSE; + *curlcode = gtls_connect_deferred(cf, data, buf, blen, &done); + if(*curlcode) { + rc = -1; + goto out; + } + else if(!done) { + *curlcode = CURLE_AGAIN; + rc = -1; + goto out; + } + DEBUGASSERT(connssl->state == ssl_connection_complete); + } + + if(connssl->earlydata_skip) { + if(connssl->earlydata_skip >= blen) { + connssl->earlydata_skip -= blen; + *curlcode = CURLE_OK; + rc = (ssize_t)blen; + goto out; + } + else { + total_written += connssl->earlydata_skip; + buf = ((const char *)buf) + connssl->earlydata_skip; + blen -= connssl->earlydata_skip; + connssl->earlydata_skip = 0; + } + } + + while(blen) { + backend->gtls.io_result = CURLE_OK; + rc = gnutls_record_send(backend->gtls.session, buf, blen); + + if(rc < 0) { + if(total_written && (rc == GNUTLS_E_AGAIN)) { + *curlcode = CURLE_OK; + rc = (ssize_t)total_written; + goto out; + } + *curlcode = (rc == GNUTLS_E_AGAIN) ? + CURLE_AGAIN : + (backend->gtls.io_result ? backend->gtls.io_result : CURLE_SEND_ERROR); + + rc = -1; + goto out; + } + nwritten = (size_t)rc; + total_written += nwritten; + DEBUGASSERT(nwritten <= blen); + buf = (char *)buf + nwritten; + blen -= nwritten; + } + rc = total_written; + +out: + return rc; +} + +/* + * This function is called to shut down the SSL layer but keep the + * socket open (CCC - Clear Command Channel) + */ +static CURLcode gtls_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct gtls_ssl_backend_data *backend = + (struct gtls_ssl_backend_data *)connssl->backend; + char buf[1024]; + CURLcode result = CURLE_OK; + ssize_t nread; + size_t i; + + DEBUGASSERT(backend); + /* If we have no handshaked connection or already shut down */ + if(!backend->gtls.session || cf->shutdown || + connssl->state != ssl_connection_complete) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->gtls.sent_shutdown) { + /* do this only once */ + backend->gtls.sent_shutdown = TRUE; + if(send_shutdown) { + int ret = gnutls_bye(backend->gtls.session, GNUTLS_SHUT_RDWR); + if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) { + CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye EAGAIN"); + connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + backend->gtls.sent_shutdown = FALSE; + result = CURLE_OK; + goto out; + } + if(ret != GNUTLS_E_SUCCESS) { + CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye error: '%s'(%d)", + gnutls_strerror((int)ret), (int)ret); + result = CURLE_RECV_ERROR; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + for(i = 0; i < 10; ++i) { + nread = gnutls_record_recv(backend->gtls.session, buf, sizeof(buf)); + if(nread <= 0) + break; + } + if(nread > 0) { + /* still data coming in? */ + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + *done = TRUE; + } + else if((nread == GNUTLS_E_AGAIN) || (nread == GNUTLS_E_INTERRUPTED)) { + connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + } + else { + CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)", + gnutls_strerror((int)nread), (int)nread); + result = CURLE_RECV_ERROR; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +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); + CURL_TRC_CF(data, cf, "close"); + if(backend->gtls.session) { + gnutls_deinit(backend->gtls.session); + backend->gtls.session = NULL; + } + if(backend->gtls.shared_creds) { + Curl_gtls_shared_creds_free(&backend->gtls.shared_creds); + } +#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 +} + +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); + + if(connssl->state == ssl_connection_deferred) { + bool done = FALSE; + *curlcode = gtls_connect_deferred(cf, data, NULL, 0, &done); + if(*curlcode) { + ret = -1; + goto out; + } + else if(!done) { + *curlcode = CURLE_AGAIN; + ret = -1; + goto out; + } + DEBUGASSERT(connssl->state == ssl_connection_complete); + } + + 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 | + SSLSUPP_CA_CACHE, + + 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 */ + gtls_recv, /* recv decrypted data */ + gtls_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_GNUTLS */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.h b/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.h new file mode 100644 index 0000000000000000000000000000000000000000..4f9c540ed27aaa66a52ba7d83793ec372e5081f3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/gtls.h @@ -0,0 +1,108 @@ +#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 +#include "timeval.h" + +#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 ssl_connect_data; + +struct gtls_shared_creds { + gnutls_certificate_credentials_t creds; + char *CAfile; /* CAfile path used to generate X509 store */ + struct curltime time; /* when the shared creds was created */ + size_t refcount; + BIT(trust_setup); /* x509 anchors + CRLs have been set up */ +}; + +CURLcode Curl_gtls_shared_creds_create(struct Curl_easy *data, + struct gtls_shared_creds **pcreds); +CURLcode Curl_gtls_shared_creds_up_ref(struct gtls_shared_creds *creds); +void Curl_gtls_shared_creds_free(struct gtls_shared_creds **pcreds); + +struct gtls_ctx { + gnutls_session_t session; + struct gtls_shared_creds *shared_creds; +#ifdef USE_GNUTLS_SRP + gnutls_srp_client_credentials_t srp_client_cred; +#endif + CURLcode io_result; /* result of last IO cfilter operation */ + BIT(sent_shutdown); +}; + +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, + struct ssl_connect_data *connssl, + 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); + +/* Extract TLS session and place in cache, if configured. */ +CURLcode Curl_gtls_update_session_id(struct Curl_cfilter *cf, + struct Curl_easy *data, + gnutls_session_t session, + struct ssl_peer *peer, + const char *alpn); + +extern const struct Curl_ssl Curl_ssl_gnutls; + +#endif /* USE_GNUTLS */ +#endif /* HEADER_CURL_GTLS_H */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/hostcheck.c b/local-test-curl-delta-01/afc-curl/lib/vtls/hostcheck.c new file mode 100644 index 0000000000000000000000000000000000000000..e46439a5ecc72d109bf810dddbc626c8e94fd386 --- /dev/null +++ b/local-test-curl-delta-01/afc-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 hostnames 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/local-test-curl-delta-01/afc-curl/lib/vtls/hostcheck.h b/local-test-curl-delta-01/afc-curl/lib/vtls/hostcheck.h new file mode 100644 index 0000000000000000000000000000000000000000..6b4e37964430f7be1f4a001b94f924647c8133ff --- /dev/null +++ b/local-test-curl-delta-01/afc-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 is 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/local-test-curl-delta-01/afc-curl/lib/vtls/keylog.c b/local-test-curl-delta-01/afc-curl/lib/vtls/keylog.c new file mode 100644 index 0000000000000000000000000000000000000000..ca86c1560823a9cb6bba9662eb8d44314c78ddef --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/keylog.h b/local-test-curl-delta-01/afc-curl/lib/vtls/keylog.h new file mode 100644 index 0000000000000000000000000000000000000000..eff5bf38f3518a15d00839cb06ca9d3957440954 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls.c b/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls.c new file mode 100644 index 0000000000000000000000000000000000000000..e071ded72fc0bdad157994dd6493fd520ccc5079 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls.c @@ -0,0 +1,1674 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 */ + +#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 /* MBEDTLS_VERSION_MAJOR >= 2 */ + +#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 "x509asn1.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; + BIT(initialized); /* mbedtls_ssl_context is initialized */ + BIT(sent_shutdown); +}; + +/* 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(TLS13_SUPPORT) && defined(MBEDTLS_SSL_SESSION_TICKETS) +#define HAS_SESSION_TICKETS +#endif + +#ifdef 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, FALSE, + &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://web.archive.org/web/20200921194007/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) + +static CURLcode +mbed_set_ssl_version_min_max(struct Curl_easy *data, + struct mbed_ssl_backend_data *backend, + struct ssl_primary_config *conn_config) +{ + /* TLS 1.0 and TLS 1.1 were dropped with mbedTLS 3.0.0 (2021). So, since + * then, and before the introduction of TLS 1.3 in 3.6.0 (2024), this + * function basically always sets TLS 1.2 as min/max, unless given + * unsupported option values. */ + +#if MBEDTLS_VERSION_NUMBER < 0x03020000 + int ver_min = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ + int ver_max = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ +#else + /* mbedTLS 3.2.0 (2022) introduced new methods for setting TLS version */ + mbedtls_ssl_protocol_version ver_min = MBEDTLS_SSL_VERSION_TLS1_2; + mbedtls_ssl_protocol_version ver_max = MBEDTLS_SSL_VERSION_TLS1_2; +#endif + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: +#if MBEDTLS_VERSION_NUMBER < 0x03000000 + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + ver_min = MBEDTLS_SSL_MINOR_VERSION_1; + break; + case CURL_SSLVERSION_TLSv1_1: + ver_min = MBEDTLS_SSL_MINOR_VERSION_2; + break; +#else + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + case CURL_SSLVERSION_TLSv1_1: +#endif + case CURL_SSLVERSION_TLSv1_2: + /* ver_min = MBEDTLS_SSL_VERSION_TLS1_2; */ + break; + case CURL_SSLVERSION_TLSv1_3: +#ifdef TLS13_SUPPORT + ver_min = MBEDTLS_SSL_VERSION_TLS1_3; + break; +#endif + default: + failf(data, "mbedTLS: unsupported minimum TLS version value: %x", + conn_config->version); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: +#ifdef TLS13_SUPPORT + ver_max = MBEDTLS_SSL_VERSION_TLS1_3; + break; +#endif + case CURL_SSLVERSION_MAX_TLSv1_2: + /* ver_max = MBEDTLS_SSL_VERSION_TLS1_2; */ + break; +#if MBEDTLS_VERSION_NUMBER < 0x03000000 + case CURL_SSLVERSION_MAX_TLSv1_1: + ver_max = MBEDTLS_SSL_MINOR_VERSION_2; + break; + case CURL_SSLVERSION_MAX_TLSv1_0: + ver_max = MBEDTLS_SSL_MINOR_VERSION_1; + break; +#else + case CURL_SSLVERSION_MAX_TLSv1_1: + case CURL_SSLVERSION_MAX_TLSv1_0: +#endif + default: + failf(data, "mbedTLS: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + +#if MBEDTLS_VERSION_NUMBER < 0x03020000 + mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, + ver_min); + mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, + ver_max); +#else + mbedtls_ssl_conf_min_tls_version(&backend->config, ver_min); + mbedtls_ssl_conf_max_tls_version(&backend->config, ver_max); +#endif + + return CURLE_OK; +} + +/* 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 +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 +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; +} +#endif + +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 *ciphers12, + const char *ciphers13) +{ + const char *ciphers = ciphers12; + const int *supported; + int *selected; + size_t supported_len, count = 0, default13_count = 0, i, j; + 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; + +#ifndef TLS13_SUPPORT + (void) ciphers13, (void) j; +#else + if(!ciphers13) { + /* Add default TLSv1.3 ciphers to selection */ + for(j = 0; j < supported_len; j++) { + uint16_t id = (uint16_t) supported[j]; + if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6) != 0) + continue; + + selected[count++] = id; + } + + default13_count = count; + } + else + ciphers = ciphers13; + +add_ciphers: +#endif + 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) { + if(i >= default13_count) + infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + selected[count++] = id; + } + +#ifdef TLS13_SUPPORT + if(ciphers == ciphers13 && ciphers12) { + ciphers = ciphers12; + goto add_ciphers; + } + + if(!ciphers12) { + /* Add default TLSv1.2 ciphers to selection */ + for(j = 0; j < supported_len; j++) { + uint16_t id = (uint16_t) supported[j]; + if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6) == 0) + continue; + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != id; i++); + if(i < count) + continue; + + selected[count++] = id; + } + } +#endif + + 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 void +mbed_dump_cert_info(struct Curl_easy *data, const mbedtls_x509_crt *crt) +{ +#if defined(CURL_DISABLE_VERBOSE_STRINGS) || \ + (MBEDTLS_VERSION_NUMBER >= 0x03000000 && defined(MBEDTLS_X509_REMOVE_INFO)) + (void) data, (void) crt; +#else + const size_t bufsize = 16384; + char *p, *buffer = malloc(bufsize); + + if(buffer && mbedtls_x509_crt_info(buffer, bufsize, " ", crt) > 0) { + infof(data, "Server certificate:"); + for(p = buffer; *p; p += *p != '\0') { + size_t s = strcspn(p, "\n"); + infof(data, "%.*s", (int) s, p); + p += s; + } + } + else + infof(data, "Unable to dump certificate information"); + + free(buffer); +#endif +} + +static void +mbed_extract_certinfo(struct Curl_easy *data, const mbedtls_x509_crt *crt) +{ + CURLcode result; + const mbedtls_x509_crt *cur; + int i; + + for(i = 0, cur = crt; cur; ++i, cur = cur->next); + result = Curl_ssl_init_certinfo(data, i); + + for(i = 0, cur = crt; result == CURLE_OK && cur; ++i, cur = cur->next) { + const char *beg = (const char *) cur->raw.p; + const char *end = beg + cur->raw.len; + result = Curl_extract_certinfo(data, i, beg, end); + } +} + +static int mbed_verify_cb(void *ptr, mbedtls_x509_crt *crt, + int depth, uint32_t *flags) +{ + struct Curl_cfilter *cf = (struct Curl_cfilter *) ptr; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_easy *data = CF_DATA_CURRENT(cf); + + if(depth == 0) { + if(data->set.verbose) + mbed_dump_cert_info(data, crt); + if(data->set.ssl.certinfo) + mbed_extract_certinfo(data, crt); + } + + if(!conn_config->verifypeer) + *flags = 0; + else if(!conn_config->verifyhost) + *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH; + + if(*flags) { +#if MBEDTLS_VERSION_NUMBER < 0x03000000 || !defined(MBEDTLS_X509_REMOVE_INFO) + char buf[128]; + mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags); + failf(data, "mbedTLS: %s", buf); +#else + failf(data, "mbedTLS: certificate verification error 0x%08x", *flags); +#endif + } + + return 0; +} + +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); + DEBUGASSERT(!backend->initialized); + + 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 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 client cert data %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; + } + +#ifdef MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED + /* New in mbedTLS 3.6.1, need to enable, default is now disabled */ + mbedtls_ssl_conf_tls13_enable_signal_new_session_tickets(&backend->config, + MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED); +#endif + + /* Always let mbedTLS verify certificates, if verifypeer or verifyhost are + * disabled we clear the corresponding error flags in the verify callback + * function. That is also where we log verification errors. */ + mbedtls_ssl_conf_verify(&backend->config, mbed_verify_cb, cf); + mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED); + + mbedtls_ssl_init(&backend->ssl); + backend->initialized = TRUE; + + /* new profile with RSA min key len = 1024 ... */ + mbedtls_ssl_conf_cert_profile(&backend->config, + &mbedtls_x509_crt_profile_fr); + + ret = mbed_set_ssl_version_min_max(data, backend, conn_config); + if(ret != CURLE_OK) + return ret; + + 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() */); + +#ifndef TLS13_SUPPORT + if(conn_config->cipher_list) { + CURLcode result = mbed_set_selected_ciphers(data, backend, + conn_config->cipher_list, + NULL); +#else + if(conn_config->cipher_list || conn_config->cipher_list13) { + CURLcode result = mbed_set_selected_ciphers(data, backend, + conn_config->cipher_list, + conn_config->cipher_list13); +#endif + if(result != CURLE_OK) { + failf(data, "mbedTLS: failed to set cipher suites"); + return result; + } + } + 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 is a cached ID we can/should use here! */ + if(ssl_config->primary.cache_session) { + void *sdata = NULL; + size_t slen = 0; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + &sdata, &slen, NULL) && slen) { + mbedtls_ssl_session session; + + mbedtls_ssl_session_init(&session); + ret = mbedtls_ssl_session_load(&session, sdata, slen); + if(ret) { + failf(data, "error loading cached session: -0x%x", -ret); + } + else { + ret = mbedtls_ssl_set_session(&backend->ssl, &session); + if(ret) + failf(data, "error setting session: -0x%x", -ret); + else + infof(data, "SSL reusing session ID"); + } + mbedtls_ssl_session_free(&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 does not 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) { + CURLcode result = (*data->set.ssl.fsslctx)(data, &backend->config, + data->set.ssl.fsslctxp); + if(result != CURLE_OK) { + failf(data, "error signaled by ssl ctx callback"); + return result; + } + } + + 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; +#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->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } + else if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + failf(data, "peer certificate could not be verified"); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(ret) { + char errorbuf[128]; +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + CURL_TRC_CF(data, cf, "TLS version %04X", + mbedtls_ssl_get_version_number(&backend->ssl)); +#endif + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_handshake returned: (-0x%04X) %s", + -ret, errorbuf); + return CURLE_SSL_CONNECT_ERROR; + } + +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + { + char cipher_str[64]; + uint16_t cipher_id; + 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: %s Handshake complete, cipher is %s", + mbedtls_ssl_get_version(&backend->ssl), cipher_str); + } +#else + infof(data, "mbedTLS: %s Handshake complete", + mbedtls_ssl_get_version(&backend->ssl)); +#endif + + if(pinnedpubkey) { + int size; + CURLcode result; + const mbedtls_x509_crt *peercert; + mbedtls_x509_crt *p = NULL; + unsigned char *pubkey = NULL; + + peercert = mbedtls_ssl_get_peer_cert(&backend->ssl); +#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/Mbed-TLS/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, connssl, (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 *session, size_t slen) +{ + (void)slen; + free(session); +} + +static CURLcode +mbed_new_session(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_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + CURLcode result = CURLE_OK; + + DEBUGASSERT(backend); + if(ssl_config->primary.cache_session) { + int ret; + mbedtls_ssl_session session; + unsigned char *sdata = NULL; + size_t slen = 0; + + mbedtls_ssl_session_init(&session); + ret = mbedtls_ssl_get_session(&backend->ssl, &session); + if(ret) { + if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED) + mbedtls_ssl_session_free(&session); + failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret); + return CURLE_SSL_CONNECT_ERROR; + } + + mbedtls_ssl_session_save(&session, NULL, 0, &slen); + if(!slen) { + failf(data, "failed to serialize session: length is 0"); + } + else { + sdata = malloc(slen); + if(sdata) { + ret = mbedtls_ssl_session_save(&session, sdata, slen, &slen); + if(ret) { + failf(data, "failed to serialize session: -0x%x", -ret); + } + else { + Curl_ssl_sessionid_lock(data); + result = Curl_ssl_set_sessionid(cf, data, &connssl->peer, NULL, + sdata, slen, mbedtls_session_free); + Curl_ssl_sessionid_unlock(data); + if(!result) + sdata = NULL; + } + } + } + mbedtls_ssl_session_free(&session); + free(sdata); + } + return result; +} + +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) { + CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> -0x%04X", + len, -ret); + *curlcode = ((ret == MBEDTLS_ERR_SSL_WANT_WRITE) +#ifdef TLS13_SUPPORT + || (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) +#endif + ) ? CURLE_AGAIN : CURLE_SEND_ERROR; + ret = -1; + } + + return ret; +} + +static void mbedtls_close_all(struct Curl_easy *data) +{ + (void)data; +} + +static CURLcode mbedtls_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)connssl->backend; + unsigned char buf[1024]; + CURLcode result = CURLE_OK; + int ret; + size_t i; + + DEBUGASSERT(backend); + + if(!backend->initialized || cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->sent_shutdown) { + /* do this only once */ + backend->sent_shutdown = TRUE; + if(send_shutdown) { + ret = mbedtls_ssl_close_notify(&backend->ssl); + switch(ret) { + case 0: /* we sent it, receive from the server */ + break; + case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: /* server also closed */ + *done = TRUE; + goto out; + case MBEDTLS_ERR_SSL_WANT_READ: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + goto out; + case MBEDTLS_ERR_SSL_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + default: + CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", -ret); + result = CURLE_RECV_ERROR; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + for(i = 0; i < 10; ++i) { + ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf)); + /* This seems to be a bug in mbedTLS TLSv1.3 where it reports + * WANT_READ, but has not encountered an EAGAIN. */ + if(ret == MBEDTLS_ERR_SSL_WANT_READ) + ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf)); +#ifdef TLS13_SUPPORT + if(ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) + continue; +#endif + if(ret <= 0) + break; + } + + if(ret > 0) { + /* still data coming in? */ + CURL_TRC_CF(data, cf, "mbedtls_shutdown, still getting data"); + } + else if(ret == 0 || (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)) { + /* We got the close notify alert and are done. */ + CURL_TRC_CF(data, cf, "mbedtls_shutdown done"); + *done = TRUE; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_READ) { + CURL_TRC_CF(data, cf, "mbedtls_shutdown, need RECV"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + } + else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + CURL_TRC_CF(data, cf, "mbedtls_shutdown, need SEND"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + } + else { + CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", -ret); + result = CURLE_RECV_ERROR; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +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; + + (void)data; + DEBUGASSERT(backend); + if(backend->initialized) { + 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 */ + backend->initialized = FALSE; + } +} + +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; + + (void)data; + DEBUGASSERT(backend); + + ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, + buffersize); + if(ret <= 0) { + CURL_TRC_CF(data, cf, "mbedtls_ssl_read(len=%zu) -> -0x%04X", + buffersize, -ret); + switch(ret) { +#ifdef HAS_SESSION_TICKETS + case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET: + mbed_new_session(cf, data); + FALLTHROUGH(); +#endif + case MBEDTLS_ERR_SSL_WANT_READ: + *curlcode = CURLE_AGAIN; + ret = -1; + break; + case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: + *curlcode = CURLE_OK; + ret = 0; + break; + default: { + char errorbuf[128]; + mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); + failf(data, "ssl_read returned: (-0x%04X) %s", -ret, errorbuf); + *curlcode = CURLE_RECV_ERROR; + ret = -1; + break; + } + } + } + return (ssize_t)ret; +} + +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 +} + +/* 'data' might be NULL */ +static CURLcode mbedtls_random(struct Curl_easy *data, + unsigned char *entropy, size_t length) +{ +#if defined(MBEDTLS_CTR_DRBG_C) + int ret; + mbedtls_entropy_context ctr_entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_entropy_init(&ctr_entropy); + mbedtls_ctr_drbg_init(&ctr_drbg); + (void)data; + + ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, + &ctr_entropy, NULL, 0); + + if(!ret) + ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length); + + 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 are 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) { + + /* 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 is available. */ + if(connssl->io_need) { + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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. + */ + connssl->io_need = CURL_SSL_IO_NEED_NONE; + retcode = mbed_connect_step2(cf, data); + if(retcode || + (nonblocking && (ssl_connect_2 == connssl->connecting_state))) + return retcode; + + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + /* For tls1.3 we get notified about new sessions */ +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + struct ssl_connect_data *ctx = cf->ctx; + struct mbed_ssl_backend_data *backend = + (struct mbed_ssl_backend_data *)ctx->backend; + + if(mbedtls_ssl_get_version_number(&backend->ssl) <= + MBEDTLS_SSL_VERSION_TLS1_2) { +#else + { /* no TLSv1.3 supported here */ +#endif + retcode = mbed_new_session(cf, data); + if(retcode) + return retcode; + } + connssl->connecting_state = ssl_connect_done; + } + + 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 +#ifdef TLS13_SUPPORT + { + int ret; +#ifdef THREADING_SUPPORT + Curl_mbedtlsthreadlock_lock_function(0); +#endif + ret = psa_crypto_init(); +#ifdef THREADING_SUPPORT + Curl_mbedtlsthreadlock_unlock_function(0); +#endif + if(ret != PSA_SUCCESS) + return 0; + } +#endif /* TLS13_SUPPORT */ + 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_CERTINFO | + SSLSUPP_PINNEDPUBKEY | + SSLSUPP_SSL_CTX | +#ifdef TLS13_SUPPORT + SSLSUPP_TLS13_CIPHERSUITES | +#endif + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST, + + sizeof(struct mbed_ssl_backend_data), + + mbedtls_init, /* init */ + mbedtls_cleanup, /* cleanup */ + mbedtls_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + mbedtls_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 */ + mbed_recv, /* recv decrypted data */ + mbed_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_MBEDTLS */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls.h b/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls.h new file mode 100644 index 0000000000000000000000000000000000000000..d8a0a06eb6aac22289e2b91fcad3a7164b77f9ae --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls_threadlock.c b/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls_threadlock.c new file mode 100644 index 0000000000000000000000000000000000000000..b96a904fcb1b6ca2c209faa672c5fbfa9fa615ff --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls_threadlock.h b/local-test-curl-delta-01/afc-curl/lib/vtls/mbedtls_threadlock.h new file mode 100644 index 0000000000000000000000000000000000000000..484626852f5576e09cffc5bbe500d9f52e2d25b6 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.c b/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.c new file mode 100644 index 0000000000000000000000000000000000000000..1b0e8dd5f0e867001868d49468673b82c7ef2697 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.c @@ -0,0 +1,5367 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) +# 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://docs.openssl.org/master/man3/SSL_CTX_set1_curves/ + * 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)) || defined(USE_MSH3) +# define OSSL_PACKAGE "quictls" +# else +# define OSSL_PACKAGE "OpenSSL" +#endif +#endif + +#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) +typedef size_t numcert_t; +#else +typedef int numcert_t; +#endif +#define ossl_valsize_t numcert_t + +#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 +/* 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 */ + +static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl); + +static CURLcode push_certinfo(struct Curl_easy *data, + BIO *mem, const char *label, int num) + WARN_UNUSED_RESULT; + +static CURLcode push_certinfo(struct Curl_easy *data, + BIO *mem, const char *label, int num) +{ + char *ptr; + long len = BIO_get_mem_data(mem, &ptr); + CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len); + (void)BIO_reset(mem); + return result; +} + +static CURLcode pubkey_show(struct Curl_easy *data, + BIO *mem, + int num, + const char *type, + const char *name, + const BIGNUM *bn) +{ + char namebuf[32]; + + msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); + + if(bn) + BN_print(mem, bn); + return push_certinfo(data, mem, 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 CURLcode X509V3_ext(struct Curl_easy *data, + int certnum, + CONST_EXTS STACK_OF(X509_EXTENSION) *exts) +{ + int i; + CURLcode result = CURLE_OK; + + if((int)sk_X509_EXTENSION_num(exts) <= 0) + /* no extensions, bail out */ + return result; + + for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) { + ASN1_OBJECT *obj; + X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i); + BUF_MEM *biomem; + char namebuf[128]; + BIO *bio_out = BIO_new(BIO_s_mem()); + + if(!bio_out) + return result; + + 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); + result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data, + biomem->length); + BIO_free(bio_out); + if(result) + break; + } + return result; +} + +static CURLcode 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) + result = CURLE_OUT_OF_MEMORY; + + for(i = 0; !result && (i < (int)numcerts); i++) { + ASN1_INTEGER *num; + X509 *x = sk_X509_value(sk, (ossl_valsize_t)i); + EVP_PKEY *pubkey = NULL; + int j; + const ASN1_BIT_STRING *psig = NULL; + + X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); + result = push_certinfo(data, mem, "Subject", i); + if(result) + break; + + X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); + result = push_certinfo(data, mem, "Issuer", i); + if(result) + break; + + BIO_printf(mem, "%lx", X509_get_version(x)); + result = push_certinfo(data, mem, "Version", i); + if(result) + break; + + 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]); + result = push_certinfo(data, mem, "Serial Number", i); + if(result) + break; + +#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); + result = push_certinfo(data, mem, "Signature Algorithm", i); + if(result) + break; + } + + xpubkey = X509_get_X509_PUBKEY(x); + if(xpubkey) { + X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey); + if(pubkeyoid) { + i2a_ASN1_OBJECT(mem, pubkeyoid); + result = push_certinfo(data, mem, "Public Key Algorithm", i); + if(result) + break; + } + } + + result = X509V3_ext(data, i, X509_get0_extensions(x)); + if(result) + break; + } +#else + { + /* before OpenSSL 1.0.2 */ + X509_CINF *cinf = x->cert_info; + + i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); + result = push_certinfo(data, mem, "Signature Algorithm", i); + + if(!result) { + i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); + result = push_certinfo(data, mem, "Public Key Algorithm", i); + } + + if(!result) + result = X509V3_ext(data, i, cinf->extensions); + + if(result) + break; + + psig = x->signature; + } +#endif + + ASN1_TIME_print(mem, X509_get0_notBefore(x)); + result = push_certinfo(data, mem, "Start date", i); + if(result) + break; + + ASN1_TIME_print(mem, X509_get0_notAfter(x)); + result = push_certinfo(data, mem, "Expire date", i); + if(result) + break; + + 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 */ + result = push_certinfo(data, mem, "RSA Public Key", i); + if(result) + break; + 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(!result && psig) { + for(j = 0; j < psig->length; j++) + BIO_printf(mem, "%02x:", psig->data[j]); + result = push_certinfo(data, mem, "Signature", i); + } + + if(!result) { + PEM_write_bio_X509(mem, x); + result = push_certinfo(data, mem, "Cert", i); + } + } + + BIO_free(mem); + + if(result) + /* cleanup all leftovers */ + Curl_ssl_free_certinfo(data); + + return result; +} + +#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); + if(blen < 0) + return 0; + + nwritten = Curl_conn_cf_send(cf->next, data, buf, (size_t)blen, FALSE, + &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; + if(blen < 0) + return 0; + + nread = Curl_conn_cf_recv(cf->next, data, buf, (size_t)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 does not 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 && num >= 0) { + 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()); +} + +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 + + /* 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 *= (time_t)i + 1; + tv.tv_usec *= (int)i + 2; + tv.tv_sec ^= ((Curl_now().tv_sec + (time_t)Curl_now().tv_usec) * + (time_t)(i + 3)) << 8; + tv.tv_usec ^= (int) ((Curl_now().tv_sec + (time_t)Curl_now().tv_usec) * + (time_t)(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 filename 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 ossl_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 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 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 + goto end; + + if(!pkey) + goto end; + + ret = SSL_CTX_use_PrivateKey(ctx, pkey); + EVP_PKEY_free(pkey); +end: + BIO_free(in); + return ret; +} + +static int +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) + 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 = ossl_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 ? + 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 ? + 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 did not 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 do not need the handle any more... */ + } + else { + failf(data, "crypto engine not set, cannot 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 would 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 = ossl_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 ? + 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 do not need the handle any more... */ + } + else { + failf(data, "crypto engine not set, cannot 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, do not check the private key if its flags indicate + * it does not 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; +} + +/* returns non-zero on failure */ +static CURLcode x509_name_oneline(X509_NAME *a, struct dynbuf *d) +{ + BIO *bio_out = BIO_new(BIO_s_mem()); + BUF_MEM *biomem; + int rc; + CURLcode result = CURLE_OUT_OF_MEMORY; + + if(bio_out) { + Curl_dyn_reset(d); + rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC); + if(rc != -1) { + BIO_get_mem_ptr(bio_out, &biomem); + result = Curl_dyn_addn(d, biomem->data, biomem->length); + BIO_free(bio_out); + } + } + return result; +} + +/** + * 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 CURLcode ossl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + char buf[1024]; + int nread = -1, err; + unsigned long sslerr; + size_t i; + + DEBUGASSERT(octx); + if(!octx->ssl || cf->shutdown) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { + /* We have not started the shutdown from our side yet. Check + * if the server already sent us one. */ + ERR_clear_error(); + for(i = 0; i < 10; ++i) { + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread); + if(nread <= 0) + break; + } + err = SSL_get_error(octx->ssl, nread); + if(!nread && err == SSL_ERROR_ZERO_RETURN) { + bool input_pending; + /* Yes, it did. */ + if(!send_shutdown) { + CURL_TRC_CF(data, cf, "SSL shutdown received, not sending"); + *done = TRUE; + goto out; + } + else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) { + /* Server closed the connection after its closy notify. It + * seems not interested to see our close notify, so do not + * send it. We are done. */ + connssl->peer_closed = TRUE; + CURL_TRC_CF(data, cf, "peer closed connection"); + *done = TRUE; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { + ERR_clear_error(); + CURL_TRC_CF(data, cf, "send SSL close notify"); + if(SSL_shutdown(octx->ssl) == 1) { + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + *done = TRUE; + goto out; + } + if(SSL_ERROR_WANT_WRITE == SSL_get_error(octx->ssl, nread)) { + CURL_TRC_CF(data, cf, "SSL shutdown still wants to send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + } + /* Having sent the close notify, we use SSL_read() to get the + * missing close notify from the server. */ + } + + for(i = 0; i < 10; ++i) { + ERR_clear_error(); + nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); + CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread); + if(nread <= 0) + break; + } + err = SSL_get_error(octx->ssl, nread); + switch(err) { + case SSL_ERROR_ZERO_RETURN: /* no more data */ + if(SSL_shutdown(octx->ssl) == 1) + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + else + CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed"); + *done = TRUE; + break; + case SSL_ERROR_NONE: /* just did not get anything */ + 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, want receive"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + break; + case SSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + break; + default: + /* Server seems to have closed the connection without sending us + * a close notify. */ + sslerr = ERR_get_error(); + CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d", + (sslerr ? + ossl_strerror(sslerr, buf, sizeof(buf)) : + SSL_ERROR_to_str(err)), + SOCKERRNO); + *done = TRUE; + result = CURLE_OK; + break; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +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) { + 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; + } +} + +static void ossl_session_free(void *sessionid, size_t idsize) +{ + /* free the ID */ + (void)idsize; + 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 hostname. + */ +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. +*/ +static CURLcode 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 do not 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 manpage 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 is not 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) ? "hostname" : + (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 *cn = NULL; + int cnlen = 0; + bool free_cn = FALSE; + + /* 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) { + cnlen = ASN1_STRING_length(tmp); + cn = (unsigned char *) ASN1_STRING_get0_data(tmp); + } + else { /* not a UTF8 name */ + cnlen = ASN1_STRING_to_UTF8(&cn, tmp); + free_cn = TRUE; + } + + if((cnlen <= 0) || !cn) + result = CURLE_OUT_OF_MEMORY; + else if((size_t)cnlen != strlen((char *)cn)) { + /* 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(!cn) { + failf(data, + "SSL: unable to obtain common name from peer certificate"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else if(!Curl_cert_hostcheck((const char *)cn, cnlen, + peer->hostname, hostlen)) { + failf(data, "SSL: certificate subject name '%s' does not match " + "target hostname '%s'", cn, peer->dispname); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, " common name: %s (matched)", cn); + } + if(free_cn) + OPENSSL_free(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 ossl_ctx *octx) +{ + 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; + X509 *cert; + OCSP_CERTID *id = NULL; + int cert_status, crl_reason; + ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; + int ret; + long len; + + (void)cf; + DEBUGASSERT(octx); + + len = (long)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 is a root cert, + no problem, but if it is 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, (ossl_valsize_t)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 does not 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 does not 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); + 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 do not 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 = (long)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; +#elif OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(LIBRESSL_VERSION_NUMBER) +typedef unsigned long 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 is 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; + CURLcode result = CURLE_OK; + size_t der_session_size; + unsigned char *der_session_buf; + unsigned char *der_session_ptr; + + if(!cf || !data) + goto out; + + config = Curl_ssl_cf_get_config(cf, data); + if(config->primary.cache_session) { + + der_session_size = i2d_SSL_SESSION(session, NULL); + if(der_session_size == 0) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + der_session_buf = der_session_ptr = malloc(der_session_size); + if(!der_session_buf) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + der_session_size = i2d_SSL_SESSION(session, &der_session_ptr); + if(der_session_size == 0) { + result = CURLE_OUT_OF_MEMORY; + free(der_session_buf); + goto out; + } + + Curl_ssl_sessionid_lock(data); + result = Curl_ssl_set_sessionid(cf, data, peer, NULL, der_session_buf, + der_session_size, ossl_session_free); + Curl_ssl_sessionid_unlock(data); + } + +out: + return result; +} + +/* 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 0; +} + +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, (ossl_valsize_t)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 did not 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; + pContext = CertEnumCertificatesInStore(hStore, pContext); + if(!pContext) + break; + +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + else { + char cert_name[256]; + if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, + NULL, cert_name, sizeof(cert_name))) + infof(data, "SSL: unknown cert name"); + else + 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, (long)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"); +#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 will not + 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://web.archive.org/web/20190422050538/ + rt.openssl.org/Ticket/Display.html?id=3621 + */ +#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) + +/* key to use at `multi->proto_hash` */ +#define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share" + +struct ossl_x509_share { + 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 */ +}; + +static void oss_x509_share_free(void *key, size_t key_len, void *p) +{ + struct ossl_x509_share *share = p; + DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY)-1)); + DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->store) { + X509_STORE_free(share->store); + } + free(share->CAfile); + free(share); +} + +static bool +cached_x509_store_expired(const struct Curl_easy *data, + const struct ossl_x509_share *mb) +{ + const struct ssl_general_config *cfg = &data->set.general_ssl; + if(cfg->ca_cache_timeout < 0) + return FALSE; + else { + 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; + + return elapsed_ms >= timeout_ms; + } +} + +static bool +cached_x509_store_different(struct Curl_cfilter *cf, + const struct ossl_x509_share *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; + struct ossl_x509_share *share; + X509_STORE *store = NULL; + + DEBUGASSERT(multi); + share = multi ? Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_OSSL_X509_KEY, + sizeof(MPROTO_OSSL_X509_KEY)-1) : NULL; + if(share && share->store && + !cached_x509_store_expired(data, share) && + !cached_x509_store_different(cf, share)) { + store = share->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 ossl_x509_share *share; + + DEBUGASSERT(multi); + if(!multi) + return; + share = Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_OSSL_X509_KEY, + sizeof(MPROTO_OSSL_X509_KEY)-1); + + if(!share) { + share = calloc(1, sizeof(*share)); + if(!share) + return; + if(!Curl_hash_add2(&multi->proto_hash, + (void *)MPROTO_OSSL_X509_KEY, + sizeof(MPROTO_OSSL_X509_KEY)-1, + share, oss_x509_share_free)) { + free(share); + return; + } + } + + 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(share->store) { + X509_STORE_free(share->store); + free(share->CAfile); + } + + share->time = Curl_now(); + share->store = store; + share->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; + SSL_SESSION *ssl_session = NULL; + const unsigned char *der_sessionid = NULL; + size_t der_sessionid_size = 0; + 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_min = 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]; + + /* 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 have been told to use an explicit SSL/TLS version */ + switch(ssl_version_min) { + 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(conn_config->version_max && + (conn_config->version_max != CURL_SSLVERSION_MAX_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: could not 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 manpage 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 is 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://web.archive.org/web/20240114184648/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 &= ~(ctx_option_t)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 &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; +#endif + + switch(ssl_version_min) { + 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 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER + /* We do retry writes sometimes from another buffer address */ + SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); +#endif + + if(alpn && alpn_len) { +#ifdef HAS_ALPN + 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 username"); + 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 is 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: could not 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"); +# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + 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) { +# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + /* have to do base64 decode here for BoringSSL */ + 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: cannot 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; + + if(peer->hostname) + dns = Curl_fetch_addr(data, peer->hostname, 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 !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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 (BoringSSL)"); + 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 %zu", elen); + } + } + else { + infof(data, "ECH: requested but no ECHConfig available"); + if(data->set.tls_ech & CURLECH_HARD) + return CURLE_SSL_CONNECT_ERROR; + } + Curl_resolv_unlink(data, &dns); + } + } +# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) + 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'", + peer->hostname ? peer->hostname : "NULL", outername); + result = SSL_ech_set_server_names(octx->ssl, + 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 /* OPENSSL_IS_BORINGSSL || OPENSSL_IS_AWSLC */ + if(trying_ech_now + && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) { + infof(data, "ECH: cannot force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#endif /* USE_ECH */ + +#endif + + octx->reused_session = FALSE; + if(ssl_config->primary.cache_session) { + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, peer, (void **)&der_sessionid, + &der_sessionid_size, NULL)) { + /* we got a session id, use it! */ + ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid, + (long)der_sessionid_size); + if(ssl_session) { + if(!SSL_set_session(octx->ssl, ssl_session)) { + Curl_ssl_sessionid_unlock(data); + SSL_SESSION_free(ssl_session); + failf(data, "SSL: SSL_set_session failed: %s", + ossl_strerror(ERR_get_error(), error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + SSL_SESSION_free(ssl_session); + /* Informational message */ + infof(data, "SSL reusing session ID"); + octx->reused_session = TRUE; + } + else { + Curl_ssl_sessionid_unlock(data); + return CURLE_SSL_CONNECT_ERROR; + } + } + 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; +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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; +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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); +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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 BoringSSL */ + 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); +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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); + DEBUGASSERT(octx); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + 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 key logging is enabled, wait for the handshake to complete and then + * proceed with logging secrets (for TLS 1.2 or older). + */ + if(Curl_tls_keylog_enabled() && !octx->keylog_done) + ossl_log_tls12_secret(octx->ssl, &octx->keylog_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); + CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail); + + if(SSL_ERROR_WANT_READ == detail) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want recv"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + if(SSL_ERROR_WANT_WRITE == detail) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } +#ifdef SSL_ERROR_WANT_ASYNC + if(SSL_ERROR_WANT_ASYNC == detail) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want async"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; + } +#endif +#ifdef SSL_ERROR_WANT_RETRY_VERIFY + if(SSL_ERROR_WANT_RETRY_VERIFY == detail) { + CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + connssl->connecting_state = ssl_connect_2; + return CURLE_OK; + } +#endif + else { + /* untreated error */ + sslerr_t errdetail; + char error_buffer[256]=""; + CURLcode result; + long lerr; + int lib; + int reason; + + /* the connection failed, we are 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; + failf(data, "SSL certificate problem: %s", + X509_verify_cert_error_string(lerr)); + } + else + failf(data, "%s", "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; + failf(data, "TLS cert problem: %s", + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); + } +#endif +#ifdef USE_ECH + else if((lib == ERR_LIB_SSL) && +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + (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; + failf(data, "ECH required: %s", + ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); + } +#endif + else { + result = CURLE_SSL_CONNECT_ERROR; + failf(data, "TLS connect error: %s", + 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 does not 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; + } + } + else { + int psigtype_nid = NID_undef; + const char *negotiated_group_name = NULL; + + /* we connected fine, we are 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 +# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) + 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 /* !OPENSSL_IS_BORINGSSL && !OPENSSL_IS_AWSLC */ +#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, connssl, 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 was not specified, do not 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://docs.openssl.org/master/man3/d2i_X509/ */ + 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 is 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 + +#define MAX_CERT_NAME_LENGTH 2048 + +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; + long lerr; + X509 *issuer; + BIO *fp = NULL; + char error_buffer[256]=""; + const char *ptr; + BIO *mem = BIO_new(BIO_s_mem()); + bool strict = (conn_config->verifypeer || conn_config->verifyhost); + struct dynbuf dname; + + DEBUGASSERT(octx); + + Curl_dyn_init(&dname, MAX_CERT_NAME_LENGTH); + + 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)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: could not get peer certificate"); + return CURLE_PEER_FAILED_VERIFICATION; + } + + infof(data, "%s certificate:", + Curl_ssl_cf_is_proxy(cf) ? "Proxy" : "Server"); + + result = x509_name_oneline(X509_get_subject_name(octx->server_cert), + &dname); + infof(data, " subject: %s", result ? "[NONE]" : Curl_dyn_ptr(&dname)); + +#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 = ossl_verifyhost(data, conn, peer, octx->server_cert); + if(result) { + X509_free(octx->server_cert); + octx->server_cert = NULL; + Curl_dyn_free(&dname); + return result; + } + } + + result = x509_name_oneline(X509_get_issuer_name(octx->server_cert), + &dname); + if(result) { + if(strict) + failf(data, "SSL: could not get X509-issuer name"); + result = CURLE_PEER_FAILED_VERIFICATION; + } + else { + infof(data, " issuer: %s", Curl_dyn_ptr(&dname)); + Curl_dyn_free(&dname); + + /* 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) { + /* do not do this after Session ID reuse */ + result = verifystatus(cf, data, octx); + 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, 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 do not 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 are 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; + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + /* 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 are 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) { + + /* 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 is available. */ + if(!nonblocking && connssl->io_need) { + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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))) + 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(); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + 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: + connssl->io_need = CURL_SSL_IO_NEED_RECV; + *curlcode = CURLE_AGAIN; + rc = -1; + goto out; + case SSL_ERROR_WANT_WRITE: + *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(); + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + 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: + *curlcode = CURLE_AGAIN; + nread = -1; + goto out; + case SSL_ERROR_WANT_WRITE: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + *curlcode = CURLE_AGAIN; + nread = -1; + goto out; + default: + /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return + value/errno" */ + /* https://docs.openssl.org/master/man3/ERR_get_error/ */ + 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 do not 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 CURLcode ossl_get_channel_binding(struct Curl_easy *data, int sockindex, + struct dynbuf *binding) +{ + /* required for X509_get_signature_nid support */ +#if OPENSSL_VERSION_NUMBER > 0x10100000L + X509 *cert; + int algo_nid; + const EVP_MD *algo_type; + const char *algo_name; + unsigned int length; + unsigned char buf[EVP_MAX_MD_SIZE]; + + const char prefix[] = "tls-server-end-point:"; + struct connectdata *conn = data->conn; + struct Curl_cfilter *cf = conn->cfilter[sockindex]; + struct ossl_ctx *octx = NULL; + + do { + const struct Curl_cftype *cft = cf->cft; + struct ssl_connect_data *connssl = cf->ctx; + + if(cft->name && !strcmp(cft->name, "SSL")) { + octx = (struct ossl_ctx *)connssl->backend; + break; + } + + if(cf->next) + cf = cf->next; + + } while(cf->next); + + if(!octx) { + failf(data, "Failed to find the SSL filter"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + cert = SSL_get1_peer_certificate(octx->ssl); + if(!cert) { + /* No server certificate, don't do channel binding */ + return CURLE_OK; + } + + if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &algo_nid, NULL)) { + failf(data, + "Unable to find digest NID for certificate signature algorithm"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + + /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */ + if(algo_nid == NID_md5 || algo_nid == NID_sha1) { + algo_type = EVP_sha256(); + } + else { + algo_type = EVP_get_digestbynid(algo_nid); + if(!algo_type) { + algo_name = OBJ_nid2sn(algo_nid); + failf(data, "Could not find digest algorithm %s (NID %d)", + algo_name ? algo_name : "(null)", algo_nid); + return CURLE_SSL_INVALIDCERTSTATUS; + } + } + + if(!X509_digest(cert, algo_type, buf, &length)) { + failf(data, "X509_digest() failed"); + return CURLE_SSL_INVALIDCERTSTATUS; + } + + /* Append "tls-server-end-point:" */ + if(Curl_dyn_addn(binding, prefix, sizeof(prefix) - 1) != CURLE_OK) + return CURLE_OUT_OF_MEMORY; + /* Append digest */ + if(Curl_dyn_addn(binding, buf, length)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +#else + /* No X509_get_signature_nid support */ + (void)data; /* unused */ + (void)sockindex; /* unused */ + (void)binding; /* unused */ + return CURLE_OK; +#endif +} + +static size_t ossl_version(char *buffer, size_t size) +{ +#ifdef LIBRESSL_VERSION_NUMBER +#ifdef HAVE_OPENSSL_VERSION + char *p; + size_t 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; /* could not seed for some reason */ + } + else { + if(!rand_enough()) + return CURLE_FAILED_INIT; + } + /* RAND_bytes() returns 1 on success, 0 otherwise. */ + rc = RAND_bytes(entropy, (ossl_valsize_t)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; +} + +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_CA_CACHE | + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST, + + 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_recv, /* recv decrypted data */ + ossl_send, /* send data to encrypt */ + ossl_get_channel_binding /* get_channel_binding */ +}; + +#endif /* USE_OPENSSL */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.h b/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.h new file mode 100644 index 0000000000000000000000000000000000000000..7aba947d18263dd97e793f61865694ed6c893062 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/openssl.h @@ -0,0 +1,111 @@ +#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. + This is a bool and not a bitfield because it is passed by address. */ + bool 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 + +extern const struct Curl_ssl Curl_ssl_openssl; + +/** + * 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/local-test-curl-delta-01/afc-curl/lib/vtls/rustls.c b/local-test-curl-delta-01/afc-curl/lib/vtls/rustls.c new file mode 100644 index 0000000000000000000000000000000000000000..5d143486d6547a1f4714de75622bbca8c40d21e3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/rustls.c @@ -0,0 +1,1105 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "rustls.h" +#include "select.h" +#include "strerror.h" +#include "multiif.h" +#include "connect.h" /* for the connect timeout */ +#include "cipher_suite.h" +#include "rand.h" + +struct rustls_ssl_backend_data +{ + const struct rustls_client_config *config; + struct rustls_connection *conn; + size_t plain_out_buffered; + BIT(data_in_pending); + BIT(sent_shutdown); +}; + +/* 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 = (uintptr_t)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, FALSE, + &result); + if(nwritten < 0) { + nwritten = 0; + if(CURLE_AGAIN == result) + ret = EAGAIN; + else + ret = EINVAL; + } + *out_n = (uintptr_t)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 is 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 will not 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, do not 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 is okay to call this function with plainbuf == NULL and plainlen == 0. + * In that case, it will not 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 int +read_file_into(const char *filename, + struct dynbuf *out) +{ + FILE *f = fopen(filename, FOPEN_READTEXT); + if(!f) { + return 0; + } + + while(!feof(f)) { + uint8_t buf[256]; + size_t rr = fread(buf, 1, sizeof(buf), f); + if(rr == 0 || + CURLE_OK != Curl_dyn_addn(out, buf, rr)) { + fclose(f); + return 0; + } + } + + return fclose(f) == 0; +} + +static void +cr_get_selected_ciphers(struct Curl_easy *data, + const char *ciphers12, + const char *ciphers13, + const struct rustls_supported_ciphersuite **selected, + size_t *selected_size) +{ + size_t supported_len = *selected_size; + size_t default_len = rustls_default_crypto_provider_ciphersuites_len(); + const struct rustls_supported_ciphersuite *entry; + const char *ciphers = ciphers12; + size_t count = 0, default13_count = 0, i, j; + const char *ptr, *end; + + DEBUGASSERT(default_len <= supported_len); + + if(!ciphers13) { + /* Add default TLSv1.3 ciphers to selection */ + for(j = 0; j < default_len; j++) { + entry = rustls_default_crypto_provider_ciphersuites_get(j); + if(rustls_supported_ciphersuite_protocol_version(entry) != + RUSTLS_TLS_VERSION_TLSV1_3) + continue; + + selected[count++] = entry; + } + + default13_count = count; + + if(!ciphers) + ciphers = ""; + } + else + ciphers = ciphers13; + +add_ciphers: + for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) { + uint16_t id = Curl_cipher_suite_walk_str(&ptr, &end); + + /* Check if cipher is supported */ + if(id) { + for(i = 0; i < supported_len; i++) { + entry = rustls_default_crypto_provider_ciphersuites_get(i); + if(rustls_supported_ciphersuite_get_suite(entry) == id) + break; + } + if(i == supported_len) + id = 0; + } + if(!id) { + if(ptr[0] != '\0') + infof(data, "rustls: unknown cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != entry; i++); + if(i < count) { + if(i >= default13_count) + infof(data, "rustls: duplicate cipher in list: \"%.*s\"", + (int) (end - ptr), ptr); + continue; + } + + selected[count++] = entry; + } + + if(ciphers == ciphers13 && ciphers12) { + ciphers = ciphers12; + goto add_ciphers; + } + + if(!ciphers12) { + /* Add default TLSv1.2 ciphers to selection */ + for(j = 0; j < default_len; j++) { + entry = rustls_default_crypto_provider_ciphersuites_get(j); + if(rustls_supported_ciphersuite_protocol_version(entry) == + RUSTLS_TLS_VERSION_TLSV1_3) + continue; + + /* No duplicates allowed (so selected cannot overflow) */ + for(i = 0; i < count && selected[i] != entry; i++); + if(i < count) + continue; + + selected[count++] = entry; + } + } + + *selected_size = count; +} + +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_crypto_provider_builder *custom_provider_builder = NULL; + const struct rustls_crypto_provider *custom_provider = NULL; + 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; + char errorbuf[256]; + size_t errorlen; + rustls_result result; + + DEBUGASSERT(backend); + rconn = backend->conn; + + { + uint16_t tls_versions[2] = { + RUSTLS_TLS_VERSION_TLSV1_2, + RUSTLS_TLS_VERSION_TLSV1_3, + }; + size_t tls_versions_len = 2; + const struct rustls_supported_ciphersuite **cipher_suites; + size_t cipher_suites_len = + rustls_default_crypto_provider_ciphersuites_len(); + + 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: + break; + case CURL_SSLVERSION_TLSv1_3: + tls_versions[0] = RUSTLS_TLS_VERSION_TLSV1_3; + tls_versions_len = 1; + break; + default: + failf(data, "rustls: unsupported minimum TLS version value"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: + break; + case CURL_SSLVERSION_MAX_TLSv1_2: + if(tls_versions[0] == RUSTLS_TLS_VERSION_TLSV1_2) { + tls_versions_len = 1; + break; + } + FALLTHROUGH(); + case CURL_SSLVERSION_MAX_TLSv1_1: + case CURL_SSLVERSION_MAX_TLSv1_0: + default: + failf(data, "rustls: unsupported maximum TLS version value"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + cipher_suites = malloc(sizeof(cipher_suites) * (cipher_suites_len)); + if(!cipher_suites) + return CURLE_OUT_OF_MEMORY; + + cr_get_selected_ciphers(data, + conn_config->cipher_list, + conn_config->cipher_list13, + cipher_suites, &cipher_suites_len); + if(cipher_suites_len == 0) { + failf(data, "rustls: no supported cipher in list"); + free(cipher_suites); + return CURLE_SSL_CIPHER; + } + + result = rustls_crypto_provider_builder_new_from_default( + &custom_provider_builder); + if(result != RUSTLS_RESULT_OK) { + failf(data, + "rustls: failed to create crypto provider builder from default"); + return CURLE_SSL_CIPHER; + } + + result = + rustls_crypto_provider_builder_set_cipher_suites( + custom_provider_builder, + cipher_suites, + cipher_suites_len); + if(result != RUSTLS_RESULT_OK) { + failf(data, + "rustls: failed to set ciphersuites for crypto provider builder"); + rustls_crypto_provider_builder_free(custom_provider_builder); + return CURLE_SSL_CIPHER; + } + + result = rustls_crypto_provider_builder_build( + custom_provider_builder, &custom_provider); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to build custom crypto provider"); + rustls_crypto_provider_builder_free(custom_provider_builder); + return CURLE_SSL_CIPHER; + } + + result = rustls_client_config_builder_new_custom(custom_provider, + tls_versions, + tls_versions_len, + &config_builder); + free(cipher_suites); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to create client config"); + return CURLE_SSL_CIPHER; + } + } + + rustls_crypto_provider_builder_free(custom_provider_builder); + rustls_crypto_provider_free(custom_provider); + + 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); + } + 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 is not 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_builder_free(config_builder); + return CURLE_SSL_CACERT_BADFILE; + } + } + else if(ssl_cafile) { + /* Enable strict parsing only if verification is not 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_builder_free(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 build trusted root certificate store"); + rustls_client_config_builder_free(config_builder); + return CURLE_SSL_CACERT_BADFILE; + } + + verifier_builder = rustls_web_pki_server_cert_verifier_builder_new(roots); + rustls_root_cert_store_free(roots); + + if(conn_config->CRLfile) { + struct dynbuf crl_contents; + Curl_dyn_init(&crl_contents, SIZE_MAX); + if(!read_file_into(conn_config->CRLfile, &crl_contents)) { + failf(data, "rustls: failed to read revocation list file"); + Curl_dyn_free(&crl_contents); + rustls_web_pki_server_cert_verifier_builder_free(verifier_builder); + return CURLE_SSL_CRL_BADFILE; + } + + result = rustls_web_pki_server_cert_verifier_builder_add_crl( + verifier_builder, + Curl_dyn_uptr(&crl_contents), + Curl_dyn_len(&crl_contents)); + Curl_dyn_free(&crl_contents); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to parse revocation list"); + rustls_web_pki_server_cert_verifier_builder_free(verifier_builder); + return CURLE_SSL_CRL_BADFILE; + } + } + + 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 build certificate verifier"); + rustls_server_cert_verifier_free(server_cert_verifier); + rustls_client_config_builder_free(config_builder); + return CURLE_SSL_CACERT_BADFILE; + } + + rustls_client_config_builder_set_server_verifier(config_builder, + server_cert_verifier); + rustls_server_cert_verifier_free(server_cert_verifier); + } + + result = rustls_client_config_builder_build( + config_builder, + &backend->config); + if(result != RUSTLS_RESULT_OK) { + failf(data, "rustls: failed to build client config"); + rustls_client_config_free(backend->config); + return CURLE_SSL_CONNECT_ERROR; + } + + 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) +{ + struct ssl_connect_data *const connssl = cf->ctx; + const uint8_t *protocol = NULL; + size_t len = 0; + + rustls_connection_get_alpn_protocol(rconn, &protocol, &len); + Curl_alpn_set_negotiated(cf, data, connssl, 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. + */ + connssl->io_need = CURL_SSL_IO_NEED_NONE; + if(!rustls_connection_is_handshaking(rconn)) { + /* 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->io_need = CURL_SSL_IO_NEED_SEND; + return CURLE_OK; + } + else if(tmperr != CURLE_OK) { + return tmperr; + } + /* REALLY Done with the handshake. */ + { + uint16_t proto = rustls_connection_get_protocol_version(rconn); + uint16_t cipher = rustls_connection_get_negotiated_ciphersuite(rconn); + char buf[64] = ""; + const char *ver = "TLS version unknown"; + if(proto == RUSTLS_TLS_VERSION_TLSV1_3) + ver = "TLSv1.3"; + if(proto == RUSTLS_TLS_VERSION_TLSV1_2) + ver = "TLSv1.2"; + Curl_cipher_suite_get_str(cipher, buf, sizeof(buf), TRUE); + infof(data, "rustls: handshake complete, %s, cipher: %s", + ver, buf); + } + connssl->state = ssl_connection_complete; + *done = TRUE; + return CURLE_OK; + } + + connssl->connecting_state = ssl_connect_2; + 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; + + /* 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 %" FMT_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"); + if(wants_write) + connssl->io_need |= CURL_SSL_IO_NEED_SEND; + if(wants_read) + connssl->io_need |= CURL_SSL_IO_NEED_RECV; + 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 cannot 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 CURLcode +cr_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct rustls_ssl_backend_data *backend = + (struct rustls_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + ssize_t nwritten, nread; + char buf[1024]; + size_t i; + + DEBUGASSERT(backend); + if(!backend->conn || cf->shutdown) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(!backend->sent_shutdown) { + /* do this only once */ + backend->sent_shutdown = TRUE; + if(send_shutdown) { + rustls_connection_send_close_notify(backend->conn); + } + } + + nwritten = cr_send(cf, data, NULL, 0, &result); + if(nwritten < 0) { + if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_OK; + goto out; + } + DEBUGASSERT(result); + CURL_TRC_CF(data, cf, "shutdown send failed: %d", result); + goto out; + } + + for(i = 0; i < 10; ++i) { + nread = cr_recv(cf, data, buf, (int)sizeof(buf), &result); + if(nread <= 0) + break; + } + + if(nread > 0) { + /* still data coming in? */ + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + *done = TRUE; + } + else if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_OK; + } + else { + DEBUGASSERT(result); + CURL_TRC_CF(data, cf, "shutdown, error: %d", result); + } + +out: + cf->shutdown = (result || *done); + return result; +} + +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; + + (void)data; + DEBUGASSERT(backend); + if(backend->conn) { + 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); +} + +static CURLcode +cr_random(struct Curl_easy *data, unsigned char *entropy, size_t length) +{ + rustls_result rresult = 0; + (void)data; + rresult = + rustls_default_crypto_provider_random(entropy, length); + return map_error(rresult); +} + +const struct Curl_ssl Curl_ssl_rustls = { + { CURLSSLBACKEND_RUSTLS, "rustls" }, + SSLSUPP_CAINFO_BLOB | /* supports */ + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST | + SSLSUPP_TLS13_CIPHERSUITES, + sizeof(struct rustls_ssl_backend_data), + + Curl_none_init, /* init */ + Curl_none_cleanup, /* cleanup */ + cr_version, /* version */ + Curl_none_check_cxn, /* check_cxn */ + cr_shutdown, /* shutdown */ + cr_data_pending, /* data_pending */ + cr_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 */ + cr_recv, /* recv decrypted data */ + cr_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_RUSTLS */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/rustls.h b/local-test-curl-delta-01/afc-curl/lib/vtls/rustls.h new file mode 100644 index 0000000000000000000000000000000000000000..bfbe23de3e6b2ad60ccc8283c25a7785b12aae6d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/schannel.c b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel.c new file mode 100644 index 0000000000000000000000000000000000000000..f4bbe4e8325f8a1ccc1e9db7312b4502507bf2e1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel.c @@ -0,0 +1,2824 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "cannot 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" + +/* Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF() + * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These + * messages are extra verbose and intended for curl developers debugging + * Schannel recv decryption. + */ +#ifdef CURL_SCHANNEL_DEV_DEBUG +#define SCH_DEV(x) x +#else +#define SCH_DEV(x) do { } while(0) +#endif + +/* 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 = (long)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_ID)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 = (DWORD)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 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 &= ~(DWORD)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)) { + + SCH_CREDENTIALS credentials = { 0 }; + TLS_PARAMETERS tls_parameters = { 0 }; + CRYPTO_SETTINGS crypto_settings[1] = { { 0 } }; + + tls_parameters.pDisabledCrypto = crypto_settings; + + /* The number of blocked suites */ + tls_parameters.cDisabledCrypto = (DWORD)0; + 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 = + Curl_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. + 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 " + "negotiates a less-secure TLS version than TLS 1.3 because the " + "user set an algorithm cipher list."); + } + 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 = + Curl_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 does not 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 does not seem to work right; we will + * do it following a more manual process. */ + backend->use_manual_cred_validation = TRUE; +#else +#error "compiler too old to support Windows CE requisite manual cert verify" +#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.cache_session) { + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, + (void **)&old_cred, NULL, 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 do not pass inbuf unless we are 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 = Curl_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, FALSE, + &result); + Curl_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->io_need & CURL_SSL_IO_NEED_SEND) ? FALSE : TRUE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + + 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) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + 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; + SCH_DEV(infof(data, "schannel: encrypted data got %zd", nread)); + } + + SCH_DEV(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 = Curl_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->io_need = CURL_SSL_IO_NEED_RECV; + 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->io_need = CURL_SSL_IO_NEED_SEND; + 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, + FALSE, &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) { + Curl_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) { + SCH_DEV(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 are 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->io_need = CURL_SSL_IO_NEED_RECV; + 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 will not 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) { + Curl_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 = + Curl_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, connssl, 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, connssl, NULL, 0); + } + } +#endif + + /* save the current session data for possible reuse */ + if(ssl_config->primary.cache_session) { + Curl_ssl_sessionid_lock(data); + /* Up ref count since call takes ownership */ + backend->cred->refcount++; + result = Curl_ssl_set_sessionid(cf, data, &connssl->peer, NULL, + backend->cred, + sizeof(struct Curl_schannel_cred), + schannel_session_free); + Curl_ssl_sessionid_unlock(data); + if(result) + return result; + } + + if(data->set.ssl.certinfo) { + int certs_count = 0; + sspi_status = + Curl_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 are 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) { + + /* check out how much more time we are 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 is available. */ + if(connssl->io_need) { + + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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))) + 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 = Curl_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 = Curl_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 is 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 + cannot 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, + FALSE, &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); + + /**************************************************************************** + * Do not return or set backend->recv_unrecoverable_err unless in the + * cleanup. The pattern for return error is set *err, optional infof, goto + * cleanup. + * + * Some verbose debug messages are wrapped by SCH_DEV() instead of DEBUGF() + * and only shown if CURL_SCHANNEL_DEV_DEBUG was defined at build time. These + * messages are extra verbose and intended for curl developers debugging + * Schannel recv decryption. + * + * 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. + */ + + SCH_DEV(infof(data, "schannel: client wants to read %zu bytes", len)); + *err = CURLE_OK; + + if(len && len <= backend->decdata_offset) { + SCH_DEV(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 is debatable what to return when !len. Regardless we cannot 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; + SCH_DEV(infof(data, "schannel: encdata_buffer resized %zu", + backend->encdata_length)); + } + + SCH_DEV(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) + SCH_DEV(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; + SCH_DEV(infof(data, "schannel: encrypted data got %zd", nread)); + } + } + + SCH_DEV(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 = Curl_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) { + SCH_DEV(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; + } + + SCH_DEV(infof(data, "schannel: decrypted data added: %zu", size)); + SCH_DEV(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) { + SCH_DEV(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; + } + + SCH_DEV(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: cannot 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; + connssl->io_need = CURL_SSL_IO_NEED_SEND; + 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; + /* We received the close notify just fine, any error we got + * from the lower filters afterwards (e.g. the socket), is not + * an error on the TLS data stream. That one ended here. */ + if(*err == CURLE_RECV_ERROR) + *err = CURLE_OK; + 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; + SCH_DEV(infof(data, "schannel: failed to decrypt data, need more data")); + goto cleanup; + } + else { +#ifndef CURL_DISABLE_VERBOSE_STRINGS + char buffer[STRERROR_LEN]; + failf(data, "schannel: failed to read data from server: %s", + Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); +#endif + *err = CURLE_RECV_ERROR; + goto cleanup; + } + } + + SCH_DEV(infof(data, "schannel: encrypted data buffer: offset %zu length %zu", + backend->encdata_offset, backend->encdata_length)); + + SCH_DEV(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 */ + SCH_DEV(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 do not want to be vulnerable + to a truncation attack however there is some browser precedent for + ignoring the close_notify for compatibility reasons. + + Additionally, Windows 2000 (v5.0) is a special case since it seems it + does not return close_notify. In that case if the connection was closed we + assume it was graceful (close_notify) since there does not 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; + failf(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; + SCH_DEV(infof(data, "schannel: decrypted data returned %zu", size)); + SCH_DEV(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 is 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 CURLcode schannel_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + /* 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; + CURLcode result = CURLE_OK; + + if(cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + + DEBUGASSERT(data); + DEBUGASSERT(backend); + + /* Not supported in schannel */ + (void)send_shutdown; + + *done = FALSE; + if(backend->ctxt) { + infof(data, "schannel: shutting down SSL/TLS connection with %s port %d", + connssl->peer.hostname, connssl->peer.port); + } + + if(!backend->ctxt || cf->shutdown) { + *done = TRUE; + goto out; + } + + if(backend->cred && backend->ctxt && !backend->sent_shutdown) { + SecBufferDesc BuffDesc; + SecBuffer Buffer; + SECURITY_STATUS sspi_status; + SecBuffer outbuf; + SecBufferDesc outbuf_desc; + DWORD dwshut = SCHANNEL_SHUTDOWN; + + InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut)); + InitSecBufferDesc(&BuffDesc, &Buffer, 1); + + sspi_status = Curl_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))); + result = CURLE_SEND_ERROR; + goto out; + } + + /* setup output buffer */ + InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); + InitSecBufferDesc(&outbuf_desc, &outbuf, 1); + + sspi_status = Curl_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, + FALSE, &result); + Curl_pSecFn->FreeContextBuffer(outbuf.pvBuffer); + if(!result) { + if(written < (ssize_t)outbuf.cbBuffer) { + /* TODO: handle partial sends */ + failf(data, "schannel: failed to send close msg: %s" + " (bytes written: %zd)", curl_easy_strerror(result), written); + result = CURLE_SEND_ERROR; + goto out; + } + backend->sent_shutdown = TRUE; + *done = TRUE; + } + else if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_OK; + goto out; + } + else { + if(!backend->recv_connection_closed) { + failf(data, "schannel: error sending close msg: %d", result); + result = CURLE_SEND_ERROR; + goto out; + } + /* Looks like server already closed the connection. + * An error to send our close notify is not a failure. */ + *done = TRUE; + result = CURLE_OK; + } + } + } + + /* If the connection seems open and we have not seen the close notify + * from the server yet, try to receive it. */ + if(backend->cred && backend->ctxt && + !backend->recv_sspi_close_notify && !backend->recv_connection_closed) { + char buffer[1024]; + ssize_t nread; + + nread = schannel_recv(cf, data, buffer, sizeof(buffer), &result); + if(nread > 0) { + /* still data coming in? */ + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + backend->recv_connection_closed = TRUE; + *done = TRUE; + } + else if(nread < 0 && result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + } + else { + CURL_TRC_CF(data, cf, "SSL shutdown, error %d", result); + result = CURLE_RECV_ERROR; + } + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void schannel_close(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; + + DEBUGASSERT(data); + DEBUGASSERT(backend); + + /* free SSPI Schannel API security context handle */ + if(backend->ctxt) { + DEBUGF(infof(data, "schannel: clear security context handle")); + Curl_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; + } +} + +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) +{ + return msnprintf(buffer, size, "Schannel"); +} + +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 was not specified, do not 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 = + Curl_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) +{ +#ifdef CURL_WINDOWS_UWP + (void)input; + (void)inputlen; + (void)provType; + (void)algId; + memset(checksum, 0, checksumlen); +#else + 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); +#endif +} + +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_cert_share *share; + 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) { + return NULL; + } + + share = Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_SCHANNEL_CERT_SHARE_KEY, + sizeof(MPROTO_SCHANNEL_CERT_SHARE_KEY)-1); + if(!share || !share->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, share->time); + if(elapsed_ms >= timeout_ms) { + return NULL; + } + } + + if(ca_info_blob) { + if(share->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(share->CAinfo_blob_digest, info_blob_digest, + CURL_SHA256_DIGEST_LENGTH)) { + return NULL; + } + } + else { + if(!conn_config->CAfile || !share->CAfile || + strcmp(share->CAfile, conn_config->CAfile)) { + return NULL; + } + } + + return share->cert_store; +} + +static void schannel_cert_share_free(void *key, size_t key_len, void *p) +{ + struct schannel_cert_share *share = p; + DEBUGASSERT(key_len == (sizeof(MPROTO_SCHANNEL_CERT_SHARE_KEY)-1)); + DEBUGASSERT(!memcmp(MPROTO_SCHANNEL_CERT_SHARE_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->cert_store) { + CertCloseStore(share->cert_store, 0); + } + free(share->CAfile); + free(share); +} + +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_cert_share *share; + size_t CAinfo_blob_size = 0; + char *CAfile = NULL; + + DEBUGASSERT(multi); + + if(!multi) { + return FALSE; + } + + share = Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_SCHANNEL_CERT_SHARE_KEY, + sizeof(MPROTO_SCHANNEL_CERT_SHARE_KEY)-1); + if(!share) { + share = calloc(1, sizeof(*share)); + if(!share) { + return FALSE; + } + if(!Curl_hash_add2(&multi->proto_hash, + (void *)MPROTO_SCHANNEL_CERT_SHARE_KEY, + sizeof(MPROTO_SCHANNEL_CERT_SHARE_KEY)-1, + share, schannel_cert_share_free)) { + free(share); + return FALSE; + } + } + + if(ca_info_blob) { + schannel_sha256sum((const unsigned char *)ca_info_blob->data, + ca_info_blob->len, + share->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(share->cert_store) { + CertCloseStore(share->cert_store, 0); + } + free(share->CAfile); + + share->time = Curl_now(); + share->cert_store = cert_store; + share->CAinfo_blob_size = CAinfo_blob_size; + share->CAfile = CAfile; + return TRUE; +} + +const struct Curl_ssl Curl_ssl_schannel = { + { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */ + + SSLSUPP_CERTINFO | +#ifdef HAS_MANUAL_VERIFY_API + SSLSUPP_CAINFO_BLOB | +#endif +#ifndef CURL_WINDOWS_UWP + SSLSUPP_PINNEDPUBKEY | +#endif + SSLSUPP_CA_CACHE | + SSLSUPP_HTTPS_PROXY | + SSLSUPP_CIPHER_LIST, + + 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_recv, /* recv decrypted data */ + schannel_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif /* USE_SCHANNEL */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/schannel.h b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel.h new file mode 100644 index 0000000000000000000000000000000000000000..b26334bcf877a0318fb5f3291b84ee60c678d28d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_int.h b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_int.h new file mode 100644 index 0000000000000000000000000000000000000000..81476bc6d817cb57b146e53c2613b8e7e3cfa3f6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_int.h @@ -0,0 +1,198 @@ +#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 + +#include "vtls.h" + +#if (defined(__MINGW32__) || defined(CERT_CHAIN_REVOCATION_CHECK_CHAIN)) \ + && !defined(CURL_WINDOWS_UWP) +#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 + cannot 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 + BIT(sent_shutdown); +}; + +/* key to use at `multi->proto_hash` */ +#define MPROTO_SCHANNEL_CERT_SHARE_KEY "tls:schannel:cert:share" + +struct schannel_cert_share { + unsigned char CAinfo_blob_digest[CURL_SHA256_DIGEST_LENGTH]; + 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 */ +}; + +/* +* size of the structure: 20 bytes. +*/ +struct num_ip_data { + DWORD size; /* 04 bytes */ + union { + struct in_addr ia; /* 04 bytes */ + struct in6_addr ia6; /* 16 bytes */ + } bData; +}; + +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/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_verify.c b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_verify.c new file mode 100644 index 0000000000000000000000000000000000000000..fede3908feba5920c7b4fc43454718c7ca2e0488 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/schannel_verify.c @@ -0,0 +1,869 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "cannot compile SCHANNEL support without SSPI." +#endif + +#include "schannel.h" +#include "schannel_int.h" + +#include "inet_pton.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 do not need to be terminated by a '\0'. + * Similar of macOS/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 < ca_buffer_limit)) { + const char *begin_cert_ptr = c_memmem(current_ca_file_ptr, + ca_buffer_limit-current_ca_file_ptr, + BEGIN_CERT, + begin_cert_len); + if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[begin_cert_len])) { + more_certs = 0; + } + else { + const char *end_cert_ptr = c_memmem(begin_cert_ptr, + ca_buffer_limit-begin_cert_ptr, + END_CERT, + end_cert_len); + if(!end_cert_ptr) { + failf(data, + "schannel: CA file '%s' is not correctly formatted", + ca_file_text); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + CERT_BLOB cert_blob; + CERT_CONTEXT *cert_context = NULL; + BOOL add_cert_result = FALSE; + DWORD actual_content_type = 0; + DWORD cert_size = (DWORD) + ((end_cert_ptr + end_cert_len) - begin_cert_ptr); + + cert_blob.pbData = (BYTE *)begin_cert_ptr; + cert_blob.cbData = cert_size; + if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB, + &cert_blob, + CERT_QUERY_CONTENT_FLAG_CERT, + CERT_QUERY_FORMAT_FLAG_ALL, + 0, + NULL, + &actual_content_type, + NULL, + NULL, + NULL, + (const void **)&cert_context)) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to extract certificate from CA file " + "'%s': %s", + ca_file_text, + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + current_ca_file_ptr = begin_cert_ptr + cert_size; + + /* Sanity check that the cert_context object is the right type */ + if(CERT_QUERY_CONTENT_CERT != actual_content_type) { + failf(data, + "schannel: unexpected content type '%lu' when extracting " + "certificate from CA file '%s'", + actual_content_type, ca_file_text); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + add_cert_result = + CertAddCertificateContextToStore(trust_store, + cert_context, + CERT_STORE_ADD_ALWAYS, + NULL); + CertFreeCertificateContext(cert_context); + if(!add_cert_result) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to add certificate from CA file '%s' " + "to certificate store: %s", + ca_file_text, + Curl_winapi_strerror(GetLastError(), buffer, + sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + more_certs = 0; + } + else { + num_certs++; + } + } + } + } + } + } + + if(result == CURLE_OK) { + if(!num_certs) { + infof(data, + "schannel: did not add any certificates from CA file '%s'", + ca_file_text); + } + else { + infof(data, + "schannel: added %d certificate(s) from CA file '%s'", + num_certs, ca_file_text); + } + } + return result; +} + +static CURLcode add_certs_file_to_store(HCERTSTORE trust_store, + const char *ca_file, + struct Curl_easy *data) +{ + CURLcode result; + HANDLE ca_file_handle = INVALID_HANDLE_VALUE; + LARGE_INTEGER file_size; + char *ca_file_buffer = NULL; + TCHAR *ca_file_tstr = NULL; + size_t ca_file_bufsize = 0; + DWORD total_bytes_read = 0; + + ca_file_tstr = curlx_convert_UTF8_to_tchar((char *)ca_file); + if(!ca_file_tstr) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: invalid path name for CA file '%s': %s", + ca_file, + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + /* + * Read the CA file completely into memory before parsing it. This + * optimizes for the common case where the CA file will be relatively + * small ( < 1 MiB ). + */ + ca_file_handle = CreateFile(ca_file_tstr, + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + if(ca_file_handle == INVALID_HANDLE_VALUE) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to open CA file '%s': %s", + ca_file, + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(!GetFileSizeEx(ca_file_handle, &file_size)) { + char buffer[STRERROR_LEN]; + failf(data, + "schannel: failed to determine size of CA file '%s': %s", + ca_file, + Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); + result = CURLE_SSL_CACERT_BADFILE; + goto cleanup; + } + + if(file_size.QuadPart > 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 hostnames. 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, + PCERT_ALT_NAME_INFO alt_name_info, + BOOL Win8_compat) +{ + DWORD actual_length = 0; +#if defined(CURL_WINDOWS_UWP) + (void)data; + (void)cert_context; + (void)host_names; + (void)length; + (void)alt_name_info; + (void)Win8_compat; +#else + BOOL compute_content = 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(Win8_compat) { + /* 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; + } +#else + (void)cert_context; + (void)Win8_compat; +#endif + + compute_content = host_names != NULL && length != 0; + + /* Initialize default return values. */ + actual_length = 1; + if(compute_content) { + *host_names = '\0'; + } + + 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 hostnames."); + break; + } + dns_w = entry->pwszDNSName; + /* pwszDNSName is in ia5 string format and hence does not contain any + * non-ASCII characters. */ + while(*dns_w != '\0') { + *current_pos++ = (TCHAR)(*dns_w++); + } + *current_pos++ = '\0'; + actual_length += (DWORD)current_length; + } + if(compute_content) { + /* Last string has double null-terminator. */ + *current_pos = '\0'; + } +#endif + return actual_length; +} + +/* +* Returns TRUE if the hostname is a numeric IPv4/IPv6 Address, +* and populates the buffer with IPv4/IPv6 info. +*/ + +static bool get_num_host_info(struct num_ip_data *ip_blob, + LPCSTR hostname) +{ + struct in_addr ia; + struct in6_addr ia6; + bool result = FALSE; + + int res = Curl_inet_pton(AF_INET, hostname, &ia); + if(res) { + ip_blob->size = sizeof(struct in_addr); + memcpy(&ip_blob->bData.ia, &ia, sizeof(struct in_addr)); + result = TRUE; + } + else { + res = Curl_inet_pton(AF_INET6, hostname, &ia6); + if(res) { + ip_blob->size = sizeof(struct in6_addr); + memcpy(&ip_blob->bData.ia6, &ia6, sizeof(struct in6_addr)); + result = TRUE; + } + } + return result; +} + +static bool get_alt_name_info(struct Curl_easy *data, + PCCERT_CONTEXT ctx, + PCERT_ALT_NAME_INFO *alt_name_info, + LPDWORD alt_name_info_size) +{ + bool result = FALSE; +#if defined(CURL_WINDOWS_UWP) + (void)data; + (void)ctx; + (void)alt_name_info; + (void)alt_name_info_size; +#else + PCERT_INFO cert_info = NULL; + PCERT_EXTENSION extension = NULL; + CRYPT_DECODE_PARA decode_para = { sizeof(CRYPT_DECODE_PARA), NULL, NULL }; + + if(!ctx) { + failf(data, "schannel: Null certificate context."); + return result; + } + + cert_info = ctx->pCertInfo; + if(!cert_info) { + failf(data, "schannel: Null certificate info."); + return result; + } + + extension = CertFindExtension(szOID_SUBJECT_ALT_NAME2, + cert_info->cExtension, + cert_info->rgExtension); + if(!extension) { + failf(data, "schannel: CertFindExtension() returned no extension."); + return result; + } + + if(!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)) { + failf(data, + "schannel: CryptDecodeObjectEx() returned no alternate name " + "information."); + return result; + } + result = TRUE; +#endif + return result; +} + +/* 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; + PCERT_ALT_NAME_INFO alt_name_info = NULL; + DWORD alt_name_info_size = 0; + struct num_ip_data ip_blob = { 0 }; + bool Win8_compat; + struct num_ip_data *p = &ip_blob; + DWORD i; + + sspi_status = + Curl_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))); + goto cleanup; + } + + Win8_compat = curlx_verify_windows_version(6, 2, 0, PLATFORM_WINNT, + VERSION_GREATER_THAN_EQUAL); + if(get_num_host_info(p, conn_hostname) || !Win8_compat) { + if(!get_alt_name_info(data, pCertContextServer, + &alt_name_info, &alt_name_info_size)) { + goto cleanup; + } + } + + if(p->size && alt_name_info) { + for(i = 0; i < alt_name_info->cAltEntry; ++i) { + PCERT_ALT_NAME_ENTRY entry = &alt_name_info->rgAltEntry[i]; + if(entry->dwAltNameChoice == CERT_ALT_NAME_IP_ADDRESS) { + if(entry->IPAddress.cbData == p->size) { + if(!memcmp(entry->IPAddress.pbData, &p->bData, + entry->IPAddress.cbData)) { + result = CURLE_OK; + infof(data, + "schannel: connection hostname (%s) matched cert's IP address!", + conn_hostname); + break; + } + } + } + } + } + else { + /* Determine the size of the string needed for the cert hostname */ + len = cert_get_name_string(data, pCertContextServer, + NULL, 0, alt_name_info, Win8_compat); + if(len == 0) { + failf(data, + "schannel: CertGetNameString() returned no " + "certificate name information"); + 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, alt_name_info, Win8_compat); + + /* Sanity check */ + if(actual_len != len) { + failf(data, + "schannel: CertGetNameString() returned certificate " + "name information of unexpected size"); + 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. + */ + 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 = + Curl_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/local-test-curl-delta-01/afc-curl/lib/vtls/sectransp.c b/local-test-curl-delta-01/afc-curl/lib/vtls/sectransp.c new file mode 100644 index 0000000000000000000000000000000000000000..c6a1c73dcf870fbc6eeb8705fa4f044491247753 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/sectransp.c @@ -0,0 +1,2779 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 Secure Transport-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_SECTRANSP + +#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" +#include "cipher_suite.h" + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunreachable-code" +#endif /* __clang__ */ + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Waddress" +#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 backend 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 backend 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 cannot include because it is not 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; + BIT(sent_shutdown); +}; + +/* Create the list of default ciphers to use by making an intersection of the + * ciphers supported by Secure Transport and the list below, using the order + * of the former. + * This list is based on TLS recommendations by Mozilla, balancing between + * security and wide compatibility: "Most ciphers that are not clearly broken + * and dangerous to use are supported" + */ +static const uint16_t default_ciphers[] = { + TLS_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */ + TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */ + TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */ + +#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */ + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */ + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */ + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */ +#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */ + TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */ + TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, /* 0x0067 */ + TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, /* 0x006B */ + TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */ + TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */ + TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* 0x009E */ + TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, /* 0x009F */ + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */ + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */ + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */ + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */ + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */ + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */ + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */ + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */ +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */ + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */ + + /* TLSv1.3 is not supported by Secure Transport, but there is also other + * code referencing TLSv1.3, like: kTLSProtocol13 ? */ + TLS_AES_128_GCM_SHA256, /* 0x1301 */ + TLS_AES_256_GCM_SHA384, /* 0x1302 */ + TLS_CHACHA20_POLY1305_SHA256, /* 0x1303 */ +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ +}; + +#define DEFAULT_CIPHERS_LEN sizeof(default_ciphers)/sizeof(default_ciphers[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 macOS 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 does not 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, FALSE, + &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; +} + +#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 = Curl_strtok_r(os_version, ".", &tok_buf); + os_version_minor = Curl_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 are not available under iOS or newer cats. 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 is 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, (CFIndex)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: could not 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 is 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 (does not 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 does not 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; i < keys_list_count; i++) { + OSStatus err = noErr; + SecCertificateRef cert = NULL; + SecIdentityRef identity = + (SecIdentityRef) CFArrayGetValueAtIndex(keys_list, i); + err = SecIdentityCopyCertificate(identity, &cert); + if(err == noErr) { + CFStringRef common_name = NULL; + OSStatus copy_status = noErr; +#if CURL_BUILD_IOS + common_name = SecCertificateCopySubjectSummary(cert); +#elif CURL_BUILD_MAC_10_7 + copy_status = SecCertificateCopyCommonName(cert, &common_name); +#endif + if(copy_status == noErr && + CFStringCompare(common_name, label_cf, 0) == kCFCompareEqualTo) { + CFRelease(cert); + CFRelease(common_name); + CFRetain(identity); + *out_cert_and_key = identity; + status = noErr; + break; + } + if(common_name) + CFRelease(common_name); + } + CFRelease(cert); + } + } + + if(keys_list) + CFRelease(keys_list); + CFRelease(query_dict); + CFRelease(label_cf); + } + else { +#if CURL_SUPPORT_MAC_10_6 + /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */ + status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); +#endif /* CURL_SUPPORT_MAC_10_6 */ + } +#elif CURL_SUPPORT_MAC_10_6 + /* For developers building on older cats, we have no choice but to fall back + to SecKeychainSearch. */ + status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); +#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ + return status; +} + +static OSStatus CopyIdentityFromPKCS12File(const char *cPath, + const struct curl_blob *blob, + const char *cPassword, + SecIdentityRef *out_cert_and_key) +{ + OSStatus status = errSecItemNotFound; + CFURLRef pkcs_url = NULL; + CFStringRef password = cPassword ? CFStringCreateWithCString(NULL, + cPassword, kCFStringEncodingUTF8) : NULL; + CFDataRef pkcs_data = NULL; + + /* We can import P12 files on iOS or macOS 10.7 or later: */ + /* These constants are documented as having first appeared in 10.6 but they + raise linker errors when used on that cat for some reason. */ +#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS + bool resource_imported; + + if(blob) { + pkcs_data = CFDataCreate(kCFAllocatorDefault, + (const unsigned char *)blob->data, + (CFIndex)blob->len); + status = (pkcs_data != NULL) ? errSecSuccess : errSecAllocate; + resource_imported = (pkcs_data != NULL); + } + else { + pkcs_url = + CFURLCreateFromFileSystemRepresentation(NULL, + (const UInt8 *)cPath, + (CFIndex)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 does not 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; +} + +static CURLcode +sectransp_set_ssl_version_min_max(struct Curl_easy *data, + struct st_ssl_backend_data *backend, + struct ssl_primary_config *conn_config) +{ +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + OSStatus err; + SSLProtocol ver_min; + SSLProtocol ver_max; + +#if CURL_SUPPORT_MAC_10_7 + if(!&SSLSetProtocolVersionMax) + goto legacy; +#endif + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + ver_min = kTLSProtocol1; + break; + case CURL_SSLVERSION_TLSv1_1: + ver_min = kTLSProtocol11; + break; + case CURL_SSLVERSION_TLSv1_2: + ver_min = kTLSProtocol12; + break; + case CURL_SSLVERSION_TLSv1_3: + default: + failf(data, "SSL: unsupported minimum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + case CURL_SSLVERSION_MAX_TLSv1_3: + case CURL_SSLVERSION_MAX_TLSv1_2: + ver_max = kTLSProtocol12; + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + ver_max = kTLSProtocol11; + break; + case CURL_SSLVERSION_MAX_TLSv1_0: + ver_max = kTLSProtocol1; + break; + default: + failf(data, "SSL: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + err = SSLSetProtocolVersionMin(backend->ssl_ctx, ver_min); + if(err != noErr) { + failf(data, "SSL: failed to set minimum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + err = SSLSetProtocolVersionMax(backend->ssl_ctx, ver_max); + if(err != noErr) { + failf(data, "SSL: failed to set maximum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + + return CURLE_OK; +#endif +#if CURL_SUPPORT_MAC_10_7 + goto legacy; +legacy: + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + break; + default: + failf(data, "SSL: unsupported minimum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + + /* only TLS 1.0 is supported, disable SSL 3.0 and SSL 2.0 */ + SSLSetProtocolVersionEnabled(backend->ssl_ctx, kSSLProtocolAll, FALSE); + SSLSetProtocolVersionEnabled(backend->ssl_ctx, kTLSProtocol1, TRUE); + + return CURLE_OK; +#endif +} + +static int sectransp_cipher_suite_get_str(uint16_t id, char *buf, + size_t buf_size, bool prefer_rfc) +{ + /* are these fortezza suites even supported ? */ + if(id == SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA) + msnprintf(buf, buf_size, "%s", "SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA"); + else if(id == SSL_FORTEZZA_DMS_WITH_NULL_SHA) + msnprintf(buf, buf_size, "%s", "SSL_FORTEZZA_DMS_WITH_NULL_SHA"); + /* can TLS_EMPTY_RENEGOTIATION_INFO_SCSV even be set ? */ + else if(id == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) + msnprintf(buf, buf_size, "%s", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"); + /* do we still need to support these SSL2-only ciphers ? */ + else if(id == SSL_RSA_WITH_RC2_CBC_MD5) + msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_RC2_CBC_MD5"); + else if(id == SSL_RSA_WITH_IDEA_CBC_MD5) + msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_IDEA_CBC_MD5"); + else if(id == SSL_RSA_WITH_DES_CBC_MD5) + msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_DES_CBC_MD5"); + else if(id == SSL_RSA_WITH_3DES_EDE_CBC_MD5) + msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_3DES_EDE_CBC_MD5"); + else + return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc); + return 0; +} + +static uint16_t sectransp_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) { + /* are these fortezza suites even supported ? */ + if(strncasecompare("SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA", *str, len)) + id = SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA; + else if(strncasecompare("SSL_FORTEZZA_DMS_WITH_NULL_SHA", *str, len)) + id = SSL_FORTEZZA_DMS_WITH_NULL_SHA; + /* can TLS_EMPTY_RENEGOTIATION_INFO_SCSV even be set ? */ + else if(strncasecompare("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", *str, len)) + id = TLS_EMPTY_RENEGOTIATION_INFO_SCSV; + /* do we still need to support these SSL2-only ciphers ? */ + else if(strncasecompare("SSL_RSA_WITH_RC2_CBC_MD5", *str, len)) + id = SSL_RSA_WITH_RC2_CBC_MD5; + else if(strncasecompare("SSL_RSA_WITH_IDEA_CBC_MD5", *str, len)) + id = SSL_RSA_WITH_IDEA_CBC_MD5; + else if(strncasecompare("SSL_RSA_WITH_DES_CBC_MD5", *str, len)) + id = SSL_RSA_WITH_DES_CBC_MD5; + else if(strncasecompare("SSL_RSA_WITH_3DES_EDE_CBC_MD5", *str, len)) + id = SSL_RSA_WITH_3DES_EDE_CBC_MD5; + } + return id; +} + +/* allocated memory must be freed */ +static SSLCipherSuite * sectransp_get_supported_ciphers(SSLContextRef ssl_ctx, + size_t *len) +{ + SSLCipherSuite *ciphers = NULL; + OSStatus err = noErr; + *len = 0; + + err = SSLGetNumberSupportedCiphers(ssl_ctx, len); + if(err != noErr) + goto failed; + + ciphers = malloc(*len * sizeof(SSLCipherSuite)); + if(!ciphers) + goto failed; + + err = SSLGetSupportedCiphers(ssl_ctx, ciphers, len); + if(err != noErr) + goto failed; + +#if CURL_BUILD_MAC + { + int maj = 0, min = 0; + GetDarwinVersionNumber(&maj, &min); + /* There is 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 macOS. */ + if(maj == 12 && min <= 3) { + size_t i = 0, j = 0; + for(; i < *len; i++) { + if(ciphers[i] >= 0xC001 && ciphers[i] <= 0xC032) + continue; + ciphers[j++] = ciphers[i]; + } + *len = j; + } + } +#endif + + return ciphers; +failed: + *len = 0; + Curl_safefree(ciphers); + return NULL; +} + +static CURLcode sectransp_set_default_ciphers(struct Curl_easy *data, + SSLContextRef ssl_ctx) +{ + CURLcode ret = CURLE_SSL_CIPHER; + size_t count = 0, i, j; + OSStatus err; + size_t supported_len; + SSLCipherSuite *ciphers = NULL; + + ciphers = sectransp_get_supported_ciphers(ssl_ctx, &supported_len); + if(!ciphers) { + failf(data, "SSL: Failed to get supported ciphers"); + goto failed; + } + + /* Intersect the ciphers supported by Secure Transport with the default + * ciphers, using the order of the former. */ + for(i = 0; i < supported_len; i++) { + for(j = 0; j < DEFAULT_CIPHERS_LEN; j++) { + if(default_ciphers[j] == ciphers[i]) { + ciphers[count++] = ciphers[i]; + break; + } + } + } + + if(count == 0) { + failf(data, "SSL: no supported default ciphers"); + goto failed; + } + + err = SSLSetEnabledCiphers(ssl_ctx, ciphers, count); + if(err != noErr) { + failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); + goto failed; + } + + ret = CURLE_OK; +failed: + Curl_safefree(ciphers); + return ret; +} + +static CURLcode sectransp_set_selected_ciphers(struct Curl_easy *data, + SSLContextRef ssl_ctx, + const char *ciphers) +{ + CURLcode ret = CURLE_SSL_CIPHER; + size_t count = 0, i; + const char *ptr, *end; + OSStatus err; + size_t supported_len; + SSLCipherSuite *supported = NULL; + SSLCipherSuite *selected = NULL; + + supported = sectransp_get_supported_ciphers(ssl_ctx, &supported_len); + if(!supported) { + failf(data, "SSL: Failed to get supported ciphers"); + goto failed; + } + + selected = malloc(supported_len * sizeof(SSLCipherSuite)); + if(!selected) { + failf(data, "SSL: Failed to allocate memory"); + goto failed; + } + + for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) { + uint16_t id = sectransp_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, "SSL: 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, "SSL: duplicate cipher in list: \"%.*s\"", (int) (end - ptr), + ptr); + continue; + } + + selected[count++] = id; + } + + if(count == 0) { + failf(data, "SSL: no supported cipher in list"); + goto failed; + } + + err = SSLSetEnabledCiphers(ssl_ctx, selected, count); + if(err != noErr) { + failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); + goto failed; + } + + ret = CURLE_OK; +failed: + Curl_safefree(supported); + Curl_safefree(selected); + return ret; +} + +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 do not 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; + CURLcode result; +#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: could not create a context"); + return CURLE_OUT_OF_MEMORY; + } + } + else { + /* The old ST API does not exist under iOS, so do not 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: could not 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: could not 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 */ + + result = sectransp_set_ssl_version_min_max(data, backend, conn_config); + if(result != CURLE_OK) + return result; + +#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && \ + defined(HAVE_BUILTIN_AVAILABLE) + 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; + 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: cannot find the certificate \"%s\" and its private " + "key in the Keychain.", cert_showfilename_error); + break; + default: + failf(data, "SSL: cannot 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 does not 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. + (Secure Transport always validates 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: cannot 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) { + result = sectransp_set_selected_ciphers(data, backend->ssl_ctx, ciphers); + } + else { + result = sectransp_set_default_ciphers(data, backend->ssl_ctx); + } + if(result != CURLE_OK) { + failf(data, "SSL: Unable to set ciphers for SSL/TLS handshake. " + "Error code: %d", (int)result); + 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 does not 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 is a cached ID we can/should use here! */ + if(ssl_config->primary.cache_session) { + 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, + NULL)) { + /* 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 is not one, then let's make one up! This has to be done prior + to starting the handshake. */ + else { + 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_set_sessionid(cf, data, &connssl->peer, NULL, + 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; + 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 CURLcode 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, (CFIndex)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; + CURLcode 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 was not specified, do not 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 = (size_t)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); + DEBUGASSERT(backend); + CURL_TRC_CF(data, cf, "connect_step2"); + + /* Here goes nothing: */ +check_handshake: + connssl->io_need = CURL_SSL_IO_NEED_NONE; + err = SSLHandshake(backend->ssl_ctx); + + if(err != noErr) { + switch(err) { + case errSSLWouldBlock: /* they are not done with us yet */ + connssl->io_need = backend->ssl_direction ? + CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + + /* The below is errSSLServerAuthCompleted; it is 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 did not match the server's + hostname: */ + 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 { + char cipher_str[64]; + /* we have been connected fine, we are 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); + + sectransp_cipher_suite_get_str((uint16_t) cipher, cipher_str, + sizeof(cipher_str), TRUE); + switch(protocol) { + case kSSLProtocol2: + infof(data, "SSL 2.0 connection using %s", cipher_str); + break; + case kSSLProtocol3: + infof(data, "SSL 3.0 connection using %s", cipher_str); + break; + case kTLSProtocol1: + infof(data, "TLS 1.0 connection using %s", cipher_str); + break; +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + case kTLSProtocol11: + infof(data, "TLS 1.1 connection using %s", cipher_str); + break; + case kTLSProtocol12: + infof(data, "TLS 1.2 connection using %s", cipher_str); + 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", cipher_str); + 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) && \ + defined(HAVE_BUILTIN_AVAILABLE) + 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); + + /* chosenProtocol is a reference to the string within alpnArr + and does not 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 does not 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 are 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) { + + /* 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 is available. */ + if(connssl->io_need) { + + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + 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))) + 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 ssize_t sectransp_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, + char *buf, + size_t buffersize, + CURLcode *curlcode); + +static CURLcode sectransp_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct st_ssl_backend_data *backend = + (struct st_ssl_backend_data *)connssl->backend; + CURLcode result = CURLE_OK; + ssize_t nread; + char buf[1024]; + size_t i; + + DEBUGASSERT(backend); + if(!backend->ssl_ctx || cf->shutdown) { + *done = TRUE; + goto out; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + + if(send_shutdown && !backend->sent_shutdown) { + OSStatus err; + + CURL_TRC_CF(data, cf, "shutdown, send close notify"); + err = SSLClose(backend->ssl_ctx); + switch(err) { + case noErr: + backend->sent_shutdown = TRUE; + break; + case errSSLWouldBlock: + connssl->io_need = CURL_SSL_IO_NEED_SEND; + result = CURLE_OK; + goto out; + default: + CURL_TRC_CF(data, cf, "shutdown, error: %d", (int)err); + result = CURLE_SEND_ERROR; + goto out; + } + } + + for(i = 0; i < 10; ++i) { + if(!backend->sent_shutdown) { + nread = sectransp_recv(cf, data, buf, (int)sizeof(buf), &result); + } + else { + /* We would like to read the close notify from the server using + * Secure Transport, however SSLRead() no longer works after we + * sent the notify from our side. So, we just read from the + * underlying filter and hope it will end. */ + nread = Curl_conn_cf_recv(cf->next, data, buf, sizeof(buf), &result); + } + CURL_TRC_CF(data, cf, "shutdown read -> %zd, %d", nread, result); + if(nread <= 0) + break; + } + + if(nread > 0) { + /* still data coming in? */ + connssl->io_need = CURL_SSL_IO_NEED_RECV; + } + else if(nread == 0) { + /* We got the close notify alert and are done. */ + CURL_TRC_CF(data, cf, "shutdown done"); + *done = TRUE; + } + else if(result == CURLE_AGAIN) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + result = CURLE_OK; + } + else { + DEBUGASSERT(result); + CURL_TRC_CF(data, cf, "shutdown, error: %d", result); + } + +out: + cf->shutdown = (result || *done); + return result; +} + +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"); +#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 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() is not 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 is 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 did not 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 have 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 is 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 | + SSLSUPP_CIPHER_LIST, + + 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 */ + sectransp_recv, /* recv decrypted data */ + sectransp_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif /* USE_SECTRANSP */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/sectransp.h b/local-test-curl-delta-01/afc-curl/lib/vtls/sectransp.h new file mode 100644 index 0000000000000000000000000000000000000000..0f1085ad91b29f10f88103f53f4ace455d4a2672 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.c b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.c new file mode 100644 index 0000000000000000000000000000000000000000..61b407ab22eaf198d51f3daecb3e532636383e86 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.c @@ -0,0 +1,2362 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "openssl.h" /* OpenSSL versions */ +#include "gtls.h" /* GnuTLS versions */ +#include "wolfssl.h" /* wolfSSL versions */ +#include "schannel.h" /* Schannel SSPI version */ +#include "sectransp.h" /* Secure Transport (Darwin) version */ +#include "mbedtls.h" /* mbedTLS versions */ +#include "bearssl.h" /* BearSSL versions */ +#include "rustls.h" /* Rustls versions */ + +#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 "connect.h" +#include "select.h" +#include "strdup.h" +#include "rand.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 is 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 = { + { ALPN_H2 }, 1 +}; +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_PRIOR_KNOWLEDGE) + return &ALPN_SPEC_H2; + 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 do not 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.cache_session = TRUE; /* 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->cache_session = source->cache_session; + 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 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) +{ + free_primary_ssl_config(&conn->ssl_config); +#ifndef CURL_DISABLE_PROXY + 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(); +} + +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; + Curl_bufq_init2(&ctx->earlydata, CURL_SSL_EARLY_MAX, 1, BUFQ_OPT_NO_SPARES); + 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) { + Curl_safefree(ctx->alpn_negotiated); + Curl_bufq_free(&ctx->earlydata); + 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 is a session ID for the given connection in the cache, and if + * there is 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 */ + char **palpn) +{ + 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(palpn) + *palpn = NULL; + if(!ssl_config) + return TRUE; + + DEBUGASSERT(ssl_config->primary.cache_session); + + if(!ssl_config->primary.cache_session || !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; + if(palpn) + *palpn = check->alpn; + no_match = FALSE; + break; + } + } + + CURL_TRC_CF(data, cf, "%s cached session ID for %s://%s:%d", + no_match ? "No" : "Found", + 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 */ + + free_primary_ssl_config(&session->ssl_config); + + Curl_safefree(session->name); + Curl_safefree(session->conn_to_host); + Curl_safefree(session->alpn); + } +} + +/* + * 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; + } + } +} + +CURLcode Curl_ssl_set_sessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + const char *alpn, + 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; + char *clone_alpn = NULL; + int conn_to_port; + long *general_age; + void *old_sessionid; + size_t old_size; + 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; + } + + if(!Curl_ssl_getsessionid(cf, data, peer, &old_sessionid, &old_size, NULL)) { + if((old_size == idsize) && + ((old_sessionid == ssl_sessionid) || + (idsize && !memcmp(old_sessionid, ssl_sessionid, idsize)))) { + /* the very same */ + sessionid_free_cb(ssl_sessionid, idsize); + return CURLE_OK; + } + Curl_ssl_delsessionid(data, old_sessionid); + } + + store = &data->state.session[0]; + oldest_age = data->state.session[0].age; /* zero if unused */ + DEBUGASSERT(ssl_config->primary.cache_session); + (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; + } + + clone_alpn = alpn ? strdup(alpn) : NULL; + if(alpn && !clone_alpn) + 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 hostname 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)) { + 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 is one already present */ + free(store->name); + free(store->conn_to_host); + store->name = clone_host; /* clone hostname */ + clone_host = NULL; + store->conn_to_host = clone_conn_to_host; /* clone connect to hostname */ + clone_conn_to_host = NULL; + store->conn_to_port = conn_to_port; /* connect to port number */ + store->alpn = clone_alpn; + clone_alpn = NULL; + /* 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); + free(clone_alpn); + 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; +} + +CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int sockindex, + struct dynbuf *binding) +{ + if(Curl_ssl->get_channel_binding) + return Curl_ssl->get_channel_binding(data, sockindex, binding); + return CURLE_OK; +} + +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) +{ + struct ssl_connect_data *connssl = cf->ctx; + + if(connssl->io_need) { + curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data); + if(sock != CURL_SOCKET_BAD) { + if(connssl->io_need & CURL_SSL_IO_NEED_SEND) { + Curl_pollset_set_out_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLOUT fd=%" FMT_SOCKET_T, + sock); + } + else { + Curl_pollset_set_in_only(data, ps, sock); + CURL_TRC_CF(data, cf, "adjust_pollset, POLLIN fd=%" FMT_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; i < ci->num_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; + + DEBUGASSERT(certnum < ci->num_of_certs); + + Curl_dyn_init(&build, CURL_X509_STR_MAX); + + 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; +} + +/* get 32 bits of random */ +CURLcode Curl_ssl_random(struct Curl_easy *data, + unsigned char *entropy, + size_t length) +{ + DEBUGASSERT(length == sizeof(int)); + if(Curl_ssl->random) + return Curl_ssl->random(data, entropy, length); + else + return CURLE_NOT_BUILT_IN; +} + +/* + * Public key pem to der conversion + */ + +static CURLcode pubkey_pem_to_der(const char *pem, + unsigned char **der, size_t *der_len) +{ + char *begin_pos, *end_pos; + size_t pem_count, pem_len; + CURLcode result; + struct dynbuf pbuf; + + /* if no pem, exit. */ + if(!pem) + return CURLE_BAD_CONTENT_ENCODING; + + Curl_dyn_init(&pbuf, MAX_PINNED_PUBKEY_SIZE); + + 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; + + /* + * 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]) { + result = Curl_dyn_addn(&pbuf, &pem[pem_count], 1); + if(result) + return result; + } + ++pem_count; + } + + result = Curl_base64_decode(Curl_dyn_ptr(&pbuf), der, der_len); + + Curl_dyn_free(&pbuf); + + 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) +{ + CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; +#endif + + /* if a path was not specified, do not 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)) { + 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 will 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); + } + else { + long filesize; + size_t size, pem_len; + CURLcode pem_read; + struct dynbuf buf; + char unsigned *pem_ptr = NULL; + size_t left; + FILE *fp = fopen(pinnedpubkey, "rb"); + if(!fp) + return result; + + Curl_dyn_init(&buf, MAX_PINNED_PUBKEY_SIZE); + + /* Determine the file's size */ + if(fseek(fp, 0, SEEK_END)) + goto end; + filesize = ftell(fp); + if(fseek(fp, 0, SEEK_SET)) + goto end; + if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE) + goto end; + + /* + * if the size of our certificate is bigger than the file + * size then it cannot match + */ + size = curlx_sotouz((curl_off_t) filesize); + if(pubkeylen > size) + goto end; + + /* + * Read the file into the dynbuf + */ + left = size; + do { + char buffer[1024]; + size_t want = left > sizeof(buffer) ? sizeof(buffer) : left; + if(want != fread(buffer, 1, want, fp)) + goto end; + if(Curl_dyn_addn(&buf, buffer, want)) + goto end; + left -= want; + } while(left); + + /* If the sizes are the same, it cannot be base64 encoded, must be der */ + if(pubkeylen == size) { + if(!memcmp(pubkey, Curl_dyn_ptr(&buf), pubkeylen)) + result = CURLE_OK; + goto end; + } + + /* + * Otherwise we will assume it is PEM and try to decode it + * after placing null terminator + */ + pem_read = pubkey_pem_to_der(Curl_dyn_ptr(&buf), &pem_ptr, &pem_len); + /* if it was not read successfully, exit */ + if(pem_read) + goto end; + + /* + * if the size of our certificate does not match the size of + * the decoded file, they cannot be the same, otherwise compare + */ + if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen)) + result = CURLE_OK; +end: + Curl_dyn_free(&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) +{ } + +CURLcode Curl_none_shutdown(struct Curl_cfilter *cf UNUSED_PARAM, + struct Curl_easy *data UNUSED_PARAM, + bool send_shutdown UNUSED_PARAM, + bool *done) +{ + (void)data; + (void)cf; + (void)send_shutdown; + /* Every SSL backend should have a shutdown implementation. Until we + * have implemented that, we put this fake in place. */ + *done = TRUE; + return CURLE_OK; +} + +int Curl_none_check_cxn(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + (void)cf; + (void)data; + return -1; +} + +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 */ + NULL, /* 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 */ + multissl_recv_plain, /* recv decrypted data */ + multissl_send_plain, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +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_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_SECTRANSP) + &Curl_ssl_sectransp; +#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_GNUTLS) + &Curl_ssl_gnutls, +#endif +#if defined(USE_MBEDTLS) + &Curl_ssl_mbedtls, +#endif +#if defined(USE_OPENSSL) + &Curl_ssl_openssl, +#endif +#if defined(USE_SECTRANSP) + &Curl_ssl_sectransp, +#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 +}; + +/* 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 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; + CURLcode result = CURLE_OUT_OF_MEMORY; + + /* We expect a clean struct, e.g. called only ONCE */ + DEBUGASSERT(peer); + DEBUGASSERT(!peer->hostname); + DEBUGASSERT(!peer->dispname); + DEBUGASSERT(!peer->sni); + /* We need the hostname for SNI negotiation. Once handshaked, this remains + * the SNI hostname for the TLS connection. When the connection is reused, + * the settings in cf->conn might change. We keep a copy of the hostname we + * use for SNI. + */ + peer->transport = transport; +#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; + peer->port = cf->conn->http_proxy.port; + } + else +#endif + { + ehostname = cf->conn->host.name; + edispname = cf->conn->host.dispname; + peer->port = cf->conn->remote_port; + } + + /* hostname MUST exist and not be empty */ + if(!ehostname || !ehostname[0]) { + result = CURLE_FAILED_INIT; + goto out; + } + + peer->hostname = strdup(ehostname); + if(!peer->hostname) + goto out; + if(!edispname || !strcmp(ehostname, edispname)) + peer->dispname = peer->hostname; + else { + peer->dispname = strdup(edispname); + if(!peer->dispname) + goto out; + } + peer->type = get_peer_type(peer->hostname); + if(peer->type == CURL_SSL_PEER_DNS) { + /* 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) + goto out; + Curl_strntolower(peer->sni, peer->hostname, len); + peer->sni[len] = 0; + } + } + result = CURLE_OK; + +out: + if(result) + Curl_ssl_peer_cleanup(peer); + return result; +} + +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; + } + + if(!cf->next) { + *done = FALSE; + return CURLE_FAILED_INIT; + } + + if(!cf->next->connected) { + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + } + + CF_DATA_SAVE(save, cf, data); + CURL_TRC_CF(data, cf, "cf_connect()"); + DEBUGASSERT(data->conn); + DEBUGASSERT(data->conn == cf->conn); + DEBUGASSERT(connssl); + + *done = FALSE; + if(!connssl->peer.hostname) { + 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(); + /* Connection can be deferred when sending early data */ + DEBUGASSERT(connssl->state == ssl_connection_complete || + connssl->state == ssl_connection_deferred); + } +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, + bool eos, CURLcode *err) +{ + struct cf_call_data save; + ssize_t nwritten = 0; + + (void)eos; + /* OpenSSL and maybe other TLS libs do not like 0-length writes. Skip. */ + *err = CURLE_OK; + if(len > 0) { + CF_DATA_SAVE(save, cf, data); + 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 CURLcode ssl_cf_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done) +{ + CURLcode result = CURLE_OK; + + *done = TRUE; + if(!cf->shutdown) { + struct cf_call_data save; + + CF_DATA_SAVE(save, cf, data); + result = Curl_ssl->shut_down(cf, data, TRUE, done); + CURL_TRC_CF(data, cf, "cf_shutdown -> %d, done=%d", result, *done); + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + } + return result; +} + +static void ssl_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + struct cf_call_data save; + + 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, + ssl_cf_shutdown, + 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, + ssl_cf_shutdown, + 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, unsigned int ssl_option) +{ + (void)data; + return (Curl_ssl->supports & ssl_option); +} + +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; +} + +static CURLcode vtls_shutdown_blocking(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct cf_call_data save; + CURLcode result = CURLE_OK; + timediff_t timeout_ms; + int what, loop = 10; + + if(cf->shutdown) { + *done = TRUE; + return CURLE_OK; + } + CF_DATA_SAVE(save, cf, data); + + *done = FALSE; + while(!result && !*done && loop--) { + timeout_ms = Curl_shutdown_timeleft(cf->conn, cf->sockindex, NULL); + + if(timeout_ms < 0) { + /* no need to continue if time is already up */ + failf(data, "SSL shutdown timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + + result = Curl_ssl->shut_down(cf, data, send_shutdown, done); + if(result ||*done) + goto out; + + if(connssl->io_need) { + what = Curl_conn_cf_poll(cf, data, timeout_ms); + if(what < 0) { + /* fatal error */ + failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); + result = CURLE_RECV_ERROR; + goto out; + } + else if(0 == what) { + /* timeout */ + failf(data, "SSL shutdown timeout"); + result = CURLE_OPERATION_TIMEDOUT; + goto out; + } + /* socket is readable or writable */ + } + } +out: + CF_DATA_RESTORE(cf, save); + cf->shutdown = (result || *done); + return result; +} + +CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data, + int sockindex, bool send_shutdown) +{ + struct Curl_cfilter *cf, *head; + CURLcode result = CURLE_OK; + + head = data->conn ? data->conn->cfilter[sockindex] : NULL; + for(cf = head; cf; cf = cf->next) { + if(cf->cft == &Curl_cft_ssl) { + bool done; + CURL_TRC_CF(data, cf, "shutdown and remove SSL, start"); + Curl_shutdown_start(data, sockindex, NULL); + result = vtls_shutdown_blocking(cf, data, send_shutdown, &done); + Curl_shutdown_clear(data, sockindex); + if(!result && !done) /* blocking failed? */ + result = CURLE_SSL_SHUTDOWN_FAILED; + Curl_conn_cf_discard_sub(head, cf, data, FALSE); + CURL_TRC_CF(data, cf, "shutdown and remove SSL, done -> %d", result); + 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; +} + +bool Curl_alpn_contains_proto(const struct alpn_spec *spec, + const char *proto) +{ + size_t i, plen = proto ? strlen(proto) : 0; + for(i = 0; spec && plen && i < spec->count; ++i) { + size_t slen = strlen(spec->entries[i]); + if((slen == plen) && !memcmp(proto, spec->entries[i], plen)) + return TRUE; + } + return FALSE; +} + +CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_connect_data *connssl, + const unsigned char *proto, + size_t proto_len) +{ + CURLcode result = CURLE_OK; + 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(connssl->alpn_negotiated) { + /* When we ask for a specific ALPN protocol, we need the confirmation + * of it by the server, as we have installed protocol handler and + * connection filter chain for exactly this protocol. */ + if(!proto_len) { + failf(data, "ALPN: asked for '%s' from previous session, " + "but server did not confirm it. Refusing to continue.", + connssl->alpn_negotiated); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + else if((strlen(connssl->alpn_negotiated) != proto_len) || + memcmp(connssl->alpn_negotiated, proto, proto_len)) { + failf(data, "ALPN: asked for '%s' from previous session, but server " + "selected '%.*s'. Refusing to continue.", + connssl->alpn_negotiated, (int)proto_len, proto); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + /* ALPN is exactly what we asked for, done. */ + infof(data, "ALPN: server confirmed to use '%s'", + connssl->alpn_negotiated); + goto out; + } + + if(proto && proto_len) { + if(memchr(proto, '\0', proto_len)) { + failf(data, "ALPN: server selected protocol contains NUL. " + "Refusing to continue."); + result = CURLE_SSL_CONNECT_ERROR; + goto out; + } + connssl->alpn_negotiated = malloc(proto_len + 1); + if(!connssl->alpn_negotiated) + return CURLE_OUT_OF_MEMORY; + memcpy(connssl->alpn_negotiated, proto, proto_len); + connssl->alpn_negotiated[proto_len] = 0; + } + + 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; + } +#endif +#ifdef USE_HTTP3 + else if(proto_len == ALPN_H3_LENGTH && + !memcmp(ALPN_H3, proto, ALPN_H3_LENGTH)) { + *palpn = CURL_HTTP_VERSION_3; + } +#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; + } + + if(connssl->state == ssl_connection_deferred) + infof(data, VTLS_INFOF_ALPN_DEFERRED, (int)proto_len, proto); + else + infof(data, VTLS_INFOF_ALPN_ACCEPTED, (int)proto_len, proto); + } + else { + *palpn = CURL_HTTP_VERSION_NONE; + if(connssl->state == ssl_connection_deferred) + infof(data, VTLS_INFOF_NO_ALPN_DEFERRED); + else + infof(data, VTLS_INFOF_NO_ALPN); + } + +out: + return result; +} + +#endif /* USE_SSL */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.h b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.h new file mode 100644 index 0000000000000000000000000000000000000000..7a223f6fead32cdacf84c940fe48ef47695e75a1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls.h @@ -0,0 +1,282 @@ +#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 SSLSUPP_CA_CACHE (1<<8) +#define SSLSUPP_CIPHER_LIST (1<<9) /* supports TLS 1.0-1.2 ciphersuites */ + +#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 \ + ALPN_ACCEPTED "%.*s" + +#define VTLS_INFOF_NO_ALPN_DEFERRED \ + "ALPN: deferred handshake for early data without specific protocol." +#define VTLS_INFOF_ALPN_DEFERRED \ + "ALPN: deferred handshake for early data using '%.*s'." + +/* Curl_multi SSL backend-specific data; declared differently by each SSL + backend */ +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 `data` 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. */ +#define CURL_X509_STR_MAX 100000 + +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); + +/* The maximum size of the SSL channel binding is 85 bytes, as defined in + * RFC 5929, Section 4.1. The 'tls-server-end-point:' prefix is 21 bytes long, + * and SHA-512 is the longest supported hash algorithm, with a digest length of + * 64 bytes. + * The maximum size of the channel binding is therefore 21 + 64 = 85 bytes. + */ +#define SSL_CB_MAX_SIZE 85 + +/* Return the tls-server-end-point channel binding, including the + * 'tls-server-end-point:' prefix. + * If successful, the data is written to the dynbuf, and CURLE_OK is returned. + * The dynbuf MUST HAVE a minimum toobig size of SSL_CB_MAX_SIZE. + * If the dynbuf is too small, CURLE_OUT_OF_MEMORY is returned. + * If channel binding is not supported, binding stays empty and CURLE_OK is + * returned. + */ +CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int sockindex, + struct dynbuf *binding); + +#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, bool send_shutdown); + +#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, unsigned 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,c) 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/local-test-curl-delta-01/afc-curl/lib/vtls/vtls_int.h b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls_int.h new file mode 100644 index 0000000000000000000000000000000000000000..13bd3fbb5e71cedb7e010bc26a5ae53f270198f7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/vtls_int.h @@ -0,0 +1,255 @@ +#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 + +struct ssl_connect_data; + +/* 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, + struct ssl_connect_data *connssl, + const unsigned char *proto, + size_t proto_len); + +bool Curl_alpn_contains_proto(const struct alpn_spec *spec, + const char *proto); + +/* enum for the nonblocking SSL connection state machine */ +typedef enum { + ssl_connect_1, + ssl_connect_2, + ssl_connect_3, + ssl_connect_done +} ssl_connect_state; + +typedef enum { + ssl_connection_none, + ssl_connection_deferred, + ssl_connection_negotiating, + ssl_connection_complete +} ssl_connection_state; + +typedef enum { + ssl_earlydata_none, + ssl_earlydata_use, + ssl_earlydata_sending, + ssl_earlydata_sent, + ssl_earlydata_accepted, + ssl_earlydata_rejected +} ssl_earlydata_state; + +#define CURL_SSL_IO_NEED_NONE (0) +#define CURL_SSL_IO_NEED_RECV (1<<0) +#define CURL_SSL_IO_NEED_SEND (1<<1) + +/* Max earlydata payload we want to send */ +#define CURL_SSL_EARLY_MAX (64*1024) + +/* Information in each SSL cfilter context: cf->ctx */ +struct ssl_connect_data { + 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 */ + char *alpn_negotiated; /* negotiated ALPN value or NULL */ + struct bufq earlydata; /* earlydata to be send to peer */ + size_t earlydata_max; /* max earlydata allowed by peer */ + size_t earlydata_skip; /* sending bytes to skip when earlydata + * is accepted by peer */ + ssl_connection_state state; + ssl_connect_state connecting_state; + ssl_earlydata_state earlydata_state; + int io_need; /* TLS signals special SEND/RECV needs */ + 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); + CURLcode (*shut_down)(struct Curl_cfilter *cf, struct Curl_easy *data, + bool send_shutdown, bool *done); + 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/shutdown, 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); + + 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); + + CURLcode (*get_channel_binding)(struct Curl_easy *data, int sockindex, + struct dynbuf *binding); + +}; + +extern const struct Curl_ssl *Curl_ssl; + + +int Curl_none_init(void); +void Curl_none_cleanup(void); +CURLcode Curl_none_shutdown(struct Curl_cfilter *cf, struct Curl_easy *data, + bool send_shutdown, bool *done); +int Curl_none_check_cxn(struct Curl_cfilter *cf, struct Curl_easy *data); +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). + * @param cf the connection filter wanting to use it + * @param data the transfer involved + * @param peer the peer the filter wants to talk to + * @param sessionid on return the TLS session + * @param idsize on return the size of the TLS session data + * @param palpn on return the ALPN string used by the session, + * set to NULL when not interested + */ +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 */ + char **palpn); + +/* Set a TLS session ID for `peer`. Replaces an existing session ID if + * not already the same. + * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). + * Call takes ownership of `ssl_sessionid`, using `sessionid_free_cb` + * to deallocate it. Is called in all outcomes, either right away or + * later when the session cache is cleaned up. + * Caller must ensure that it has properly shared ownership of this sessionid + * object with cache (e.g. incrementing refcount on success) + */ +CURLcode Curl_ssl_set_sessionid(struct Curl_cfilter *cf, + struct Curl_easy *data, + const struct ssl_peer *peer, + const char *alpn, + void *sessionid, + size_t sessionid_size, + Curl_ssl_sessionid_dtor *sessionid_free_cb); + +#endif /* USE_SSL */ + +#endif /* HEADER_CURL_VTLS_INT_H */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.c b/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.c new file mode 100644 index 0000000000000000000000000000000000000000..3394cb2748c51341e33fdfd604529078cc4ba3fc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.c @@ -0,0 +1,2061 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 + +#if LIBWOLFSSL_VERSION_HEX < 0x03004006 /* wolfSSL 3.4.6 (2015) */ +#error "wolfSSL version should be at least 3.4.6" +#endif + +/* 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 + +#ifdef HAVE_WOLFSSL_BIO +#define USE_BIO_CHAIN +#ifdef HAVE_WOLFSSL_FULL_BIO +#define USE_FULL_BIO +#else /* HAVE_WOLFSSL_FULL_BIO */ +#undef USE_FULL_BIO +#endif +/* wolfSSL 5.7.4 and older do not have these symbols, but only the + * OpenSSL ones. */ +#ifndef WOLFSSL_BIO_CTRL_GET_CLOSE +#define WOLFSSL_BIO_CTRL_GET_CLOSE BIO_CTRL_GET_CLOSE +#define WOLFSSL_BIO_CTRL_SET_CLOSE BIO_CTRL_SET_CLOSE +#define WOLFSSL_BIO_CTRL_FLUSH BIO_CTRL_FLUSH +#define WOLFSSL_BIO_CTRL_DUP BIO_CTRL_DUP +#define wolfSSL_BIO_set_retry_write BIO_set_retry_write +#define wolfSSL_BIO_set_retry_read BIO_set_retry_read +#endif /* !WOLFSSL_BIO_CTRL_GET_CLOSE */ + +#else /* HAVE_WOLFSSL_BIO */ +#undef USE_BIO_CHAIN +#endif + +#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(WOLFSSL *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) != + WOLFSSL_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 wolfssl_do_file_type(const char *type) +{ + if(!type || !type[0]) + return WOLFSSL_FILETYPE_PEM; + if(strcasecompare(type, "PEM")) + return WOLFSSL_FILETYPE_PEM; + if(strcasecompare(type, "DER")) + return WOLFSSL_FILETYPE_ASN1; + return -1; +} + +#ifdef WOLFSSL_HAVE_KYBER +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) +{ +#ifdef USE_FULL_BIO + wolfSSL_BIO_set_shutdown(bio, 1); +#endif + 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 = wolfSSL_BIO_get_data(bio); + long ret = 1; + + (void)cf; + (void)ptr; + (void)num; + switch(cmd) { + case WOLFSSL_BIO_CTRL_GET_CLOSE: +#ifdef USE_FULL_BIO + ret = (long)wolfSSL_BIO_get_shutdown(bio); +#else + ret = 0; +#endif + break; + case WOLFSSL_BIO_CTRL_SET_CLOSE: +#ifdef USE_FULL_BIO + wolfSSL_BIO_set_shutdown(bio, (int)num); +#endif + break; + case WOLFSSL_BIO_CTRL_FLUSH: + /* we do no delayed writes, but if we ever would, this + * needs to trigger it. */ + ret = 1; + break; + case WOLFSSL_BIO_CTRL_DUP: + ret = 1; + break; +#ifdef WOLFSSL_BIO_CTRL_EOF + case WOLFSSL_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_ctx *backend = + (struct wolfssl_ctx *)connssl->backend; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + ssize_t nwritten, skiplen = 0; + CURLcode result = CURLE_OK; + + DEBUGASSERT(data); + if(backend->shutting_down && backend->io_send_blocked_len && + (backend->io_send_blocked_len < blen)) { + /* bug in wolfSSL: + * It adds the close notify message again every time we retry + * sending during shutdown. */ + CURL_TRC_CF(data, cf, "bio_write, shutdown restrict send of %d" + " to %d bytes", blen, backend->io_send_blocked_len); + skiplen = (ssize_t)(blen - backend->io_send_blocked_len); + blen = backend->io_send_blocked_len; + } + nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &result); + backend->io_result = result; + CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d", + blen, nwritten, result); +#ifdef USE_FULL_BIO + wolfSSL_BIO_clear_retry_flags(bio); +#endif + if(nwritten < 0 && CURLE_AGAIN == result) { + wolfSSL_BIO_set_retry_write(bio); + if(backend->shutting_down && !backend->io_send_blocked_len) + backend->io_send_blocked_len = blen; + } + else if(!result && skiplen) + nwritten += skiplen; + 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_ctx *backend = + (struct wolfssl_ctx *)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); +#ifdef USE_FULL_BIO + wolfSSL_BIO_clear_retry_flags(bio); +#endif + if(nread < 0 && CURLE_AGAIN == result) + wolfSSL_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(WOLFSSL_BIO_MEMORY, + "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 */ + +static void wolfssl_session_free(void *sdata, size_t slen) +{ + (void)slen; + free(sdata); +} + +CURLcode wssl_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + WOLFSSL_SESSION *session) +{ + CURLcode result = CURLE_OK; + unsigned char *sdata = NULL; + unsigned int slen; + + if(!session) + goto out; + + slen = wolfSSL_i2d_SSL_SESSION(session, NULL); + if(slen <= 0) { + CURL_TRC_CF(data, cf, "fail to assess session length: %u", slen); + result = CURLE_FAILED_INIT; + goto out; + } + sdata = calloc(1, slen); + if(!sdata) { + failf(data, "unable to allocate session buffer of %u bytes", slen); + result = CURLE_OUT_OF_MEMORY; + goto out; + } + slen = wolfSSL_i2d_SSL_SESSION(session, &sdata); + if(slen <= 0) { + CURL_TRC_CF(data, cf, "fail to serialize session: %u", slen); + result = CURLE_FAILED_INIT; + goto out; + } + + Curl_ssl_sessionid_lock(data); + result = Curl_ssl_set_sessionid(cf, data, peer, NULL, + sdata, slen, wolfssl_session_free); + Curl_ssl_sessionid_unlock(data); + if(result) + failf(data, "failed to add new ssl session to cache (%d)", result); + else { + CURL_TRC_CF(data, cf, "added new session to cache"); + sdata = NULL; + } + +out: + free(sdata); + return 0; +} + +static int wssl_vtls_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session) +{ + struct Curl_cfilter *cf; + + cf = (struct Curl_cfilter*)wolfSSL_get_app_data(ssl); + DEBUGASSERT(cf != NULL); + if(cf && session) { + struct ssl_connect_data *connssl = cf->ctx; + struct Curl_easy *data = CF_DATA_CURRENT(cf); + DEBUGASSERT(connssl); + DEBUGASSERT(data); + if(connssl && data) { + (void)wssl_cache_session(cf, data, &connssl->peer, session); + } + } + return 0; +} + +CURLcode wssl_setup_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wolfssl_ctx *wss, + struct ssl_peer *peer) +{ + void *psdata; + const unsigned char *sdata = NULL; + size_t slen = 0; + CURLcode result = CURLE_OK; + + Curl_ssl_sessionid_lock(data); + if(!Curl_ssl_getsessionid(cf, data, peer, &psdata, &slen, NULL)) { + WOLFSSL_SESSION *session; + sdata = psdata; + session = wolfSSL_d2i_SSL_SESSION(NULL, &sdata, (long)slen); + if(session) { + int ret = wolfSSL_set_session(wss->handle, session); + if(ret != WOLFSSL_SUCCESS) { + Curl_ssl_delsessionid(data, psdata); + infof(data, "previous session not accepted (%d), " + "removing from cache", ret); + } + else + infof(data, "SSL reusing session ID"); + wolfSSL_SESSION_free(session); + } + else { + failf(data, "could not decode previous session"); + } + } + Curl_ssl_sessionid_unlock(data); + return result; +} + +static CURLcode populate_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + WOLFSSL_X509_STORE *store, + struct wolfssl_ctx *wssl) +{ + 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 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; + struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + bool imported_native_ca = FALSE; + +#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(wssl->ctx) != WOLFSSL_SUCCESS) { + infof(data, "error importing native CA store, continuing anyway"); + } + else { + imported_native_ca = TRUE; + infof(data, "successfully imported native CA store"); + wssl->x509_store_setup = TRUE; + } + } +#endif /* !NO_FILESYSTEM */ + + /* load certificate blob */ + if(ca_info_blob) { + if(wolfSSL_CTX_load_verify_buffer(wssl->ctx, ca_info_blob->data, + (long)ca_info_blob->len, + WOLFSSL_FILETYPE_PEM) != + WOLFSSL_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 { + infof(data, "successfully imported CA certificate blob"); + wssl->x509_store_setup = TRUE; + } + } + +#ifndef NO_FILESYSTEM + /* load trusted cacert from file if not blob */ + + 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((ssl_cafile || ssl_capath) && (!wssl->x509_store_setup)) { + int rc = + wolfSSL_CTX_load_verify_locations_ex(wssl->ctx, + ssl_cafile, + ssl_capath, + WOLFSSL_LOAD_FLAG_IGNORE_ERR); + if(WOLFSSL_SUCCESS != rc) { + if(conn_config->verifypeer) { + /* 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"); + } +#endif + (void)store; + wssl->x509_store_setup = TRUE; + return CURLE_OK; +} + +/* key to use at `multi->proto_hash` */ +#define MPROTO_WSSL_X509_KEY "tls:wssl:x509:share" + +struct wssl_x509_share { + char *CAfile; /* CAfile path used to generate X509 store */ + WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */ + struct curltime time; /* when the cached store was created */ +}; + +static void wssl_x509_share_free(void *key, size_t key_len, void *p) +{ + struct wssl_x509_share *share = p; + DEBUGASSERT(key_len == (sizeof(MPROTO_WSSL_X509_KEY)-1)); + DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len)); + (void)key; + (void)key_len; + if(share->store) { + wolfSSL_X509_STORE_free(share->store); + } + free(share->CAfile); + free(share); +} + +static bool +cached_x509_store_expired(const struct Curl_easy *data, + const struct wssl_x509_share *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 wssl_x509_share *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 WOLFSSL_X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf, + const struct Curl_easy *data) +{ + struct Curl_multi *multi = data->multi; + struct wssl_x509_share *share; + WOLFSSL_X509_STORE *store = NULL; + + DEBUGASSERT(multi); + share = multi ? Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_WSSL_X509_KEY, + sizeof(MPROTO_WSSL_X509_KEY)-1) : NULL; + if(share && share->store && + !cached_x509_store_expired(data, share) && + !cached_x509_store_different(cf, share)) { + store = share->store; + } + + return store; +} + +static void set_cached_x509_store(struct Curl_cfilter *cf, + const struct Curl_easy *data, + WOLFSSL_X509_STORE *store) +{ + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + struct Curl_multi *multi = data->multi; + struct wssl_x509_share *share; + + DEBUGASSERT(multi); + if(!multi) + return; + share = Curl_hash_pick(&multi->proto_hash, + (void *)MPROTO_WSSL_X509_KEY, + sizeof(MPROTO_WSSL_X509_KEY)-1); + + if(!share) { + share = calloc(1, sizeof(*share)); + if(!share) + return; + if(!Curl_hash_add2(&multi->proto_hash, + (void *)MPROTO_WSSL_X509_KEY, + sizeof(MPROTO_WSSL_X509_KEY)-1, + share, wssl_x509_share_free)) { + free(share); + return; + } + } + + if(wolfSSL_X509_STORE_up_ref(store)) { + char *CAfile = NULL; + + if(conn_config->CAfile) { + CAfile = strdup(conn_config->CAfile); + if(!CAfile) { + wolfSSL_X509_STORE_free(store); + return; + } + } + + if(share->store) { + wolfSSL_X509_STORE_free(share->store); + free(share->CAfile); + } + + share->time = Curl_now(); + share->store = store; + share->CAfile = CAfile; + } +} + +CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wolfssl_ctx *wssl) +{ + 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; + WOLFSSL_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 wolfSSL'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 = cache_criteria_met ? get_cached_x509_store(cf, data) : NULL; + if(cached_store && wolfSSL_CTX_get_cert_store(wssl->ctx) == cached_store) { + /* The cached store is already in use, do nothing. */ + } + else if(cached_store && wolfSSL_X509_STORE_up_ref(cached_store)) { + wolfSSL_CTX_set_cert_store(wssl->ctx, cached_store); + } + else if(cache_criteria_met) { + /* wolfSSL's initial store in CTX is not shareable by default. + * Make a new one, suitable for adding to the cache. See #14278 */ + WOLFSSL_X509_STORE *store = wolfSSL_X509_STORE_new(); + if(!store) { + failf(data, "SSL: could not create a X509 store"); + return CURLE_OUT_OF_MEMORY; + } + wolfSSL_CTX_set_cert_store(wssl->ctx, store); + + result = populate_x509_store(cf, data, store, wssl); + if(!result) { + set_cached_x509_store(cf, data, store); + } + } + else { + /* We never share the CTX's store, use it. */ + WOLFSSL_X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ctx); + result = populate_x509_store(cf, data, store, wssl); + } + + return result; +} + +#ifdef WOLFSSL_TLS13 +static CURLcode +wssl_add_default_ciphers(bool tls13, struct dynbuf *buf) +{ + int i; + char *str; + + for(i = 0; (str = wolfSSL_get_cipher_list(i)); i++) { + size_t n; + if((strncmp(str, "TLS13", 5) == 0) != tls13) + continue; + + /* if there already is data in the string, add colon separator */ + if(Curl_dyn_len(buf)) { + CURLcode result = Curl_dyn_addn(buf, ":", 1); + if(result) + return result; + } + + n = strlen(str); + if(Curl_dyn_addn(buf, str, n)) + return CURLE_OUT_OF_MEMORY; + } + + return CURLE_OK; +} +#endif + +/* 4.2.0 (2019) */ +#if LIBWOLFSSL_VERSION_HEX < 0x04002000 || !defined(OPENSSL_EXTRA) +static int +wssl_legacy_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version) +{ + int res; + switch(version) { + default: + case TLS1_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1); + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_1_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_1); + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_2_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_2); +#ifdef WOLFSSL_TLS13 + if(res == WOLFSSL_SUCCESS) + return res; + FALLTHROUGH(); + case TLS1_3_VERSION: + res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3); +#endif + } + return res; +} +static int +wssl_legacy_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version) +{ + (void) ctx, (void) version; + return WOLFSSL_NOT_IMPLEMENTED; +} +#define wolfSSL_CTX_set_min_proto_version wssl_legacy_CTX_set_min_proto_version +#define wolfSSL_CTX_set_max_proto_version wssl_legacy_CTX_set_max_proto_version +#endif + +/* + * 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) +{ + int res; + char *curves; + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ctx *backend = + (struct wolfssl_ctx *)connssl->backend; + struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); + const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); + WOLFSSL_METHOD* req_method = NULL; +#ifdef WOLFSSL_HAVE_KYBER + word16 pqkem = 0; + size_t idx = 0; +#endif + + DEBUGASSERT(backend); + + if(connssl->state == ssl_connection_complete) + return CURLE_OK; + +#if LIBWOLFSSL_VERSION_HEX < 0x04002000 /* 4.2.0 (2019) */ + req_method = wolfSSLv23_client_method(); +#else + req_method = wolfTLS_client_method(); +#endif + if(!req_method) { + failf(data, "wolfSSL: could not create a client 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, "wolfSSL: could not create a context"); + return CURLE_OUT_OF_MEMORY; + } + + switch(conn_config->version) { + case CURL_SSLVERSION_DEFAULT: + case CURL_SSLVERSION_TLSv1: + case CURL_SSLVERSION_TLSv1_0: + res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_VERSION); + break; + case CURL_SSLVERSION_TLSv1_1: + res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_1_VERSION); + break; + case CURL_SSLVERSION_TLSv1_2: + res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_2_VERSION); + break; +#ifdef WOLFSSL_TLS13 + case CURL_SSLVERSION_TLSv1_3: + res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_3_VERSION); + break; +#endif + default: + failf(data, "wolfSSL: unsupported minimum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + if(res != WOLFSSL_SUCCESS) { + failf(data, "wolfSSL: failed set the minimum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + + switch(conn_config->version_max) { +#ifdef WOLFSSL_TLS13 + case CURL_SSLVERSION_MAX_TLSv1_3: + res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_3_VERSION); + break; +#endif + case CURL_SSLVERSION_MAX_TLSv1_2: + res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_2_VERSION); + break; + case CURL_SSLVERSION_MAX_TLSv1_1: + res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_1_VERSION); + break; + case CURL_SSLVERSION_MAX_TLSv1_0: + res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_VERSION); + break; + case CURL_SSLVERSION_MAX_DEFAULT: + case CURL_SSLVERSION_MAX_NONE: + res = WOLFSSL_SUCCESS; + break; + default: + failf(data, "wolfSSL: unsupported maximum TLS version value"); + return CURLE_SSL_CONNECT_ERROR; + } + if(res != WOLFSSL_SUCCESS) { + failf(data, "wolfSSL: failed set the maximum TLS version"); + return CURLE_SSL_CONNECT_ERROR; + } + +#ifndef WOLFSSL_TLS13 + { + char *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); + } + } +#else +#define MAX_CIPHER_LEN 4096 + if(conn_config->cipher_list || conn_config->cipher_list13) { + const char *ciphers12 = conn_config->cipher_list; + const char *ciphers13 = conn_config->cipher_list13; + struct dynbuf c; + CURLcode result; + Curl_dyn_init(&c, MAX_CIPHER_LEN); + + if(ciphers13) + result = Curl_dyn_add(&c, ciphers13); + else + result = wssl_add_default_ciphers(TRUE, &c); + + if(!result) { + if(ciphers12) { + if(Curl_dyn_len(&c)) + result = Curl_dyn_addn(&c, ":", 1); + if(!result) + result = Curl_dyn_add(&c, ciphers12); + } + else + result = wssl_add_default_ciphers(FALSE, &c); + } + if(result) + return result; + + if(!wolfSSL_CTX_set_cipher_list(backend->ctx, Curl_dyn_ptr(&c))) { + failf(data, "failed setting cipher list: %s", Curl_dyn_ptr(&c)); + Curl_dyn_free(&c); + return CURLE_SSL_CIPHER; + } + infof(data, "Cipher selection: %s", Curl_dyn_ptr(&c)); + Curl_dyn_free(&c); + } +#endif + + curves = conn_config->curves; + if(curves) { + +#ifdef WOLFSSL_HAVE_KYBER + for(idx = 0; gnm[idx].name != NULL; idx++) { + if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) { + pqkem = gnm[idx].group; + break; + } + } + + if(pqkem == 0) +#endif + { + if(!wolfSSL_CTX_set1_curves_list(backend->ctx, curves)) { + failf(data, "failed setting curves list: '%s'", curves); + return CURLE_SSL_CIPHER; + } + } + } + + /* Load the client certificate, and private key */ +#ifndef NO_FILESYSTEM + if(ssl_config->primary.cert_blob || ssl_config->primary.clientcert) { + const char *cert_file = ssl_config->primary.clientcert; + const char *key_file = ssl_config->key; + const struct curl_blob *cert_blob = ssl_config->primary.cert_blob; + const struct curl_blob *key_blob = ssl_config->key_blob; + int file_type = wolfssl_do_file_type(ssl_config->cert_type); + int rc; + + switch(file_type) { + case WOLFSSL_FILETYPE_PEM: + rc = cert_blob ? + wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx, + cert_blob->data, + (long)cert_blob->len) : + wolfSSL_CTX_use_certificate_chain_file(backend->ctx, cert_file); + break; + case WOLFSSL_FILETYPE_ASN1: + rc = cert_blob ? + wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data, + (long)cert_blob->len, file_type) : + wolfSSL_CTX_use_certificate_file(backend->ctx, cert_file, file_type); + break; + default: + failf(data, "unknown cert type"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(rc != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!key_blob && !key_file) { + key_blob = cert_blob; + key_file = cert_file; + } + else + file_type = wolfssl_do_file_type(ssl_config->key_type); + + rc = key_blob ? + wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data, + (long)key_blob->len, file_type) : + wolfSSL_CTX_use_PrivateKey_file(backend->ctx, key_file, file_type); + if(rc != 1) { + failf(data, "unable to set private key"); + return CURLE_SSL_CONNECT_ERROR; + } + } +#else /* NO_FILESYSTEM */ + if(ssl_config->primary.cert_blob) { + const struct curl_blob *cert_blob = ssl_config->primary.cert_blob; + const struct curl_blob *key_blob = ssl_config->key_blob; + int file_type = wolfssl_do_file_type(ssl_config->cert_type); + int rc; + + switch(file_type) { + case WOLFSSL_FILETYPE_PEM: + rc = wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx, + cert_blob->data, + (long)cert_blob->len); + break; + case WOLFSSL_FILETYPE_ASN1: + rc = wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data, + (long)cert_blob->len, file_type); + break; + default: + failf(data, "unknown cert type"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(rc != 1) { + failf(data, "unable to use client certificate"); + return CURLE_SSL_CONNECT_ERROR; + } + + if(!key_blob) + key_blob = cert_blob; + else + file_type = wolfssl_do_file_type(ssl_config->key_type); + + if(wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data, + (long)key_blob->len, + 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 ? WOLFSSL_VERIFY_PEER : + WOLFSSL_VERIFY_NONE, NULL); + +#ifdef HAVE_SNI + if(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; + if(!backend->x509_store_setup) { + result = Curl_wssl_setup_x509_store(cf, data, backend); + if(result) + return result; + } + 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 cannot 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: could not create a handle"); + return CURLE_OUT_OF_MEMORY; + } + +#ifdef WOLFSSL_HAVE_KYBER + if(pqkem) { + if(wolfSSL_UseKeyShare(backend->handle, pqkem) != WOLFSSL_SUCCESS) { + failf(data, "unable to use PQ 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, (unsigned int)proto.len, + WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != WOLFSSL_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 is a cached ID we can/should use here! */ + if(ssl_config->primary.cache_session) { + /* Set session from cache if there is one */ + (void)wssl_setup_session(cf, data, backend, &connssl->peer); + /* Register to get notified when a new session is received */ + wolfSSL_set_app_data(backend->handle, cf); + wolfSSL_CTX_sess_set_new_cb(backend->ctx, wssl_vtls_new_session_cb); + } + +#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_unlink(data, &dns); + } + } + + if(trying_ech_now + && SSL_set_min_proto_version(backend->handle, TLS1_3_VERSION) != 1) { + infof(data, "ECH: cannot force TLSv1.3 [ERROR]"); + return CURLE_SSL_CONNECT_ERROR; + } + + } +#endif /* USE_ECH */ + +#ifdef USE_BIO_CHAIN + { + WOLFSSL_BIO *bio; + + bio = wolfSSL_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 char *wolfssl_strerror(unsigned long error, char *buf, + unsigned long size) +{ + DEBUGASSERT(size > 40); + *buf = '\0'; + + wolfSSL_ERR_error_string_n(error, buf, size); + + if(!*buf) { + const char *msg = error ? "Unknown error" : "No error"; + /* the string fits because the assert above assures this */ + strcpy(buf, msg); + } + + return buf; +} + + +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_ctx *backend = + (struct wolfssl_ctx *)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) == WOLFSSL_FAILURE) + return CURLE_SSL_CONNECT_ERROR; + } + + if(!backend->x509_store_setup) { + /* After having send off the ClientHello, we prepare the x509 + * store to verify the coming certificate from the server */ + CURLcode result; + result = Curl_wssl_setup_x509_store(cf, data, backend); + if(result) + return result; + } + + connssl->io_need = CURL_SSL_IO_NEED_NONE; + 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 == WOLFSSL_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) { + int detail = wolfSSL_get_error(backend->handle, ret); + + if(WOLFSSL_ERROR_WANT_READ == detail) { + connssl->io_need = CURL_SSL_IO_NEED_RECV; + return CURLE_OK; + } + else if(WOLFSSL_ERROR_WANT_WRITE == detail) { + connssl->io_need = CURL_SSL_IO_NEED_SEND; + 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 + } + 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"); + } + } + else if(ASN_AFTER_DATE_E == detail) { + failf(data, "server verification failed: certificate has expired."); + return CURLE_PEER_FAILED_VERIFICATION; + } + else if(ASN_BEFORE_DATE_E == detail) { + failf(data, "server verification failed: certificate not valid yet."); + return CURLE_PEER_FAILED_VERIFICATION; + } +#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 does not 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 { + char error_buffer[256]; + failf(data, "SSL_connect failed with error %d: %s", detail, + wolfssl_strerror((unsigned long)detail, error_buffer, + sizeof(error_buffer))); + return CURLE_SSL_CONNECT_ERROR; + } + } + + if(pinnedpubkey) { +#ifdef KEEP_PEER_CERT + WOLFSSL_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 == WOLFSSL_SUCCESS) { + Curl_alpn_set_negotiated(cf, data, connssl, + (const unsigned char *)protocol, protocol_len); + } + else if(rc == WOLFSSL_ALPN_NOT_FOUND) + Curl_alpn_set_negotiated(cf, data, connssl, 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 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_ctx *backend = + (struct wolfssl_ctx *)connssl->backend; + 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 WOLFSSL_ERROR_WANT_READ: + case WOLFSSL_ERROR_WANT_WRITE: + /* there is 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); + { + char error_buffer[256]; + failf(data, "SSL write: %s, errno %d", + wolfssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), + SOCKERRNO); + } + *curlcode = CURLE_SEND_ERROR; + return -1; + } + } + CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d", len, rc); + return rc; +} + +static CURLcode wolfssl_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool send_shutdown, bool *done) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ctx *wctx = (struct wolfssl_ctx *)connssl->backend; + CURLcode result = CURLE_OK; + char buf[1024]; + char error_buffer[256]; + int nread = -1, err; + size_t i; + int detail; + + DEBUGASSERT(wctx); + if(!wctx->handle || cf->shutdown) { + *done = TRUE; + goto out; + } + + wctx->shutting_down = TRUE; + connssl->io_need = CURL_SSL_IO_NEED_NONE; + *done = FALSE; + if(!(wolfSSL_get_shutdown(wctx->handle) & WOLFSSL_SENT_SHUTDOWN)) { + /* We have not started the shutdown from our side yet. Check + * if the server already sent us one. */ + wolfSSL_ERR_clear_error(); + nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf)); + err = wolfSSL_get_error(wctx->handle, nread); + CURL_TRC_CF(data, cf, "wolfSSL_read, nread=%d, err=%d", nread, err); + if(!nread && err == WOLFSSL_ERROR_ZERO_RETURN) { + bool input_pending; + /* Yes, it did. */ + if(!send_shutdown) { + CURL_TRC_CF(data, cf, "SSL shutdown received, not sending"); + *done = TRUE; + goto out; + } + else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) { + /* Server closed the connection after its closy notify. It + * seems not interested to see our close notify, so do not + * send it. We are done. */ + CURL_TRC_CF(data, cf, "peer closed connection"); + connssl->peer_closed = TRUE; + *done = TRUE; + goto out; + } + } + } + + /* SSL should now have started the shutdown from our side. Since it + * was not complete, we are lacking the close notify from the server. */ + if(send_shutdown) { + wolfSSL_ERR_clear_error(); + if(wolfSSL_shutdown(wctx->handle) == 1) { + CURL_TRC_CF(data, cf, "SSL shutdown finished"); + *done = TRUE; + goto out; + } + if(WOLFSSL_ERROR_WANT_WRITE == wolfSSL_get_error(wctx->handle, nread)) { + CURL_TRC_CF(data, cf, "SSL shutdown still wants to send"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + goto out; + } + /* Having sent the close notify, we use wolfSSL_read() to get the + * missing close notify from the server. */ + } + + for(i = 0; i < 10; ++i) { + wolfSSL_ERR_clear_error(); + nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf)); + if(nread <= 0) + break; + } + err = wolfSSL_get_error(wctx->handle, nread); + switch(err) { + case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "SSL shutdown received"); + *done = TRUE; + break; + case WOLFSSL_ERROR_NONE: /* just did not get anything */ + case WOLFSSL_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, want receive"); + connssl->io_need = CURL_SSL_IO_NEED_RECV; + break; + case WOLFSSL_ERROR_WANT_WRITE: + CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); + connssl->io_need = CURL_SSL_IO_NEED_SEND; + break; + default: + detail = wolfSSL_get_error(wctx->handle, err); + CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)", + wolfssl_strerror((unsigned long)err, error_buffer, + sizeof(error_buffer)), + detail); + result = CURLE_RECV_ERROR; + break; + } + +out: + cf->shutdown = (result || *done); + return result; +} + +static void wolfssl_close(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct ssl_connect_data *connssl = cf->ctx; + struct wolfssl_ctx *backend = + (struct wolfssl_ctx *)connssl->backend; + + (void) data; + + DEBUGASSERT(backend); + + if(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_ctx *backend = + (struct wolfssl_ctx *)connssl->backend; + 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 WOLFSSL_ERROR_ZERO_RETURN: /* no more data */ + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen); + *curlcode = CURLE_OK; + return 0; + case WOLFSSL_ERROR_NONE: + case WOLFSSL_ERROR_WANT_READ: + case WOLFSSL_ERROR_WANT_WRITE: + if(!backend->io_result && connssl->peer_closed) { + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen); + *curlcode = CURLE_OK; + return 0; + } + /* there is 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; + } + else if(!backend->io_result && connssl->peer_closed) { + CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen); + *curlcode = CURLE_OK; + return 0; + } + else { + char error_buffer[256]; + failf(data, "SSL read: %s, errno %d", + wolfssl_strerror((unsigned long)err, error_buffer, + sizeof(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() == WOLFSSL_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_ctx *backend; + + (void)data; + DEBUGASSERT(ctx && ctx->backend); + + backend = (struct wolfssl_ctx *)ctx->backend; + if(backend->handle) /* SSL is in use */ + return wolfSSL_pending(backend->handle); + else + return FALSE; +} + +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); + + /* 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 are 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) { + + /* 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 is available. */ + if(connssl->io_need) { + curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ? + sockfd : CURL_SOCKET_BAD; + curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ? + sockfd : CURL_SOCKET_BAD; + int 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))) + return result; + } /* repeat step2 until all transactions are done. */ + + if(ssl_connect_3 == connssl->connecting_state) { + /* In other backends, this is where we verify the certificate, but + * wolfSSL already does that as part of the handshake. */ + connssl->connecting_state = ssl_connect_done; + } + + 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_ctx *backend = + (struct wolfssl_ctx *)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 | +#ifdef WOLFSSL_TLS13 + SSLSUPP_TLS13_CIPHERSUITES | +#endif + SSLSUPP_CA_CACHE | + SSLSUPP_CIPHER_LIST, + + sizeof(struct wolfssl_ctx), + + 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 */ + wolfssl_recv, /* recv decrypted data */ + wolfssl_send, /* send data to encrypt */ + NULL, /* get_channel_binding */ +}; + +#endif diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.h b/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.h new file mode 100644 index 0000000000000000000000000000000000000000..dc2967d69c7480bc95e5135db25ed15338f3ba2d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/wolfssl.h @@ -0,0 +1,66 @@ +#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 + +#include "urldata.h" + +struct WOLFSSL; +typedef struct WOLFSSL WOLFSSL; +struct WOLFSSL_CTX; +typedef struct WOLFSSL_CTX WOLFSSL_CTX; +struct WOLFSSL_SESSION; +typedef struct WOLFSSL_SESSION WOLFSSL_SESSION; + +extern const struct Curl_ssl Curl_ssl_wolfssl; + +struct wolfssl_ctx { + WOLFSSL_CTX *ctx; + WOLFSSL *handle; + CURLcode io_result; /* result of last BIO cfilter operation */ + int io_send_blocked_len; /* length of last BIO write that EAGAINed */ + BIT(x509_store_setup); /* x509 store has been set up */ + BIT(shutting_down); /* TLS is being shut down */ +}; + +CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wolfssl_ctx *wssl); + +CURLcode wssl_setup_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct wolfssl_ctx *wss, + struct ssl_peer *peer); + +CURLcode wssl_cache_session(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct ssl_peer *peer, + WOLFSSL_SESSION *session); + + +#endif /* USE_WOLFSSL */ +#endif /* HEADER_CURL_WOLFSSL_H */ diff --git a/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.c b/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.c new file mode 100644 index 0000000000000000000000000000000000000000..fe4a38b8f747a24ef5aa44dfc71b2b7e1e1a9d66 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.c @@ -0,0 +1,1259 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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) || \ + defined(USE_MBEDTLS) + +#if defined(USE_WOLFSSL) || defined(USE_SCHANNEL) +#define WANT_PARSEX509 /* uses Curl_parseX509() */ +#endif + +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) || \ + defined(USE_MBEDTLS) +#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 + + +#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 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.10045.4.3.1", "ecdsa-with-SHA224" }, + { "1.2.840.10045.4.3.2", "ecdsa-with-SHA256" }, + { "1.2.840.10045.4.3.3", "ecdsa-with-SHA384" }, + { "1.2.840.10045.4.3.4", "ecdsa-with-SHA512" }, + { "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" }, + { "2.5.4.3", "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" }, + { "2.5.29.17", "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 */ + size_t 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) { + /* 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, CURL_X509_STR_MAX); + 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 = Curl_dyn_add(store, Curl_dyn_ptr(&buf)); + 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 && ISDIGIT(*fracp); 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; + } + + /* timezone follows optional fractional seconds. */ + tzp = fracp; + fracl = 0; /* no fractional seconds detected so far */ + if(fracp < end && (*fracp == '.' || *fracp == ',')) { + /* Have fractional seconds, e.g. "[.,]\d+". How many? */ + fracp++; /* should be a digit char or BAD ARGUMENT */ + tzp = fracp; + while(tzp < end && ISDIGIT(*tzp)) + tzp++; + if(tzp == fracp) /* never looped, no digit after [.,] */ + return CURLE_BAD_FUNCTION_ARGUMENT; + fracl = tzp - fracp; /* number of fractional sec digits */ + DEBUGASSERT(fracl > 0); + /* Strip trailing zeroes in fractional seconds. + * May reduce fracl to 0 if only '0's are present. */ + while(fracl && fracp[fracl - 1] == '0') + fracl--; + } + + /* Process timezone. */ + if(tzp >= end) { + tzp = ""; + tzl = 0; + } + else if(*tzp == 'Z') { + sep = " "; + tzp = "GMT"; + tzl = 3; + } + else if((*tzp == '+') || (*tzp == '-')) { + sep = " UTC"; + tzl = end - tzp; + } + else { + sep = " "; + 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); +} + +#ifdef UNITTESTS +/* used by unit1656.c */ +CURLcode Curl_x509_GTime2str(struct dynbuf *store, + const char *beg, const char *end) +{ + return GTime2str(store, beg, end); +} +#endif + +/* + * 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 result; /* 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, CURL_X509_STR_MAX); + + 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); + + if(!str) { + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto error; + } + + /* 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, CURL_X509_STR_MAX); + + /* 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) == CURLE_OK + ? 0 : 1; + } + + /* 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, CURL_X509_STR_MAX); + /* 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: + if(result) + failf(data, "Failed extracting certificate chain"); + 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/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.h b/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.h new file mode 100644 index 0000000000000000000000000000000000000000..5b48596c75910a5ef74e60c5e114a3e90762beb0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/lib/vtls/x509asn1.h @@ -0,0 +1,92 @@ +#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) || \ + defined(USE_MBEDTLS) + +#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); + +#ifdef UNITTESTS +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) || \ + defined(USE_MBEDTLS) + +/* used by unit1656.c */ +CURLcode Curl_x509_GTime2str(struct dynbuf *store, + const char *beg, const char *end); +#endif +#endif + +#endif /* USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL or USE_SECTRANSP */ +#endif /* HEADER_CURL_X509ASN1_H */ diff --git a/local-test-curl-delta-01/afc-curl/packages/OS400/README.OS400 b/local-test-curl-delta-01/afc-curl/packages/OS400/README.OS400 new file mode 100644 index 0000000000000000000000000000000000000000..1bc4132f679797b4e6a2e27f501769934a61e00a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/README.OS400 @@ -0,0 +1,390 @@ + +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 test environment is 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/local-test-curl-delta-01/afc-curl/packages/OS400/ccsidcurl.c b/local-test-curl-delta-01/afc-curl/packages/OS400/ccsidcurl.c new file mode 100644 index 0000000000000000000000000000000000000000..48f7f6d4aeb1296a49e5e72bf95a73c8bb459c78 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/ccsidcurl.c @@ -0,0 +1,1530 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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; + struct Curl_easy *data = easy; + + 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 = data->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; + } + + data->set.postfieldsize = pfsize; /* Replace data size. */ + s = cp; + } + + result = curl_easy_setopt(easy, CURLOPT_POSTFIELDS, s); + data->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/local-test-curl-delta-01/afc-curl/packages/OS400/ccsidcurl.h b/local-test-curl-delta-01/afc-curl/packages/OS400/ccsidcurl.h new file mode 100644 index 0000000000000000000000000000000000000000..ab01d32b854be3cfd4152bacd7d520900c859695 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/config400.default b/local-test-curl-delta-01/afc-curl/packages/OS400/config400.default new file mode 100644 index 0000000000000000000000000000000000000000..4e7ddbac5772f58f44a2e0ef3602bfebf599cc33 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/config400.default @@ -0,0 +1,56 @@ +#!/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. +setenv PASEPERL '/QOpenSys/pkgs/bin/perl' # PASE Perl interpreter. + +# 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/local-test-curl-delta-01/afc-curl/packages/OS400/curl.cmd b/local-test-curl-delta-01/afc-curl/packages/OS400/curl.cmd new file mode 100644 index 0000000000000000000000000000000000000000..822f4db207e662ebbce7b803f46bdb4907093258 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/curl.inc.in b/local-test-curl-delta-01/afc-curl/packages/OS400/curl.inc.in new file mode 100644 index 0000000000000000000000000000000000000000..81ba82c358803a2391168de38f88e3baecac5519 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/curl.inc.in @@ -0,0 +1,3450 @@ + ************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 c X'00001000' + d CURLU_PUNY2IDN c X'00002000' + d CURLU_GET_EMPTY... + d c X'00004000' + d CURLU_NO_GUESS_SCHEME... + d c X'00008000' + * + 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 + d CURLOPT_TCP_KEEPCNT... + d c 00326 + * + /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/local-test-curl-delta-01/afc-curl/packages/OS400/curlcl.c b/local-test-curl-delta-01/afc-curl/packages/OS400/curlcl.c new file mode 100644 index 0000000000000000000000000000000000000000..02edcd63c0c12361b80e2b97804bdd5ae55d5d66 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/curlmain.c b/local-test-curl-delta-01/afc-curl/packages/OS400/curlmain.c new file mode 100644 index 0000000000000000000000000000000000000000..079b9b0d9dcda2e52844d14f894b664cca7bbd89 --- /dev/null +++ b/local-test-curl-delta-01/afc-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]; + /* To/From codes are 32 byte long strings with + reserved fields initialized to ZEROs */ + const char tocode[32] = {"IBMCCSID01208"}; /* Use UTF-8. */ + const char fromcode[32] = {"IBMCCSID000000000010"}; + + ebcdic_argc = argc; + ebcdic_argv = argv; + + /* Build the encoding converter. */ + 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/local-test-curl-delta-01/afc-curl/packages/OS400/initscript.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/initscript.sh new file mode 100644 index 0000000000000000000000000000000000000000..69a354ab0d0c1440414811f952316d7de0b664a4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/initscript.sh @@ -0,0 +1,297 @@ +#!/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 + +# Check if perl available. +{ [ -n "${PASEPERL}" ] && [ -x "${PASEPERL}" ]; } || PASEPERL= + +# 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}" + } > "${1}"__819.c + CMD="CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('${1}__819.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}" + if [ "${DEBUG}" = "*NONE" ] + then rm -f "${1}"__819.c + fi + # 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/local-test-curl-delta-01/afc-curl/packages/OS400/make-docs.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/make-docs.sh new file mode 100644 index 0000000000000000000000000000000000000000..b79b19e92813788ca423098514dc1c87f455f211 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/make-docs.sh @@ -0,0 +1,65 @@ +#!/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 +# +########################################################################### +# +# Documentation build script for the OS/400. +# + + +SCRIPTDIR=$(dirname "${0}") +. "${SCRIPTDIR}/initscript.sh" + +[ -n "${PASEPERL}" ] || exit 0 # Perl needed for doc build. +cd "${TOPDIR}/docs" || exit 1 +[ -d "${IFSDIR}/docs" ] || mkdir "${IFSDIR}/docs" + + +# Command line options. + +( + cd cmdline-opts || exit 1 + MANPAGE=curl.1 + TEXTPAGE=curl.txt + get_make_vars Makefile.inc + rm -f "${IFSDIR}/docs/${MANPAGE}" "${IFSDIR}/docs/${TEXTPAGE}" + + # Prepare online manual. + # shellcheck disable=SC2086 + ${PASEPERL} "${TOPDIR}/scripts/managen" -c 75 \ + listhelp ${DPAGES} > "${TOPDIR}/src/tool_listhelp.c" + + # Generate text manual and copy it to DB2. + # shellcheck disable=SC2086 + ${PASEPERL} "${TOPDIR}/scripts/managen" -I "${TOPDIR}/include" \ + -c 75 ascii ${DPAGES} > "${IFSDIR}/docs/${TEXTPAGE}" + MEMBER="${LIBIFSNAME}/DOCS.FILE/MANUAL.MBR" + CMD="CPY OBJ('${IFSDIR}/docs/${TEXTPAGE}') TOOBJ('${MEMBER}')" + CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" + CLcommand "${CMD}" + +# Man page is useless as OS/400 has no man command. +# # shellcheck disable=SC2086 +# ${PASEPERL} "${TOPDIR}/scripts/managen" -I "${TOPDIR}/include" \ +# mainpage ${DPAGES} > "${IFSDIR}/docs/${MANPAGE}" +) diff --git a/local-test-curl-delta-01/afc-curl/packages/OS400/make-include.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/make-include.sh new file mode 100644 index 0000000000000000000000000000000000000000..e30e950539ee3838b177d840fc5cf3988a695198 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/make-lib.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/make-lib.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7b5b519e7e88443a582be515e509e6f38b8c4ea --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/make-src.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/make-src.sh new file mode 100644 index 0000000000000000000000000000000000000000..21fd0015b464fef8ebb480ac32c1b97a110e2e84 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/make-src.sh @@ -0,0 +1,110 @@ +#!/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 + + +# Check if built-in manual can be generated. + +USE_MANUAL= +if [ -f "${IFSDIR}/docs/curl.txt" ] && [ -n "${PASEPERL}" ] +then "${PASEPERL}" ./mkhelp.pl < "${IFSDIR}/docs/curl.txt" > tool_hugehelp.c + USE_MANUAL="'USE_MANUAL'" +fi + + +# 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}" "${USE_MANUAL}" +done + +for SRC in ${CURL_CFILES} +do MODULE=$(db2_name "${SRC}") + make_module "${MODULE}" "${SRC}" "${USE_MANUAL}" +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/local-test-curl-delta-01/afc-curl/packages/OS400/make-tests.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/make-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a2125965cfc9774b1c1960440c5cec9e7ef1641 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/make-tests.sh @@ -0,0 +1,144 @@ +#!/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 + + # shellcheck disable=SC2153 + build_all_programs "" "${TARGETLIB}/${SRVPGM}" +) diff --git a/local-test-curl-delta-01/afc-curl/packages/OS400/makefile.sh b/local-test-curl-delta-01/afc-curl/packages/OS400/makefile.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f75845215895b2fcc4d2363efa928cc3781dc3c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/OS400/makefile.sh @@ -0,0 +1,135 @@ +#!/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 + + +# Make sure all files are UTF8-encoded. + +# shellcheck disable=SC2038 +find "${TOPDIR}" -type f -print | xargs ls -S | while read -r CCSID FILE +do if [ "${CCSID}" != 1208 ] + then CMD="CPY OBJ('${FILE}') TOOBJ('${FILE}') FROMCCSID(*OBJ)" + CMD="${CMD} TOCCSID(1208) DTAFMT(*TEXT) REPLACE(*YES)" + (CLcommand "${CMD}") + fi +done + + +# 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.md" "${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 docs src tests +for SUBDIR in include lib docs src +do "${SCRIPTDIR}/make-${SUBDIR}.sh" +done diff --git a/local-test-curl-delta-01/afc-curl/packages/OS400/os400sys.c b/local-test-curl-delta-01/afc-curl/packages/OS400/os400sys.c new file mode 100644 index 0000000000000000000000000000000000000000..07be5dcc514bbfc6e1cebeae56ad3523c2a4f476 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/os400sys.h b/local-test-curl-delta-01/afc-curl/packages/OS400/os400sys.h new file mode 100644 index 0000000000000000000000000000000000000000..d5ff412f285245727a584cb5379d8bf0b4aed57d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/HEADERAPI b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/HEADERAPI new file mode 100644 index 0000000000000000000000000000000000000000..2c2407ea247ef491c302d110402a3e1cbaeab446 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/HTTPPOST b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/HTTPPOST new file mode 100644 index 0000000000000000000000000000000000000000..21202ebe0250745b5207317c2223449fed26abb6 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/INMEMORY b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/INMEMORY new file mode 100644 index 0000000000000000000000000000000000000000..e6f43abc84756347739b1030be5688e4e88e82db --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SIMPLE1 b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SIMPLE1 new file mode 100644 index 0000000000000000000000000000000000000000..52c0c93e89f2fba2c38f49627376a652b7a87bf0 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SIMPLE2 b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SIMPLE2 new file mode 100644 index 0000000000000000000000000000000000000000..493c91ee2315ac758556091ae981c817b6896528 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SMTPSRCMBR b/local-test-curl-delta-01/afc-curl/packages/OS400/rpg-examples/SMTPSRCMBR new file mode 100644 index 0000000000000000000000000000000000000000..88f4fd25ca2039eac64e6c0d05697e2ec2f1c293 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/Makefile.am b/local-test-curl-delta-01/afc-curl/packages/vms/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..e869a8978c6b7db34144704f8a6d5c31d8261192 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/backup_gnv_curl_src.com b/local-test-curl-delta-01/afc-curl/packages/vms/backup_gnv_curl_src.com new file mode 100644 index 0000000000000000000000000000000000000000..298f11f80fe2394030e42697bcae74e6d26171e9 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_curl-config_script.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_curl-config_script.com new file mode 100644 index 0000000000000000000000000000000000000000..1667d0745c8801b7182230862d4408a70480e91d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl.com new file mode 100644 index 0000000000000000000000000000000000000000..36e7281135f963f89a879701049d742d8b3d5232 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_pcsi_desc.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_pcsi_desc.com new file mode 100644 index 0000000000000000000000000000000000000000..85674261ce38765972c30c2f99fe0ed0200beaf0 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_pcsi_text.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_pcsi_text.com new file mode 100644 index 0000000000000000000000000000000000000000..8f109c1e7e4e1473596c04a108627d4964ead271 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_release_notes.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_gnv_curl_release_notes.com new file mode 100644 index 0000000000000000000000000000000000000000..0da94454d5be230931a84ec3169a33178927ac9d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/build_libcurl_pc.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_libcurl_pc.com new file mode 100644 index 0000000000000000000000000000000000000000..de7db26958bb8d36fcff689612a1d6a923e5ed57 --- /dev/null +++ b/local-test-curl-delta-01/afc-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_PC_LIBS_PRIVATE@", 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("@LIBCURL_PC_CFLAGS@", 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/local-test-curl-delta-01/afc-curl/packages/vms/build_vms.com b/local-test-curl-delta-01/afc-curl/packages/vms/build_vms.com new file mode 100644 index 0000000000000000000000000000000000000000..d8f89f6ef4366e1d48222a520cfb4a29d3fcb018 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/clean_gnv_curl.com b/local-test-curl-delta-01/afc-curl/packages/vms/clean_gnv_curl.com new file mode 100644 index 0000000000000000000000000000000000000000..1a9a0eb71a6314e948f5b23f8ec5b8dfdb6c1318 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/compare_curl_source.com b/local-test-curl-delta-01/afc-curl/packages/vms/compare_curl_source.com new file mode 100644 index 0000000000000000000000000000000000000000..13ff4667f9311f30851c8953636e0d298289ef73 --- /dev/null +++ b/local-test-curl-delta-01/afc-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. +$! +$! Only files present in the copy directory are listed. +$! +$! Diagnostics are displayed about the 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/local-test-curl-delta-01/afc-curl/packages/vms/config_h.com b/local-test-curl-delta-01/afc-curl/packages/vms/config_h.com new file mode 100644 index 0000000000000000000000000000000000000000..8d231f4c978166d27fb603e7db464fa38abe98bb --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curl_crtl_init.c b/local-test-curl-delta-01/afc-curl/packages/vms/curl_crtl_init.c new file mode 100644 index 0000000000000000000000000000000000000000..a94fb6664b63504814e156d28162bcf7fdb54c1d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/vms/curl_crtl_init.c @@ -0,0 +1,332 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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/local-test-curl-delta-01/afc-curl/packages/vms/curl_gnv_build_steps.txt b/local-test-curl-delta-01/afc-curl/packages/vms/curl_gnv_build_steps.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7ea95219b51b9d20c0f6ac93479a65444531f88 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curl_release_note_start.txt b/local-test-curl-delta-01/afc-curl/packages/vms/curl_release_note_start.txt new file mode 100644 index 0000000000000000000000000000000000000000..62b2836359fa92cdc2c88a2e3f17ab1f0f5a6452 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curl_startup.com b/local-test-curl-delta-01/afc-curl/packages/vms/curl_startup.com new file mode 100644 index 0000000000000000000000000000000000000000..e90bbecbb9d6ddc105e1e85205d21ea599bd7c71 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.h b/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.h new file mode 100644 index 0000000000000000000000000000000000000000..9b5c4c76d14421afdb8d3e9963fd295afcab868e --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.msg b/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.msg new file mode 100644 index 0000000000000000000000000000000000000000..8d428e88b6b22b21a914ccad43ef8b02aaf8b24a --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.sdl b/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg.sdl new file mode 100644 index 0000000000000000000000000000000000000000..db5baad606f0b799cd1b1bf4a4b7b68ff5648e07 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg_vms.h b/local-test-curl-delta-01/afc-curl/packages/vms/curlmsg_vms.h new file mode 100644 index 0000000000000000000000000000000000000000..29a38db493e939855b0fa0c8fa4b24f09a7fd4fe --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/generate_config_vms_h_curl.com b/local-test-curl-delta-01/afc-curl/packages/vms/generate_config_vms_h_curl.com new file mode 100644 index 0000000000000000000000000000000000000000..81ede597ea79b1a0bafc84d71f97bbd2cf48fa9e --- /dev/null +++ b/local-test-curl-delta-01/afc-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 CURL_OS ""ALPHA-HP-VMS""" +$write cvh "#elif defined(__vax)" +$write cvh "#define CURL_OS ""VAX-HP-VMS""" +$write cvh "#elif defined(__ia64)" +$write cvh "#define CURL_OS ""IA64-HP-VMS"" +$write cvh "#else" +$write cvh "#define CURL_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/local-test-curl-delta-01/afc-curl/packages/vms/generate_vax_transfer.com b/local-test-curl-delta-01/afc-curl/packages/vms/generate_vax_transfer.com new file mode 100644 index 0000000000000000000000000000000000000000..3ed49cb24096146f41130d4c196dc7b0f39cf843 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/gnv_conftest.c_first b/local-test-curl-delta-01/afc-curl/packages/vms/gnv_conftest.c_first new file mode 100644 index 0000000000000000000000000000000000000000..317b1abfc75ad9051fa71138a7ccfe44100c6f22 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/gnv_curl_configure.sh b/local-test-curl-delta-01/afc-curl/packages/vms/gnv_curl_configure.sh new file mode 100644 index 0000000000000000000000000000000000000000..21558001ed86f50a97d7542b96ea2bd6140b0e56 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/gnv_libcurl_symbols.opt b/local-test-curl-delta-01/afc-curl/packages/vms/gnv_libcurl_symbols.opt new file mode 100644 index 0000000000000000000000000000000000000000..5bc2a852b93cf6309b5bd268aac9ef94d44d0d95 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/gnv_link_curl.com b/local-test-curl-delta-01/afc-curl/packages/vms/gnv_link_curl.com new file mode 100644 index 0000000000000000000000000000000000000000..2acd49a6ad2a78ec23d651d028190316d5460312 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/vms/gnv_link_curl.com @@ -0,0 +1,852 @@ +$! 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_soc.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/local-test-curl-delta-01/afc-curl/packages/vms/macro32_exactcase.patch b/local-test-curl-delta-01/afc-curl/packages/vms/macro32_exactcase.patch new file mode 100644 index 0000000000000000000000000000000000000000..eda5cac7b771c795682df7d12fb0a6ef3c4304a2 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/make_gnv_curl_install.sh b/local-test-curl-delta-01/afc-curl/packages/vms/make_gnv_curl_install.sh new file mode 100644 index 0000000000000000000000000000000000000000..b85ef0ced245f785c3426e9df922f436ea58c4d4 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/make_pcsi_curl_kit_name.com b/local-test-curl-delta-01/afc-curl/packages/vms/make_pcsi_curl_kit_name.com new file mode 100644 index 0000000000000000000000000000000000000000..956f7c1677980ec366730d65922e547fe52e7e4d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/pcsi_gnv_curl_file_list.txt b/local-test-curl-delta-01/afc-curl/packages/vms/pcsi_gnv_curl_file_list.txt new file mode 100644 index 0000000000000000000000000000000000000000..586f7e767536584b748b625ba7f8e3f8854b7e56 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/pcsi_product_gnv_curl.com b/local-test-curl-delta-01/afc-curl/packages/vms/pcsi_product_gnv_curl.com new file mode 100644 index 0000000000000000000000000000000000000000..83d8fa3b661129434ad8efc2203ad92c0877147d --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/readme b/local-test-curl-delta-01/afc-curl/packages/vms/readme new file mode 100644 index 0000000000000000000000000000000000000000..042a22b8070e1bb795093a309a9c98396c1b311c --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/report_openssl_version.c b/local-test-curl-delta-01/afc-curl/packages/vms/report_openssl_version.c new file mode 100644 index 0000000000000000000000000000000000000000..d08fe713b072ddd62c9f48246ec0d7af3e8cc74b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/packages/vms/report_openssl_version.c @@ -0,0 +1,99 @@ +/* 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) { + ssl_version = (const char * (*)(int))dlsym(libptr, "ssleay_version"); + if(!ssl_version) { + ssl_version = (const char * (*)(int))dlsym(libptr, "SSLEAY_VERSION"); + } + } + + dlclose(libptr); + + if(!ssl_version) { + 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/local-test-curl-delta-01/afc-curl/packages/vms/setup_gnv_curl_build.com b/local-test-curl-delta-01/afc-curl/packages/vms/setup_gnv_curl_build.com new file mode 100644 index 0000000000000000000000000000000000000000..49882463f3c44d57b8d44f7ab96ae349e158d63c --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/stage_curl_install.com b/local-test-curl-delta-01/afc-curl/packages/vms/stage_curl_install.com new file mode 100644 index 0000000000000000000000000000000000000000..10ae17adcb3e4439f2ad2d6c57ece5836a97f24f --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/packages/vms/vms_eco_level.h b/local-test-curl-delta-01/afc-curl/packages/vms/vms_eco_level.h new file mode 100644 index 0000000000000000000000000000000000000000..89f1dfd628aa2e6198f2c61ce460c74492586487 --- /dev/null +++ b/local-test-curl-delta-01/afc-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/local-test-curl-delta-01/afc-curl/tests/certs/.gitignore b/local-test-curl-delta-01/afc-curl/tests/certs/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f549fdf14f09f32f72efee9121fa011678e57bad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/.gitignore @@ -0,0 +1,10 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl +EdelCurlRoot-*-ca.cacert +EdelCurlRoot-ca.cnt +EdelCurlRoot-ca.cnt.old +EdelCurlRoot-ca.db +EdelCurlRoot-ca.db.attr +EdelCurlRoot-ca.db.attr.old +EdelCurlRoot-ca.db.old diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/certs/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f9011b13f60ec84140d35f380e83bde2fde7f25f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/CMakeLists.txt @@ -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 +# +########################################################################### +find_program(SH_EXECUTABLE "sh") +mark_as_advanced(SH_EXECUTABLE) +if(SH_EXECUTABLE) + # Get 'CERTCONFIGS', 'GENERATEDCERTS', 'SRPFILES' variables + transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + + add_custom_target(clean-certs + COMMAND ${CMAKE_COMMAND} -E remove ${GENERATEDCERTS} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) + + add_custom_target(build-certs + DEPENDS ${CERTCONFIGS} ${SRPFILES} + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genroot.sh" EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" Server-localhost EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" Server-localhost.nn EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" Server-localhost0h EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" Server-localhost-firstSAN EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" Server-localhost-lastSAN EdelCurlRoot + COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/genserv.sh" stunnel EdelCurlRoot + COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/stunnel-sv.pem" "${CMAKE_CURRENT_SOURCE_DIR}/../stunnel.pem" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) +endif() diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cacert b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cacert new file mode 100644 index 0000000000000000000000000000000000000000..4e191f5e60c55f8550b968ba68e7a4d9acbbf1ec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cacert @@ -0,0 +1,95 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980969522 (0xf3475512a32) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:36 2022 GMT + Not After : May 28 12:21:36 2039 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:a1:d8:60:15:d1:5b:09:3b:d1:4e:79:40:0a:03: + 81:07:60:ba:6b:03:f4:87:4e:1e:e9:77:b1:ea:83: + 66:56:c4:6c:19:5e:cf:64:23:44:03:f5:d0:27:e1: + 1d:a5:05:dd:a5:f2:c1:9a:28:e2:31:66:a2:7b:e0: + 3b:bb:f3:b4:06:b4:43:97:7b:80:3c:96:1b:ed:85: + 7c:8b:2e:0f:62:b9:53:69:3d:2b:19:af:16:d3:e2: + a9:d3:2d:f2:ec:b1:31:76:2d:d9:78:67:91:ce:16: + 52:e3:68:34:f1:bc:f0:5e:99:bf:28:cf:91:88:31: + a6:48:cc:fb:84:a1:87:85:8b:08:18:eb:39:e9:34: + ee:1b:3a:a3:bd:2a:77:63:50:c8:88:6b:f1:d3:c4: + b7:25:db:7f:eb:b9:84:73:a8:86:8a:69:7d:40:5a: + c3:24:81:10:8d:97:ae:ce:45:eb:5d:fb:14:31:5b: + a1:c2:d1:aa:2f:44:a0:42:28:38:16:c7:42:1e:dd: + db:0f:a9:d9:70:25:cc:da:be:e9:8c:8c:84:48:a3: + ab:af:20:7a:7e:b3:09:a9:05:0d:ce:f8:9b:c2:77: + e8:82:f8:6a:56:21:db:92:a7:0a:3c:f1:0c:a0:d4: + 9c:8c:c0:62:2b:62:bc:5e:c4:ba:5e:3a:fc:1a:05: + 49:ef + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: critical + CA:TRUE + X509v3 Key Usage: critical + Certificate Sign, CRL Sign + X509v3 Subject Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 86:19:bd:3d:12:4f:6b:8c:8e:1b:72:db:8f:9b:67:68:96:f8: + f4:ad:d9:a0:b5:48:0e:19:f6:34:09:92:a5:b8:ab:70:c6:6b: + 44:be:f7:fd:a4:75:ad:16:c4:ad:54:aa:c4:36:e6:86:87:84: + 0d:d9:1f:ea:b5:95:3a:69:60:02:2f:5c:a2:a3:1d:c9:28:f6: + 78:22:cd:e3:1d:47:37:a0:a0:a4:8a:3b:da:50:a9:12:e0:e4: + e7:1f:b6:bc:7e:e8:b6:a1:b7:99:9f:98:2c:c1:70:db:32:ea: + 82:45:ff:71:ea:36:34:65:bd:ad:cd:c5:2b:a2:a1:6b:2e:a3: + 30:b2:95:ea:77:a9:17:cf:bf:e4:df:4f:ef:6d:72:d0:a1:95: + c6:ef:e5:b8:70:0f:d2:82:b3:a7:54:4b:f7:2d:b9:2f:dc:37: + ff:f7:4d:26:b4:4b:6a:46:a3:f9:2c:ad:58:8c:96:e8:e6:a4: + aa:d0:c1:2d:35:db:b5:2f:ac:34:40:e3:7f:da:f7:34:f8:a2: + fd:6f:61:46:69:f0:24:20:32:f3:ad:e2:72:27:1a:58:a3:aa: + 77:4e:fa:06:5e:34:40:d3:50:39:66:29:f6:a6:f5:40:3a:af: + 97:23:19:cf:58:27:c9:8f:c4:b3:58:9e:87:78:2f:a7:24:9e: + 3e:5d:d1:52 +-----BEGIN CERTIFICATE----- +MIIENDCCAxygAwIBAgIGDzR1USoyMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzZaFw0zOTA1MjgxMjIxMzZaMGgxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAKHYYBXRWwk70U55QAoDgQdgumsD9IdO +Hul3seqDZlbEbBlez2QjRAP10CfhHaUF3aXywZoo4jFmonvgO7vztAa0Q5d7gDyW +G+2FfIsuD2K5U2k9KxmvFtPiqdMt8uyxMXYt2Xhnkc4WUuNoNPG88F6ZvyjPkYgx +pkjM+4Shh4WLCBjrOek07hs6o70qd2NQyIhr8dPEtyXbf+u5hHOohoppfUBawySB +EI2Xrs5F6137FDFbocLRqi9EoEIoOBbHQh7d2w+p2XAlzNq+6YyMhEijq68gen6z +CakFDc74m8J36IL4alYh25KnCjzxDKDUnIzAYitivF7Eul46/BoFSe8CAwEAAaOB +4zCB4DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU +h8uxMy7BZ35x4+UrTE2ks27SW6kwHwYDVR0jBBgwFoAUh8uxMy7BZ35x4+UrTE2k +s27SW6kwQwYIKwYBBQUHAQEENzA1MDMGCCsGAQUFBzAChidodHRwOi8vdGVzdC5j +dXJsLnNlL2NhL0VkZWxDdXJsUm9vdC5jZXIwOAYDVR0fBDEwLzAtoCugKYYnaHR0 +cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY3JsMA0GCSqGSIb3DQEB +CwUAA4IBAQCGGb09Ek9rjI4bctuPm2dolvj0rdmgtUgOGfY0CZKluKtwxmtEvvf9 +pHWtFsStVKrENuaGh4QN2R/qtZU6aWACL1yiox3JKPZ4Is3jHUc3oKCkijvaUKkS +4OTnH7a8fui2obeZn5gswXDbMuqCRf9x6jY0Zb2tzcUroqFrLqMwspXqd6kXz7/k +30/vbXLQoZXG7+W4cA/SgrOnVEv3Lbkv3Df/900mtEtqRqP5LK1YjJbo5qSq0MEt +Ndu1L6w0QON/2vc0+KL9b2FGafAkIDLzreJyJxpYo6p3TvoGXjRA01A5Zin2pvVA +Oq+XIxnPWCfJj8SzWJ6HeC+nJJ4+XdFS +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cnf b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cnf new file mode 100644 index 0000000000000000000000000000000000000000..b8c630b5de1f0c141de73c94ed4b9527042a72c5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.cnf @@ -0,0 +1,11 @@ +[ ca ] +default_ca = EdelCurlRoot + +[ EdelCurlRoot ] +database = EdelCurlRoot-ca.db +certificate = EdelCurlRoot-ca.crt +private_key = EdelCurlRoot-ca.key +crlnumber = EdelCurlRoot-ca.cnt +default_md = sha256 +default_days = 365 +default_crl_days = 30 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.crt b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.crt new file mode 100644 index 0000000000000000000000000000000000000000..4e191f5e60c55f8550b968ba68e7a4d9acbbf1ec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.crt @@ -0,0 +1,95 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980969522 (0xf3475512a32) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:36 2022 GMT + Not After : May 28 12:21:36 2039 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:a1:d8:60:15:d1:5b:09:3b:d1:4e:79:40:0a:03: + 81:07:60:ba:6b:03:f4:87:4e:1e:e9:77:b1:ea:83: + 66:56:c4:6c:19:5e:cf:64:23:44:03:f5:d0:27:e1: + 1d:a5:05:dd:a5:f2:c1:9a:28:e2:31:66:a2:7b:e0: + 3b:bb:f3:b4:06:b4:43:97:7b:80:3c:96:1b:ed:85: + 7c:8b:2e:0f:62:b9:53:69:3d:2b:19:af:16:d3:e2: + a9:d3:2d:f2:ec:b1:31:76:2d:d9:78:67:91:ce:16: + 52:e3:68:34:f1:bc:f0:5e:99:bf:28:cf:91:88:31: + a6:48:cc:fb:84:a1:87:85:8b:08:18:eb:39:e9:34: + ee:1b:3a:a3:bd:2a:77:63:50:c8:88:6b:f1:d3:c4: + b7:25:db:7f:eb:b9:84:73:a8:86:8a:69:7d:40:5a: + c3:24:81:10:8d:97:ae:ce:45:eb:5d:fb:14:31:5b: + a1:c2:d1:aa:2f:44:a0:42:28:38:16:c7:42:1e:dd: + db:0f:a9:d9:70:25:cc:da:be:e9:8c:8c:84:48:a3: + ab:af:20:7a:7e:b3:09:a9:05:0d:ce:f8:9b:c2:77: + e8:82:f8:6a:56:21:db:92:a7:0a:3c:f1:0c:a0:d4: + 9c:8c:c0:62:2b:62:bc:5e:c4:ba:5e:3a:fc:1a:05: + 49:ef + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: critical + CA:TRUE + X509v3 Key Usage: critical + Certificate Sign, CRL Sign + X509v3 Subject Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 86:19:bd:3d:12:4f:6b:8c:8e:1b:72:db:8f:9b:67:68:96:f8: + f4:ad:d9:a0:b5:48:0e:19:f6:34:09:92:a5:b8:ab:70:c6:6b: + 44:be:f7:fd:a4:75:ad:16:c4:ad:54:aa:c4:36:e6:86:87:84: + 0d:d9:1f:ea:b5:95:3a:69:60:02:2f:5c:a2:a3:1d:c9:28:f6: + 78:22:cd:e3:1d:47:37:a0:a0:a4:8a:3b:da:50:a9:12:e0:e4: + e7:1f:b6:bc:7e:e8:b6:a1:b7:99:9f:98:2c:c1:70:db:32:ea: + 82:45:ff:71:ea:36:34:65:bd:ad:cd:c5:2b:a2:a1:6b:2e:a3: + 30:b2:95:ea:77:a9:17:cf:bf:e4:df:4f:ef:6d:72:d0:a1:95: + c6:ef:e5:b8:70:0f:d2:82:b3:a7:54:4b:f7:2d:b9:2f:dc:37: + ff:f7:4d:26:b4:4b:6a:46:a3:f9:2c:ad:58:8c:96:e8:e6:a4: + aa:d0:c1:2d:35:db:b5:2f:ac:34:40:e3:7f:da:f7:34:f8:a2: + fd:6f:61:46:69:f0:24:20:32:f3:ad:e2:72:27:1a:58:a3:aa: + 77:4e:fa:06:5e:34:40:d3:50:39:66:29:f6:a6:f5:40:3a:af: + 97:23:19:cf:58:27:c9:8f:c4:b3:58:9e:87:78:2f:a7:24:9e: + 3e:5d:d1:52 +-----BEGIN CERTIFICATE----- +MIIENDCCAxygAwIBAgIGDzR1USoyMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzZaFw0zOTA1MjgxMjIxMzZaMGgxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAKHYYBXRWwk70U55QAoDgQdgumsD9IdO +Hul3seqDZlbEbBlez2QjRAP10CfhHaUF3aXywZoo4jFmonvgO7vztAa0Q5d7gDyW +G+2FfIsuD2K5U2k9KxmvFtPiqdMt8uyxMXYt2Xhnkc4WUuNoNPG88F6ZvyjPkYgx +pkjM+4Shh4WLCBjrOek07hs6o70qd2NQyIhr8dPEtyXbf+u5hHOohoppfUBawySB +EI2Xrs5F6137FDFbocLRqi9EoEIoOBbHQh7d2w+p2XAlzNq+6YyMhEijq68gen6z +CakFDc74m8J36IL4alYh25KnCjzxDKDUnIzAYitivF7Eul46/BoFSe8CAwEAAaOB +4zCB4DAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU +h8uxMy7BZ35x4+UrTE2ks27SW6kwHwYDVR0jBBgwFoAUh8uxMy7BZ35x4+UrTE2k +s27SW6kwQwYIKwYBBQUHAQEENzA1MDMGCCsGAQUFBzAChidodHRwOi8vdGVzdC5j +dXJsLnNlL2NhL0VkZWxDdXJsUm9vdC5jZXIwOAYDVR0fBDEwLzAtoCugKYYnaHR0 +cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY3JsMA0GCSqGSIb3DQEB +CwUAA4IBAQCGGb09Ek9rjI4bctuPm2dolvj0rdmgtUgOGfY0CZKluKtwxmtEvvf9 +pHWtFsStVKrENuaGh4QN2R/qtZU6aWACL1yiox3JKPZ4Is3jHUc3oKCkijvaUKkS +4OTnH7a8fui2obeZn5gswXDbMuqCRf9x6jY0Zb2tzcUroqFrLqMwspXqd6kXz7/k +30/vbXLQoZXG7+W4cA/SgrOnVEv3Lbkv3Df/900mtEtqRqP5LK1YjJbo5qSq0MEt +Ndu1L6w0QON/2vc0+KL9b2FGafAkIDLzreJyJxpYo6p3TvoGXjRA01A5Zin2pvVA +Oq+XIxnPWCfJj8SzWJ6HeC+nJJ4+XdFS +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.csr b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.csr new file mode 100644 index 0000000000000000000000000000000000000000..2eeb6f055fe6866065cf85c42a729f626cfe634f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.csr @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICrTCCAZUCAQAwaDELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxJjAkBgNVBAMMHU5vcnRoZXJu +IE5vd2hlcmUgVHJ1c3QgQW5jaG9yMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAodhgFdFbCTvRTnlACgOBB2C6awP0h04e6Xex6oNmVsRsGV7PZCNEA/XQ +J+EdpQXdpfLBmijiMWaie+A7u/O0BrRDl3uAPJYb7YV8iy4PYrlTaT0rGa8W0+Kp +0y3y7LExdi3ZeGeRzhZS42g08bzwXpm/KM+RiDGmSMz7hKGHhYsIGOs56TTuGzqj +vSp3Y1DIiGvx08S3Jdt/67mEc6iGiml9QFrDJIEQjZeuzkXrXfsUMVuhwtGqL0Sg +Qig4FsdCHt3bD6nZcCXM2r7pjIyESKOrryB6frMJqQUNzvibwnfogvhqViHbkqcK +PPEMoNScjMBiK2K8XsS6Xjr8GgVJ7wIDAQABoAAwDQYJKoZIhvcNAQELBQADggEB +AGRzOAmRFC2HX9tV94v7PxAPLY8LC5IsCdk2E07gQ76kWU8B0qd3Okx970O6d9Iw +jy27At8CIFmCwdiNpOfLv1uqtbBgitxRX6FfciN5Lu0D1wxICc2gX7tDgqLhrT8E +fp8q7/F//UPT04l5B6b+2h210Rkzjs/EmjQt2cFGjQpGSy8nb1ey3/W91NAej7Aq +Hrp3/64hC+0QZMpgYQpYx65LYOST+U8lnDbrlcRUQqkUmGidwbYqGQMv+Tk5TKjL +zMOjuu/I6stoGSJGJvhrfToZazG0u9tT+sXQdbi3emXVP1tMVpkhOYvKaaCno9QR +RREL1l6yq15NUoT030u7pvs= +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.der b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.der new file mode 100644 index 0000000000000000000000000000000000000000..9a4e2ef89c3a94a533bfd0991cc09fafd6885dc4 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.key b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.key new file mode 100644 index 0000000000000000000000000000000000000000..624ab3f54915e233b8fa94329ffdbcfbfbd73c36 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCh2GAV0VsJO9FO +eUAKA4EHYLprA/SHTh7pd7Hqg2ZWxGwZXs9kI0QD9dAn4R2lBd2l8sGaKOIxZqJ7 +4Du787QGtEOXe4A8lhvthXyLLg9iuVNpPSsZrxbT4qnTLfLssTF2Ldl4Z5HOFlLj +aDTxvPBemb8oz5GIMaZIzPuEoYeFiwgY6znpNO4bOqO9KndjUMiIa/HTxLcl23/r +uYRzqIaKaX1AWsMkgRCNl67ORetd+xQxW6HC0aovRKBCKDgWx0Ie3dsPqdlwJcza +vumMjIRIo6uvIHp+swmpBQ3O+JvCd+iC+GpWIduSpwo88Qyg1JyMwGIrYrxexLpe +OvwaBUnvAgMBAAECggEADFrjQucfhv3tBYuWCu2njPOiZ4b+xNF+5J3BlECBsIAA +LJOjS2axy4eZY2H5DF79Q6zbgLQ8SD8oikJc7QU2qgha3JaN/JINAb3d+xYCEKxL +JM6JmsVV/cjg5AEu+UixmO75Ggr2A4CKxVdwK0AcLWyZPjlSR85aflY/oSlfmh8a +txULdID0fH+/tIVQE/xlS9M8xfHxqQQyoBsWkwPPcxhgPRgPpTxo/a12iZk2z+lV +F/1TZxyb0MWRktVgHQwhmXSnEguosspjk6fqDXwM14WJLQA1XdFdblI3aiHmlc5h +qanreSsaUgYsV1WvVxh1qfoljm6pUzoYvOChdz62SQKBgQDiavOlubV+kgFU4he+ +LzdaZJUlq6JO4dbbcgE4lZBnoJp2Ga5V1OvBnBcrdtiHO46V2Durq66YHa/tZfTN +6RlA6GyPVLb6qlwbCYUnpSfuwIVJx7Zty7FrnOn9oRlwLpQQMG4AOsS3E+JY1vQZ +9+8htuT9OprjY2Mx6wLm2EuZ3QKBgQC2/aZll+nRMerAsZLsTm1idkvxztvDPyoQ +yQwGlDy79OvezjzXEAczGk/XDSRnGIptZQacxw5z/Lw8IHaaTp7GPFBrD7Lr84dc +QopdLqqeQJ2n7WGjmJ3gLJCp7NHHP+xDkipc2Xq+nFGlS+PxVzB0hOq3wQdPV54e +h+x9CNDkOwKBgA3TfiFmn8Ck5dPrIowIkhbBAaKVQooSnG42HgD4kSLi2cvQcabo +I6VlBL0wurQ3XNOlqq8nArhjR7T1fud8DoC6MLbn82yHLqyv/iOXoEKiGwGQYoF9 +6M2rfVZxmf4RuhTrACyfahfL7QyDw9A6Ja4nXwBfrcmo7gvEUB8MokE5AoGBAKbY +sZ5SG/wE4oGdp1PU0oGDUQ2CSfhFIGq7lT5ubM4HrASz0N9amuXqaL+xGO7zfkvu +YFAUY0Y4O70q8FkTtEsVdVGYt8/RdSsW9KevxBuU2OrjUzJiFhjvKVv2NPPSge6+ +V+fe177yMrNfdc94axLimky/MJYUUnSOBH+gyS4/AoGBALJt7WqFnb3iazOgVUDd +ZGOJUuBnlgS6MK/YxP+8csq+MPnGVVGruXx72hzWe3bJ8QM16QvHUPC9RNgnclXB +Ekx45SNSG1g//rxHwCJAgcTlnhiTZQ21Fn3V2EckjOa/Z4udk/7PxFRto1beNznK +nW2eB0xvsK+qq5yc3TQClWgc +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.prm b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.prm new file mode 100644 index 0000000000000000000000000000000000000000..cf1b30d23902cbd5efca1090278f124f93642d41 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/EdelCurlRoot-ca.prm @@ -0,0 +1,33 @@ +extensions = x509v3 + +[ x509v3 ] +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign,cRLSign +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 2048 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = Northern Nowhere Trust Anchor diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..a2b45885afd8a063cda499dffcc91dcaf620e5c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.am @@ -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 +# +########################################################################### +AUTOMAKE_OPTIONS = foreign + +SUBDIRS = scripts + +include Makefile.inc + +EXTRA_DIST = $(CERTCONFIGS) $(GENERATEDCERTS) $(SRPFILES) CMakeLists.txt + +# Rebuild the certificates + +clean-certs: + cd $(srcdir); rm -f $(GENERATEDCERTS) + +build-certs: $(srcdir)/EdelCurlRoot-ca.cacert $(srcdir)/Server-localhost-sv.pem \ + $(srcdir)/Server-localhost.nn-sv.pem $(srcdir)/Server-localhost0h-sv.pem \ + $(srcdir)/Server-localhost-firstSAN-sv.pem $(srcdir)/Server-localhost-lastSAN-sv.pem \ + $(srcdir)/stunnel-sv.pem $(srcdir)/../stunnel.pem + +$(srcdir)/EdelCurlRoot-ca.cacert: + cd $(srcdir); scripts/genroot.sh EdelCurlRoot + +$(srcdir)/Server-localhost-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh Server-localhost EdelCurlRoot + +$(srcdir)/Server-localhost.nn-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh Server-localhost.nn EdelCurlRoot + +$(srcdir)/Server-localhost0h-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh Server-localhost0h EdelCurlRoot + +$(srcdir)/Server-localhost-firstSAN-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh Server-localhost-firstSAN EdelCurlRoot + +$(srcdir)/Server-localhost-lastSAN-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh Server-localhost-lastSAN EdelCurlRoot + +$(srcdir)/stunnel-sv.pem: $(srcdir)/EdelCurlRoot-ca.cacert + cd $(srcdir); scripts/genserv.sh stunnel EdelCurlRoot + + $(srcdir)/../stunnel.pem: $(srcdir)/stunnel-sv.pem + cp $< $@ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.inc b/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..032baec2492202c693e21c6144c1b4b3661b74ff --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Makefile.inc @@ -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 +# +########################################################################### +CERTCONFIGS = \ + EdelCurlRoot-ca.prm \ + EdelCurlRoot-ca.cnf \ + Server-localhost-sv.prm \ + Server-localhost.nn-sv.prm \ + Server-localhost0h-sv.prm \ + Server-localhost-firstSAN-sv.prm \ + Server-localhost-lastSAN-sv.prm \ + stunnel-sv.prm + +GENERATEDCERTS = \ + EdelCurlRoot-ca.cacert \ + EdelCurlRoot-ca.crt \ + EdelCurlRoot-ca.csr \ + EdelCurlRoot-ca.der \ + EdelCurlRoot-ca.key \ + Server-localhost-sv.crl \ + Server-localhost-sv.crt \ + Server-localhost-sv.csr \ + Server-localhost-sv.der \ + Server-localhost-sv.dhp \ + Server-localhost-sv.key \ + Server-localhost-sv.pem \ + Server-localhost-sv.pub.der \ + Server-localhost-sv.pub.pem \ + Server-localhost-sv.pubkey-pinned \ + Server-localhost.nn-sv.crl \ + Server-localhost.nn-sv.crt \ + Server-localhost.nn-sv.csr \ + Server-localhost.nn-sv.der \ + Server-localhost.nn-sv.dhp \ + Server-localhost.nn-sv.key \ + Server-localhost.nn-sv.pem \ + Server-localhost.nn-sv.pub.der \ + Server-localhost.nn-sv.pub.pem \ + Server-localhost.nn-sv.pubkey-pinned \ + Server-localhost0h-sv.crl \ + Server-localhost0h-sv.crt \ + Server-localhost0h-sv.csr \ + Server-localhost0h-sv.der \ + Server-localhost0h-sv.dhp \ + Server-localhost0h-sv.key \ + Server-localhost0h-sv.pem \ + Server-localhost0h-sv.pub.der \ + Server-localhost0h-sv.pub.pem \ + Server-localhost0h-sv.pubkey-pinned \ + Server-localhost-firstSAN-sv.crl \ + Server-localhost-firstSAN-sv.crt \ + Server-localhost-firstSAN-sv.csr \ + Server-localhost-firstSAN-sv.der \ + Server-localhost-firstSAN-sv.dhp \ + Server-localhost-firstSAN-sv.key \ + Server-localhost-firstSAN-sv.pem \ + Server-localhost-firstSAN-sv.pub.der \ + Server-localhost-firstSAN-sv.pub.pem \ + Server-localhost-firstSAN-sv.pubkey-pinned \ + Server-localhost-lastSAN-sv.crl \ + Server-localhost-lastSAN-sv.crt \ + Server-localhost-lastSAN-sv.csr \ + Server-localhost-lastSAN-sv.der \ + Server-localhost-lastSAN-sv.dhp \ + Server-localhost-lastSAN-sv.key \ + Server-localhost-lastSAN-sv.pem \ + Server-localhost-lastSAN-sv.pub.der \ + Server-localhost-lastSAN-sv.pub.pem \ + Server-localhost-lastSAN-sv.pubkey-pinned \ + stunnel-sv.crl \ + stunnel-sv.crt \ + stunnel-sv.csr \ + stunnel-sv.der \ + stunnel-sv.dhp \ + stunnel-sv.key \ + stunnel-sv.pem \ + stunnel-sv.der \ + stunnel-sv.pub.der \ + stunnel-sv.pub.pem \ + stunnel-sv.pubkey-pinned + +SRPFILES = \ + srp-verifier-conf \ + srp-verifier-db diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..1944a4a03567fb92c5fc565180d6dc697d994e74 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crl @@ -0,0 +1,14 @@ +-----BEGIN X509 CRL----- +MIICKDCCARACAQEwDQYJKoZIhvcNAQELBQAwaDELMAkGA1UEBhMCTk4xMTAvBgNV +BAoMKEVkZWwgQ3VybCBBcmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxJjAk +BgNVBAMMHU5vcnRoZXJuIE5vd2hlcmUgVHJ1c3QgQW5jaG9yFw0yMjEyMjMxMjIx +MzhaFw0yMzAxMjIxMjIxMzhaMGQwFwIGDzR1USo8Fw0yMjEyMjMxMjIxMzZaMBcC +Bg80dVFRYRcNMjIxMjIzMTIyMTM3WjAXAgYPNHVRUXUXDTIyMTIyMzEyMjEzN1ow +FwIGDzR1UVGJFw0yMjEyMjMxMjIxMzhaoA4wDDAKBgNVHRQEAwIBATANBgkqhkiG +9w0BAQsFAAOCAQEANTZwNcoHukPV2Wf9ykTUELJtpH3OCzinsOBm/h0LRWp06NAm +0YJcStMclU7syd6izwPZPI9HT5tPQKHaxJDa8rZH4XRE8bSIAHQacj+22mcLV1EB +5TdRRRHA6UvhebO8f6cf32SQIJ821LDW1FeFj3VvJqRfM6P9E0BNiCGvxJCFAE4K ++/uN5v/x12kKDl3+7wqh1q36qM99QRbNbWh+3ndxG5Gm8Zl2MWLstMLVDI0SjipZ +mnMpQ0py5IdiStCY8iYiTk48QUqQ9Jki+bmjNwG05HQUVdUiwwtJhlYhyTpNIBE8 +MB+39cFiwpJ7YbFC8Quhppg/isJ2ZaBmTg7zpA== +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..6eadce2caa031420713551fe75d4035983655662 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.crt @@ -0,0 +1,100 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979593 (0xf3475515189) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:38 2022 GMT + Not After : Mar 11 12:21:38 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:aa:14:6e:3d:82:1c:28:cd:8f:80:af:50:ed:17: + 97:6d:e6:a8:61:3e:ac:a8:ac:13:ce:99:eb:29:2c: + 49:73:f9:12:40:35:c4:79:84:0d:9e:b0:28:c4:9f: + 64:e3:c1:6d:2d:71:11:5d:4b:14:61:20:4b:18:a1: + cb:21:6d:9e:78:1b:11:d2:83:1c:89:75:d5:77:3d: + ca:c8:83:17:74:5c:44:b2:1f:ac:f3:8b:c5:6a:34: + 7a:86:ab:08:f5:3d:79:72:ab:36:48:23:de:2b:ba: + 4c:e0:ef:18:91:64:97:c6:09:92:ed:26:d2:a7:0d: + a2:21:1f:34:06:c7:99:17:b2:50:96:b6:0f:9b:ed: + 45:ff:be:81:47:29:e5:f3:49:db:21:65:44:de:8d: + 2b:12:07:12:0d:59:cc:bb:4d:1a:33:c0:7a:7e:e5: + 5b:06:50:62:b2:7f:8f:5c:6d:91:cb:6a:5c:e3:e4: + ae:b9:ab:0d:36:ef:0a:d5:6d:07:5b:25:58:20:0d: + d2:4b:25:0f:e8:11:f5:ce:19:b1:29:c6:d3:49:d7: + f2:4a:78:52:d2:c5:fc:4f:11:63:f1:4e:77:ae:0a: + 87:65:45:49:b6:ac:21:1b:c8:94:c1:0c:e7:13:e6: + be:f3:ff:a2:bd:68:4c:c6:34:04:2b:fc:ff:c3:e8: + 23:57 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost, DNS:localhost1, DNS:localhost2 + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + DB:7A:18:5E:83:AC:D3:48:C9:00:99:3C:EB:BF:A6:21:F0:39:80:CC + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 75:0d:9b:eb:8a:df:ca:a7:7c:9d:9e:6a:eb:30:10:24:12:1b: + 81:f6:cd:b0:a0:f8:de:10:f1:6e:b8:57:3a:3a:b0:a4:8c:1d: + c1:8f:95:22:e3:1f:8b:3a:21:89:e5:96:08:3d:83:33:37:66: + 48:03:f7:98:dd:2f:6d:09:7a:82:26:c1:eb:16:b9:5e:5b:f5: + 67:4c:a0:e7:93:e7:2e:d4:53:b8:77:5f:5e:6a:3a:d9:06:19: + ca:85:ca:7c:09:61:0d:08:8b:6a:b3:e2:03:8c:ea:b1:55:b2: + 30:9b:aa:66:0e:6e:d7:0a:0a:22:ca:6d:8d:d8:53:a8:bc:df: + 13:29:d3:b6:1e:9f:3e:a1:8d:f3:8c:48:bf:71:e9:4e:f4:76: + ed:77:97:3f:59:27:ca:bb:5b:7c:58:23:82:e7:b5:2d:39:02: + 9f:52:07:2f:7b:17:6d:c8:af:90:f5:ed:81:99:a9:cf:80:fb: + eb:ba:9c:bc:9a:df:c5:04:78:2c:73:73:bf:95:23:cf:fb:c9: + 3e:fa:5b:ee:02:39:8e:09:78:ca:89:08:fd:83:77:37:72:01: + 6c:dd:fb:eb:70:20:df:87:28:b3:0f:a0:c5:b3:70:fb:5d:38: + 72:23:46:7f:f5:d8:fc:b6:67:72:82:e5:ce:29:f5:b5:34:db: + a3:d5:fe:20 +-----BEGIN CERTIFICATE----- +MIIEXzCCA0egAwIBAgIGDzR1UVGJMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzhaFw0zMTAzMTExMjIxMzhaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCqFG49ghwozY+Ar1DtF5dt5qhhPqyorBPOmespLElz+RJANcR5hA2e +sCjEn2TjwW0tcRFdSxRhIEsYocshbZ54GxHSgxyJddV3PcrIgxd0XESyH6zzi8Vq +NHqGqwj1PXlyqzZII94rukzg7xiRZJfGCZLtJtKnDaIhHzQGx5kXslCWtg+b7UX/ +voFHKeXzSdshZUTejSsSBxINWcy7TRozwHp+5VsGUGKyf49cbZHLalzj5K65qw02 +7wrVbQdbJVggDdJLJQ/oEfXOGbEpxtNJ1/JKeFLSxfxPEWPxTneuCodlRUm2rCEb +yJTBDOcT5r7z/6K9aEzGNAQr/P/D6CNXAgMBAAGjggEeMIIBGjAsBgNVHREEJTAj +gglsb2NhbGhvc3SCCmxvY2FsaG9zdDGCCmxvY2FsaG9zdDIwCwYDVR0PBAQDAgOo +MBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1UdDgQWBBTbehheg6zTSMkAmTzrv6Yh +8DmAzDAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAA +MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5z +ZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90 +ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOC +AQEAdQ2b64rfyqd8nZ5q6zAQJBIbgfbNsKD43hDxbrhXOjqwpIwdwY+VIuMfizoh +ieWWCD2DMzdmSAP3mN0vbQl6gibB6xa5Xlv1Z0yg55PnLtRTuHdfXmo62QYZyoXK +fAlhDQiLarPiA4zqsVWyMJuqZg5u1woKIsptjdhTqLzfEynTth6fPqGN84xIv3Hp +TvR27XeXP1knyrtbfFgjgue1LTkCn1IHL3sXbcivkPXtgZmpz4D767qcvJrfxQR4 +LHNzv5Ujz/vJPvpb7gI5jgl4yokI/YN3N3IBbN3763Ag34cosw+gxbNw+104ciNG +f/XY/LZncoLlzin1tTTbo9X+IA== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..031639c5ae97342cbb1cc328f1b64ad0322c170a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxFTATBgNVBAMMDGxvY2FsaG9z +dC5ubjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKoUbj2CHCjNj4Cv +UO0Xl23mqGE+rKisE86Z6yksSXP5EkA1xHmEDZ6wKMSfZOPBbS1xEV1LFGEgSxih +yyFtnngbEdKDHIl11Xc9ysiDF3RcRLIfrPOLxWo0eoarCPU9eXKrNkgj3iu6TODv +GJFkl8YJku0m0qcNoiEfNAbHmReyUJa2D5vtRf++gUcp5fNJ2yFlRN6NKxIHEg1Z +zLtNGjPAen7lWwZQYrJ/j1xtkctqXOPkrrmrDTbvCtVtB1slWCAN0kslD+gR9c4Z +sSnG00nX8kp4UtLF/E8RY/FOd64Kh2VFSbasIRvIlMEM5xPmvvP/or1oTMY0BCv8 +/8PoI1cCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQBRfTSEtMHj/52TYk5kUHlY +gTBoePcTVfRCBRfqlGGDAokBrvXq/dFU+5Z/CyulXWnqPji+qw6GDG8KPX0oA6wj +4Yi2z0Dy4BYaRO4PWTGPZ6zsSXAtv0CVtf995O8Ko8axhYQhjDb54G8oMOr5XOHz +GV4LolrlsgxNM0m/KJ2FPVnnfN78qbRO8DpqjFwDOS+ZCIHh+59X34Jyi1HCse+Y +XJ4/YIV5Aw5rGabRproxESwV01Eq4HsXEKP9TtdNDFMkrObWisb7g2M40i4QTR9/ +BNCt3d5vcnAxi2rf+CEvHQDGROZ0tTOZ20HowBA4ahMbYsfC9U+pFkq08auaoe6n +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..2c17c0f935029468de10b222b2959c2409757cc9 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..0b6bbaa9052f4aaf30423d51720a15db7b5aac00 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqFG49ghwozY+A +r1DtF5dt5qhhPqyorBPOmespLElz+RJANcR5hA2esCjEn2TjwW0tcRFdSxRhIEsY +ocshbZ54GxHSgxyJddV3PcrIgxd0XESyH6zzi8VqNHqGqwj1PXlyqzZII94rukzg +7xiRZJfGCZLtJtKnDaIhHzQGx5kXslCWtg+b7UX/voFHKeXzSdshZUTejSsSBxIN +Wcy7TRozwHp+5VsGUGKyf49cbZHLalzj5K65qw027wrVbQdbJVggDdJLJQ/oEfXO +GbEpxtNJ1/JKeFLSxfxPEWPxTneuCodlRUm2rCEbyJTBDOcT5r7z/6K9aEzGNAQr +/P/D6CNXAgMBAAECggEABTfYrgT/xHXbOkOmuvieLp5ODH7joPLldvX3+FpqxxSL +EhdB7qNaaVYftYLrkaVNvKS/3BDBfk+nwr+Qmy4X8wH5m0sdpSqWfDDLAPAss53y +zi8ZLcBJ6v3TMa5AQolfBPPFzrfzAA8GNao3IuSLoK5BqMFMmhjr+8kGS8CrGn0c +PaMd+zNUaCo0ml7dsO+14qjeLSSzKaYl7mOHeEq02B3UDa5twvkyVQiCHV7CThF0 +0oxJ+DOFzBefPB8pIurh6X0WwaDumEQVnEaaaOWEa1IayscTSrkLcNwkZC55/23M +k9qaR/qGnfUSpu34NTlyy7ifbJOeHp+rZDEFKgBoWQKBgQDalQKzRAjpXn9sSBQS +aTvP293zxP5ueJnv0TmViUfadDDPZ/VX6W0n7mGuOmNKaWnjM1rvMGpqo6e65eir +obuUe7GfJAqexUK6VDFOIzFSBqWpquyjjHWa6C4zgL+BVDGItIhQI/6wYsQ0HgLV +R/n3nqCcYAc/a131GDGdfshbwwKBgQDHMePvhNBZo3p1vUG5l3HiTQRmeDmhlOmT +qU5XRBPDnh5Hdkq3G34QVwaLEDapyQOnbrylVlE0a+uaB+llzw4GrFOVcRi0K8M5 +wcwI8sSgfoOyv6WKH5780I9T1EiNBDmS5XFr+dkI16+GO1LJdI5JuMoio+0WBKHk +m3He1rik3QKBgQC1ds/vE6RyWclfk9dWEZdeUSJKpli0Tds+hWxRAM9uRNfg2GWO +vnOomvbtNfwIYstNm+z6di9iqMsvFn+7PWIFO0uS2tEWTp2/IvZr8DuZ5XrTCNu8 +S3e3StpQV6qlK8iTvY0NO1TOCrDos6GWf1K+iCq+p9pchD5Uo+lM31xnEQKBgHSL ++0pkEiewX/FNp4v4UTjQSTfPNiEVaMjtsZmbiljVRfAYBUU3f739vSVWejVDGLE5 +OIUgiOi8ECCSanwX9qPu5gS1JHgedt5vRnsh1+vzugi22xuCvto7CPFKbpybkTgi +qQc9K0BiOh+2zAx09t+pkBNOiGRul26TiL+SMHy9AoGABbo9jk6Je4fcLmB9YtHT +O8L+e2S88r/KuXGrqECD5c/FZL33oTrP9pzvL4Be2W8489DM2UMMD4w0uiUIq/Iu +5Hp/Lsj8ha2OHoU2TbFaNFoS3fvaOz9zQ0GySjpMngZOKIoYtR9R4ZNI/hlmhAqq +usJ3GDPcvFSsedJr8gP52QU= +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..e06863227f9e7c4a160a649a8335ae25534ce2ce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pem @@ -0,0 +1,163 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost,DNS:localhost1,DNS:localhost2 +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqFG49ghwozY+A +r1DtF5dt5qhhPqyorBPOmespLElz+RJANcR5hA2esCjEn2TjwW0tcRFdSxRhIEsY +ocshbZ54GxHSgxyJddV3PcrIgxd0XESyH6zzi8VqNHqGqwj1PXlyqzZII94rukzg +7xiRZJfGCZLtJtKnDaIhHzQGx5kXslCWtg+b7UX/voFHKeXzSdshZUTejSsSBxIN +Wcy7TRozwHp+5VsGUGKyf49cbZHLalzj5K65qw027wrVbQdbJVggDdJLJQ/oEfXO +GbEpxtNJ1/JKeFLSxfxPEWPxTneuCodlRUm2rCEbyJTBDOcT5r7z/6K9aEzGNAQr +/P/D6CNXAgMBAAECggEABTfYrgT/xHXbOkOmuvieLp5ODH7joPLldvX3+FpqxxSL +EhdB7qNaaVYftYLrkaVNvKS/3BDBfk+nwr+Qmy4X8wH5m0sdpSqWfDDLAPAss53y +zi8ZLcBJ6v3TMa5AQolfBPPFzrfzAA8GNao3IuSLoK5BqMFMmhjr+8kGS8CrGn0c +PaMd+zNUaCo0ml7dsO+14qjeLSSzKaYl7mOHeEq02B3UDa5twvkyVQiCHV7CThF0 +0oxJ+DOFzBefPB8pIurh6X0WwaDumEQVnEaaaOWEa1IayscTSrkLcNwkZC55/23M +k9qaR/qGnfUSpu34NTlyy7ifbJOeHp+rZDEFKgBoWQKBgQDalQKzRAjpXn9sSBQS +aTvP293zxP5ueJnv0TmViUfadDDPZ/VX6W0n7mGuOmNKaWnjM1rvMGpqo6e65eir +obuUe7GfJAqexUK6VDFOIzFSBqWpquyjjHWa6C4zgL+BVDGItIhQI/6wYsQ0HgLV +R/n3nqCcYAc/a131GDGdfshbwwKBgQDHMePvhNBZo3p1vUG5l3HiTQRmeDmhlOmT +qU5XRBPDnh5Hdkq3G34QVwaLEDapyQOnbrylVlE0a+uaB+llzw4GrFOVcRi0K8M5 +wcwI8sSgfoOyv6WKH5780I9T1EiNBDmS5XFr+dkI16+GO1LJdI5JuMoio+0WBKHk +m3He1rik3QKBgQC1ds/vE6RyWclfk9dWEZdeUSJKpli0Tds+hWxRAM9uRNfg2GWO +vnOomvbtNfwIYstNm+z6di9iqMsvFn+7PWIFO0uS2tEWTp2/IvZr8DuZ5XrTCNu8 +S3e3StpQV6qlK8iTvY0NO1TOCrDos6GWf1K+iCq+p9pchD5Uo+lM31xnEQKBgHSL ++0pkEiewX/FNp4v4UTjQSTfPNiEVaMjtsZmbiljVRfAYBUU3f739vSVWejVDGLE5 +OIUgiOi8ECCSanwX9qPu5gS1JHgedt5vRnsh1+vzugi22xuCvto7CPFKbpybkTgi +qQc9K0BiOh+2zAx09t+pkBNOiGRul26TiL+SMHy9AoGABbo9jk6Je4fcLmB9YtHT +O8L+e2S88r/KuXGrqECD5c/FZL33oTrP9pzvL4Be2W8489DM2UMMD4w0uiUIq/Iu +5Hp/Lsj8ha2OHoU2TbFaNFoS3fvaOz9zQ0GySjpMngZOKIoYtR9R4ZNI/hlmhAqq +usJ3GDPcvFSsedJr8gP52QU= +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979593 (0xf3475515189) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:38 2022 GMT + Not After : Mar 11 12:21:38 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:aa:14:6e:3d:82:1c:28:cd:8f:80:af:50:ed:17: + 97:6d:e6:a8:61:3e:ac:a8:ac:13:ce:99:eb:29:2c: + 49:73:f9:12:40:35:c4:79:84:0d:9e:b0:28:c4:9f: + 64:e3:c1:6d:2d:71:11:5d:4b:14:61:20:4b:18:a1: + cb:21:6d:9e:78:1b:11:d2:83:1c:89:75:d5:77:3d: + ca:c8:83:17:74:5c:44:b2:1f:ac:f3:8b:c5:6a:34: + 7a:86:ab:08:f5:3d:79:72:ab:36:48:23:de:2b:ba: + 4c:e0:ef:18:91:64:97:c6:09:92:ed:26:d2:a7:0d: + a2:21:1f:34:06:c7:99:17:b2:50:96:b6:0f:9b:ed: + 45:ff:be:81:47:29:e5:f3:49:db:21:65:44:de:8d: + 2b:12:07:12:0d:59:cc:bb:4d:1a:33:c0:7a:7e:e5: + 5b:06:50:62:b2:7f:8f:5c:6d:91:cb:6a:5c:e3:e4: + ae:b9:ab:0d:36:ef:0a:d5:6d:07:5b:25:58:20:0d: + d2:4b:25:0f:e8:11:f5:ce:19:b1:29:c6:d3:49:d7: + f2:4a:78:52:d2:c5:fc:4f:11:63:f1:4e:77:ae:0a: + 87:65:45:49:b6:ac:21:1b:c8:94:c1:0c:e7:13:e6: + be:f3:ff:a2:bd:68:4c:c6:34:04:2b:fc:ff:c3:e8: + 23:57 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost, DNS:localhost1, DNS:localhost2 + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + DB:7A:18:5E:83:AC:D3:48:C9:00:99:3C:EB:BF:A6:21:F0:39:80:CC + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 75:0d:9b:eb:8a:df:ca:a7:7c:9d:9e:6a:eb:30:10:24:12:1b: + 81:f6:cd:b0:a0:f8:de:10:f1:6e:b8:57:3a:3a:b0:a4:8c:1d: + c1:8f:95:22:e3:1f:8b:3a:21:89:e5:96:08:3d:83:33:37:66: + 48:03:f7:98:dd:2f:6d:09:7a:82:26:c1:eb:16:b9:5e:5b:f5: + 67:4c:a0:e7:93:e7:2e:d4:53:b8:77:5f:5e:6a:3a:d9:06:19: + ca:85:ca:7c:09:61:0d:08:8b:6a:b3:e2:03:8c:ea:b1:55:b2: + 30:9b:aa:66:0e:6e:d7:0a:0a:22:ca:6d:8d:d8:53:a8:bc:df: + 13:29:d3:b6:1e:9f:3e:a1:8d:f3:8c:48:bf:71:e9:4e:f4:76: + ed:77:97:3f:59:27:ca:bb:5b:7c:58:23:82:e7:b5:2d:39:02: + 9f:52:07:2f:7b:17:6d:c8:af:90:f5:ed:81:99:a9:cf:80:fb: + eb:ba:9c:bc:9a:df:c5:04:78:2c:73:73:bf:95:23:cf:fb:c9: + 3e:fa:5b:ee:02:39:8e:09:78:ca:89:08:fd:83:77:37:72:01: + 6c:dd:fb:eb:70:20:df:87:28:b3:0f:a0:c5:b3:70:fb:5d:38: + 72:23:46:7f:f5:d8:fc:b6:67:72:82:e5:ce:29:f5:b5:34:db: + a3:d5:fe:20 +-----BEGIN CERTIFICATE----- +MIIEXzCCA0egAwIBAgIGDzR1UVGJMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzhaFw0zMTAzMTExMjIxMzhaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCqFG49ghwozY+Ar1DtF5dt5qhhPqyorBPOmespLElz+RJANcR5hA2e +sCjEn2TjwW0tcRFdSxRhIEsYocshbZ54GxHSgxyJddV3PcrIgxd0XESyH6zzi8Vq +NHqGqwj1PXlyqzZII94rukzg7xiRZJfGCZLtJtKnDaIhHzQGx5kXslCWtg+b7UX/ +voFHKeXzSdshZUTejSsSBxINWcy7TRozwHp+5VsGUGKyf49cbZHLalzj5K65qw02 +7wrVbQdbJVggDdJLJQ/oEfXOGbEpxtNJ1/JKeFLSxfxPEWPxTneuCodlRUm2rCEb +yJTBDOcT5r7z/6K9aEzGNAQr/P/D6CNXAgMBAAGjggEeMIIBGjAsBgNVHREEJTAj +gglsb2NhbGhvc3SCCmxvY2FsaG9zdDGCCmxvY2FsaG9zdDIwCwYDVR0PBAQDAgOo +MBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1UdDgQWBBTbehheg6zTSMkAmTzrv6Yh +8DmAzDAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAA +MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5z +ZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90 +ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOC +AQEAdQ2b64rfyqd8nZ5q6zAQJBIbgfbNsKD43hDxbrhXOjqwpIwdwY+VIuMfizoh +ieWWCD2DMzdmSAP3mN0vbQl6gibB6xa5Xlv1Z0yg55PnLtRTuHdfXmo62QYZyoXK +fAlhDQiLarPiA4zqsVWyMJuqZg5u1woKIsptjdhTqLzfEynTth6fPqGN84xIv3Hp +TvR27XeXP1knyrtbfFgjgue1LTkCn1IHL3sXbcivkPXtgZmpz4D767qcvJrfxQR4 +LHNzv5Ujz/vJPvpb7gI5jgl4yokI/YN3N3IBbN3763Ag34cosw+gxbNw+104ciNG +f/XY/LZncoLlzin1tTTbo9X+IA== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..1a388993572d9d408521d330421e00f978c38121 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.prm @@ -0,0 +1,35 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost,DNS:localhost1,DNS:localhost2 +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..0bb787737c3360757dd15b887d086175d2b94fe8 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..4bc6c6936e12340bf6a4ccda708bd0e1cf77373c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqhRuPYIcKM2PgK9Q7ReX +beaoYT6sqKwTzpnrKSxJc/kSQDXEeYQNnrAoxJ9k48FtLXERXUsUYSBLGKHLIW2e +eBsR0oMciXXVdz3KyIMXdFxEsh+s84vFajR6hqsI9T15cqs2SCPeK7pM4O8YkWSX +xgmS7SbSpw2iIR80BseZF7JQlrYPm+1F/76BRynl80nbIWVE3o0rEgcSDVnMu00a +M8B6fuVbBlBisn+PXG2Ry2pc4+SuuasNNu8K1W0HWyVYIA3SSyUP6BH1zhmxKcbT +SdfySnhS0sX8TxFj8U53rgqHZUVJtqwhG8iUwQznE+a+8/+ivWhMxjQEK/z/w+gj +VwIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..892077d8ee0c836391947f926dfb42c83b049f5d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-firstSAN-sv.pubkey-pinned @@ -0,0 +1 @@ ++V1rGPoCoOLZjthRz6LwtLV9Z/6Gds5LH3j8KUrCIwc= diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..e47a90cfd4f898fd0ee7b4e65fb0b658e82d17ad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crl @@ -0,0 +1,15 @@ +-----BEGIN X509 CRL----- +MIICQTCCASkCAQEwDQYJKoZIhvcNAQELBQAwaDELMAkGA1UEBhMCTk4xMTAvBgNV +BAoMKEVkZWwgQ3VybCBBcmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxJjAk +BgNVBAMMHU5vcnRoZXJuIE5vd2hlcmUgVHJ1c3QgQW5jaG9yFw0yMjEyMjMxMjIx +MzhaFw0yMzAxMjIxMjIxMzhaMH0wFwIGDzR1USo8Fw0yMjEyMjMxMjIxMzZaMBcC +Bg80dVFRYRcNMjIxMjIzMTIyMTM3WjAXAgYPNHVRUXUXDTIyMTIyMzEyMjEzN1ow +FwIGDzR1UVGJFw0yMjEyMjMxMjIxMzhaMBcCBg80dVF4rhcNMjIxMjIzMTIyMTM4 +WqAOMAwwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQADggEBADZeuue7woDyqDdc +DCxuNE94pNl78cTedT+V9svX0gbMExAI0WRovb9FudimX+CRofFTwZ4RSDF7AdHw +PqbVSMjZtGTlQrKrMAZ5kBMs9ZI1tWGpGVJNxv4hKMt2VITLPJ22CP8j3yZahNpw +/kgJQx+7aIRKTC1n6UEAsOsLyDsrFDvdXU2euU0NIx6KudeRUagdgyOntwrLaeeW ++g18IZTewQWefx4iA6eW6y3E9CM0n3d4n7VAxLb95TysLAUoxOeVxtUSa+wm8jWt +gjm/2UkFxX79dDhDMc5LsL9mBDL3dasunhcUCtI5CTL1aX2Fg2YkztsyQiO0lNx/ +meUHDNM= +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..ec37cf15aa7f1d37bb7ad38d2ab017dd631b86f2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.crt @@ -0,0 +1,100 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980989614 (0xf34755178ae) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:38 2022 GMT + Not After : Mar 11 12:21:38 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c8:84:fe:69:64:33:c3:dc:b5:74:8a:c7:b2:bb: + d9:69:e2:a9:95:6d:5f:b7:25:e6:82:00:2b:f5:53: + 21:e7:28:ae:66:b6:38:fd:15:b1:91:88:52:31:29: + bb:73:e2:e0:99:62:95:44:35:51:d7:54:c8:d2:6d: + 25:3c:f0:2e:03:1b:a8:a1:25:e1:83:9a:5c:bd:65: + 57:93:44:7e:a3:cc:dd:ac:59:69:60:01:e0:80:b9: + d0:c4:70:63:cf:17:a0:c6:13:0f:21:3b:c8:c1:46: + 4e:18:fd:6a:36:76:24:4a:57:d8:73:2f:13:42:a0: + 2e:90:1f:bf:84:9d:81:e7:bd:f8:75:53:f3:fa:52: + e1:f0:aa:f6:23:d7:0d:61:17:0c:e5:9a:ab:e2:d5: + e8:c3:c9:6b:2a:a6:da:f9:cb:f6:4d:1d:40:53:7e: + 68:2f:51:9f:d3:17:95:34:21:32:0d:47:d6:a9:4d: + 28:bb:e0:50:13:2f:5b:76:a1:90:5a:51:48:2f:ce: + db:d9:da:2e:d1:3a:0f:fb:80:61:24:0b:0b:79:b2: + 45:cd:1d:2d:66:ee:4a:96:5d:08:b7:c4:80:95:2d: + 4e:8e:ac:0e:15:fa:2c:06:0c:49:74:49:81:77:17: + a5:b2:01:de:aa:88:2b:9a:66:13:bb:06:b4:89:fb: + e4:91 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost1, DNS:localhost2, DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + B3:77:93:C4:CA:9A:B3:62:CF:51:0D:17:1D:8E:87:F6:C2:3E:17:75 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 10:22:60:56:f6:14:b7:03:18:c4:01:ba:06:c7:65:49:98:d7: + 64:64:d4:2a:2b:19:16:d1:0e:e9:b0:04:86:01:fb:ae:37:e4: + c9:19:37:d5:02:27:63:da:6f:de:a2:d0:23:36:7f:2f:3e:55: + d2:b5:ef:23:5d:f7:ac:71:3f:95:77:bc:74:d3:1e:51:d9:7d: + 7e:0d:8e:03:f3:82:95:3e:88:dd:3c:ed:3a:aa:b4:e1:85:fb: + d8:ea:3f:6a:7d:34:b7:b3:df:b1:fe:2b:ec:af:e0:1c:9c:ec: + 43:63:80:17:3a:32:ca:13:35:2d:c7:3d:3e:ac:aa:55:d6:1a: + 6d:3f:f0:ff:23:4f:e0:88:a1:42:d9:91:1c:a5:6b:87:14:1b: + 0b:4d:24:a8:33:36:7a:21:f7:e2:86:9c:65:36:f3:7c:0c:4d: + be:f1:98:45:c3:27:e4:11:4a:7d:8a:e3:70:ae:fb:ac:9f:a6: + f4:0d:dc:a7:83:39:50:c3:1e:1a:95:68:0d:b0:56:8f:64:d2: + db:a1:a7:97:d1:2c:ea:7a:f9:9b:2f:5f:4d:ed:7c:f9:df:74: + 1a:81:73:79:f8:00:2a:78:18:23:72:7a:4b:66:6b:61:da:95: + 29:85:7c:4d:42:76:2e:43:70:6d:ac:0c:dc:98:d5:47:da:e1: + 54:0c:71:bf +-----BEGIN CERTIFICATE----- +MIIEXzCCA0egAwIBAgIGDzR1UXiuMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzhaFw0zMTAzMTExMjIxMzhaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDIhP5pZDPD3LV0iseyu9lp4qmVbV+3JeaCACv1UyHnKK5mtjj9FbGR +iFIxKbtz4uCZYpVENVHXVMjSbSU88C4DG6ihJeGDmly9ZVeTRH6jzN2sWWlgAeCA +udDEcGPPF6DGEw8hO8jBRk4Y/Wo2diRKV9hzLxNCoC6QH7+EnYHnvfh1U/P6UuHw +qvYj1w1hFwzlmqvi1ejDyWsqptr5y/ZNHUBTfmgvUZ/TF5U0ITINR9apTSi74FAT +L1t2oZBaUUgvztvZ2i7ROg/7gGEkCwt5skXNHS1m7kqWXQi3xICVLU6OrA4V+iwG +DEl0SYF3F6WyAd6qiCuaZhO7BrSJ++SRAgMBAAGjggEeMIIBGjAsBgNVHREEJTAj +ggpsb2NhbGhvc3Qxggpsb2NhbGhvc3Qygglsb2NhbGhvc3QwCwYDVR0PBAQDAgOo +MBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1UdDgQWBBSzd5PEypqzYs9RDRcdjof2 +wj4XdTAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAA +MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5z +ZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90 +ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOC +AQEAECJgVvYUtwMYxAG6BsdlSZjXZGTUKisZFtEO6bAEhgH7rjfkyRk31QInY9pv +3qLQIzZ/Lz5V0rXvI133rHE/lXe8dNMeUdl9fg2OA/OClT6I3TztOqq04YX72Oo/ +an00t7Pfsf4r7K/gHJzsQ2OAFzoyyhM1Lcc9PqyqVdYabT/w/yNP4IihQtmRHKVr +hxQbC00kqDM2eiH34oacZTbzfAxNvvGYRcMn5BFKfYrjcK77rJ+m9A3cp4M5UMMe +GpVoDbBWj2TS26Gnl9Es6nr5my9fTe18+d90GoFzefgAKngYI3J6S2ZrYdqVKYV8 +TUJ2LkNwbawM3JjVR9rhVAxxvw== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..ec930784d9d446ef5cd407d190dc24feca57ac66 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxFTATBgNVBAMMDGxvY2FsaG9z +dC5ubjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMiE/mlkM8PctXSK +x7K72WniqZVtX7cl5oIAK/VTIecorma2OP0VsZGIUjEpu3Pi4JlilUQ1UddUyNJt +JTzwLgMbqKEl4YOaXL1lV5NEfqPM3axZaWAB4IC50MRwY88XoMYTDyE7yMFGThj9 +ajZ2JEpX2HMvE0KgLpAfv4Sdgee9+HVT8/pS4fCq9iPXDWEXDOWaq+LV6MPJayqm +2vnL9k0dQFN+aC9Rn9MXlTQhMg1H1qlNKLvgUBMvW3ahkFpRSC/O29naLtE6D/uA +YSQLC3myRc0dLWbuSpZdCLfEgJUtTo6sDhX6LAYMSXRJgXcXpbIB3qqIK5pmE7sG +tIn75JECAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQCeDxLX9uy0Fv7yaY/gqL/G +x+TFx7xoKOJwqu3NqrGiTfs6SeXvmxIj5oOE2gBi9cjc184TUa/zHSW+iYug2RVO +f18zO3sOUXeFLN10f1OEgkOEm6k9I4MuWhEJuCY0FePAl6i71b4iy2O6n0CxLNKB +D+IM8MBOjx18Ev+BETXmf2R6zyQaVY+VP541XRtcCwcMU9IV92CilhfHjPJy3g4V +7mQIcvgdpQMuQLsBvMY+yFRUwRpWiPjOOot5q6bQKgA5pcRU7UtraqLzT7gG9cF2 +SDN2y9A05EWYZB7/hlg+URdJKjrCLn20i5BR52VVepLDWUOCBafkdCOp1O6JTRK2 +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..c4706a58e71c3f07ef8fbf4c09cf14f587e5381b Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..7a5d854fb198ccc5a1e43de2119b503f3cdd6208 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIhP5pZDPD3LV0 +iseyu9lp4qmVbV+3JeaCACv1UyHnKK5mtjj9FbGRiFIxKbtz4uCZYpVENVHXVMjS +bSU88C4DG6ihJeGDmly9ZVeTRH6jzN2sWWlgAeCAudDEcGPPF6DGEw8hO8jBRk4Y +/Wo2diRKV9hzLxNCoC6QH7+EnYHnvfh1U/P6UuHwqvYj1w1hFwzlmqvi1ejDyWsq +ptr5y/ZNHUBTfmgvUZ/TF5U0ITINR9apTSi74FATL1t2oZBaUUgvztvZ2i7ROg/7 +gGEkCwt5skXNHS1m7kqWXQi3xICVLU6OrA4V+iwGDEl0SYF3F6WyAd6qiCuaZhO7 +BrSJ++SRAgMBAAECggEAApUDLABsPI6EGqj/1dDJRa2zcSxm92DfpUG9zytVIYN6 +rXFqw0g10LyF5xf/uogLzDCCtg25YlG3QqMWVUDNguDmt2kutycJddnkemMUfg+m +X3CzpJbEQ+bApgrsH2+micPB5d5odnlX35wByQuVP4zT3sssJGc+JOvNEkwvRE3o +0x+B7qnW5YWDA9X67Sb9Kgcg9xExC7lbUqQoDetpa6x36LVx2OCqmomIKf8CQqHr +FOOTKNkTs6mal3jxxxwvLmj7Bkz+InSIRK0VE9d5G2VWliwcRMVjB9c5oh/P6Le3 +/jCyi18omkMgQK0Hm6CJBjsT+PdJu09hbo1TXD8cbQKBgQD8CwQNzHSolSUoKMpd +SfsAIB5gjILns7xAAtemkHEn15ga6p7510wtvkWAzOqBtt3RrTqb/AoWKUkHwfRd +AYFE1RrGVUA0Yohuf4eJFjAXuEQXNKx2uuHIpwEf0UpfiyAFLzDyUmTjMHLw15ZP +OrhIHJBRfWiU9nWIScNZC4/A7QKBgQDLquZxndjls3h/LotU62CcjZSqU59Wbhfs +VoGDgvj5jxxdcy4u7BntYYBKsaIL7k/Q6vyrNWnQoUgazhIqJ3RJ2p3OzaCLjKY8 +7+vf8F1bSZL+VbHTJZfuPKKShGlIfZ0ixjuP0vEUh+xblEwsmgNN4XOc/M/mVyid +qek2xFPRtQKBgA8SXZCxrDw0hv9KyScg+Gh+gzKE1IMkhVpSkTC9rHaUdt0NMKqC +DGUj3qYgGtnc5JDYSgvv226N03cqSwGQyHkkQTChAnDff4cUCzfQYtnYRAIbPUDw +VfYYvoF3k3n5KNYGh2fGM5A+YnEygyODwGdXhe3JkQpvXoHi31Kg1VzVAoGBAKGa +JCmopq50PjskElg6P7lYucqAeaCZ0I+tgCx6otVZ0ZbwyodevZ/WSnZ6BetTl69c +lUnAIwrwvgbO1ijuj13+glLSY/32hv05Hb7duSWy9liqZGP2o1vcbt61A9kKGsG5 +6w7OwI2a4Fc2D08gkVideB/rlYbeR5L6e9sB4sQ1AoGAcLMiz2/cF40/pMhqq/C/ +SyFDa1OAquW00PujVrTbgIHY+2HdjaIlzwNVFWIY/K7LCJtLvK6mVCVbo1n7/Agp +qYZZzPEUwJ84ZY1ZNxC0Z89dBFmJeFvyNSan9zGujye7Kx8QctCvn5DzjoWtA52k +MvALyxOMqzvGI5bC4r1o3Hw= +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..c3124ff1ca1c2baa2426614e18a2d7cca8d2aa5e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pem @@ -0,0 +1,163 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost1,DNS:localhost2,DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIhP5pZDPD3LV0 +iseyu9lp4qmVbV+3JeaCACv1UyHnKK5mtjj9FbGRiFIxKbtz4uCZYpVENVHXVMjS +bSU88C4DG6ihJeGDmly9ZVeTRH6jzN2sWWlgAeCAudDEcGPPF6DGEw8hO8jBRk4Y +/Wo2diRKV9hzLxNCoC6QH7+EnYHnvfh1U/P6UuHwqvYj1w1hFwzlmqvi1ejDyWsq +ptr5y/ZNHUBTfmgvUZ/TF5U0ITINR9apTSi74FATL1t2oZBaUUgvztvZ2i7ROg/7 +gGEkCwt5skXNHS1m7kqWXQi3xICVLU6OrA4V+iwGDEl0SYF3F6WyAd6qiCuaZhO7 +BrSJ++SRAgMBAAECggEAApUDLABsPI6EGqj/1dDJRa2zcSxm92DfpUG9zytVIYN6 +rXFqw0g10LyF5xf/uogLzDCCtg25YlG3QqMWVUDNguDmt2kutycJddnkemMUfg+m +X3CzpJbEQ+bApgrsH2+micPB5d5odnlX35wByQuVP4zT3sssJGc+JOvNEkwvRE3o +0x+B7qnW5YWDA9X67Sb9Kgcg9xExC7lbUqQoDetpa6x36LVx2OCqmomIKf8CQqHr +FOOTKNkTs6mal3jxxxwvLmj7Bkz+InSIRK0VE9d5G2VWliwcRMVjB9c5oh/P6Le3 +/jCyi18omkMgQK0Hm6CJBjsT+PdJu09hbo1TXD8cbQKBgQD8CwQNzHSolSUoKMpd +SfsAIB5gjILns7xAAtemkHEn15ga6p7510wtvkWAzOqBtt3RrTqb/AoWKUkHwfRd +AYFE1RrGVUA0Yohuf4eJFjAXuEQXNKx2uuHIpwEf0UpfiyAFLzDyUmTjMHLw15ZP +OrhIHJBRfWiU9nWIScNZC4/A7QKBgQDLquZxndjls3h/LotU62CcjZSqU59Wbhfs +VoGDgvj5jxxdcy4u7BntYYBKsaIL7k/Q6vyrNWnQoUgazhIqJ3RJ2p3OzaCLjKY8 +7+vf8F1bSZL+VbHTJZfuPKKShGlIfZ0ixjuP0vEUh+xblEwsmgNN4XOc/M/mVyid +qek2xFPRtQKBgA8SXZCxrDw0hv9KyScg+Gh+gzKE1IMkhVpSkTC9rHaUdt0NMKqC +DGUj3qYgGtnc5JDYSgvv226N03cqSwGQyHkkQTChAnDff4cUCzfQYtnYRAIbPUDw +VfYYvoF3k3n5KNYGh2fGM5A+YnEygyODwGdXhe3JkQpvXoHi31Kg1VzVAoGBAKGa +JCmopq50PjskElg6P7lYucqAeaCZ0I+tgCx6otVZ0ZbwyodevZ/WSnZ6BetTl69c +lUnAIwrwvgbO1ijuj13+glLSY/32hv05Hb7duSWy9liqZGP2o1vcbt61A9kKGsG5 +6w7OwI2a4Fc2D08gkVideB/rlYbeR5L6e9sB4sQ1AoGAcLMiz2/cF40/pMhqq/C/ +SyFDa1OAquW00PujVrTbgIHY+2HdjaIlzwNVFWIY/K7LCJtLvK6mVCVbo1n7/Agp +qYZZzPEUwJ84ZY1ZNxC0Z89dBFmJeFvyNSan9zGujye7Kx8QctCvn5DzjoWtA52k +MvALyxOMqzvGI5bC4r1o3Hw= +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980989614 (0xf34755178ae) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:38 2022 GMT + Not After : Mar 11 12:21:38 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c8:84:fe:69:64:33:c3:dc:b5:74:8a:c7:b2:bb: + d9:69:e2:a9:95:6d:5f:b7:25:e6:82:00:2b:f5:53: + 21:e7:28:ae:66:b6:38:fd:15:b1:91:88:52:31:29: + bb:73:e2:e0:99:62:95:44:35:51:d7:54:c8:d2:6d: + 25:3c:f0:2e:03:1b:a8:a1:25:e1:83:9a:5c:bd:65: + 57:93:44:7e:a3:cc:dd:ac:59:69:60:01:e0:80:b9: + d0:c4:70:63:cf:17:a0:c6:13:0f:21:3b:c8:c1:46: + 4e:18:fd:6a:36:76:24:4a:57:d8:73:2f:13:42:a0: + 2e:90:1f:bf:84:9d:81:e7:bd:f8:75:53:f3:fa:52: + e1:f0:aa:f6:23:d7:0d:61:17:0c:e5:9a:ab:e2:d5: + e8:c3:c9:6b:2a:a6:da:f9:cb:f6:4d:1d:40:53:7e: + 68:2f:51:9f:d3:17:95:34:21:32:0d:47:d6:a9:4d: + 28:bb:e0:50:13:2f:5b:76:a1:90:5a:51:48:2f:ce: + db:d9:da:2e:d1:3a:0f:fb:80:61:24:0b:0b:79:b2: + 45:cd:1d:2d:66:ee:4a:96:5d:08:b7:c4:80:95:2d: + 4e:8e:ac:0e:15:fa:2c:06:0c:49:74:49:81:77:17: + a5:b2:01:de:aa:88:2b:9a:66:13:bb:06:b4:89:fb: + e4:91 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost1, DNS:localhost2, DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + B3:77:93:C4:CA:9A:B3:62:CF:51:0D:17:1D:8E:87:F6:C2:3E:17:75 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 10:22:60:56:f6:14:b7:03:18:c4:01:ba:06:c7:65:49:98:d7: + 64:64:d4:2a:2b:19:16:d1:0e:e9:b0:04:86:01:fb:ae:37:e4: + c9:19:37:d5:02:27:63:da:6f:de:a2:d0:23:36:7f:2f:3e:55: + d2:b5:ef:23:5d:f7:ac:71:3f:95:77:bc:74:d3:1e:51:d9:7d: + 7e:0d:8e:03:f3:82:95:3e:88:dd:3c:ed:3a:aa:b4:e1:85:fb: + d8:ea:3f:6a:7d:34:b7:b3:df:b1:fe:2b:ec:af:e0:1c:9c:ec: + 43:63:80:17:3a:32:ca:13:35:2d:c7:3d:3e:ac:aa:55:d6:1a: + 6d:3f:f0:ff:23:4f:e0:88:a1:42:d9:91:1c:a5:6b:87:14:1b: + 0b:4d:24:a8:33:36:7a:21:f7:e2:86:9c:65:36:f3:7c:0c:4d: + be:f1:98:45:c3:27:e4:11:4a:7d:8a:e3:70:ae:fb:ac:9f:a6: + f4:0d:dc:a7:83:39:50:c3:1e:1a:95:68:0d:b0:56:8f:64:d2: + db:a1:a7:97:d1:2c:ea:7a:f9:9b:2f:5f:4d:ed:7c:f9:df:74: + 1a:81:73:79:f8:00:2a:78:18:23:72:7a:4b:66:6b:61:da:95: + 29:85:7c:4d:42:76:2e:43:70:6d:ac:0c:dc:98:d5:47:da:e1: + 54:0c:71:bf +-----BEGIN CERTIFICATE----- +MIIEXzCCA0egAwIBAgIGDzR1UXiuMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzhaFw0zMTAzMTExMjIxMzhaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDIhP5pZDPD3LV0iseyu9lp4qmVbV+3JeaCACv1UyHnKK5mtjj9FbGR +iFIxKbtz4uCZYpVENVHXVMjSbSU88C4DG6ihJeGDmly9ZVeTRH6jzN2sWWlgAeCA +udDEcGPPF6DGEw8hO8jBRk4Y/Wo2diRKV9hzLxNCoC6QH7+EnYHnvfh1U/P6UuHw +qvYj1w1hFwzlmqvi1ejDyWsqptr5y/ZNHUBTfmgvUZ/TF5U0ITINR9apTSi74FAT +L1t2oZBaUUgvztvZ2i7ROg/7gGEkCwt5skXNHS1m7kqWXQi3xICVLU6OrA4V+iwG +DEl0SYF3F6WyAd6qiCuaZhO7BrSJ++SRAgMBAAGjggEeMIIBGjAsBgNVHREEJTAj +ggpsb2NhbGhvc3Qxggpsb2NhbGhvc3Qygglsb2NhbGhvc3QwCwYDVR0PBAQDAgOo +MBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1UdDgQWBBSzd5PEypqzYs9RDRcdjof2 +wj4XdTAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAA +MEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5z +ZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90 +ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOC +AQEAECJgVvYUtwMYxAG6BsdlSZjXZGTUKisZFtEO6bAEhgH7rjfkyRk31QInY9pv +3qLQIzZ/Lz5V0rXvI133rHE/lXe8dNMeUdl9fg2OA/OClT6I3TztOqq04YX72Oo/ +an00t7Pfsf4r7K/gHJzsQ2OAFzoyyhM1Lcc9PqyqVdYabT/w/yNP4IihQtmRHKVr +hxQbC00kqDM2eiH34oacZTbzfAxNvvGYRcMn5BFKfYrjcK77rJ+m9A3cp4M5UMMe +GpVoDbBWj2TS26Gnl9Es6nr5my9fTe18+d90GoFzefgAKngYI3J6S2ZrYdqVKYV8 +TUJ2LkNwbawM3JjVR9rhVAxxvw== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..fd2507323e1c5b0c33864e13ea8f8920d1b134e9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.prm @@ -0,0 +1,35 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost1,DNS:localhost2,DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..fc61b6de96f3685d667ea2cbb1a399024d16cf78 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..3644fd9a947360093123165c36bf3a35f6846b7b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyIT+aWQzw9y1dIrHsrvZ +aeKplW1ftyXmggAr9VMh5yiuZrY4/RWxkYhSMSm7c+LgmWKVRDVR11TI0m0lPPAu +AxuooSXhg5pcvWVXk0R+o8zdrFlpYAHggLnQxHBjzxegxhMPITvIwUZOGP1qNnYk +SlfYcy8TQqAukB+/hJ2B5734dVPz+lLh8Kr2I9cNYRcM5Zqr4tXow8lrKqba+cv2 +TR1AU35oL1Gf0xeVNCEyDUfWqU0ou+BQEy9bdqGQWlFIL87b2dou0ToP+4BhJAsL +ebJFzR0tZu5Kll0It8SAlS1OjqwOFfosBgxJdEmBdxelsgHeqogrmmYTuwa0ifvk +kQIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..bcb4d42535aeb5a2994aa3cd516fc76591abdb3f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-lastSAN-sv.pubkey-pinned @@ -0,0 +1 @@ +1iO+QG+cArKLLyo3az2OBu0lM1t8v5bLLI3pNXoJJQ0= diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..d10b90c4c8d229701c7f1e92e57b1823becf2699 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crl @@ -0,0 +1,12 @@ +-----BEGIN X509 CRL----- +MIIB3DCBxQIBATANBgkqhkiG9w0BAQsFADBoMQswCQYDVQQGEwJOTjExMC8GA1UE +CgwoRWRlbCBDdXJsIEFyY3RpYyBJbGx1ZGl1bSBSZXNlYXJjaCBDbG91ZDEmMCQG +A1UEAwwdTm9ydGhlcm4gTm93aGVyZSBUcnVzdCBBbmNob3IXDTIyMTIyMzEyMjEz +NloXDTIzMDEyMjEyMjEzNlowGTAXAgYPNHVRKjwXDTIyMTIyMzEyMjEzNlqgDjAM +MAoGA1UdFAQDAgEBMA0GCSqGSIb3DQEBCwUAA4IBAQBU6nAPnIyD/G6eK21pfHeh +myCoBy+B9b8R1Ed1Y3YDoWS6KFXAoPJxWmy0gdo0sbhzVvC4iSb1iZzWjki/rAVL +lkYdJr+r/D5y7A80+Kngf18j77oLvtRkNiVT4Kac1kHg7h9oznO42T+DI90PPd33 +puX+J/aH9V51NUyZcQWQjY7ZiOMbMUnCjozwhidVPL65pK/ggrTFy08WorHpx4Ew +i1oT5qD478+/4alUxs+EFJMvVTBPrKbpBYq2fr1n1L1/XdRGLi4U3M9B4jsXdmXd +JyHPVlMNNBPTM8S95vNko4Q94UuZrCQv0TlPJtQI1B0KDDWCJxuyA/3+hYRFglBe +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..06355e3e6adfee56db671f9fc655c90fa3e7243d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.crt @@ -0,0 +1,99 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980969532 (0xf3475512a3c) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:36 2022 GMT + Not After : Mar 11 12:21:36 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c6:b8:04:3d:d6:fa:31:a0:d7:f7:e9:88:4b:5a: + 5e:6f:6f:db:f4:c9:4b:7e:6c:2a:cf:34:7b:2a:ba: + 1a:71:ad:7f:78:6c:f7:1e:ca:07:d0:29:03:49:e4: + 63:86:4c:f6:67:3f:bd:32:69:cb:b8:15:e7:0e:cf: + 28:3d:9e:96:91:8e:4f:73:a9:27:77:4c:26:61:cd: + d6:e7:4e:3c:64:c3:13:ba:8e:ec:03:0f:bc:d4:83: + b3:94:f2:be:d0:18:30:c5:52:49:cb:9a:60:cf:f3: + b9:ca:2f:63:9d:34:ee:87:3a:58:e7:a1:99:dd:dc: + 56:87:e1:a0:d7:6b:37:ae:bb:13:db:7d:fa:2a:3d: + 9c:39:79:f6:01:a6:e3:3a:e7:18:14:cb:c7:57:b9: + 83:d1:ba:b8:2c:5a:c4:97:2f:ee:8d:68:48:37:f8: + 17:db:32:b9:ea:25:4f:28:57:01:39:13:dc:c0:f7: + d0:cc:65:f9:2b:b8:4c:a1:5b:11:ce:44:e2:28:b9: + 63:62:fd:08:fa:b6:cd:49:d5:b9:fe:9e:68:9c:9a: + b5:1a:3e:cc:bf:0e:74:db:52:3f:25:30:cd:7d:02: + 41:c7:c9:8a:58:12:35:25:21:95:c4:6b:c3:f5:79: + c2:00:cb:ef:7f:d7:9f:89:c9:ff:c0:b9:72:59:4c: + 33:47 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 4A:F1:79:1B:13:71:A4:0F:F9:06:CC:B6:2C:CD:24:46:DF:E6:08:2D + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 67:ef:ad:8f:fa:ee:f1:fd:33:67:62:06:5f:09:55:7c:cf:82: + 1a:e8:fc:f5:97:ba:63:bd:d0:a0:8b:85:2c:fc:f0:34:4a:97: + b2:18:d7:63:34:63:f4:1f:50:c7:0e:13:d9:bc:3b:73:3d:41: + 93:16:b3:30:95:88:cd:75:c8:8c:58:4b:ab:96:e6:78:68:15: + 0f:84:e7:8e:17:94:1a:b3:f3:12:ab:26:fd:fa:73:31:33:36: + 85:83:2d:e3:3a:f2:a6:29:c6:37:30:3d:17:d2:39:31:d1:56: + 1b:8d:df:fb:07:ad:81:0b:91:e5:bd:7b:37:a0:a0:5a:2c:33: + 2b:8d:69:8b:d7:c1:45:61:85:ef:32:45:dd:00:a2:81:98:44: + 0d:eb:01:95:fc:ac:0f:b5:34:a4:5f:35:5c:68:63:50:5a:69: + 56:f3:99:c4:67:70:89:13:30:c0:64:ff:f1:a6:77:68:69:63: + 9e:6f:f8:3c:6f:cd:af:7f:de:0d:87:55:ae:39:b3:b2:f5:4f: + 47:79:1f:32:ee:ae:8f:32:dc:88:30:cd:38:6c:4b:28:55:c3: + 7d:74:6b:de:d0:49:c9:05:ea:62:71:a6:f8:1e:76:da:3c:a7: + 17:cd:1a:92:a3:c4:e8:85:d1:ad:34:0c:71:37:3f:6c:d3:7f: + 9a:d6:ca:de +-----BEGIN CERTIFICATE----- +MIIERDCCAyygAwIBAgIGDzR1USo8MA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzZaFw0zMTAzMTExMjIxMzZaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQDGuAQ91voxoNf36YhLWl5vb9v0yUt+bCrPNHsquhpxrX94bPceygfQKQNJ +5GOGTPZnP70yacu4FecOzyg9npaRjk9zqSd3TCZhzdbnTjxkwxO6juwDD7zUg7OU +8r7QGDDFUknLmmDP87nKL2OdNO6HOljnoZnd3FaH4aDXazeuuxPbffoqPZw5efYB +puM65xgUy8dXuYPRurgsWsSXL+6NaEg3+BfbMrnqJU8oVwE5E9zA99DMZfkruEyh +WxHOROIouWNi/Qj6ts1J1bn+nmicmrUaPsy/DnTbUj8lMM19AkHHyYpYEjUlIZXE +a8P1ecIAy+9/15+Jyf/AuXJZTDNHAgMBAAGjggEGMIIBAjAUBgNVHREEDTALggls +b2NhbGhvc3QwCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1Ud +DgQWBBRK8XkbE3GkD/kGzLYszSRG3+YILTAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj +5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcw +AoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1Ud +HwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290 +LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAZ++tj/ru8f0zZ2IGXwlVfM+CGuj89Ze6 +Y73QoIuFLPzwNEqXshjXYzRj9B9Qxw4T2bw7cz1BkxazMJWIzXXIjFhLq5bmeGgV +D4TnjheUGrPzEqsm/fpzMTM2hYMt4zrypinGNzA9F9I5MdFWG43f+wetgQuR5b17 +N6CgWiwzK41pi9fBRWGF7zJF3QCigZhEDesBlfysD7U0pF81XGhjUFppVvOZxGdw +iRMwwGT/8aZ3aGljnm/4PG/Nr3/eDYdVrjmzsvVPR3kfMu6ujzLciDDNOGxLKFXD +fXRr3tBJyQXqYnGm+B522jynF80akqPE6IXRrTQMcTc/bNN/mtbK3g== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..aa3dc8ccc2c5b350df9aafe39a04b9b5c7dbbc14 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICmTCCAYECAQAwVDELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxEjAQBgNVBAMMCWxvY2FsaG9z +dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMa4BD3W+jGg1/fpiEta +Xm9v2/TJS35sKs80eyq6GnGtf3hs9x7KB9ApA0nkY4ZM9mc/vTJpy7gV5w7PKD2e +lpGOT3OpJ3dMJmHN1udOPGTDE7qO7AMPvNSDs5TyvtAYMMVSScuaYM/zucovY500 +7oc6WOehmd3cVofhoNdrN667E9t9+io9nDl59gGm4zrnGBTLx1e5g9G6uCxaxJcv +7o1oSDf4F9syueolTyhXATkT3MD30Mxl+Su4TKFbEc5E4ii5Y2L9CPq2zUnVuf6e +aJyatRo+zL8OdNtSPyUwzX0CQcfJilgSNSUhlcRrw/V5wgDL73/Xn4nJ/8C5cllM +M0cCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQBtz8OLB7+70UnIZ1s3VNIoYetH +yqnBkNQusZrWmv4kHrIUP4K8zq0HCTGTWdxOAp23aU+yZyceu75aD8WosZoT0Q71 +zTLMMjo+ZRkeWuTo+xyLYoSdlkmyQN9xaj0owQ6UycL07aainnf2+n/ybaMFtUYB +g1LVOwSvtyLQTxByZZ7mJvl+fczSN+E4AuNA8feECXh3oZ/MmWKFGIhkJ36Q4DYD +PZ9J2RAV11KeHXLAKjnxsetQRiEdlvKetRknMCptgjVO23qIV62EbyL5mKrlz9Kx +lTzM788YjSx+u2PTWJi4gduTcsirVel3yFJyHjvSEhMPTPuSDfD1fXSvp22G +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..2e56bd991499df11888576f7734525c3fb5f7e8d Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..a2c95eea911c35a4c71323753d4a0afe6d41f041 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDGuAQ91voxoNf3 +6YhLWl5vb9v0yUt+bCrPNHsquhpxrX94bPceygfQKQNJ5GOGTPZnP70yacu4FecO +zyg9npaRjk9zqSd3TCZhzdbnTjxkwxO6juwDD7zUg7OU8r7QGDDFUknLmmDP87nK +L2OdNO6HOljnoZnd3FaH4aDXazeuuxPbffoqPZw5efYBpuM65xgUy8dXuYPRurgs +WsSXL+6NaEg3+BfbMrnqJU8oVwE5E9zA99DMZfkruEyhWxHOROIouWNi/Qj6ts1J +1bn+nmicmrUaPsy/DnTbUj8lMM19AkHHyYpYEjUlIZXEa8P1ecIAy+9/15+Jyf/A +uXJZTDNHAgMBAAECggEAH48J3WhOw6LvqYeFBbKMXNY+8FknjCRRiCaliNuVZ4hO +PinP9SvQodZhl1KWG7YNS8hrm54BpHKWB1wO3/pXnzYimBO9GM0XK2EtR/68yKPS +dkZMZRASxQ1Fb9o9Q38T/8JZxeP2jBAA6YMtJsJJP2Cczex0Ky/a7il/CbcVWMJF +VCqHEWCBge59xZifsKiAiK/Yw5W6uyi9OZ9a2D7bzJh0sojPIY90d7EhW4u/QCzk +aXn78RbgxDkQyz5AQrIQzEMcOYr+AxiVT5S1v15FoaoWlm1IrNpEmf63PvwRKPZM +ZW1cqR8onTQBndzAdwn9qHjtuRvhoHMe5RWs4rzDAQKBgQDTq2NGbkNdK14oSu7/ +t+z4Z3nGhHmY9pI1jF5/s3ialO/7YD4ul5MXaJt6dbklkPqsN0vmhPeeavAy6tsG +iU4SdTuptKg5aZMZnDa9zu9lM4raJpDf9AuncffjVFqy9EDII5Wi1UIRDTD8D1gp +LBYuFUTpo7R+JD3yqLXvbOw8UQKBgQDwVkgTqbAwbx35sKhpFo0VOAj3GVZkC6zt +nFS03MmHPjge69u3B3I6oavYtwROq+6S9rj3MLuj4DhVbO5Yxi+XqY5wXhFUPPSp +1ejXF8aAwWtZEeMTTsaN8jl3nfzdNul8G5mVfpY/VmZMhuAXclsAR9ke/x+FcmrQ +Furd0lxIFwKBgQDSXVobzEf817YLW3WuBbBorAY1ysFCyYND3s6oIcjx8KWU8fC6 +w3+3WwpyqX8pm63V7Frtriaede9k2050b498/rAeGGK8NHWylTM+buQzcwdDieKg +AN54Ouc/Mj217tRXVC5KF6JCahbN274lpSAiCpdjkIQ4fXJnsU6ntlwOEQKBgQDr +rCAHsAkGpZ+mPlYWnreADC+2ZtExT8WmRvtFU5AHH7sWj0An7ZRU7D5AR89gefZ7 +hJaCRvZpTzDOi//5a3Y16V200Hl7uj5M4GbvrO/JSGHEuOaMA15uyQ0TQAg6wGMa +gVIMp1IcD9RGzKeoNkoIL2w4mgJF8JnPLfnnxSUaxwKBgQCXP6btCbX7fryeIfUB +PC1TOtyNvNWeoPJNT9eeNHxPC5VW2AC78XKxbHsVec16KJsOgj4Elc3h8/+X0wAU +7Zo9CD7M2i1Tm5sKh90yBsZsU6jBWOBorLQnatDKVPXHLblVAEgK0qTJTAW8hLDn +myYsFbt36qBXf1dVvo+5yhCxAw== +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..2761de438370278e8932fcf46b5c1f5e26a5d372 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pem @@ -0,0 +1,162 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDGuAQ91voxoNf3 +6YhLWl5vb9v0yUt+bCrPNHsquhpxrX94bPceygfQKQNJ5GOGTPZnP70yacu4FecO +zyg9npaRjk9zqSd3TCZhzdbnTjxkwxO6juwDD7zUg7OU8r7QGDDFUknLmmDP87nK +L2OdNO6HOljnoZnd3FaH4aDXazeuuxPbffoqPZw5efYBpuM65xgUy8dXuYPRurgs +WsSXL+6NaEg3+BfbMrnqJU8oVwE5E9zA99DMZfkruEyhWxHOROIouWNi/Qj6ts1J +1bn+nmicmrUaPsy/DnTbUj8lMM19AkHHyYpYEjUlIZXEa8P1ecIAy+9/15+Jyf/A +uXJZTDNHAgMBAAECggEAH48J3WhOw6LvqYeFBbKMXNY+8FknjCRRiCaliNuVZ4hO +PinP9SvQodZhl1KWG7YNS8hrm54BpHKWB1wO3/pXnzYimBO9GM0XK2EtR/68yKPS +dkZMZRASxQ1Fb9o9Q38T/8JZxeP2jBAA6YMtJsJJP2Cczex0Ky/a7il/CbcVWMJF +VCqHEWCBge59xZifsKiAiK/Yw5W6uyi9OZ9a2D7bzJh0sojPIY90d7EhW4u/QCzk +aXn78RbgxDkQyz5AQrIQzEMcOYr+AxiVT5S1v15FoaoWlm1IrNpEmf63PvwRKPZM +ZW1cqR8onTQBndzAdwn9qHjtuRvhoHMe5RWs4rzDAQKBgQDTq2NGbkNdK14oSu7/ +t+z4Z3nGhHmY9pI1jF5/s3ialO/7YD4ul5MXaJt6dbklkPqsN0vmhPeeavAy6tsG +iU4SdTuptKg5aZMZnDa9zu9lM4raJpDf9AuncffjVFqy9EDII5Wi1UIRDTD8D1gp +LBYuFUTpo7R+JD3yqLXvbOw8UQKBgQDwVkgTqbAwbx35sKhpFo0VOAj3GVZkC6zt +nFS03MmHPjge69u3B3I6oavYtwROq+6S9rj3MLuj4DhVbO5Yxi+XqY5wXhFUPPSp +1ejXF8aAwWtZEeMTTsaN8jl3nfzdNul8G5mVfpY/VmZMhuAXclsAR9ke/x+FcmrQ +Furd0lxIFwKBgQDSXVobzEf817YLW3WuBbBorAY1ysFCyYND3s6oIcjx8KWU8fC6 +w3+3WwpyqX8pm63V7Frtriaede9k2050b498/rAeGGK8NHWylTM+buQzcwdDieKg +AN54Ouc/Mj217tRXVC5KF6JCahbN274lpSAiCpdjkIQ4fXJnsU6ntlwOEQKBgQDr +rCAHsAkGpZ+mPlYWnreADC+2ZtExT8WmRvtFU5AHH7sWj0An7ZRU7D5AR89gefZ7 +hJaCRvZpTzDOi//5a3Y16V200Hl7uj5M4GbvrO/JSGHEuOaMA15uyQ0TQAg6wGMa +gVIMp1IcD9RGzKeoNkoIL2w4mgJF8JnPLfnnxSUaxwKBgQCXP6btCbX7fryeIfUB +PC1TOtyNvNWeoPJNT9eeNHxPC5VW2AC78XKxbHsVec16KJsOgj4Elc3h8/+X0wAU +7Zo9CD7M2i1Tm5sKh90yBsZsU6jBWOBorLQnatDKVPXHLblVAEgK0qTJTAW8hLDn +myYsFbt36qBXf1dVvo+5yhCxAw== +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980969532 (0xf3475512a3c) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:36 2022 GMT + Not After : Mar 11 12:21:36 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c6:b8:04:3d:d6:fa:31:a0:d7:f7:e9:88:4b:5a: + 5e:6f:6f:db:f4:c9:4b:7e:6c:2a:cf:34:7b:2a:ba: + 1a:71:ad:7f:78:6c:f7:1e:ca:07:d0:29:03:49:e4: + 63:86:4c:f6:67:3f:bd:32:69:cb:b8:15:e7:0e:cf: + 28:3d:9e:96:91:8e:4f:73:a9:27:77:4c:26:61:cd: + d6:e7:4e:3c:64:c3:13:ba:8e:ec:03:0f:bc:d4:83: + b3:94:f2:be:d0:18:30:c5:52:49:cb:9a:60:cf:f3: + b9:ca:2f:63:9d:34:ee:87:3a:58:e7:a1:99:dd:dc: + 56:87:e1:a0:d7:6b:37:ae:bb:13:db:7d:fa:2a:3d: + 9c:39:79:f6:01:a6:e3:3a:e7:18:14:cb:c7:57:b9: + 83:d1:ba:b8:2c:5a:c4:97:2f:ee:8d:68:48:37:f8: + 17:db:32:b9:ea:25:4f:28:57:01:39:13:dc:c0:f7: + d0:cc:65:f9:2b:b8:4c:a1:5b:11:ce:44:e2:28:b9: + 63:62:fd:08:fa:b6:cd:49:d5:b9:fe:9e:68:9c:9a: + b5:1a:3e:cc:bf:0e:74:db:52:3f:25:30:cd:7d:02: + 41:c7:c9:8a:58:12:35:25:21:95:c4:6b:c3:f5:79: + c2:00:cb:ef:7f:d7:9f:89:c9:ff:c0:b9:72:59:4c: + 33:47 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 4A:F1:79:1B:13:71:A4:0F:F9:06:CC:B6:2C:CD:24:46:DF:E6:08:2D + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 67:ef:ad:8f:fa:ee:f1:fd:33:67:62:06:5f:09:55:7c:cf:82: + 1a:e8:fc:f5:97:ba:63:bd:d0:a0:8b:85:2c:fc:f0:34:4a:97: + b2:18:d7:63:34:63:f4:1f:50:c7:0e:13:d9:bc:3b:73:3d:41: + 93:16:b3:30:95:88:cd:75:c8:8c:58:4b:ab:96:e6:78:68:15: + 0f:84:e7:8e:17:94:1a:b3:f3:12:ab:26:fd:fa:73:31:33:36: + 85:83:2d:e3:3a:f2:a6:29:c6:37:30:3d:17:d2:39:31:d1:56: + 1b:8d:df:fb:07:ad:81:0b:91:e5:bd:7b:37:a0:a0:5a:2c:33: + 2b:8d:69:8b:d7:c1:45:61:85:ef:32:45:dd:00:a2:81:98:44: + 0d:eb:01:95:fc:ac:0f:b5:34:a4:5f:35:5c:68:63:50:5a:69: + 56:f3:99:c4:67:70:89:13:30:c0:64:ff:f1:a6:77:68:69:63: + 9e:6f:f8:3c:6f:cd:af:7f:de:0d:87:55:ae:39:b3:b2:f5:4f: + 47:79:1f:32:ee:ae:8f:32:dc:88:30:cd:38:6c:4b:28:55:c3: + 7d:74:6b:de:d0:49:c9:05:ea:62:71:a6:f8:1e:76:da:3c:a7: + 17:cd:1a:92:a3:c4:e8:85:d1:ad:34:0c:71:37:3f:6c:d3:7f: + 9a:d6:ca:de +-----BEGIN CERTIFICATE----- +MIIERDCCAyygAwIBAgIGDzR1USo8MA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzZaFw0zMTAzMTExMjIxMzZaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQDGuAQ91voxoNf36YhLWl5vb9v0yUt+bCrPNHsquhpxrX94bPceygfQKQNJ +5GOGTPZnP70yacu4FecOzyg9npaRjk9zqSd3TCZhzdbnTjxkwxO6juwDD7zUg7OU +8r7QGDDFUknLmmDP87nKL2OdNO6HOljnoZnd3FaH4aDXazeuuxPbffoqPZw5efYB +puM65xgUy8dXuYPRurgsWsSXL+6NaEg3+BfbMrnqJU8oVwE5E9zA99DMZfkruEyh +WxHOROIouWNi/Qj6ts1J1bn+nmicmrUaPsy/DnTbUj8lMM19AkHHyYpYEjUlIZXE +a8P1ecIAy+9/15+Jyf/AuXJZTDNHAgMBAAGjggEGMIIBAjAUBgNVHREEDTALggls +b2NhbGhvc3QwCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1Ud +DgQWBBRK8XkbE3GkD/kGzLYszSRG3+YILTAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj +5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcw +AoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1Ud +HwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290 +LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAZ++tj/ru8f0zZ2IGXwlVfM+CGuj89Ze6 +Y73QoIuFLPzwNEqXshjXYzRj9B9Qxw4T2bw7cz1BkxazMJWIzXXIjFhLq5bmeGgV +D4TnjheUGrPzEqsm/fpzMTM2hYMt4zrypinGNzA9F9I5MdFWG43f+wetgQuR5b17 +N6CgWiwzK41pi9fBRWGF7zJF3QCigZhEDesBlfysD7U0pF81XGhjUFppVvOZxGdw +iRMwwGT/8aZ3aGljnm/4PG/Nr3/eDYdVrjmzsvVPR3kfMu6ujzLciDDNOGxLKFXD +fXRr3tBJyQXqYnGm+B522jynF80akqPE6IXRrTQMcTc/bNN/mtbK3g== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..54a07e3f3e496ae4c15d3eb7fc9874ae7ca1a0ab --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.prm @@ -0,0 +1,35 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..000c72163e027da8a50eb39d1439d89a43149649 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..24fe144547a2bec503f387e7953077916a417bb3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxrgEPdb6MaDX9+mIS1pe +b2/b9MlLfmwqzzR7Kroaca1/eGz3HsoH0CkDSeRjhkz2Zz+9MmnLuBXnDs8oPZ6W +kY5Pc6knd0wmYc3W5048ZMMTuo7sAw+81IOzlPK+0BgwxVJJy5pgz/O5yi9jnTTu +hzpY56GZ3dxWh+Gg12s3rrsT2336Kj2cOXn2AabjOucYFMvHV7mD0bq4LFrEly/u +jWhIN/gX2zK56iVPKFcBORPcwPfQzGX5K7hMoVsRzkTiKLljYv0I+rbNSdW5/p5o +nJq1Gj7Mvw5021I/JTDNfQJBx8mKWBI1JSGVxGvD9XnCAMvvf9eficn/wLlyWUwz +RwIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..96a362a6c5ade55e18fad131bf4d4f704dcc3051 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost-sv.pubkey-pinned @@ -0,0 +1 @@ +AAUDLk4c98xcFUDvA9i/MnA9HuO03IPi15r+Cx9OXnc= diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..a944c337549bc4ab476ede9fe375b80e146833d7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crl @@ -0,0 +1,13 @@ +-----BEGIN X509 CRL----- +MIIB9TCB3gIBATANBgkqhkiG9w0BAQsFADBoMQswCQYDVQQGEwJOTjExMC8GA1UE +CgwoRWRlbCBDdXJsIEFyY3RpYyBJbGx1ZGl1bSBSZXNlYXJjaCBDbG91ZDEmMCQG +A1UEAwwdTm9ydGhlcm4gTm93aGVyZSBUcnVzdCBBbmNob3IXDTIyMTIyMzEyMjEz +N1oXDTIzMDEyMjEyMjEzN1owMjAXAgYPNHVRKjwXDTIyMTIyMzEyMjEzNlowFwIG +DzR1UVFhFw0yMjEyMjMxMjIxMzdaoA4wDDAKBgNVHRQEAwIBATANBgkqhkiG9w0B +AQsFAAOCAQEAii+pMstYDtBKHc84kkIEwV+zwGAAJo+jf/AHnqbagpoPKn61ci74 +74Q8BlrYTOksAJhVA/DwFnB8rwGHtGpnDvXtjpVMpvrQSGwi6D6FdjwUkq1aTQrF +AZEHps1FCWYrOprz3YF49xQAKuq6yX+UxJXdUOqXZPgbtdGZBHNAdVK3Hu45C25e +7U1CWKOHRMLyGJ4ynzysf3cUiSqHZG1A+WB6BeSz6guOVyb8I8/VZ+e3whcxAa5+ +YORoKFRS24bO/c9/XBsSC3E6i3kuPg/UVdI726DQwOXBYwtrkESzMsMMgeEXrNFm +j3IyctWm2G/i/WkCNrt3bfTKV4th8tHdlA== +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..7738e5ba6c7775480c1f1569c1fb407b8c5a8265 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.crt @@ -0,0 +1,99 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979553 (0xf3475515161) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:37 2022 GMT + Not After : Mar 11 12:21:37 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:a3:9a:e4:0f:e0:bd:93:a9:5a:a7:5e:ad:85:5e: + d6:e0:98:b4:e9:22:e0:62:90:c3:d9:57:37:16:5d: + 57:3d:68:ca:e2:cf:2f:46:67:1a:0c:af:0e:89:86: + 01:06:df:d6:c9:80:15:0a:43:85:40:3f:da:ee:ee: + 78:09:7c:90:e4:89:63:92:40:0b:22:1c:e2:d3:16: + a9:93:62:e4:04:7a:b0:ab:25:3a:74:02:44:ea:f1: + 31:89:94:29:74:a0:e2:bb:ae:e7:0f:f1:38:6a:87: + 1e:dd:5b:e6:a4:cc:97:ac:d3:01:9a:71:27:a3:22: + 6d:d8:4a:c7:49:5c:16:ae:61:a7:06:3a:90:b4:df: + 71:af:a5:fd:51:46:75:cd:78:e0:0c:52:99:41:4f: + 56:29:a6:a2:a3:dd:d9:7e:29:3e:68:a5:af:c0:34: + b5:73:52:12:04:90:07:1b:f5:8b:a3:71:56:c5:95: + 4e:62:18:d4:ec:e9:4e:90:1b:91:25:bb:32:15:db: + 15:38:59:14:c9:c5:c6:0a:08:aa:2d:f5:67:aa:2f: + eb:97:74:8a:8b:3e:5f:09:27:b0:bf:b3:a3:85:e9: + 7a:f5:39:dc:1d:c7:f4:34:73:d8:f2:ed:b0:c9:1d: + 2a:85:ee:e2:fb:51:09:5e:ff:bf:bc:79:c3:6d:30: + 89:b9 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost.nn + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 85:A2:1D:76:BD:C6:8B:D6:D2:2D:05:77:24:EC:78:7B:70:71:77:C1 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 66:8f:f5:ea:6a:5d:58:b6:50:b0:5b:7b:1f:c1:54:d9:a3:bb: + 36:1b:eb:19:4a:0e:1c:26:43:32:84:de:cb:c9:eb:08:9a:ee: + 9d:d5:a6:62:3e:70:de:61:89:a9:d0:11:20:2a:a6:5c:19:ab: + 91:71:78:f6:5f:ab:e6:03:94:b3:94:42:7b:42:c6:37:f0:4c: + b7:49:5d:90:c5:e3:24:2c:a0:ce:fe:be:71:11:3e:e6:0b:13: + 85:8d:36:e6:db:82:8b:fd:51:a3:3d:42:4c:0d:fd:cf:0b:d8: + 37:ab:f2:e5:53:15:3f:01:d7:a9:78:d5:99:fe:33:88:d7:c6: + 31:dd:bf:b1:d2:e6:31:17:6e:28:91:19:26:36:d7:bc:98:04: + 4c:30:cb:58:ec:b3:c9:1d:22:bf:28:bc:17:6d:2d:5d:36:c3: + e5:12:80:5d:02:4c:61:48:95:a8:77:96:49:e2:17:87:fd:3b: + cc:55:15:0d:b8:13:5e:31:97:05:78:78:7b:0d:8e:3d:ac:25: + 99:81:61:77:c4:a4:a2:25:f1:70:34:17:40:f7:cb:f3:fd:da: + ad:bd:6d:f1:dc:85:0f:dd:4d:21:9e:19:6a:97:b3:43:44:71: + db:74:3f:bf:8a:8d:06:54:48:fd:9e:88:e8:5d:d2:be:ee:b4: + 69:1b:63:11 +-----BEGIN CERTIFICATE----- +MIIESjCCAzKgAwIBAgIGDzR1UVFhMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzdaFw0zMTAzMTExMjIxMzdaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCjmuQP4L2TqVqnXq2FXtbgmLTpIuBikMPZVzcWXVc9aMrizy9GZxoM +rw6JhgEG39bJgBUKQ4VAP9ru7ngJfJDkiWOSQAsiHOLTFqmTYuQEerCrJTp0AkTq +8TGJlCl0oOK7rucP8Thqhx7dW+akzJes0wGacSejIm3YSsdJXBauYacGOpC033Gv +pf1RRnXNeOAMUplBT1YppqKj3dl+KT5opa/ANLVzUhIEkAcb9YujcVbFlU5iGNTs +6U6QG5EluzIV2xU4WRTJxcYKCKot9WeqL+uXdIqLPl8JJ7C/s6OF6Xr1Odwdx/Q0 +c9jy7bDJHSqF7uL7UQle/7+8ecNtMIm5AgMBAAGjggEJMIIBBTAXBgNVHREEEDAO +ggxsb2NhbGhvc3Qubm4wCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMB +MB0GA1UdDgQWBBSFoh12vcaL1tItBXck7Hh7cHF3wTAfBgNVHSMEGDAWgBSHy7Ez +LsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggr +BgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2Vy +MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1 +cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAZo/16mpdWLZQsFt7H8FU2aO7 +NhvrGUoOHCZDMoTey8nrCJrundWmYj5w3mGJqdARICqmXBmrkXF49l+r5gOUs5RC +e0LGN/BMt0ldkMXjJCygzv6+cRE+5gsThY025tuCi/1Roz1CTA39zwvYN6vy5VMV +PwHXqXjVmf4ziNfGMd2/sdLmMRduKJEZJjbXvJgETDDLWOyzyR0ivyi8F20tXTbD +5RKAXQJMYUiVqHeWSeIXh/07zFUVDbgTXjGXBXh4ew2OPawlmYFhd8SkoiXxcDQX +QPfL8/3arb1t8dyFD91NIZ4ZapezQ0Rx23Q/v4qNBlRI/Z6I6F3Svu60aRtjEQ== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..af0d1c485fce3e984a8549a6f5bfc93def2762b4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxFTATBgNVBAMMDGxvY2FsaG9z +dC5ubjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKOa5A/gvZOpWqde +rYVe1uCYtOki4GKQw9lXNxZdVz1oyuLPL0ZnGgyvDomGAQbf1smAFQpDhUA/2u7u +eAl8kOSJY5JACyIc4tMWqZNi5AR6sKslOnQCROrxMYmUKXSg4ruu5w/xOGqHHt1b +5qTMl6zTAZpxJ6MibdhKx0lcFq5hpwY6kLTfca+l/VFGdc144AxSmUFPVimmoqPd +2X4pPmilr8A0tXNSEgSQBxv1i6NxVsWVTmIY1OzpTpAbkSW7MhXbFThZFMnFxgoI +qi31Z6ov65d0ios+XwknsL+zo4XpevU53B3H9DRz2PLtsMkdKoXu4vtRCV7/v7x5 +w20wibkCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQArdsmGDGMvCUZ4dOwsUDdP +C0RCBrgwRM7jQf1f4u2avePF/sl0RYhNLYhGUT2KUqLNs5+j7wKErthD32lWSPpa +orPnibZkEKaO7ZVFUtcN7EOmluXFXsapKilYPDCEeSsHwM5Aaofl8Mkb5e5H+idf +Vea2DuEKFQfumczzaD9JK9tPzsVbJ6FwiPeI46XpH7vrf1DZmauDp83GfAXc1Mrm +dd8QdoGhdNjTi7H+36l1jY+7xnZ+s1vwqxIt4BCf6p6iBy4GHApFaD7bP6dizEUq +weTUXHllb2bgz4cHHvV5n3NXzC6oE9sVw0nLdnfPFiZpGn8VnUW1ZvE3pGcWkAzC +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..10b7e35584c3ee67f8ce186cabd957c269212b61 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..3e4af202edd11f621cbb30cee6aa2cad4e27f437 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCjmuQP4L2TqVqn +Xq2FXtbgmLTpIuBikMPZVzcWXVc9aMrizy9GZxoMrw6JhgEG39bJgBUKQ4VAP9ru +7ngJfJDkiWOSQAsiHOLTFqmTYuQEerCrJTp0AkTq8TGJlCl0oOK7rucP8Thqhx7d +W+akzJes0wGacSejIm3YSsdJXBauYacGOpC033Gvpf1RRnXNeOAMUplBT1YppqKj +3dl+KT5opa/ANLVzUhIEkAcb9YujcVbFlU5iGNTs6U6QG5EluzIV2xU4WRTJxcYK +CKot9WeqL+uXdIqLPl8JJ7C/s6OF6Xr1Odwdx/Q0c9jy7bDJHSqF7uL7UQle/7+8 +ecNtMIm5AgMBAAECggEATTaCwAOfNRtOT4NdfX5fByzK5OSy5ZHQ/LgupX1z+OWG +KzkA5McwAiB0Se9WeLoXko3CYE+xibsZRn6BZGjHsTQuLA3Rs03StzEQ4yBe4MZO +rtcpGSsg/4jJilbEoeh0WYOYRWvg5lXS+UGwPsLYKpaDQTJ6NIHBOb1BBJxTkASA +ti7+uGn5DvRlOgFICBpNzRl83akeV8oLOJAqMZAlGI54jZa+cHkGfkJp+JyMbtjA +zML+oen1BYGHP++uM8fg4bn9bpixpg784qiJJsjzjQVofpZc1CaTJ32hzBCvEYrw +kQS5zhFsEP6fn278VWijFd2QOnxoyergumVOvBbNCQKBgQC+hB56kNGVuPcfSekW +xa5BytDlfAiAvo34N5VhHHNbe/RDtJ2w5z2ZqKg2AL0efWPb4kCMaiXZf9my0Kjm +iRv4LQA/hj1M7W33ubg93LZ9gnVdZSzuslR6CgXoIkmP4GZPF6n7+HxKStmeqBiE +TMc80OVE1ogXbPGcKOjxHvglawKBgQDb1tECQ9TFQtVveys69ycFSjQAFt569mQT +PBnVLtJ8RT3JX5rTKHLmYSl7kNylIzqO43+R8HZLGj09euRjTcKpatNkg7l74/PM +YUDQki8voWfXchpbN9pbRVhuw9TBNUvMiL9pEdoBl85MyDhydD/gC9809ljZyo+y +q8RCrP4yawKBgBXI+cs+IBkky21SgErQU/rF/Fkhc791CrrlcDlojXBanjXXw2hl +KNAXTxTNxNJluDN+ja8AvE9ApV4jKg0ihIY+bxbUfNH9HGQFYqIASQXVEyKY3Sh2 +T96cosxGj27aVBibNh7P7TZ5lKTlx9fpB6dWo8DZXzp+hKo8q1ZXGjz9AoGAdNuy +zKZr8tO9Cv6JE1YPqvMvwyBk8S4KMmNPRBAYmTBhUKr+bOJieW4KlAGEGFAqr4vk +4xnUd8Wh6g1qXBMYt9/uMM8IiP+6N9k2j+g1JveAcHjZ48VD0CKDiJWWgYGoIjhK +rzprDU+5vPztbIG49oq5Ark0r8jKK+q8b8jvcrMCgYB/eTv2L5ReL99Hvrtm5oVE +BkkLS4dr8hnA7QJyo84yy8yq1w5KzOiMpnnK7v6N9NkGMn7Ia8HMqFyGuqaINzlY +NdYt+qoxLXdIDzKTSS91GAwfF25iyptx2DsdY2j2Smhp4put1/QygAbvlwXZy+kG +T8c+FOuI1h2Bg0bSSoTfIQ== +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..4ce5c1e6bc1c50ffa5fcea08363124727433f48e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pem @@ -0,0 +1,162 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost.nn +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCjmuQP4L2TqVqn +Xq2FXtbgmLTpIuBikMPZVzcWXVc9aMrizy9GZxoMrw6JhgEG39bJgBUKQ4VAP9ru +7ngJfJDkiWOSQAsiHOLTFqmTYuQEerCrJTp0AkTq8TGJlCl0oOK7rucP8Thqhx7d +W+akzJes0wGacSejIm3YSsdJXBauYacGOpC033Gvpf1RRnXNeOAMUplBT1YppqKj +3dl+KT5opa/ANLVzUhIEkAcb9YujcVbFlU5iGNTs6U6QG5EluzIV2xU4WRTJxcYK +CKot9WeqL+uXdIqLPl8JJ7C/s6OF6Xr1Odwdx/Q0c9jy7bDJHSqF7uL7UQle/7+8 +ecNtMIm5AgMBAAECggEATTaCwAOfNRtOT4NdfX5fByzK5OSy5ZHQ/LgupX1z+OWG +KzkA5McwAiB0Se9WeLoXko3CYE+xibsZRn6BZGjHsTQuLA3Rs03StzEQ4yBe4MZO +rtcpGSsg/4jJilbEoeh0WYOYRWvg5lXS+UGwPsLYKpaDQTJ6NIHBOb1BBJxTkASA +ti7+uGn5DvRlOgFICBpNzRl83akeV8oLOJAqMZAlGI54jZa+cHkGfkJp+JyMbtjA +zML+oen1BYGHP++uM8fg4bn9bpixpg784qiJJsjzjQVofpZc1CaTJ32hzBCvEYrw +kQS5zhFsEP6fn278VWijFd2QOnxoyergumVOvBbNCQKBgQC+hB56kNGVuPcfSekW +xa5BytDlfAiAvo34N5VhHHNbe/RDtJ2w5z2ZqKg2AL0efWPb4kCMaiXZf9my0Kjm +iRv4LQA/hj1M7W33ubg93LZ9gnVdZSzuslR6CgXoIkmP4GZPF6n7+HxKStmeqBiE +TMc80OVE1ogXbPGcKOjxHvglawKBgQDb1tECQ9TFQtVveys69ycFSjQAFt569mQT +PBnVLtJ8RT3JX5rTKHLmYSl7kNylIzqO43+R8HZLGj09euRjTcKpatNkg7l74/PM +YUDQki8voWfXchpbN9pbRVhuw9TBNUvMiL9pEdoBl85MyDhydD/gC9809ljZyo+y +q8RCrP4yawKBgBXI+cs+IBkky21SgErQU/rF/Fkhc791CrrlcDlojXBanjXXw2hl +KNAXTxTNxNJluDN+ja8AvE9ApV4jKg0ihIY+bxbUfNH9HGQFYqIASQXVEyKY3Sh2 +T96cosxGj27aVBibNh7P7TZ5lKTlx9fpB6dWo8DZXzp+hKo8q1ZXGjz9AoGAdNuy +zKZr8tO9Cv6JE1YPqvMvwyBk8S4KMmNPRBAYmTBhUKr+bOJieW4KlAGEGFAqr4vk +4xnUd8Wh6g1qXBMYt9/uMM8IiP+6N9k2j+g1JveAcHjZ48VD0CKDiJWWgYGoIjhK +rzprDU+5vPztbIG49oq5Ark0r8jKK+q8b8jvcrMCgYB/eTv2L5ReL99Hvrtm5oVE +BkkLS4dr8hnA7QJyo84yy8yq1w5KzOiMpnnK7v6N9NkGMn7Ia8HMqFyGuqaINzlY +NdYt+qoxLXdIDzKTSS91GAwfF25iyptx2DsdY2j2Smhp4put1/QygAbvlwXZy+kG +T8c+FOuI1h2Bg0bSSoTfIQ== +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979553 (0xf3475515161) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:37 2022 GMT + Not After : Mar 11 12:21:37 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost.nn + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:a3:9a:e4:0f:e0:bd:93:a9:5a:a7:5e:ad:85:5e: + d6:e0:98:b4:e9:22:e0:62:90:c3:d9:57:37:16:5d: + 57:3d:68:ca:e2:cf:2f:46:67:1a:0c:af:0e:89:86: + 01:06:df:d6:c9:80:15:0a:43:85:40:3f:da:ee:ee: + 78:09:7c:90:e4:89:63:92:40:0b:22:1c:e2:d3:16: + a9:93:62:e4:04:7a:b0:ab:25:3a:74:02:44:ea:f1: + 31:89:94:29:74:a0:e2:bb:ae:e7:0f:f1:38:6a:87: + 1e:dd:5b:e6:a4:cc:97:ac:d3:01:9a:71:27:a3:22: + 6d:d8:4a:c7:49:5c:16:ae:61:a7:06:3a:90:b4:df: + 71:af:a5:fd:51:46:75:cd:78:e0:0c:52:99:41:4f: + 56:29:a6:a2:a3:dd:d9:7e:29:3e:68:a5:af:c0:34: + b5:73:52:12:04:90:07:1b:f5:8b:a3:71:56:c5:95: + 4e:62:18:d4:ec:e9:4e:90:1b:91:25:bb:32:15:db: + 15:38:59:14:c9:c5:c6:0a:08:aa:2d:f5:67:aa:2f: + eb:97:74:8a:8b:3e:5f:09:27:b0:bf:b3:a3:85:e9: + 7a:f5:39:dc:1d:c7:f4:34:73:d8:f2:ed:b0:c9:1d: + 2a:85:ee:e2:fb:51:09:5e:ff:bf:bc:79:c3:6d:30: + 89:b9 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost.nn + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 85:A2:1D:76:BD:C6:8B:D6:D2:2D:05:77:24:EC:78:7B:70:71:77:C1 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 66:8f:f5:ea:6a:5d:58:b6:50:b0:5b:7b:1f:c1:54:d9:a3:bb: + 36:1b:eb:19:4a:0e:1c:26:43:32:84:de:cb:c9:eb:08:9a:ee: + 9d:d5:a6:62:3e:70:de:61:89:a9:d0:11:20:2a:a6:5c:19:ab: + 91:71:78:f6:5f:ab:e6:03:94:b3:94:42:7b:42:c6:37:f0:4c: + b7:49:5d:90:c5:e3:24:2c:a0:ce:fe:be:71:11:3e:e6:0b:13: + 85:8d:36:e6:db:82:8b:fd:51:a3:3d:42:4c:0d:fd:cf:0b:d8: + 37:ab:f2:e5:53:15:3f:01:d7:a9:78:d5:99:fe:33:88:d7:c6: + 31:dd:bf:b1:d2:e6:31:17:6e:28:91:19:26:36:d7:bc:98:04: + 4c:30:cb:58:ec:b3:c9:1d:22:bf:28:bc:17:6d:2d:5d:36:c3: + e5:12:80:5d:02:4c:61:48:95:a8:77:96:49:e2:17:87:fd:3b: + cc:55:15:0d:b8:13:5e:31:97:05:78:78:7b:0d:8e:3d:ac:25: + 99:81:61:77:c4:a4:a2:25:f1:70:34:17:40:f7:cb:f3:fd:da: + ad:bd:6d:f1:dc:85:0f:dd:4d:21:9e:19:6a:97:b3:43:44:71: + db:74:3f:bf:8a:8d:06:54:48:fd:9e:88:e8:5d:d2:be:ee:b4: + 69:1b:63:11 +-----BEGIN CERTIFICATE----- +MIIESjCCAzKgAwIBAgIGDzR1UVFhMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzdaFw0zMTAzMTExMjIxMzdaMFcxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRUwEwYDVQQDDAxsb2NhbGhvc3Qubm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCjmuQP4L2TqVqnXq2FXtbgmLTpIuBikMPZVzcWXVc9aMrizy9GZxoM +rw6JhgEG39bJgBUKQ4VAP9ru7ngJfJDkiWOSQAsiHOLTFqmTYuQEerCrJTp0AkTq +8TGJlCl0oOK7rucP8Thqhx7dW+akzJes0wGacSejIm3YSsdJXBauYacGOpC033Gv +pf1RRnXNeOAMUplBT1YppqKj3dl+KT5opa/ANLVzUhIEkAcb9YujcVbFlU5iGNTs +6U6QG5EluzIV2xU4WRTJxcYKCKot9WeqL+uXdIqLPl8JJ7C/s6OF6Xr1Odwdx/Q0 +c9jy7bDJHSqF7uL7UQle/7+8ecNtMIm5AgMBAAGjggEJMIIBBTAXBgNVHREEEDAO +ggxsb2NhbGhvc3Qubm4wCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMB +MB0GA1UdDgQWBBSFoh12vcaL1tItBXck7Hh7cHF3wTAfBgNVHSMEGDAWgBSHy7Ez +LsFnfnHj5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggr +BgEFBQcwAoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2Vy +MDgGA1UdHwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1 +cmxSb290LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAZo/16mpdWLZQsFt7H8FU2aO7 +NhvrGUoOHCZDMoTey8nrCJrundWmYj5w3mGJqdARICqmXBmrkXF49l+r5gOUs5RC +e0LGN/BMt0ldkMXjJCygzv6+cRE+5gsThY025tuCi/1Roz1CTA39zwvYN6vy5VMV +PwHXqXjVmf4ziNfGMd2/sdLmMRduKJEZJjbXvJgETDDLWOyzyR0ivyi8F20tXTbD +5RKAXQJMYUiVqHeWSeIXh/07zFUVDbgTXjGXBXh4ew2OPawlmYFhd8SkoiXxcDQX +QPfL8/3arb1t8dyFD91NIZ4ZapezQ0Rx23Q/v4qNBlRI/Z6I6F3Svu60aRtjEQ== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..376fc3a11574f09af99c067840f77a4b49a14526 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.prm @@ -0,0 +1,35 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost.nn +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost.nn diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..af9bcfa4709780ee72c8abc1aeef8935ca3850e5 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..85636ddd57f38fffca030317060a945620f987eb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo5rkD+C9k6lap16thV7W +4Ji06SLgYpDD2Vc3Fl1XPWjK4s8vRmcaDK8OiYYBBt/WyYAVCkOFQD/a7u54CXyQ +5IljkkALIhzi0xapk2LkBHqwqyU6dAJE6vExiZQpdKDiu67nD/E4aoce3VvmpMyX +rNMBmnEnoyJt2ErHSVwWrmGnBjqQtN9xr6X9UUZ1zXjgDFKZQU9WKaaio93Zfik+ +aKWvwDS1c1ISBJAHG/WLo3FWxZVOYhjU7OlOkBuRJbsyFdsVOFkUycXGCgiqLfVn +qi/rl3SKiz5fCSewv7Ojhel69TncHcf0NHPY8u2wyR0qhe7i+1EJXv+/vHnDbTCJ +uQIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..ce49b285790f4f2043d2e514966ea7ff3bfe5594 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost.nn-sv.pubkey-pinned @@ -0,0 +1 @@ +YRy84GLJxpJBGddJjhnqze5DJhkOUWytnCEqS0u0mTA= diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..f1d44014981468cdcde69b88e9e92243278528cd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crl @@ -0,0 +1,14 @@ +-----BEGIN X509 CRL----- +MIICDjCB9wIBATANBgkqhkiG9w0BAQsFADBoMQswCQYDVQQGEwJOTjExMC8GA1UE +CgwoRWRlbCBDdXJsIEFyY3RpYyBJbGx1ZGl1bSBSZXNlYXJjaCBDbG91ZDEmMCQG +A1UEAwwdTm9ydGhlcm4gTm93aGVyZSBUcnVzdCBBbmNob3IXDTIyMTIyMzEyMjEz +N1oXDTIzMDEyMjEyMjEzN1owSzAXAgYPNHVRKjwXDTIyMTIyMzEyMjEzNlowFwIG +DzR1UVFhFw0yMjEyMjMxMjIxMzdaMBcCBg80dVFRdRcNMjIxMjIzMTIyMTM3WqAO +MAwwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQADggEBAEYPECPj+TzlRKUcYBwN +SWqSBzua1dBket0sNYYnm2Jvst27guK10XwGcD4Jei7VDdTXfxLiXMQahWO/SIUE +ZGrFhU6vdq7rSk179acREDYFgYDNxgSKgyU4SjzTJ+VantWs+ky0lsyiu2Sh8B4G +bDmG4mEPXPykHufpbmkUCLqFd89JiuhNTripOUzJfAWLDPPYf4gn2ktenz/hFwJA +o5CSWsn13iO+9NRVJ/5ErIuoLEdGzRVoCfDNKAJ2XE0ZhRPclmRHThaoxRnBeQFg +AVGB+xLd3BSZQuOw3pxn4smGXg/9BW3qEba5W24P4WA4ldw2j4q8WviOygvUVBQ7 +pCw= +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..e9892d0430032606f2af7750a597ff37b5b773b4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.crt @@ -0,0 +1,99 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979573 (0xf3475515175) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:37 2022 GMT + Not After : Mar 11 12:21:37 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:df:29:93:58:82:1d:a2:b8:07:2a:b2:8f:93:0e: + df:15:49:72:06:93:19:4a:2d:c5:bd:56:92:5a:da: + f4:d3:9a:01:1c:ee:47:57:0e:9e:d8:d7:0d:c4:ce: + 4b:a2:f0:fc:07:ec:91:e9:95:08:f4:e9:5d:f2:49: + f3:0b:98:f0:d8:c7:d4:67:2f:fb:f2:94:3b:14:c8: + 06:da:39:70:8a:f9:4b:70:a8:74:6b:3f:5b:d1:a4: + 1c:ea:bd:f1:9e:c1:e2:e7:98:88:4f:e9:4b:b6:c8: + d6:9e:01:f3:b7:c9:ee:cd:e2:d7:96:68:14:d7:44: + c6:11:13:9f:6c:06:4e:57:98:53:c8:40:de:9d:44: + 1f:6a:f4:01:b0:56:47:5e:3b:b5:3c:29:9b:96:f3: + 9a:5a:78:d1:11:51:25:0e:43:82:4a:d3:df:54:5a: + 46:00:de:b0:a2:2e:65:54:44:40:9c:64:d3:e8:3f: + e8:ac:e3:0c:fb:36:0a:c5:79:37:a9:a2:ef:06:14: + 43:ac:9e:20:de:30:d2:ea:79:7d:ef:f2:0c:93:70: + 8d:bb:14:ff:4c:56:41:e4:2a:de:92:0a:ce:65:2c: + d3:fb:29:0f:4f:f9:16:d7:62:54:4e:4c:a8:05:34: + 5d:e6:20:e3:89:bc:7b:1f:df:21:57:66:a9:20:ce: + e6:b3 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + 0 ..localhost.h + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 6B:56:00:F3:01:BC:16:8B:EB:CF:75:A1:89:DB:26:B1:C4:ED:71:64 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 5a:b2:83:c0:94:ce:25:aa:a0:f4:b6:71:fb:16:b4:e0:10:3c: + 9c:a0:db:2a:fc:b7:f8:97:64:cc:19:92:56:63:a9:e6:50:d6: + 6d:79:b6:a3:62:23:d2:48:21:37:46:46:3e:9d:cd:1f:55:18: + 77:fd:7f:35:ea:d8:68:9c:1c:2f:c8:23:43:a2:cd:77:3c:5c: + 21:94:93:80:84:d0:6a:8a:5b:ae:11:be:79:3e:80:17:32:9e: + 73:0b:dd:0d:f5:f6:4f:3f:1b:a3:eb:aa:21:06:a7:ef:c7:bf: + e5:87:67:2c:38:a3:c1:d4:f2:b4:ce:72:9d:2e:f8:b9:91:cb: + 83:1a:c9:be:74:bb:ac:78:5c:d9:3e:fd:1f:9d:ac:19:5e:b3: + 00:66:38:71:7e:06:2e:fe:1a:c0:ad:f7:82:1d:85:6d:3d:3c: + 9d:62:66:cd:1e:6d:f1:67:7a:05:4a:58:6e:7a:a7:1f:2f:7c: + 5f:c0:2c:19:df:de:c6:2d:13:c6:3b:ea:6d:98:d0:55:98:4c: + 00:a7:e2:2f:7d:86:24:49:2d:86:c3:75:d0:71:41:16:8c:7b: + 49:25:eb:d2:cd:9b:08:b4:5f:6e:aa:4a:2d:6c:5b:89:67:7f: + 3f:0c:43:43:bd:83:f7:ef:1e:ee:e7:6a:e7:3a:c1:c7:aa:1d: + 5b:34:1b:d1 +-----BEGIN CERTIFICATE----- +MIIERjCCAy6gAwIBAgIGDzR1UVF1MA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzdaFw0zMTAzMTExMjIxMzdaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQDfKZNYgh2iuAcqso+TDt8VSXIGkxlKLcW9VpJa2vTTmgEc7kdXDp7Y1w3E +zkui8PwH7JHplQj06V3ySfMLmPDYx9RnL/vylDsUyAbaOXCK+UtwqHRrP1vRpBzq +vfGeweLnmIhP6Uu2yNaeAfO3ye7N4teWaBTXRMYRE59sBk5XmFPIQN6dRB9q9AGw +VkdeO7U8KZuW85paeNERUSUOQ4JK099UWkYA3rCiLmVURECcZNPoP+is4wz7NgrF +eTepou8GFEOsniDeMNLqeX3v8gyTcI27FP9MVkHkKt6SCs5lLNP7KQ9P+RbXYlRO +TKgFNF3mIOOJvHsf3yFXZqkgzuazAgMBAAGjggEIMIIBBDAWBgNVHREEDzANggts +b2NhbGhvc3QAaDALBgNVHQ8EBAMCA6gwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYD +VR0OBBYEFGtWAPMBvBaL6891oYnbJrHE7XFkMB8GA1UdIwQYMBaAFIfLsTMuwWd+ +cePlK0xNpLNu0lupMAkGA1UdEwQCMAAwQwYIKwYBBQUHAQEENzA1MDMGCCsGAQUF +BzAChidodHRwOi8vdGVzdC5jdXJsLnNlL2NhL0VkZWxDdXJsUm9vdC5jZXIwOAYD +VR0fBDEwLzAtoCugKYYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJv +b3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQBasoPAlM4lqqD0tnH7FrTgEDycoNsq +/Lf4l2TMGZJWY6nmUNZtebajYiPSSCE3RkY+nc0fVRh3/X816thonBwvyCNDos13 +PFwhlJOAhNBqiluuEb55PoAXMp5zC90N9fZPPxuj66ohBqfvx7/lh2csOKPB1PK0 +znKdLvi5kcuDGsm+dLuseFzZPv0fnawZXrMAZjhxfgYu/hrArfeCHYVtPTydYmbN +Hm3xZ3oFSlhueqcfL3xfwCwZ397GLRPGO+ptmNBVmEwAp+IvfYYkSS2Gw3XQcUEW +jHtJJevSzZsItF9uqkotbFuJZ38/DENDvYP37x7u52rnOsHHqh1bNBvR +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..d2a021e58cb9c61f978cff97b116e0255da12a02 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICmTCCAYECAQAwVDELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxEjAQBgNVBAMMCWxvY2FsaG9z +dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN8pk1iCHaK4Byqyj5MO +3xVJcgaTGUotxb1Wklra9NOaARzuR1cOntjXDcTOS6Lw/AfskemVCPTpXfJJ8wuY +8NjH1Gcv+/KUOxTIBto5cIr5S3CodGs/W9GkHOq98Z7B4ueYiE/pS7bI1p4B87fJ +7s3i15ZoFNdExhETn2wGTleYU8hA3p1EH2r0AbBWR147tTwpm5bzmlp40RFRJQ5D +gkrT31RaRgDesKIuZVREQJxk0+g/6KzjDPs2CsV5N6mi7wYUQ6yeIN4w0up5fe/y +DJNwjbsU/0xWQeQq3pIKzmUs0/spD0/5FtdiVE5MqAU0XeYg44m8ex/fIVdmqSDO +5rMCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQAMIFsOpe5YFYwa7F2qr1CoBYhR +XNOEK5Yc6pY4ND+/1hbsSkT285Ar7yIA4+fFwYa4F4DkpzfZ0DLwHPqQE85pQf2M +YyjwMIU97xwNKLHrrObpgVJ+hs8cDj0zYJVGnIWiK1556I5lotupuzzig7Fyo0XY +OSbg+NxaXMHil4eLWIs8CapWAU4gHcZnDpkYL86aWfeFAYixB/FkcAzZJR+fOSif +KYTc0kKR34nDpJVN1pck03tCvRY48SRliHnNpAP/Enf57BLSJvA15f64Iz3hthxL +47xJsj2zs+CkHvfYnaLhDpTlOxr73uK4dhWcyynufvjElO2G+MOMcFRduWU6 +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..cdadd76bb4393a20e698f1974fdd96299818cd37 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..0e0533ec377d51f25fb453cd41d6ef67bd195450 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDfKZNYgh2iuAcq +so+TDt8VSXIGkxlKLcW9VpJa2vTTmgEc7kdXDp7Y1w3Ezkui8PwH7JHplQj06V3y +SfMLmPDYx9RnL/vylDsUyAbaOXCK+UtwqHRrP1vRpBzqvfGeweLnmIhP6Uu2yNae +AfO3ye7N4teWaBTXRMYRE59sBk5XmFPIQN6dRB9q9AGwVkdeO7U8KZuW85paeNER +USUOQ4JK099UWkYA3rCiLmVURECcZNPoP+is4wz7NgrFeTepou8GFEOsniDeMNLq +eX3v8gyTcI27FP9MVkHkKt6SCs5lLNP7KQ9P+RbXYlROTKgFNF3mIOOJvHsf3yFX +ZqkgzuazAgMBAAECggEAa31sIpKx0aHQmeleLJhaLbetu6r44HkBqPxdDHQwvweM +B7JiHHXHX2zejfBMEFUBIJP7iEYoBUeu37hs4CYvxEskbPt44NQzTQQ4AL7wDZCc +nMwXH11qTaU95HfPPQfo0mLvLYaS2J0Oexc3nEwgwXzFGQZTG4ld2fXYsUCsVZX8 +PoHbkKWEHveQEFDmGezguc2UG3DrXaZv5gbMhVik048zX3P5cn0ic9TK9yEFZDXS +8Qiq/SHTHEnkZV5J8s12pcDyQdi1cN96MVZ1/feeg1Pc06q7PN7xvkmZHCQ1tOdl +b7STXNPrJ0P7OwbeB0Q3xNwqI25wicN1oaBvdR/PAQKBgQD4gN6+sR74FNC4q99T +fuFqwJ36W8GG0jc9joJTbITXGSdArQHm838Mippp0P3MrUTLqXI0nhjH8ePjF83R +KRWGoUvSc2Xe7LjzzEmg9CmtB+QD97Qir0468izqnlP1Ef16kbbIMLsoVgIht6YY +klUYs7x3AtDBvHV7EKlP63kUgQKBgQDl5QDW+KZRvQU/G7tWsOZ6iQ3Ed8Zt4uRk +EshPeCoz0S0ks8pzpa+YaAAUKsHvgiL7oLMFquuVHn7TctYBoe2/bwdj0/IW/1pP +oDJqRJIbamjYj6qKG7Ihx0yx+z7f7vbKCgC5ifzy0Xl60E9fRIf3/dVopU+3qtwG +qOphkrNRMwKBgQCrEixFIjGrnsjBGLC5DhOoJcmbXCcx5O1aVwyo2X/pg8td3rv8 +fYvs2k3KorDVgkJl4dRZHKz6mC7FWtG5N4s2DzvfOMncWSJJ00ysnOlD0LbLdG5x +ojU8pxL8wNoTT7sr8bvevI1bCzqUc5TIPZSPWMxZMXr8o/xMKAAmoHfOAQKBgDBH +VlTO5Qa3XlmxdjcvcUd8bsK6sJY1FueZNi3SO3KkVAmoJDUDL4wfEx0pGY810ijr +x4zCJzUqsVGwhRbUrbwNEg053lZMC+g66Tt96P0O7LPF//d+93q2gvnBnKOkaHln +fl14iAFqUkujYXfNSYyf5uhSBxq4K/rOEGKrTzMXAoGBAL3Hz3s5Gvy44SMV0UHl +18gEqR0y9mXfgON9Rk0yE+fFYFRnFf4iHIxhodXPIGeu1CpqtXjEcG8JXVXniaao +qNGbVs2QoBUVW81sHG9h/ulHCAwjFvZhFYgDiRQPcVd3lNJM4gigjRyw/nRnQH+2 +MVCJe5htDEMM58h8LepU4T8M +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..9c4c9632adac6e3ff1879a47adc153c6cfe1da1b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pem @@ -0,0 +1,163 @@ +extensions = x509v3 + +[ x509v3 ] +#subjectAltName = DNS:localhost\0h +subjectAltName = DER:30:0d:82:0b:6c:6f:63:61:6c:68:6f:73:74:00:68 +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDfKZNYgh2iuAcq +so+TDt8VSXIGkxlKLcW9VpJa2vTTmgEc7kdXDp7Y1w3Ezkui8PwH7JHplQj06V3y +SfMLmPDYx9RnL/vylDsUyAbaOXCK+UtwqHRrP1vRpBzqvfGeweLnmIhP6Uu2yNae +AfO3ye7N4teWaBTXRMYRE59sBk5XmFPIQN6dRB9q9AGwVkdeO7U8KZuW85paeNER +USUOQ4JK099UWkYA3rCiLmVURECcZNPoP+is4wz7NgrFeTepou8GFEOsniDeMNLq +eX3v8gyTcI27FP9MVkHkKt6SCs5lLNP7KQ9P+RbXYlROTKgFNF3mIOOJvHsf3yFX +ZqkgzuazAgMBAAECggEAa31sIpKx0aHQmeleLJhaLbetu6r44HkBqPxdDHQwvweM +B7JiHHXHX2zejfBMEFUBIJP7iEYoBUeu37hs4CYvxEskbPt44NQzTQQ4AL7wDZCc +nMwXH11qTaU95HfPPQfo0mLvLYaS2J0Oexc3nEwgwXzFGQZTG4ld2fXYsUCsVZX8 +PoHbkKWEHveQEFDmGezguc2UG3DrXaZv5gbMhVik048zX3P5cn0ic9TK9yEFZDXS +8Qiq/SHTHEnkZV5J8s12pcDyQdi1cN96MVZ1/feeg1Pc06q7PN7xvkmZHCQ1tOdl +b7STXNPrJ0P7OwbeB0Q3xNwqI25wicN1oaBvdR/PAQKBgQD4gN6+sR74FNC4q99T +fuFqwJ36W8GG0jc9joJTbITXGSdArQHm838Mippp0P3MrUTLqXI0nhjH8ePjF83R +KRWGoUvSc2Xe7LjzzEmg9CmtB+QD97Qir0468izqnlP1Ef16kbbIMLsoVgIht6YY +klUYs7x3AtDBvHV7EKlP63kUgQKBgQDl5QDW+KZRvQU/G7tWsOZ6iQ3Ed8Zt4uRk +EshPeCoz0S0ks8pzpa+YaAAUKsHvgiL7oLMFquuVHn7TctYBoe2/bwdj0/IW/1pP +oDJqRJIbamjYj6qKG7Ihx0yx+z7f7vbKCgC5ifzy0Xl60E9fRIf3/dVopU+3qtwG +qOphkrNRMwKBgQCrEixFIjGrnsjBGLC5DhOoJcmbXCcx5O1aVwyo2X/pg8td3rv8 +fYvs2k3KorDVgkJl4dRZHKz6mC7FWtG5N4s2DzvfOMncWSJJ00ysnOlD0LbLdG5x +ojU8pxL8wNoTT7sr8bvevI1bCzqUc5TIPZSPWMxZMXr8o/xMKAAmoHfOAQKBgDBH +VlTO5Qa3XlmxdjcvcUd8bsK6sJY1FueZNi3SO3KkVAmoJDUDL4wfEx0pGY810ijr +x4zCJzUqsVGwhRbUrbwNEg053lZMC+g66Tt96P0O7LPF//d+93q2gvnBnKOkaHln +fl14iAFqUkujYXfNSYyf5uhSBxq4K/rOEGKrTzMXAoGBAL3Hz3s5Gvy44SMV0UHl +18gEqR0y9mXfgON9Rk0yE+fFYFRnFf4iHIxhodXPIGeu1CpqtXjEcG8JXVXniaao +qNGbVs2QoBUVW81sHG9h/ulHCAwjFvZhFYgDiRQPcVd3lNJM4gigjRyw/nRnQH+2 +MVCJe5htDEMM58h8LepU4T8M +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980979573 (0xf3475515175) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:37 2022 GMT + Not After : Mar 11 12:21:37 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:df:29:93:58:82:1d:a2:b8:07:2a:b2:8f:93:0e: + df:15:49:72:06:93:19:4a:2d:c5:bd:56:92:5a:da: + f4:d3:9a:01:1c:ee:47:57:0e:9e:d8:d7:0d:c4:ce: + 4b:a2:f0:fc:07:ec:91:e9:95:08:f4:e9:5d:f2:49: + f3:0b:98:f0:d8:c7:d4:67:2f:fb:f2:94:3b:14:c8: + 06:da:39:70:8a:f9:4b:70:a8:74:6b:3f:5b:d1:a4: + 1c:ea:bd:f1:9e:c1:e2:e7:98:88:4f:e9:4b:b6:c8: + d6:9e:01:f3:b7:c9:ee:cd:e2:d7:96:68:14:d7:44: + c6:11:13:9f:6c:06:4e:57:98:53:c8:40:de:9d:44: + 1f:6a:f4:01:b0:56:47:5e:3b:b5:3c:29:9b:96:f3: + 9a:5a:78:d1:11:51:25:0e:43:82:4a:d3:df:54:5a: + 46:00:de:b0:a2:2e:65:54:44:40:9c:64:d3:e8:3f: + e8:ac:e3:0c:fb:36:0a:c5:79:37:a9:a2:ef:06:14: + 43:ac:9e:20:de:30:d2:ea:79:7d:ef:f2:0c:93:70: + 8d:bb:14:ff:4c:56:41:e4:2a:de:92:0a:ce:65:2c: + d3:fb:29:0f:4f:f9:16:d7:62:54:4e:4c:a8:05:34: + 5d:e6:20:e3:89:bc:7b:1f:df:21:57:66:a9:20:ce: + e6:b3 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + 0 ..localhost.h + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 6B:56:00:F3:01:BC:16:8B:EB:CF:75:A1:89:DB:26:B1:C4:ED:71:64 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 5a:b2:83:c0:94:ce:25:aa:a0:f4:b6:71:fb:16:b4:e0:10:3c: + 9c:a0:db:2a:fc:b7:f8:97:64:cc:19:92:56:63:a9:e6:50:d6: + 6d:79:b6:a3:62:23:d2:48:21:37:46:46:3e:9d:cd:1f:55:18: + 77:fd:7f:35:ea:d8:68:9c:1c:2f:c8:23:43:a2:cd:77:3c:5c: + 21:94:93:80:84:d0:6a:8a:5b:ae:11:be:79:3e:80:17:32:9e: + 73:0b:dd:0d:f5:f6:4f:3f:1b:a3:eb:aa:21:06:a7:ef:c7:bf: + e5:87:67:2c:38:a3:c1:d4:f2:b4:ce:72:9d:2e:f8:b9:91:cb: + 83:1a:c9:be:74:bb:ac:78:5c:d9:3e:fd:1f:9d:ac:19:5e:b3: + 00:66:38:71:7e:06:2e:fe:1a:c0:ad:f7:82:1d:85:6d:3d:3c: + 9d:62:66:cd:1e:6d:f1:67:7a:05:4a:58:6e:7a:a7:1f:2f:7c: + 5f:c0:2c:19:df:de:c6:2d:13:c6:3b:ea:6d:98:d0:55:98:4c: + 00:a7:e2:2f:7d:86:24:49:2d:86:c3:75:d0:71:41:16:8c:7b: + 49:25:eb:d2:cd:9b:08:b4:5f:6e:aa:4a:2d:6c:5b:89:67:7f: + 3f:0c:43:43:bd:83:f7:ef:1e:ee:e7:6a:e7:3a:c1:c7:aa:1d: + 5b:34:1b:d1 +-----BEGIN CERTIFICATE----- +MIIERjCCAy6gAwIBAgIGDzR1UVF1MA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzdaFw0zMTAzMTExMjIxMzdaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQDfKZNYgh2iuAcqso+TDt8VSXIGkxlKLcW9VpJa2vTTmgEc7kdXDp7Y1w3E +zkui8PwH7JHplQj06V3ySfMLmPDYx9RnL/vylDsUyAbaOXCK+UtwqHRrP1vRpBzq +vfGeweLnmIhP6Uu2yNaeAfO3ye7N4teWaBTXRMYRE59sBk5XmFPIQN6dRB9q9AGw +VkdeO7U8KZuW85paeNERUSUOQ4JK099UWkYA3rCiLmVURECcZNPoP+is4wz7NgrF +eTepou8GFEOsniDeMNLqeX3v8gyTcI27FP9MVkHkKt6SCs5lLNP7KQ9P+RbXYlRO +TKgFNF3mIOOJvHsf3yFXZqkgzuazAgMBAAGjggEIMIIBBDAWBgNVHREEDzANggts +b2NhbGhvc3QAaDALBgNVHQ8EBAMCA6gwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYD +VR0OBBYEFGtWAPMBvBaL6891oYnbJrHE7XFkMB8GA1UdIwQYMBaAFIfLsTMuwWd+ +cePlK0xNpLNu0lupMAkGA1UdEwQCMAAwQwYIKwYBBQUHAQEENzA1MDMGCCsGAQUF +BzAChidodHRwOi8vdGVzdC5jdXJsLnNlL2NhL0VkZWxDdXJsUm9vdC5jZXIwOAYD +VR0fBDEwLzAtoCugKYYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJv +b3QuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQBasoPAlM4lqqD0tnH7FrTgEDycoNsq +/Lf4l2TMGZJWY6nmUNZtebajYiPSSCE3RkY+nc0fVRh3/X816thonBwvyCNDos13 +PFwhlJOAhNBqiluuEb55PoAXMp5zC90N9fZPPxuj66ohBqfvx7/lh2csOKPB1PK0 +znKdLvi5kcuDGsm+dLuseFzZPv0fnawZXrMAZjhxfgYu/hrArfeCHYVtPTydYmbN +Hm3xZ3oFSlhueqcfL3xfwCwZ397GLRPGO+ptmNBVmEwAp+IvfYYkSS2Gw3XQcUEW +jHtJJevSzZsItF9uqkotbFuJZ38/DENDvYP37x7u52rnOsHHqh1bNBvR +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..4285341763166bbc4832aaa3f19f5ba8e12f5beb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.prm @@ -0,0 +1,36 @@ +extensions = x509v3 + +[ x509v3 ] +#subjectAltName = DNS:localhost\0h +subjectAltName = DER:30:0d:82:0b:6c:6f:63:61:6c:68:6f:73:74:00:68 +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 1024 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..5c0e00d056456f317df7a06096adbb5061307092 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..b8a1ee9e2c10ae324993e1a12919b10d6c9fbbb7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3ymTWIIdorgHKrKPkw7f +FUlyBpMZSi3FvVaSWtr005oBHO5HVw6e2NcNxM5LovD8B+yR6ZUI9Old8knzC5jw +2MfUZy/78pQ7FMgG2jlwivlLcKh0az9b0aQc6r3xnsHi55iIT+lLtsjWngHzt8nu +zeLXlmgU10TGEROfbAZOV5hTyEDenUQfavQBsFZHXju1PCmblvOaWnjREVElDkOC +StPfVFpGAN6woi5lVERAnGTT6D/orOMM+zYKxXk3qaLvBhRDrJ4g3jDS6nl97/IM +k3CNuxT/TFZB5CrekgrOZSzT+ykPT/kW12JUTkyoBTRd5iDjibx7H98hV2apIM7m +swIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..0347fc0f5e9d56c4cbf75d38db5c94907e2362ca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/Server-localhost0h-sv.pubkey-pinned @@ -0,0 +1 @@ +uWdzTJv+PXoad5XzSPC85Nm6FcqVkGl+8tTRW5KCLbA= diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/scripts/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..82b5f277eb09b7af3858abc9fa7683d1e5572604 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/Makefile.am @@ -0,0 +1,30 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 + +SCRIPTFILES = \ + genroot.sh \ + genserv.sh + +EXTRA_DIST = $(SCRIPTFILES) diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genroot.sh b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genroot.sh new file mode 100644 index 0000000000000000000000000000000000000000..86afb1853492516cd43a178bb94ea7cff33dd49f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genroot.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) EdelWeb for EdelKey and OpenEvidence +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# exit on first fail +set -eu + +OPENSSL=openssl +if [ -f /usr/local/ssl/bin/openssl ]; then + OPENSSL=/usr/local/ssl/bin/openssl +fi + +command -v "$OPENSSL" +"$OPENSSL" version + +USAGE='echo Usage is genroot.sh ' + +HOME=$(pwd) +cd "$HOME" + +KEYSIZE=2048 +DURATION=6000 +# The -sha256 option was introduced in OpenSSL 1.0.1 +DIGESTALGO=-sha256 + +NOTOK= + +PREFIX="${1:-}" +if [ -z "$PREFIX" ]; then + echo 'No configuration prefix' + NOTOK=1 +else + if [ ! -f "$PREFIX-ca.prm" ]; then + echo "No configuration file $PREFIX-ca.prm" + NOTOK=1 + fi +fi + +if [ -n "$NOTOK" ]; then + echo 'Sorry, I cannot do that for you.' + $USAGE + exit +fi + +echo "PREFIX=$PREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE" + +set -x + +"$OPENSSL" genrsa -out "$PREFIX-ca.key" -passout fd:0 "$KEYSIZE" < "$PREFIX-ca.cacert" +"$OPENSSL" x509 -in "$PREFIX-ca.cacert" -outform der -out "$PREFIX-ca.der" +"$OPENSSL" x509 -in "$PREFIX-ca.cacert" -text -nameopt multiline > "$PREFIX-ca.crt" +"$OPENSSL" x509 -noout -text -in "$PREFIX-ca.cacert" -nameopt multiline +# "$OPENSSL" rsa -in "../keys/$PREFIX-ca.key" -text -noout -pubout diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genserv.sh b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genserv.sh new file mode 100644 index 0000000000000000000000000000000000000000..73e4978363c0844da5d61b98fb025215981c651a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/scripts/genserv.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) EdelWeb for EdelKey and OpenEvidence +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# exit on first fail +set -eu + +OPENSSL=openssl +if [ -f /usr/local/ssl/bin/openssl ]; then + OPENSSL=/usr/local/ssl/bin/openssl +fi + +command -v "$OPENSSL" +"$OPENSSL" version + +USAGE='echo Usage is genserv.sh ' + +HOME=$(pwd) +cd "$HOME" + +KEYSIZE=2048 +DURATION=300 +# The -sha256 option was introduced in OpenSSL 1.0.1 +DIGESTALGO=-sha256 + +REQ=YES +P12=NO +DHP=NO + +NOTOK= + +PREFIX="${1:-}" +if [ -z "$PREFIX" ]; then + echo 'No configuration prefix' + NOTOK=1 +else + if [ ! -f "$PREFIX-sv.prm" ]; then + echo "No configuration file $PREFIX-sv.prm" + NOTOK=1 + fi +fi + +CAPREFIX="${2:-}" +if [ -z "$CAPREFIX" ]; then + echo 'No CA prefix' + NOTOK=1 +else + if [ ! -f "$CAPREFIX-ca.cacert" ]; then + echo "No CA certificate file $CAPREFIX-ca.caert" + NOTOK=1 + fi + if [ ! -f "$CAPREFIX-ca.key" ]; then + echo "No $CAPREFIX key" + NOTOK=1 + fi +fi + +if [ -n "$NOTOK" ]; then + echo 'Sorry, I cannot do that for you.' + $USAGE + exit +fi + +echo "PREFIX=$PREFIX CAPREFIX=$CAPREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE" + +set -x + +if [ "$DHP" = YES ]; then + "$OPENSSL" dhparam -2 -out "$PREFIX-sv.dhp" "$KEYSIZE" +fi +if [ "$REQ" = YES ]; then + "$OPENSSL" req -config "$PREFIX-sv.prm" -newkey "rsa:$KEYSIZE" -keyout "$PREFIX-sv.key" -out "$PREFIX-sv.csr" -passout fd:0 < "$PREFIX-sv.crt" + +if [ "$P12" = YES ]; then + "$OPENSSL" pkcs12 -export -des3 -out "$PREFIX-sv.p12" -caname "$CAPREFIX" -name "$PREFIX" -inkey "$PREFIX-sv.key" -in "$PREFIX-sv.crt" -certfile "$CAPREFIX-ca.crt" +fi + +"$OPENSSL" x509 -noout -text -hash -in "$PREFIX-sv.crt" -nameopt multiline + +# revoke server cert +touch "$CAPREFIX-ca.db" +echo 01 > "$CAPREFIX-ca.cnt" +"$OPENSSL" ca -config "$CAPREFIX-ca.cnf" -revoke "$PREFIX-sv.crt" + +# issue CRL +"$OPENSSL" ca -config "$CAPREFIX-ca.cnf" -gencrl -out "$PREFIX-sv.crl" + +"$OPENSSL" x509 -in "$PREFIX-sv.crt" -outform der -out "$PREFIX-sv.der" + +# all together now +touch "$PREFIX-sv.dhp" +cat "$PREFIX-sv.prm" "$PREFIX-sv.key" "$PREFIX-sv.crt" "$PREFIX-sv.dhp" > "$PREFIX-sv.pem" +chmod o-r "$PREFIX-sv.prm" + +"$OPENSSL" x509 -in "$PREFIX-sv.pem" -pubkey -noout | \ +"$OPENSSL" pkey -pubin -outform der | "$OPENSSL" dgst -sha256 -binary | \ +"$OPENSSL" enc -base64 > "$PREFIX-sv.pubkey-pinned" + +echo "$PREFIX-sv.pem done" diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-conf b/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-conf new file mode 100644 index 0000000000000000000000000000000000000000..67825ceabd9fd607b933ee366d4d99189697e605 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-conf @@ -0,0 +1,3 @@ +1:Ewl2hcjiutMd3Fu2lgFnUXWSc67TVyy2vwYCKoS9MLsrdJVT9RgWTCuEqWJrfB6uE3LsE9GkOlaZabS7M29sj5TnzUqOLJMjiwEzArfiLr9WbMRANlF68N5AVLcPWvNx6Zjl3m5Scp0BzJBz9TkgfhzKJZ.WtP3Mv/67I/0wmRZ:2 +2:dUyyhxav9tgnyIg65wHxkzkb7VIPh4o0lkwfOKiPp4rVJrzLRYVBtb76gKlaO7ef5LYGEw3G.4E0jbMxcYBetDy2YdpiP/3GWJInoBbvYHIRO9uBuxgsFKTKWu7RnR7yTau/IrFTdQ4LY/q.AvoCzMxV0PKvD9Odso/LFIItn8PbTov3VMn/ZEH2SqhtpBUkWtmcIkEflhX/YY/fkBKfBbe27/zUaKUUZEUYZ2H2nlCL60.JIPeZJSzsu/xHDVcx:2 +3:2iQzj1CagQc/5ctbuJYLWlhtAsPHc7xWVyCPAKFRLWKADpASkqe9djWPFWTNTdeJtL8nAhImCn3Sr/IAdQ1FrGw0WvQUstPx3FO9KNcXOwisOQ1VlL.gheAHYfbYyBaxXL.NcJx9TUwgWDT0hRzFzqSrdGGTN3FgSTA1v4QnHtEygNj3eZ.u0MThqWUaDiP87nqha7XnT66bkTCkQ8.7T8L4KZjIImrNrUftedTTBi.WCi.zlrBxDuOM0da0JbUkQlXqvp0yvJAPpC11nxmmZOAbQOywZGmu9nhZNuwTlxjfIro0FOdthaDTuZRL9VL7MRPUDo/DQEyW.d4H.UIlzp:2 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-db b/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-db new file mode 100644 index 0000000000000000000000000000000000000000..2f851a342dc6e8cff469678228572baa2e08b5d1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/srp-verifier-db @@ -0,0 +1,2 @@ +jsmith:34fPk7u.w3R/M1k2sQ9F.04GZqLKAsqDn44CHGu7ML0M8VWwu1p79OLxi6jRhSNdSM46Kx9GRVyJLXz7eok53..A6X5p3NdnMSYX8WwYrDmuseHDr.eua7gjd04S4EoY4ZuKix2.WGAsMTwk86AmTvcqyzqsH7GDhGOHEhjP5zs:lTjBBoK04K9vTKiL10rI/:1 +alice:3IIP1g1HDTN6VEUr8DUkMleocoC1cpuFZnmunDaGhMyIsw8LAwCc7ZapWaC66gZSyis4ezSuCqvhsJdwdc.0es2UrH6PBkBQflcQDuC.dEpjhWgAcH2Dw.2qU.E0ApQzLkcKOjXMQ2R6jMBL14kEUPjjHS3aa16yB.Afj3bNPdf:1JxU4GkweUEii6.b0grkzU:1 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crl b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crl new file mode 100644 index 0000000000000000000000000000000000000000..494ce735876b274107fd0fa6e09d8044dc76787e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crl @@ -0,0 +1,15 @@ +-----BEGIN X509 CRL----- +MIICWzCCAUMCAQEwDQYJKoZIhvcNAQELBQAwaDELMAkGA1UEBhMCTk4xMTAvBgNV +BAoMKEVkZWwgQ3VybCBBcmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxJjAk +BgNVBAMMHU5vcnRoZXJuIE5vd2hlcmUgVHJ1c3QgQW5jaG9yFw0yMjEyMjMxMjIx +MzlaFw0yMzAxMjIxMjIxMzlaMIGWMBcCBg80dVEqPBcNMjIxMjIzMTIyMTM2WjAX +AgYPNHVRUWEXDTIyMTIyMzEyMjEzN1owFwIGDzR1UVF1Fw0yMjEyMjMxMjIxMzda +MBcCBg80dVFRiRcNMjIxMjIzMTIyMTM4WjAXAgYPNHVReK4XDTIyMTIyMzEyMjEz +OFowFwIGDzR1UZ/TFw0yMjEyMjMxMjIxMzlaoA4wDDAKBgNVHRQEAwIBATANBgkq +hkiG9w0BAQsFAAOCAQEAMcVpjkRfr71+8t8qMGDR7jNycVDsEw8H+t4wXq44EkVu +Z3uB7IPa5KQJ4HNZ5U/5yfWrLQ14YsOHEPIWaDyXG+MYKa82t/VGSzkWdiPE/onz +Y3PBkclURacEZ5NHWTDGJXGttO7cHPPN4FsKxAsS7EWPRSCCKBGIxY3L+4QcziZV +G9zsrzn0B7NI11E9+VGm0HbhSxXUthayPvHeUmjpeJ+711R22ANNTV2jAMqFn2ZP +i6PNenZXC3xt1cZd4/T6343TT5jd0QB1JUiSFGYWZw3sSga6d57Mf5WTOCAfJsWL +X1Wds0WsQ/XbsGySCLXPWfOaxrfhk3FJHSwIDjKoAg== +-----END X509 CRL----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crt b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crt new file mode 100644 index 0000000000000000000000000000000000000000..82285808cbe198fcdbdd3f7fa17377e42dc40e79 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.crt @@ -0,0 +1,99 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980999635 (0xf3475519fd3) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:39 2022 GMT + Not After : Mar 11 12:21:39 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:ab:0a:b0:03:d0:76:fe:5e:ce:15:de:61:d5:e3: + 91:6f:7c:d6:bb:ca:26:8e:78:be:26:35:d1:a6:59: + f1:d5:3c:55:3e:09:2c:ec:a0:d4:af:0e:3c:5a:a2: + b5:b0:78:51:95:62:80:80:71:c8:4e:9f:59:59:93: + 40:12:b2:a9:ce:b2:cd:17:8b:9f:27:f3:e3:cf:23: + 78:06:d2:06:23:5f:9b:20:ec:42:77:66:ad:a4:5e: + 82:b4:4d:94:72:ea:13:64:72:fc:cb:83:2c:d7:a1: + 8b:f5:2e:4c:d3:c1:88:b2:c8:98:19:5f:ef:98:fc: + 62:80:b3:67:cc:1f:23:fc:5f:38:cd:82:6e:2d:96: + d9:35:93:fe:29:a2:69:65:c0:df:45:ab:3f:ac:17: + 18:00:80:4a:b7:c9:ba:b8:5f:29:bb:c4:ac:16:97: + cc:57:34:10:c9:36:65:6c:3e:d8:89:45:c8:a5:42: + 84:7c:5e:cd:1a:e8:f1:3e:55:b3:21:0f:d0:36:13: + f2:c4:2f:b9:73:41:fa:87:aa:dc:44:d6:64:96:e4: + 5a:50:f9:4a:9f:e0:a2:e7:69:f4:ad:5a:cf:3a:20: + e5:a7:09:e2:cf:e8:19:a1:00:ae:a8:bb:22:02:34: + 5c:b3:cf:b5:24:4c:76:bf:ad:e9:f1:b8:d3:86:ba: + 7d:93 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 9C:97:B0:3D:B3:50:B1:F6:D4:71:E2:EB:CB:80:EA:93:7C:98:CC:72 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 0b:8a:ed:6a:87:fa:71:15:88:25:58:85:1b:4a:09:bf:43:00: + 35:93:78:0d:72:14:30:51:e2:93:83:a1:da:1b:2f:a9:31:ae: + b7:c7:4c:72:c2:5e:32:24:f1:96:93:70:d5:3f:b5:85:80:13: + 75:32:cf:0e:f8:5d:c4:a2:29:84:43:2c:75:81:26:12:6a:a0: + cb:7b:57:c1:92:78:85:08:fa:64:50:c2:7b:83:02:4d:79:13: + bc:61:64:4d:b8:6b:d5:f1:84:6b:12:5c:69:90:ad:40:47:c0: + ed:dd:ea:8a:66:7e:87:85:19:aa:89:d3:3c:08:72:08:a1:4d: + 63:60:5b:9b:17:9e:00:12:a1:00:52:ca:78:01:88:18:c7:ed: + 5b:c7:e4:d9:eb:bd:3f:af:92:53:3f:fe:58:57:0d:fc:f4:7b: + 7b:a2:4f:e9:b9:5c:b5:a4:52:50:b4:56:5a:44:8e:d9:d0:ed: + de:8f:7e:ac:1c:58:76:5b:a8:79:c9:95:ab:85:1d:db:4c:13: + 82:4a:a5:41:1b:29:f5:d3:96:df:80:d1:1e:00:7d:ba:35:94: + 57:81:e1:08:2a:81:6b:1c:30:50:37:01:1a:0e:26:4f:6b:ed: + c9:50:17:37:2b:33:3f:68:fe:c6:f0:21:8c:e7:b2:79:55:f2: + 42:bd:2f:b0 +-----BEGIN CERTIFICATE----- +MIIERDCCAyygAwIBAgIGDzR1UZ/TMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzlaFw0zMTAzMTExMjIxMzlaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCrCrAD0Hb+Xs4V3mHV45FvfNa7yiaOeL4mNdGmWfHVPFU+CSzsoNSvDjxa +orWweFGVYoCAcchOn1lZk0ASsqnOss0Xi58n8+PPI3gG0gYjX5sg7EJ3Zq2kXoK0 +TZRy6hNkcvzLgyzXoYv1LkzTwYiyyJgZX++Y/GKAs2fMHyP8XzjNgm4tltk1k/4p +omllwN9Fqz+sFxgAgEq3ybq4Xym7xKwWl8xXNBDJNmVsPtiJRcilQoR8Xs0a6PE+ +VbMhD9A2E/LEL7lzQfqHqtxE1mSW5FpQ+Uqf4KLnafStWs86IOWnCeLP6BmhAK6o +uyICNFyzz7UkTHa/renxuNOGun2TAgMBAAGjggEGMIIBAjAUBgNVHREEDTALggls +b2NhbGhvc3QwCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1Ud +DgQWBBScl7A9s1Cx9tRx4uvLgOqTfJjMcjAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj +5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcw +AoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1Ud +HwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290 +LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAC4rtaof6cRWIJViFG0oJv0MANZN4DXIU +MFHik4Oh2hsvqTGut8dMcsJeMiTxlpNw1T+1hYATdTLPDvhdxKIphEMsdYEmEmqg +y3tXwZJ4hQj6ZFDCe4MCTXkTvGFkTbhr1fGEaxJcaZCtQEfA7d3qimZ+h4UZqonT +PAhyCKFNY2BbmxeeABKhAFLKeAGIGMftW8fk2eu9P6+SUz/+WFcN/PR7e6JP6blc +taRSULRWWkSO2dDt3o9+rBxYdluoecmVq4Ud20wTgkqlQRsp9dOW34DRHgB9ujWU +V4HhCCqBaxwwUDcBGg4mT2vtyVAXNyszP2j+xvAhjOeyeVXyQr0vsA== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.csr b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.csr new file mode 100644 index 0000000000000000000000000000000000000000..739cd68eb3a0b665b25e7b6266f7c8e461954f2f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.csr @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICmTCCAYECAQAwVDELMAkGA1UEBhMCTk4xMTAvBgNVBAoMKEVkZWwgQ3VybCBB +cmN0aWMgSWxsdWRpdW0gUmVzZWFyY2ggQ2xvdWQxEjAQBgNVBAMMCWxvY2FsaG9z +dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKsKsAPQdv5ezhXeYdXj +kW981rvKJo54viY10aZZ8dU8VT4JLOyg1K8OPFqitbB4UZVigIBxyE6fWVmTQBKy +qc6yzReLnyfz488jeAbSBiNfmyDsQndmraRegrRNlHLqE2Ry/MuDLNehi/UuTNPB +iLLImBlf75j8YoCzZ8wfI/xfOM2Cbi2W2TWT/imiaWXA30WrP6wXGACASrfJurhf +KbvErBaXzFc0EMk2ZWw+2IlFyKVChHxezRro8T5VsyEP0DYT8sQvuXNB+oeq3ETW +ZJbkWlD5Sp/goudp9K1azzog5acJ4s/oGaEArqi7IgI0XLPPtSRMdr+t6fG404a6 +fZMCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQAauiYRPParSazzDjwG98G8YzZk +1V/Q3rOzPN5a4veBMVO0kTxrTLImX/+BU6Bj6YgbpUGzIUqbkEunCQ5vtbFTrooD +uT2tZtENXrj6i1fR3BArnLiP1Pg+PO1ONvTuY+384v2CIeE7AP6V0wZw5W9OJSkP +eM8RU5OJn5zJkxhmUdREg5d3VuIE67ABcbCsxqMAhJuPw6mFgN6ffZl06nZ2cR5k +TeOmze7EL8UCNByTtwqBdgryPQu3UEsBq0GxQJcBzcmB3vfClLhnTLic4sRHGdTO +Ql+6CFqNnP5+bEMWqExPmWsdogFtwJsiQvr2nk/i2ogKAoRs+T0siTcF1+RM +-----END CERTIFICATE REQUEST----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.der b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.der new file mode 100644 index 0000000000000000000000000000000000000000..9c015f8fc648a096eb3c61d6ffc3a068e6873c6c Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.dhp b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.dhp new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.key b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.key new file mode 100644 index 0000000000000000000000000000000000000000..84c86c2ee0119f899e470e96a5f95442178c56b6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrCrAD0Hb+Xs4V +3mHV45FvfNa7yiaOeL4mNdGmWfHVPFU+CSzsoNSvDjxaorWweFGVYoCAcchOn1lZ +k0ASsqnOss0Xi58n8+PPI3gG0gYjX5sg7EJ3Zq2kXoK0TZRy6hNkcvzLgyzXoYv1 +LkzTwYiyyJgZX++Y/GKAs2fMHyP8XzjNgm4tltk1k/4pomllwN9Fqz+sFxgAgEq3 +ybq4Xym7xKwWl8xXNBDJNmVsPtiJRcilQoR8Xs0a6PE+VbMhD9A2E/LEL7lzQfqH +qtxE1mSW5FpQ+Uqf4KLnafStWs86IOWnCeLP6BmhAK6ouyICNFyzz7UkTHa/renx +uNOGun2TAgMBAAECggEAH0BsKb5Ax7h90jwYRzL141d9isFkaxq/r46c2FbN24bT +EmstxKycP8ILoAnjxbMuQOvHC/D+RvNRqY7Aocn4Qdakp50wvuWOpc3Ww/RC/9qb +pxfUCyn9Jy/HlPcp3RdM5MknzG2S13Fid7F2gyh0+CmztMs1JZBT1S0ylXbJJfbY +1pdlHcf9oEbYo36vGd9rtJHAFzsFfwua0idl76XYuOnR3bpOkHl1B5cJ8jpOliPv +VTmzn0cIgAmk7IByHHqGQ0u30PFiElI9kEbkKWoxAM1hq1pFU58jQhvp0ZkjVENL +bSFB2B4DbyosxPlbUgvJCN4B7nclqzYqBdrrk6/ZLQKBgQC1lDrPSGIGXLwvkZYS +xc0wtaCC7u6m7zV8rzh5HGcEoVvtmya/VyoZR8KGIpSor8COIkZqFtan6C77C3MH +wClbu2Kn3FkGb76D5U2Xwl38zepzjn8Z5qXc3bZfccrsDY1gXPicgsmcKUY9xV5/ +T0RjESDKB+xxkJpCjia6klm2NQKBgQDxJNuqB6frDYKaj7mW/rvyHqkeT94J6eDY +BcMZVKeHRNWcBMOvJDChVmpsCjJPOWHhHOlAE755NxWn8wpgyiUcac3BiysMgvTT +pyH8UVWaP/DWYOfpuhtcLPkIjKnPijOvshpyWBxfXNIejiovoT6E3IXKOxr5g5yq +U/9a5+I9pwKBgDyJG4YpkoyedBrDxa2ihkL7+nRMZgH/c+yKmiA+aNXxWa2AcU2P +KLje5KpFcxw948s/AAy0aoH19Vu6uHHYDbHIah6eZouvy2s7kj/LC/yRRd2anyMq +cxeMTxXI4ScLaZu7wyKis8Y9OG61k0iMS7dfaXgRZjGCTPttWtoOmpwVAoGAd2k+ +EXuLDl15UBpd18S6wxGlw2nfVN9oxPBNhUyjTNusP38oe6EbJ7mIJ4oBEbQjoPrV +EjL0vkelxK4YdIeFSwWlqvLEVYS/wdNgg/auwhxpoW8JSHctNz7Z7v7g0/Hm2FkE +uZyiKCLptdHGWCGruNUOt27/U5F10e6YY6ayJL8CgYEAoE/ddHIlrKFzcZ0cu47R +ky4D4x32ceC2au4eGPLMDItPjceXe8I6zgB5P8/U5U3PRw5oWabpAf5lAcRwa12c +23xgy9O5QNlyps/rAdnVjwxqGwEd5E2LrZ2+JDflPRGunx2VO5v9CxXvsxu9F3Rj +tREtebHe2H7u5jNsIQArnRI= +-----END PRIVATE KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pem b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pem new file mode 100644 index 0000000000000000000000000000000000000000..b273ff76173edc28b3372ab46303d0907bbf50ad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pem @@ -0,0 +1,162 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 12048 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrCrAD0Hb+Xs4V +3mHV45FvfNa7yiaOeL4mNdGmWfHVPFU+CSzsoNSvDjxaorWweFGVYoCAcchOn1lZ +k0ASsqnOss0Xi58n8+PPI3gG0gYjX5sg7EJ3Zq2kXoK0TZRy6hNkcvzLgyzXoYv1 +LkzTwYiyyJgZX++Y/GKAs2fMHyP8XzjNgm4tltk1k/4pomllwN9Fqz+sFxgAgEq3 +ybq4Xym7xKwWl8xXNBDJNmVsPtiJRcilQoR8Xs0a6PE+VbMhD9A2E/LEL7lzQfqH +qtxE1mSW5FpQ+Uqf4KLnafStWs86IOWnCeLP6BmhAK6ouyICNFyzz7UkTHa/renx +uNOGun2TAgMBAAECggEAH0BsKb5Ax7h90jwYRzL141d9isFkaxq/r46c2FbN24bT +EmstxKycP8ILoAnjxbMuQOvHC/D+RvNRqY7Aocn4Qdakp50wvuWOpc3Ww/RC/9qb +pxfUCyn9Jy/HlPcp3RdM5MknzG2S13Fid7F2gyh0+CmztMs1JZBT1S0ylXbJJfbY +1pdlHcf9oEbYo36vGd9rtJHAFzsFfwua0idl76XYuOnR3bpOkHl1B5cJ8jpOliPv +VTmzn0cIgAmk7IByHHqGQ0u30PFiElI9kEbkKWoxAM1hq1pFU58jQhvp0ZkjVENL +bSFB2B4DbyosxPlbUgvJCN4B7nclqzYqBdrrk6/ZLQKBgQC1lDrPSGIGXLwvkZYS +xc0wtaCC7u6m7zV8rzh5HGcEoVvtmya/VyoZR8KGIpSor8COIkZqFtan6C77C3MH +wClbu2Kn3FkGb76D5U2Xwl38zepzjn8Z5qXc3bZfccrsDY1gXPicgsmcKUY9xV5/ +T0RjESDKB+xxkJpCjia6klm2NQKBgQDxJNuqB6frDYKaj7mW/rvyHqkeT94J6eDY +BcMZVKeHRNWcBMOvJDChVmpsCjJPOWHhHOlAE755NxWn8wpgyiUcac3BiysMgvTT +pyH8UVWaP/DWYOfpuhtcLPkIjKnPijOvshpyWBxfXNIejiovoT6E3IXKOxr5g5yq +U/9a5+I9pwKBgDyJG4YpkoyedBrDxa2ihkL7+nRMZgH/c+yKmiA+aNXxWa2AcU2P +KLje5KpFcxw948s/AAy0aoH19Vu6uHHYDbHIah6eZouvy2s7kj/LC/yRRd2anyMq +cxeMTxXI4ScLaZu7wyKis8Y9OG61k0iMS7dfaXgRZjGCTPttWtoOmpwVAoGAd2k+ +EXuLDl15UBpd18S6wxGlw2nfVN9oxPBNhUyjTNusP38oe6EbJ7mIJ4oBEbQjoPrV +EjL0vkelxK4YdIeFSwWlqvLEVYS/wdNgg/auwhxpoW8JSHctNz7Z7v7g0/Hm2FkE +uZyiKCLptdHGWCGruNUOt27/U5F10e6YY6ayJL8CgYEAoE/ddHIlrKFzcZ0cu47R +ky4D4x32ceC2au4eGPLMDItPjceXe8I6zgB5P8/U5U3PRw5oWabpAf5lAcRwa12c +23xgy9O5QNlyps/rAdnVjwxqGwEd5E2LrZ2+JDflPRGunx2VO5v9CxXvsxu9F3Rj +tREtebHe2H7u5jNsIQArnRI= +-----END PRIVATE KEY----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 16717980999635 (0xf3475519fd3) + Signature Algorithm: sha256WithRSAEncryption + Issuer: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = Northern Nowhere Trust Anchor + Validity + Not Before: Dec 23 12:21:39 2022 GMT + Not After : Mar 11 12:21:39 2031 GMT + Subject: + countryName = NN + organizationName = Edel Curl Arctic Illudium Research Cloud + commonName = localhost + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:ab:0a:b0:03:d0:76:fe:5e:ce:15:de:61:d5:e3: + 91:6f:7c:d6:bb:ca:26:8e:78:be:26:35:d1:a6:59: + f1:d5:3c:55:3e:09:2c:ec:a0:d4:af:0e:3c:5a:a2: + b5:b0:78:51:95:62:80:80:71:c8:4e:9f:59:59:93: + 40:12:b2:a9:ce:b2:cd:17:8b:9f:27:f3:e3:cf:23: + 78:06:d2:06:23:5f:9b:20:ec:42:77:66:ad:a4:5e: + 82:b4:4d:94:72:ea:13:64:72:fc:cb:83:2c:d7:a1: + 8b:f5:2e:4c:d3:c1:88:b2:c8:98:19:5f:ef:98:fc: + 62:80:b3:67:cc:1f:23:fc:5f:38:cd:82:6e:2d:96: + d9:35:93:fe:29:a2:69:65:c0:df:45:ab:3f:ac:17: + 18:00:80:4a:b7:c9:ba:b8:5f:29:bb:c4:ac:16:97: + cc:57:34:10:c9:36:65:6c:3e:d8:89:45:c8:a5:42: + 84:7c:5e:cd:1a:e8:f1:3e:55:b3:21:0f:d0:36:13: + f2:c4:2f:b9:73:41:fa:87:aa:dc:44:d6:64:96:e4: + 5a:50:f9:4a:9f:e0:a2:e7:69:f4:ad:5a:cf:3a:20: + e5:a7:09:e2:cf:e8:19:a1:00:ae:a8:bb:22:02:34: + 5c:b3:cf:b5:24:4c:76:bf:ad:e9:f1:b8:d3:86:ba: + 7d:93 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:localhost + X509v3 Key Usage: + Digital Signature, Key Encipherment, Key Agreement + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Key Identifier: + 9C:97:B0:3D:B3:50:B1:F6:D4:71:E2:EB:CB:80:EA:93:7C:98:CC:72 + X509v3 Authority Key Identifier: + 87:CB:B1:33:2E:C1:67:7E:71:E3:E5:2B:4C:4D:A4:B3:6E:D2:5B:A9 + X509v3 Basic Constraints: + CA:FALSE + Authority Information Access: + CA Issuers - URI:http://test.curl.se/ca/EdelCurlRoot.cer + X509v3 CRL Distribution Points: + Full Name: + URI:http://test.curl.se/ca/EdelCurlRoot.crl + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 0b:8a:ed:6a:87:fa:71:15:88:25:58:85:1b:4a:09:bf:43:00: + 35:93:78:0d:72:14:30:51:e2:93:83:a1:da:1b:2f:a9:31:ae: + b7:c7:4c:72:c2:5e:32:24:f1:96:93:70:d5:3f:b5:85:80:13: + 75:32:cf:0e:f8:5d:c4:a2:29:84:43:2c:75:81:26:12:6a:a0: + cb:7b:57:c1:92:78:85:08:fa:64:50:c2:7b:83:02:4d:79:13: + bc:61:64:4d:b8:6b:d5:f1:84:6b:12:5c:69:90:ad:40:47:c0: + ed:dd:ea:8a:66:7e:87:85:19:aa:89:d3:3c:08:72:08:a1:4d: + 63:60:5b:9b:17:9e:00:12:a1:00:52:ca:78:01:88:18:c7:ed: + 5b:c7:e4:d9:eb:bd:3f:af:92:53:3f:fe:58:57:0d:fc:f4:7b: + 7b:a2:4f:e9:b9:5c:b5:a4:52:50:b4:56:5a:44:8e:d9:d0:ed: + de:8f:7e:ac:1c:58:76:5b:a8:79:c9:95:ab:85:1d:db:4c:13: + 82:4a:a5:41:1b:29:f5:d3:96:df:80:d1:1e:00:7d:ba:35:94: + 57:81:e1:08:2a:81:6b:1c:30:50:37:01:1a:0e:26:4f:6b:ed: + c9:50:17:37:2b:33:3f:68:fe:c6:f0:21:8c:e7:b2:79:55:f2: + 42:bd:2f:b0 +-----BEGIN CERTIFICATE----- +MIIERDCCAyygAwIBAgIGDzR1UZ/TMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNVBAYT +Ak5OMTEwLwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNo +IENsb3VkMSYwJAYDVQQDDB1Ob3J0aGVybiBOb3doZXJlIFRydXN0IEFuY2hvcjAe +Fw0yMjEyMjMxMjIxMzlaFw0zMTAzMTExMjIxMzlaMFQxCzAJBgNVBAYTAk5OMTEw +LwYDVQQKDChFZGVsIEN1cmwgQXJjdGljIElsbHVkaXVtIFJlc2VhcmNoIENsb3Vk +MRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCrCrAD0Hb+Xs4V3mHV45FvfNa7yiaOeL4mNdGmWfHVPFU+CSzsoNSvDjxa +orWweFGVYoCAcchOn1lZk0ASsqnOss0Xi58n8+PPI3gG0gYjX5sg7EJ3Zq2kXoK0 +TZRy6hNkcvzLgyzXoYv1LkzTwYiyyJgZX++Y/GKAs2fMHyP8XzjNgm4tltk1k/4p +omllwN9Fqz+sFxgAgEq3ybq4Xym7xKwWl8xXNBDJNmVsPtiJRcilQoR8Xs0a6PE+ +VbMhD9A2E/LEL7lzQfqHqtxE1mSW5FpQ+Uqf4KLnafStWs86IOWnCeLP6BmhAK6o +uyICNFyzz7UkTHa/renxuNOGun2TAgMBAAGjggEGMIIBAjAUBgNVHREEDTALggls +b2NhbGhvc3QwCwYDVR0PBAQDAgOoMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB0GA1Ud +DgQWBBScl7A9s1Cx9tRx4uvLgOqTfJjMcjAfBgNVHSMEGDAWgBSHy7EzLsFnfnHj +5StMTaSzbtJbqTAJBgNVHRMEAjAAMEMGCCsGAQUFBwEBBDcwNTAzBggrBgEFBQcw +AoYnaHR0cDovL3Rlc3QuY3VybC5zZS9jYS9FZGVsQ3VybFJvb3QuY2VyMDgGA1Ud +HwQxMC8wLaAroCmGJ2h0dHA6Ly90ZXN0LmN1cmwuc2UvY2EvRWRlbEN1cmxSb290 +LmNybDANBgkqhkiG9w0BAQsFAAOCAQEAC4rtaof6cRWIJViFG0oJv0MANZN4DXIU +MFHik4Oh2hsvqTGut8dMcsJeMiTxlpNw1T+1hYATdTLPDvhdxKIphEMsdYEmEmqg +y3tXwZJ4hQj6ZFDCe4MCTXkTvGFkTbhr1fGEaxJcaZCtQEfA7d3qimZ+h4UZqonT +PAhyCKFNY2BbmxeeABKhAFLKeAGIGMftW8fk2eu9P6+SUz/+WFcN/PR7e6JP6blc +taRSULRWWkSO2dDt3o9+rBxYdluoecmVq4Ud20wTgkqlQRsp9dOW34DRHgB9ujWU +V4HhCCqBaxwwUDcBGg4mT2vtyVAXNyszP2j+xvAhjOeyeVXyQr0vsA== +-----END CERTIFICATE----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.prm b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.prm new file mode 100644 index 0000000000000000000000000000000000000000..8fd080bd8b0d2164b25584a87cd952a126730732 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.prm @@ -0,0 +1,35 @@ +extensions = x509v3 + +[ x509v3 ] +subjectAltName = DNS:localhost +keyUsage = keyEncipherment,digitalSignature,keyAgreement +extendedKeyUsage = serverAuth +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid +basicConstraints = CA:false +authorityInfoAccess = @issuer_info +crlDistributionPoints = @crl_info + +[ crl_ext ] +authorityKeyIdentifier = keyid:always +authorityInfoAccess = @issuer_info + +[ issuer_info ] +caIssuers;URI.0 = http://test.curl.se/ca/EdelCurlRoot.cer + +[ crl_info ] +URI.0 = http://test.curl.se/ca/EdelCurlRoot.crl + +[ req ] +default_bits = 12048 +distinguished_name = req_DN +default_md = sha256 +string_mask = utf8only + +[ req_DN ] +countryName = "Country Name is Northern Nowhere" +countryName_value = NN +organizationName = "Organization Name" +organizationName_value = Edel Curl Arctic Illudium Research Cloud +commonName = "Common Name" +commonName_value = localhost diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.der b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.der new file mode 100644 index 0000000000000000000000000000000000000000..434e87937535de8efa1f8f448d1e28f7e54826d4 Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.der differ diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.pem b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.pem new file mode 100644 index 0000000000000000000000000000000000000000..5458d6573ba9e919d8defa67f8163bcacaac2702 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqwqwA9B2/l7OFd5h1eOR +b3zWu8omjni+JjXRplnx1TxVPgks7KDUrw48WqK1sHhRlWKAgHHITp9ZWZNAErKp +zrLNF4ufJ/PjzyN4BtIGI1+bIOxCd2atpF6CtE2UcuoTZHL8y4Ms16GL9S5M08GI +ssiYGV/vmPxigLNnzB8j/F84zYJuLZbZNZP+KaJpZcDfRas/rBcYAIBKt8m6uF8p +u8SsFpfMVzQQyTZlbD7YiUXIpUKEfF7NGujxPlWzIQ/QNhPyxC+5c0H6h6rcRNZk +luRaUPlKn+Ci52n0rVrPOiDlpwniz+gZoQCuqLsiAjRcs8+1JEx2v63p8bjThrp9 +kwIDAQAB +-----END PUBLIC KEY----- diff --git a/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pubkey-pinned b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pubkey-pinned new file mode 100644 index 0000000000000000000000000000000000000000..4829e494aa587ffc9a2f463438745b4a1123ead9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/certs/stunnel-sv.pubkey-pinned @@ -0,0 +1 @@ +LpY019g4f7/9H+Q+AwdGYQsvwIj2JzM6m1jlyyJK1ro= diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test10 b/local-test-curl-delta-01/afc-curl/tests/data/test10 new file mode 100644 index 0000000000000000000000000000000000000000..ac1486ec09119117166f1635ee960eba257d2de1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test10 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP PUT + + +# Server-side + + +HTTP/1.0 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake + +blablabla + + + + +# Client-side + + +http + + +simple HTTP PUT from file + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER -T %LOGDIR/test%TESTNUMBER.txt + + +Weird + file + to + upload +for + testing +the + PUT + feature + + + +# Verify data after the test has been "shot" + + +PUT /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 78 + +Weird + file + to + upload +for + testing +the + PUT + feature + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1000 b/local-test-curl-delta-01/afc-curl/tests/data/test1000 new file mode 100644 index 0000000000000000000000000000000000000000..e102a006e043310a78523ef368db99a2ef943e59 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1000 @@ -0,0 +1,45 @@ + + + +FTP +PASV +LIST +NOBODY + + +# +# Server-side + + + + + +# +# Client-side + + +ftp + + +FTP dir list PASV with -I + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER/ -I + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1004 b/local-test-curl-delta-01/afc-curl/tests/data/test1004 new file mode 100644 index 0000000000000000000000000000000000000000..33faaafb197b829c8973443cfe9aa316bf19c344 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1004 @@ -0,0 +1,57 @@ + + + +HTTP +HTTP GET +HTTP proxy + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +proxy + + +http + + +HTTP GET with empty proxy + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --proxy "" + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1011 b/local-test-curl-delta-01/afc-curl/tests/data/test1011 new file mode 100644 index 0000000000000000000000000000000000000000..d6a3d1aa7d072a14bfd458646beef124a8f9cb8c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1011 @@ -0,0 +1,74 @@ + + + +HTTP +HTTP POST +followlocation + + +# +# Server-side + + +HTTP/1.1 301 OK +Location: moo.html&testcase=/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 0 + + + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + +HTTP/1.1 301 OK +Location: moo.html&testcase=/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 0 + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + + +# +# Client-side + + +http + + +HTTP POST with 301 redirect + + +http://%HOSTIP:%HTTPPORT/blah/%TESTNUMBER -L -d "moo" + + + +# +# Verify data after the test has been "shot" + + +POST /blah/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 3 +Content-Type: application/x-www-form-urlencoded + +mooGET /blah/moo.html&testcase=/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1020 b/local-test-curl-delta-01/afc-curl/tests/data/test1020 new file mode 100644 index 0000000000000000000000000000000000000000..c2cd7f2d23cde900fb0e2a56dd8aa07f033bc28f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1020 @@ -0,0 +1,41 @@ + + + +FILE +Range + + + +# Server-side + + + + + +# Client-side + + +none + + +file + + +-Y range on a file:// URL to stdout + + +-r -9 file://localhost%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt + + +1234567890 +1234567890 + + + +# Verify data after the test has been "shot" + + +34567890 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1022 b/local-test-curl-delta-01/afc-curl/tests/data/test1022 new file mode 100644 index 0000000000000000000000000000000000000000..597dfd05d05a7dd2b8bd53f76f8308e197dfd6a1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1022 @@ -0,0 +1,37 @@ + + + +curl-config + + + +# +# Server-side + + + +# +# Client-side + + +none + + +Compare curl --version with curl-config --version + + +--version + + + +# +# Verify data after the test has been "shot" + + +%SRCDIR/libtest/test%TESTNUMBER.pl ../curl-config %LOGDIR/stdout%TESTNUMBER version + + +0 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1024 b/local-test-curl-delta-01/afc-curl/tests/data/test1024 new file mode 100644 index 0000000000000000000000000000000000000000..55deec98bbdb01ce14d3539de7b356e940539413 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1024 @@ -0,0 +1,106 @@ + + + +HTTP +HTTP GET +followlocation +cookies + + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: ../data/%TESTNUMBER0002.txt +Set-Cookie: firstcookie=want; path=/want/ +Content-Length: 69 + +This server reply is for testing a Location: following with cookies + + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: ../want/%TESTNUMBER0003.txt +Set-Cookie: nextcookie=data; path=/data/ +Content-Length: 69 + +This server reply is for testing a Location: following with cookies + + + +HTTP/1.1 200 Followed here fine +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: ../data/%TESTNUMBER0002.txt +Set-Cookie: firstcookie=want; path=/want/ +Content-Length: 69 + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: ../want/%TESTNUMBER0003.txt +Set-Cookie: nextcookie=data; path=/data/ +Content-Length: 69 + +HTTP/1.1 200 Followed here fine +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + + +# Client-side + + +http + + +HTTP Location: following with cookies + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER -L -c %LOGDIR/jar%TESTNUMBER + + +cookies + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /data/%TESTNUMBER0002.txt HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/%TESTNUMBER0003.txt HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Cookie: firstcookie=want + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1027 b/local-test-curl-delta-01/afc-curl/tests/data/test1027 new file mode 100644 index 0000000000000000000000000000000000000000..354df4e40efe30aac35218704520a40a72e0eecd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1027 @@ -0,0 +1,39 @@ + + + +--help + + + +# +# Server-side + + + +# +# Client-side + + +none + + +curl --help + + +--help + + + +# +# Verify data after the test has been "shot" + + +0 + +# Search for these two sentinel lines in the help output; if they are found, +# then chances are good the entire help is there. + +%PERL -e 'open(IN,$ARGV[0]); my $lines=grep(/(Usage: curl )|(--version\s*Show version)/, ); exit ($lines != 2); # Let this file pass an XML syntax check: ' %LOGDIR/stdout%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1033 b/local-test-curl-delta-01/afc-curl/tests/data/test1033 new file mode 100644 index 0000000000000000000000000000000000000000..b19bf1ce96fd90582ff07f8522405e90190eff41 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1033 @@ -0,0 +1,58 @@ + +# +# This case with an unexpected 1xx response used to cause a "hang" before the fix +# got 7.19.0 + + +HTTP +HTTP GET + + + +# +# Server-side + + +HTTP/1.1 102 unexpected huh?! + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +HTTP GET with 102 response! + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1037 b/local-test-curl-delta-01/afc-curl/tests/data/test1037 new file mode 100644 index 0000000000000000000000000000000000000000..967561b3b65e9ed637728a65754db1f1e01b5687 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1037 @@ -0,0 +1,57 @@ + + + +FTP +PASV +RETR +Resume + + + +# Server-side + + +expected to be a file without the first part +but we emulate that + + +65 + + +REPLY EPSV 500 no such command + + + +# Client-side + + +ftp + + +FTP download resume from end of empty file + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER -C - + + + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +PASV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1041 b/local-test-curl-delta-01/afc-curl/tests/data/test1041 new file mode 100644 index 0000000000000000000000000000000000000000..bb793d51ead829352ddcbe7d45491627ada893f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1041 @@ -0,0 +1,75 @@ + +# Similar to test33 + + +HTTP +HTTP PUT +Resume +Content-Range + + + +# Server-side + + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Accept-Ranges: bytes +Content-Length: 0 +Connection: close +Content-Type: text/html + + + + +# Client-side + + +http + + +HTTP PUT with resume from end of already-uploaded file + + +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -T%LOGDIR/test%TESTNUMBER.txt -C - + + + +# Verify data after the test has been "shot" + +# curl doesn't do a HEAD request on the remote file so it has no idea whether +# it can skip part of the file or not. Instead, it sends the entire file. + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Content-Range: bytes 0-99/100 +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 100 + +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1046 b/local-test-curl-delta-01/afc-curl/tests/data/test1046 new file mode 100644 index 0000000000000000000000000000000000000000..fd05b3d5357b5829ecf700f560f05f4e8100ef68 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1046 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP GET +--interface +IPv6 + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Mon, 28 Jul 2008 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/plain + +-foo- + + + +# +# Client-side + + +IPv6 + + +http-ipv6 + + +HTTP-IPv6 GET with numeric localhost --interface + + +-g "http://%HOST6IP:%HTTP6PORT/%TESTNUMBER" --interface %CLIENT6IP-NB + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOST6IP:%HTTP6PORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1055 b/local-test-curl-delta-01/afc-curl/tests/data/test1055 new file mode 100644 index 0000000000000000000000000000000000000000..0624a969a7865c633f8b7189951fe30b917dbba1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1055 @@ -0,0 +1,96 @@ + + + +HTTP +HTTP PUT +followlocation +FTP +EPSV +STOR + + + +# +# Server-side + + +HTTP/1.1 307 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Location: ftp://%HOSTIP:%FTPPORT/%TESTNUMBER +Content-Length: 0 +Connection: close + + + + +# +# Client-side + + +http +ftp + + +HTTP PUT Location: redirect to FTP URL + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -L -T %LOGDIR/test%TESTNUMBER.txt + + +Weird + file + to + upload +for + testing +the + PUT + feature + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 78 + +Weird + file + to + upload +for + testing +the + PUT + feature +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE I +STOR %TESTNUMBER +QUIT + + +Weird + file + to + upload +for + testing +the + PUT + feature + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1066 b/local-test-curl-delta-01/afc-curl/tests/data/test1066 new file mode 100644 index 0000000000000000000000000000000000000000..5b2b178f096964998a896e1ad736aba649b2343f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1066 @@ -0,0 +1,81 @@ + + + +HTTP +HTTP GET + + + +# Server-side + + +HTTP/1.1 200 OK +Server: thebest/1.0 +Content-Type: text/plain +Content-Length: 6 + +first + + +HTTP/1.1 200 OK +Server: thebest/1.0 +Content-Type: text/plain +Content-Length: 7 + +second + + + +# Client-side + + +http + + +HTTP --dump-header - with two URLs + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER0001 --dump-header - + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/%TESTNUMBER0001 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +HTTP/1.1 200 OK +HTTP/1.1 200 OK +Server: thebest/1.0 +Server: thebest/1.0 +Content-Type: text/plain +Content-Type: text/plain +Content-Length: 6 +Content-Length: 6 + + +first +HTTP/1.1 200 OK +HTTP/1.1 200 OK +Server: thebest/1.0 +Server: thebest/1.0 +Content-Type: text/plain +Content-Type: text/plain +Content-Length: 7 +Content-Length: 7 + + +second + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1067 b/local-test-curl-delta-01/afc-curl/tests/data/test1067 new file mode 100644 index 0000000000000000000000000000000000000000..8bb2233e36e51d33caa591f050d1b077d58a593f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1067 @@ -0,0 +1,80 @@ + + + +HTTP +HTTP GET +followlocation + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: data/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +This server reply is for testing a simple Location: following + + + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + +HTTP/1.1 301 This is a weirdo text message swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: data/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + + +# Client-side + + +http + + +HTTP Location: following with auto-referer + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER --silent --location --referer "firstone.html;auto" --write-out "%{stderr}|%{referer}|" + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Referer: firstone.html + +GET /want/data/%TESTNUMBER0002.txt?coolsite=yes HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Referer: http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER + + + +|http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER| + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1070 b/local-test-curl-delta-01/afc-curl/tests/data/test1070 new file mode 100644 index 0000000000000000000000000000000000000000..18c2df3adcd261766e749a8d92552bfc45275760 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1070 @@ -0,0 +1,63 @@ + + + +HTTP +HTTP POST + + +# +# Server-side + + +HTTP/1.1 403 Go away and swsclose +Server: test-server/fake +Content-Type: text/html +Content-Length: 55 +Connection: close + +you are not supposed to be allowed to send things here + + +skip: 2300 + + + +# +# Client-side + + +http + + +HTTP POST with server closing connection before (all) data is received + + +-d @%LOGDIR/input%TESTNUMBER http://%HOSTIP:%HTTPPORT/%TESTNUMBER -H "Expect: 100-continue" + + +This creates the named file with this content before the test case is run, +which is useful if the test case needs a file to act on. We create this file +rather large (larger than your typical TCP packet) so that not all of it can nor +will be sent in one go as that is kind of the point of this test! + +Here's 2000 x 'O': +OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO + + + +# +# Verify data after the test has been "shot" + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Expect: 100-continue +Content-Length: 2313 +Content-Type: application/x-www-form-urlencoded + +This creates + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1076 b/local-test-curl-delta-01/afc-curl/tests/data/test1076 new file mode 100644 index 0000000000000000000000000000000000000000..258d14e6a8fd3cafbc5ae27d39c0217269649fee --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1076 @@ -0,0 +1,77 @@ + + + +HTTP +HTTP POST +followlocation + + +# +# Server-side + + +HTTP/1.1 302 OK swsclose +Location: moo.html&testcase=/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + + + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + +HTTP/1.1 302 OK swsclose +Location: moo.html&testcase=/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + + +# +# Client-side + + +http + + +HTTP POST with 302 redirect and --post302 + + +http://%HOSTIP:%HTTPPORT/blah/%TESTNUMBER -L -d "moo" --post302 + + + +# +# Verify data after the test has been "shot" + + +POST /blah/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 3 +Content-Type: application/x-www-form-urlencoded + +mooPOST /blah/moo.html&testcase=/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 3 +Content-Type: application/x-www-form-urlencoded + +moo + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1092 b/local-test-curl-delta-01/afc-curl/tests/data/test1092 new file mode 100644 index 0000000000000000000000000000000000000000..3d7b741ea7466d15092acb737c02b0614805b9a7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1092 @@ -0,0 +1,55 @@ + + + +FTP +HTTP +HTTP GET +HTTP proxy +type= + + +# +# Server-side + + +HTTP/1.0 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes + +contents + + + +# +# Client-side + + +http + + +ftp +proxy + + +FTP with type=i over HTTP proxy + + +"ftp://%HOSTIP:%HTTPPORT/we/want/that/page/%TESTNUMBER;type=i" --use-ascii -x %HOSTIP:%HTTPPORT + + + +# +# Verify data after the test has been "shot" + + +GET ftp://%HOSTIP:%HTTPPORT/we/want/that/page/%TESTNUMBER;type=i HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1096 b/local-test-curl-delta-01/afc-curl/tests/data/test1096 new file mode 100644 index 0000000000000000000000000000000000000000..f8eb1d4fb228079123130d70a054aaa9c16a054b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1096 @@ -0,0 +1,54 @@ + + + +FTP +PASV +RETR +FAILURE + + +# Server-side + + +REPLY RETR 550 no such file! +REPLY SIZE 500 command not understood + + + +# Client-side + + +ftp + + +Two FTP downloads, with failed RETR but reused control connection + + +ftp://%HOSTIP:%FTPPORT/dir/%TESTNUMBER ftp://%HOSTIP:%FTPPORT/dir/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +QUIT + + +78 + + +USER anonymous +PASS ftp@example.com +PWD +CWD dir +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +EPSV +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1108 b/local-test-curl-delta-01/afc-curl/tests/data/test1108 new file mode 100644 index 0000000000000000000000000000000000000000..c6008af300594bfa7e60acf5fff64ce5dc192d49 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1108 @@ -0,0 +1,45 @@ + + + +FTP +PASV +RETR +PRET + + +# Server-side + + + +REPLY PRET 550 unknown command + + + +# Client-side + + +ftp + + +FTP RETR PASV with PRET not supported + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER --ftp-pret + + + + +# Verify data after the test has been "shot" + + +USER anonymous +PASS ftp@example.com +PWD +PRET RETR %TESTNUMBER + +# we expect that the server doesn't understand PRET + +84 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1122 b/local-test-curl-delta-01/afc-curl/tests/data/test1122 new file mode 100644 index 0000000000000000000000000000000000000000..478bafb3cf4e115bac24b0217b6b4cf83af639fc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1122 @@ -0,0 +1,69 @@ + + + +HTTP +HTTP GET +compressed +Transfer-Encoding + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LIHN3c2Nsb3NlDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUz +IEdNVA0KU2VydmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8x +LjMuMjYuMWEgUEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3Bl +cmwvMS4yOQ0KVmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsg +Y2hhcnNldD1JU08tODg1OS0xDQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcA0KQ29udGVudC1MZW5n +dGg6IDQ0DQoNCh+LCAh5nqtBAANsYWxhbGEAy8nMS1Uw5FLIAdFGXAoQhjEXAAoCcWAYAAAA + + +# This ignore Content-Length + +HTTP/1.1 200 OK swsclose +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Transfer-Encoding: gzip +Content-Length: 44 + +line 1 + line 2 + line 3 + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET gzip transfer-encoded content + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --tr-encoding + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Connection: TE +TE: gzip + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1125 b/local-test-curl-delta-01/afc-curl/tests/data/test1125 new file mode 100644 index 0000000000000000000000000000000000000000..62e56e6e70d4e34595d715117106a0d08ac7094e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1125 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP GET +compressed +Transfer-Encoding + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcCwgY2h1bmtlZA0KDQoyYw0KH4sICHme +q0EAA2xhbGFsYQDLycxLVTDkUsgB0UZcChCGMRcACgJxYBgAAAANCjANCg0K + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Transfer-Encoding: gzip, chunked + +line 1 + line 2 + line 3 + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET transfer-encoding with custom Connection: + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --tr-encoding -H "Connection: close" + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Connection: close, TE +TE: gzip + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1126 b/local-test-curl-delta-01/afc-curl/tests/data/test1126 new file mode 100644 index 0000000000000000000000000000000000000000..b25820b0cfa594811592116d2f3aa179f5d70f22 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1126 @@ -0,0 +1,50 @@ + + + +HTTP +HTTP GET +If-Modified-Since + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2003 12:10:00 GMT +Content-Length: 11 +Content-Type: text/html + +0123456789 + + + +# +# Client-side + + +http + + +HTTP 200 If-Modified-Since with newer document + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -z "dec 12 12:00:00 1999 GMT" + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +If-Modified-Since: Sun, 12 Dec 1999 12:00:00 GMT + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1143 b/local-test-curl-delta-01/afc-curl/tests/data/test1143 new file mode 100644 index 0000000000000000000000000000000000000000..e9053b179436d0f4541fee153cfd1b98778df02e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1143 @@ -0,0 +1,48 @@ + + + +HTTP +HTTP GET +followlocation + + +# Server-side + + +HTTP/1.1 200 hello +Connection: close +Content-Length: 4 + +hej + + + +# Client-side + + +http + + +HTTP URL with http:/ (one slash!) + + +http:/%HOSTIP:%HTTPPORT/want/%TESTNUMBER + + +# Needed for MSYS2 to not treat the argument as a POSIX path list +# that has to be converted to Windows paths +MSYS2_ARG_CONV_EXCL=http:/ + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1159 b/local-test-curl-delta-01/afc-curl/tests/data/test1159 new file mode 100644 index 0000000000000000000000000000000000000000..6ef2e4ad66e7e2d7527938b9ef951ab7f8169858 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1159 @@ -0,0 +1,56 @@ + + + +HTTP +HTTP GET +redirect_url +followlocation +--write-out + + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message swsclose +Location: ht3p://localhost/ +Content-Length: 62 +Connection: close + +This server reply is for testing a simple Location: following + + + +# Client-side + + +http + + +HTTP Location: and 'redirect_url' with non-supported scheme + + +http://%HOSTIP:%HTTPPORT/we/want/our/%TESTNUMBER -w '%{redirect_url}\n' + + + +# Verify data after the test has been "shot" + + +GET /we/want/our/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +HTTP/1.1 301 This is a weirdo text message swsclose +Location: ht3p://localhost/ +Content-Length: 62 +Connection: close + +This server reply is for testing a simple Location: following +ht3p://localhost/ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1160 b/local-test-curl-delta-01/afc-curl/tests/data/test1160 new file mode 100644 index 0000000000000000000000000000000000000000..0e946b34bf46e06f70ad17385b85dfdfe8236689 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1160 @@ -0,0 +1,55 @@ + + + + +HTTP +HTTP GET +cookies + + + +# Server-side + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 0 +Set-Cookie: ____________ÿ= ; ÿ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz†……€zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzúzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzó –zzzzzzzzzzzz~zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz¶zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz + + + + +# Client-side + + +http + + +HTTP with long funny format cookie + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -c %LOGDIR/cookies%TESTNUMBER.txt + + +cookies + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +# Netscape HTTP Cookie File +# https://curl.se/docs/http-cookies.html +# This file was generated by libcurl! Edit at your own risk. + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1163 b/local-test-curl-delta-01/afc-curl/tests/data/test1163 new file mode 100644 index 0000000000000000000000000000000000000000..09ede0cb8712f535652aea11734fc20d35adacaf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1163 @@ -0,0 +1,55 @@ + + + +FTP +RETR +LIST +wildcardmatch +ftplistparser +flaky + + + +# +# Server-side + + + + + +# Client-side + + +ftp + + +lib576 + + +FTP wildcard with pattern ending with an open-bracket + + +"ftp://%HOSTIP:%FTPPORT/fully_simulated/DOS/*[][" + + + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD fully_simulated +CWD DOS +EPSV +TYPE A +LIST +QUIT + +# 78 == CURLE_REMOTE_FILE_NOT_FOUND + +78 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1166 b/local-test-curl-delta-01/afc-curl/tests/data/test1166 new file mode 100644 index 0000000000000000000000000000000000000000..92e8ff40469b378fb7f9f2b5748f43d7d671d839 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1166 @@ -0,0 +1,52 @@ + + + +HTTP +HTTP GET +followlocation +cookies + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Set-Cookie: trackyou=want; path=/ +Content-Length: 68 + +This server reply is for testing a Location: following with cookies + + + +# Client-side + + +http + + +HTTP response with cookies but not receiving! + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1167 b/local-test-curl-delta-01/afc-curl/tests/data/test1167 new file mode 100644 index 0000000000000000000000000000000000000000..76777f81b7f74f68989f39b8bcad680be7172d72 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1167 @@ -0,0 +1,24 @@ + + + +source analysis + + + +# +# Client-side + + +none + + + +Verify curl prefix of public symbols in header files + + + +%SRCDIR/test1167.pl %SRCDIR/.. + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1169 b/local-test-curl-delta-01/afc-curl/tests/data/test1169 new file mode 100644 index 0000000000000000000000000000000000000000..bba5d131e5adffe1d015f52d1fc87cd1fd8ec7bf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1169 @@ -0,0 +1,34 @@ + + + +runtests.pl + + + +# +# Client-side + + +none + + +Verify that runtests.pl accepts an -L option + + + +%SRCDIR/runtests.pl -L %PWD/%LOGDIR/test%TESTNUMBER-library.pl + +# Create a simple perl snippet that lets runtests.pl +# exit with a code we can check. + +exit 123 + + + + + +123 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test117 b/local-test-curl-delta-01/afc-curl/tests/data/test117 new file mode 100644 index 0000000000000000000000000000000000000000..c292af73078cad9fab4ffdd830aeb77d48e9d6d5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test117 @@ -0,0 +1,47 @@ + + + +FTP +FAILURE + + +# Server-side + + +REPLY EPSV 314 bluah you f00l! +REPLY TYPE 314 bluah you f00l! + + + +# Client-side + + +ftp + + +FTP download, failed TYPE + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +QUIT + + +17 + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +PASV +TYPE I +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1170 b/local-test-curl-delta-01/afc-curl/tests/data/test1170 new file mode 100644 index 0000000000000000000000000000000000000000..16dc6908df41e738cb513e18e8369817f133da48 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1170 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP GET +compressed +Transfer-Encoding + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcCwgY2h1bmtlZA0KDQoyYw0KH4sICHme +q0EAA2xhbGFsYQDLycxLVTDkUsgB0UZcChCGMRcACgJxYBgAAAANCjANCg0K + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Transfer-Encoding: gzip, chunked + +line 1 + line 2 + line 3 + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET transfer-encoding with removed Connection: + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --tr-encoding -H "Connection:" + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Connection: TE +TE: gzip + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1173 b/local-test-curl-delta-01/afc-curl/tests/data/test1173 new file mode 100644 index 0000000000000000000000000000000000000000..89b0cb5a7a5e04e5284967a63d56671222d6fadb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1173 @@ -0,0 +1,32 @@ + + + +source analysis +documentation +--manual + + + +# +# Client-side + + +none + + + +Manpage syntax checks + + + +%SRCDIR/test1173.pl %SRCDIR/../docs/libcurl/symbols-in-versions %PWD/../docs/*.1 %PWD/../docs/cmdline-opts/*.1 %PWD/../docs/libcurl/*.3 %PWD/../docs/libcurl/opts/*.3 + + + + + +ok + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1182 b/local-test-curl-delta-01/afc-curl/tests/data/test1182 new file mode 100644 index 0000000000000000000000000000000000000000..118b967b3e8953f1bbd618496368400211d2872f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1182 @@ -0,0 +1,35 @@ + + + +runtests.pl + + + +# +# Client-side + + +none + + +Verify that runtests.pl accepts an exclude file with the -E option + + + +%SRCDIR/runtests.pl -o TESTDIR=%LOGDIR/data -o LOGDIR=%LOGDIR/log -E %LOGDIR/test%TESTNUMBER-exclude-file 1 + + +mkdir %LOGDIR/data ; mkdir %LOGDIR/log; cp %SRCDIR/data/test1 %LOGDIR/data; echo 'test:1:Test should not run for unit test %TESTNUMBER' > %LOGDIR/test%TESTNUMBER-exclude-file + + + + + +1 + + +grep -q "Test should not run for unit test %TESTNUMBER" %LOGDIR/stdout%TESTNUMBER + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1183 b/local-test-curl-delta-01/afc-curl/tests/data/test1183 new file mode 100644 index 0000000000000000000000000000000000000000..5f795ed66601258ebe55dea15f4b9a532471b6fb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1183 @@ -0,0 +1,48 @@ + + + +HTTP +HTTP GET + + + +# Server-side + + +HTTP/1.1 200 OK +Server: Blafasel/5.0 +Date: Sat, 16 Jan 2021 14:48:30 GMT +Content-Length: 12 + +Bla bla bla + + + + +# Client-side + + +http + + +proxy + + +%TESTNUMBER used instead of actual test number + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify that the %TESTNUMBER has been resolved to %TESTNUMBER + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1184 b/local-test-curl-delta-01/afc-curl/tests/data/test1184 new file mode 100644 index 0000000000000000000000000000000000000000..268da350fbe8c9fa27562605a6cc07067a368332 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1184 @@ -0,0 +1,108 @@ + + + +HTTP +HTTP CONNECT +HTTP proxy +proxytunnel + + + +# +# Server-side + + +HTTP/1.1 200 Mighty fine indeed +Server: test tunnel 2000 + + + + +HTTP/1.1 302 OK +Location: http://%HOSTIP.%TESTNUMBER:%HTTPPORT/we/want/that/page/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Funny-head: yesyes +Content-Length: 9 +Connection: close + +contents + + + +HTTP/1.1 200 OK +Content-Length: 7 + +second + + + +# +# Client-side + + +http +http-proxy + + +HTTP 1.1 CONNECT with redirect and set -H user-agent + + +-x %HOSTIP:%PROXYPORT -p http://%HOSTIP.%TESTNUMBER:%HTTPPORT/we/want/that/page/%TESTNUMBER -L -H "User-Agent: %TESTNUMBER-agent" + + +proxy + + + +# +# Verify data after the test has been "shot" + + +CONNECT %HOSTIP.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: %HOSTIP.%TESTNUMBER:%HTTPPORT +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + +CONNECT %HOSTIP.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: %HOSTIP.%TESTNUMBER:%HTTPPORT +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + +GET /we/want/that/page/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP.%TESTNUMBER:%HTTPPORT +Accept: */* +User-Agent: %TESTNUMBER-agent + +GET /we/want/that/page/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP.%TESTNUMBER:%HTTPPORT +Accept: */* +User-Agent: %TESTNUMBER-agent + + + +HTTP/1.1 200 Mighty fine indeed +Server: test tunnel 2000 + +HTTP/1.1 302 OK +Location: http://%HOSTIP.%TESTNUMBER:%HTTPPORT/we/want/that/page/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Funny-head: yesyes +Content-Length: 9 +Connection: close + +HTTP/1.1 200 Mighty fine indeed +Server: test tunnel 2000 + +HTTP/1.1 200 OK +Content-Length: 7 + +second + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1185 b/local-test-curl-delta-01/afc-curl/tests/data/test1185 new file mode 100644 index 0000000000000000000000000000000000000000..c3133aa23b5f89bf0830be96d954d17ea618be6e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1185 @@ -0,0 +1,210 @@ + + + +checksrc + + + +# +# Client-side + + +none + + +checksrc + + + +%SRCDIR/../scripts/checksrc.pl %LOGDIR/code%TESTNUMBER.c + + +/* test source code + * Violate each rule at least once. + **/ +int hello; /*------------------------------------------------------------------*/ +int tab; +int trailing_space; +int a = func (); +int b = func( b); +int b = func(b ); +func(a, b , c); + +int hello() +{ + return(2); +} +func(a, b,c); + +if(a == 2) { + ; +} else { + moo = 2; +} + +if(a == 2){ /* followed by comment */ + ; +} + +func() ; + +a = sprintf(buffer, "%s", moo); + +FILE *f = fopen("filename", "r"); + +void startfunc(int a, int b) { + func(); +} + + for(;;) { + func(1); + } while(1); + + char * name = "hello"; + char* name = "hello"; + + int foo=bar; + int foo= bar; + int foo = bar; + int foo = bar;foo++; + for(;;) { + } + + int a = sizeof int; + int a = snprintf(buffer, sizeof(buffer), "%d", 99); + int moo = hej?wrong:a>b; + int moo2 = wrong2:(a)>(b); + + if(a) b++; + + // CPP comment ? + + /* comment doesn't end + + + + +# +# Verify data after the test has been "shot" + + +./%LOGDIR/code1185.c:4:82: warning: Longer than 79 columns (LONGLINE) + int hello; /*------------------------------------------------------------------*/ +./%LOGDIR/code1185.c:5:4: error: Contains TAB character (TABS) + int tab; + ^ +./%LOGDIR/code1185.c:7:13: warning: func with space (SPACEBEFOREPAREN) + int a = func (); + ^ +./%LOGDIR/code1185.c:8:14: warning: space after open parenthesis (SPACEAFTERPAREN) + int b = func( b); + ^ +./%LOGDIR/code1185.c:9:16: warning: space before close parenthesis (SPACEBEFORECLOSE) + int b = func(b ); + ^ +./%LOGDIR/code1185.c:10:11: warning: space before comma (SPACEBEFORECOMMA) + func(a, b , c); + ^ +./%LOGDIR/code1185.c:14:9: warning: return without space before paren (RETURNNOSPACE) + return(2); + ^ +./%LOGDIR/code1185.c:16:11: warning: comma without following space (COMMANOSPACE) + func(a, b,c); + ^ +./%LOGDIR/code1185.c:18:12: warning: wrongly placed open brace (BRACEPOS) + if(a == 2) { + ^ +./%LOGDIR/code1185.c:20:1: warning: else after closing brace on same line (BRACEELSE) + } else { + ^ +./%LOGDIR/code1185.c:24:11: warning: missing space after close paren (PARENBRACE) + if(a == 2){ + ^ +./%LOGDIR/code1185.c:28:7: warning: no space before semicolon (SPACESEMICOLON) + func() ; + ^ +./%LOGDIR/code1185.c:30:5: warning: use of sprintf is banned (BANNEDFUNC) + a = sprintf(buffer, "%s", moo); + ^ +./%LOGDIR/code1185.c:32:11: warning: use of non-binary fopen without FOPEN_* macro: r (FOPENMODE) + FILE *f = fopen("filename", "r"); + ^ +./%LOGDIR/code1185.c:34:30: warning: wrongly placed open brace (BRACEPOS) + void startfunc(int a, int b) { + ^ +./%LOGDIR/code1185.c:39:6: warning: not indented 2 steps (uses 4) (INDENTATION) + func(1); + ^ +./%LOGDIR/code1185.c:42:8: warning: space after declarative asterisk (ASTERISKSPACE) + char * name = "hello"; + ^ +./%LOGDIR/code1185.c:43:7: warning: space after declarative asterisk (ASTERISKSPACE) + char* name = "hello"; + ^ +./%LOGDIR/code1185.c:43:6: warning: no space before asterisk (ASTERISKNOSPACE) + char* name = "hello"; + ^ +./%LOGDIR/code1185.c:45:10: warning: no space after equals sign (EQUALSNOSPACE) + int foo=bar; + ^ +./%LOGDIR/code1185.c:46:9: warning: no space before equals sign (NOSPACEEQUALS) + int foo= bar; + ^ +./%LOGDIR/code1185.c:48:16: warning: no space after semicolon (SEMINOSPACE) + int foo = bar;foo++; + ^ +./%LOGDIR/code1185.c:49:10: warning: multiple spaces (MULTISPACE) + for(;;) { + ^ +./%LOGDIR/code1185.c:50:2: warning: not indented 2 steps (uses 0) (INDENTATION) + } + ^ +./%LOGDIR/code1185.c:52:16: warning: sizeof without parenthesis (SIZEOFNOPAREN) + int a = sizeof int; + ^ +./%LOGDIR/code1185.c:53:10: warning: use of snprintf is banned (SNPRINTF) + int a = snprintf(buffer, sizeof(buffer), "%d", 99); + ^ +./%LOGDIR/code1185.c:54:21: warning: missing space before colon (NOSPACEC) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:54:22: warning: missing space after colon (NOSPACEC) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:54:15: warning: missing space before question mark (NOSPACEQ) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:54:16: warning: missing space after question mark (NOSPACEQ) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:54:23: warning: missing space before less or greater than (NOSPACETHAN) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:54:23: warning: missing space after less or greater than (NOSPACETHAN) + int moo = hej?wrong:a>b; + ^ +./%LOGDIR/code1185.c:55:23: warning: missing space before less or greater than (NOSPACETHAN) + int moo2 = wrong2:(a)>(b); + ^ +./%LOGDIR/code1185.c:55:23: warning: missing space after less or greater than (NOSPACETHAN) + int moo2 = wrong2:(a)>(b); + ^ +./%LOGDIR/code1185.c:57:7: warning: conditional block on the same line (ONELINECONDITION) + if(a) b++; + ^ +./%LOGDIR/code1185.c:59:2: warning: // comment (CPPCOMMENTS) + // CPP comment ? + ^ +./%LOGDIR/code1185.c:1:1: error: Missing copyright statement (COPYRIGHT) + + ^ +./%LOGDIR/code1185.c:1:1: error: Missing closing comment (OPENCOMMENT) + + ^ +checksrc: 0 errors and 38 warnings + + +5 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1194 b/local-test-curl-delta-01/afc-curl/tests/data/test1194 new file mode 100644 index 0000000000000000000000000000000000000000..cabf6beb0f172a0fc6311134d13b6f7e54768413 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1194 @@ -0,0 +1,59 @@ + + + +MQTT +MQTT SUBSCRIBE + + + +# +# Server-side + + +hello + + +00 04 31 31 39 30 68 65 6c 6c 6f 5b 4c 46 5d 0a + + +PUBLISH-before-SUBACK TRUE + + + +# +# Client-side + + +mqtt + + +mqtt + + +MQTT SUBSCRIBE with PUBLISH befoire SUBACK + + +mqtt://%HOSTIP:%MQTTPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + +# These are hexadecimal protocol dumps from the client +# +# Strip out the random part of the client id from the CONNECT message +# before comparison + +s/^(.* 00044d5154540402003c000c6375726c).*/$1/ + + +client CONNECT 18 00044d5154540402003c000c6375726c +server CONNACK 2 20020000 +client SUBSCRIBE 9 000100043131393400 +server PUBLISH c 300c00043131393468656c6c6f0a +server SUBACK 3 9003000100 +server DISCONNECT 0 e000 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1198 b/local-test-curl-delta-01/afc-curl/tests/data/test1198 new file mode 100644 index 0000000000000000000000000000000000000000..a81e4bb81507e39540bf7a5467c2a382ed9bb84c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1198 @@ -0,0 +1,54 @@ + + + +MQTT +MQTT SUBSCRIBE + + + +# +# Server-side + + +hello + + +00 04 31 31 39 30 68 65 6c 6c 6f 5b 4c 46 5d 0a + + + +# +# Client-side + + +mqtt + + +mqtt + + +MQTT PUBLISH empty payload, single space topic + + +mqtt://%HOSTIP:%MQTTPORT/%20 -d "" + + + +# +# Verify data after the test has been "shot" + +# These are hexadecimal protocol dumps from the client +# +# Strip out the random part of the client id from the CONNECT message +# before comparison + +s/^(.* 00044d5154540402003c000c6375726c).*/$1/ + + +client CONNECT 18 00044d5154540402003c000c6375726c +server CONNACK 2 20020000 +client PUBLISH 3 000120 +client DISCONNECT 0 e000 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1205 b/local-test-curl-delta-01/afc-curl/tests/data/test1205 new file mode 100644 index 0000000000000000000000000000000000000000..5a7fb7dc51fae3c94976c6d2e30d50d9202a2203 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1205 @@ -0,0 +1,48 @@ + + + +HTTP +HTTP GET + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Funny-head: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAendofthem + +-foo- + + + +# +# Client-side + + +http + + +HTTP GET with 18K HTTP header + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1214 b/local-test-curl-delta-01/afc-curl/tests/data/test1214 new file mode 100644 index 0000000000000000000000000000000000000000..fc8a94eaf70f9bb8f01a648f3e971a04adcd90df --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1214 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP GET +HTTP proxy + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Funny-head: yesyes +Content-Length: 22 + +the content goes here + + + +# Client-side + + +http + + +HTTP with proxy and URL with ? and no slash separator + +# the thing here is that this sloppy form is accepted and we convert it +# for normal server use, and we need to make sure it gets converted to +# RFC style even for proxies + +-x %HOSTIP:%HTTPPORT http://we.want.that.site.com.%TESTNUMBER?moo=foo + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://we.want.that.site.com.%TESTNUMBER/?moo=foo HTTP/1.1 +Host: we.want.that.site.com.%TESTNUMBER +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1220 b/local-test-curl-delta-01/afc-curl/tests/data/test1220 new file mode 100644 index 0000000000000000000000000000000000000000..38e5b8876cdab9aa661e0c44604d3490217341b4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1220 @@ -0,0 +1,37 @@ + + + +FILE +URL + + + +# Server-side + + + + + +# Client-side + + +file + + +file:// URLs with query string + + +file://localhost%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt?a_query=foobar#afragment + + +contents in a single file + + + +# Verify data after the test has been "shot" + + +contents in a single file + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1222 b/local-test-curl-delta-01/afc-curl/tests/data/test1222 new file mode 100644 index 0000000000000000000000000000000000000000..b46fd11563568bca90c7b6f9e8bb1cbb17d93a5f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1222 @@ -0,0 +1,24 @@ + + + +source analysis + + + +# +# Client-side + + +none + + + +Verify deprecation statuses and versions + + + +%SRCDIR/test1222.pl %SRCDIR/.. + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1224 b/local-test-curl-delta-01/afc-curl/tests/data/test1224 new file mode 100644 index 0000000000000000000000000000000000000000..61036cd085dccde542ce40b7247c48f54d4d442f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1224 @@ -0,0 +1,52 @@ + + + +FTP +PASV +RETR + + +# Server-side + + +data + to + see +that FTP +works + so does it? + + + +# Client-side + + +ftp + + +FTP fetch a file from the root directory + + +ftp://%HOSTIP:%FTPPORT//%TESTNUMBER + + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD / +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1228 b/local-test-curl-delta-01/afc-curl/tests/data/test1228 new file mode 100644 index 0000000000000000000000000000000000000000..a4df51c46ccf5b499eeea4dcfd1425a6f248826f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1228 @@ -0,0 +1,58 @@ + + + +HTTP +HTTP GET +HTTP proxy +cookies +cookie path + + + + +HTTP/1.1 200 OK +Date: Tue, 25 Sep 2001 19:37:44 GMT +Set-Cookie: path1=root; domain=.example.fake; path=/; +Set-Cookie: path2=depth1; domain=.example.fake; path=/hoge; +Content-Length: 34 + +This server says cookie path test + + + +# Client-side + + +http + + +HTTP cookie path match + + +http://example.fake/hoge/%TESTNUMBER http://example.fake/hogege/ -b nonexisting -x %HOSTIP:%HTTPPORT + + +cookies +proxy + + + +# Verify data after the test has been "shot" + + +GET http://example.fake/hoge/%TESTNUMBER HTTP/1.1 +Host: example.fake +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://example.fake/hogege/ HTTP/1.1 +Host: example.fake +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive +Cookie: path1=root + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1231 b/local-test-curl-delta-01/afc-curl/tests/data/test1231 new file mode 100644 index 0000000000000000000000000000000000000000..2c7c8bb0009d3b1de007c9d5deecffd95087b204 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1231 @@ -0,0 +1,60 @@ + + + +HTTP +HTTP GET +dotdot removal + + + +# +# Server-side + + +HTTP/1.1 200 OK +Content-Length: 6 +Connection: close + +-foo- + + + +HTTP/1.1 200 OK +Content-Length: 7 +Connection: close + +-cool- + + + +# +# Client-side + + +http + + +HTTP URL with dotdot removal from path + + +http://%HOSTIP:%HTTPPORT/../../hej/but/who/../%TESTNUMBER?stupid=me/../%TESTNUMBER#soo/../%TESTNUMBER http://%HOSTIP:%HTTPPORT/../../hej/but/who/../%TESTNUMBER0001#/../%TESTNUMBER0001 + + + +# +# Verify data after the test has been "shot" + + +GET /hej/but/%TESTNUMBER?stupid=me/../%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /hej/but/%TESTNUMBER0001 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1232 b/local-test-curl-delta-01/afc-curl/tests/data/test1232 new file mode 100644 index 0000000000000000000000000000000000000000..28d2eee735d76ae232fa309d2e587198d69a450c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1232 @@ -0,0 +1,67 @@ + + +# This test is a copy of test 1231, modified to use an HTTP proxy. + +HTTP +HTTP GET +HTTP proxy +dotdot removal + + + +# +# Server-side + + +HTTP/1.1 200 OK +Content-Length: 6 +Connection: close + +-foo- + + + +HTTP/1.1 200 OK +Content-Length: 7 +Connection: close + +-cool- + + + +# +# Client-side + + +http + + +HTTP URL with dotdot removal from path using an HTTP proxy + + +--proxy http://%HOSTIP:%HTTPPORT http://test.remote.haxx.se.%TESTNUMBER:8990/../../hej/but/who/../%TESTNUMBER?stupid=me/../%TESTNUMBER#soo/../%TESTNUMBER http://test.remote.haxx.se.%TESTNUMBER:8990/../../hej/but/who/../%TESTNUMBER0001#/../%TESTNUMBER0001 + + +proxy + + + +# +# Verify data after the test has been "shot" + + +GET http://test.remote.haxx.se.%TESTNUMBER:8990/hej/but/%TESTNUMBER?stupid=me/../%TESTNUMBER HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://test.remote.haxx.se.%TESTNUMBER:8990/hej/but/%TESTNUMBER0001 HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1234 b/local-test-curl-delta-01/afc-curl/tests/data/test1234 new file mode 100644 index 0000000000000000000000000000000000000000..5676a809cd0a938891bf0366ef42ad61e218e5b3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1234 @@ -0,0 +1,33 @@ + + + +globbing +{} list +FAILURE + + +# Server-side + + + +# Client-side + + +none + + +abusing {}-globbing + + +"%HOSTIP:%NOLISTENPORT/%TESTNUMBER[0-1]{" "%HOSTIP:%NOLISTENPORT/{}{}{}{" + + + +# Verify data after the test has been "shot" + +# 3 == CURLE_URL_MALFORMAT + +3 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1236 b/local-test-curl-delta-01/afc-curl/tests/data/test1236 new file mode 100644 index 0000000000000000000000000000000000000000..286bb0a02f426553562270116f20c979b4289e61 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1236 @@ -0,0 +1,33 @@ + + + +globbing +FAILURE + + +# Server-side + + + +# Client-side + + +none + + +[] globbing overflowing the range counter + +# 2^62 == 4611686018427387904 + +"%HOSTIP:%NOLISTENPORT/1234[0-1]{" "%HOSTIP:%NOLISTENPORT/[1-4611686018427387904][1-4611686018427387904]" + + + +# Verify data after the test has been "shot" + +# 3 == CURLE_URL_MALFORMAT + +3 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1237 b/local-test-curl-delta-01/afc-curl/tests/data/test1237 new file mode 100644 index 0000000000000000000000000000000000000000..7e49f830d10e43de6755da86c8bb7fbbad6967c2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1237 @@ -0,0 +1,45 @@ + + + +HTTP +HTTP Basic auth + + +# Server-side + + +HTTP/1.1 200 OK +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +-foo- + + + +# Client-side + + +http + + +URL with 1000+ letter user name + password + + +"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB@%HOSTIP:%HTTPPORT/%TESTNUMBER" + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQTpCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI= +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1254 b/local-test-curl-delta-01/afc-curl/tests/data/test1254 new file mode 100644 index 0000000000000000000000000000000000000000..07e77ed2a2eccae494baa1ba49a1ae86506a07d7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1254 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP proxy +NO_PROXY +noproxy + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 4 +Content-Type: text/html + +foo + + + +# Client-side + + +http + + +override NO_PROXY by --noproxy and access target URL through proxy + + +NO_PROXY=example.com + + +http://somewhere.example.com/%TESTNUMBER --proxy http://%HOSTIP:%HTTPPORT --noproxy "" + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://somewhere.example.com/%TESTNUMBER HTTP/1.1 +Host: somewhere.example.com +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1262 b/local-test-curl-delta-01/afc-curl/tests/data/test1262 new file mode 100644 index 0000000000000000000000000000000000000000..2cb5d8857c6e82a3aa81b03449448354450fa10f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1262 @@ -0,0 +1,43 @@ + +# similar to test 139 but with a reversed time condition + + +FTP +RETR +-z + + +# Server-side + + +213 20030409102659 + + + +# Client-side + + +ftp + + +FTP request and denied to download an older file with -z + + +ftp://%HOSTIP:%FTPPORT/blalbla/%TESTNUMBER -z "-1 jan 2001" + + + + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD blalbla +MDTM %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1269 b/local-test-curl-delta-01/afc-curl/tests/data/test1269 new file mode 100644 index 0000000000000000000000000000000000000000..6cc68e0f007438a905bce005417aecbdbadd00d9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1269 @@ -0,0 +1,34 @@ + + + +--retry-delay + + + +# +# Server-side + + + +# +# Client-side + + +none + + +too large --retry-delay value + + +--retry 3 --retry-delay 9223372036854776 http://%HOSTIP:%NOLISTENPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +2 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test127 b/local-test-curl-delta-01/afc-curl/tests/data/test127 new file mode 100644 index 0000000000000000000000000000000000000000..6871e0dc4e4c626ce4e79a899ae03cd34e20f5fd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test127 @@ -0,0 +1,49 @@ + + + +FTP +PASV +RETR +--disable-epsv + + +# Server-side + + +moooooooo + + + +# Client-side + + +ftp + + +FTP --disable-epsv + + +ftp://%HOSTIP:%FTPPORT/path/to/file/%TESTNUMBER --disable-epsv + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +CWD to +CWD file +PASV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1270 b/local-test-curl-delta-01/afc-curl/tests/data/test1270 new file mode 100644 index 0000000000000000000000000000000000000000..1e1fa67bb54f5fc5f2d2bca6ba496efa0c42ee4b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1270 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP GET +redirect_url +followlocation +--write-out + + + +# Server-side + + +HTTP/1.1 302 Captive Portal +Server: ohlala/2000 +Date: Tue, 17 Dec 2019 13:08:30 GMT +Cache-Control: no-cache,no-store,must-revalidate,post-check=0,pre-check=0 +Location: https://moo.moo.moo +Content-Type: text/html; charset=utf-8 +X-Frame-Options: SAMEORIGIN +Strict-Transport-Security: max-age=604800 +Content-Length: 0 +Connection: close + + + + +# Client-side + + +http + + +Basic 'redirect_url' + + +http://%HOSTIP:%HTTPPORT/we/want/our/%TESTNUMBER -w '%{redirect_url}\n' -s + + + +# Verify data after the test has been "shot" + + +GET /we/want/our/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +HTTP/1.1 302 Captive Portal +Server: ohlala/2000 +Date: Tue, 17 Dec 2019 13:08:30 GMT +Cache-Control: no-cache,no-store,must-revalidate,post-check=0,pre-check=0 +Location: https://moo.moo.moo +Content-Type: text/html; charset=utf-8 +X-Frame-Options: SAMEORIGIN +Strict-Transport-Security: max-age=604800 +Content-Length: 0 +Connection: close + +https://moo.moo.moo/ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1282 b/local-test-curl-delta-01/afc-curl/tests/data/test1282 new file mode 100644 index 0000000000000000000000000000000000000000..f57275187f2e4026e37dbffe6e364aebe271d678 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1282 @@ -0,0 +1,45 @@ + + + +FTP +PASV +RETR + + +# Server-side + + +REPLY PASS 633 XXXXXXXX\x00\x00XXXXXXXX + + + +# Client-side + + +ftp + + +GSS-API + + +FTP with 633 response before gss initialized + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER + + + + +# Verify data after the test has been "shot" + + +USER anonymous +PASS ftp@example.com + + +# 67 == CURLE_LOGIN_DENIED + +67 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1285 b/local-test-curl-delta-01/afc-curl/tests/data/test1285 new file mode 100644 index 0000000000000000000000000000000000000000..986cb92cc76c4df215d4add73568df24585efed4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1285 @@ -0,0 +1,95 @@ + + + +HTTP +HTTP PUT +HTTP Digest auth + + + +# Server-side + + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + + + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + + +# Client-side + +# + +http + + +!SSPI +crypto + + +HTTP PUT --digest with user-specified Content-Length header + +# This test is to ensure 'Content-Length: 0' is sent while negotiating auth +# even when there is a user-specified Content-Length header. +# https://github.com/curl/curl/pull/1242 + +-H "Content-Length: 85" -u auser:apasswd --digest -T %LOGDIR/put%TESTNUMBER http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + +This is data we upload with PUT +a second line +line three +four is the number of lines + + + +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 0 + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="auser", realm="testrealm", nonce="1053604144", uri="/%TESTNUMBER", response="dc185587d5e8391b347eef194c2a3cd6" +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 85 + +This is data we upload with PUT +a second line +line three +four is the number of lines + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1293 b/local-test-curl-delta-01/afc-curl/tests/data/test1293 new file mode 100644 index 0000000000000000000000000000000000000000..afecfaf2f9bc508c7dd931107ac61b153c512456 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1293 @@ -0,0 +1,68 @@ + + + +HTTP +HTTP GET +-F + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +Mime + + +http + + +Multipart formpost to two URLs, the first failing + + +http://0 http://%HOSTIP:%HTTPPORT/%TESTNUMBER -F= + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 138 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data + + +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1296 b/local-test-curl-delta-01/afc-curl/tests/data/test1296 new file mode 100644 index 0000000000000000000000000000000000000000..65fbdb2dbb51a734baf94db8f361ff45428072a0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1296 @@ -0,0 +1,53 @@ + + + +HTTP +HTTP Basic + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# Client-side + + +http + + + +HTTP URL with %0a in name part + + + +http://user%0aname:password@%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dXNlcgpuYW1lOnBhc3N3b3Jk +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1297 b/local-test-curl-delta-01/afc-curl/tests/data/test1297 new file mode 100644 index 0000000000000000000000000000000000000000..386154af30b34a20b1714a120096adba190c5193 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1297 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP proxy +proxytunnel + + + +# +# Server-side + + +HTTP/1.1 200 Mighty fine indeed +Server: test tunnel 2000 + + + + + + + +# +# Client-side + + +http +http-proxy + + +CONNECT to peer that returns nothing + + +--proxytunnel --proxy %HOSTIP:%PROXYPORT http://%HOSTIP:%HTTPPORT/we/want/that/page/%TESTNUMBER + + +proxy + + + +# +# Verify data after the test has been "shot" + + +CONNECT %HOSTIP:%HTTPPORT HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + +GET /we/want/that/page/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + +# 52 - got nothing + +52 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test13 b/local-test-curl-delta-01/afc-curl/tests/data/test13 new file mode 100644 index 0000000000000000000000000000000000000000..b8bcf164944ed8952ac41715860a7b12cfb2d0d7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test13 @@ -0,0 +1,42 @@ + + + +HTTP +HTTP custom request + + +# Server-side + + +HTTP/1.1 200 Read you +Content-Length: 29 +Deleted: suppose we got a header like this! ;-) + +blabla custom request result + + + +# Client-side + + +http + + +HTTP custom request 'DELETE' + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER -X DELETE + + + +# Verify data after the test has been "shot" + + +DELETE /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1317 b/local-test-curl-delta-01/afc-curl/tests/data/test1317 new file mode 100644 index 0000000000000000000000000000000000000000..6ef065280d9efc721703139f2dcef58dd4a63584 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1317 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP GET +--resolve + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +HTTP with --resolve + + +--resolve example.com:%HTTPPORT:%HOSTIP http://example.com:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: example.com:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1343 b/local-test-curl-delta-01/afc-curl/tests/data/test1343 new file mode 100644 index 0000000000000000000000000000000000000000..c6a18f2ba7d2cb51398389054ab0abe4b2fa835e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1343 @@ -0,0 +1,70 @@ + + + +HTTP +HTTP GET + + + +# + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +12345 + + + +# +# Client-side + + +http + + +HTTP GET with -O -i without Content-Disposition, -D stdout + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -i -O -D - --output-dir %LOGDIR + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +12345 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1355 b/local-test-curl-delta-01/afc-curl/tests/data/test1355 new file mode 100644 index 0000000000000000000000000000000000000000..e99dd015d94f6816ee2ace256cda0a3fad9bdb60 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1355 @@ -0,0 +1,56 @@ + + + +FTP +RETR + + + +# Server-side + + +fooo +mooo + + + +# Client-side + + +ftp + + +FTP download, file without C-D inside, using -O -i, without -D + + +ftp://%HOSTIP:%FTPPORT/path/file%TESTNUMBER -O -i --output-dir %LOGDIR + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE file%TESTNUMBER +RETR file%TESTNUMBER +QUIT + + + +fooo +mooo + + + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1356 b/local-test-curl-delta-01/afc-curl/tests/data/test1356 new file mode 100644 index 0000000000000000000000000000000000000000..77a88be563a4e925e23c9cf7b9870e665cb46ad6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1356 @@ -0,0 +1,73 @@ + + + +FTP +RETR + + + +# Server-side + +# file%TESTNUMBER contents... + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +MOOOO + + + +# Client-side + + +ftp + + +FTP download, file with Content-Disposition inside, using -O + + +ftp://%HOSTIP:%FTPPORT/path/file%TESTNUMBER -O --output-dir %LOGDIR + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE file%TESTNUMBER +RETR file%TESTNUMBER +QUIT + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +MOOOO + + + + + +%LOGDIR/name%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1364 b/local-test-curl-delta-01/afc-curl/tests/data/test1364 new file mode 100644 index 0000000000000000000000000000000000000000..2b3b566f6ab476126c6742aa9b5422340d2e0342 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1364 @@ -0,0 +1,69 @@ + + + +HTTP +HTTP GET + + + +# + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +12345 + + + +# +# Client-side + + +http + + +HTTP GET -o fname without Content-Disposition, -D file + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -o %LOGDIR/outfile%TESTNUMBER -D %LOGDIR/heads%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +12345 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + + + + + + + +%LOGDIR/%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1373 b/local-test-curl-delta-01/afc-curl/tests/data/test1373 new file mode 100644 index 0000000000000000000000000000000000000000..7d94775d6ffca4c77996bdc6f880148bcff082be --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1373 @@ -0,0 +1,73 @@ + + + +HTTP +HTTP GET + + + +# + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +12345 + + + +# +# Client-side + + +http + + +HTTP GET -o fname -i without Content-Disposition, -D stdout + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -i -o %LOGDIR/outfile%TESTNUMBER -D - + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + +12345 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html + + + + +%LOGDIR/%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1375 b/local-test-curl-delta-01/afc-curl/tests/data/test1375 new file mode 100644 index 0000000000000000000000000000000000000000..f56a7d90b368a9b8e42a3e29a297e03675e5d539 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1375 @@ -0,0 +1,77 @@ + + + +HTTP +HTTP GET + + + +# + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +12345 + + + +# +# Client-side + + +http + + +HTTP GET -o fname -i and Content-Disposition, -D stdout + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -i -o %LOGDIR/outfile%TESTNUMBER -D - + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +12345 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + + + + +%LOGDIR/%TESTNUMBER +%LOGDIR/name%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1380 b/local-test-curl-delta-01/afc-curl/tests/data/test1380 new file mode 100644 index 0000000000000000000000000000000000000000..d534223959b71b41521e02623fb167e1018175c0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1380 @@ -0,0 +1,76 @@ + + + +FTP +RETR + + + +# Server-side + + +fooo +mooo + + + +# Client-side + + +ftp + + +FTP DL, file without C-D inside, using -o fname -D stdout + + +ftp://%HOSTIP:%FTPPORT/path/file%TESTNUMBER -o %LOGDIR/download%TESTNUMBER -D - + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE file%TESTNUMBER +RETR file%TESTNUMBER +QUIT + + + +fooo +mooo + + + +220- _ _ ____ _ +220- ___| | | | _ \| | +220- / __| | | | |_) | | +220- | (__| |_| | _ {| |___ +220 \___|\___/|_| \_\_____| +331 We are happy you popped in! +230 Welcome you silly person +257 "/" is current directory +250 CWD command successful. +229 Entering Passive Mode (stripped) +200 I modify TYPE as you wanted +213 10 +150 Binary data connection for %TESTNUMBER () (10 bytes). +226 File transfer complete + + +s/^(229 Entering Passive Mode \().*(\).*)/${1}stripped${2}/ + + + +%LOGDIR/file%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1382 b/local-test-curl-delta-01/afc-curl/tests/data/test1382 new file mode 100644 index 0000000000000000000000000000000000000000..d96ad468a78338c6c5107e51052b03f31f91990b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1382 @@ -0,0 +1,77 @@ + + + +FTP +RETR +-J + + + +# Server-side + + +fooo +mooo + + + +# Client-side + + +ftp + + +FTP DL, file without C-D inside, using -o fname -J -D stdout + + +ftp://%HOSTIP:%FTPPORT/path/file%TESTNUMBER -o %LOGDIR/download%TESTNUMBER -J -D - + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE file%TESTNUMBER +RETR file%TESTNUMBER +QUIT + + + +fooo +mooo + + + +220- _ _ ____ _ +220- ___| | | | _ \| | +220- / __| | | | |_) | | +220- | (__| |_| | _ {| |___ +220 \___|\___/|_| \_\_____| +331 We are happy you popped in! +230 Welcome you silly person +257 "/" is current directory +250 CWD command successful. +229 Entering Passive Mode (stripped) +200 I modify TYPE as you wanted +213 10 +150 Binary data connection for %TESTNUMBER () (10 bytes). +226 File transfer complete + + +s/^(229 Entering Passive Mode \().*(\).*)/${1}stripped${2}/ + + + +%LOGDIR/file%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1392 b/local-test-curl-delta-01/afc-curl/tests/data/test1392 new file mode 100644 index 0000000000000000000000000000000000000000..49472104ed09499f8d33254faeaa0ea0939166d4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1392 @@ -0,0 +1,92 @@ + + + +FTP +RETR + + + +# Server-side + +# file%TESTNUMBER contents... + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +MOOOO + + + +# Client-side + + +ftp + + +FTP DL, file with C-D inside, using -o fname -i -D stdout + + +ftp://%HOSTIP:%FTPPORT/path/file%TESTNUMBER -o %LOGDIR/download%TESTNUMBER -i -D - + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE file%TESTNUMBER +RETR file%TESTNUMBER +QUIT + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Content-Type: text/html +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange + +MOOOO + + + +220- _ _ ____ _ +220- ___| | | | _ \| | +220- / __| | | | |_) | | +220- | (__| |_| | _ {| |___ +220 \___|\___/|_| \_\_____| +331 We are happy you popped in! +230 Welcome you silly person +257 "/" is current directory +250 CWD command successful. +229 Entering Passive Mode (stripped) +200 I modify TYPE as you wanted +213 222 +150 Binary data connection for %TESTNUMBER () (222 bytes). +226 File transfer complete + + +s/^(229 Entering Passive Mode \().*(\).*)/${1}stripped${2}/ + + + +%LOGDIR/file%TESTNUMBER +%LOGDIR/name%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1397 b/local-test-curl-delta-01/afc-curl/tests/data/test1397 new file mode 100644 index 0000000000000000000000000000000000000000..f31b2c2a3f330d7e261b763962e9ecee4a46f3f2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1397 @@ -0,0 +1,22 @@ + + + +unittest +Curl_cert_hostcheck + + + +# +# Client-side + + +none + + +unittest + + +Curl_cert_hostcheck unit tests + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1400 b/local-test-curl-delta-01/afc-curl/tests/data/test1400 new file mode 100644 index 0000000000000000000000000000000000000000..2264771605e10dc3c1ee4b96769e36f4123079ad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1400 @@ -0,0 +1,110 @@ + + + +HTTP +HTTP GET +--libcurl + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Thu, 29 Jul 2008 14:49:00 GMT +Server: test-server/fake +Content-Length: 0 +Connection: close + + + + +# Client-side + + +http + + +--libcurl for simple HTTP GET + + +SSL_CERT_FILE= + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER --libcurl %LOGDIR/test%TESTNUMBER.c + + + +# Verify data after the test has been "shot" + + +GET /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +s/(USERAGENT, \")[^\"]+/${1}stripped/ +# CURLOPT_SSL_VERIFYPEER, SSH_KNOWNHOSTS and HTTP_VERSION vary with +# CURLOPT_INTERLEAVEDATA requires RTSP protocol +# configurations - just ignore them +$_ = '' if /CURLOPT_SSL_VERIFYPEER/ +$_ = '' if /CURLOPT_SSH_KNOWNHOSTS/ +$_ = '' if /CURLOPT_HTTP_VERSION/ +$_ = '' if /CURLOPT_HTTP09_ALLOWED/ +$_ = '' if /CURLOPT_INTERLEAVEDATA/ + + +/********* Sample code generated by the curl command line tool ********** + * All curl_easy_setopt() options are documented at: + * https://curl.se/libcurl/c/curl_easy_setopt.html + ************************************************************************/ +#include + +int main(int argc, char *argv[]) +{ + CURLcode ret; + CURL *hnd; + + hnd = curl_easy_init(); + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L); + curl_easy_setopt(hnd, CURLOPT_URL, "http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER"); + curl_easy_setopt(hnd, CURLOPT_USERAGENT, "stripped"); + curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); +%if ftp + curl_easy_setopt(hnd, CURLOPT_FTP_SKIP_PASV_IP, 1L); +%endif + curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L); + + /* Here is a list of options the curl code used that cannot get generated + as source easily. You may choose to either not use them or implement + them yourself. + + CURLOPT_WRITEDATA was set to an object pointer + CURLOPT_WRITEFUNCTION was set to a function pointer + CURLOPT_READDATA was set to an object pointer + CURLOPT_READFUNCTION was set to a function pointer + CURLOPT_SEEKDATA was set to an object pointer + CURLOPT_SEEKFUNCTION was set to a function pointer + CURLOPT_ERRORBUFFER was set to an object pointer + CURLOPT_STDERR was set to an object pointer + CURLOPT_DEBUGFUNCTION was set to a function pointer + CURLOPT_DEBUGDATA was set to an object pointer + CURLOPT_HEADERFUNCTION was set to a function pointer + CURLOPT_HEADERDATA was set to an object pointer + + */ + + ret = curl_easy_perform(hnd); + + curl_easy_cleanup(hnd); + hnd = NULL; + + return (int)ret; +} +/**** End of sample code ****/ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1401 b/local-test-curl-delta-01/afc-curl/tests/data/test1401 new file mode 100644 index 0000000000000000000000000000000000000000..166d444f984bfd43fccf49c7d11caeede99fe4d4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1401 @@ -0,0 +1,133 @@ + + + +HTTP +HTTP GET +HTTP Basic auth +HTTP set cookie +cookies +--libcurl + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Thu, 29 Jul 2008 14:49:00 GMT +Server: test-server/fake +Content-Length: 0 +Content-Type: text/plain +Connection: close + + + + +# Client-side + + +http + + +--libcurl for GET with various options + + +http +ftp +file +cookies + + +SSL_CERT_FILE= + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER --libcurl %LOGDIR/test%TESTNUMBER.c --basic -u fake:user -H "X-Files: Mulder" -H "X-Men: cyclops, iceman" -A MyUA -b chocolate=chip --proto "=http,ftp,file" + + + +# Verify data after the test has been "shot" + + +GET /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic ZmFrZTp1c2Vy +User-Agent: MyUA +Accept: */* +Cookie: chocolate=chip +X-Files: Mulder +X-Men: cyclops, iceman + + + +# CURLOPT_SSL_VERIFYPEER, SSH_KNOWNHOSTS and HTTP_VERSION vary with +# configurations - just ignore them +$_ = '' if /CURLOPT_SSL_VERIFYPEER/ +$_ = '' if /CURLOPT_SSH_KNOWNHOSTS/ +$_ = '' if /CURLOPT_HTTP_VERSION/ +$_ = '' if /CURLOPT_INTERLEAVEDATA/ + + +/********* Sample code generated by the curl command line tool ********** + * All curl_easy_setopt() options are documented at: + * https://curl.se/libcurl/c/curl_easy_setopt.html + ************************************************************************/ +#include + +int main(int argc, char *argv[]) +{ + CURLcode ret; + CURL *hnd; + struct curl_slist *slist1; + + slist1 = NULL; + slist1 = curl_slist_append(slist1, "X-Files: Mulder"); + slist1 = curl_slist_append(slist1, "X-Men: cyclops, iceman"); + + hnd = curl_easy_init(); + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L); + curl_easy_setopt(hnd, CURLOPT_URL, "http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER"); + curl_easy_setopt(hnd, CURLOPT_USERPWD, "fake:user"); + curl_easy_setopt(hnd, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC); + curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1); + curl_easy_setopt(hnd, CURLOPT_USERAGENT, "MyUA"); + curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); + curl_easy_setopt(hnd, CURLOPT_COOKIE, "chocolate=chip"); + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); +%if ftp + curl_easy_setopt(hnd, CURLOPT_FTP_SKIP_PASV_IP, 1L); +%endif + curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L); + curl_easy_setopt(hnd, CURLOPT_PROTOCOLS_STR, "file,ftp,http"); + + /* Here is a list of options the curl code used that cannot get generated + as source easily. You may choose to either not use them or implement + them yourself. + + CURLOPT_WRITEDATA was set to an object pointer + CURLOPT_WRITEFUNCTION was set to a function pointer + CURLOPT_READDATA was set to an object pointer + CURLOPT_READFUNCTION was set to a function pointer + CURLOPT_SEEKDATA was set to an object pointer + CURLOPT_SEEKFUNCTION was set to a function pointer + CURLOPT_ERRORBUFFER was set to an object pointer + CURLOPT_STDERR was set to an object pointer + CURLOPT_DEBUGFUNCTION was set to a function pointer + CURLOPT_DEBUGDATA was set to an object pointer + CURLOPT_HEADERFUNCTION was set to a function pointer + CURLOPT_HEADERDATA was set to an object pointer + + */ + + ret = curl_easy_perform(hnd); + + curl_easy_cleanup(hnd); + hnd = NULL; + curl_slist_free_all(slist1); + slist1 = NULL; + + return (int)ret; +} +/**** End of sample code ****/ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1407 b/local-test-curl-delta-01/afc-curl/tests/data/test1407 new file mode 100644 index 0000000000000000000000000000000000000000..aa80787266de6940b6986b0efca32a9e50c37ba4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1407 @@ -0,0 +1,112 @@ + +# Based on test851 + + +POP3 +Clear Text +LIST +--libcurl + + + +# +# Server-side + + +REPLY LIST +OK %TESTNUMBER 100\r\n. + + + +# +# Client-side + + +pop3 + + +--libcurl for POP3 LIST one message + + +SSL_CERT_FILE= + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -l -u user:secret --libcurl %LOGDIR/test%TESTNUMBER.c + +# Need ftp so the FTP options are written in the --libcurl template + +ftp + + + +# +# Verify data after the test has been "shot" + + +CAPA +USER user +PASS secret +LIST %TESTNUMBER +QUIT + + +/********* Sample code generated by the curl command line tool ********** + * All curl_easy_setopt() options are documented at: + * https://curl.se/libcurl/c/curl_easy_setopt.html + ************************************************************************/ +#include + +int main(int argc, char *argv[]) +{ + CURLcode ret; + CURL *hnd; + + hnd = curl_easy_init(); + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L); + curl_easy_setopt(hnd, CURLOPT_URL, "pop3://%HOSTIP:%POP3PORT/%TESTNUMBER"); + curl_easy_setopt(hnd, CURLOPT_DIRLISTONLY, 1L); + curl_easy_setopt(hnd, CURLOPT_USERPWD, "user:secret"); + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_FTP_SKIP_PASV_IP, 1L); + curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L); + + /* Here is a list of options the curl code used that cannot get generated + as source easily. You may choose to either not use them or implement + them yourself. + + CURLOPT_WRITEDATA was set to an object pointer + CURLOPT_WRITEFUNCTION was set to a function pointer + CURLOPT_READDATA was set to an object pointer + CURLOPT_READFUNCTION was set to a function pointer + CURLOPT_SEEKDATA was set to an object pointer + CURLOPT_SEEKFUNCTION was set to a function pointer + CURLOPT_ERRORBUFFER was set to an object pointer + CURLOPT_STDERR was set to an object pointer + CURLOPT_DEBUGFUNCTION was set to a function pointer + CURLOPT_DEBUGDATA was set to an object pointer + CURLOPT_HEADERFUNCTION was set to a function pointer + CURLOPT_HEADERDATA was set to an object pointer + + */ + + ret = curl_easy_perform(hnd); + + curl_easy_cleanup(hnd); + hnd = NULL; + + return (int)ret; +} +/**** End of sample code ****/ + + +# These options vary with configurations - just ignore them +# CURLOPT_INTERLEAVEDATA requires RTSP (HTTP) protocol +$_ = '' if /CURLOPT_USERAGENT/ +$_ = '' if /CURLOPT_MAXREDIRS/ +$_ = '' if /CURLOPT_SSL_VERIFYPEER/ +$_ = '' if /CURLOPT_SSH_KNOWNHOSTS/ +$_ = '' if /CURLOPT_HTTP_VERSION/ +$_ = '' if /CURLOPT_HTTP09_ALLOWED/ +$_ = '' if /CURLOPT_INTERLEAVEDATA/ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1408 b/local-test-curl-delta-01/afc-curl/tests/data/test1408 new file mode 100644 index 0000000000000000000000000000000000000000..5c7f6493dfeaf8d720ed0221bc73df8229711c26 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1408 @@ -0,0 +1,73 @@ + + + +HTTP +HTTP GET +IPv6 +cookies +cookiejar + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Content-Type: text/html +Set-Cookie: time=1 + +-foo- + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Content-Type: text/html +Set-Cookie: time=2 + +-foo- + + + + + +# +# Client-side + + +cookies +IPv6 + + +http-ipv6 + + +HTTP receive cookies over IPV6 + + +-c %LOGDIR/jar%TESTNUMBER -g http://%HOST6IP:%HTTP6PORT/path/%TESTNUMBER0001 http://%HOST6IP:%HTTP6PORT/path/%TESTNUMBER0002 + + + +# +# Verify data after the test has been "shot" + + +GET /path/%TESTNUMBER0001 HTTP/1.1 +Host: %HOST6IP:%HTTP6PORT +User-Agent: curl/%VERSION +Accept: */* + +GET /path/%TESTNUMBER0002 HTTP/1.1 +Host: %HOST6IP:%HTTP6PORT +User-Agent: curl/%VERSION +Accept: */* +Cookie: time=1 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test141 b/local-test-curl-delta-01/afc-curl/tests/data/test141 new file mode 100644 index 0000000000000000000000000000000000000000..5ffbc452356ae1c2f5c17e560910985b0b1043ff --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test141 @@ -0,0 +1,55 @@ + + + +FTP +NOBODY + + +# Server-side + + + + +42 + + +213 20030409102659 + + + +# Client-side + + +ftp + + +FTP download info with -I + + +ftp://%HOSTIP:%FTPPORT/blalbla/%TESTNUMBER -I + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD blalbla +MDTM %TESTNUMBER +TYPE I +SIZE %TESTNUMBER +REST 0 +QUIT + + +Last-Modified: Wed, 09 Apr 2003 10:26:59 GMT +Content-Length: 42 +Accept-ranges: bytes + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1415 b/local-test-curl-delta-01/afc-curl/tests/data/test1415 new file mode 100644 index 0000000000000000000000000000000000000000..ae07d76f42b517d6090cb8f5e38d828b3bff851a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1415 @@ -0,0 +1,93 @@ + + + +HTTP +HTTP GET +HTTP proxy +cookies +cookiejar +delete expired cookie + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 4 +Content-Type: text/html +Funny-head: yesyes +Set-Cookie: test1value=test1; domain=example.com; path=/; +%if large-time +Set-Cookie: test2value=test2; expires=Thursday, 31-Dec-2525 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test3value=test3; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test4value=test4; expires=Thursday, 31-Dec-2525 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test5value=test5; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test6value=test6; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test7value=test7; expires=Thursday, 31-Dec-2525 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test8value=test8; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +%else +Set-Cookie: test2value=test2; expires=Thursday, 31-Dec-2037 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test3value=test3; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test4value=test4; expires=Thursday, 31-Dec-2037 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test5value=test5; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test6value=test6; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +Set-Cookie: test7value=test7; expires=Thursday, 31-Dec-2037 00:00:00 GMT; domain=example.com; path=/; +Set-Cookie: test8value=test8; expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=example.com; path=/; +%endif + +boo + + + +# Client-side + + +http + + +Delete expired cookies + + +TZ=GMT + + +http://example.com/we/want/%TESTNUMBER -b none -c %LOGDIR/jar%TESTNUMBER.txt -x %HOSTIP:%HTTPPORT + + +cookies +proxy + + + +# Verify data after the test has been "shot" + + +GET http://example.com/we/want/%TESTNUMBER HTTP/1.1 +Host: example.com +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + +# Netscape HTTP Cookie File +# https://curl.se/docs/http-cookies.html +# This file was generated by libcurl! Edit at your own risk. + +%if large-time +.example.com TRUE / FALSE 17545593600 test7value test7 +.example.com TRUE / FALSE 17545593600 test4value test4 +.example.com TRUE / FALSE 17545593600 test2value test2 +%else +.example.com TRUE / FALSE 2145830400 test7value test7 +.example.com TRUE / FALSE 2145830400 test4value test4 +.example.com TRUE / FALSE 2145830400 test2value test2 +%endif +.example.com TRUE / FALSE 0 test1value test1 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1433 b/local-test-curl-delta-01/afc-curl/tests/data/test1433 new file mode 100644 index 0000000000000000000000000000000000000000..aec6181a1eb31accef56825ea35775bcfbcace26 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1433 @@ -0,0 +1,55 @@ + + + +HTTP +HTTP GET + + + + + +HTTP/1.0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + + +HTTP GET with 100-digit subversion number in response + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +1 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1438 b/local-test-curl-delta-01/afc-curl/tests/data/test1438 new file mode 100644 index 0000000000000000000000000000000000000000..cbf19550d0bc55080f553603a937c47f87dbd55d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1438 @@ -0,0 +1,57 @@ + + + +HTTP +protocol +--write-out + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 9 +Connection: close +Content-Type: text/plain + +testdata + + + + +# Client-side + + +http + + + +Check if %{scheme} returns HTTP + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --write-out '%{scheme}' + + + +# Verify data + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 9 +Connection: close +Content-Type: text/plain + +testdata +http + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1451 b/local-test-curl-delta-01/afc-curl/tests/data/test1451 new file mode 100644 index 0000000000000000000000000000000000000000..be4240118e815f37e901f90d3a65a2f6b5f2cbe3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1451 @@ -0,0 +1,40 @@ + + + +SMB + + + +# +# Server-side + + +Basic SMB test complete + + + +# +# Client-side + + +smb + + +smb + + +Basic SMB request + + +-u 'curltest:curltest' smb://%HOSTIP:%SMBPORT/TESTS/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +Basic SMB test complete + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1460 b/local-test-curl-delta-01/afc-curl/tests/data/test1460 new file mode 100644 index 0000000000000000000000000000000000000000..7422d4b99b2061e896f39dfbc90eb3a568b6e34c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1460 @@ -0,0 +1,52 @@ + + + +HTTP +HTTP GET +-J + + + +# + + +HTTP/1.1 200 swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Disposition: filename=name%TESTNUMBER; charset=funny; option=strange +Content-Length: 4 + +hej + + + +# +# Client-side + + +http + + +HTTP GET with -Ji and Content-Disposition with existing file + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -Ji -O --output-dir %LOGDIR + + +initial content + + + +# +# Verify data after the test has been "shot" + +# Warning: Failed to open the file log/name1460: File exists + +23 + + +initial content + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1461 b/local-test-curl-delta-01/afc-curl/tests/data/test1461 new file mode 100644 index 0000000000000000000000000000000000000000..f1c481ec6586ecf35def0f5c1f1ebd0033b8690b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1461 @@ -0,0 +1,60 @@ + + + +--help + + + +# +# Server-side + + + +# +# Client-side + + +manual + + +none + + +curl important --help + + +--help + + + +# +# Verify data after the test has been "shot" + + +0 + + +Usage: curl [options...] + -d, --data HTTP POST data + -f, --fail Fail fast with no output on HTTP errors + -h, --help Get help for commands + -o, --output Write to file instead of stdout + -O, --remote-name Write output to file named as remote file + -i, --show-headers Show response headers in output + -s, --silent Silent mode + -T, --upload-file Transfer local FILE to destination + -u, --user Server user and password + -A, --user-agent Send User-Agent to server + -v, --verbose Make the operation more talkative + -V, --version Show version number and quit + +This is not the full help; this menu is split into categories. +Use "--help category" to get an overview of all categories, which are: +auth, connection, curl, deprecated, dns, file, ftp, global, http, imap, ldap, +output, pop3, post, proxy, scp, sftp, smtp, ssh, telnet, tftp, timeout, tls, +upload, verbose. +Use "--help all" to list all options +Use "--help [option]" to view documentation for a given option + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1466 b/local-test-curl-delta-01/afc-curl/tests/data/test1466 new file mode 100644 index 0000000000000000000000000000000000000000..315974ad413bc3d4ea64f5bc5701e2805f99412e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1466 @@ -0,0 +1,45 @@ + + + +HTTP +HTTP GET + + + + + +HTTP/1.1 405 405 +Content-Length: 6 +Connection: close + +-foo- + + + +# +# Client-side + + +http + + + +HTTP GET with 3-digit response and only digits in reason + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1467 b/local-test-curl-delta-01/afc-curl/tests/data/test1467 new file mode 100644 index 0000000000000000000000000000000000000000..568670a71a136f4910fc998ded13132cf859c286 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1467 @@ -0,0 +1,60 @@ + + + +HTTP +HTTP GET +SOCKS5 +UnixSockets + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +proxy +UnixSockets + + +http +socks5unix + + +HTTP GET via SOCKS5 proxy via Unix sockets + + +--socks5 localhost%SOCKSUNIXPATH http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1469 b/local-test-curl-delta-01/afc-curl/tests/data/test1469 new file mode 100644 index 0000000000000000000000000000000000000000..1aa512e50fbf288c499c36cdbee619ac00c7b39f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1469 @@ -0,0 +1,30 @@ + + + +FTP +URL +FAILURE + + + +# Client-side + + +none + + +Space in FTP upload URL + + +"ftp://%HOSTIP:%NOLISTENPORT/%TESTNUMBER%/with space/" -T %LOGDIR/irrelevant-file + + + +# Verify data after the test has been "shot" + +# 3 == CURLE_URL_MALFORMAT + +3 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1471 b/local-test-curl-delta-01/afc-curl/tests/data/test1471 new file mode 100644 index 0000000000000000000000000000000000000000..e8e41430ddebfca66756933b096248122a0f1274 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1471 @@ -0,0 +1,42 @@ + + + +Onion +Tor +FAILURE + + +# +# Server-side + + + +# +# Client-side + + +none + + +http + + +Fail to resolve .onion TLD + + +red.onion + + + +# +# Verify data after the test has been "shot" + +# Couldn't resolve host name + +6 + + +curl: (6) Not resolving .onion address (RFC 7686) + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1475 b/local-test-curl-delta-01/afc-curl/tests/data/test1475 new file mode 100644 index 0000000000000000000000000000000000000000..f88ef74ee279ff82f7803128ef6d2fc0d3791dd7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1475 @@ -0,0 +1,83 @@ + +# also verified by 1156 in libcurl API terms + + + +HTTP +HTTP GET +Resume + + + +# Server-side + + +HTTP/1.1 416 Invalid range +Connection: close +Content-Length: 0 +Content-Range: */100 + + + +# The file data that exists at the start of the test must be included in +# the verification. + +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +HTTP/1.1 416 Invalid range +Connection: close +Content-Length: 0 +Content-Range: */100 + + + + + +# Client-side + + +http + + +http + + +-f and 416 with Content-Range: */size + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -C - -f + + +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Range: bytes=100- +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1479 b/local-test-curl-delta-01/afc-curl/tests/data/test1479 new file mode 100644 index 0000000000000000000000000000000000000000..9e22e77f4cc4fc5fdbc1d2b88d80d860a75e3aeb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1479 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP/0.9 + + + +# +# Server-side + + +HTTP/1.1 200 OK +Content-Length: 5 + +Data + + +Data +Data +Data + + + + + +# +# Client-side + + +http + + +HTTP/1.1 response followed by an HTTP/0.9 response over the same connection + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER http://%HOSTIP:%HTTPPORT/%TESTNUMBER0002 + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +# Hyper curl returns unsupported protocol +# built-in curl returns weird_server_reply + +%if hyper +1 +%else +8 +%endif + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test148 b/local-test-curl-delta-01/afc-curl/tests/data/test148 new file mode 100644 index 0000000000000000000000000000000000000000..c8ec7a6d18b8aaf52b34920b9e8ad7b76ccb7890 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test148 @@ -0,0 +1,52 @@ + + + +FTP + + + +# Server-side + + +REPLY CWD 550 I won't allow this on my server +REPLY MKD 550 We will have no such thing + + + +# Client-side + + +ftp + + +FTP with --ftp-create-dirs (failing MKD) + + +ftp://%HOSTIP:%FTPPORT/attempt/to/get/this/%TESTNUMBER --ftp-create-dirs + + + +# Verify data after the test has been "shot" + + +QUIT + +# Strip all valid kinds of PORT and EPRT that curl can send + +^PORT \d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3} +^EPRT \|1\|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\|\d{1,5}\| + + +9 + + +USER anonymous +PASS ftp@example.com +PWD +CWD attempt +MKD attempt +CWD attempt +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1483 b/local-test-curl-delta-01/afc-curl/tests/data/test1483 new file mode 100644 index 0000000000000000000000000000000000000000..5bb59a9c9f894012ca1020fdfc2de7423963c606 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1483 @@ -0,0 +1,90 @@ + + + +HTTP +HTTP GET +chunked Transfer-Encoding +DELAY + + +# +# Server-side + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Transfer-Encoding: chunked +Connection: mooo + +40 +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +30 +bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +21;heresatest=moooo +cccccccccccccccccccccccccccccccc + +0 +%if !hyper +chunky-trailer: header data +another-header: yes +%endif + + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Transfer-Encoding: chunked +Connection: mooo + +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccc +%if !hyper +chunky-trailer: header data +another-header: yes +%endif + + +writedelay: 10 + + + +# +# Client-side + + +http + + +HTTP GET with double chunked in TE header + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -D %LOGDIR/heads%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Transfer-Encoding: chunked +Connection: mooo + +%if !hyper +chunky-trailer: header data +another-header: yes +%endif + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1484 b/local-test-curl-delta-01/afc-curl/tests/data/test1484 new file mode 100644 index 0000000000000000000000000000000000000000..52de029a081488d10083a80899a189a808dbb25b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1484 @@ -0,0 +1,53 @@ + + + +HTTP +HTTP HEAD + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Transfer-Encoding: chunked + +HEAD response with content + +# make sure no data is written + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Transfer-Encoding: chunked + + + + +# +# Client-side + + +http + + +HTTP HEAD with response body to ignore + + +-I http://%HOSTIP:%HTTPPORT/%TESTNUMBER --http1.1 + + + +# +# Verify data after the test has been "shot" + + +HEAD /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1488 b/local-test-curl-delta-01/afc-curl/tests/data/test1488 new file mode 100644 index 0000000000000000000000000000000000000000..f987e151d398378d4e3011d8917feeab31ea64c7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1488 @@ -0,0 +1,31 @@ + + + +documentation +symbols-in-versions +manpages + + + +# +# Client-side + + +none + + + +symbols-in-versions and manpages agree on added-in versions + + + +%SRCDIR/test1488.pl %SRCDIR/.. ../include/curl + + + + + +OK + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1490 b/local-test-curl-delta-01/afc-curl/tests/data/test1490 new file mode 100644 index 0000000000000000000000000000000000000000..41d4c3a4093302bbfa6c5b8af6b1a266e277e4e3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1490 @@ -0,0 +1,43 @@ + + + +FILE + + + +# no Server-side + +# Client-side + + +file + + +"upload" with file:// overwriting existing + + +file://localhost%FILE_PWD/%LOGDIR/result%TESTNUMBER.txt -T %LOGDIR/upload%TESTNUMBER.txt + + +data +in +file +to +write + + +already existing + + + +# Verify data after the test has been "shot" + + +data +in +file +to +write + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1505 b/local-test-curl-delta-01/afc-curl/tests/data/test1505 new file mode 100644 index 0000000000000000000000000000000000000000..666e4d984bb00e283aaa7e98f31434619cad6057 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1505 @@ -0,0 +1,55 @@ + + + +HTTP +HTTP GET +multi +CURLOPT_RESOLVE + + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +lib%TESTNUMBER + + +HTTP multi with CURLOPT_RESOLVE, cleanup sequence PB + + +http://google.com:%HTTPPORT/%TESTNUMBER %HTTPPORT %HOSTIP + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: google.com:%HTTPPORT +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1506 b/local-test-curl-delta-01/afc-curl/tests/data/test1506 new file mode 100644 index 0000000000000000000000000000000000000000..0a62c0c2a6424ce3729822f781e8410fdfbf63c1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1506 @@ -0,0 +1,95 @@ + + + +HTTP +multi +verbose logs + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + + +# Client-side + + +http + + +lib%TESTNUMBER + + +HTTP GET connection cache limit (CURLMOPT_MAXCONNECTS) + + +http://%HOSTIP:%HTTPPORT/path/%TESTNUMBER %HOSTIP %HTTPPORT + + + +# Verify data after the test has been "shot" + + +GET /path/%TESTNUMBER0001 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER0003 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER0004 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + + + +^Host:.* + + +* Connection #0 to host server1.example.com left intact +* Connection #1 to host server2.example.com left intact +* Connection #2 to host server3.example.com left intact +* Connection #3 to host server4.example.com left intact + + +$_ = '' if (($_ !~ /left intact/) && ($_ !~ /Closing connection/)) + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1511 b/local-test-curl-delta-01/afc-curl/tests/data/test1511 new file mode 100644 index 0000000000000000000000000000000000000000..25e9938807a3cb000f6b8d5af1939750e5e72c16 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1511 @@ -0,0 +1,71 @@ + + + +HTTP +CURLOPT_TIMECONDITION + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fakem +Last-Modified: Mon, 22 Apr 2013 17:45:05 GMT +Content-Type: text/html +Content-Length: 12 +Connection: close + +Hello World + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fakem +Last-Modified: Mon, 22 Apr 2013 17:45:05 GMT +Content-Type: text/html +Content-Length: 12 +Connection: close + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fakem +Last-Modified: Mon, 22 Apr 2013 17:45:05 GMT +Content-Type: text/html +Content-Length: 12 +Connection: close + +Hello World + + + + +# Client-side + + +http + + +http + + +lib%TESTNUMBER + + +HTTP GET time conditions in repeated requests + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" +# TEST_ERR_SUCCESS is errorcode 120 + + +120 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1512 b/local-test-curl-delta-01/afc-curl/tests/data/test1512 new file mode 100644 index 0000000000000000000000000000000000000000..c3a532c96b3bd418e173e33a094b346667bdd5a2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1512 @@ -0,0 +1,80 @@ + + + +HTTP +GLOBAL DNS CACHE + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + + +# Client-side + + +http + + +lib%TESTNUMBER + + +GLOBAL CACHE test over two easy performs + + +http://%HOSTIP:%HTTPPORT/path/%TESTNUMBER %HOSTIP %HTTPPORT + + + +# Verify data after the test has been "shot" + + +GET /path/%TESTNUMBER0001 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + + + +^Host:.* + + +$_ = '' if (($_ !~ /left intact/) && ($_ !~ /Closing connection/)) + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1516 b/local-test-curl-delta-01/afc-curl/tests/data/test1516 new file mode 100644 index 0000000000000000000000000000000000000000..79f0275f03c3efc5d5460776e78eb48927b39c55 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1516 @@ -0,0 +1,58 @@ + + + + +HTTP +multi +FAILURE +resolve + + + + +# Close the connection after the first request but don't tell the client to do +# so! When starting the second request it'll detect a dead connection and must +# not clean the DNS entries added manually. + +HTTP/1.1 200 OK +Date: Thu, 03 Feb 2014 17:04:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Content-Length: 6 + +hello + + +HTTP/1.1 200 OK +Date: Thu, 03 Feb 2014 17:04:02 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html +Content-Length: 6 + +hello + + + + + +http + + +lib1515 + + +caching of manual libcurl DNS entries after dead connection + + +/path/%TESTNUMBER %HOSTIP %HTTPPORT + + + + + +0 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1521 b/local-test-curl-delta-01/afc-curl/tests/data/test1521 new file mode 100644 index 0000000000000000000000000000000000000000..f62f58c5f9bf71cf511721efdcdca0e9ca96698f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1521 @@ -0,0 +1,33 @@ + + + +curl_easy_setopt + + + +# +# Client-side + + +none + + +lib%TESTNUMBER + + + +Test all curl_easy_setopt and curl_easy_getinfo options + + +unused + + + +# +# Verify data after the test has been "shot" + + +ok + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1523 b/local-test-curl-delta-01/afc-curl/tests/data/test1523 new file mode 100644 index 0000000000000000000000000000000000000000..7cc94ba47a747d57811533681319f19f68bd8eaa --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1523 @@ -0,0 +1,50 @@ + + + +CURLINFO_LOW_SPEED_LIMIT +DELAY + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Connection: close +Funny-head: yesyes + +AA + + +writedelay: 1000 + + +# +# Client-side + + +http + + +lib%TESTNUMBER + + + +CURLINFO_LOW_SPEED_LIMIT + + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + +http + + + +# +# Verify data after the test has been "shot" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1526 b/local-test-curl-delta-01/afc-curl/tests/data/test1526 new file mode 100644 index 0000000000000000000000000000000000000000..cd4a4f48b03223e0ec4bd4392e925faae8149b0f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1526 @@ -0,0 +1,80 @@ + + + +HTTP +HTTP PUT +HTTP CONNECT +HTTP proxy +proxytunnel +CURLOPT_PROXYHEADER + + + +# Server-side + + +HTTP/1.1 200 OK +Server: present + + + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" + + + +HTTP/1.1 200 OK +Server: present + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" + + + + +# Client-side + + +http +http-proxy + + +lib%TESTNUMBER + + +CURLOPT_PROXYHEADER: separate host/proxy headers + + + http://the.old.moo.%TESTNUMBER:%HTTPPORT/%TESTNUMBER %HOSTIP:%PROXYPORT + + +proxy + + + +# Verify data after the test has been "shot" + + +CONNECT the.old.moo.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: the.old.moo.%TESTNUMBER:%HTTPPORT +Proxy-Connection: Keep-Alive +User-Agent: Proxy Agent + + + +PUT /%TESTNUMBER HTTP/1.1 +Host: the.old.moo.%TESTNUMBER:%HTTPPORT +Accept: */* +User-Agent: Http Agent +Content-Length: 13 + +Hello Cloud! + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1544 b/local-test-curl-delta-01/afc-curl/tests/data/test1544 new file mode 100644 index 0000000000000000000000000000000000000000..037caa0ac617091477252ef69282d82a6cac3795 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1544 @@ -0,0 +1,24 @@ + + + +source analysis + + + +# +# Client-side + + +none + + + +Verify all string options are translated by OS/400 wrapper + + + +%SRCDIR/test1544.pl %SRCDIR/.. + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1546 b/local-test-curl-delta-01/afc-curl/tests/data/test1546 new file mode 100644 index 0000000000000000000000000000000000000000..0ec7093f712d9269e7ac9051642f16b75b2b81e5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1546 @@ -0,0 +1,63 @@ + + + +HTTP +HTTP GET +Transfer-Encoding + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache +Transfer-Encoding: chunked, gzip + +0 + + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache + + + + +# +# Client-side + + +libz + + +http + + +HTTP transfer-encoding wrong order + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --tr-encoding + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Connection: TE +TE: gzip + + + +61 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test155 b/local-test-curl-delta-01/afc-curl/tests/data/test155 new file mode 100644 index 0000000000000000000000000000000000000000..83aed115f8f864d26f1ae1c4c3e1b1e064b0e21d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test155 @@ -0,0 +1,130 @@ + + + +HTTP +HTTP PUT +HTTP NTLM auth +NTLM + + + +# Server-side + + +HTTP/1.1 401 NTLM Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Blackmagic realm="gimme all yer s3cr3ts" +WWW-Authenticate: Basic realm="gimme all yer s3cr3ts" +WWW-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +moo + + +# This is supposed to be returned when the server gets a first +# Authorization: NTLM line passed-in from the client + +HTTP/1.1 401 Type-1 received, send back type-2 +Server: Microsoft-IIS/5.0 +Content-Length: 34 +Content-Type: text/html; charset=iso-8859-1 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== + +This is not the real page either! + + +# This is supposed to be returned when the server gets the second +# Authorization: NTLM line passed-in from the client + +HTTP/1.1 200 Type-3 Received and all Things are fine swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + +HTTP/1.1 401 NTLM Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Blackmagic realm="gimme all yer s3cr3ts" +WWW-Authenticate: Basic realm="gimme all yer s3cr3ts" +WWW-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +HTTP/1.1 401 Type-1 received, send back type-2 +Server: Microsoft-IIS/5.0 +Content-Length: 34 +Content-Type: text/html; charset=iso-8859-1 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== + +HTTP/1.1 200 Type-3 Received and all Things are fine swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + + +# Client-side + + +NTLM +SSL +!SSPI + + +http + + +HTTP PUT with --anyauth authorization (picking NTLM) + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -T %LOGDIR/put%TESTNUMBER -u testuser:testpass --anyauth + + +This is data we upload with PUT +a second line +line three +four is the number of lines + + + +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 85 + +This is data we upload with PUT +a second line +line three +four is the number of lines +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 0 + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 85 + +This is data we upload with PUT +a second line +line three +four is the number of lines + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1557 b/local-test-curl-delta-01/afc-curl/tests/data/test1557 new file mode 100644 index 0000000000000000000000000000000000000000..031809f4e1e509b22d8786d849a7c0f462e3f0e6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1557 @@ -0,0 +1,36 @@ + + + +multi +crash + + + + + + + + +none + + +lib%TESTNUMBER + + + +Removing easy handle that's in the pending connections list doesn't leave behind a dangling entry + + +nothing + + + +# +# Verify that the test runs to completion without crashing + + +0 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1558 b/local-test-curl-delta-01/afc-curl/tests/data/test1558 new file mode 100644 index 0000000000000000000000000000000000000000..46332d198c69e305b0dffa5d5b85e8adf809da6d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1558 @@ -0,0 +1,46 @@ + + + +curl_easy_getinfo +CURLINFO_PROTOCOL + + + + + + + + +none + + +file + + +lib%TESTNUMBER + + + +CURLINFO_PROTOCOL for file:// transfer + + +file://%FILE_PWD/%LOGDIR/data%TESTNUMBER + + +hello + + + +# +# Verify that the test runs to completion without crashing + + +0 + + +hello +Protocol: 400 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1562 b/local-test-curl-delta-01/afc-curl/tests/data/test1562 new file mode 100644 index 0000000000000000000000000000000000000000..b9755aa2488d8ed19245f164055d35ebc38ee9ae --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1562 @@ -0,0 +1,72 @@ + + + +HTTPS +HTTP +HTTP GET +cookies +HTTP replaced headers + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Set-Cookie: foo=123; path=/; secure; +Content-Length: 7 + +nomnom + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Set-Cookie: foo=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ +Content-Length: 7 + +nomnom + + + +# Client-side + + +SSL + + +http +https + + +Expire secure cookies over HTTPS + + +-k https://%HOSTIP:%HTTPSPORT/%TESTNUMBER0001 -H "Host: www.example.com" https://%HOSTIP:%HTTPSPORT/%TESTNUMBER0002 -b "non-existing" https://%HOSTIP:%HTTPSPORT/%TESTNUMBER0001 + + + + +GET /%TESTNUMBER0001 HTTP/1.1 +Host: www.example.com +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER0002 HTTP/1.1 +Host: www.example.com +User-Agent: curl/%VERSION +Accept: */* +Cookie: foo=123 + +GET /%TESTNUMBER0001 HTTP/1.1 +Host: www.example.com +User-Agent: curl/%VERSION +Accept: */* + + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1570 b/local-test-curl-delta-01/afc-curl/tests/data/test1570 new file mode 100644 index 0000000000000000000000000000000000000000..e558b9bc32bff1f2333ff9eba58c3613eaeeca26 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1570 @@ -0,0 +1,76 @@ + + + +FTP +PASV +RETR + + +# Server-side + + +data + to + see +that FTP +works + so does it? + + +REPLY EPSV 500 no such command + + + +# Client-side + + +ftp + + +FTP first type=D then regular URL + + +lib1569 + + +"ftp://%HOSTIP:%FTPPORT/%TESTNUMBER;type=D" ftp://%HOSTIP:%FTPPORT/%TESTNUMBER + + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +PASV +TYPE A +NLST +PASV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + +data + to + see +that FTP +works + so does it? +data + to + see +that FTP +works + so does it? + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1595 b/local-test-curl-delta-01/afc-curl/tests/data/test1595 new file mode 100644 index 0000000000000000000000000000000000000000..4dade7c199a32016eebd6ff5fb798357f6ebf486 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1595 @@ -0,0 +1,48 @@ + + + +HTTP +HTTP GET +HTTP replaced headers +CURLOPT_TIMECONDITION +If-Modified-Since + + + +# Server-side + + +HTTP/1.1 503 Error +Date: Thu, 11 Jul 2019 02:26:59 GMT +Server: test-server/swsclose + + + +# Client-side + + +http + + +HTTP Retry-After header extraction (without header) + + +lib1594 + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + + + +Retry-After 0 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1605 b/local-test-curl-delta-01/afc-curl/tests/data/test1605 new file mode 100644 index 0000000000000000000000000000000000000000..d97c851787986613217e542a37e547b3325693b8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1605 @@ -0,0 +1,21 @@ + + + +unittest + + + +# +# Client-side + + +none + + +unittest + + +Test negative data lengths as input to libcurl functions + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1608 b/local-test-curl-delta-01/afc-curl/tests/data/test1608 new file mode 100644 index 0000000000000000000000000000000000000000..c7d6a0a90cca86a3b61ac8736b29a2eb6ca665a3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1608 @@ -0,0 +1,23 @@ + + + +unittest +curlopt_dns_shuffle_addresses + + + +# +# Client-side + + +none + + +unittest +shuffle-dns + + +verify DNS shuffling + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1610 b/local-test-curl-delta-01/afc-curl/tests/data/test1610 new file mode 100644 index 0000000000000000000000000000000000000000..8ee68d43c4d472f8a014205c6796dd07160f456a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1610 @@ -0,0 +1,22 @@ + + + +unittest +SHA256 + + + +# +# Client-side + + +none + + +unittest + + +SHA256 unit tests + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1614 b/local-test-curl-delta-01/afc-curl/tests/data/test1614 new file mode 100644 index 0000000000000000000000000000000000000000..2c4d6abe9f8d93de1aeed8fe574e6f46e7824f34 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1614 @@ -0,0 +1,25 @@ + + + +unittest + + + +# +# Client-side + + +none + + +unittest +proxy + + +noproxy and cidr comparisons + + + +0 + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1616 b/local-test-curl-delta-01/afc-curl/tests/data/test1616 new file mode 100644 index 0000000000000000000000000000000000000000..cce79c122a8365a0191f3b5ba87813f1903191af --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1616 @@ -0,0 +1,22 @@ + + + +unittest +hash + + + +# +# Client-side + + +none + + +unittest + + +Internal hash_offt create/add/destroy testing, exercising clean functions + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test167 b/local-test-curl-delta-01/afc-curl/tests/data/test167 new file mode 100644 index 0000000000000000000000000000000000000000..031b92077f3ef8f0ab4a4e0e4cd7a5a1b3f8a14d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test167 @@ -0,0 +1,78 @@ + + + +HTTP +HTTP GET +HTTP proxy +HTTP proxy Basic auth +HTTP Digest auth + + + +# Server-side + + +HTTP/1.1 401 Authorization Required swsclose +WWW-Authenticate: Digest realm="weirdorealm", nonce="12345" + + + + +HTTP/1.1 200 OK swsclose +Server: no +Content-Length: 15 + +Nice auth sir! + + + +HTTP/1.1 401 Authorization Required swsclose +WWW-Authenticate: Digest realm="weirdorealm", nonce="12345" + +HTTP/1.1 200 OK swsclose +Server: no +Content-Length: 15 + +Nice auth sir! + + + +# Client-side + + +http + + +!SSPI +crypto +proxy + + +HTTP with proxy-requiring-Basic to site-requiring-Digest + + +http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER --proxy http://%HOSTIP:%HTTPPORT --proxy-user foo:bar --digest --user digest:alot + + + +# Verify data after the test has been "shot" + + +GET http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER HTTP/1.1 +Host: data.from.server.requiring.digest.hohoho.com +Proxy-Authorization: Basic Zm9vOmJhcg== +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER HTTP/1.1 +Host: data.from.server.requiring.digest.hohoho.com +Proxy-Authorization: Basic Zm9vOmJhcg== +Authorization: Digest username="digest", realm="weirdorealm", nonce="12345", uri="/%TESTNUMBER", response="13c7c02a252cbe1c46d8669898a3be26" +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1670 b/local-test-curl-delta-01/afc-curl/tests/data/test1670 new file mode 100644 index 0000000000000000000000000000000000000000..34d79f766fce93d9fdd031baf6627dcd8878efba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1670 @@ -0,0 +1,61 @@ + + + +HTTP +HTTP GET +-w +%header + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +headers-api + + +http + + +-w individual header output + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -w '%header{etag} %header{nope} %header{DATE}\n' -o %LOGDIR/%TESTNUMBER.out + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +"21025-dc7-39462498" Tue, 09 Nov 2010 14:49:00 GMT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1680 b/local-test-curl-delta-01/afc-curl/tests/data/test1680 new file mode 100644 index 0000000000000000000000000000000000000000..4775a411b0fe1df39f7102163e4b4b9481c6a996 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1680 @@ -0,0 +1,55 @@ + + + +HTTP +HTTP GET +--clobber + + + +# +# Server-side + + +HTTP/1.0 200 OK +Connection: close +Content-Type: text/plain +Content-Length: 4 + +foo + + + +# +# Client-side + + +HTTP GET with explicit clobber + + +http + + +http + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -o %LOGDIR/exist%TESTNUMBER --clobber + + +to be overwritten + + + +# +# Verify data after the test has been "shot" + + +HTTP/1.0 200 OK +Connection: close +Content-Type: text/plain +Content-Length: 4 + +foo + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test169 b/local-test-curl-delta-01/afc-curl/tests/data/test169 new file mode 100644 index 0000000000000000000000000000000000000000..3a86cdf516a84dbe3310a815f6c28487f7e1e246 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test169 @@ -0,0 +1,119 @@ + + + +HTTP +HTTP GET +HTTP proxy +HTTP proxy NTLM auth +HTTP Digest auth +NTLM + + + +# Server-side + + +# this is returned first since we get no proxy-auth + +HTTP/1.1 407 Authorization Required to proxy me my dear swsclose +Proxy-Authenticate: NTLM + +And you should ignore this data. + + +# then this is returned since we get no server-auth + +HTTP/1.1 200 Authorizated fine +Content-Length: 27 + +Welcome to the end station + + + +HTTP/1.1 407 NTLM type-1 received sending back type-2 +Server: Microsoft-IIS/5.0 +Content-Length: 34 +Content-Type: text/html; charset=iso-8859-1 +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== + +This is not the real page either! + + +# This is supposed to be returned when the server gets the second +# Authorization: NTLM line passed-in from the client + +HTTP/1.1 401 You now need to authenticate with the host +Server: Microsoft-IIS/5.0 +WWW-Authenticate: Digest realm="r e a l m", nonce="abcdef" +Content-Length: 46 +Content-Type: text/html; charset=iso-8859-1 + +We have not authenticated with the server yet + + + +HTTP/1.1 407 NTLM type-1 received sending back type-2 +Server: Microsoft-IIS/5.0 +Content-Length: 34 +Content-Type: text/html; charset=iso-8859-1 +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== + +HTTP/1.1 401 You now need to authenticate with the host +Server: Microsoft-IIS/5.0 +WWW-Authenticate: Digest realm="r e a l m", nonce="abcdef" +Content-Length: 46 +Content-Type: text/html; charset=iso-8859-1 + +HTTP/1.1 200 Authorizated fine +Content-Length: 27 + +Welcome to the end station + + + +# Client-side + + +http + + +NTLM +SSL +!SSPI +proxy + + +HTTP with proxy-requiring-NTLM to site-requiring-Digest + + +http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER --proxy http://%HOSTIP:%HTTPPORT --proxy-user testuser:testpass --proxy-ntlm --digest --user digest:alot + + + +# Verify data after the test has been "shot" + + +GET http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER HTTP/1.1 +Host: data.from.server.requiring.digest.hohoho.com +Proxy-Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER HTTP/1.1 +Host: data.from.server.requiring.digest.hohoho.com +Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://data.from.server.requiring.digest.hohoho.com/%TESTNUMBER HTTP/1.1 +Host: data.from.server.requiring.digest.hohoho.com +Authorization: Digest username="digest", realm="r e a l m", nonce="abcdef", uri="/%TESTNUMBER", response="95d48591985a03c4b49cb962aa7bd3e6" +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test183 b/local-test-curl-delta-01/afc-curl/tests/data/test183 new file mode 100644 index 0000000000000000000000000000000000000000..ba0df8c2feae3a2633c6c357f7127c1ad6d542ec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test183 @@ -0,0 +1,56 @@ + + + +HTTP +HTTP GET +HTTP proxy +persistent connection + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 4 + +moo + + + +# Client-side + + +http + + +HTTP GET two URLs over a single proxy with persistent connection + + +http://deathstar.another.galaxy/%TESTNUMBER http://a.galaxy.far.far.away/%TESTNUMBER --proxy http://%HOSTIP:%HTTPPORT + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://deathstar.another.galaxy/%TESTNUMBER HTTP/1.1 +Host: deathstar.another.galaxy +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://a.galaxy.far.far.away/%TESTNUMBER HTTP/1.1 +Host: a.galaxy.far.far.away +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test184 b/local-test-curl-delta-01/afc-curl/tests/data/test184 new file mode 100644 index 0000000000000000000000000000000000000000..95c9e288b731aa6882eb36d9cd5fb5653d2acfc9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test184 @@ -0,0 +1,76 @@ + + + +HTTP +HTTP GET +HTTP proxy +followlocation + + + +# Server-side + + +HTTP/1.1 301 OK swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 4 +Location: http://yet.another.host/%TESTNUMBER + +moo + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 4 + +moo + + +HTTP/1.1 301 OK swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 4 +Location: http://yet.another.host/%TESTNUMBER + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 4 + +moo + + + +# Client-side + + +http + + +HTTP replace Host: when following Location: to new host + + +http://deathstar.another.galaxy/%TESTNUMBER -L -H "Host: another.visitor.stay.a.while.stay.foreeeeeever" --proxy http://%HOSTIP:%HTTPPORT + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://deathstar.another.galaxy/%TESTNUMBER HTTP/1.1 +Host: another.visitor.stay.a.while.stay.foreeeeeever +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://yet.another.host/%TESTNUMBER HTTP/1.1 +Host: yet.another.host +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test187 b/local-test-curl-delta-01/afc-curl/tests/data/test187 new file mode 100644 index 0000000000000000000000000000000000000000..aff3a9d1ade83b6bbbeea216ecb34e567f70d1fd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test187 @@ -0,0 +1,76 @@ + + + +HTTP +HTTP GET +followlocation + + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: /root/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +This server reply is for testing a simple Location: following + + + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: /root/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + + +# Client-side + + +http + + +HTTP redirect with bad host name separation and slash in parameters + + +http://%HOSTIP:%HTTPPORT?oh=what-weird=test/%TESTNUMBER -L + + + +# Verify data after the test has been "shot" + + +GET /?oh=what-weird=test/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /root/%TESTNUMBER0002.txt?coolsite=yes HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1906 b/local-test-curl-delta-01/afc-curl/tests/data/test1906 new file mode 100644 index 0000000000000000000000000000000000000000..6769d0cdb0eee596ee025fe842bf974ad883314e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1906 @@ -0,0 +1,49 @@ + + + +CURLOPT_CURLU +CURLOPT_PORT + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Funny-head: yesyes swsclose + + + + +# Client-side + + +http + + +CURLOPT_CURLU and CURLOPT_PORT + + +lib%TESTNUMBER + + +# The tool does two requests, the first sets CURLOPT_PORT to 1 +# the second resets the port again and expects that request to work. + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1909 b/local-test-curl-delta-01/afc-curl/tests/data/test1909 new file mode 100644 index 0000000000000000000000000000000000000000..2d868cc0bb60427495d9751384feea2abe748248 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1909 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP GET +retry + + + +# +# Server-side + + +HTTP/1.1 200 OK swsclose swsbounce +Content-Length: 5 +Connection: close + +bbb + + +HTTP/1.1 200 OK +Content-Length: 5 +Connection: close + +data + + + +# +# Client-side + + +http + + +HTTP GET --retry-all-errors to overcome partial transfer + + +--retry 1 --retry-all-errors -o %LOGDIR/outfile%TESTNUMBER http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +data + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1914 b/local-test-curl-delta-01/afc-curl/tests/data/test1914 new file mode 100644 index 0000000000000000000000000000000000000000..1aa3e48c01cfab7f56c9c9afbafb6379f6322e82 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1914 @@ -0,0 +1,42 @@ + + + +FTP +CURLOPT_NOBODY +CURLOPT_FILETIME + + + +# Server-side + + +REPLY MDTM 550 no such file + + + +# Client-side + + +ftp + + +# require debug so that alt-svc can work over plain old HTTP + +FTP with NOBODY and FILETIME set, getting a missing file + + +lib1913 + + + +ftp://%HOSTIP:%FTPPORT/not-there/1913 1 + + + +# Verify data after the test has been "shot" + + +78 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1915 b/local-test-curl-delta-01/afc-curl/tests/data/test1915 new file mode 100644 index 0000000000000000000000000000000000000000..34a2881efe490b9931334d17c178f6b7b06ba55f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1915 @@ -0,0 +1,58 @@ + + + +HTTP +HSTS +CURLOPT_HSTSREADFUNCTION + + + +# Server-side + + + +# Client-side + + +HSTS +http + + +none + + + +HSTS read/write callbacks + + +lib%TESTNUMBER + + + +http://%HOSTIP:%NOLISTENPORT/not-there/%TESTNUMBER + + + +# Verify data after the test has been "shot" + +# 7 CURLE_COULDNT_CONNECT (expected since there's nothing listening there) +# 42 CURLE_ABORTED_BY_CALLBACK + +42 + + +%if large-time +[0/4] 1.example.com 25250320 01:02:03 +[1/4] 2.example.com 25250320 03:02:01 +[2/4] 3.example.com 25250319 01:02:03 +%else +[0/4] 1.example.com 20370320 01:02:03 +[1/4] 2.example.com 20370320 03:02:01 +[2/4] 3.example.com 20370319 01:02:03 +%endif +[3/4] 4.example.com unlimited +First request returned 7 +Second request returned 42 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1935 b/local-test-curl-delta-01/afc-curl/tests/data/test1935 new file mode 100644 index 0000000000000000000000000000000000000000..b36e1fade8bd16f39327356235c6ef5f6cef25a6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1935 @@ -0,0 +1,69 @@ + + + +HTTP +CURLOPT_AWS_SIGV4 + + + +# Server-side + + +HTTP/1.1 302 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 +Location: /%TESTNUMBER0002 + + + +HTTP/1.1 200 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 + + + + +# Client-side + + +http + +# this relies on the debug feature which allow to set the time + +SSL +Debug +crypto + + + +HTTP AWS_SIGV4 with two providers and region + + +lib%TESTNUMBER + + + +http://127.0.0.1:9000/%TESTNUMBER/testapi/test 127.0.0.1:9000:%HOSTIP:%HTTPPORT + + + +# Verify data after the test has been "shot" + + +^User-Agent:.* +^Content-Type:.* +^Accept:.* + + +GET /%TESTNUMBER/testapi/test HTTP/1.1 +Host: 127.0.0.1:9000 +Authorization: XXX4-HMAC-SHA256 Credential=xxx/19700101/rrr/127/xxx4_request, SignedHeaders=content-type;host;x-yyy-date, Signature=a0b11b97b54689428d4188b788ed32865d607822d85d3e91cf06141f479dac0b +X-Yyy-Date: 19700101T000000Z + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1945 b/local-test-curl-delta-01/afc-curl/tests/data/test1945 new file mode 100644 index 0000000000000000000000000000000000000000..86fa147adcf0b4c641e1ebcaf9be5efa27174f15 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1945 @@ -0,0 +1,76 @@ + + + +curl_easy_header +CONNECT + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test with trailing space +Content-Type: text/html +Content-Length: 0 +Set-Cookie: onecookie=data; +Set-Cookie: secondcookie=2data; +Set-Cookie: cookie3=data3; +Location: /%TESTNUMBER0002 + + + +HTTP/1.1 200 Sure go ahead +Server: from the connect +Silly-thing: yes yes + + + + +# Client-side + + +proxy +SSL +headers-api + + +http +http-proxy + + + +curl_easy_nextheader with server + CONNECT + + +lib%TESTNUMBER + + + +http://hello:%HTTPPORT/%TESTNUMBER %HOSTIP:%PROXYPORT + + + +# Verify data after the test has been "shot" + + +CONNECT hello:%HTTPPORT HTTP/1.1 +Host: hello:%HTTPPORT +Proxy-Connection: Keep-Alive + + + + Server == from the connect (0/2) + Silly-thing == yes yes (0/1) + Date == Thu, 09 Nov 2010 14:49:00 GMT (0/1) + Server == test with trailing space (1/2) + Content-Type == text/html (0/1) + Content-Length == 0 (0/1) + Set-Cookie == onecookie=data; (0/3) + Set-Cookie == secondcookie=2data; (1/3) + Set-Cookie == cookie3=data3; (2/3) + Location == /19450002 (0/1) + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1948 b/local-test-curl-delta-01/afc-curl/tests/data/test1948 new file mode 100644 index 0000000000000000000000000000000000000000..4c50b02acd718bb730bad97cac7955e4993d2268 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1948 @@ -0,0 +1,72 @@ + + + +HTTP +HTTP POST +HTTP PUT + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Thu, 01 Nov 2001 14:49:00 GMT +Content-Type: text/html +Content-Length: 6 + +hello + + +HTTP/1.1 200 OK +Date: Thu, 01 Nov 2001 14:49:00 GMT +Content-Type: text/html +Content-Length: 6 + +hello +HTTP/1.1 200 OK +Date: Thu, 01 Nov 2001 14:49:00 GMT +Content-Type: text/html +Content-Length: 6 + +hello + + + +# Client-side + + +http + + + +CURLOPT_POST after CURLOPT_UPLOAD reusing handle + + +lib%TESTNUMBER + + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 22 + +This is test PUT data +POST /1948 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 22 +Content-Type: application/x-www-form-urlencoded + +This is test PUT data + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test197 b/local-test-curl-delta-01/afc-curl/tests/data/test197 new file mode 100644 index 0000000000000000000000000000000000000000..d940b0dc38e9ec6b8b28fca86c561501f8babb49 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test197 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP GET +retry + + +# +# Server-side + + +HTTP/1.1 503 BAD swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 21 + +server not available + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Connection: close + +ok + + + + +# +# Client-side + + +http + + +HTTP GET --retry on 503 error with output to stdout + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --retry 1000 + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +HTTP/1.1 503 BAD swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 21 + +server not available +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Connection: close + +ok + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1972 b/local-test-curl-delta-01/afc-curl/tests/data/test1972 new file mode 100644 index 0000000000000000000000000000000000000000..901aae29e8b202f603f5ccf85785f6b7c7ef2a64 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1972 @@ -0,0 +1,79 @@ + + + +HTTP +CURLOPT_AWS_SIGV4 + + + +# Server-side + + +HTTP/1.1 302 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 +Location: /%TESTNUMBER0002 + + + +HTTP/1.1 200 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 + + + + +# Client-side + + +http + +# this relies on the debug feature which allow to set the time + +SSL +Debug +crypto + + +CURL_FORCEHOST=1 + + + +HTTP AWS_SIGV4 for AWS S3: MIMEPOST + + +lib%TESTNUMBER + + + +http://exam.ple.com:9000/aws_sigv4/testapi/test exam.ple.com:9000:%HOSTIP:%HTTPPORT + + + +# Verify data after the test has been "shot" + + +^User-Agent:.* +^Content-Type:.* +^Accept:.* + + +POST /aws_sigv4/testapi/test HTTP/1.1 +Host: exam.ple.com:9000 +Authorization: AWS4-HMAC-SHA256 Credential=xxx/19700101/us-east-1/s3/aws4_request, SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date, Signature=eaee0f1c5984ad5d81c8bc7805f28c7b83b35322de654b2ace18cb8cf6d5a9cb +X-Amz-Date: 19700101T000000Z +x-amz-content-sha256: UNSIGNED-PAYLOAD +Content-Length: 154 + +--------------------------qrstuvwxyz0123456789AB +Content-Disposition: attachment; name="foo" + +bar +--------------------------qrstuvwxyz0123456789AB-- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test1973 b/local-test-curl-delta-01/afc-curl/tests/data/test1973 new file mode 100644 index 0000000000000000000000000000000000000000..af64b90e082b5d5c8a9e80aae4ec3ece569406b0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test1973 @@ -0,0 +1,75 @@ + + + +HTTP +CURLOPT_AWS_SIGV4 + + + +# Server-side + + +HTTP/1.1 302 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 +Location: /%TESTNUMBER0002 + + + +HTTP/1.1 200 OK +Date: Thu, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 + + + + +# Client-side + + +http + +# this relies on the debug feature which allow to set the time + +SSL +Debug +crypto + + +CURL_FORCEHOST=1 + + + +HTTP AWS_SIGV4 for AWS S3: POSTFIELDS + + +lib%TESTNUMBER + + + +http://exam.ple.com:9000/aws_sigv4/testapi/test exam.ple.com:9000:%HOSTIP:%HTTPPORT + + + +# Verify data after the test has been "shot" + + +^User-Agent:.* +^Content-Type:.* +^Accept:.* + + +POST /aws_sigv4/testapi/test HTTP/1.1 +Host: exam.ple.com:9000 +Authorization: AWS4-HMAC-SHA256 Credential=xxx/19700101/us-east-1/s3/aws4_request, SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date, Signature=7eb34202214384872221b99a9c671b7517891ac6af56b0aff24ec51adf62b10a +X-Amz-Date: 19700101T000000Z +x-amz-content-sha256: 4b02e333ccf7cf530ddee3e10ebe54e935500b5e570e68650d63d743e8bbc045 +Content-Length: 12 + +post fields + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test200 b/local-test-curl-delta-01/afc-curl/tests/data/test200 new file mode 100644 index 0000000000000000000000000000000000000000..1a81ac82565dddc38194eb863cbc57e8b6a999fc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test200 @@ -0,0 +1,41 @@ + + + +FILE + + + + + +foo + bar +bar + foo +moo + + + +# Client-side + + +file + + +basic file:// file + + +file://localhost%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt + + +foo + bar +bar + foo +moo + + + +# Verify data after the test has been "shot" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2000 b/local-test-curl-delta-01/afc-curl/tests/data/test2000 new file mode 100644 index 0000000000000000000000000000000000000000..ee2e50734946ebc910a584e1761524d845c99259 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2000 @@ -0,0 +1,76 @@ + + + +FTP +PASV +FILE +multiprotocol + + + +# +# Server-side + + +data + to + see +that FTP +works + so does it? + + + +# +# Client-side + + +ftp +file + + +FTP RETR followed by FILE + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER file://localhost%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt + + +foo + bar +bar + foo +moo + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + +data + to + see +that FTP +works + so does it? +foo + bar +bar + foo +moo + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test201 b/local-test-curl-delta-01/afc-curl/tests/data/test201 new file mode 100644 index 0000000000000000000000000000000000000000..a413ca3ff5d52a0ddb90dd6965e1818072f9f3f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test201 @@ -0,0 +1,34 @@ + + + +FILE +FAILURE + + + +# Server-side + + + + + +# Client-side + + +file + + +missing file:// file + + +file://localhost/%FILE_PWD/%LOGDIR/non-existent-file.txt + + + +# Verify data after the test has been "shot" + + +37 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2025 b/local-test-curl-delta-01/afc-curl/tests/data/test2025 new file mode 100644 index 0000000000000000000000000000000000000000..4794d3c0e9c443bd2ae414376338bf9aadb360cb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2025 @@ -0,0 +1,262 @@ + + + +HTTP +HTTP GET +HTTP Basic auth +HTTP NTLM auth +NTLM + + +# Server-side + + + + + + +HTTP/1.1 401 Sorry wrong password +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! + + + + +HTTP/1.1 401 Need Basic or NTLM auth +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 27 +WWW-Authenticate: Basic realm="testrealm" +WWW-Authenticate: NTLM + +This is not the real page! + + + +HTTP/1.1 401 NTLM intermediate +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +This is still not the real page! + + + +HTTP/1.1 200 Things are fine in server land +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + + +HTTP/1.1 401 Sorry wrong password (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! + + + + +HTTP/1.1 401 Need Basic or NTLM auth (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 27 +WWW-Authenticate: Basic realm="testrealm" +WWW-Authenticate: NTLM + +This is not the real page! + + + +HTTP/1.1 401 NTLM intermediate (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +This is still not the real page! + + + +HTTP/1.1 401 Sorry wrong password (3) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! + + + + +HTTP/1.1 401 Need Basic or NTLM auth (3) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 27 +WWW-Authenticate: Basic realm="testrealm" +WWW-Authenticate: NTLM + +This is not the real page! + + + +HTTP/1.1 401 NTLM intermediate (3) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +This is still not the real page! + + + +HTTP/1.1 200 Things are fine in server land (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + +HTTP/1.1 401 Sorry wrong password +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! +HTTP/1.1 401 NTLM intermediate +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +HTTP/1.1 200 Things are fine in server land +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! +HTTP/1.1 401 Sorry wrong password (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! +HTTP/1.1 401 NTLM intermediate (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +HTTP/1.1 401 Sorry wrong password (3) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! +HTTP/1.1 401 NTLM intermediate (3) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +HTTP/1.1 200 Things are fine in server land (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + + +# Client-side + + +NTLM +SSL +!SSPI + + +http + + +libauthretry + + + +HTTP authorization retry (Basic switching to NTLM) + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER basic ntlm + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER0100 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dGVzdHVzZXI6d3JvbmdwYXNz +Accept: */* + +GET /%TESTNUMBER0200 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +Accept: */* + +GET /%TESTNUMBER0200 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoABAI+/Fp9IERAQ74OsdNPbBpg7o8CVwLSO4DtFyIcZHUMKVktWIu92s2892OVpd2JzqnRlc3R1c2VyV09SS1NUQVRJT04= +Accept: */* + +GET /%TESTNUMBER0300 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dGVzdHVzZXI6d3JvbmdwYXNz +Accept: */* + +GET /%TESTNUMBER0400 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +Accept: */* + +GET /%TESTNUMBER0400 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoABANgKEcT5xUUBHw5+0m4FjWTGNzg6PeHJHbaPwNwCt/tXcnIeTQCTMAg12SPDyNXMf3Rlc3R1c2VyV09SS1NUQVRJT04= +Accept: */* + +GET /%TESTNUMBER0500 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +Accept: */* + +GET /%TESTNUMBER0500 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoABAI+/Fp9IERAQ74OsdNPbBpg7o8CVwLSO4DtFyIcZHUMKVktWIu92s2892OVpd2JzqnRlc3R1c2VyV09SS1NUQVRJT04= +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2032 b/local-test-curl-delta-01/afc-curl/tests/data/test2032 new file mode 100644 index 0000000000000000000000000000000000000000..d3d199c14c1c6122906aa01bc1c06ccbf1d847c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2032 @@ -0,0 +1,114 @@ + + + +HTTP +HTTP GET +HTTP Basic auth +HTTP NTLM auth +NTLM +flaky +timing-dependent + + +# Server-side + + + + +HTTP/1.1 401 Need Basic or NTLM auth +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 29 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is a bad password page! + + + + +HTTP/1.1 401 Need Basic or NTLM auth (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 27 +WWW-Authenticate: NTLM +WWW-Authenticate: Basic realm="testrealm" + +This is not the real page! + + + +HTTP/1.1 401 NTLM intermediate (2) +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 33 +WWW-Authenticate: NTLM TlRMTVNTUAACAAAACAAIADAAAACGgAEAq6U1NAWaJCIAAAAAAAAAAAAAAAA4AAAATlRMTUF1dGg= + +This is still not the real page! + + + +HTTP/1.1 200 Things are fine in server land +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 32 + +Finally, this is the real page! + + + +Data connection 0: 228 +Data connection 1: 228 +Data connection 2: 402 + + + + +# Client-side + + +NTLM +SSL +!SSPI + + +http + + +libntlmconnect + + + +NTLM connection mapping + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER0100 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3M= +Accept: */* + +GET /%TESTNUMBER0100 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3M= +Accept: */* + +GET /%TESTNUMBER0200 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +Accept: */* + +GET /%TESTNUMBER0200 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoABAI+/Fp9IERAQ74OsdNPbBpg7o8CVwLSO4DtFyIcZHUMKVktWIu92s2892OVpd2JzqnRlc3R1c2VyV09SS1NUQVRJT04= +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2047 b/local-test-curl-delta-01/afc-curl/tests/data/test2047 new file mode 100644 index 0000000000000000000000000000000000000000..1d7be6db364a848e3823feb0fc5ae838af1c5e71 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2047 @@ -0,0 +1,99 @@ + + + +HTTP +HTTP GET +HTTP proxy +IDN +followlocation +--write-out + + + +# +# Server-side + + +HTTP/1.1 302 OK swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 9 +Content-Type: text/plain +Location: ./%TESTNUMBER0001 + +redirect + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Content-Type: text/plain; charset=us-ascii + +OK + + + +# +# Client-side + + +http + + +IDN +proxy +codeset-utf8 + + +LC_ALL=en_US.UTF-8 +LC_CTYPE=en_US.UTF-8 + + +Connection reuse with IDN host name over HTTP proxy + + + +http://åäö.se/%TESTNUMBER -x %HOSTIP:%HTTPPORT -w "%{num_connects}\n%{num_redirects}\n%{size_download}\n%{url_effective}\n%{content_type}\n%{response_code}\n" -L + + + +# +# Verify data after the test has been "shot" + + +GET http://xn--4cab6c.se/%TESTNUMBER HTTP/1.1 +Host: xn--4cab6c.se +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://xn--4cab6c.se/%TESTNUMBER0001 HTTP/1.1 +Host: xn--4cab6c.se +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + +HTTP/1.1 302 OK swsbounce +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 9 +Content-Type: text/plain +Location: ./%TESTNUMBER0001 + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Content-Type: text/plain; charset=us-ascii + +OK +1 +1 +3 +http://åäö.se/%TESTNUMBER0001 +text/plain; charset=us-ascii +200 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2054 b/local-test-curl-delta-01/afc-curl/tests/data/test2054 new file mode 100644 index 0000000000000000000000000000000000000000..8217444e5364e7c0b45e0c0ee4da62ca41b38aa4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2054 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP GET +CURLOPT_CONNECT_TO + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 3 +Content-Type: text/plain + +OK + + + +# +# Client-side + + +http + + +Connect to specific host: use the first "connect-to" string that matches + + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --connect-to foo::bar: --connect-to :123::456 --next http://www.example.com:%HTTPPORT/%TESTNUMBER --connect-to www.example.com::%HOSTIP: --connect-to www.example.com::foo: --next http://%HOSTIP:8083/%TESTNUMBER --connect-to :8083::%HTTPPORT --connect-to :8083::123 --next http://www.example.com:8084/%TESTNUMBER --connect-to www.example.com:8084:%HOSTIP:%HTTPPORT --connect-to www.example.com:8084:foo:123 + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: www.example.com:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:8083 +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: www.example.com:8084 +User-Agent: curl/%VERSION +Accept: */* + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test206 b/local-test-curl-delta-01/afc-curl/tests/data/test206 new file mode 100644 index 0000000000000000000000000000000000000000..19fbbfb4a50b654a0fd026bf63fd8226137d99df --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test206 @@ -0,0 +1,108 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP proxy +proxytunnel +HTTP proxy Digest auth + + + +# Server-side + + +connection-monitor +auth_required + + + +# this is returned first since we get no proxy-auth + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: Digest realm="weirdorealm", nonce="12345" +Content-Length: 33 + +And you should ignore this data. + + +# this is returned when we get a GET! + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 7 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +daniel + + +# then this is returned when we get proxy-auth + +HTTP/1.1 200 OK swsbounce +Server: no + + + + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: Digest realm="weirdorealm", nonce="12345" +Content-Length: 33 + +HTTP/1.1 200 OK swsbounce +Server: no + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 7 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +daniel + + + +# Client-side + + +http + + +!SSPI +crypto +proxy + + +HTTP proxy CONNECT auth Digest + + +http://test.remote.haxx.se.%TESTNUMBER:8990/path/%TESTNUMBER0002 --proxy http://%HOSTIP:%HTTPPORT --proxy-user silly:person --proxy-digest --proxytunnel + + + +# Verify data after the test has been "shot" + + +CONNECT test.remote.haxx.se.%TESTNUMBER:8990 HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + +CONNECT test.remote.haxx.se.%TESTNUMBER:8990 HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +Proxy-Authorization: Digest username="silly", realm="weirdorealm", nonce="12345", uri="test.remote.haxx.se.%TESTNUMBER:8990", response="003e36decb4dbf6366b3ecb9b87c24ec" +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + +GET /path/%TESTNUMBER0002 HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +User-Agent: curl/%VERSION +Accept: */* + +[DISCONNECT] + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2065 b/local-test-curl-delta-01/afc-curl/tests/data/test2065 new file mode 100644 index 0000000000000000000000000000000000000000..4f3a510744ce96ce58ec50732e3853d52e09f888 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2065 @@ -0,0 +1,83 @@ + + + +HTTP +HTTP GET +HTTP Digest auth + + +# Server-side + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="2053604145", algorithm="SHA-512-256" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +This is not the real page + + +# This is supposed to be returned when the server gets a +# Authorization: Digest line passed-in from the client + +HTTP/1.1 401 Still a bad password you moron +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 34 + +This is not the real page either + + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="2053604145", algorithm="SHA-512-256" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +HTTP/1.1 401 Still a bad password you moron +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 34 + +This is not the real page either + + + + +# Client-side + + +http + + +!SSPI +crypto +sha512-256 + + +HTTP with RFC7616 Digest authorization with bad password, SHA-512-256 and userhash=false + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -u testuser:test2pass --digest + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="testuser", realm="testrealm", nonce="2053604145", uri="/%TESTNUMBER", response="0373a49d7d352ff54884faaf762fc6c89281b4112ad8fcbbe1d1ee52dcf7a802", algorithm=SHA-512-256 +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2069 b/local-test-curl-delta-01/afc-curl/tests/data/test2069 new file mode 100644 index 0000000000000000000000000000000000000000..74d719fd3e9dc3730f79e333e35c9ca403ea551a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2069 @@ -0,0 +1,88 @@ + + + +HTTP +HTTP POST +HTTP Digest auth + + + +# Server-side + + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144", algorithm="SHA-256", userhash=true +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + + + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144", algorithm="SHA-256", userhash=true +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + + +# Client-side + +# + +http + + +!SSPI +crypto + + +HTTP POST --digest with SHA-256, userhash=true and user-specified Content-Length header + +# This test is to ensure 'Content-Length: 0' is sent while negotiating auth +# even when there is a user-specified Content-Length header. +# https://github.com/curl/curl/pull/1242 + +-H "Content-Length: 11" -u auser:apasswd --digest -d "junkelijunk" http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 0 +Content-Type: application/x-www-form-urlencoded + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="fddc3bc7b753b73ab0848fd83cb20cbbca971258eb8d20c941dd5e0b010d66be", realm="testrealm", nonce="1053604144", uri="/%TESTNUMBER", response="9a29f1dab407e62daa7121185f9f12db6177415e03f35d9a881550095a83378d", algorithm=SHA-256, userhash=true +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 11 +Content-Type: application/x-www-form-urlencoded + +junkelijunk + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2071 b/local-test-curl-delta-01/afc-curl/tests/data/test2071 new file mode 100644 index 0000000000000000000000000000000000000000..544893af572ad79e23fff88ec9cae40b7f1283eb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2071 @@ -0,0 +1,41 @@ + + + +FILE + + + + + +foo + bar +bar + foo +moo + + + +# Client-side + + +file + + +basic file:// file with "127.0.0.1" hostname + + +file://127.0.0.1%FILE_PWD/%LOGDIR/test2070.txt + + +foo + bar +bar + foo +moo + + + +# Verify data after the test has been "shot" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2074 b/local-test-curl-delta-01/afc-curl/tests/data/test2074 new file mode 100644 index 0000000000000000000000000000000000000000..1ef3480b5c2524b966ca2a87b36925d6dca95c84 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2074 @@ -0,0 +1,55 @@ + + + +HTTP +HTTP GET +AUTH OAUTHBEARER + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +HTTP GET + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --oauth2-bearer mF_9.B5f-4.1JqM + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Bearer mF_9.B5f-4.1JqM +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2083 b/local-test-curl-delta-01/afc-curl/tests/data/test2083 new file mode 100644 index 0000000000000000000000000000000000000000..9256151a862c5581d46c348ae0a3900bb5f903ba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2083 @@ -0,0 +1,45 @@ + + + +FTP + + + +# Server-side + + + + + +# Client-side + + +ftp + + + +Pre-request callback for FTP + + +libprereq + + + +ftp://%HOSTIP:%FTPPORT/test-%TESTNUMBER/ + + + +# Verify data after the test has been "shot" + + +s/^Local port = \d+/Local port = stripped/ + + +Connected to %HOSTIP +Connected from %CLIENTIP +Remote port = %FTPPORT +Local port = stripped +Returning = 0 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2084 b/local-test-curl-delta-01/afc-curl/tests/data/test2084 new file mode 100644 index 0000000000000000000000000000000000000000..ced7086c4b331dda1e43808447fb6a016a050fa0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2084 @@ -0,0 +1,54 @@ + + + +HTTP + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 0 + + + + +# Client-side + + +http + + + +Pre-request callback for HTTP with callback terminating transfer + + +libprereq + + + +%HOSTIP:%HTTPPORT/%TESTNUMBER#err + + + +# Verify data after the test has been "shot" + + +42 + + +s/^Local port = \d+/Local port = stripped/ + + +Connected to %HOSTIP +Connected from %CLIENTIP +Remote port = %HTTPPORT +Local port = stripped +Returning = 1 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test209 b/local-test-curl-delta-01/afc-curl/tests/data/test209 new file mode 100644 index 0000000000000000000000000000000000000000..887d04fbeef74c5184314a0abf8e5e198a2a6a3d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test209 @@ -0,0 +1,115 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP proxy +HTTP proxy NTLM auth +NTLM + + + +# Server-side + + +# this is returned first since we get no proxy-auth + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +Content-Length: 33 + +And you should ignore this data. + + +# This is supposed to be returned when the server gets the second +# Authorization: NTLM line passed-in from the client + +HTTP/1.1 200 Things are fine in proxy land +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 + + + +# this is returned when we get a GET! + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 7 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +daniel + + +# then this is returned when we get proxy-auth + +HTTP/1.1 200 OK swsbounce +Server: no + +Nice proxy auth sir! + + + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +Content-Length: 33 + +HTTP/1.1 200 Things are fine in proxy land +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 7 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +daniel + + + +# Client-side + + +http + + +NTLM +SSL +!SSPI +proxy + + +HTTP proxy CONNECT auth NTLM + + +http://test.remote.example.com.%TESTNUMBER:%HTTPPORT/path/%TESTNUMBER0002 --proxy http://%HOSTIP:%HTTPPORT --proxy-user testuser:testpass --proxy-ntlm --proxytunnel + + + +# Verify data after the test has been "shot" + + +CONNECT test.remote.example.com.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: test.remote.example.com.%TESTNUMBER:%HTTPPORT +Proxy-Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + +CONNECT test.remote.example.com.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: test.remote.example.com.%TESTNUMBER:%HTTPPORT +Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + +GET /path/%TESTNUMBER0002 HTTP/1.1 +Host: test.remote.example.com.%TESTNUMBER:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test210 b/local-test-curl-delta-01/afc-curl/tests/data/test210 new file mode 100644 index 0000000000000000000000000000000000000000..c4ccb6b2c321d150152a228890eb42e2ad87a426 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test210 @@ -0,0 +1,55 @@ + + + +FTP + + + +# Server-side + + +data blobb + + +# data is sent to stdout + + +# Client-side + + +ftp + + +Get two FTP files from the same remote dir: no second CWD + + +ftp://%HOSTIP:%FTPPORT/a/path/%TESTNUMBER ftp://%HOSTIP:%FTPPORT/a/path/%TESTNUMBER + + +data blobb +data blobb + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD a +CWD path +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +EPSV +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test218 b/local-test-curl-delta-01/afc-curl/tests/data/test218 new file mode 100644 index 0000000000000000000000000000000000000000..cf9c41ad49d74029e9de9b0073bbbcd870447ae1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test218 @@ -0,0 +1,60 @@ + + + +HTTP +HTTP PUT +chunked Transfer-Encoding + + +# +# Server-side + + +HTTP/1.0 200 OK +Server: test-server/fake +Content-Type: text/html +Content-Length: 6 + +blaha + + + +# +# Client-side + + +http + + +HTTP PUT from a file but enforce chunked transfer-encoding + + + -T %LOGDIR/file%TESTNUMBER -H "Transfer-Encoding: chunked" http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + +just some tiny teeny contents + + + +# +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Transfer-Encoding: chunked + +%if hyper +1E +%else +1e +%endif +just some tiny teeny contents + +0 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test220 b/local-test-curl-delta-01/afc-curl/tests/data/test220 new file mode 100644 index 0000000000000000000000000000000000000000..8b28ec0a3d1e35b288d2ea077e906af60cc66668 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test220 @@ -0,0 +1,69 @@ + + + +HTTP +HTTP GET +compressed + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpDb250ZW50LUVuY29kaW5nOiBHWklQDQpDb250ZW50LUxlbmd0aDogNDQNCg0K +H4sICHmeq0EAA2xhbGFsYQDLycxLVTDkUsgB0UZcChCGMRcACgJxYBgAAAA= + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Content-Encoding: GZIP +Content-Length: 44 + +line 1 + line 2 + line 3 + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET gzip compressed content + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --compressed + + + +# +# Verify data after the test has been "shot" + + +s/^Accept-Encoding: [a-zA-Z, ]*/Accept-Encoding: xxx/ + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Accept-Encoding: xxx + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2201 b/local-test-curl-delta-01/afc-curl/tests/data/test2201 new file mode 100644 index 0000000000000000000000000000000000000000..7c804e8013fe9cfbd1daa69b006e88cdd3a520c3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2201 @@ -0,0 +1,50 @@ + + + +MQTT +MQTT PUBLISH + + + +# +# Server-side + + + + + +# +# Client-side + + +mqtt + + +mqtt + + +MQTT PUBLISH with user and password valid + + +mqtt://%HOSTIP:%MQTTPORT/%TESTNUMBER -d something -u testuser:testpasswd + + + +# +# Verify data after the test has been "shot" + +# These are hexadecimal protocol dumps from the client +# +# Strip out the random part of the client id from the CONNECT message +# before comparison + +s/^(.* 00044d51545404c2003c000c6375726c).*/$1/ + + +client CONNECT 2e 00044d51545404c2003c000c6375726c +server CONNACK 2 20020000 +client PUBLISH f 000432323031736f6d657468696e67 +client DISCONNECT 0 e000 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test222 b/local-test-curl-delta-01/afc-curl/tests/data/test222 new file mode 100644 index 0000000000000000000000000000000000000000..d5744ea80f10f1aad1f2918dd6cd7b2b2e4b4f79 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test222 @@ -0,0 +1,200 @@ + + + +HTTP +HTTP GET +compressed + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpDb250ZW50LUVuY29kaW5nOiBkZWZsYXRlDQpDb250ZW50LUxlbmd0aDogMTMw +NQ0KDQp4nNxY227jNhB9N5B/YP3UArZuthM5cLQoctkEzTbB2gW6TwYt0TYbSRRIyrk89Ns7lCiJ +sRyvd4O+BEhicuacw+EMSZOZfHpKYrQhXFCWnnVdy+kikoYsounqrHszvev7/mjcd7ufgs7kl4u7 +89m3+0uUcfYPCWU/pkICEE2/TWeXX1B3LWV2attLTsQ6IVhaKZH2AocPJI3sZdLXPNF3rKEVyagL +oltaQQehyqbaTW9Oo8A9dr2JbRhKRIQlmeMoIoAYj/2+4/c9FznDU8c99cYT2/AbhDxTH1HgOc6w +7zp910eOd+rBz0BTKsSrOFKckLlYMy6DMOdxHY5hb+OXeRwXcITTCMV00aYWEB0eEaGWOmdJUlJS +giRjtQDH/BktGUdhTEkq+4JGBP319RZJjlOxhIpaMItGyFDeGQyiAuFyBKVaqXBV3yWNiTjq5EJ1 +1BjiOZX4yUI3Eok8y0BfoOvZ7L5X/J320BW0jzpXRfvi5nzWQ7PL2z8v4fP24neAXd3cXvaK4T/f +3V9ffoU2DPBIYoiplOpnTMiebubQChl7oEQU2ijPYoYjGAKWWp6QqJl1D2VYiEfGI9WEyNI8WRT2 +6fT2qBMSLumShlBXMP1BOPiYKEOBajzBCMW0IBsZeyScREedxXOVpB6Sa/JmxquyWEed2RqoCMPv +gqZqMwlIbZ1qlWAGmw55zlEnxukqxysiihhIuqGcpQkMIEBHl9BYGxsqcUzl81yEjJNgdOIPrdHJ +xN6yb4EzwkOQDAaWe2xgK/MWGubzAHttbCALk17XLMtjzJuxjkdjiGEIy3nb0yJUA7oDy3dfEV6H +YjjKYJzRK7QRDsfFueFbI2di647pmYcsB13Prbza8ApTDuIPaowxgMgXIuQ0k3BEimCgTofXphIG +pU/D9Vzt5eCCLHEey4ltGksY1H9eHWAZlD3YeWhWJ6Wt1os9sVusRmzNEvK2ECxgyksVdXjaJkPr +1gKNply9HC4HYK2kaI3I4sU7XATAWkTRGpEXmh0uAmAtomiNSLiGPUZitjpcqqZowUaikeVZcrgg +gLWUojUiEVkcLgJgLaJojQgTT4eLAFiLKJpRLxGp8/IHalYSqrppurHMcw5pEyTQ67fqGoXZiB8o +yUZUxdgIQ0TdHA5XUWgtUxAbnYRyzvjhSiVea2myWdeEBVWtoFl6YgqHHKTgy83M/hudw+kBKaN5 +gm5Lx8SuEBqvvqfknJOY1Jlrmef6/hacWK5nwQXpDfcbbHWvOjl2/FGLWF2w2hx1L9p9cdoFLOdi +75rMBM5RAhNeMzmXa/iqhpy1TCUS5xJuMqIOqexX3dqgT2CcUhKjqSQpfMOvJrbpbFGgSrvr/u8C +ryKiimwgW3TOYhLcPaaE17jCVEVqm6FWvWoJqy94ThOaYmnOTnK4IRS1gYLWnZbX8473uQd7ufuc +ru/v5bp7x4WlsT/qvW73eLjPPd5L9sd7vc5etzv6TtzfCWx/ZIPW2OX9brv8sCYyeDLBQwyuo7VO +bXxG8jkjZ11OQngdKJt6SdWLssGZG9lRQ+1y7CTqewu4T4aqGDtdO5nG46xF3X64vcWVVKoNBXa4 +s6Nf9W3qt51aJbbeaQ3i7byx4t6G4/8vac5PZ2w4eGfG1Pvq4yfK9QYj9x2ZeoGn2MfP0sBzhifv +yNI1oUmE44+fqOFwNPDekaiwD0998TN5Miz6rK//KxR0/gMAAP//gjMRo2MAAAAA//8DAN04jtE= + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Content-Encoding: deflate +Content-Length: 1305 + + + + + + 1612 + 1998-08-21 04:01:29 + 2004-10-18 02:22:23 + curl + curl and libcurl + Command line tool and library for client-side URL transfers. + curl and libcurl is a tool for transferring files +using URL syntax. It supports HTTP, HTTPS, FTP, +FTPS, DICT, TELNET, LDAP, FILE, and GOPHER, as +well as HTTP-post, HTTP-put, cookies, FTP upload, +resumed transfers, passwords, portnumbers, SSL +certificates, Kerberos, and proxies. It is powered +by libcurl, the client-side URL transfer library. +There are bindings to libcurl for over 20 +languages and environments. + + 5784.57 + 3.16 + 169 + 6594.54 + 13.81 + 105 + 8.50 + 21 + 183 + 323 + Default + http://freshmeat.net/projects/curl/ + http://freshmeat.net/redir/curl/1612/url_homepage/ + http://freshmeat.net/redir/curl/1612/url_tgz/ + http://freshmeat.net/redir/curl/1612/url_bz2/ + http://freshmeat.net/redir/curl/1612/url_zip/ + http://freshmeat.net/redir/curl/1612/url_changelog/ + http://freshmeat.net/redir/curl/1612/url_rpm/ + http://freshmeat.net/redir/curl/1612/url_deb/ + http://freshmeat.net/redir/curl/1612/url_osx/ + http://freshmeat.net/redir/curl/1612/url_bsdport/ + + http://freshmeat.net/redir/curl/1612/url_cvs/ + http://freshmeat.net/redir/curl/1612/url_list/ + http://freshmeat.net/redir/curl/1612/url_mirror/ + + MIT/X Consortium License + + 7.12.2 + 176085 + 2004-10-18 02:22:23 + + + + + Daniel Stenberg + http://freshmeat.net/~bagder/ + Owner + + + + 12 + 226 + 3 + 2 + 188 + 216 + 200 + 220 + 164 + 90 + 89 + 809 + 150 + 224 + 900 + 839 + + + + 0 + 7464 + 7464 + OpenSSL (Default) + + + 0 + 0 + 7443 + OpenLDAP + + + 0 + 0 + 12351 + zlib + + + 0 + 0 + 32047 + Heimdal + + + 0 + 0 + 44532 + c-ares + + + + + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET deflate compressed content + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --compressed + + + +# +# Verify data after the test has been "shot" + + +s/^Accept-Encoding: [a-zA-Z, ]*/Accept-Encoding: xxx/ + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Accept-Encoding: xxx + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test224 b/local-test-curl-delta-01/afc-curl/tests/data/test224 new file mode 100644 index 0000000000000000000000000000000000000000..0b654c2e8c2a83d73e231b349764bb2c87850815 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test224 @@ -0,0 +1,105 @@ + + + +HTTP +HTTP GET +compressed + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpDb250ZW50LUVuY29kaW5nOiBnemlwDQpDb250ZW50LUxlbmd0aDogMjE4Ng0K +DQofiwgcv7yrQQIDMAB0aGlzIGlzIGFuIGV4dHJhIGZpZWxkIHRoYXQgbXVzdCBiZSByZW1vdmVk +X19fX19sb25nLWZpbGVuYW1lLXh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4 +eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4AHRoaXMgaXMgYSBj +b21tZW50IHRoYXQgbXVzdCBiZSBza2lwcGVkACvNS87PLShKLS5OTVFIr8osUEhJLElUKM8syVDI +yc9Lh4hlpCampBZxAQC4UJ7LLQAAAA== + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Content-Encoding: gzip +Content-Length: 2186 + +uncompressed gzip data with long gzip header + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET gzip compressed content with huge comment and extra field + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --compressed + + + +# +# Verify data after the test has been "shot" + + +s/^Accept-Encoding: [a-zA-Z, ]*/Accept-Encoding: xxx/ + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Accept-Encoding: xxx + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test226 b/local-test-curl-delta-01/afc-curl/tests/data/test226 new file mode 100644 index 0000000000000000000000000000000000000000..df0c4ac6f48c49779f7ff8d01dab94b8927de3a3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test226 @@ -0,0 +1,29 @@ + + + +FTP +FAILURE + + + +# Client-side + + +ftp + + +FTP %0d-code in URL's CWD part + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER%0d + + + +# Verify data after the test has been "shot" + +# 3 == CURLE_URL_MALFORMAT + +3 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test23 b/local-test-curl-delta-01/afc-curl/tests/data/test23 new file mode 100644 index 0000000000000000000000000000000000000000..1f15b218e1a7ee868d0998cefa05cbc8e6900d27 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test23 @@ -0,0 +1,33 @@ + + + +unsupported protocol +FAILURE + + +# Server-side + + + + + +# Client-side + + +http + + +unsupported protocol:// URL + + +htfp://%HOSTIP:%HTTPPORT/none.htfml + + + +# Verify data after the test has been "shot" + + +1 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test237 b/local-test-curl-delta-01/afc-curl/tests/data/test237 new file mode 100644 index 0000000000000000000000000000000000000000..9e68651189f219eafc9af312189af992b8efdce2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test237 @@ -0,0 +1,44 @@ + + + +FTP + + + +# Server-side + + +REPLY PASV 227 Entering Passiv Mode (1216,256,2,127,127,127) + + + +# Client-side + + +ftp + + +FTP getting bad host in 227-response to PASV + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER --disable-epsv + + + +# Verify data after the test has been "shot" +# The bogus address used here is chosen specifically so that when processed on +# certain hosts with buggy resolver code, the resulting address (192.0.2.127) +# is from an address block that is guaranteed never to be assigned (RFC3330). + +# 14 = CURLE_FTP_WEIRD_227_FORMAT + +14 + + +USER anonymous +PASS ftp@example.com +PWD +PASV + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2401 b/local-test-curl-delta-01/afc-curl/tests/data/test2401 new file mode 100644 index 0000000000000000000000000000000000000000..9929c1394b44400be569902e27b60267ea9dc456 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2401 @@ -0,0 +1,71 @@ + + + +HTTP +HTTP POST +HTTP/2 +HTTPS + + + +# +# Server-side + + +HTTP/1.1 201 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close +Content-Length: 0 +Funny-head: yesyes + + + + +# +# Client-side + + +Debug +http/2 +SSL + + +http/2 + + +HTTP/2 POST over HTTPS + + + + +-k --http2 "https://%HOSTIP:%HTTP2TLSPORT/%TESTNUMBER" -d "moo" + + + + +# +# Verify data after the test has been "shot" + + +HTTP/2 201 +date: Tue, 09 Nov 2010 14:49:00 GMT +content-length: 0 +funny-head: yesyes +server: nghttpx +via: 1.1 nghttpx + + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTP2TLSPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 3 +Content-Type: application/x-www-form-urlencoded +X-Forwarded-Proto: https +Via: 2 nghttpx + +moo + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2406 b/local-test-curl-delta-01/afc-curl/tests/data/test2406 new file mode 100644 index 0000000000000000000000000000000000000000..6bf4fa8cd961c368430aac5be475e39153b41091 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2406 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP GET +HTTP/2 +HTTPS + + + +# +# Server-side + + +HTTP/1.1 404 nope +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +Debug +http/2 +SSL + + +http/2 + + +HTTP/2 over HTTPS with -f + + + + +-k --http2 -f "https://%HOSTIP:%HTTP2TLSPORT/%TESTNUMBER" + + + + +# +# Verify data after the test has been "shot" + + +HTTP/2 404 +date: Tue, 09 Nov 2010 14:49:00 GMT +content-length: 6 +content-type: text/html +funny-head: yesyes +server: nghttpx +via: 1.1 nghttpx + + + +22 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test243 b/local-test-curl-delta-01/afc-curl/tests/data/test243 new file mode 100644 index 0000000000000000000000000000000000000000..3952571b6ed1da73a07febec45d5d8f47b9a44e9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test243 @@ -0,0 +1,121 @@ + + + +HTTP +HTTP GET +HTTP proxy +HTTP proxy NTLM auth +--proxy-anyauth +NTLM + + + +# Server-side + + + +HTTP/1.1 407 Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Proxy-Authenticate: Blackmagic realm="gimme all yer s3cr3ts" +Proxy-Authenticate: Basic realm="gimme all yer s3cr3ts" +Proxy-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +This is not the real page + + +# this is returned first since we get no proxy-auth + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +Content-Length: 34 + +Hey you, authenticate or go away! + + +# This is supposed to be returned when the server gets the second +# Authorization: NTLM line passed-in from the client + +HTTP/1.1 200 Things are fine in proxy land swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 42 + +Contents of that page you requested, sir. + + + +HTTP/1.1 407 Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Proxy-Authenticate: Blackmagic realm="gimme all yer s3cr3ts" +Proxy-Authenticate: Basic realm="gimme all yer s3cr3ts" +Proxy-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +HTTP/1.1 407 Authorization Required to proxy me my dear +Proxy-Authenticate: NTLM TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +Content-Length: 34 + +HTTP/1.1 200 Things are fine in proxy land swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 42 + +Contents of that page you requested, sir. + + + +# Client-side + + +http + + +NTLM +SSL +!SSPI +proxy + + +HTTP POST with --proxy-anyauth, picking NTLM + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --proxy http://%HOSTIP:%HTTPPORT --proxy-user testuser:testpass --proxy-anyauth -d "postit" + + + +# Verify data after the test has been "shot" + + +POST http://%HOSTIP:%HTTPPORT/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive +Content-Length: 6 +Content-Type: application/x-www-form-urlencoded + +postitPOST http://%HOSTIP:%HTTPPORT/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Proxy-Authorization: NTLM TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive +Content-Length: 0 +Content-Type: application/x-www-form-urlencoded + +POST http://%HOSTIP:%HTTPPORT/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Proxy-Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive +Content-Length: 6 +Content-Type: application/x-www-form-urlencoded + +postit + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test246 b/local-test-curl-delta-01/afc-curl/tests/data/test246 new file mode 100644 index 0000000000000000000000000000000000000000..a756028b9c88704c4d771234ec087cb2b691ebfa --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test246 @@ -0,0 +1,95 @@ + + + +HTTP +HTTP POST +HTTP Digest auth + + + +# Server-side + + +HTTP/1.1 100 Continue +Server: Microsoft-IIS/5.0 +Date: Sun, 03 Apr 2005 14:57:45 GMT +X-Powered-By: ASP.NET + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + + + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + +HTTP/1.1 100 Continue +Server: Microsoft-IIS/5.0 +Date: Sun, 03 Apr 2005 14:57:45 GMT +X-Powered-By: ASP.NET + +HTTP/1.1 401 authentication please swsbounce +Server: Microsoft-IIS/6.0 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604144" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 0 + +HTTP/1.1 200 A OK +Server: Microsoft-IIS/6.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 3 + +ok + + + + +# Client-side + +# + +http + + +!SSPI +crypto + + +HTTP POST --digest with server doing a 100 before 401 response + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -u auser:apasswd --digest -d "junkelijunk" + + + +# Verify data after the test has been "shot" + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 0 +Content-Type: application/x-www-form-urlencoded + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="auser", realm="testrealm", nonce="1053604144", uri="/%TESTNUMBER", response="761e6fc9a760c39d587092e8d840e740" +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 11 +Content-Type: application/x-www-form-urlencoded + +junkelijunk + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test25 b/local-test-curl-delta-01/afc-curl/tests/data/test25 new file mode 100644 index 0000000000000000000000000000000000000000..b00ef84ece696620e58cb0d39a2b67eec71c8dc0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test25 @@ -0,0 +1,113 @@ + + + +HTTP +HTTP GET +followlocation +--max-redirs + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +Redirect to the same URL again! + + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + +HTTP/1.1 301 This is a weirdo text message +Server: test-server/fake +Location: data/reply/%TESTNUMBER +Content-Length: 32 +Connection: close + + + + +# Client-side + + +http + + +looping HTTP Location: following with --max-redirs + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER -L --max-redirs 5 + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/data/reply/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/data/reply/data/reply/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/data/reply/data/reply/data/reply/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/data/reply/data/reply/data/reply/data/reply/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /want/data/reply/data/reply/data/reply/data/reply/data/reply/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +47 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test251 b/local-test-curl-delta-01/afc-curl/tests/data/test251 new file mode 100644 index 0000000000000000000000000000000000000000..6de2003c8f9ef78164a534ac2fef6c6a5baad9d6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test251 @@ -0,0 +1,62 @@ + + + +FTP +SLOWDOWN + + + +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + +SLOWDOWN + + + +# Client-side + + +ftp + + +FTP dir list, PORT with specified IP and slow response + + +ftp://%HOSTIP:%FTPPORT/ -P %CLIENTIP + + + +# Verify data after the test has been "shot" + + +QUIT + +# Strip all valid kinds of PORT and EPRT that curl can send + +^PORT \d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3} +^EPRT \|1\|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\|\d{1,5}\| + + +USER anonymous +PASS ftp@example.com +PWD +PORT 127,0,0,1,243,212 +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test252 b/local-test-curl-delta-01/afc-curl/tests/data/test252 new file mode 100644 index 0000000000000000000000000000000000000000..35c3014a0bc9c12cd2c21eafce28b44a467adf7f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test252 @@ -0,0 +1,61 @@ + + + +FTP +FTP-ipv6 +IPv6 +EPSV + + +# +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + + +# +# Client-side + + +IPv6 + + +ftp-ipv6 + + +FTP IPv6 dir list PASV + + +-g "ftp://%HOST6IP:%FTP6PORT/" + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test254 b/local-test-curl-delta-01/afc-curl/tests/data/test254 new file mode 100644 index 0000000000000000000000000000000000000000..ede445355a65d82f2269bc9a50d3982678b484b8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test254 @@ -0,0 +1,62 @@ + + + +FTP +FTP-ipv6 +IPv6 +EPSV +--disable-epsv + + +# +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + + +# +# Client-side + + +IPv6 + + +ftp-ipv6 + + +FTP IPv6 dir list PASV and --disable-epsv + + +-g "ftp://%HOST6IP:%FTP6PORT/" --disable-epsv + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test2604 b/local-test-curl-delta-01/afc-curl/tests/data/test2604 new file mode 100644 index 0000000000000000000000000000000000000000..4e825aa273f2334472bde37bd91d23fa93141366 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test2604 @@ -0,0 +1,22 @@ + + + +unittest + + + +# +# Client-side + + +none + + +unittest +sftp + + +Curl_get_pathname unit test + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test268 b/local-test-curl-delta-01/afc-curl/tests/data/test268 new file mode 100644 index 0000000000000000000000000000000000000000..0d205fe734628f679b464fa2ed97cdb53a06577c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test268 @@ -0,0 +1,59 @@ + + + +HTTP +variables + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +JSON encoding of Unicode string + + +%hex[%e2%80%9c]hex% + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --variable hello@%LOGDIR/junk --expand-data {{hello:json}} + + + +# +# Verify data after the test has been "shot" + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 3 +Content-Type: application/x-www-form-urlencoded + +%hex[%e2%80%9c]hex% + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test272 b/local-test-curl-delta-01/afc-curl/tests/data/test272 new file mode 100644 index 0000000000000000000000000000000000000000..5607a1081693ef1bf7277674cfb35f23e9561d32 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test272 @@ -0,0 +1,43 @@ + + + +FTP +PASV +RETR + + +# Server-side + + +213 20040101121212 + + + +# Client-side + + +ftp + + +FTP timed conditioned get file with identical time stamp + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER -z "2004 jan 1 12:12:12 UTC" + + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +MDTM %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test275 b/local-test-curl-delta-01/afc-curl/tests/data/test275 new file mode 100644 index 0000000000000000000000000000000000000000..d0abcac18485fddad3f7168d120d37176c938cf7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test275 @@ -0,0 +1,90 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP Basic auth +HTTP proxy +HTTP proxy Basic auth +proxytunnel + + + +# +# Server-side + + +HTTP/1.1 200 OK +Connected-fine: sure + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 9 + +contents + + +HTTP/1.1 200 OK +Connected-fine: sure + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Type: text/html +Content-Length: 9 + +contents + + + +# +# Client-side + + +http +http-proxy + + +HTTP CONNECT with proxytunnel getting two URLs from the same host + + +http://remotesite.com.%TESTNUMBER:%HTTPPORT/we/want/that/page/%TESTNUMBER -p -x %HOSTIP:%PROXYPORT --user iam:myself --proxy-user youare:yourself http://remotesite.com.%TESTNUMBER:%HTTPPORT/we/want/that/page/%TESTNUMBER + + +proxy + + + +# +# Verify data after the test has been "shot" + + +CONNECT remotesite.com.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: remotesite.com.%TESTNUMBER:%HTTPPORT +Proxy-Authorization: Basic eW91YXJlOnlvdXJzZWxm +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + +GET /we/want/that/page/%TESTNUMBER HTTP/1.1 +Host: remotesite.com.%TESTNUMBER:%HTTPPORT +Authorization: Basic aWFtOm15c2VsZg== +User-Agent: curl/%VERSION +Accept: */* + +GET /we/want/that/page/%TESTNUMBER HTTP/1.1 +Host: remotesite.com.%TESTNUMBER:%HTTPPORT +Authorization: Basic aWFtOm15c2VsZg== +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test281 b/local-test-curl-delta-01/afc-curl/tests/data/test281 new file mode 100644 index 0000000000000000000000000000000000000000..23af513a02a78d1dfeb962e4424d7155d1cdedc1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test281 @@ -0,0 +1,59 @@ + + + +HTTP +HTTP PUT + + +# Server-side + + +HTTP/1.1 100 Continue + +HTTP/1.1 401 Bad Auth swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +WWW-Authenticate: Basic Realm=authenticate +Server: test-server/fake + + + + + +# Client-side + + +http + + +HTTP PUT from file with 100 + 401 responses and -f without auth given + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER -f -T %LOGDIR/test%TESTNUMBER.txt + + +Weird + file + to + upload + + + +# Verify data after the test has been "shot" + + +22 + + +PUT /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 38 + +Weird + file + to + upload + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test285 b/local-test-curl-delta-01/afc-curl/tests/data/test285 new file mode 100644 index 0000000000000000000000000000000000000000..03dc96f6a080806c1f99db0a7144ea10de47bcdd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test285 @@ -0,0 +1,47 @@ + + + +TFTP +TFTP WRQ + + + +# +# Client-side + + +tftp + + +TFTP send + + +-T %LOGDIR/test%TESTNUMBER.txt tftp://%HOSTIP:%TFTPPORT// --connect-timeout 549 + + +a chunk of +data +sent + to server + + + +# +# Verify pseudo protocol after the test has been "shot" + + +a chunk of +data +sent + to server + + +opcode = 2 +mode = octet +tsize = 32 +blksize = 512 +timeout = 10 +filename = /test%TESTNUMBER.txt + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test287 b/local-test-curl-delta-01/afc-curl/tests/data/test287 new file mode 100644 index 0000000000000000000000000000000000000000..85d557ec96d9e64f4957317b67f37e54b2e2c75f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test287 @@ -0,0 +1,56 @@ + + + +HTTP +HTTP CONNECT +HTTP proxy +proxytunnel + + + +# Server-side + + + +HTTP/1.1 405 Method Not Allowed swsclose + +And you should ignore this data. + + + + +# Client-side + + +http + + +HTTP proxy CONNECT with custom User-Agent header + + +http://test.remote.example.com.%TESTNUMBER:%HTTPPORT/path/%TESTNUMBER -H "User-Agent: looser/2015" --proxy http://%HOSTIP:%HTTPPORT --proxytunnel --proxy-header "User-Agent: looser/2007" + + +proxy + + + +# Verify data after the test has been "shot" + + +CONNECT test.remote.example.com.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: test.remote.example.com.%TESTNUMBER:%HTTPPORT +Proxy-Connection: Keep-Alive +User-Agent: looser/2007 + + +# CURLE_RECV_ERROR + +56 + + +HTTP/1.1 405 Method Not Allowed swsclose + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test298 b/local-test-curl-delta-01/afc-curl/tests/data/test298 new file mode 100644 index 0000000000000000000000000000000000000000..3880a60732df793fcdd41a0bfc74ee4c8e75c097 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test298 @@ -0,0 +1,48 @@ + + + +FTP +PASV +CWD +--ftp-method +nocwd + + +# +# Server-side + + +bla bla bla + + + +# Client-side + + +ftp + + +FTP CWD with --ftp-method nocwd + + +--ftp-method nocwd ftp://%HOSTIP:%FTPPORT/first/second/th%69rd/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE I +SIZE first/second/third/%TESTNUMBER +RETR first/second/third/%TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test299 b/local-test-curl-delta-01/afc-curl/tests/data/test299 new file mode 100644 index 0000000000000000000000000000000000000000..fc80c6296f2d862432ba1b4071a501f167e1ae5e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test299 @@ -0,0 +1,52 @@ + + + +FTP +HTTP +CURLOPT_USERPWD +HTTP proxy + + + +# Server-side + + +HTTP/1.0 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake + +blablabla + + + + +# Client-side + + +http + + +ftp +proxy + + +FTP over HTTP proxy with user:pass not in url + + +-x http://%HOSTIP:%HTTPPORT -u michal:aybabtu ftp://host.com/we/want/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET ftp://michal:aybabtu@host.com/we/want/%TESTNUMBER HTTP/1.1 +Host: host.com:21 +Authorization: Basic bWljaGFsOmF5YmFidHU= +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3000 b/local-test-curl-delta-01/afc-curl/tests/data/test3000 new file mode 100644 index 0000000000000000000000000000000000000000..43c2695c98d1ad12c1564b27f37f36b1b8785635 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3000 @@ -0,0 +1,53 @@ + + + +HTTPS +HTTP GET +PEM certificate + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 7 + +MooMoo + + + +# +# Client-side + + +SSL +!Schannel +local-http + + +https Server-localhost-firstSAN-sv.pem + + +HTTPS GET to localhost, first subject alt name matches, CN does not match + + +-4 --cacert %SRCDIR/certs/EdelCurlRoot-ca.crt https://localhost:%HTTPSPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: localhost:%HTTPSPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3009 b/local-test-curl-delta-01/afc-curl/tests/data/test3009 new file mode 100644 index 0000000000000000000000000000000000000000..213e8ae682bc7bc2c9a2e18c37b14ff3316d7ec1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3009 @@ -0,0 +1,57 @@ + + + +-O + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +http + + +--output-dir a non-existing directory + + +http://%HOSTIP:%HTTPPORT/this/is/the/%TESTNUMBER -O --output-dir %PWD/not-there + + + +# +# Verify data after the test has been "shot" + + +GET /this/is/the/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +23 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3015 b/local-test-curl-delta-01/afc-curl/tests/data/test3015 new file mode 100644 index 0000000000000000000000000000000000000000..41e0640bc239fd10f7c7fba53c650b1cfd21fe25 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3015 @@ -0,0 +1,78 @@ + + + +HTTP +HTTP GET +followlocation +chunked Transfer-Encoding +--write-out + + + +# +# Server-side + + +HTTP/1.1 302 OK +Date: Sun, 13 Sep 2020 15:00 GMT +Content-Length: 8 +Connection: close +Content-Type: text/plain +Location: ./%TESTNUMBER0001 + +monster + + +HTTP/1.1 200 OK +Date: Sun, 13 Sep 2020 15:00 GMT +Transfer-Encoding: chunked +Connection: close +Content-Type: text/plain; charset=us-ascii + +0007 +bigger +0008 +monster + +0 + + + + + +# +# Client-side + + +http + + +HTTP GET -w num_headers with redirected fetch (2 connects) + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -w "%{num_headers}\n" -L -o%DEV_NULL + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER0001 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + +4 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3020 b/local-test-curl-delta-01/afc-curl/tests/data/test3020 new file mode 100644 index 0000000000000000000000000000000000000000..25bf6dd929470e90aa7f3b8d9bd3f3306a2521b9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3020 @@ -0,0 +1,36 @@ + + + +HTTP +HTTP GET +--connect-to + + + +# +# Server-side + + + +# +# Client-side + + +http + + +HTTP with invalid --connect-to syntax + + +--connect-to ::example.com:example.com http://example.com:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +49 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3025 b/local-test-curl-delta-01/afc-curl/tests/data/test3025 new file mode 100644 index 0000000000000000000000000000000000000000..eaff47ce745ffccc3c2fad95637caee4aa5c7532 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3025 @@ -0,0 +1,47 @@ + + + +HTTP +HTTP GET + + + +# +# Server-side + + +ICY 200 OK +Content-Length: 7 + +MooMoo + + + +# +# Client-side + + +http + + +!hyper + + +CURLOPT_HTTP200ALIASES + + +lib%TESTNUMBER + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +0 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3028 b/local-test-curl-delta-01/afc-curl/tests/data/test3028 new file mode 100644 index 0000000000000000000000000000000000000000..bc69e862af08580b35296a23269fed0463efbc0b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3028 @@ -0,0 +1,73 @@ + + + +HTTP +HTTP CONNECT + + +# +# Server-side + + +HTTP/1.1 200 Mighty fine indeed + + + + +HTTP/1.1 404 Not Found +Server: nginx/1.23.2 +Date: Wed, 09 Nov 2022 09:44:58 GMT +Content-Type: text/plain; charset=utf-8 +Content-Length: 4 +Connection: keep-alive +X-Content-Type-Options: nosniff + +haha + + + + +# +# Client-side + + +http +http-proxy + + +HTTP GET when PROXY Protocol enabled behind a proxy + + +--haproxy-protocol http://%HOSTIP:%HTTPPORT/page --proxytunnel -x %HOSTIP:%PROXYPORT + + +proxy + + + +# +# Verify data after the test has been "shot" + + +s/^PROXY TCP4 %CLIENTIP %HOSTIP (\d*) %PROXYPORT/proxy-line/ + + + +CONNECT %HOSTIP:%HTTPPORT HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + + +proxy-line +GET /page HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3102 b/local-test-curl-delta-01/afc-curl/tests/data/test3102 new file mode 100644 index 0000000000000000000000000000000000000000..7635e65432760d30b111055c0eab03818e411452 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3102 @@ -0,0 +1,50 @@ + + + +HTTPS +HTTP GET + + + +# +# Server-side + + + + + +# +# Client-side + +# SSL with libraries supporting CURLOPT_CERTINFO + +SSL +!bearssl +!rustls +!wolfssl + + +https + + +lib%TESTNUMBER + + +verify certificate chain order with simple HTTPS GET + + +https://%HOSTIP:%HTTPSPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPSPORT +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test312 b/local-test-curl-delta-01/afc-curl/tests/data/test312 new file mode 100644 index 0000000000000000000000000000000000000000..52fc37cbd72b514abd7d2585c0802d63fcd4d0b5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test312 @@ -0,0 +1,40 @@ + + + +HTTPS +HTTP GET +PEM certificate + + + +# +# Server-side + + + +# +# Client-side + + +SSL +local-http + + +https Server-localhost.nn-sv.pem + + +HTTPS GET to localhost and null-prefixed CN cert + + +-4 --cacert %SRCDIR/certs/EdelCurlRoot-ca.crt https://localhost:%HTTPSPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +60 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test316 b/local-test-curl-delta-01/afc-curl/tests/data/test316 new file mode 100644 index 0000000000000000000000000000000000000000..d2216ad06ae9d63e89dce411c6feb3bc139fefdb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test316 @@ -0,0 +1,196 @@ + + + +HTTP +HTTP GET +compressed + + +# +# Server-side + +# Length of not-encoded content is 16512 what is greater than default value of +# CURL_MAX_WRITE_SIZE (16384) + +SFRUUC8xLjEgMjAwIE9LDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUzIEdNVA0KU2Vy +dmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8xLjMuMjYuMWEg +UEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3BlcmwvMS4yOQ0K +VmFyeTogQWNjZXB0LUVuY29kaW5nDQpDb250ZW50LVR5cGU6IHRleHQvaHRtbDsgY2hhcnNldD1J +U08tODg1OS0xDQpDb250ZW50LUVuY29kaW5nOiBicg0KQ29udGVudC1MZW5ndGg6IDMxDQoNCht/ +QABk8ZjPKBrrr8cSrEGrQmJR88jq2Xuf3BsASAAK + + + +HTTP/1.1 200 OK +Date: Mon, 29 Nov 2004 21:56:53 GMT +Server: Apache/1.3.31 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.9-1 mod_ssl/2.8.20 OpenSSL/0.9.7d mod_perl/1.29 +Vary: Accept-Encoding +Content-Type: text/html; charset=ISO-8859-1 +Content-Encoding: br +Content-Length: 31 + +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF +0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF + + + + +# +# Client-side + + +brotli + + +http + + +HTTP GET brotli compressed content of size more than CURL_MAX_WRITE_SIZE + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --compressed + + + +# +# Verify data after the test has been "shot" + + +s/^Accept-Encoding: [a-zA-Z, ]*/Accept-Encoding: xxx/ + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Accept-Encoding: xxx + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test319 b/local-test-curl-delta-01/afc-curl/tests/data/test319 new file mode 100644 index 0000000000000000000000000000000000000000..81ef747191d87e4ba54074314e0b895fadbfb943 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test319 @@ -0,0 +1,56 @@ + + + +HTTP +HTTP GET +compressed +Transfer-Encoding + + +# +# Server-side + + +SFRUUC8xLjEgMjAwIE9LIHN3c2Nsb3NlDQpEYXRlOiBNb24sIDI5IE5vdiAyMDA0IDIxOjU2OjUz +IEdNVA0KU2VydmVyOiBBcGFjaGUvMS4zLjMxIChEZWJpYW4gR05VL0xpbnV4KSBtb2RfZ3ppcC8x +LjMuMjYuMWEgUEhQLzQuMy45LTEgbW9kX3NzbC8yLjguMjAgT3BlblNTTC8wLjkuN2QgbW9kX3Bl +cmwvMS4yOQ0KQ29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9SVNPLTg4NTktMQ0KVHJh +bnNmZXItRW5jb2Rpbmc6IGd6aXANCkNvbnRlbnQtTGVuZ3RoOiA0NA0KDQofiwgIeZ6rQQADbGFs +YWxhAMvJzEtVMORSyAHRRlwKEIYxFwAKAnFgGAAAAA== + + + +H4sICHmeq0EAA2xhbGFsYQDLycxLVTDkUsgB0UZcChCGMRcACgJxYBgAAAA= + + + + +# +# Client-side + + +libz + + +http + + +HTTP GET gzip transfer-encoded data in raw mode + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --raw + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test3205 b/local-test-curl-delta-01/afc-curl/tests/data/test3205 new file mode 100644 index 0000000000000000000000000000000000000000..3a26cd6d893ebfec92c9601bc003ac26ee165972 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test3205 @@ -0,0 +1,22 @@ + + + +unittest +cipher_suite + + + +# +# Client-side + + +none + + +unittest + + +cipher suite name lookup + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test323 b/local-test-curl-delta-01/afc-curl/tests/data/test323 new file mode 100644 index 0000000000000000000000000000000000000000..72320a66e9498f8b2acccc0a02138d3708d6599c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test323 @@ -0,0 +1,33 @@ + + + +HTTPS +TLS-SRP +FAILURE + + + +# Client-side + + +https + + +TLS-SRP + + +TLS-SRP to non-TLS-SRP server + + +--insecure --tlsauthtype SRP --tlsuser jsmith --tlspassword badpass https://%HOSTIP:%HTTPSPORT/want/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +35 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test33 b/local-test-curl-delta-01/afc-curl/tests/data/test33 new file mode 100644 index 0000000000000000000000000000000000000000..34afff35b70553d6deccf43d8663d8ca15ea3554 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test33 @@ -0,0 +1,60 @@ + + + +HTTP +HTTP PUT +Resume +Content-Range + + +# Server-side + + +HTTP/1.1 200 OK swsclose + + + + +# Client-side + + +http + + +HTTP PUT with resume + + +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 +012345678 + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -T%LOGDIR/test%TESTNUMBER.txt -C 50 + + + +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Content-Range: bytes 50-99/100 +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 50 + +012345678 +012345678 +012345678 +012345678 +012345678 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test332 b/local-test-curl-delta-01/afc-curl/tests/data/test332 new file mode 100644 index 0000000000000000000000000000000000000000..e00f7723116e0bcf8ea1e8c797e2c37d9a1506b1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test332 @@ -0,0 +1,47 @@ + + + +TFTP +TFTP RRQ +FAILURE + + + + + +a chunk of +data +returned + to client + + + +# +# Client-side + + +tftp + + +TFTP retrieve with blksize 400 + + +tftp://%HOSTIP:%TFTPPORT//%TESTNUMBER --tftp-blksize 400 + + + +# +# Verify pseudo protocol after the test has been "shot" + + +^timeout = [5-6]$ + + +opcode = 1 +mode = octet +tsize = 0 +blksize = 400 +filename = /%TESTNUMBER + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test34 b/local-test-curl-delta-01/afc-curl/tests/data/test34 new file mode 100644 index 0000000000000000000000000000000000000000..5d81a5a8f7846b34f7a545ca6d94d1b84fe8f91b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test34 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP GET +chunked Transfer-Encoding + + +# +# Server-side + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Connection: mooo + +40 +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +30 +bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +21;heresatest=moooo +cccccccccccccccccccccccccccccccc + +0 + + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Connection: mooo + +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccc + + + +# +# Client-side + + +http + + +HTTP GET with chunked Transfer-Encoding + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test355 b/local-test-curl-delta-01/afc-curl/tests/data/test355 new file mode 100644 index 0000000000000000000000000000000000000000..67f7777ff504236a4c19d63bad6d5ae791456381 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test355 @@ -0,0 +1,55 @@ + + + +HTTP +Alt-Svc + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +alt-svc + + +http + + +load Alt-Svc from file and use + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --alt-svc "" + + +h1 example.com 80 h1 %HOSTIP %HTTPPORT "20290222 22:19:28" 0 0 + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test365 b/local-test-curl-delta-01/afc-curl/tests/data/test365 new file mode 100644 index 0000000000000000000000000000000000000000..05ab8faa36e6b92ef8ffe39e9b7e53f24cbf2425 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test365 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP GET +Chunked + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 123456 +Transfer-Encoding: chunked +Content-Type: text/html +Funny-head: yesyes + +10 +chunked data fun +0 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 123456 +Transfer-Encoding: chunked +Content-Type: text/html +Funny-head: yesyes + +chunked data fun + + + +# +# Client-side + + +http + + +HTTP/1.1 with chunked AND Content-Length headers + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test37 b/local-test-curl-delta-01/afc-curl/tests/data/test37 new file mode 100644 index 0000000000000000000000000000000000000000..d5e79824c6e20d1c42fe639923b7c0f3c3ee343b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test37 @@ -0,0 +1,45 @@ + + + +HTTP +HTTP GET +FAILURE + + +# +# Server-side + + + + + +# +# Client-side + + +http + + +HTTP GET with nothing returned from server + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +52 + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test380 b/local-test-curl-delta-01/afc-curl/tests/data/test380 new file mode 100644 index 0000000000000000000000000000000000000000..47676e3dd8e156f5a3a01803ae4095caba1aa1b2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test380 @@ -0,0 +1,64 @@ + + + +FTP +EPSV +LIST +netrc + + +# +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + + +# +# Client-side + + +ftp + + +pick netrc password based on user name in URL + + + +--netrc --netrc-file %LOGDIR/netrc%TESTNUMBER ftp://mary@%HOSTIP:%FTPPORT/ + + +# the following two lines were created while testing curl +machine %HOSTIP login frankenstein password wrongone +machine %HOSTIP login mary password yram + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER mary +PASS yram +PWD +EPSV +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test387 b/local-test-curl-delta-01/afc-curl/tests/data/test387 new file mode 100644 index 0000000000000000000000000000000000000000..d0e5c95ed4b0c3e950a18e22d1cfd9de0459be7b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test387 @@ -0,0 +1,59 @@ + + + +HTTP +gzip + + + +# +# Server-side + + +HTTP/1.1 200 OK +Content-Length: 6 +Transfer-Encoding: gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip,gzip + +-foo- + + + +# +# Client-side + + +http + + +libz + + +Response with overly long compression chain + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -sS --tr-encoding + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Connection: TE +TE: gzip + + + +# CURLE_BAD_CONTENT_ENCODING is 61 + +61 + + +curl: (61) Reject response due to more than 5 content encodings + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test390 b/local-test-curl-delta-01/afc-curl/tests/data/test390 new file mode 100644 index 0000000000000000000000000000000000000000..83f1cec422e647a8df397435b5116872cdc03015 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test390 @@ -0,0 +1,48 @@ + + + +HTTP +FTP +parallel + + + +# +# Server-side + + +HTTP/1.1 200 OK +Content-Length: 10001 +Content-Type: text/html + +%repeat[1000 x hellohttp!]% + + + +%repeat[1000 x hello ftp!]% + + + + +# +# Client-side + + +%repeat[1000 x hellofile!]% + + +http +ftp + + +curl HTTP, FILE and FTP in parallel + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER file://localhost%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt ftp://%HOSTIP:%FTPPORT/%TESTNUMBER0002 --parallel -o %LOGDIR/%TESTNUMBER.a -o %LOGDIR/%TESTNUMBER.b -o %LOGDIR/%TESTNUMBER.c + + + +# + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test403 b/local-test-curl-delta-01/afc-curl/tests/data/test403 new file mode 100644 index 0000000000000000000000000000000000000000..7c08d5ca865d5a9e4b56a139b22915bfdab1eb2b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test403 @@ -0,0 +1,63 @@ + + + +FTP +FTPS +PASV +LIST +CCC +FAILURE + + +# +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + + +# +# Client-side + + +SSL + + +ftps + + +FTPS with CCC not supported by server + + +-k --ftp-ssl-control --ftp-ssl-ccc ftps://%HOSTIP:%FTPSPORT/ + + + +# +# Verify data after the test has been "shot" + + +USER anonymous +PASS ftp@example.com +PBSZ 0 +PROT C +CCC +PWD +EPSV +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test409 b/local-test-curl-delta-01/afc-curl/tests/data/test409 new file mode 100644 index 0000000000000000000000000000000000000000..a1f902933238535c73fb9e6746abf27a59414547 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test409 @@ -0,0 +1,57 @@ + + + +FTP +FTPS +EPSV +STOR + + + +# Client-side + + +SSL + + +ftps + + +FTPS PASV upload file + + +data + to + see +that FTP +works + so does it? + + +-k --ftp-ssl-control ftps://%HOSTIP:%FTPSPORT/%TESTNUMBER -T %LOGDIR/test%TESTNUMBER.txt + + + +# Verify data after the test has been "shot" + + +data + to + see +that FTP +works + so does it? + + +USER anonymous +PASS ftp@example.com +PBSZ 0 +PROT C +PWD +EPSV +TYPE I +STOR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test412 b/local-test-curl-delta-01/afc-curl/tests/data/test412 new file mode 100644 index 0000000000000000000000000000000000000000..5923054fc7db6c54eae771476ba2bda775f72b38 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test412 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP GET +Alt-Svc +trailing-dot + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +alt-svc +Debug + + +http + + +alt-svc using host name with trailing dot in URL + + +# make debug-curl accept Alt-Svc over plain HTTP +CURL_ALTSVC_HTTP="yeah" + + +--alt-svc "%LOGDIR/altsvc-%TESTNUMBER" "http://whohoo.:12345/%TESTNUMBER" + + +h1 whohoo 12345 h1 %HOSTIP %HTTPPORT "20290222 22:19:28" 0 0 + + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: whohoo.:12345 +User-Agent: curl/%VERSION +Accept: */* +Alt-Used: %HOSTIP:%HTTPPORT + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test423 b/local-test-curl-delta-01/afc-curl/tests/data/test423 new file mode 100644 index 0000000000000000000000000000000000000000..6c6e725b0119bd714c9df2a98d48701c298115bf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test423 @@ -0,0 +1,51 @@ + + + +-w +--write-out + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 0 +Connection: close +Content-Type: text/html +Funny-head: yesyes + + + + +# +# Client-side + + +http + + +-w with url.* variables + + +"http://uuuu:pppp@%HOSTIP:%HTTPPORT/%TESTNUMBER?qqqq#ffff" "h55p://hello2000:1/%TESTNUMBER?qqqq#ffff" "local host" "http://u22u:p22p@%HOSTIP:%HTTPPORT/%TESTNUMBER?qqqq#ffff" -w '%{url.host}+%{url.path}+%{url.scheme}+%{url.user}+%{url.password}+%{url.port}+%{url.query}+%{url.fragment}\n' + + + +# +# Verify data after the test has been "shot" + + +%HOSTIP+/%TESTNUMBER+http+uuuu+pppp+%HTTPPORT+qqqq+ffff +hello2000+/%TESTNUMBER+h55p+++1+qqqq+ffff ++++++++ +%HOSTIP+/%TESTNUMBER+http+u22u+p22p+%HTTPPORT+qqqq+ffff + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test43 b/local-test-curl-delta-01/afc-curl/tests/data/test43 new file mode 100644 index 0000000000000000000000000000000000000000..1c36f1c60c678b1993b6ebe3aae48840371829ba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test43 @@ -0,0 +1,81 @@ + + + +HTTP +HTTP GET +followlocation +HTTP proxy + + +# Server-side + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: data/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +This server reply is for testing a simple Location: following + + + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + +HTTP/1.1 301 This is a weirdo text message +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: data/%TESTNUMBER0002.txt?coolsite=yes +Connection: close + +HTTP/1.1 200 Followed here fine swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 52 + +If this is received, the location following worked + + + + +# Client-side + + +http + + +HTTP Location: following over HTTP proxy + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER -L -x %HOSTIP:%HTTPPORT + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://%HOSTIP:%HTTPPORT/want/data/%TESTNUMBER0002.txt?coolsite=yes HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test44 b/local-test-curl-delta-01/afc-curl/tests/data/test44 new file mode 100644 index 0000000000000000000000000000000000000000..bc103e031b342ff65bb6653ee9df60b2bb446120 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test44 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP FORMPOST +HTTP replaced headers + + +# Server-side + + +HTTP/1.0 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake + +blablabla + + + + +# Client-side + + +Mime + + +http + + +HTTP RFC1867-type formposting without Expect: header + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER -F name=daniel -F tool=curl -F file=@%LOGDIR/test%TESTNUMBER.txt -H "Expect:" + +# We create this file before the command is invoked! + +foo- +This is a moo- +bar + + + +# Verify data after the test has been "shot" + + +^(Content-Type: multipart/form-data;|------).* + + +POST /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 432 +Content-Type: multipart/form-data; boundary=----------------------------7c633d5c27ce + +------------------------------7c633d5c27ce +Content-Disposition: form-data; name="name" + +daniel +------------------------------7c633d5c27ce +Content-Disposition: form-data; name="tool" + +curl +------------------------------7c633d5c27ce +Content-Disposition: form-data; name="file"; filename="test%TESTNUMBER.txt" +Content-Type: text/plain + +foo- +This is a moo- +bar + +------------------------------7c633d5c27ce-- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test446 b/local-test-curl-delta-01/afc-curl/tests/data/test446 new file mode 100644 index 0000000000000000000000000000000000000000..7f98912560a8b65f3e169c4ae5cad8d3fba4aa58 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test446 @@ -0,0 +1,84 @@ + + + + +HTTP +HTTP proxy +HSTS +trailing-dot + + + + + +# we use this as response to a CONNECT + +HTTP/1.1 200 OK + + + +HTTP/1.1 200 OK +Content-Length: 6 +Strict-Transport-Security: max-age=604800 + +-foo- + + +HTTP/1.1 200 OK +Content-Length: 6 +Strict-Transport-Security: max-age=6048000 + +-baa- + + + + + +https +http-proxy + + +HSTS +proxy +https +Debug + + +CURL_HSTS_HTTP=yes +CURL_TIME=2000000000 + + + +HSTS with two URLs + + +-x http://%HOSTIP:%PROXYPORT --hsts %LOGDIR/hsts%TESTNUMBER http://this.hsts.example./%TESTNUMBER http://another.example.com/%TESTNUMBER0002 + + + + +# we let it CONNECT to the server to confirm HSTS but deny from there + +GET http://this.hsts.example./%TESTNUMBER HTTP/1.1 +Host: this.hsts.example. +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://another.example.com/%TESTNUMBER0002 HTTP/1.1 +Host: another.example.com +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + +# Your HSTS cache. https://curl.se/docs/hsts.html +# This file was generated by libcurl! Edit at your own risk. +this.hsts.example "20330525 03:33:20" +another.example.com "20330727 03:33:20" + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test447 b/local-test-curl-delta-01/afc-curl/tests/data/test447 new file mode 100644 index 0000000000000000000000000000000000000000..2783b750b61d78e1aa789241a476934584e97a7f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test447 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP PUT +growing file + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +Debug + + +http + + +HTTP PUT with growing file + + +CURL_UPLOAD_SIZE=498 + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -T %LOGDIR/upload%TESTNUMBER + + +%repeat[100 x hello]% + + + +# +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 498 + +%repeat[99 x hello]%hel + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test448 b/local-test-curl-delta-01/afc-curl/tests/data/test448 new file mode 100644 index 0000000000000000000000000000000000000000..0e257e70495cb1f4dc481514d8adf3e3214c3bc5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test448 @@ -0,0 +1,67 @@ + + + +HTTP +variables +--config + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +FUNVALUE=contents +VALUE2=curl +BLANK= + + +Environment variables within config file, unbalanced braces + + +--variable %FUNVALUE +--variable %VALUE2 +--expand-data 1{{FUNVALUE}}2{{VALUE2}}3{{curl_NOT_SET}}4{{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}}5{{broken + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -K %LOGDIR/cmd + + + +# +# Verify data after the test has been "shot" + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 157 +Content-Type: application/x-www-form-urlencoded + +1contents2curl34{{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}}5{{broken + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test453 b/local-test-curl-delta-01/afc-curl/tests/data/test453 new file mode 100644 index 0000000000000000000000000000000000000000..c1b27d03e21aae31d0ca62c8f5eec16325943320 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test453 @@ -0,0 +1,33 @@ + + + +HTTP +variables + + + +# +# Client-side + + +http + + +Variable output containing null byte + + +%hex[%01%02%03%00%04%05%06]hex% + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --variable what@%LOGDIR/junk --expand-data "{{what}}" + + + +# +# Verify data after the test has been "shot" + + +2 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test456 b/local-test-curl-delta-01/afc-curl/tests/data/test456 new file mode 100644 index 0000000000000000000000000000000000000000..1623aecaf794487f57993451fafb088798cc8a48 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test456 @@ -0,0 +1,33 @@ + + + +HTTP +variables + + + +# +# Client-side + + +http + + +Variable output starting with null byte + + +%hex[%00]hex%hello + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --variable what@%LOGDIR/junk --expand-data "{{what}}" + + + +# +# Verify data after the test has been "shot" + + +2 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test457 b/local-test-curl-delta-01/afc-curl/tests/data/test457 new file mode 100644 index 0000000000000000000000000000000000000000..aa391d7fd00908aac3e433f0ae878e277073220c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test457 @@ -0,0 +1,69 @@ + + + +HTTP +HTTP GET +chunked Transfer-Encoding + + +# +# Server-side + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Connection: mooo + +40 +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +30 +bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +21;heresatest=moooo +cccccccccccccccccccccccccccccc +c + +0 + + + +HTTP/1.1 200 funky chunky! +Server: fakeit/0.9 fakeitbad/1.0 +Transfer-Encoding: chunked +Connection: mooo + +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccc + + + +# +# Client-side + + +http + + +chunked Transfer-Encoding with --max-filesize + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --max-filesize 143 + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + +# curl: (63) Exceeded the maximum allowed file size (143) + +63 + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test462 b/local-test-curl-delta-01/afc-curl/tests/data/test462 new file mode 100644 index 0000000000000000000000000000000000000000..24c414ef3f11442fe1be4ac14373e76e967ada88 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test462 @@ -0,0 +1,39 @@ + + + +variables +--config + + + +# +# Server-side + + + +# +# Client-side + + +none + + +Missing environment variables in config file + + +variable %MISSING +expand-data {{MISSING}} + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -K %LOGDIR/cmd + + + +# +# Verify data after the test has been "shot" + + +26 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test463 b/local-test-curl-delta-01/afc-curl/tests/data/test463 new file mode 100644 index 0000000000000000000000000000000000000000..27ecd4ba58007689a5763aae023118a92104024b Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/data/test463 differ diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test480 b/local-test-curl-delta-01/afc-curl/tests/data/test480 new file mode 100644 index 0000000000000000000000000000000000000000..aab889f472caa22a16e719483eae4e23802969c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test480 @@ -0,0 +1,38 @@ + + + +netrc +pop3 + + +# +# Server-side + + + + +# +# Client-side + + +pop3 + + +Reject .netrc with credentials using CRLF for POP3 + + +--netrc --netrc-file %LOGDIR/netrc%TESTNUMBER pop3://%HOSTIP:%POP3PORT/%TESTNUMBER + + +machine %HOSTIP + login alice + password "password\r\ncommand" + + + + + +26 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test481 b/local-test-curl-delta-01/afc-curl/tests/data/test481 new file mode 100644 index 0000000000000000000000000000000000000000..33e7734bcf072b5b48a98be8dbeac6cf336c9701 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test481 @@ -0,0 +1,49 @@ + + + +HTTP +HTTP GET +--no-clobber +--continue-at + + + +# +# Server-side + + + +# +# Client-side + + +http + + +--no-clobber with --continue-at + + +initial content + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --no-clobber -C 1 -o "%LOGDIR/%TESTNUMBER" + + + +# +# Verify data after the test has been "shot" + + +2 + + +curl: --continue-at is mutually exclusive with --no-clobber +curl: option -C: is badly used here +%if manual +curl: try 'curl --help' or 'curl --manual' for more information +%else +curl: try 'curl --help' for more information +%endif + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test49 b/local-test-curl-delta-01/afc-curl/tests/data/test49 new file mode 100644 index 0000000000000000000000000000000000000000..996cf018bde1f0080faa96e49e110e1dd712b6ce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test49 @@ -0,0 +1,72 @@ + + + +HTTP +HTTP GET +followlocation + + +# +# Server-side + + +HTTP/1.1 302 OK swsclose +Location: ../moo.html/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + + + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + +HTTP/1.1 302 OK swsclose +Location: ../moo.html/%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:49:00 GMT +Connection: close + +body + + + +# +# Client-side + + +http + + +HTTP follow redirect with ../ + + +http://%HOSTIP:%HTTPPORT/we/are/all/twits/%TESTNUMBER -L + + + +# +# Verify data after the test has been "shot" + + +GET /we/are/all/twits/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /we/are/all/moo.html/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test490 b/local-test-curl-delta-01/afc-curl/tests/data/test490 new file mode 100644 index 0000000000000000000000000000000000000000..a0bc8f35396385d33647953518394c9f7704f584 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test490 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP PUT + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +Two globbed HTTP PUTs + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -T '{%LOGDIR/in%TESTNUMBER,%LOGDIR/in%TESTNUMBER}' + + +surprise! + + + +# +# Verify data after the test has been "shot" + + +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 10 + +surprise! +PUT /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Content-Length: 10 + +surprise! + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test493 b/local-test-curl-delta-01/afc-curl/tests/data/test493 new file mode 100644 index 0000000000000000000000000000000000000000..d157f0355fa9c508e96f408b9a8648421b96a844 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test493 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP proxy +HSTS +url_effective + + + + + +# we use this as response to a CONNECT + +HTTP/1.1 403 not OK at all +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Funny-head: yesyes + +-foo- + + + + + +http + + +HSTS +proxy +https + + + +.hsts.example "99991001 04:47:41" + + + +HSTS and %{url_effective} after upgrade + + +-x http://%HOSTIP:%HTTPPORT http://this.hsts.example/%TESTNUMBER --hsts %LOGDIR/input%TESTNUMBER -w '%{url_effective}\n' + + +test-duphandle + + + + +# we let it CONNECT to the server to confirm HSTS but deny from there + +CONNECT this.hsts.example:443 HTTP/1.1 +Host: this.hsts.example:443 +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + +HTTP/1.1 403 not OK at all +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 6 +Connection: close +Funny-head: yesyes + +https://this.hsts.example/%TESTNUMBER + +# Proxy CONNECT aborted + +56 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test498 b/local-test-curl-delta-01/afc-curl/tests/data/test498 new file mode 100644 index 0000000000000000000000000000000000000000..b1fc02380bdd6af2065115ce240bd019ccbcbd52 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test498 @@ -0,0 +1,56 @@ + + + +HTTP +HTTP GET + + + +# +# Server-side + + +HTTP/1.1 301 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Location: / +Connection: close +Content-Type: text/html +%repeat[1700 x Repeat-this-Header-a-large-number-of-times: Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, who was a farmer, and Aunt Em, who was the farmer’s wife.%0a]% +-foo- + + + +# +# Client-side + + +http + + +Reject too large HTTP response headers on endless redirects + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --max-redirs 400 --location + + + +# +# Verify data after the test has been "shot" + +# curl: (56) Too large response headers: 6144086 > 6144000 +# hyper returns a generic error that libcurl converts to an even more +# generic error + +%if hyper +1 +%else +56 +%endif + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test501 b/local-test-curl-delta-01/afc-curl/tests/data/test501 new file mode 100644 index 0000000000000000000000000000000000000000..fb115cba645f2818e7313342f28d4cddef43288b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test501 @@ -0,0 +1,40 @@ + + + +missing URL + + +# +# Server-side + + + +# Client-side + + +none + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +simple libcurl attempt operation without URL set + + +http://%HOSTIP:%NOLISTENPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +3 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test502 b/local-test-curl-delta-01/afc-curl/tests/data/test502 new file mode 100644 index 0000000000000000000000000000000000000000..4e7ce38ae2c3692f5d52833e7b712ddecd2bfdf7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test502 @@ -0,0 +1,47 @@ + + + +FILE + + +# +# Server-side + + +foo + bar swsclose +bar + foo +moo + + + +# Client-side + + +file + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +simple multi file:// get + + +file://%FILE_PWD/%LOGDIR/test%TESTNUMBER.txt + + +foo + bar swsclose +bar + foo +moo + + + +# Verify data after the test has been "shot" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test503 b/local-test-curl-delta-01/afc-curl/tests/data/test503 new file mode 100644 index 0000000000000000000000000000000000000000..9fbc00b951c84c37f139c53b333ce5eb16f6726c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test503 @@ -0,0 +1,90 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP proxy +HTTP proxy Basic auth +proxytunnel +multi + + + +# Server-side + + +connection-monitor + + +HTTP/1.1 200 Mighty fine indeed + + + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" + + + +HTTP/1.1 200 Mighty fine indeed + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" + + + + +# Client-side + + +http +http-proxy + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + +proxy + + +simple multi http:// through proxytunnel with authentication info + + +http://machine.%TESTNUMBER:%HTTPPORT/%TESTNUMBER %HOSTIP:%PROXYPORT + + +foo + bar +bar + foo +moo + + + +# Verify data after the test has been "shot" + + +CONNECT machine.%TESTNUMBER:%HTTPPORT HTTP/1.1 +Host: machine.%TESTNUMBER:%HTTPPORT +Proxy-Authorization: Basic dGVzdCUyMDppbmclNDE= +Proxy-Connection: Keep-Alive + +[DISCONNECT] + + +GET /%TESTNUMBER HTTP/1.1 +Host: machine.%TESTNUMBER:%HTTPPORT +Authorization: Basic dGVzdDppbmc= +Accept: */* + +[DISCONNECT] + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test51 b/local-test-curl-delta-01/afc-curl/tests/data/test51 new file mode 100644 index 0000000000000000000000000000000000000000..277da000fbaf4814b0cc297c1e47abec2c25537e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test51 @@ -0,0 +1,72 @@ + + + +HTTP +HTTP GET +followlocation + + +# +# Server-side + + +HTTP/1.1 302 OK swsclose +Location: ../../../../../../../%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:50:00 GMT +Connection: close + + + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:50:00 GMT +Connection: close + +body + + +HTTP/1.1 302 OK swsclose +Location: ../../../../../../../%TESTNUMBER0002 +Date: Tue, 09 Nov 2010 14:50:00 GMT +Connection: close + +HTTP/1.1 200 OK swsclose +Location: this should be ignored +Date: Tue, 09 Nov 2010 14:50:00 GMT +Connection: close + +body + + + +# +# Client-side + + +http + + +HTTP follow redirect with excessive ../ + + +http://%HOSTIP:%HTTPPORT/we/are/all/twits/%TESTNUMBER -L + + + +# +# Verify data after the test has been "shot" + + +GET /we/are/all/twits/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test520 b/local-test-curl-delta-01/afc-curl/tests/data/test520 new file mode 100644 index 0000000000000000000000000000000000000000..17d89199bfe90b950497a379cab763d032eabe92 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test520 @@ -0,0 +1,56 @@ + + + +FTP + + + +# +# Server-side + + +contents of file + + +REPLY MDTM 213 20030405060708 + + + +# Client-side + + +ftp + +# tool is what to use instead of 'curl' + +lib520 + + + +FTP RETR with FILETIME + + +ftp://%HOSTIP:%FTPPORT/520 + + + +# +# Verify data after the test has been "shot" + + +QUIT + + + +USER anonymous +PASS ftp@example.com +PWD +MDTM 520 +EPSV +TYPE I +SIZE 520 +RETR 520 +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test522 b/local-test-curl-delta-01/afc-curl/tests/data/test522 new file mode 100644 index 0000000000000000000000000000000000000000..3aa053a58434f0052588f2857fdf0e0855bbc77f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test522 @@ -0,0 +1,57 @@ + + + +HTTP +HTTP GET +CURLOPT_PORT + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 + +hello + + + +# +# Client-side + + +http + + +lib521 + + +HTTP GET with CURLOPT_PORT + + +http://%HOSTIP/%TESTNUMBER %HTTPPORT + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic eHh4Onl5eQ== +Accept: */* + + + +hello + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test528 b/local-test-curl-delta-01/afc-curl/tests/data/test528 new file mode 100644 index 0000000000000000000000000000000000000000..7cb9e8b1149f27417636b7ffbf0f04adbc9470a2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test528 @@ -0,0 +1,65 @@ + + + +HTTP +HTTP GET +multi + + + +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 47 + +file contents should appear once for each file + + +file contents should appear once for each file +file contents should appear once for each file +file contents should appear once for each file +file contents should appear once for each file + + + +# Client-side + + +http + + +lib526 + + +HTTP GET same file using different handles but same connection + + +http://%HOSTIP:%HTTPPORT/path/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +GET /path/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + +GET /path/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test53 b/local-test-curl-delta-01/afc-curl/tests/data/test53 new file mode 100644 index 0000000000000000000000000000000000000000..0bbc5d63734e8e6f6e5c252d97df788d1cfecec1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test53 @@ -0,0 +1,55 @@ + + + +HTTP +HTTP GET +cookies + + +# Server-side + + +HTTP/1.1 200 OK +Server: Microsoft-IIS/4.0 +Date: Tue, 25 Sep 2001 19:37:44 GMT +Content-Type: text/html +Connection: close +Content-Length: 21 + +This server says moo + + + +# Client-side + + +http + + +HTTP, junk session cookies + + +%HOSTIP:%HTTPPORT/want/%TESTNUMBER -b %LOGDIR/injar%TESTNUMBER -j + + +%HOSTIP FALSE / FALSE 22139150993 mooo indeed +%HOSTIP FALSE / FALSE 0 moo1 indeed +%HOSTIP FALSE / FALSE 1 moo2 indeed + + +cookies + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +Cookie: mooo=indeed + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test538 b/local-test-curl-delta-01/afc-curl/tests/data/test538 new file mode 100644 index 0000000000000000000000000000000000000000..a269cdf1a2122c61060a2cad68f5840b5eb65e2b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test538 @@ -0,0 +1,45 @@ + + + +FTP +FAILURE +multi + + + +# Server-side + + +REPLY PASS 314 bluah you f00l! + + + +# Client-side + + +ftp + +# NOTE that we use the 504 tool for this case + +lib504 + + +FTP multi-interface download, failed login: PASS not valid + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER + + + +# Verify data after the test has been "shot" +# TEST_ERR_SUCCESS is errorcode 120 + + +120 + + +USER anonymous +PASS ftp@example.com + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test545 b/local-test-curl-delta-01/afc-curl/tests/data/test545 new file mode 100644 index 0000000000000000000000000000000000000000..3827cb9de419b087cfb1af9dc202d44bcf5da41f Binary files /dev/null and b/local-test-curl-delta-01/afc-curl/tests/data/test545 differ diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test546 b/local-test-curl-delta-01/afc-curl/tests/data/test546 new file mode 100644 index 0000000000000000000000000000000000000000..6021b6758172e94bfc073518b9c67a5af7fe0437 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test546 @@ -0,0 +1,73 @@ + + + +FTP +PASV +RETR +multi + + +# Server-side + + +data + to + see +that FTP +works + so does it? + + + +REPLY RETR 550 the file doesn't exist +COUNT RETR 1 +REPLY SIZE 500 Can't check for file existence +COUNT SIZE 1 + + + +# Client-side + + +ftp + + +lib533 + + +FTP RETR a non-existing file then a found one using the multi interface + + +ftp://%HOSTIP:%FTPPORT/path/%TESTNUMBER ftp://%HOSTIP:%FTPPORT/path/%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +EPSV +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + +data + to + see +that FTP +works + so does it? + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test551 b/local-test-curl-delta-01/afc-curl/tests/data/test551 new file mode 100644 index 0000000000000000000000000000000000000000..452da3927f6336bed85a6dd8d200d0b830c7ba80 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test551 @@ -0,0 +1,98 @@ + + +# this test is meant to be exactly like 547 but using Digest instead of NTLM + +HTTP +HTTP POST +POST callback +HTTP proxy +HTTP proxy Digest auth + + + +# Server-side + + +# as a bonus, ww use an excessive nonce length + +HTTP/1.1 407 Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Proxy-Authenticate: Digest realm="something fun to read", nonce="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +This is not the real page + + +# This is supposed to be returned when the server gets the Digest +# Authorization: line passed-in from the client + +HTTP/1.1 200 Things are fine in proxy land swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 42 + +Contents of that page you requested, sir. + + + +HTTP/1.1 407 Authorization Required swsclose +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Proxy-Authenticate: Digest realm="something fun to read", nonce="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +Content-Type: text/html; charset=iso-8859-1 +Connection: close + +HTTP/1.1 200 Things are fine in proxy land swsclose +Server: Microsoft-IIS/5.0 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 42 + +Contents of that page you requested, sir. + + + +# Client-side + + +http + +# tool to use + +lib547 + + +!SSPI +crypto +proxy + + +HTTP proxy auth Digest with POST data from read callback + + +http://test.remote.example.com/path/%TESTNUMBER http://%HOSTIP:%HTTPPORT s1lly:pers0n + + + +# Verify data after the test has been "shot" + + +POST http://test.remote.example.com/path/%TESTNUMBER HTTP/1.1 +Host: test.remote.example.com +Accept: */* +Proxy-Connection: Keep-Alive +Content-Length: 36 +Content-Type: application/x-www-form-urlencoded + +this is the blurb we want to upload +POST http://test.remote.example.com/path/%TESTNUMBER HTTP/1.1 +Host: test.remote.example.com +Proxy-Authorization: Digest username="s1lly", realm="something fun to read", nonce="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", uri="/path/%TESTNUMBER", response="3325240726fbdaf1e61f3a0dd40b930c" +Accept: */* +Proxy-Connection: Keep-Alive +Content-Length: 36 +Content-Type: application/x-www-form-urlencoded + +this is the blurb we want to upload + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test557 b/local-test-curl-delta-01/afc-curl/tests/data/test557 new file mode 100644 index 0000000000000000000000000000000000000000..9d86c0ac2182d6b12d517d31c5ef27e99c615a2f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test557 @@ -0,0 +1,48 @@ + + + +printf +unittest + + +# +# Server-side + + + +# Client-side + + +none + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +curl_mprintf() testing + + +nothing + + + +# +# Verify data after the test has been "shot" + + +All curl_mprintf() unsigned short tests OK! +All curl_mprintf() signed short tests OK! +All curl_mprintf() unsigned int tests OK! +All curl_mprintf() signed int tests OK! +All curl_mprintf() unsigned long tests OK! +All curl_mprintf() signed long tests OK! +All curl_mprintf() curl_off_t tests OK! +All curl_mprintf() strings tests OK! +All float strings tests OK! +All curl_mprintf() octal & hexadecimal tests OK! + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test559 b/local-test-curl-delta-01/afc-curl/tests/data/test559 new file mode 100644 index 0000000000000000000000000000000000000000..982209ce9df409c0c427f2611b1936d39b0ef6c1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test559 @@ -0,0 +1,51 @@ + + + +CURLOPT_BUFFERSIZE +HTTP + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 2049 +Connection: close +Content-Type: text/html +Silly-header: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + +ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + + + +# Client-side + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +use tiny CURLOPT_BUFFERSIZE + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test564 b/local-test-curl-delta-01/afc-curl/tests/data/test564 new file mode 100644 index 0000000000000000000000000000000000000000..3b0a2ae1ed3d368e296470b07797bf1bcb22d631 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test564 @@ -0,0 +1,71 @@ + +# Warning: if this test fails to start the SSH server, check that none of +# the user's shell profiles sends output to stdout of a non-interactive shell. + + +FTP +PASV +RETR +multi +SOCKS4 + + +# Server-side + + +data + to + see +that FTP +works + so does it? + + + + +# Client-side + + +ftp +socks4 + + +lib%TESTNUMBER + + +FTP RETR a file over a SOCKS proxy using the multi interface + + +ftp://%HOSTIP:%FTPPORT/path/%TESTNUMBER %HOSTIP:%SOCKSPORT + + +proxy + + + +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD path +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + +data + to + see +that FTP +works + so does it? + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test57 b/local-test-curl-delta-01/afc-curl/tests/data/test57 new file mode 100644 index 0000000000000000000000000000000000000000..f177f08eb46c3f3935632547e9e83ad12e8bd49b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test57 @@ -0,0 +1,46 @@ + + + +HTTP +HTTP GET +--write-out + + + +# Server-side + + +HTTP/1.1 200 OK swsclose +Funny-head: yesyes +Content-Type: text/html; charset=ISO-8859-4 + + + + +# Client-side + + +http + + +HTTP content-type with spaces in + + +-w "%{content_type}\n" http://%HOSTIP:%HTTPPORT/%TESTNUMBER -o %LOGDIR/out%TESTNUMBER + + + +# Verify data after the test has been "shot" + + +text/html; charset=ISO-8859-4 + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test583 b/local-test-curl-delta-01/afc-curl/tests/data/test583 new file mode 100644 index 0000000000000000000000000000000000000000..c9e614bae8edc0d266df9312f7669dac1d52b042 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test583 @@ -0,0 +1,42 @@ + + + +SFTP +multi + + + +# Server-side + + + + + +# Client-side + + +sftp + + +lib%TESTNUMBER + + +SFTP with multi interface, remove handle early + + +# The command here uses 'localhost' just to make sure that curl_multi_perform +# won't reach too far in the first invoke. When using c-ares at least, the +# name resolve will cause it to return rather quickly and thus we could trigger +# the problem we're looking to verify. + +sftp://localhost:%SSHPORT%SSH_PWD/%LOGDIR/upload%TESTNUMBER.txt %USER: %LOGDIR/server/curl_client_key.pub %LOGDIR/server/curl_client_key + + + +# Verify data after the test has been "shot" + + +0 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test596 b/local-test-curl-delta-01/afc-curl/tests/data/test596 new file mode 100644 index 0000000000000000000000000000000000000000..30e401df7af354e02829a290afbb714f9eef8f4d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test596 @@ -0,0 +1,63 @@ + +# +# This test is like 585 but uses active FTP instead of HTTP +# + + +FTP + + +# +# Server-side + + +moo + + +[OPEN] counter: 1 +[OPEN] counter: 2 +[CLOSE] counter: 2 +moo +[CLOSE] counter: 1 + + + +# Client-side + + +ftp + +# tool is what to use instead of 'curl' + +lib585 + + + +verify close callbacks with active FTP + + +ftp://%HOSTIP:%FTPPORT/%TESTNUMBER %LOGDIR/ip%TESTNUMBER activeftp + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +s/^(EPRT \|1\|)(.*)/$1/ + + +USER anonymous +PASS ftp@example.com +PWD +EPRT |1| +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test599 b/local-test-curl-delta-01/afc-curl/tests/data/test599 new file mode 100644 index 0000000000000000000000000000000000000000..5d334e070b2d6b6d573bf4b876f38239f3fba1a2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test599 @@ -0,0 +1,86 @@ + + + +HTTP +HTTP POST +chunked Transfer-Encoding + + +# +# Server-side + + +HTTP/1.1 302 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: %TESTNUMBER0001 +Content-Length: 6 +Connection: close +Content-Type: text/html + +-foo- + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Transfer-Encoding: chunked +Connection: close +Content-Type: text/html + +32 +this data is slightly larger than the first piece + +0 + + + + +HTTP/1.1 302 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Location: %TESTNUMBER0001 +Content-Length: 6 +Connection: close +Content-Type: text/html + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Transfer-Encoding: chunked +Connection: close +Content-Type: text/html + +this data is slightly larger than the first piece + + + + +# Client-side + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + +# Bug 3510057 pointed out that when following a location to a larger chunked +# encoded page, the first size would still be used in the progress callback + +HTTP GET with progress callback and redirects changing content sizes + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER %LOGDIR/ip%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +CL -1 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test608 b/local-test-curl-delta-01/afc-curl/tests/data/test608 new file mode 100644 index 0000000000000000000000000000000000000000..6f9ed07b9594ef182efe2d84a3066895ec111cd2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test608 @@ -0,0 +1,46 @@ + + + +SFTP +post-quote + + + +# +# Server-side + + +Test file for rename test + + + +# +# Client-side + + +sftp + + +SFTP post-quote rename + + +--key %LOGDIR/server/curl_client_key --pubkey %LOGDIR/server/curl_client_key.pub -u %USER: -Q "-rename %SSH_PWD/%LOGDIR/file%TESTNUMBER.txt %SSH_PWD/%LOGDIR/file%TESTNUMBER-renamed.txt" sftp://%HOSTIP:%SSHPORT%SSH_PWD/%LOGDIR/file%TESTNUMBER.txt --insecure + +# Verify that the file was renamed properly, then rename the file back to what +# it was so the verify section works and the file can be cleaned up. + +Test file for rename test + + + +# +# Verify data after the test has been "shot" + + +Test file for rename test + + +%PERL %SRCDIR/libtest/test610.pl gone %PWD/%LOGDIR/file%TESTNUMBER.txt move %PWD/%LOGDIR/file%TESTNUMBER-renamed.txt %PWD/%LOGDIR/file%TESTNUMBER.txt + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test627 b/local-test-curl-delta-01/afc-curl/tests/data/test627 new file mode 100644 index 0000000000000000000000000000000000000000..4696209b8ba169308247b7bdf1bc4156036d0d24 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test627 @@ -0,0 +1,43 @@ + + + +SFTP +pre-quote +NOBODY + + + +# +# Server-side + + + + + +# +# Client-side + + +sftp + + +SFTP quote remove file with NOBODY + + +--key %LOGDIR/server/curl_client_key --pubkey %LOGDIR/server/curl_client_key.pub -u %USER: -I -Q "rm %SSH_PWD/%LOGDIR/file%TESTNUMBER.txt" sftp://%HOSTIP:%SSHPORT --insecure + + +Dummy test file for remove test + + + +# +# Verify data after the test has been "shot" + + + + +%PERL %SRCDIR/libtest/test610.pl gone %PWD/%LOGDIR/test%TESTNUMBER.txt + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test63 b/local-test-curl-delta-01/afc-curl/tests/data/test63 new file mode 100644 index 0000000000000000000000000000000000000000..3a7e015fd3560431a2c2551eb94f0e204d84f228 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test63 @@ -0,0 +1,53 @@ + + + +HTTP +HTTP GET +HTTP proxy +HTTP proxy Basic auth + + +# Server-side + + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Type: text/html +Content-Length: 26 + +the content would go here + + + +# Client-side + + +http + + +HTTP with proxy authorization set in environment + + +http_proxy=http://fake:user@%HOSTIP:%HTTPPORT/ + + +http://we.want.that.site.com/%TESTNUMBER + + +proxy + + + +# Verify data after the test has been "shot" + + +GET http://we.want.that.site.com/%TESTNUMBER HTTP/1.1 +Host: we.want.that.site.com +Proxy-Authorization: Basic ZmFrZTp1c2Vy +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test643 b/local-test-curl-delta-01/afc-curl/tests/data/test643 new file mode 100644 index 0000000000000000000000000000000000000000..400d1b9ca528b2a4f692aa43e477bac2b6e180cb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test643 @@ -0,0 +1,134 @@ + + + +HTTP +HTTP POST +HTTP MIME POST + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + + +# Client-side + + +Mime + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +HTTP multi-part mimepost using read callback for the file part + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + +# Note that the stripping above removes 12 bytes from every occurrence of the +# boundary string and since 5 of them are in the body contents, we see +# (5*12) == 60 bytes less + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 676 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data; name="sendfile"; filename="postit2.c" + +dummy + +------------------------------ +Content-Disposition: form-data; name="callbackdata" + +dummy + +------------------------------ +Content-Disposition: form-data; name="filename" + +postit2.c +------------------------------ +Content-Disposition: form-data; name="submit" + +send +------------------------------ +Content-Disposition: form-data; name="somename"; filename="somefile.txt" +Content-Type: text/plain + +blah blah +-------------------------------- +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 690 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data; name="sendfile alternative"; filename="file name 2" + +dummy + +------------------------------ +Content-Disposition: form-data; name="callbackdata" + +dummy + +------------------------------ +Content-Disposition: form-data; name="filename" + +postit2.c +------------------------------ +Content-Disposition: form-data; name="submit" + +send +------------------------------ +Content-Disposition: form-data; name="somename"; filename="somefile.txt" +Content-Type: text/plain + +blah blah +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test647 b/local-test-curl-delta-01/afc-curl/tests/data/test647 new file mode 100644 index 0000000000000000000000000000000000000000..d34fe21f74272f279c203ec91a56f21af26d4d54 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test647 @@ -0,0 +1,82 @@ + + + +IMAP +APPEND +MULTIPART + + + +# +# Server-side + + + +# +# Client-side + + +Mime + + +imap + + +IMAP APPEND multipart using mime API + + +imap://%HOSTIP:%IMAPPORT/%TESTNUMBER -F "=(;type=multipart/alternative" -F "= This is the html version;type=text/html" -F "=This is the plain text version" -F "=)" -F "=@%LOGDIR/test%TESTNUMBER.txt" -H "Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST)" -H "From: Fred Foobar " -H "To: joe@example.com" -H "Message-Id: " -H "Subject: afternoon meeting" -u user:secret + + +This is an attached file. + +It may contain any type of data. + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + + +A001 CAPABILITY +A002 LOGIN user secret +A003 APPEND %TESTNUMBER (\Seen) {940} +A004 LOGOUT + + +Content-Type: multipart/mixed; boundary=---------------------------- +Mime-Version: 1.0 +Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST) +From: Fred Foobar +To: joe@example.com +Message-Id: +Subject: afternoon meeting + +------------------------------ +Content-Type: multipart/alternative; boundary=---------------------------- + +------------------------------ +Content-Type: text/html +Content-Transfer-Encoding: 8bit + +This is the html version +------------------------------ + +This is the plain text version +-------------------------------- + +------------------------------ +Content-Disposition: attachment; filename="test%TESTNUMBER.txt" + +This is an attached file. + +It may contain any type of data. + +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test65 b/local-test-curl-delta-01/afc-curl/tests/data/test65 new file mode 100644 index 0000000000000000000000000000000000000000..fcf43563fc7d665e972aae1455196ef12eae73d5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test65 @@ -0,0 +1,82 @@ + + + +HTTP +HTTP GET +HTTP Digest auth + + +# Server-side + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="2053604145" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +This is not the real page + + +# This is supposed to be returned when the server gets a +# Authorization: Digest line passed-in from the client + +HTTP/1.1 401 Still a bad password you moron +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 34 + +This is not the real page either + + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="2053604145" +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +HTTP/1.1 401 Still a bad password you moron +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 34 + +This is not the real page either + + + + +# Client-side + + +http + + +!SSPI +crypto + + +HTTP with Digest authorization with bad password + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -u testuser:test2pass --digest + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="testuser", realm="testrealm", nonce="2053604145", uri="/%TESTNUMBER", response="66d68d3251f1839576ba7c766cf9205b" +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test651 b/local-test-curl-delta-01/afc-curl/tests/data/test651 new file mode 100644 index 0000000000000000000000000000000000000000..48e42df6174dfefd3e94c33fc56dcf3573fa7496 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test651 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP POST +FORM + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + + +# Client-side + + +form-api + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +curl_formadd with huge COPYCONTENTS + + + Some data from stdin + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER %LOGDIR/test%TESTNUMBER.filedata + + +This is data from a file. + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + +# Note that the stripping above removes 12 bytes from every occurrence of the +# boundary string and since 5 of them are in the body contents, we see +# (5*12) == 60 bytes less + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 17151 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data; name="hello" + +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test652 b/local-test-curl-delta-01/afc-curl/tests/data/test652 new file mode 100644 index 0000000000000000000000000000000000000000..31ec7b821daa6caef5462f6adfdd2852d5358d64 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test652 @@ -0,0 +1,361 @@ + + + +SMTP +MIME + + + +# +# Server-side + + + +# +# Client-side + + +Mime + + +smtp + + +lib%TESTNUMBER + + + +SMTP with encoded huge mime data contents + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + + +EHLO %TESTNUMBER +MAIL FROM: +RCPT TO: +DATA +QUIT + + +Content-Type: multipart/mixed; boundary=---------------------------- +Mime-Version: 1.0 + +------------------------------ +Content-Disposition: attachment; filename="myfile.jpg" +Content-Type: image/jpeg +Content-Transfer-Encoding: base64 + +QUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZG +RkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExM +TExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFS +UlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dX +V1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0ND +Q0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJ +SUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5O +Tk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRU +VFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpa +WlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVF +RkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tL +S0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFR +UVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZX +V1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJC +QkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhI +SEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5O +Tk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NT +U1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZ +WVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVF +RUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpK +S0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQ +UFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZW +VlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFC +QkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dH +R0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1N +TU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNT +U1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhY +WFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDRERERERE +REREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpK +SkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09P +UFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVV +VVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFB +QUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZH +R0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExM +TExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJS +UlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hY +WFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0ND +Q0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJ +SUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09P +T09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRU +VVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpa +WlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZG +RkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tM +TExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFR +UVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dX +V1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkND +Q0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhI +SElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5O +Tk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRU +VFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZ +WlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVF +RUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tL +S0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBR +UVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZW +VlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJC +QkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hI +SEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1N +TU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NT +U1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZ +WVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERE +RUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpK +SkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQ +UFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVW +VlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFB +QUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dH +R0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1N +TU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJS +UlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhY +WFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDRERE +REREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJ +SkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09P +T09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVV +VVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpB +QUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZG +RkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExM +TExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJS +UlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dX +V1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0ND +Q0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJ +SUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5O +T09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRU +VFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpa +WlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVG +RkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tL +S0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFR +UVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldX +V1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJC +QkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhI +SEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5O +Tk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NT +VFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZ +WVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVF +RUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpL +S0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQ +UFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZW +VlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJC +QkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dH +R0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1N +TU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NT +U1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhY +WVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERE +RERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpK +SkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09Q +UFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVV +VVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFB +QUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdH +R0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExM +TE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJS +UlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhY +WFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0ND +REREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJ +SUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09P +T09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRV +VVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpa +WlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZG +RkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xM +TExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFR +UVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dX +V1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0ND +Q0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhI +SUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5O +Tk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRU +VFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVla +WlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVF +RUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tL +S0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFR +UVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZW +VldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJC +QkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhI +SEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1N +Tk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NT +U1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZ +WVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERF +RUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpK +SkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQ +UFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZW +VlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFB +QUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dH +R0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1N +TU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJS +U1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhY +WFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERE +RERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlK +SkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09P +T09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVV +VVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFB +QUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZG +RkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExM +TExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJS +UlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dX +WFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0ND +Q0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJ +SUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5P +T09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRU +VFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpa +WlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZG +RkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tL +S0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFR +UVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dX +V1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJC +Q0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhI +SEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5O +Tk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NU +VFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZ +WVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVF +RUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktL +S0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQ +UFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZW +VlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJC +QkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dH +SEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1N +TU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NT +U1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZ +WVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERE +RERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpK +SkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQ +UFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVV +VVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFB +QUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dH +R0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExM +TU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJS +UlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhY +WFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NE +RERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJ +SUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09P +T09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVV +VVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpa +WkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZG +RkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExM +TExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFR +UlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dX +V1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0ND +Q0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJ +SUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5O +Tk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRU +VFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpa +WlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVF +RUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tL +S0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFR +UVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZW +V1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJC +QkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhI +SEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1O +Tk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NT +U1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZ +WVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVF +RUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpK +SktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQ +UFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZW +VlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFB +QkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dH +R0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1N +TU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJT +U1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhY +WFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERE +RERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpK +SkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09P +T1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVV +VVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFB +QUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZG +R0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExM +TExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJS +UlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dY +WFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0ND +Q0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJ +SUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9P +T09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRU +VFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpa +WlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZG +RkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tL +TExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFR +UVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dX +V1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJD +Q0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhI +SEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5O +Tk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RU +VFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZ +WVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVF +RUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tL +S0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQ +UVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZW +VlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJC +QkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dI +SEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1N +TU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NT +U1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZ +WVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDRERERERERERE +REVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpK +SkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQ +UFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVV +VlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFB +QUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dH +R0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExN +TU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJS +UlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhY +WFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RE +RERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJ +SUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09P +T09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVV +VVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpa +QUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZG +RkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExM +TExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFS +UlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dX +V1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0ND +Q0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJ +SUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5O +Tk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRU +VFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpa +WlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVF +RkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tL +S0tLTExMTExMTExMTE1NTU1NTU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFR +UVFRUVFRUlJSUlJSUlJSUlNTU1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZX +V1dXV1dXV1dXWFhYWFhYWFhYWFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJC +QkJDQ0NDQ0NDQ0NDREREREREREREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhI +SEhISEhJSUlJSUlJSUlJSkpKSkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5O +Tk5OTk5OTk5PT09PT09PT09PUFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NT +U1RUVFRUVFRUVFRVVVVVVVVVVVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZ +WVlZWVpaWlpaWlpaWlpBQUFBQUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVF +RUVFRUVFRUZGRkZGRkZGRkZHR0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpK +S0tLS0tLS0tLS0xMTExMTExMTExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQ +UFBQUVFRUVFRUVFRUVJSUlJSUlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZW +VlZWVlZWV1dXV1dXV1dXV1hYWFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFC +QkJCQkJCQkJCQ0NDQ0NDQ0NDQ0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dH +R0dISEhISEhISEhISUlJSUlJSUlJSUpKSkpKSkpKSkpLS0tLS0tLS0tLTExMTExMTExMTE1NTU1N +TU1NTU1OTk5OTk5OTk5OT09PT09PT09PT1BQUFBQUFBQUFBRUVFRUVFRUVFRUlJSUlJSUlJSUlNT +U1NTU1NTU1NUVFRUVFRUVFRUVVVVVVVVVVVVVVZWVlZWVlZWVlZXV1dXV1dXV1dXWFhYWFhYWFhY +WFlZWVlZWVlZWVlaWlpaWlpaWlpaQUFBQUFBQUFBQUJCQkJCQkJCQkJDQ0NDQ0NDQ0NDRERERERE +REREREVFRUVFRUVFRUVGRkZGRkZGRkZGR0dHR0dHR0dHR0hISEhISEhISEhJSUlJSUlJSUlJSkpK +SkpKSkpKSktLS0tLS0tLS0tMTExMTExMTExMTU1NTU1NTU1NTU5OTk5OTk5OTk5PT09PT09PT09P +UFBQUFBQUFBQUFFRUVFRUVFRUVFSUlJSUlJSUlJSU1NTU1NTU1NTU1RUVFRUVFRUVFRVVVVVVVVV +VVVVVlZWVlZWVlZWVldXV1dXV1dXV1dYWFhYWFhYWFhYWVlZWVlZWVlZWVpaWlpaWlpaWlpBQUFB +QUFBQUFBQkJCQkJCQkJCQkNDQ0NDQ0NDQ0NERERERERERERERUVFRUVFRUVFRUZGRkZGRkZGRkZH +R0dHR0dHR0dHSEhISEhISEhISElJSUlJSUlJSUlKSkpKSkpKSkpKS0tLS0tLS0tLS0xMTExMTExM +TExNTU1NTU1NTU1NTk5OTk5OTk5OTk9PT09PT09PT09QUFBQUFBQUFBQUVFRUVFRUVFRUVJSUlJS +UlJSUlJTU1NTU1NTU1NTVFRUVFRUVFRUVFVVVVVVVVVVVVVWVlZWVlZWVlZWV1dXV1dXV1dXV1hY +WFhYWFhYWFhZWVlZWVlZWVlZWlpaWlpaWlpaWkFBQUFBQUFBQUFCQkJCQkJCQkJCQ0NDQ0NDQ0ND +Q0RERERERERERERFRUVFRUVFRUVFRkZGRkZGRkZGRkdHR0dHR0dHR0dISEhISEhISEhISUlJSUlJ +SUlJSUpKSkpKSkpKSko= +-------------------------------- +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test660 b/local-test-curl-delta-01/afc-curl/tests/data/test660 new file mode 100644 index 0000000000000000000000000000000000000000..8fdf879d9ad23ad9d76393db4075b6a1e725f74e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test660 @@ -0,0 +1,34 @@ + + + +IMAP +CONNECT_ONLY + + + +# Client-side + + +imap + + +lib597 + + +IMAP CONNECT_ONLY option + + + +imap://%HOSTIP:%IMAPPORT/%TESTNUMBER + + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test661 b/local-test-curl-delta-01/afc-curl/tests/data/test661 new file mode 100644 index 0000000000000000000000000000000000000000..799d51e2d5a95da4fc881a9827274068313ab0c3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test661 @@ -0,0 +1,76 @@ + + + +FTP + + + +# +# Server-side + + + + + +# Client-side + + +ftp + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +Avoid redundant CWDs + + +ftp://%HOSTIP:%FTPPORT/ + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +CWD /folderA +EPSV +TYPE I +RETR %TESTNUMBER +CWD /folderB +EPSV +RETR %TESTNUMBER +QUIT +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE I +RETR /folderA/%TESTNUMBER +CWD /folderB +EPSV +RETR %TESTNUMBER +EPSV +RETR /folderA/%TESTNUMBER +QUIT +USER anonymous +PASS ftp@example.com +PWD +SYST +QUIT +USER anonymous +PASS ftp@example.com +PWD +SYST +SYST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test670 b/local-test-curl-delta-01/afc-curl/tests/data/test670 new file mode 100644 index 0000000000000000000000000000000000000000..94910b5362b78923d4f2c4104126bda7e4ad5907 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test670 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP POST +MIME + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + + +# Client-side + + +Mime + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +Request pause from mime read callback: multi + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 154 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data; name="field" + +AB +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test671 b/local-test-curl-delta-01/afc-curl/tests/data/test671 new file mode 100644 index 0000000000000000000000000000000000000000..e49aacd51ae209e4a83ebb4fa45ff45b14562253 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test671 @@ -0,0 +1,75 @@ + + + +HTTP +HTTP POST +MIME + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Connection: close +Content-Type: text/html + +hello + + + +# Client-side + + +Mime + + +http + +# tool is what to use instead of 'curl' + +lib%TESTNUMBER + + + +Request pause from mime read callback: easy + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +s/^--------------------------[A-Za-z0-9]*/------------------------------/ +s/boundary=------------------------[A-Za-z0-9]*/boundary=----------------------------/ + + +POST /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 154 +Content-Type: multipart/form-data; boundary=---------------------------- + +------------------------------ +Content-Disposition: form-data; name="field" + +AB +-------------------------------- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test684 b/local-test-curl-delta-01/afc-curl/tests/data/test684 new file mode 100644 index 0000000000000000000000000000000000000000..a63424e2509cb55783961328df6fd9a843884cee --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test684 @@ -0,0 +1,52 @@ + + + +HTTP +netrc + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Fri, 05 Aug 2022 10:09:00 GMT +Server: test-server/fake +Content-Type: text/plain +Content-Length: 6 +Connection: close + +-foo- + + + +# +# Client-side + + +http + + +netrc with no login + + +--netrc-optional --netrc-file %LOGDIR/netrc%TESTNUMBER http://%HOSTIP:%HTTPPORT/ + + +machine %HOSTIP password 5up3r53cr37 + + + +# +# Verify data after the test has been "shot" + + +GET / HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic %b64[:5up3r53cr37]b64% +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test690 b/local-test-curl-delta-01/afc-curl/tests/data/test690 new file mode 100644 index 0000000000000000000000000000000000000000..6f333381c0e81cbd710846f89fa28a00c6cd1d22 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test690 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP GET + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +http + + +-O with URL without path using trailing slash + + +http://%HOSTIP:%HTTPPORT/ -O --output-dir %LOGDIR + + + +# +# Verify data after the test has been "shot" + + +GET / HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test70 b/local-test-curl-delta-01/afc-curl/tests/data/test70 new file mode 100644 index 0000000000000000000000000000000000000000..69cba7da47f72336af0fb2b256b00ef0e041b22d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test70 @@ -0,0 +1,85 @@ + + + +HTTP +HTTP GET +HTTP Digest auth +--anyauth + + +# Server-side + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604199" +WWW-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +This is not the real page + + +# This is supposed to be returned when the server gets a +# Authorization: Digest line passed-in from the client + +HTTP/1.1 200 OK +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 23 + +This IS the real page! + + + +HTTP/1.1 401 Authorization Required +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +WWW-Authenticate: Digest realm="testrealm", nonce="1053604199" +WWW-Authenticate: NTLM +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 26 + +HTTP/1.1 200 OK +Server: Apache/1.3.27 (Darwin) PHP/4.1.2 +Content-Type: text/html; charset=iso-8859-1 +Content-Length: 23 + +This IS the real page! + + + + +# Client-side + + +!SSPI +NTLM + + +http + + +HTTP with Digest *OR* NTLM authorization + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -u testuser:testpass --anyauth + + + +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Digest username="testuser", realm="testrealm", nonce="1053604199", uri="/%TESTNUMBER", response="2c9a6f00af0d86497b177b90e90c688a" +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test707 b/local-test-curl-delta-01/afc-curl/tests/data/test707 new file mode 100644 index 0000000000000000000000000000000000000000..f22b2010ee1206f2b3f1e59827c917da0a530cbe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test707 @@ -0,0 +1,63 @@ + +#based off test 100 + + +FTP +PASV +LIST +SOCKS5 + + +# +# Server-side + + +total 20 +drwxr-xr-x 8 98 98 512 Oct 22 13:06 . +drwxr-xr-x 8 98 98 512 Oct 22 13:06 .. +drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT +-r--r--r-- 1 0 1 35 Jul 16 1996 README +lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin +dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev +drwxrwxrwx 2 98 98 512 May 29 16:04 download.html +dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc +drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub +dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr + + + +# +# Client-side + + +proxy + + +ftp +socks5 + + +FTP dir list PASV via SOCKS5 + + +--socks5 %HOSTIP:%SOCKSPORT ftp://%HOSTIP:%FTPPORT/ + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE A +LIST +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test709 b/local-test-curl-delta-01/afc-curl/tests/data/test709 new file mode 100644 index 0000000000000000000000000000000000000000..656675395c7fda425a8d40843be24e0bec91ef5c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test709 @@ -0,0 +1,61 @@ + + + +HTTP +HTTP GET +SOCKS5 + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +proxy + + +http +socks5 + + +http_proxy=socks5://%HOSTIP:%SOCKSPORT + + +HTTP GET via SOCKS5 set in http_proxy environment variable + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test71 b/local-test-curl-delta-01/afc-curl/tests/data/test71 new file mode 100644 index 0000000000000000000000000000000000000000..f47879a3f7384b9f464a11474275034a1400a368 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test71 @@ -0,0 +1,81 @@ + + + +HTTP +HTTP FORMPOST +config file + + +# Server-side + + +HTTP/1.1 200 OK swsclose +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 11 + +blablabla + + + + +# Client-side + + +Mime + + +http + + +HTTP and -F upload in config file + + +-F name=daniel +-F tool=curl +-F file=@%LOGDIR/test%TESTNUMBER.txt +user-agent = "" + + +http://%HOSTIP:%HTTPPORT/we/want/%TESTNUMBER -K - + +# We create this file before the command is invoked! + +foo- +This is a moo- +bar + + + +# Verify data after the test has been "shot" + + +^(Content-Type: multipart/form-data;|------------).* + + +POST /we/want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Accept: */* +Content-Length: 432 +Content-Type: multipart/form-data; boundary=----------------------------9ef8d6205763 + +------------------------------9ef8d6205763 +Content-Disposition: form-data; name="name" + +daniel +------------------------------9ef8d6205763 +Content-Disposition: form-data; name="tool" + +curl +------------------------------9ef8d6205763 +Content-Disposition: form-data; name="file"; filename="test%TESTNUMBER.txt" +Content-Type: text/plain + +foo- +This is a moo- +bar + +------------------------------9ef8d6205763-- + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test710 b/local-test-curl-delta-01/afc-curl/tests/data/test710 new file mode 100644 index 0000000000000000000000000000000000000000..02033831b68b78d7cc87d2b588b57dac2397aae3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test710 @@ -0,0 +1,58 @@ + + + +HTTP +HTTP GET +SOCKS5 + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +# +# Client-side + + +proxy + + +http +socks5 + + +HTTP GET via SOCKS5 set with --proxy + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER --proxy socks5://%HOSTIP:%SOCKSPORT + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test713 b/local-test-curl-delta-01/afc-curl/tests/data/test713 new file mode 100644 index 0000000000000000000000000000000000000000..81374027fe71dc73b2f495e02cbdd8b1a5533563 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test713 @@ -0,0 +1,55 @@ + +#based off test 712 + + +FTP +PASV +RETR +SOCKS5 +CURLOPT_CONNECT_TO + + +# +# Server-side + + +silly content + + + +# +# Client-side + + +proxy + + +ftp +socks5 + + +FTP fetch with --proxy set to socks5:// and with --connect-to + + +ftp://ftp.example.com/%TESTNUMBER --connect-to ::%HOSTIP:%FTPPORT --proxy socks5://%HOSTIP:%SOCKSPORT + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +USER anonymous +PASS ftp@example.com +PWD +EPSV +TYPE I +SIZE %TESTNUMBER +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test718 b/local-test-curl-delta-01/afc-curl/tests/data/test718 new file mode 100644 index 0000000000000000000000000000000000000000..dcbf7d77a15cf54618f82abe9ae3214974fc0cf7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test718 @@ -0,0 +1,61 @@ + + + +HTTP +HTTP GET +HTTP CONNECT +HTTP proxy +proxytunnel +HTTP proxy Digest auth + + + +# Server-side + + +# this is returned first since we get no proxy-auth + +HTTP/1.1 407 Authorization Required to proxy me swsclose +Proxy-Authenticate: Digest realm="weirdorealm", nonce="12345" + + + + +HTTP/1.1 407 Authorization Required to proxy me swsclose +Proxy-Authenticate: Digest realm="weirdorealm", nonce="12345" + + + + +# Client-side + + +http + + +!SSPI +crypto +proxy + + +HTTP proxy CONNECT (no auth) with proxy returning 407 and closing + + +http://test.remote.haxx.se.%TESTNUMBER:8990/path/%TESTNUMBER0002 --proxy http://%HOSTIP:%HTTPPORT --proxytunnel + + + +# Verify data after the test has been "shot" + + +CONNECT test.remote.haxx.se.%TESTNUMBER:8990 HTTP/1.1 +Host: test.remote.haxx.se.%TESTNUMBER:8990 +User-Agent: curl/%VERSION +Proxy-Connection: Keep-Alive + + + +56 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test726 b/local-test-curl-delta-01/afc-curl/tests/data/test726 new file mode 100644 index 0000000000000000000000000000000000000000..f51adf594e63245acb67721f545738f6802c3b7c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test726 @@ -0,0 +1,40 @@ + + + +IPFS + + + +# +# Server-side + + + +# +# Client-side + + +http + + +# +# Set a home that doesn't have a ".ipfs" folder. %PWD should be good. +# This is to prevent the automatic gateway detection from finding a gateway file in your home folder. +HOME=%PWD + + +IPFS with no gateway URL (no environment or home file either) + + +ipfs://bafybeidecnvkrygux6uoukouzps5ofkeevoqland7kopseiod6pzqvjg7u + + + +# +# Verify with no gateway url and no auto detection + + +37 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test738 b/local-test-curl-delta-01/afc-curl/tests/data/test738 new file mode 100644 index 0000000000000000000000000000000000000000..5c05137dc3c9713c304a0820b91f2093290f9581 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test738 @@ -0,0 +1,37 @@ + + + +IPFS + + + +# +# Server-side + + + +# +# Client-side + + +http + + +IPFS_PATH=%LOGDIR/.ipfs/ + + +IPFS with IPFS_PATH, no gateway file + + +ipfs://bafybeidecnvkrygux6uoukouzps5ofkeevoqland7kopseiod6pzqvjg7u + + + +# +# Verify error code with no gateway file (detection fails) + + +37 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test740 b/local-test-curl-delta-01/afc-curl/tests/data/test740 new file mode 100644 index 0000000000000000000000000000000000000000..97258d3842b8cd67234ac8c7d06ac4fedae9db74 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test740 @@ -0,0 +1,60 @@ + + + +IPFS + + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 21 +Connection: close +Content-Type: text/plain +Funny-head: yesyes + +Hello curl from IPFS + + + +# +# Client-side + + +http + + +HOME=%PWD/%LOGDIR + + +IPFS with gateway URL from multiline gateway file + + +ipfs://bafybeidecnvkrygux6uoukouzps5ofkeevoqland7kopseiod6pzqvjg7u + + +http://%HOSTIP:%HTTPPORT +foo +bar + + + +# +# Verify data after the test has been "shot" + + +GET /ipfs/bafybeidecnvkrygux6uoukouzps5ofkeevoqland7kopseiod6pzqvjg7u HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test742 b/local-test-curl-delta-01/afc-curl/tests/data/test742 new file mode 100644 index 0000000000000000000000000000000000000000..34e284d18dabdb75b9d7759773d978f47358379e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test742 @@ -0,0 +1,66 @@ + + + +HTTP +SOCKS5 +all_proxy + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2000 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html +Funny-head: yesyes + +-foo- + +# method 2 is SOCKS5 asking for user+password + +method 2 +user aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +password bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +backendport %HTTPPORT + + + +# +# Client-side + + +socks5 +http + + +SOCKS5-hostname with max length credentials and max host name length + + +# target a port that won't work without the SOCKS magic + +http://cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:%HTTPPORT -x socks5h://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb@%HOSTIP:%SOCKSPORT + + +proxy + + + +# +# Verify data after the test has been "shot" + + +GET / HTTP/1.1 +Host: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test75 b/local-test-curl-delta-01/afc-curl/tests/data/test75 new file mode 100644 index 0000000000000000000000000000000000000000..dc8b49979fe3af2091a80b5149aa7d94dd37e6a5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test75 @@ -0,0 +1,44 @@ + + + +HTTP +HTTP GET +globbing +FAILURE + + +# +# Server-side + + + +# +# Client-side + + +none + + +http + + +HTTP, urlglob retrieval with bad range + + +"http://a-site-never-accessed.example.org/[2-1]" -o "%LOGDIR/weee#1.dump" --stderr - + + + +# +# Verify data after the test has been "shot" + + +3 + + +curl: (3) bad range in URL position 47: +http://a-site-never-accessed.example.org/[2-1] + ^ + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test77 b/local-test-curl-delta-01/afc-curl/tests/data/test77 new file mode 100644 index 0000000000000000000000000000000000000000..baa9bfc3607447d8a38352f641e1a54d3c71a81a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test77 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP GET +If-Modified-Since +-z + + +# +# Server-side + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Last-Modified: Tue, 13 Jun 2010 12:10:00 GMT +ETag: "21025-dc7-39462498" +Accept-Ranges: bytes +Content-Length: 6 +Connection: close +Content-Type: text/html + +-foo- + + + +# +# Client-side + + +http + + +HTTP with -z "older date" + + +http://%HOSTIP:%HTTPPORT/%TESTNUMBER -z "dec 12 12:00:00 1999 GMT" + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +User-Agent: curl/%VERSION +Accept: */* +If-Modified-Since: Sun, 12 Dec 1999 12:00:00 GMT + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test781 b/local-test-curl-delta-01/afc-curl/tests/data/test781 new file mode 100644 index 0000000000000000000000000000000000000000..4892415bf46b4b3c7cab7f186fd5a3e7fdf101c9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test781 @@ -0,0 +1,87 @@ + + + +HTTP +HTTP proxy +HSTS + + + + + +# we use this as response to a CONNECT + +HTTP/1.1 200 OK +Server: fake + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes +Strict-Transport-Security: max-age=1000 + + + + + + +http +http-proxy +https + + +HSTS +proxy +https +Debug +large-time + + + +CURL_HSTS_HTTP=yes +CURL_TIME=1728465947 + + + +.hsts.example "20991001 04:47:41" +this.hsts.example "99991001 04:47:41" + + + +HSTS update expiry, with parent includeSubDomains domain present + + +-x http://%HOSTIP:%PROXYPORT http://this.hsts.example:%HTTPSPORT/%TESTNUMBER --hsts %LOGDIR/input%TESTNUMBER -k + + +test-duphandle + + + + + + +HTTP/1.1 200 OK +Server: fake + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes +Strict-Transport-Security: max-age=1000 + + + + +# Your HSTS cache. https://curl.se/docs/hsts.html +# This file was generated by libcurl! Edit at your own risk. +.hsts.example "20991001 04:47:41" +this.hsts.example "20241009 09:42:27" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test783 b/local-test-curl-delta-01/afc-curl/tests/data/test783 new file mode 100644 index 0000000000000000000000000000000000000000..f12cc4507d5b1bf2501375fb8fcf3f0d8e7ae425 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test783 @@ -0,0 +1,87 @@ + + + +HTTP +HTTP proxy +HSTS + + + + + +# we use this as response to a CONNECT + +HTTP/1.1 200 OK +Server: fake + + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes +Strict-Transport-Security: max-age=1000; + + + + + + +http +http-proxy +https + + +HSTS +proxy +https +Debug +large-time + + + +CURL_HSTS_HTTP=yes +CURL_TIME=1728465947 + + + +.hsts.example "20991001 04:47:41" +.this.hsts.example "99991001 04:47:41" + + + +HSTS update expiry, removing includesubdomains in update + + +-x http://%HOSTIP:%PROXYPORT http://this.hsts.example:%HTTPSPORT/%TESTNUMBER --hsts %LOGDIR/input%TESTNUMBER -k + + +test-duphandle + + + + + + +HTTP/1.1 200 OK +Server: fake + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes +Strict-Transport-Security: max-age=1000; + + + + +# Your HSTS cache. https://curl.se/docs/hsts.html +# This file was generated by libcurl! Edit at your own risk. +.hsts.example "20991001 04:47:41" +this.hsts.example "20241009 09:42:27" + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test799 b/local-test-curl-delta-01/afc-curl/tests/data/test799 new file mode 100644 index 0000000000000000000000000000000000000000..e8563a598fe4afb78bf08838c8b7f6afe9cb5c5c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test799 @@ -0,0 +1,53 @@ + + + +IMAP +Clear Text +SASL AUTH +LOGIN + + + +# +# Server-side + + +AUTH PLAIN +REPLY LOGIN A002 OK LOGIN completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP with --login-options 'AUTH=+LOGIN' + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user:secret --login-options AUTH=+LOGIN + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN user secret +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test806 b/local-test-curl-delta-01/afc-curl/tests/data/test806 new file mode 100644 index 0000000000000000000000000000000000000000..adfbc11212cf9988e4bb122b9d570b0c9c34202c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test806 @@ -0,0 +1,44 @@ + + + +IMAP +Clear Text +LIST + + + +# +# Server-side + + +* LIST () "/" /%TESTNUMBER/blurdybloop +* LIST (\Noselect) "/" /%TESTNUMBER/foo +* LIST () "/" /%TESTNUMBER/foo/bar + + + +# +# Client-side + + +imap + + +IMAP LIST mailbox + + +imap://%HOSTIP:%IMAPPORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN user secret +A003 LIST "%TESTNUMBER" * +A004 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test811 b/local-test-curl-delta-01/afc-curl/tests/data/test811 new file mode 100644 index 0000000000000000000000000000000000000000..e2520c3319642e75c398c94ab75df76ccfde566f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test811 @@ -0,0 +1,40 @@ + + + +IMAP +Clear Text +CREATE +CUSTOMREQUEST + + + +# +# Server-side + + + +# +# Client-side + + +imap + + +IMAP CREATE mailbox (CUSTOMREQUEST) + + +imap://%HOSTIP:%IMAPPORT -u user:secret -X 'CREATE %TESTNUMBER' + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN user secret +A003 CREATE %TESTNUMBER +A004 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test819 b/local-test-curl-delta-01/afc-curl/tests/data/test819 new file mode 100644 index 0000000000000000000000000000000000000000..50ff2266912642de592def0032b1408df40c2be4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test819 @@ -0,0 +1,56 @@ + + + +IMAP +SASL +SASL AUTH PLAIN +RFC4616 + + + +# +# Server-side + + +AUTH PLAIN +REPLY AUTHENTICATE + +REPLY AHVzZXIAc2VjcmV0 A002 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP plain authentication + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user:secret + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE PLAIN +AHVzZXIAc2VjcmV0 +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test822 b/local-test-curl-delta-01/afc-curl/tests/data/test822 new file mode 100644 index 0000000000000000000000000000000000000000..61db77dc3c362c98c0f1420caec690fa766a709d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test822 @@ -0,0 +1,63 @@ + + + +IMAP +SASL +SASL AUTH NTLM +NTLM + + + +# +# Server-side + + +AUTH NTLM +REPLY AUTHENTICATE + +REPLY TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= + TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +REPLY TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= A002 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +NTLM +SSL +!SSPI + + +IMAP NTLM authentication + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u testuser:testpass + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE NTLM +TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test828 b/local-test-curl-delta-01/afc-curl/tests/data/test828 new file mode 100644 index 0000000000000000000000000000000000000000..a3548464e88129da23cd9532e5282416ae1fb17a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test828 @@ -0,0 +1,56 @@ + + + +IMAP +SASL +SASL AUTH OAUTH2 +SASL-IR +RFC6749 + + + +# +# Server-side + + +AUTH XOAUTH2 +CAPA SASL-IR +REPLY AUTHENTICATE A002 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP OAuth 2.0 (XOAUTH2) authentication with initial response + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user --oauth2-bearer mF_9.B5f-4.1JqM + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG1GXzkuQjVmLTQuMUpxTQEB +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test835 b/local-test-curl-delta-01/afc-curl/tests/data/test835 new file mode 100644 index 0000000000000000000000000000000000000000..17c8675eb2af72d3b5b4fee0ce5e7747bdd6a46a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test835 @@ -0,0 +1,67 @@ + + + +IMAP +SASL +SASL AUTH DIGEST-MD5 +SASL AUTH PLAIN +SASL DOWNGRADE +RFC2831 + + + +# +# Server-side + + +AUTH DIGEST-MD5 PLAIN +REPLY "AUTHENTICATE DIGEST-MD5" + Rubbish +REPLY * A002 NO AUTH exchange cancelled by client +REPLY "AUTHENTICATE PLAIN" + +REPLY AHVzZXIAc2VjcmV0 A003 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +!SSPI +Debug +crypto + + +IMAP DIGEST-MD5 authentication with SASL downgrade + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user:secret + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE DIGEST-MD5 +* +A003 AUTHENTICATE PLAIN +AHVzZXIAc2VjcmV0 +A004 SELECT %TESTNUMBER +A005 FETCH 1 BODY[] +A006 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test836 b/local-test-curl-delta-01/afc-curl/tests/data/test836 new file mode 100644 index 0000000000000000000000000000000000000000..821d5392bb8c063481a03256aeb43e11b29c5ff9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test836 @@ -0,0 +1,59 @@ + + + +IMAP +Clear Text +FETCH +connection reuse + + + +# +# Server-side + + +REPLY "LOGIN user.one secret" A002 OK LOGIN completed +REPLY "LOGIN user.two secret" B002 OK LOGIN completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP multiple connection authentication + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user.one:secret -: 'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;UID=2' -u user.two:secret + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN user.one secret +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT +B001 CAPABILITY +B002 LOGIN user.two secret +B003 SELECT %TESTNUMBER +B004 FETCH 2 BODY[] +B005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test84 b/local-test-curl-delta-01/afc-curl/tests/data/test84 new file mode 100644 index 0000000000000000000000000000000000000000..3b842eaffe8398a3956a8020eca9204a1667f53f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test84 @@ -0,0 +1,54 @@ + + + +HTTP +HTTP GET +HTTP Basic auth +HTTP proxy + + +# +# Server-side + + +HTTP/1.0 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake swsclose +Content-Type: text/html +Funny-head: yesyes + +contents + + + +# +# Client-side + + +http + + +HTTP over proxy with site authentication + + +http://%HOSTIP:%HTTPPORT/we/want/that/page/%TESTNUMBER -x %HOSTIP:%HTTPPORT --user iam:myself + + +proxy + + + +# +# Verify data after the test has been "shot" + + +GET http://%HOSTIP:%HTTPPORT/we/want/that/page/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic aWFtOm15c2VsZg== +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test841 b/local-test-curl-delta-01/afc-curl/tests/data/test841 new file mode 100644 index 0000000000000000000000000000000000000000..cc1d075fbc3f05ad835bdd06ef0a57e48b9bc719 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test841 @@ -0,0 +1,51 @@ + + + +IMAP +Clear Text +FETCH +CUSTOMREQUEST + + + +# +# Server-side + + +body + ++ Curl did not used to like this line +-- + yours sincerely + + +* 123 FETCH (BODY[1] {70} + + + +# +# Client-side + + +imap + + +IMAP custom request doesn't check continuation data + + + imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/ -u user:secret -X 'FETCH 123 BODY[1]' + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN user secret +A003 SELECT %TESTNUMBER +A004 FETCH 123 BODY[1] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test842 b/local-test-curl-delta-01/afc-curl/tests/data/test842 new file mode 100644 index 0000000000000000000000000000000000000000..1cea6e39d35fb4721877b85f90636500af50d23f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test842 @@ -0,0 +1,59 @@ + + + +IMAP +SASL +SASL AUTH OAUTH2 +RFC6749 +RFC7628 + + + +# +# Server-side + + +AUTH OAUTHBEARER +REPLY AUTHENTICATE + +REPLY %b64[n,a=user,%01host=127.0.0.1%01port=%IMAPPORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% A002 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP OAuth 2.0 (OAUTHBEARER) authentication + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user --oauth2-bearer mF_9.B5f-4.1JqM + +# The protocol section doesn't support ways of specifying the raw data in the +# base64 encoded message so we must assert this + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE OAUTHBEARER +%b64[n,a=user,%01host=127.0.0.1%01port=%IMAPPORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test843 b/local-test-curl-delta-01/afc-curl/tests/data/test843 new file mode 100644 index 0000000000000000000000000000000000000000..774c4c5e74b4f8b33466cfdf19cf1a9c00aae587 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test843 @@ -0,0 +1,57 @@ + + + +IMAP +SASL +SASL AUTH OAUTH2 +SASL-IR +RFC6749 +RFC7628 + + + +# +# Server-side + + +AUTH OAUTHBEARER +CAPA SASL-IR +REPLY AUTHENTICATE A002 OK AUTHENTICATE completed + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP OAuth 2.0 (OAUTHBEARER) authentication with initial response + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;MAILINDEX=1' -u user --oauth2-bearer mF_9.B5f-4.1JqM + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 AUTHENTICATE OAUTHBEARER %b64[n,a=user,%01host=127.0.0.1%01port=%IMAPPORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test847 b/local-test-curl-delta-01/afc-curl/tests/data/test847 new file mode 100644 index 0000000000000000000000000000000000000000..6972f45fb129a352c0e3952007b123719946c1f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test847 @@ -0,0 +1,49 @@ + + + +IMAP +Clear Text +FETCH + + + +# +# Server-side + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imap + + +IMAP FETCH message + + +'imap://%HOSTIP:%IMAPPORT/%TESTNUMBER/;UID=1' -u '"user:sec"ret{' + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN "\"user" "sec\"ret{" +A003 SELECT %TESTNUMBER +A004 UID FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test852 b/local-test-curl-delta-01/afc-curl/tests/data/test852 new file mode 100644 index 0000000000000000000000000000000000000000..ed433862bfbe58e03a263f674d6b64b79859dcba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test852 @@ -0,0 +1,47 @@ + + + +POP3 +Clear Text +LIST +FAILURE + + + +# +# Server-side + + +REPLY LIST -ERR no such message + + + +# +# Client-side + + +pop3 + + +POP3 LIST invalid message + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -l -u user:secret + + + +# +# Verify data after the test has been "shot" + + +8 + + +CAPA +USER user +PASS secret +LIST %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test857 b/local-test-curl-delta-01/afc-curl/tests/data/test857 new file mode 100644 index 0000000000000000000000000000000000000000..5868a2d57ffdaf9d601653c20173137c2e665722 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test857 @@ -0,0 +1,60 @@ + + + +POP3 +Clear Text +RETR + + + +# +# Server-side + + +From: me@somewhere +To: fake@nowhere + +..body with a single dot first +...triple dots... + +-- + yours sincerely + + +From: me@somewhere +To: fake@nowhere + +.body with a single dot first +..triple dots... + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +POP3 RETR message with dot-prefixed line + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + + +CAPA +USER user +PASS secret +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test860 b/local-test-curl-delta-01/afc-curl/tests/data/test860 new file mode 100644 index 0000000000000000000000000000000000000000..5e1f3f611b2712abd14df48a4d11cb09467243c6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test860 @@ -0,0 +1,41 @@ + + + +POP3 +Clear Text +NOOP +CUSTOMREQUEST + + + +# +# Server-side + + + +# +# Client-side + + +pop3 + + +POP3 NOOP (CUSTOMREQUEST) + + +pop3://%HOSTIP:%POP3PORT -u user:secret -X NOOP -I + + + +# +# Verify data after the test has been "shot" + + +CAPA +USER user +PASS secret +NOOP +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test864 b/local-test-curl-delta-01/afc-curl/tests/data/test864 new file mode 100644 index 0000000000000000000000000000000000000000..4f40a52ab0291c0f01607d37cdd50456361dc77b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test864 @@ -0,0 +1,54 @@ + + + +POP3 +APOP + + + +# +# Server-side + + +CAPA APOP +REPLY welcome +OK curl POP3 server ready to serve <1972.987654321\@curl> + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +crypto + + +POP3 APOP authentication + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + + +CAPA +APOP user 7501b4cdc224d469940e65e7b5e4d6eb +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test865 b/local-test-curl-delta-01/afc-curl/tests/data/test865 new file mode 100644 index 0000000000000000000000000000000000000000..59bf1c154b5b44f88a364baeaabafc47dde5810d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test865 @@ -0,0 +1,57 @@ + + + +POP3 +SASL +SASL AUTH PLAIN +RFC1734 +RFC4616 +RFC5034 + + + +# +# Server-side + + +AUTH PLAIN +REPLY AUTH + +REPLY AHVzZXIAc2VjcmV0 +OK Login successful + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +POP3 plain authentication + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + + +CAPA +AUTH PLAIN +AHVzZXIAc2VjcmV0 +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test868 b/local-test-curl-delta-01/afc-curl/tests/data/test868 new file mode 100644 index 0000000000000000000000000000000000000000..6807fa56f170ab73b880dc5af1928b311c1488f5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test868 @@ -0,0 +1,64 @@ + + + +POP3 +SASL +SASL AUTH NTLM +RFC1734 +RFC5034 +NTLM + + + +# +# Server-side + + +AUTH NTLM +REPLY AUTH + +REPLY TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= + TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +REPLY TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +OK Login successful + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +NTLM +SSL +!SSPI + + +POP3 NTLM authentication + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u testuser:testpass + + + +# +# Verify data after the test has been "shot" + + +CAPA +AUTH NTLM +TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test871 b/local-test-curl-delta-01/afc-curl/tests/data/test871 new file mode 100644 index 0000000000000000000000000000000000000000..38335177d4d5b989b5e6b222222a1451754b4ee6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test871 @@ -0,0 +1,56 @@ + + + +POP3 +SASL +SASL AUTH PLAIN +SASL-IR +RFC1734 +RFC4616 +RFC5034 + + + +# +# Server-side + + +AUTH PLAIN +REPLY AUTH +OK Login successful + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +POP3 plain authentication with initial response + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret --sasl-ir + + + +# +# Verify data after the test has been "shot" + + +CAPA +AUTH PLAIN AHVzZXIAc2VjcmV0 +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test876 b/local-test-curl-delta-01/afc-curl/tests/data/test876 new file mode 100644 index 0000000000000000000000000000000000000000..a34b97a9d3e80496a941c9e90279f56c0513f8ce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test876 @@ -0,0 +1,57 @@ + + + +POP3 +SASL +SASL AUTH CRAM-MD5 +SASL CANCELLATION +RFC1734 +RFC2195 +RFC5034 + + + +# +# Server-side + + +AUTH CRAM-MD5 +REPLY AUTH + Rubbish +REPLY * -ERR AUTH exchange cancelled by client + + + +# +# Client-side + + +pop3 + + +crypto + + +POP3 CRAM-MD5 graceful cancellation + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + +# 67 - CURLE_LOGIN_DENIED + +67 + +# +# The multi interface considers a broken "CONNECT" as a prematurely broken +# transfer and such a connection will not get a "QUIT" + +CAPA +AUTH CRAM-MD5 +* + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test882 b/local-test-curl-delta-01/afc-curl/tests/data/test882 new file mode 100644 index 0000000000000000000000000000000000000000..b4fa465340b8bbb6a532740691017eac3b3cf621 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test882 @@ -0,0 +1,58 @@ + + + +POP3 +Clear Text +RETR +connection reuse + + + +# +# Server-side + + +REPLY "PASS secret" +OK Login successful + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +POP3 multiple connection authentication + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER001 -u user.one:secret -: pop3://%HOSTIP:%POP3PORT/%TESTNUMBER002 -u user.two:secret + + + +# +# Verify data after the test has been "shot" + + +CAPA +USER user.one +PASS secret +RETR %TESTNUMBER001 +QUIT +CAPA +USER user.two +PASS secret +RETR %TESTNUMBER002 +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test887 b/local-test-curl-delta-01/afc-curl/tests/data/test887 new file mode 100644 index 0000000000000000000000000000000000000000..ada1ce1a6b001e4acd509bf3b13a8e0b1fb87e10 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test887 @@ -0,0 +1,58 @@ + + + +POP3 +SASL +SASL AUTH OAUTH2 +RFC1734 +RFC5034 +RFC6749 +RFC7628 + + + +# +# Server-side + + +AUTH OAUTHBEARER +REPLY AUTH + +REPLY %b64[n,a=user,%01host=127.0.0.1%01port=%POP3PORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +OK Login successful + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +pop3 + + +POP3 OAuth 2.0 (OAUTHBEARER) authentication + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user --oauth2-bearer mF_9.B5f-4.1JqM + + + +# +# Verify data after the test has been "shot" + + +CAPA +AUTH OAUTHBEARER +%b64[n,a=user,%01host=127.0.0.1%01port=%POP3PORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +RETR %TESTNUMBER +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test891 b/local-test-curl-delta-01/afc-curl/tests/data/test891 new file mode 100644 index 0000000000000000000000000000000000000000..f022db96a70a2a173ab18d862aa2e4722e52d21b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test891 @@ -0,0 +1,47 @@ + + + +POP3 + + + +# +# Server-side + + +AUTH CRAM-MD5 +REPLYLF AUTH + + + + +# +# Client-side + + +pop3 + + +crypto + + +POP3 with short authentication response + + +pop3://%HOSTIP:%POP3PORT/%TESTNUMBER -u user:secret + + + +# +# Verify data after the test has been "shot" + + +CAPA +AUTH CRAM-MD5 +dXNlciA1YzhkYjAzZjA0Y2VjMGY0M2JjYjA2MDAyMzkxNDE5MA== + +# CURLE_LOGIN_DENIED + +67 + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test899 b/local-test-curl-delta-01/afc-curl/tests/data/test899 new file mode 100644 index 0000000000000000000000000000000000000000..d1f1936fc0c9729376db2a39f05a185dd502b823 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test899 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP GET +Basic + + + +# +# Server-side + + +HTTP/1.1 302 go go go +Content-Length: 8 +Location: http://user:pass@%HOSTIP:%HTTPPORT/basic-auth/user/%TESTNUMBER0002 +Content-Type: text/html +Funny-head: yesyes + +notreal + + +HTTP/1.1 200 OK +Content-Length: 6 +Content-Type: text/html +Funny-head: yesyes + +final + + + +# +# Client-side + + +http + + +URL with credentials redirects to URL with different credentials + + +http://first:secret@%HOSTIP:%HTTPPORT/%TESTNUMBER -L + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic Zmlyc3Q6c2VjcmV0 +User-Agent: curl/%VERSION +Accept: */* + +GET /basic-auth/user/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic dXNlcjpwYXNz +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test900 b/local-test-curl-delta-01/afc-curl/tests/data/test900 new file mode 100644 index 0000000000000000000000000000000000000000..371544b7657adb60c3799e3cd34871e2d7751dfe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test900 @@ -0,0 +1,51 @@ + + + +SMTP + + + +# +# Server-side + + + +# +# Client-side + + +smtp + + +SMTP + + +From: different +To: another + +body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +MAIL FROM: +RCPT TO: +DATA +QUIT + + +From: different +To: another + +body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test901 b/local-test-curl-delta-01/afc-curl/tests/data/test901 new file mode 100644 index 0000000000000000000000000000000000000000..a97233d871661d28853ea19e33f0e1302d4f6f5e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test901 @@ -0,0 +1,63 @@ + + + +SMTP + + + +# +# Server-side + + + +# +# Client-side + + +smtp + + +SMTP with CRLF-dot-CRLF in data + + +From: different +To: another + + +. +. + +. + +body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +MAIL FROM: +RCPT TO: +DATA +QUIT + + +From: different +To: another + + +.. +.. + +.. + +body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test902 b/local-test-curl-delta-01/afc-curl/tests/data/test902 new file mode 100644 index 0000000000000000000000000000000000000000..961fc7bfbf82e0ade18ec0721e34ccbe656e7159 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test902 @@ -0,0 +1,57 @@ + + + +SMTP +SMTP HELO +RFC821 + + + +# +# Server-side + + +REPLY EHLO 500 Command unrecognized + + + +# +# Client-side + + +smtp + + +RFC821-only SMTP server (EHLO not supported) + + +From: different +To: another + +body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +HELO %TESTNUMBER +MAIL FROM: +RCPT TO: +DATA +QUIT + + +From: different +To: another + +body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test906 b/local-test-curl-delta-01/afc-curl/tests/data/test906 new file mode 100644 index 0000000000000000000000000000000000000000..863dce698c7b8ff40e5c2cbdebeb0757020656f6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test906 @@ -0,0 +1,63 @@ + + + +SMTP +SASL +SASL AUTH NTLM +RFC4954 +NTLM + + + +# +# Server-side + + +AUTH NTLM +REPLY AUTH 334 NTLM supported +REPLY TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= 334 TlRMTVNTUAACAAAAAgACADAAAACGggEAc51AYVDgyNcAAAAAAAAAAG4AbgAyAAAAQ0MCAAQAQwBDAAEAEgBFAEwASQBTAEEAQgBFAFQASAAEABgAYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAwAsAGUAbABpAHMAYQBiAGUAdABoAC4AYwBjAC4AaQBjAGUAZABlAHYALgBuAHUAAAAAAA== +REPLY TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= 235 Authenticated + + + +# +# Client-side + + +smtp + + +NTLM +SSL +!SSPI + + +SMTP NTLM authentication + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u testuser:testpass -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH NTLM +TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +TlRMTVNTUAADAAAAGAAYAEAAAAAYABgAWAAAAAAAAABwAAAACAAIAHAAAAALAAsAeAAAAAAAAAAAAAAAhoIBAFpkQwKRCZFMhjj0tw47wEjKHRHlvzfxQamFcheMuv8v+xeqphEO5V41xRd7R9deOXRlc3R1c2VyV09SS1NUQVRJT04= +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test919 b/local-test-curl-delta-01/afc-curl/tests/data/test919 new file mode 100644 index 0000000000000000000000000000000000000000..833a67c97b50e3098f4b6d92c533bc6a73c48cae --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test919 @@ -0,0 +1,55 @@ + + + +SMTP +SASL +SASL AUTH PLAIN +SASL-IR +RFC4616 +RFC4954 + + + +# +# Server-side + + +AUTH PLAIN +REPLY AUTH 235 Authenticated + + + +# +# Client-side + + +smtp + + +SMTP plain authentication with initial response + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user:secret --sasl-ir -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH PLAIN AHVzZXIAc2VjcmV0 +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test92 b/local-test-curl-delta-01/afc-curl/tests/data/test92 new file mode 100644 index 0000000000000000000000000000000000000000..f6250d19625341de27a7565e6f4c2874090415a9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test92 @@ -0,0 +1,67 @@ + + + +HTTP +HTTP GET +Content-Range +Resume + + + +# Server-side + + +HTTP/1.1 416 Requested Range Not Satisfiable +Date: Fri, 24 Oct 2003 21:33:12 GMT +Server: Apache/1.3.19 (Unix) (Red-Hat/Linux) mod_ssl/2.8.1 OpenSSL/0.9.6 PHP/4.3.1 +Last-Modified: Fri, 24 Oct 2003 18:01:23 GMT +ETag: "ab57a-507-3f9968f3" +Accept-Ranges: bytes +Content-Length: 4 +Content-Range: bytes */87 +Content-Type: image/gif + +bad + + +# The body should be ignored. + +HTTP/1.1 416 Requested Range Not Satisfiable +Date: Fri, 24 Oct 2003 21:33:12 GMT +Server: Apache/1.3.19 (Unix) (Red-Hat/Linux) mod_ssl/2.8.1 OpenSSL/0.9.6 PHP/4.3.1 +Last-Modified: Fri, 24 Oct 2003 18:01:23 GMT +ETag: "ab57a-507-3f9968f3" +Accept-Ranges: bytes +Content-Length: 4 +Content-Range: bytes */87 +Content-Type: image/gif + + + + +# Client-side + + +http + + +HTTP resume transfer with the whole file already downloaded + + +http://%HOSTIP:%HTTPPORT/want/%TESTNUMBER -C 87 + + + +# Verify data after the test has been "shot" + + +GET /want/%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Range: bytes=87- +User-Agent: curl/%VERSION +Accept: */* + + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test923 b/local-test-curl-delta-01/afc-curl/tests/data/test923 new file mode 100644 index 0000000000000000000000000000000000000000..19cdd9667e1fb2f38ea8fd25476e81e27071c83a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test923 @@ -0,0 +1,37 @@ + + + +SMTP +VRFY + + + +# +# Server-side + + + +# +# Client-side + + +smtp + + +SMTP VRFY + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +VRFY recipient +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test935 b/local-test-curl-delta-01/afc-curl/tests/data/test935 new file mode 100644 index 0000000000000000000000000000000000000000..bbd4d9475771e30f93d901eba27f9cebebdfac8a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test935 @@ -0,0 +1,65 @@ + + + +SMTP +SASL +SASL AUTH CRAM-MD5 +SASL AUTH PLAIN +SASL DOWNGRADE +RFC2195 +RFC4954 + + + +# +# Server-side + + +AUTH CRAM-MD5 PLAIN +REPLY "AUTH CRAM-MD5" 334 Rubbish +REPLY * 501 AUTH exchange cancelled by client +REPLY "AUTH PLAIN" 334 PLAIN supported +REPLY AHVzZXIAc2VjcmV0 235 Authenticated + + + +# +# Client-side + + +smtp + + +crypto + + +SMTP CRAM-MD5 authentication with SASL downgrade + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user:secret -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH CRAM-MD5 +* +AUTH PLAIN +AHVzZXIAc2VjcmV0 +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test936 b/local-test-curl-delta-01/afc-curl/tests/data/test936 new file mode 100644 index 0000000000000000000000000000000000000000..723cebca37bb2675c15493c6fc08acf0eba8b321 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test936 @@ -0,0 +1,68 @@ + + + +SMTP +SASL +SASL AUTH NTLM +SASL AUTH PLAIN +SASL DOWNGRADE +RFC4954 + + + +# +# Server-side + + +AUTH NTLM PLAIN +REPLY "AUTH NTLM" 334 NTLM supported +REPLY TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= 334 Rubbish +REPLY * 501 AUTH exchange cancelled by client +REPLY "AUTH PLAIN" 334 PLAIN supported +REPLY AHVzZXIAc2VjcmV0 235 Authenticated + + + +# +# Client-side + + +smtp + + +NTLM +SSL +!SSPI + + +SMTP NTLM authentication with SASL downgrade + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user:secret -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH NTLM +TlRMTVNTUAABAAAABoIIAAAAAAAAAAAAAAAAAAAAAAA= +* +AUTH PLAIN +AHVzZXIAc2VjcmV0 +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test947 b/local-test-curl-delta-01/afc-curl/tests/data/test947 new file mode 100644 index 0000000000000000000000000000000000000000..5ca2be671462aa4b5acbe0f8c1557737b423edce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test947 @@ -0,0 +1,56 @@ + + + +SMTP +SASL +SASL AUTH OAUTH2 +SASL-IR +RFC4954 +RFC6749 +RFC7628 + + + +# +# Server-side + + +AUTH OAUTHBEARER +REPLY AUTH 235 Authenticated + + + +# +# Client-side + + +smtp + + +SMTP OAuth 2.0 (OAUTHBEARER) authentication with initial response + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user --oauth2-bearer mF_9.B5f-4.1JqM --sasl-ir -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH OAUTHBEARER %b64[n,a=user,%01host=127.0.0.1%01port=%SMTPPORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test949 b/local-test-curl-delta-01/afc-curl/tests/data/test949 new file mode 100644 index 0000000000000000000000000000000000000000..136baf4efa00a30d324ed2e92c8a592812fac67c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test949 @@ -0,0 +1,57 @@ + + + +SMTP +SASL +SASL AUTH OAUTH2 +SASL-IR +RFC4954 +RFC6749 +RFC7628 + + + +# +# Server-side + + +AUTH OAUTHBEARER +REPLY AUTH 334 eyJzdGF0dXMiOiJpbnZhbGlkX3Rva2VuIiwic2NvcGUiOiJleGFtcGxlX3Njb3BlIiwib3BlbmlkLWNvbmZpZ3VyYXRpb24iOiJodHRwczovL2V4YW1wbGUuY29tLy53ZWxsLWtub3duL29wZW5pZC1jb25maWd1cmF0aW9uIn0 +REPLY AQ== 535 Username and Password not accepted. Learn more at\r\n535 http://support.example.com/mail/oauth + + + +# +# Client-side + + +smtp + + +SMTP OAuth 2.0 (OAUTHBEARER) failure as continuation with initial response + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user --oauth2-bearer mF_9.B5f-4.1JqM --sasl-ir -T - + + + +# +# Verify data after the test has been "shot" + +# 67 - CURLE_LOGIN_DENIED + +67 + +# +# The multi interface considers a broken "CONNECT" as a prematurely broken +# transfer and such a connection will not get a "QUIT" + +EHLO %TESTNUMBER +AUTH OAUTHBEARER %b64[n,a=user,%01host=127.0.0.1%01port=%SMTPPORT%01auth=Bearer mF_9.B5f-4.1JqM%01%01]b64% +AQ== + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test968 b/local-test-curl-delta-01/afc-curl/tests/data/test968 new file mode 100644 index 0000000000000000000000000000000000000000..b057be62917c63c7b94331ec38122e7db5e892ad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test968 @@ -0,0 +1,50 @@ + + + +SMTP +VRFY +IDN + + + +# +# Server-side + + +CAPA SMTPUTF8 + + + +# +# Client-side + + +smtp + + +IDN +!win32 +codeset-utf8 + + +LC_ALL=en_US.UTF-8 +LC_CTYPE=en_US.UTF-8 + + +SMTP VRFY with SMTPUTF8 support + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt Användaren + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +VRFY Användaren SMTPUTF8 +QUIT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test979 b/local-test-curl-delta-01/afc-curl/tests/data/test979 new file mode 100644 index 0000000000000000000000000000000000000000..40cc35044d9f6d484c75598444d9fe0325713c8c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test979 @@ -0,0 +1,64 @@ + + + +HTTP +HTTP GET +Basic + + + +# +# Server-side + + +HTTP/1.1 302 go go go +Content-Length: 8 +Location: http://%HOSTIP:%HTTPPORT/user/%TESTNUMBER0002 +Content-Type: text/html +Funny-head: yesyes + +notreal + + +HTTP/1.1 200 OK +Content-Length: 6 +Content-Type: text/html +Funny-head: yesyes + +final + + + +# +# Client-side + + +http + + +-u with redirect to absolute URL using same origin and auth + + +http://first:secret@%HOSTIP:%HTTPPORT/%TESTNUMBER -L -u smith:doggie + + + +# +# Verify data after the test has been "shot" + + +GET /%TESTNUMBER HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic c21pdGg6ZG9nZ2ll +User-Agent: curl/%VERSION +Accept: */* + +GET /user/%TESTNUMBER0002 HTTP/1.1 +Host: %HOSTIP:%HTTPPORT +Authorization: Basic c21pdGg6ZG9nZ2ll +User-Agent: curl/%VERSION +Accept: */* + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test980 b/local-test-curl-delta-01/afc-curl/tests/data/test980 new file mode 100644 index 0000000000000000000000000000000000000000..5811b437d4115dd3f7e26b599fd0f05859c3775f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test980 @@ -0,0 +1,52 @@ + + + +SMTP +STARTTLS + + + +# +# Server-side + + +CAPA STARTTLS +AUTH PLAIN +REPLY STARTTLS 454 currently unavailable\r\n235 Authenticated\r\n250 2.1.0 Sender ok\r\n250 2.1.5 Recipient ok\r\n354 Enter mail\r\n250 2.0.0 Accepted +REPLY AUTH 535 5.7.8 Authentication credentials invalid + + + +# +# Client-side + + +SSL + + +smtp + + +SMTP STARTTLS pipelined server response + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user:secret --ssl --sasl-ir -T - + + + +# +# Verify data after the test has been "shot" + +# 8 is CURLE_WEIRD_SERVER_REPLY + +8 + + +EHLO %TESTNUMBER +STARTTLS + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test984 b/local-test-curl-delta-01/afc-curl/tests/data/test984 new file mode 100644 index 0000000000000000000000000000000000000000..314a24e6cb5a101bd9343cb435850f767f5159c8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test984 @@ -0,0 +1,56 @@ + + + +IMAP +STARTTLS + + + +# +# Server-side + + +REPLY CAPABILITY A001 BAD Not implemented + + + +# +# Client-side + + +SSL + + +imap + + +IMAP require STARTTLS with failing capabilities + + +imap://%HOSTIP:%IMAPPORT/%TESTNUMBER -T %LOGDIR/upload%TESTNUMBER -u user:secret --ssl-reqd + + +Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST) +From: Fred Foobar +Subject: afternoon meeting +To: joe@example.com +Message-Id: +MIME-Version: 1.0 +Content-Type: TEXT/PLAIN; CHARSET=US-ASCII + +Hello Joe, do you think we can meet at 3:30 tomorrow? + + + +# +# Verify data after the test has been "shot" + +# 64 is CURLE_USE_SSL_FAILED + +64 + + +A001 CAPABILITY + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test987 b/local-test-curl-delta-01/afc-curl/tests/data/test987 new file mode 100644 index 0000000000000000000000000000000000000000..bf926b7fe25b8f56671bdfff8f1a03112079fd07 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test987 @@ -0,0 +1,51 @@ + + + +SMTPS + + + +# +# Server-side + + + +# +# Client-side + + +smtps + + +SMTPS with redundant explicit SSL request + + +From: different +To: another + +body + + +-k --ssl-reqd --mail-rcpt recipient@example.com --mail-from sender@example.com -T - smtps://%HOSTIP:%SMTPSPORT/%TESTNUMBER + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +MAIL FROM: +RCPT TO: +DATA +QUIT + + +From: different +To: another + +body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test988 b/local-test-curl-delta-01/afc-curl/tests/data/test988 new file mode 100644 index 0000000000000000000000000000000000000000..31e1c8711b62a021e42f27368278da35487a7271 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test988 @@ -0,0 +1,48 @@ + + + +IMAPS +FETCH + + + +# +# Server-side + + +From: me@somewhere +To: fake@nowhere + +body + +-- + yours sincerely + + + +# +# Client-side + + +imaps + + +IMAPS FETCH with redundant explicit SSL request + + +-k --ssl-reqd -u '"user:sec"ret{' 'imaps://%HOSTIP:%IMAPSPORT/%TESTNUMBER/;MAILINDEX=1' + + + +# +# Verify data after the test has been "shot" + + +A001 CAPABILITY +A002 LOGIN "\"user" "sec\"ret{" +A003 SELECT %TESTNUMBER +A004 FETCH 1 BODY[] +A005 LOGOUT + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test992 b/local-test-curl-delta-01/afc-curl/tests/data/test992 new file mode 100644 index 0000000000000000000000000000000000000000..dad0aa51a5fbaad09f3a45360d227b34377f4f99 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test992 @@ -0,0 +1,52 @@ + + + +SASL + + + +# +# Server-side + + +AUTH OAUTHBEARER XOAUTH2 +REPLY AUTH 334 XOAUTH2 supported +REPLY dXNlcj11c2VyAWF1dGg9QmVhcmVyIG1GXzkuQjVmLTQuMUpxTQEB 235 Authenticated + + + +# +# Client-side + + +smtp + + +SASL verify default mechanisms are reset by login options + + +mail body + + +smtp://%HOSTIP:%SMTPPORT/%TESTNUMBER --mail-rcpt recipient@example.com --mail-from sender@example.com -u user --oauth2-bearer mF_9.B5f-4.1JqM --login-options "AUTH=XOAUTH2" -T - + + + +# +# Verify data after the test has been "shot" + + +EHLO %TESTNUMBER +AUTH XOAUTH2 +dXNlcj11c2VyAWF1dGg9QmVhcmVyIG1GXzkuQjVmLTQuMUpxTQEB +MAIL FROM: +RCPT TO: +DATA +QUIT + + +mail body +. + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test994 b/local-test-curl-delta-01/afc-curl/tests/data/test994 new file mode 100644 index 0000000000000000000000000000000000000000..e19d8c01082bb6a8781f77fc4d9f677e19a9ac2c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test994 @@ -0,0 +1,42 @@ + + + +HTTP +HTTP GET + + + +# +# Server-side + + + +# +# Client-side + + +http + + +--skip-existing with globbing + + +-o "%LOGDIR/#1" "http://%HOSTIP:%HTTPPORT/%TESTNUMBER/{hey,ho}" --skip-existing + + +content + + +content + + + +# +# Verify data after the test has been "shot" + + +Note: skips transfer, "%LOGDIR/hey" exists locally +Note: skips transfer, "%LOGDIR/ho" exists locally + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/data/test998 b/local-test-curl-delta-01/afc-curl/tests/data/test998 new file mode 100644 index 0000000000000000000000000000000000000000..c3a8f51699b5db7973c0e9804492a8c72f3a2d49 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/data/test998 @@ -0,0 +1,92 @@ + + + +HTTP +--location-trusted + + + +# +# Server-side + + +HTTP/1.1 301 redirect +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 0 +Connection: close +Content-Type: text/html +Location: http://somewhere.else.example/a/path/%TESTNUMBER0002 + + + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + +HTTP/1.1 301 redirect +Date: Tue, 09 Nov 2010 14:49:00 GMT +Server: test-server/fake +Content-Length: 0 +Connection: close +Content-Type: text/html +Location: http://somewhere.else.example/a/path/%TESTNUMBER0002 + +HTTP/1.1 200 OK +Date: Tue, 09 Nov 2010 14:49:00 GMT +Content-Length: 6 +Content-Type: text/html +Funny-head: yesyes + +-foo- + + + + +# +# Client-side + + +proxy + + +http + + +HTTP with auth in URL redirected to another host + + +-x %HOSTIP:%HTTPPORT http://alberto:einstein@somwhere.example/%TESTNUMBER --location-trusted + + + +# +# Verify data after the test has been "shot" + + +QUIT + + +GET http://somwhere.example/998 HTTP/1.1 +Host: somwhere.example +Authorization: Basic YWxiZXJ0bzplaW5zdGVpbg== +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + +GET http://somewhere.else.example/a/path/9980002 HTTP/1.1 +Host: somewhere.else.example +Authorization: Basic YWxiZXJ0bzplaW5zdGVpbg== +User-Agent: curl/%VERSION +Accept: */* +Proxy-Connection: Keep-Alive + + + + diff --git a/local-test-curl-delta-01/afc-curl/tests/http/.gitignore b/local-test-curl-delta-01/afc-curl/tests/http/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..37a847fa93454d45d7e2e1b437e74f68b3a359c5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/.gitignore @@ -0,0 +1,6 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +config.ini +gen diff --git a/local-test-curl-delta-01/afc-curl/tests/http/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/http/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..aeedad094a1a89e1da12c6f64f4c240c678373ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/CMakeLists.txt @@ -0,0 +1,62 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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_program(CADDY "caddy") # /usr/bin/caddy +if(NOT CADDY) + set(CADDY "") +endif() +mark_as_advanced(CADDY) + +find_program(VSFTPD "vsftpd") # /usr/sbin/vsftpd +if(NOT VSFTPD) + set(VSFTPD "") +endif() +mark_as_advanced(VSFTPD) + +find_program(HTTPD "apache2") # /usr/sbin/apache2 +if(NOT HTTPD) + set(HTTPD "") +endif() +mark_as_advanced(HTTPD) + +find_program(APACHECTL "apache2ctl") # /usr/sbin/apache2ctl +if(NOT APACHECTL) + set(APACHECTL "") +endif() +mark_as_advanced(APACHECTL) + +find_program(APXS "apxs") +if(NOT APXS) + set(APXS "") +endif() +mark_as_advanced(APXS) + +find_program(HTTPD_NGHTTPX "nghttpx" PATHS "/usr/bin" "/usr/local/bin") +if(NOT HTTPD_NGHTTPX) + set(HTTPD_NGHTTPX "") +endif() +mark_as_advanced(HTTPD_NGHTTPX) + +# Consumed variables: APACHECTL, APXS, CADDY, HTTPD, HTTPD_NGHTTPX, VSFTPD +configure_file("config.ini.in" "${CMAKE_CURRENT_BINARY_DIR}/config.ini" @ONLY) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/http/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..6039460543744ae18dd777e5a23b2ce0f896523f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/Makefile.am @@ -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 +# +########################################################################### + +SUBDIRS = clients + +TESTENV = \ +testenv/__init__.py \ +testenv/caddy.py \ +testenv/certs.py \ +testenv/client.py \ +testenv/curl.py \ +testenv/env.py \ +testenv/httpd.py \ +testenv/mod_curltest/mod_curltest.c \ +testenv/nghttpx.py \ +testenv/ports.py \ +testenv/vsftpd.py \ +testenv/ws_echo_server.py + +EXTRA_DIST = \ +CMakeLists.txt \ +conftest.py \ +requirements.txt \ +scorecard.py \ +test_01_basic.py \ +test_02_download.py \ +test_03_goaway.py \ +test_04_stuttered.py \ +test_05_errors.py \ +test_06_eyeballs.py \ +test_07_upload.py \ +test_08_caddy.py \ +test_09_push.py \ +test_10_proxy.py \ +test_11_unix.py \ +test_12_reuse.py \ +test_13_proxy_auth.py \ +test_14_auth.py \ +test_15_tracing.py \ +test_16_info.py \ +test_17_ssl_use.py \ +test_18_methods.py \ +test_19_shutdown.py \ +test_20_websockets.py \ +test_30_vsftpd.py \ +test_31_vsftpds.py \ +$(TESTENV) + +clean-local: + rm -rf *.pyc __pycache__ + rm -rf gen + +check: clients + +clients: + @(cd clients; $(MAKE) check) + +checksrc: + cd clients && $(MAKE) checksrc diff --git a/local-test-curl-delta-01/afc-curl/tests/http/README.md b/local-test-curl-delta-01/afc-curl/tests/http/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fc3a0b22b2dab26049d40c6e6b28cb331252bdcf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/README.md @@ -0,0 +1,129 @@ + + +# The curl HTTP Test Suite + +This is an additional test suite using a combination of Apache httpd and nghttpx servers to perform various tests beyond the capabilities of the standard curl test suite. + +# Usage + +The test cases and necessary files are in `tests/http`. You can invoke `pytest` from there or from the top level curl checkout and it will find all tests. + +``` +curl> pytest test/http +platform darwin -- Python 3.9.15, pytest-6.2.0, py-1.10.0, pluggy-0.13.1 +rootdir: /Users/sei/projects/curl +collected 5 items + +tests/http/test_01_basic.py ..... +``` + +Pytest takes arguments. `-v` increases its verbosity and can be used several times. `-k ` can be used to run only matching test cases. The `expr` can be something resembling a python test or just a string that needs to match test cases in their names. + +``` +curl/tests/http> pytest -vv -k test_01_02 +``` + +runs all test cases that have `test_01_02` in their name. This does not have to be the start of the name. + +Depending on your setup, some test cases may be skipped and appear as `s` in the output. If you run pytest verbose, it will also give you the reason for skipping. + +# Prerequisites + +You will need: + +1. a recent Python, the `cryptography` module and, of course, `pytest` +2. an apache httpd development version. On Debian/Ubuntu, the package `apache2-dev` has this. +3. a local `curl` project build +3. optionally, a `nghttpx` with HTTP/3 enabled or h3 test cases will be skipped. + +### Configuration + +Via curl's `configure` script you may specify: + + * `--with-test-nghttpx=` if you have nghttpx to use somewhere outside your `$PATH`. + * `--with-test-httpd=` if you have an Apache httpd installed somewhere else. On Debian/Ubuntu it will otherwise look into `/usr/bin` and `/usr/sbin` to find those. + * `--with-test-caddy=` if you have a Caddy web server installed somewhere else. + * `--with-test-vsftpd=` if you have a vsftpd ftp server installed somewhere else. + +## Usage Tips + +Several test cases are parameterized, for example with the HTTP version to use. If you want to run a test with a particular protocol only, use a command line like: + +``` +curl/tests/http> pytest -k "test_02_06 and h2" +``` + +Test cases can be repeated, with the `pytest-repeat` module (`pip install pytest-repeat`). Like in: + +``` +curl/tests/http> pytest -k "test_02_06 and h2" --count=100 +``` + +which then runs this test case a hundred times. In case of flaky tests, you can make pytest stop on the first one with: + +``` +curl/tests/http> pytest -k "test_02_06 and h2" --count=100 --maxfail=1 +``` + +which allow you to inspect output and log files for the failed run. Speaking of log files, the verbosity of pytest is also used to collect curl trace output. If you specify `-v` three times, the `curl` command is started with `--trace`: + +``` +curl/tests/http> pytest -vvv -k "test_02_06 and h2" --count=100 --maxfail=1 +``` + +all of curl's output and trace file are found in `tests/http/gen/curl`. + +## Writing Tests + +There is a lot of [`pytest` documentation](https://docs.pytest.org/) with examples. No use in repeating that here. Assuming you are somewhat familiar with it, it is useful how *this* general test suite is setup. Especially if you want to add test cases. + +### Servers + +In `conftest.py` 3 "fixtures" are defined that are used by all test cases: + +1. `env`: the test environment. It is an instance of class `testenv/env.py:Env`. It holds all information about paths, availability of features (HTTP/3), port numbers to use, domains and SSL certificates for those. +2. `httpd`: the Apache httpd instance, configured and started, then stopped at the end of the test suite. It has sites configured for the domains from `env`. It also loads a local module `mod_curltest?` and makes it available in certain locations. (more on mod_curltest below). +3. `nghttpx`: an instance of nghttpx that provides HTTP/3 support. `nghttpx` proxies those requests to the `httpd` server. In a direct mapping, so you may access all the resources under the same path as with HTTP/2. Only the port number used for HTTP/3 requests will be different. + +`pytest` manages these fixture so that they are created once and terminated before exit. This means you can `Ctrl-C` a running pytest and the server will shutdown. Only when you brutally chop its head off, might there be servers left +behind. + +### Test Cases + +Tests making use of these fixtures have them in their parameter list. This tells pytest that a particular test needs them, so it has to create them. Since one can invoke pytest for just a single test, it is important that a test references the ones it needs. + +All test cases start with `test_` in their name. We use a double number scheme to group them. This makes it ease to run only specific tests and also give a short mnemonic to communicate trouble with others in the project. Otherwise you are free to name test cases as you think fitting. + +Tests are grouped thematically in a file with a single Python test class. This is convenient if you need a special "fixture" for several tests. "fixtures" can have "class" scope. + +There is a curl helper class that knows how to invoke curl and interpret its output. Among other things, it does add the local CA to the command line, so that SSL connections to the test servers are verified. Nothing prevents anyone from running curl directly, for specific uses not covered by the `CurlClient` class. + +### mod_curltest + +The module source code is found in `testenv/mod_curltest`. It is compiled using the `apxs` command, commonly provided via the `apache2-dev` package. Compilation is quick and done once at the start of a test run. + +The module adds 2 "handlers" to the Apache server (right now). Handler are pieces of code that receive HTTP requests and generate the response. Those handlers are: + +* `curltest-echo`: hooked up on the path `/curltest/echo`. This one echoes a request and copies all data from the request body to the response body. Useful for simulating upload and checking that the data arrived as intended. +* `curltest-tweak`: hooked up on the path `/curltest/tweak`. This handler is more of a Swiss army knife. It interprets parameters from the URL query string to drive its behavior. + * `status=nnn`: generate a response with HTTP status code `nnn`. + * `chunks=n`: generate `n` chunks of data in the response body, defaults to 3. + * `chunk_size=nnn`: each chunk should contain `nnn` bytes of data. Maximum is 16KB right now. + * `chunkd_delay=duration`: wait `duration` time between writing chunks + * `delay=duration`: wait `duration` time to send the response headers + * `body_error=(timeout|reset)`: produce an error after the first chunk in the response body + * `id=str`: add `str` in the response header `request-id` + +`duration` values are integers, optionally followed by a unit. Units are: + + * `d`: days (probably not useful here) + * `h`: hours + * `mi`: minutes + * `s`: seconds (the default) + * `ms`: milliseconds + +As you can see, `mod_curltest`'s tweak handler allow to simulate many kinds of responses. An example of its use is `test_03_01` where responses are delayed using `chunk_delay`. This gives the response a defined duration and the test uses that to reload `httpd` in the middle of the first request. A graceful reload in httpd lets ongoing requests finish, but will close the connection afterwards and tear down the serving process. The following request need then to open a new connection. This is verified by the test case. diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/.gitignore b/local-test-curl-delta-01/afc-curl/tests/http/clients/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..dd6eb29e7fe88a94ebe6c13734ab5d3b380f878c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/.gitignore @@ -0,0 +1,13 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +h2-serverpush +hx-download +hx-upload +ws-data +ws-pingpong +h2-upgrade-extreme +tls-session-reuse +h2-pausing +upload-pausing diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/http/clients/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..32c7f4d4b737abd3e8126412dceab6af69906464 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/CMakeLists.txt @@ -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 +# +########################################################################### + +add_custom_target(test-http-clients) + +# Get 'check_PROGRAMS' variable +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + +foreach(_target IN LISTS check_PROGRAMS) + set(_target_name "curlt-client-${_target}") + add_executable(${_target_name} EXCLUDE_FROM_ALL "${_target}.c") + add_dependencies(testdeps ${_target_name}) + add_dependencies(test-http-clients ${_target_name}) + target_include_directories(${_target_name} PRIVATE + "${PROJECT_BINARY_DIR}/lib" # for "curl_config.h" + "${PROJECT_SOURCE_DIR}/lib" # for "curl_setup.h" + ) + target_link_libraries(${_target_name} ${LIB_SELECTED} ${CURL_LIBS}) + target_compile_definitions(${_target_name} PRIVATE "CURL_NO_OLDIES") + if(LIB_SELECTED STREQUAL LIB_STATIC AND WIN32) + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB") + endif() + set_target_properties(${_target_name} PROPERTIES + OUTPUT_NAME "${_target}" UNITY_BUILD OFF + PROJECT_LABEL "Test client ${_target}") +endforeach() diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..935614c5fd043d51ad93416a11fc3e232fa9b3c9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.am @@ -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 +# +########################################################################### + +AUTOMAKE_OPTIONS = foreign nostdinc + +EXTRA_DIST = CMakeLists.txt + +# 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 + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib + +LIBDIR = $(top_builddir)/lib + +# Avoid libcurl obsolete stuff +AM_CPPFLAGS += -DCURL_NO_OLDIES + +if USE_CPPFLAG_CURL_STATICLIB +AM_CPPFLAGS += -DCURL_STATICLIB +endif + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +# Dependencies +LDADD = $(LIBDIR)/libcurl.la @LIBCURL_PC_LIBS_PRIVATE@ + +# This might hold -Werror +CFLAGS += @CURL_CFLAG_EXTRAS@ + +# Makefile.inc provides the check_PROGRAMS define +include Makefile.inc + +all: $(check_PROGRAMS) + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(srcdir)/*.c) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.inc b/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..c5e4e8afbeb756b1410e3916b916682644e3e514 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/Makefile.inc @@ -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 +# +########################################################################### + +# These are all libcurl example programs to be test compiled +check_PROGRAMS = \ + hx-download \ + hx-upload \ + h2-pausing \ + h2-serverpush \ + h2-upgrade-extreme \ + tls-session-reuse \ + upload-pausing \ + ws-data \ + ws-pingpong diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-pausing.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-pausing.c new file mode 100644 index 0000000000000000000000000000000000000000..1fd54d4f6375f122c8eeb9d1e6da654ebaa8f3e9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-pausing.c @@ -0,0 +1,410 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP/2 download pausing + * + */ +/* This is based on the PoC client of issue #11982 + */ +#include + +#include +#include +#include +#include + +#ifndef _MSC_VER +/* somewhat Unix-specific */ +#include /* getopt() */ +#endif + +#ifndef _MSC_VER +#define HANDLECOUNT 2 + +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +static int err(void) +{ + fprintf(stderr, "something unexpected went wrong - bailing out!\n"); + exit(2); +} + +static void usage(const char *msg) +{ + if(msg) + fprintf(stderr, "%s\n", msg); + fprintf(stderr, + "usage: [options] url\n" + " pause downloads with following options:\n" + " -V http_version (http/1.1, h2, h3) http version to use\n" + ); +} + +struct handle +{ + int idx; + int paused; + int resumed; + int errored; + int fail_write; + CURL *h; +}; + +static size_t cb(char *data, size_t size, size_t nmemb, void *clientp) +{ + size_t realsize = size * nmemb; + struct handle *handle = (struct handle *) clientp; + curl_off_t totalsize; + + (void)data; + if(curl_easy_getinfo(handle->h, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, + &totalsize) == CURLE_OK) + fprintf(stderr, "INFO: [%d] write, Content-Length %"CURL_FORMAT_CURL_OFF_T + "\n", handle->idx, totalsize); + + if(!handle->resumed) { + ++handle->paused; + fprintf(stderr, "INFO: [%d] write, PAUSING %d time on %lu bytes\n", + handle->idx, handle->paused, (long)realsize); + assert(handle->paused == 1); + return CURL_WRITEFUNC_PAUSE; + } + if(handle->fail_write) { + ++handle->errored; + fprintf(stderr, "INFO: [%d] FAIL write of %lu bytes, %d time\n", + handle->idx, (long)realsize, handle->errored); + return CURL_WRITEFUNC_ERROR; + } + fprintf(stderr, "INFO: [%d] write, accepting %lu bytes\n", + handle->idx, (long)realsize); + return realsize; +} +#endif /* !_MSC_VER */ + +int main(int argc, char *argv[]) +{ +#ifndef _MSC_VER + struct handle handles[HANDLECOUNT]; + CURLM *multi_handle; + int i, still_running = 1, msgs_left, numfds; + CURLMsg *msg; + int rounds = 0; + int rc = 0; + CURLU *cu; + struct curl_slist *resolve = NULL; + char resolve_buf[1024]; + char *url, *host = NULL, *port = NULL; + int all_paused = 0; + int resume_round = -1; + int http_version = CURL_HTTP_VERSION_2_0; + int ch; + + while((ch = getopt(argc, argv, "hV:")) != -1) { + switch(ch) { + case 'h': + usage(NULL); + return 2; + case 'V': { + if(!strcmp("http/1.1", optarg)) + http_version = CURL_HTTP_VERSION_1_1; + else if(!strcmp("h2", optarg)) + http_version = CURL_HTTP_VERSION_2_0; + else if(!strcmp("h3", optarg)) + http_version = CURL_HTTP_VERSION_3ONLY; + else { + usage("invalid http version"); + return 1; + } + break; + } + default: + usage("invalid option"); + return 1; + } + } + argc -= optind; + argv += optind; + + if(argc != 1) { + fprintf(stderr, "ERROR: need URL as argument\n"); + return 2; + } + url = argv[0]; + + curl_global_init(CURL_GLOBAL_DEFAULT); + curl_global_trace("ids,time,http/2,http/3"); + + cu = curl_url(); + if(!cu) { + fprintf(stderr, "out of memory\n"); + exit(1); + } + if(curl_url_set(cu, CURLUPART_URL, url, 0)) { + fprintf(stderr, "not a URL: '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_HOST, &host, 0)) { + fprintf(stderr, "could not get host of '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_PORT, &port, 0)) { + fprintf(stderr, "could not get port of '%s'\n", url); + exit(1); + } + memset(&resolve, 0, sizeof(resolve)); + curl_msnprintf(resolve_buf, sizeof(resolve_buf)-1, "%s:%s:127.0.0.1", + host, port); + resolve = curl_slist_append(resolve, resolve_buf); + + for(i = 0; i < HANDLECOUNT; i++) { + handles[i].idx = i; + handles[i].paused = 0; + handles[i].resumed = 0; + handles[i].errored = 0; + handles[i].fail_write = 1; + handles[i].h = curl_easy_init(); + if(!handles[i].h || + curl_easy_setopt(handles[i].h, CURLOPT_WRITEFUNCTION, cb) != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_WRITEDATA, &handles[i]) + != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_FOLLOWLOCATION, 1L) != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_VERBOSE, 1L) != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_DEBUGFUNCTION, debug_cb) + != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_SSL_VERIFYPEER, 0L) != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_RESOLVE, resolve) != CURLE_OK || + curl_easy_setopt(handles[i].h, CURLOPT_PIPEWAIT, 1L) || + curl_easy_setopt(handles[i].h, CURLOPT_URL, url) != CURLE_OK) { + err(); + } + curl_easy_setopt(handles[i].h, CURLOPT_HTTP_VERSION, (long)http_version); + } + + multi_handle = curl_multi_init(); + if(!multi_handle) + err(); + + for(i = 0; i < HANDLECOUNT; i++) { + if(curl_multi_add_handle(multi_handle, handles[i].h) != CURLM_OK) + err(); + } + + for(rounds = 0;; rounds++) { + fprintf(stderr, "INFO: multi_perform round %d\n", rounds); + if(curl_multi_perform(multi_handle, &still_running) != CURLM_OK) + err(); + + if(!still_running) { + int as_expected = 1; + fprintf(stderr, "INFO: no more handles running\n"); + for(i = 0; i < HANDLECOUNT; i++) { + if(!handles[i].paused) { + fprintf(stderr, "ERROR: [%d] NOT PAUSED\n", i); + as_expected = 0; + } + else if(handles[i].paused != 1) { + fprintf(stderr, "ERROR: [%d] PAUSED %d times!\n", + i, handles[i].paused); + as_expected = 0; + } + else if(!handles[i].resumed) { + fprintf(stderr, "ERROR: [%d] NOT resumed!\n", i); + as_expected = 0; + } + else if(handles[i].errored != 1) { + fprintf(stderr, "ERROR: [%d] NOT errored once, %d instead!\n", + i, handles[i].errored); + as_expected = 0; + } + } + if(!as_expected) { + fprintf(stderr, "ERROR: handles not in expected state " + "after %d rounds\n", rounds); + rc = 1; + } + break; + } + + if(curl_multi_poll(multi_handle, NULL, 0, 100, &numfds) != CURLM_OK) + err(); + + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(multi_handle, &msgs_left)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + for(i = 0; i < HANDLECOUNT; i++) { + if(msg->easy_handle == handles[i].h) { + if(handles[i].paused != 1 || !handles[i].resumed) { + fprintf(stderr, "ERROR: [%d] done, pauses=%d, resumed=%d, " + "result %d - wtf?\n", i, handles[i].paused, + handles[i].resumed, msg->data.result); + rc = 1; + goto out; + } + } + } + } + } + + /* Successfully paused? */ + if(!all_paused) { + for(i = 0; i < HANDLECOUNT; i++) { + if(!handles[i].paused) { + break; + } + } + all_paused = (i == HANDLECOUNT); + if(all_paused) { + fprintf(stderr, "INFO: all transfers paused\n"); + /* give transfer some rounds to mess things up */ + resume_round = rounds + 2; + } + } + if(resume_round > 0 && rounds == resume_round) { + /* time to resume */ + for(i = 0; i < HANDLECOUNT; i++) { + fprintf(stderr, "INFO: [%d] resumed\n", i); + handles[i].resumed = 1; + curl_easy_pause(handles[i].h, CURLPAUSE_CONT); + } + } + } + +out: + for(i = 0; i < HANDLECOUNT; i++) { + curl_multi_remove_handle(multi_handle, handles[i].h); + curl_easy_cleanup(handles[i].h); + } + + + curl_slist_free_all(resolve); + curl_free(host); + curl_free(port); + curl_url_cleanup(cu); + curl_multi_cleanup(multi_handle); + curl_global_cleanup(); + + return rc; +#else + (void)argc; + (void)argv; + fprintf(stderr, "Not supported with this compiler.\n"); + return 1; +#endif /* !_MSC_VER */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-serverpush.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-serverpush.c new file mode 100644 index 0000000000000000000000000000000000000000..1710f355c2fbd42e949ebc492db6b68c5514243e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-serverpush.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 + * + ***************************************************************************/ +/* + * HTTP/2 server push + * + */ +/* curl stuff */ +#include + +#include +#include +#include + +#ifndef CURLPIPE_MULTIPLEX +#error "too old libcurl, cannot do HTTP/2 server push!" +#endif + +static +void dump(const char *text, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stderr, "%s, %lu bytes (0x%lx)\n", + text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stderr, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stderr, "%02x ", ptr[i + c]); + else + fputs(" ", stderr); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stderr, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stderr); /* newline */ + } +} + +static +int my_trace(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userp) +{ + const char *text; + (void)handle; /* prevent compiler warning */ + (void)userp; + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "== Info: %s", data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, (unsigned char *)data, size, 1); + return 0; +} + +#define OUTPUTFILE "download_0.data" + +static int setup(CURL *hnd, const char *url) +{ + FILE *out = fopen(OUTPUTFILE, "wb"); + if(!out) + /* failed */ + return 1; + + curl_easy_setopt(hnd, CURLOPT_URL, url); + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); + + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, out); + + /* please be verbose */ + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace); + +#if (CURLPIPE_MULTIPLEX > 0) + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +#endif + return 0; /* all is good */ +} + +/* called when there's an incoming push */ +static int server_push_callback(CURL *parent, + CURL *easy, + size_t num_headers, + struct curl_pushheaders *headers, + void *userp) +{ + char *headp; + size_t i; + int *transfers = (int *)userp; + char filename[128]; + FILE *out; + static unsigned int count = 0; + int rv; + + (void)parent; /* we have no use for this */ + curl_msnprintf(filename, sizeof(filename)-1, "push%u", count++); + + /* here's a new stream, save it in a new file for each new push */ + out = fopen(filename, "wb"); + if(!out) { + /* if we cannot save it, deny it */ + fprintf(stderr, "Failed to create output file for push\n"); + rv = CURL_PUSH_DENY; + goto out; + } + + /* write to this file */ + curl_easy_setopt(easy, CURLOPT_WRITEDATA, out); + + fprintf(stderr, "**** push callback approves stream %u, got %lu headers!\n", + count, (unsigned long)num_headers); + + for(i = 0; i < num_headers; i++) { + headp = curl_pushheader_bynum(headers, i); + fprintf(stderr, "**** header %lu: %s\n", (unsigned long)i, headp); + } + + headp = curl_pushheader_byname(headers, ":path"); + if(headp) { + fprintf(stderr, "**** The PATH is %s\n", headp /* skip :path + colon */); + } + + (*transfers)++; /* one more */ + rv = CURL_PUSH_OK; + +out: + return rv; +} + + +/* + * Download a file over HTTP/2, take care of server push. + */ +int main(int argc, char *argv[]) +{ + CURL *easy; + CURLM *multi_handle; + int transfers = 1; /* we start with one */ + struct CURLMsg *m; + const char *url; + + if(argc != 2) { + fprintf(stderr, "need URL as argument\n"); + return 2; + } + url = argv[1]; + + multi_handle = curl_multi_init(); + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + curl_multi_setopt(multi_handle, CURLMOPT_PUSHFUNCTION, server_push_callback); + curl_multi_setopt(multi_handle, CURLMOPT_PUSHDATA, &transfers); + + easy = curl_easy_init(); + if(setup(easy, url)) { + fprintf(stderr, "failed\n"); + return 1; + } + + curl_multi_add_handle(multi_handle, easy); + do { + int still_running; /* keep number of running handles */ + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + + if(mc) + break; + + /* + * A little caution when doing server push is that libcurl itself has + * created and added one or more easy handles but we need to clean them up + * when we are done. + */ + do { + int msgq = 0; + m = curl_multi_info_read(multi_handle, &msgq); + if(m && (m->msg == CURLMSG_DONE)) { + CURL *e = m->easy_handle; + transfers--; + curl_multi_remove_handle(multi_handle, e); + curl_easy_cleanup(e); + } + } while(m); + + } while(transfers); /* as long as we have transfers going */ + + curl_multi_cleanup(multi_handle); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-upgrade-extreme.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-upgrade-extreme.c new file mode 100644 index 0000000000000000000000000000000000000000..e6e39c17096a5c418d7d0353f600a0dcdd439db4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/h2-upgrade-extreme.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 + * + ***************************************************************************/ +/* + * HTTP/2 Upgrade test + * + */ +#include + +#include +#include +/* #include */ +#include + +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +static size_t write_cb(char *ptr, size_t size, size_t nmemb, void *opaque) +{ + (void)ptr; + (void)opaque; + return size * nmemb; +} + +int main(int argc, char *argv[]) +{ + const char *url; + CURLM *multi; + CURL *easy; + CURLMcode mc; + int running_handles = 0, start_count, numfds; + CURLMsg *msg; + int msgs_in_queue; + char range[128]; + + if(argc != 2) { + fprintf(stderr, "%s URL\n", argv[0]); + exit(2); + } + + url = argv[1]; + multi = curl_multi_init(); + if(!multi) { + fprintf(stderr, "curl_multi_init failed\n"); + exit(1); + } + + start_count = 200; + do { + if(start_count) { + easy = curl_easy_init(); + if(!easy) { + fprintf(stderr, "curl_easy_init failed\n"); + exit(1); + } + curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, debug_cb); + curl_easy_setopt(easy, CURLOPT_URL, url); + curl_easy_setopt(easy, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(easy, CURLOPT_AUTOREFERER, 1L); + curl_easy_setopt(easy, CURLOPT_FAILONERROR, 1L); + curl_easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(easy, CURLOPT_WRITEDATA, NULL); + curl_easy_setopt(easy, CURLOPT_HTTPGET, 1L); + curl_msnprintf(range, sizeof(range), + "%" CURL_FORMAT_CURL_OFF_TU "-" + "%" CURL_FORMAT_CURL_OFF_TU, + (curl_off_t)0, + (curl_off_t)16384); + curl_easy_setopt(easy, CURLOPT_RANGE, range); + + mc = curl_multi_add_handle(multi, easy); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_add_handle: %s\n", + curl_multi_strerror(mc)); + exit(1); + } + --start_count; + } + + mc = curl_multi_perform(multi, &running_handles); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_perform: %s\n", + curl_multi_strerror(mc)); + exit(1); + } + + if(running_handles) { + mc = curl_multi_poll(multi, NULL, 0, 1000000, &numfds); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_poll: %s\n", + curl_multi_strerror(mc)); + exit(1); + } + } + + /* Check for finished handles and remove. */ + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(multi, &msgs_in_queue)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + long status = 0; + curl_off_t xfer_id; + curl_easy_getinfo(msg->easy_handle, CURLINFO_XFER_ID, &xfer_id); + curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &status); + if(msg->data.result == CURLE_SEND_ERROR || + msg->data.result == CURLE_RECV_ERROR) { + /* We get these if the server had a GOAWAY in transit on + * re-using a connection */ + } + else if(msg->data.result) { + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T + ": failed with %d\n", xfer_id, msg->data.result); + exit(1); + } + else if(status != 206) { + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T + ": wrong http status %ld (expected 206)\n", xfer_id, status); + exit(1); + } + curl_multi_remove_handle(multi, msg->easy_handle); + curl_easy_cleanup(msg->easy_handle); + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T" retiring " + "(%d now running)\n", xfer_id, running_handles); + } + } + + fprintf(stderr, "running_handles=%d, yet_to_start=%d\n", + running_handles, start_count); + + } while(running_handles > 0 || start_count); + + fprintf(stderr, "exiting\n"); + exit(EXIT_SUCCESS); +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-download.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-download.c new file mode 100644 index 0000000000000000000000000000000000000000..94e9d0cbd6d43b3e00c321e2521f047f2b17a54a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-download.c @@ -0,0 +1,547 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP/2 server push + * + */ +/* curl stuff */ +#include + +#include +#include +#include + +#ifndef _MSC_VER +/* somewhat Unix-specific */ +#include /* getopt() */ +#endif + +#ifndef CURLPIPE_MULTIPLEX +#error "too old libcurl, cannot do HTTP/2 server push!" +#endif + +#ifndef _MSC_VER +static int verbose = 1; + +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +struct transfer { + int idx; + CURL *easy; + char filename[128]; + FILE *out; + curl_off_t recv_size; + curl_off_t fail_at; + curl_off_t pause_at; + curl_off_t abort_at; + int started; + int paused; + int resumed; + int done; +}; + +static size_t transfer_count = 1; +static struct transfer *transfers; +static int forbid_reuse = 0; + +static struct transfer *get_transfer_for_easy(CURL *easy) +{ + size_t i; + for(i = 0; i < transfer_count; ++i) { + if(easy == transfers[i].easy) + return &transfers[i]; + } + return NULL; +} + +static size_t my_write_cb(char *buf, size_t nitems, size_t buflen, + void *userdata) +{ + struct transfer *t = userdata; + size_t blen = (nitems * buflen); + size_t nwritten; + + fprintf(stderr, "[t-%d] RECV %ld bytes, total=%ld, pause_at=%ld\n", + t->idx, (long)blen, (long)t->recv_size, (long)t->pause_at); + if(!t->out) { + curl_msnprintf(t->filename, sizeof(t->filename)-1, "download_%u.data", + t->idx); + t->out = fopen(t->filename, "wb"); + if(!t->out) + return 0; + } + + if(!t->resumed && + t->recv_size < t->pause_at && + ((t->recv_size + (curl_off_t)blen) >= t->pause_at)) { + fprintf(stderr, "[t-%d] PAUSE\n", t->idx); + t->paused = 1; + return CURL_WRITEFUNC_PAUSE; + } + + nwritten = fwrite(buf, nitems, buflen, t->out); + if(nwritten < blen) { + fprintf(stderr, "[t-%d] write failure\n", t->idx); + return 0; + } + t->recv_size += (curl_off_t)nwritten; + if(t->fail_at > 0 && t->recv_size >= t->fail_at) { + fprintf(stderr, "[t-%d] FAIL by write callback at %ld bytes\n", + t->idx, (long)t->recv_size); + return CURL_WRITEFUNC_ERROR; + } + + return (size_t)nwritten; +} + +static int my_progress_cb(void *userdata, + curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + struct transfer *t = userdata; + (void)ultotal; + (void)ulnow; + (void)dltotal; + if(t->abort_at > 0 && dlnow >= t->abort_at) { + fprintf(stderr, "[t-%d] ABORT by progress_cb at %ld bytes\n", + t->idx, (long)dlnow); + return 1; + } + return 0; +} + +static int setup(CURL *hnd, const char *url, struct transfer *t, + int http_version, struct curl_slist *host, + CURLSH *share, int use_earlydata, int fresh_connect) +{ + curl_easy_setopt(hnd, CURLOPT_SHARE, share); + curl_easy_setopt(hnd, CURLOPT_URL, url); + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, http_version); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, (long)(128 * 1024)); + curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, my_write_cb); + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, t); + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(hnd, CURLOPT_XFERINFOFUNCTION, my_progress_cb); + curl_easy_setopt(hnd, CURLOPT_XFERINFODATA, t); + if(use_earlydata) + curl_easy_setopt(hnd, CURLOPT_SSL_OPTIONS, (long)CURLSSLOPT_EARLYDATA); + if(forbid_reuse) + curl_easy_setopt(hnd, CURLOPT_FORBID_REUSE, 1L); + if(host) + curl_easy_setopt(hnd, CURLOPT_RESOLVE, host); + if(fresh_connect) + curl_easy_setopt(hnd, CURLOPT_FRESH_CONNECT, 1L); + + /* please be verbose */ + if(verbose) { + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, debug_cb); + } + +#if (CURLPIPE_MULTIPLEX > 0) + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +#endif + return 0; /* all is good */ +} + +static void usage(const char *msg) +{ + if(msg) + fprintf(stderr, "%s\n", msg); + fprintf(stderr, + "usage: [options] url\n" + " download a url with following options:\n" + " -a abort paused transfer\n" + " -m number max parallel downloads\n" + " -e use TLS early data when possible\n" + " -f forbid connection reuse\n" + " -n number total downloads\n"); + fprintf(stderr, + " -A number abort transfer after `number` response bytes\n" + " -F number fail writing response after `number` response bytes\n" + " -P number pause transfer after `number` response bytes\n" + " -r :: resolve information\n" + " -V http_version (http/1.1, h2, h3) http version to use\n" + ); +} +#endif /* !_MSC_VER */ + +/* + * Download a file over HTTP/2, take care of server push. + */ +int main(int argc, char *argv[]) +{ +#ifndef _MSC_VER + CURLM *multi_handle; + struct CURLMsg *m; + CURLSH *share; + const char *url; + size_t i, n, max_parallel = 1; + size_t active_transfers; + size_t pause_offset = 0; + size_t abort_offset = 0; + size_t fail_offset = 0; + int abort_paused = 0, use_earlydata = 0; + struct transfer *t; + int http_version = CURL_HTTP_VERSION_2_0; + int ch; + struct curl_slist *host = NULL; + char *resolve = NULL; + size_t max_host_conns = 0; + int fresh_connect = 0; + + while((ch = getopt(argc, argv, "aefhm:n:xA:F:M:P:r:V:")) != -1) { + switch(ch) { + case 'h': + usage(NULL); + return 2; + case 'a': + abort_paused = 1; + break; + case 'e': + use_earlydata = 1; + break; + case 'f': + forbid_reuse = 1; + break; + case 'm': + max_parallel = (size_t)strtol(optarg, NULL, 10); + break; + case 'n': + transfer_count = (size_t)strtol(optarg, NULL, 10); + break; + case 'x': + fresh_connect = 1; + break; + case 'A': + abort_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'F': + fail_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'M': + max_host_conns = (size_t)strtol(optarg, NULL, 10); + break; + case 'P': + pause_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'r': + resolve = strdup(optarg); + break; + case 'V': { + if(!strcmp("http/1.1", optarg)) + http_version = CURL_HTTP_VERSION_1_1; + else if(!strcmp("h2", optarg)) + http_version = CURL_HTTP_VERSION_2_0; + else if(!strcmp("h3", optarg)) + http_version = CURL_HTTP_VERSION_3ONLY; + else { + usage("invalid http version"); + return 1; + } + break; + } + default: + usage("invalid option"); + return 1; + } + } + argc -= optind; + argv += optind; + + curl_global_init(CURL_GLOBAL_DEFAULT); + curl_global_trace("ids,time,http/2,http/3"); + + if(argc != 1) { + usage("not enough arguments"); + return 2; + } + url = argv[0]; + + if(resolve) + host = curl_slist_append(NULL, resolve); + + share = curl_share_init(); + if(!share) { + fprintf(stderr, "error allocating share\n"); + return 1; + } + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); + /* curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT); */ + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_PSL); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_HSTS); + + transfers = calloc(transfer_count, sizeof(*transfers)); + if(!transfers) { + fprintf(stderr, "error allocating transfer structs\n"); + return 1; + } + + multi_handle = curl_multi_init(); + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, + (long)max_host_conns); + + active_transfers = 0; + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + t->idx = (int)i; + t->abort_at = (curl_off_t)abort_offset; + t->fail_at = (curl_off_t)fail_offset; + t->pause_at = (curl_off_t)pause_offset; + } + + n = (max_parallel < transfer_count) ? max_parallel : transfer_count; + for(i = 0; i < n; ++i) { + t = &transfers[i]; + t->easy = curl_easy_init(); + if(!t->easy || + setup(t->easy, url, t, http_version, host, share, use_earlydata, + fresh_connect)) { + fprintf(stderr, "[t-%d] FAILED setup\n", (int)i); + return 1; + } + curl_multi_add_handle(multi_handle, t->easy); + t->started = 1; + ++active_transfers; + fprintf(stderr, "[t-%d] STARTED\n", t->idx); + } + + do { + int still_running; /* keep number of running handles */ + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) { + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + } + + if(mc) + break; + + do { + int msgq = 0; + m = curl_multi_info_read(multi_handle, &msgq); + if(m && (m->msg == CURLMSG_DONE)) { + CURL *e = m->easy_handle; + --active_transfers; + curl_multi_remove_handle(multi_handle, e); + t = get_transfer_for_easy(e); + if(t) { + t->done = 1; + fprintf(stderr, "[t-%d] FINISHED\n", t->idx); + if(use_earlydata) { + curl_off_t sent; + curl_easy_getinfo(e, CURLINFO_EARLYDATA_SENT_T, &sent); + fprintf(stderr, "[t-%d] EarlyData: %ld\n", t->idx, (long)sent); + } + } + else { + curl_easy_cleanup(e); + fprintf(stderr, "unknown FINISHED???\n"); + } + } + + + /* nothing happening, maintenance */ + if(abort_paused) { + /* abort paused transfers */ + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->done && t->paused && t->easy) { + curl_multi_remove_handle(multi_handle, t->easy); + t->done = 1; + active_transfers--; + fprintf(stderr, "[t-%d] ABORTED\n", t->idx); + } + } + } + else { + /* resume one paused transfer */ + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->done && t->paused) { + t->resumed = 1; + t->paused = 0; + curl_easy_pause(t->easy, CURLPAUSE_CONT); + fprintf(stderr, "[t-%d] RESUMED\n", t->idx); + break; + } + } + } + + while(active_transfers < max_parallel) { + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->started) { + t->easy = curl_easy_init(); + if(!t->easy || + setup(t->easy, url, t, http_version, host, share, + use_earlydata, fresh_connect)) { + fprintf(stderr, "[t-%d] FAILED setup\n", (int)i); + return 1; + } + curl_multi_add_handle(multi_handle, t->easy); + t->started = 1; + ++active_transfers; + fprintf(stderr, "[t-%d] STARTED\n", t->idx); + break; + } + } + /* all started */ + if(i == transfer_count) + break; + } + } while(m); + + } while(active_transfers); /* as long as we have transfers going */ + + curl_multi_cleanup(multi_handle); + + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(t->out) { + fclose(t->out); + t->out = NULL; + } + if(t->easy) { + curl_easy_cleanup(t->easy); + t->easy = NULL; + } + } + free(transfers); + + curl_share_cleanup(share); + curl_slist_free_all(host); + free(resolve); + + return 0; +#else + (void)argc; + (void)argv; + fprintf(stderr, "Not supported with this compiler.\n"); + return 1; +#endif /* !_MSC_VER */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-upload.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-upload.c new file mode 100644 index 0000000000000000000000000000000000000000..06df2f4cbfdd56cadff74e4ab242aeeb1001558d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/hx-upload.c @@ -0,0 +1,617 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * HTTP upload tests and tweaks + * + */ +/* curl stuff */ +#include + +#include +#include +#include + +#ifndef _MSC_VER +/* somewhat Unix-specific */ +#include /* getopt() */ +#endif + +#ifndef CURLPIPE_MULTIPLEX +#error "too old libcurl" +#endif + +#ifndef _MSC_VER +static int verbose = 1; + +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +struct transfer { + int idx; + CURL *easy; + const char *method; + char filename[128]; + FILE *out; + curl_off_t send_total; + curl_off_t recv_size; + curl_off_t send_size; + curl_off_t fail_at; + curl_off_t pause_at; + curl_off_t abort_at; + int started; + int paused; + int resumed; + int done; +}; + +static size_t transfer_count = 1; +static struct transfer *transfers; +static int forbid_reuse = 0; + +static struct transfer *get_transfer_for_easy(CURL *easy) +{ + size_t i; + for(i = 0; i < transfer_count; ++i) { + if(easy == transfers[i].easy) + return &transfers[i]; + } + return NULL; +} + +static size_t my_write_cb(char *buf, size_t nitems, size_t buflen, + void *userdata) +{ + struct transfer *t = userdata; + size_t blen = (nitems * buflen); + size_t nwritten; + + fprintf(stderr, "[t-%d] RECV %ld bytes, total=%ld, pause_at=%ld\n", + t->idx, (long)blen, (long)t->recv_size, (long)t->pause_at); + if(!t->out) { + curl_msnprintf(t->filename, sizeof(t->filename)-1, "download_%u.data", + t->idx); + t->out = fopen(t->filename, "wb"); + if(!t->out) + return 0; + } + + nwritten = fwrite(buf, nitems, buflen, t->out); + if(nwritten < blen) { + fprintf(stderr, "[t-%d] write failure\n", t->idx); + return 0; + } + t->recv_size += (curl_off_t)nwritten; + return (size_t)nwritten; +} + +static size_t my_read_cb(char *buf, size_t nitems, size_t buflen, + void *userdata) +{ + struct transfer *t = userdata; + size_t blen = (nitems * buflen); + size_t nread; + + if(t->send_total <= t->send_size) + nread = 0; + else if((t->send_total - t->send_size) < (curl_off_t)blen) + nread = (size_t)(t->send_total - t->send_size); + else + nread = blen; + + fprintf(stderr, "[t-%d] SEND %ld bytes, total=%ld, pause_at=%ld\n", + t->idx, (long)nread, (long)t->send_total, (long)t->pause_at); + + if(!t->resumed && + t->send_size < t->pause_at && + ((t->send_size + (curl_off_t)blen) >= t->pause_at)) { + fprintf(stderr, "[t-%d] PAUSE\n", t->idx); + t->paused = 1; + return CURL_READFUNC_PAUSE; + } + + memset(buf, 'x', nread); + t->send_size += (curl_off_t)nread; + if(t->fail_at > 0 && t->send_size >= t->fail_at) { + fprintf(stderr, "[t-%d] ABORT by read callback at %ld bytes\n", + t->idx, (long)t->send_size); + return CURL_READFUNC_ABORT; + } + return (size_t)nread; +} + +static int my_progress_cb(void *userdata, + curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + struct transfer *t = userdata; + (void)ultotal; + (void)dlnow; + (void)dltotal; + if(t->abort_at > 0 && ulnow >= t->abort_at) { + fprintf(stderr, "[t-%d] ABORT by progress_cb at %ld bytes sent\n", + t->idx, (long)ulnow); + return 1; + } + return 0; +} + +static int setup(CURL *hnd, const char *url, struct transfer *t, + int http_version, struct curl_slist *host, + CURLSH *share, int use_earlydata, int announce_length) +{ + curl_easy_setopt(hnd, CURLOPT_SHARE, share); + curl_easy_setopt(hnd, CURLOPT_URL, url); + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, http_version); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, (long)(128 * 1024)); + curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, my_write_cb); + curl_easy_setopt(hnd, CURLOPT_WRITEDATA, t); + if(use_earlydata) + curl_easy_setopt(hnd, CURLOPT_SSL_OPTIONS, (long)CURLSSLOPT_EARLYDATA); + + if(!t->method || !strcmp("PUT", t->method)) + curl_easy_setopt(hnd, CURLOPT_UPLOAD, 1L); + else if(!strcmp("POST", t->method)) + curl_easy_setopt(hnd, CURLOPT_POST, 1L); + else { + fprintf(stderr, "unsupported method '%s'\n", t->method); + return 1; + } + curl_easy_setopt(hnd, CURLOPT_READFUNCTION, my_read_cb); + curl_easy_setopt(hnd, CURLOPT_READDATA, t); + if(announce_length) + curl_easy_setopt(hnd, CURLOPT_INFILESIZE_LARGE, t->send_total); + + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(hnd, CURLOPT_XFERINFOFUNCTION, my_progress_cb); + curl_easy_setopt(hnd, CURLOPT_XFERINFODATA, t); + if(forbid_reuse) + curl_easy_setopt(hnd, CURLOPT_FORBID_REUSE, 1L); + if(host) + curl_easy_setopt(hnd, CURLOPT_RESOLVE, host); + + /* please be verbose */ + if(verbose) { + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, debug_cb); + } + +#if (CURLPIPE_MULTIPLEX > 0) + /* wait for pipe connection to confirm */ + curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L); +#endif + return 0; /* all is good */ +} + +static void usage(const char *msg) +{ + if(msg) + fprintf(stderr, "%s\n", msg); + fprintf(stderr, + "usage: [options] url\n" + " upload to a url with following options:\n" + " -a abort paused transfer\n" + " -e use TLS earlydata\n" + " -m number max parallel uploads\n" + " -n number total uploads\n" + " -A number abort transfer after `number` request body bytes\n" + " -F number fail reading request body after `number` of bytes\n" + " -P number pause transfer after `number` request body bytes\n" + " -r :: resolve information\n" + " -S number size to upload\n" + " -V http_version (http/1.1, h2, h3) http version to use\n" + ); +} +#endif /* !_MSC_VER */ + +/* + * Download a file over HTTP/2, take care of server push. + */ +int main(int argc, char *argv[]) +{ +#ifndef _MSC_VER + CURLM *multi_handle; + struct CURLMsg *m; + CURLSH *share; + const char *url; + const char *method = "PUT"; + size_t i, n, max_parallel = 1; + size_t active_transfers; + size_t pause_offset = 0; + size_t abort_offset = 0; + size_t fail_offset = 0; + size_t send_total = (128 * 1024); + int abort_paused = 0; + int reuse_easy = 0; + int use_earlydata = 0; + int announce_length = 0; + struct transfer *t; + int http_version = CURL_HTTP_VERSION_2_0; + struct curl_slist *host = NULL; + const char *resolve = NULL; + int ch; + + while((ch = getopt(argc, argv, "aefhlm:n:A:F:M:P:r:RS:V:")) != -1) { + switch(ch) { + case 'h': + usage(NULL); + return 2; + case 'a': + abort_paused = 1; + break; + case 'e': + use_earlydata = 1; + break; + case 'f': + forbid_reuse = 1; + break; + case 'l': + announce_length = 1; + break; + case 'm': + max_parallel = (size_t)strtol(optarg, NULL, 10); + break; + case 'n': + transfer_count = (size_t)strtol(optarg, NULL, 10); + break; + case 'A': + abort_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'F': + fail_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'M': + method = optarg; + break; + case 'P': + pause_offset = (size_t)strtol(optarg, NULL, 10); + break; + case 'r': + resolve = optarg; + break; + case 'R': + reuse_easy = 1; + break; + case 'S': + send_total = (size_t)strtol(optarg, NULL, 10); + break; + case 'V': { + if(!strcmp("http/1.1", optarg)) + http_version = CURL_HTTP_VERSION_1_1; + else if(!strcmp("h2", optarg)) + http_version = CURL_HTTP_VERSION_2_0; + else if(!strcmp("h3", optarg)) + http_version = CURL_HTTP_VERSION_3ONLY; + else { + usage("invalid http version"); + return 1; + } + break; + } + default: + usage("invalid option"); + return 1; + } + } + argc -= optind; + argv += optind; + + if(max_parallel > 1 && reuse_easy) { + usage("cannot mix -R and -P"); + return 2; + } + + curl_global_init(CURL_GLOBAL_DEFAULT); + curl_global_trace("ids,time,http/2,http/3"); + + if(argc != 1) { + usage("not enough arguments"); + return 2; + } + url = argv[0]; + + if(resolve) + host = curl_slist_append(NULL, resolve); + + share = curl_share_init(); + if(!share) { + fprintf(stderr, "error allocating share\n"); + return 1; + } + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_PSL); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_HSTS); + + transfers = calloc(transfer_count, sizeof(*transfers)); + if(!transfers) { + fprintf(stderr, "error allocating transfer structs\n"); + return 1; + } + + active_transfers = 0; + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + t->idx = (int)i; + t->method = method; + t->send_total = (curl_off_t)send_total; + t->abort_at = (curl_off_t)abort_offset; + t->fail_at = (curl_off_t)fail_offset; + t->pause_at = (curl_off_t)pause_offset; + } + + if(reuse_easy) { + CURL *easy = curl_easy_init(); + CURLcode rc = CURLE_OK; + if(!easy) { + fprintf(stderr, "failed to init easy handle\n"); + return 1; + } + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + t->easy = easy; + if(setup(t->easy, url, t, http_version, host, share, use_earlydata, + announce_length)) { + fprintf(stderr, "[t-%d] FAILED setup\n", (int)i); + return 1; + } + + fprintf(stderr, "[t-%d] STARTING\n", t->idx); + rc = curl_easy_perform(easy); + fprintf(stderr, "[t-%d] DONE -> %d\n", t->idx, rc); + t->easy = NULL; + curl_easy_reset(easy); + } + curl_easy_cleanup(easy); + } + else { + multi_handle = curl_multi_init(); + curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + + n = (max_parallel < transfer_count) ? max_parallel : transfer_count; + for(i = 0; i < n; ++i) { + t = &transfers[i]; + t->easy = curl_easy_init(); + if(!t->easy || setup(t->easy, url, t, http_version, host, share, + use_earlydata, announce_length)) { + fprintf(stderr, "[t-%d] FAILED setup\n", (int)i); + return 1; + } + curl_multi_add_handle(multi_handle, t->easy); + t->started = 1; + ++active_transfers; + fprintf(stderr, "[t-%d] STARTED\n", t->idx); + } + + do { + int still_running; /* keep number of running handles */ + CURLMcode mc = curl_multi_perform(multi_handle, &still_running); + + if(still_running) { + /* wait for activity, timeout or "nothing" */ + mc = curl_multi_poll(multi_handle, NULL, 0, 1000, NULL); + } + + if(mc) + break; + + do { + int msgq = 0; + m = curl_multi_info_read(multi_handle, &msgq); + if(m && (m->msg == CURLMSG_DONE)) { + CURL *e = m->easy_handle; + --active_transfers; + curl_multi_remove_handle(multi_handle, e); + t = get_transfer_for_easy(e); + if(t) { + t->done = 1; + fprintf(stderr, "[t-%d] FINISHED\n", t->idx); + if(use_earlydata) { + curl_off_t sent; + curl_easy_getinfo(e, CURLINFO_EARLYDATA_SENT_T, &sent); + fprintf(stderr, "[t-%d] EarlyData: %ld\n", t->idx, (long)sent); + } + } + else { + curl_easy_cleanup(e); + fprintf(stderr, "unknown FINISHED???\n"); + } + } + + + /* nothing happening, maintenance */ + if(abort_paused) { + /* abort paused transfers */ + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->done && t->paused && t->easy) { + curl_multi_remove_handle(multi_handle, t->easy); + t->done = 1; + active_transfers--; + fprintf(stderr, "[t-%d] ABORTED\n", t->idx); + } + } + } + else { + /* resume one paused transfer */ + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->done && t->paused) { + t->resumed = 1; + t->paused = 0; + curl_easy_pause(t->easy, CURLPAUSE_CONT); + fprintf(stderr, "[t-%d] RESUMED\n", t->idx); + break; + } + } + } + + while(active_transfers < max_parallel) { + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(!t->started) { + t->easy = curl_easy_init(); + if(!t->easy || setup(t->easy, url, t, http_version, host, + share, use_earlydata, announce_length)) { + fprintf(stderr, "[t-%d] FAILED setup\n", (int)i); + return 1; + } + curl_multi_add_handle(multi_handle, t->easy); + t->started = 1; + ++active_transfers; + fprintf(stderr, "[t-%d] STARTED\n", t->idx); + break; + } + } + /* all started */ + if(i == transfer_count) + break; + } + } while(m); + + } while(active_transfers); /* as long as we have transfers going */ + + curl_multi_cleanup(multi_handle); + } + + for(i = 0; i < transfer_count; ++i) { + t = &transfers[i]; + if(t->out) { + fclose(t->out); + t->out = NULL; + } + if(t->easy) { + curl_easy_cleanup(t->easy); + t->easy = NULL; + } + } + free(transfers); + curl_share_cleanup(share); + + return 0; +#else + (void)argc; + (void)argv; + fprintf(stderr, "Not supported with this compiler.\n"); + return 1; +#endif /* !_MSC_VER */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/tls-session-reuse.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/tls-session-reuse.c new file mode 100644 index 0000000000000000000000000000000000000000..8e8d635597301c3bbb48c0be1a39cb169c484a23 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/tls-session-reuse.c @@ -0,0 +1,311 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * TLS session reuse + * + */ +#include + +#include +#include +#include +/* #include */ +#include + +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +static size_t write_cb(char *ptr, size_t size, size_t nmemb, void *opaque) +{ + (void)ptr; + (void)opaque; + return size * nmemb; +} + +static void add_transfer(CURLM *multi, CURLSH *share, + struct curl_slist *resolve, + const char *url, int http_version) +{ + CURL *easy; + CURLMcode mc; + + easy = curl_easy_init(); + if(!easy) { + fprintf(stderr, "curl_easy_init failed\n"); + exit(1); + } + curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, debug_cb); + curl_easy_setopt(easy, CURLOPT_URL, url); + curl_easy_setopt(easy, CURLOPT_SHARE, share); + curl_easy_setopt(easy, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(easy, CURLOPT_AUTOREFERER, 1L); + curl_easy_setopt(easy, CURLOPT_FAILONERROR, 1L); + curl_easy_setopt(easy, CURLOPT_HTTP_VERSION, http_version); + curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(easy, CURLOPT_WRITEDATA, NULL); + curl_easy_setopt(easy, CURLOPT_HTTPGET, 1L); + curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 0L); + if(resolve) + curl_easy_setopt(easy, CURLOPT_RESOLVE, resolve); + + + mc = curl_multi_add_handle(multi, easy); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_add_handle: %s\n", + curl_multi_strerror(mc)); + exit(1); + } +} + +int main(int argc, char *argv[]) +{ + const char *url; + CURLM *multi; + CURLMcode mc; + int running_handles = 0, numfds; + CURLMsg *msg; + CURLSH *share; + CURLU *cu; + struct curl_slist resolve; + char resolve_buf[1024]; + int msgs_in_queue; + int add_more, waits, ongoing = 0; + char *host, *port; + int http_version = CURL_HTTP_VERSION_1_1; + + if(argc != 3) { + fprintf(stderr, "%s proto URL\n", argv[0]); + exit(2); + } + + if(!strcmp("h2", argv[1])) + http_version = CURL_HTTP_VERSION_2; + else if(!strcmp("h3", argv[1])) + http_version = CURL_HTTP_VERSION_3ONLY; + + url = argv[2]; + cu = curl_url(); + if(!cu) { + fprintf(stderr, "out of memory\n"); + exit(1); + } + if(curl_url_set(cu, CURLUPART_URL, url, 0)) { + fprintf(stderr, "not a URL: '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_HOST, &host, 0)) { + fprintf(stderr, "could not get host of '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_PORT, &port, 0)) { + fprintf(stderr, "could not get port of '%s'\n", url); + exit(1); + } + + memset(&resolve, 0, sizeof(resolve)); + curl_msnprintf(resolve_buf, sizeof(resolve_buf)-1, "%s:%s:127.0.0.1", + host, port); + curl_slist_append(&resolve, resolve_buf); + + multi = curl_multi_init(); + if(!multi) { + fprintf(stderr, "curl_multi_init failed\n"); + exit(1); + } + + share = curl_share_init(); + if(!share) { + fprintf(stderr, "curl_share_init failed\n"); + exit(1); + } + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); + + + add_transfer(multi, share, &resolve, url, http_version); + ++ongoing; + add_more = 6; + waits = 3; + do { + mc = curl_multi_perform(multi, &running_handles); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_perform: %s\n", + curl_multi_strerror(mc)); + exit(1); + } + + if(running_handles) { + mc = curl_multi_poll(multi, NULL, 0, 1000000, &numfds); + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_poll: %s\n", + curl_multi_strerror(mc)); + exit(1); + } + } + + if(waits) { + --waits; + } + else { + while(add_more) { + add_transfer(multi, share, &resolve, url, http_version); + ++ongoing; + --add_more; + } + } + + /* Check for finished handles and remove. */ + /* !checksrc! disable EQUALSNULL 1 */ + while((msg = curl_multi_info_read(multi, &msgs_in_queue)) != NULL) { + if(msg->msg == CURLMSG_DONE) { + long status = 0; + curl_off_t xfer_id; + curl_easy_getinfo(msg->easy_handle, CURLINFO_XFER_ID, &xfer_id); + curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &status); + if(msg->data.result == CURLE_SEND_ERROR || + msg->data.result == CURLE_RECV_ERROR) { + /* We get these if the server had a GOAWAY in transit on + * re-using a connection */ + } + else if(msg->data.result) { + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T + ": failed with %d\n", xfer_id, msg->data.result); + exit(1); + } + else if(status != 200) { + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T + ": wrong http status %ld (expected 200)\n", xfer_id, status); + exit(1); + } + curl_multi_remove_handle(multi, msg->easy_handle); + curl_easy_cleanup(msg->easy_handle); + --ongoing; + fprintf(stderr, "transfer #%" CURL_FORMAT_CURL_OFF_T" retiring " + "(%d now running)\n", xfer_id, running_handles); + } + } + + fprintf(stderr, "running_handles=%d, yet_to_start=%d\n", + running_handles, add_more); + + } while(ongoing || add_more); + + fprintf(stderr, "exiting\n"); + exit(EXIT_SUCCESS); +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/upload-pausing.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/upload-pausing.c new file mode 100644 index 0000000000000000000000000000000000000000..ff68b7bd1450d0b4ed075a0fa1de480b4a50b31e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/upload-pausing.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 + * + ***************************************************************************/ +/* + * upload pausing + * + */ +/* This is based on the PoC client of issue #11769 + */ +#include + +#include +#include +#include + +#ifndef _MSC_VER +/* somewhat Unix-specific */ +#include /* getopt() */ +#endif + +#ifndef _MSC_VER +static void log_line_start(FILE *log, const char *idsbuf, curl_infotype type) +{ + /* + * This is the trace look that is similar to what libcurl makes on its + * own. + */ + static const char * const s_infotype[] = { + "* ", "< ", "> ", "{ ", "} ", "{ ", "} " + }; + if(idsbuf && *idsbuf) + fprintf(log, "%s%s", idsbuf, s_infotype[type]); + else + fputs(s_infotype[type], log); +} + +#define TRC_IDS_FORMAT_IDS_1 "[%" CURL_FORMAT_CURL_OFF_T "-x] " +#define TRC_IDS_FORMAT_IDS_2 "[%" CURL_FORMAT_CURL_OFF_T "-%" \ + CURL_FORMAT_CURL_OFF_T "] " +/* +** callback for CURLOPT_DEBUGFUNCTION +*/ +static int debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userdata) +{ + FILE *output = stderr; + static int newl = 0; + static int traced_data = 0; + char idsbuf[60]; + curl_off_t xfer_id, conn_id; + + (void)handle; /* not used */ + (void)userdata; + + if(!curl_easy_getinfo(handle, CURLINFO_XFER_ID, &xfer_id) && xfer_id >= 0) { + if(!curl_easy_getinfo(handle, CURLINFO_CONN_ID, &conn_id) && + conn_id >= 0) { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_2, xfer_id, + conn_id); + } + else { + curl_msnprintf(idsbuf, sizeof(idsbuf), TRC_IDS_FORMAT_IDS_1, xfer_id); + } + } + else + idsbuf[0] = 0; + + switch(type) { + case CURLINFO_HEADER_OUT: + if(size > 0) { + size_t st = 0; + size_t i; + for(i = 0; i < size - 1; i++) { + if(data[i] == '\n') { /* LF */ + if(!newl) { + log_line_start(output, idsbuf, type); + } + (void)fwrite(data + st, i - st + 1, 1, output); + st = i + 1; + newl = 0; + } + } + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data + st, i - st + 1, 1, output); + } + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_TEXT: + case CURLINFO_HEADER_IN: + if(!newl) + log_line_start(output, idsbuf, type); + (void)fwrite(data, size, 1, output); + newl = (size && (data[size - 1] != '\n')) ? 1 : 0; + traced_data = 0; + break; + case CURLINFO_DATA_OUT: + case CURLINFO_DATA_IN: + case CURLINFO_SSL_DATA_IN: + case CURLINFO_SSL_DATA_OUT: + if(!traced_data) { + if(!newl) + log_line_start(output, idsbuf, type); + fprintf(output, "[%ld bytes data]\n", (long)size); + newl = 0; + traced_data = 1; + } + break; + default: /* nada */ + newl = 0; + traced_data = 1; + break; + } + + return 0; +} + +#define PAUSE_READ_AFTER 1 +static size_t total_read = 0; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, + void *userdata) +{ + (void)size; + (void)nmemb; + (void)userdata; + if(total_read >= PAUSE_READ_AFTER) { + fprintf(stderr, "read_callback, return PAUSE\n"); + return CURL_READFUNC_PAUSE; + } + else { + ptr[0] = '\n'; + ++total_read; + fprintf(stderr, "read_callback, return 1 byte\n"); + return 1; + } +} + +static int progress_callback(void *clientp, + curl_off_t dltotal, + curl_off_t dlnow, + curl_off_t ultotal, + curl_off_t ulnow) +{ + (void)dltotal; + (void)dlnow; + (void)ultotal; + (void)ulnow; + (void)clientp; +#if 0 + /* Used to unpause on progress, but keeping for now. */ + { + CURL *curl = (CURL *)clientp; + curl_easy_pause(curl, CURLPAUSE_CONT); + /* curl_easy_pause(curl, CURLPAUSE_RECV_CONT); */ + } +#endif + return 0; +} + +static int err(void) +{ + fprintf(stderr, "something unexpected went wrong - bailing out!\n"); + exit(2); +} + +static void usage(const char *msg) +{ + if(msg) + fprintf(stderr, "%s\n", msg); + fprintf(stderr, + "usage: [options] url\n" + " upload and pause, options:\n" + " -V http_version (http/1.1, h2, h3) http version to use\n" + ); +} +#endif /* !_MSC_VER */ + +int main(int argc, char *argv[]) +{ +#ifndef _MSC_VER + CURL *curl; + CURLcode rc = CURLE_OK; + CURLU *cu; + struct curl_slist *resolve = NULL; + char resolve_buf[1024]; + char *url, *host = NULL, *port = NULL; + int http_version = CURL_HTTP_VERSION_1_1; + int ch; + + while((ch = getopt(argc, argv, "V:")) != -1) { + switch(ch) { + case 'V': { + if(!strcmp("http/1.1", optarg)) + http_version = CURL_HTTP_VERSION_1_1; + else if(!strcmp("h2", optarg)) + http_version = CURL_HTTP_VERSION_2_0; + else if(!strcmp("h3", optarg)) + http_version = CURL_HTTP_VERSION_3ONLY; + else { + usage("invalid http version"); + return 1; + } + break; + } + default: + usage("invalid option"); + return 1; + } + } + argc -= optind; + argv += optind; + + if(argc != 1) { + usage("not enough arguments"); + return 2; + } + url = argv[0]; + + curl_global_init(CURL_GLOBAL_DEFAULT); + curl_global_trace("ids,time"); + + cu = curl_url(); + if(!cu) { + fprintf(stderr, "out of memory\n"); + exit(1); + } + if(curl_url_set(cu, CURLUPART_URL, url, 0)) { + fprintf(stderr, "not a URL: '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_HOST, &host, 0)) { + fprintf(stderr, "could not get host of '%s'\n", url); + exit(1); + } + if(curl_url_get(cu, CURLUPART_PORT, &port, 0)) { + fprintf(stderr, "could not get port of '%s'\n", url); + exit(1); + } + memset(&resolve, 0, sizeof(resolve)); + curl_msnprintf(resolve_buf, sizeof(resolve_buf)-1, "%s:%s:127.0.0.1", + host, port); + resolve = curl_slist_append(resolve, resolve_buf); + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "out of memory\n"); + exit(1); + } + /* We want to use our own read function. */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* It will help us to continue the read function. */ + curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback); + curl_easy_setopt(curl, CURLOPT_XFERINFODATA, curl); + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); + + /* It will help us to ensure that keepalive does not help. */ + curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); + curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 1L); + curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 1L); + curl_easy_setopt(curl, CURLOPT_TCP_KEEPCNT, 1L); + + /* Enable uploading. */ + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + if(curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L) != CURLE_OK || + curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, debug_cb) + != CURLE_OK || + curl_easy_setopt(curl, CURLOPT_RESOLVE, resolve) != CURLE_OK) + err(); + + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, http_version); + + rc = curl_easy_perform(curl); + + if(curl) { + curl_easy_cleanup(curl); + } + + curl_slist_free_all(resolve); + curl_free(host); + curl_free(port); + curl_url_cleanup(cu); + curl_global_cleanup(); + + return (int)rc; +#else + (void)argc; + (void)argv; + fprintf(stderr, "Not supported with this compiler.\n"); + return 1; +#endif /* !_MSC_VER */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-data.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-data.c new file mode 100644 index 0000000000000000000000000000000000000000..6698326dfb8b6a78d9a82d2cc5aa4ff1f83044c8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-data.c @@ -0,0 +1,271 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * WebSockets data echos + * + */ +/* curl stuff */ +#include "curl_setup.h" +#include + +#include +#include +#include + +#ifndef CURL_DISABLE_WEBSOCKETS + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#include +#endif + +static +void dump(const char *text, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stderr, "%s, %lu bytes (0x%lx)\n", + text, (unsigned long)size, (unsigned long)size); + + for(i = 0; i < size; i += width) { + + fprintf(stderr, "%4.4lx: ", (unsigned long)i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stderr, "%02x ", ptr[i + c]); + else + fputs(" ", stderr); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stderr, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stderr); /* newline */ + } +} + +static CURLcode send_binary(CURL *curl, char *buf, size_t buflen) +{ + size_t nwritten; + CURLcode result = + curl_ws_send(curl, buf, buflen, &nwritten, 0, CURLWS_BINARY); + fprintf(stderr, "ws: send_binary(len=%ld) -> %d, %ld\n", + (long)buflen, result, (long)nwritten); + return result; +} + +static CURLcode recv_binary(CURL *curl, char *exp_data, size_t exp_len) +{ + const struct curl_ws_frame *frame; + char recvbuf[256]; + size_t r_offset, nread; + CURLcode result; + + fprintf(stderr, "recv_binary: expected payload %ld bytes\n", (long)exp_len); + r_offset = 0; + while(1) { + result = curl_ws_recv(curl, recvbuf, sizeof(recvbuf), &nread, &frame); + if(result == CURLE_AGAIN) { + fprintf(stderr, "EAGAIN, sleep, try again\n"); +#ifdef _WIN32 + Sleep(100); +#else + usleep(100*1000); +#endif + continue; + } + fprintf(stderr, "ws: curl_ws_recv(offset=%ld, len=%ld) -> %d, %ld\n", + (long)r_offset, (long)sizeof(recvbuf), result, (long)nread); + if(result) { + return result; + } + if(!(frame->flags & CURLWS_BINARY)) { + fprintf(stderr, "recv_data: wrong frame, got %ld bytes rflags %x\n", + (long)nread, frame->flags); + return CURLE_RECV_ERROR; + } + if(frame->offset != (curl_off_t)r_offset) { + fprintf(stderr, "recv_data: frame offset, expected %ld, got %ld\n", + (long)r_offset, (long)frame->offset); + return CURLE_RECV_ERROR; + } + if(frame->bytesleft != (curl_off_t)(exp_len - r_offset - nread)) { + fprintf(stderr, "recv_data: frame bytesleft, expected %ld, got %ld\n", + (long)(exp_len - r_offset - nread), (long)frame->bytesleft); + return CURLE_RECV_ERROR; + } + if(r_offset + nread > exp_len) { + fprintf(stderr, "recv_data: data length, expected %ld, now at %ld\n", + (long)exp_len, (long)(r_offset + nread)); + return CURLE_RECV_ERROR; + } + if(memcmp(exp_data + r_offset, recvbuf, nread)) { + fprintf(stderr, "recv_data: data differs, offset=%ld, len=%ld\n", + (long)r_offset, (long)nread); + dump("expected:", (unsigned char *)exp_data + r_offset, nread, 0); + dump("received:", (unsigned char *)recvbuf, nread, 0); + return CURLE_RECV_ERROR; + } + r_offset += nread; + if(r_offset >= exp_len) { + fprintf(stderr, "recv_data: frame complete\n"); + break; + } + } + return CURLE_OK; +} + +/* just close the connection */ +static void websocket_close(CURL *curl) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, "", 0, &sent, 0, CURLWS_CLOSE); + fprintf(stderr, + "ws: curl_ws_send returned %u, sent %u\n", (int)result, (int)sent); +} + +static CURLcode data_echo(CURL *curl, size_t plen_min, size_t plen_max) +{ + CURLcode res = CURLE_OK; + size_t len; + char *send_buf; + size_t i; + + send_buf = calloc(1, plen_max); + if(!send_buf) + return CURLE_OUT_OF_MEMORY; + for(i = 0; i < plen_max; ++i) { + send_buf[i] = (char)('0' + ((int)i % 10)); + } + + for(len = plen_min; len <= plen_max; ++len) { + res = send_binary(curl, send_buf, len); + if(res) + goto out; + res = recv_binary(curl, send_buf, len); + if(res) { + fprintf(stderr, "recv_data(len=%ld) -> %d\n", (long)len, res); + goto out; + } + } + +out: + if(!res) + websocket_close(curl); + free(send_buf); + return res; +} + +#endif + +int main(int argc, char *argv[]) +{ +#ifndef CURL_DISABLE_WEBSOCKETS + CURL *curl; + CURLcode res = CURLE_OK; + const char *url; + long l1, l2; + size_t plen_min, plen_max; + + + if(argc != 4) { + fprintf(stderr, "usage: ws-data url minlen maxlen\n"); + return 2; + } + url = argv[1]; + l1 = strtol(argv[2], NULL, 10); + if(l1 < 0) { + fprintf(stderr, "minlen must be >= 0, got %ld\n", l1); + return 2; + } + l2 = strtol(argv[3], NULL, 10); + if(l2 < 0) { + fprintf(stderr, "maxlen must be >= 0, got %ld\n", l2); + return 2; + } + plen_min = l1; + plen_max = l2; + if(plen_max < plen_min) { + fprintf(stderr, "maxlen must be >= minlen, got %ld-%ld\n", + (long)plen_min, (long)plen_max); + return 2; + } + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "ws-data"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */ + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %u\n", (int)res); + if(res == CURLE_OK) + res = data_echo(curl, plen_min, plen_max); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return (int)res; + +#else /* !CURL_DISABLE_WEBSOCKETS */ + (void)argc; + (void)argv; + fprintf(stderr, "WebSockets not enabled in libcurl\n"); + return 1; +#endif /* CURL_DISABLE_WEBSOCKETS */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-pingpong.c b/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-pingpong.c new file mode 100644 index 0000000000000000000000000000000000000000..efb01bcd711396ace2e39caacbf2f17a3c787d73 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/clients/ws-pingpong.c @@ -0,0 +1,166 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * WebSockets pingpong + * + */ +/* curl stuff */ +#include "curl_setup.h" +#include + +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#include +#endif + +#ifndef CURL_DISABLE_WEBSOCKETS + +static CURLcode ping(CURL *curl, const char *send_payload) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, send_payload, strlen(send_payload), &sent, 0, + CURLWS_PING); + fprintf(stderr, + "ws: curl_ws_send returned %u, sent %u\n", (int)result, (int)sent); + + return result; +} + +static CURLcode recv_pong(CURL *curl, const char *expected_payload) +{ + size_t rlen; + const struct curl_ws_frame *meta; + char buffer[256]; + CURLcode result = curl_ws_recv(curl, buffer, sizeof(buffer), &rlen, &meta); + if(result) { + fprintf(stderr, "ws: curl_ws_recv returned %u, received %ld\n", + (int)result, (long)rlen); + return result; + } + + if(!(meta->flags & CURLWS_PONG)) { + fprintf(stderr, "recv_pong: wrong frame, got %d bytes rflags %x\n", + (int)rlen, meta->flags); + return CURLE_RECV_ERROR; + } + + fprintf(stderr, "ws: got PONG back\n"); + if(rlen == strlen(expected_payload) && + !memcmp(expected_payload, buffer, rlen)) { + fprintf(stderr, "ws: got the same payload back\n"); + return CURLE_OK; + } + fprintf(stderr, "ws: did NOT get the same payload back\n"); + return CURLE_RECV_ERROR; +} + +/* just close the connection */ +static void websocket_close(CURL *curl) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, "", 0, &sent, 0, CURLWS_CLOSE); + fprintf(stderr, + "ws: curl_ws_send returned %u, sent %u\n", (int)result, (int)sent); +} + +static CURLcode pingpong(CURL *curl, const char *payload) +{ + CURLcode res; + int i; + + res = ping(curl, payload); + if(res) + return res; + for(i = 0; i < 10; ++i) { + fprintf(stderr, "Receive pong\n"); + res = recv_pong(curl, payload); + if(res == CURLE_AGAIN) { +#ifdef _WIN32 + Sleep(100); +#else + usleep(100*1000); +#endif + continue; + } + websocket_close(curl); + return res; + } + websocket_close(curl); + return CURLE_RECV_ERROR; +} + +#endif + +int main(int argc, char *argv[]) +{ +#ifndef CURL_DISABLE_WEBSOCKETS + CURL *curl; + CURLcode res = CURLE_OK; + const char *url, *payload; + + if(argc != 3) { + fprintf(stderr, "usage: ws-pingpong url payload\n"); + return 2; + } + url = argv[1]; + payload = argv[2]; + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "ws-pingpong"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */ + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %u\n", (int)res); + if(res == CURLE_OK) + res = pingpong(curl, payload); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return (int)res; + +#else /* !CURL_DISABLE_WEBSOCKETS */ + (void)argc; + (void)argv; + fprintf(stderr, "WebSockets not enabled in libcurl\n"); + return 1; +#endif /* CURL_DISABLE_WEBSOCKETS */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/config.ini.in b/local-test-curl-delta-01/afc-curl/tests/http/config.ini.in new file mode 100644 index 0000000000000000000000000000000000000000..8475c03b8aeb2d10578f1c20c3317b94e5ddd292 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/config.ini.in @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +[global] + +[httpd] +apxs = @APXS@ +httpd = @HTTPD@ +apachectl = @APACHECTL@ + +[nghttpx] +nghttpx = @HTTPD_NGHTTPX@ + +[caddy] +caddy = @CADDY@ + +[vsftpd] +vsftpd = @VSFTPD@ diff --git a/local-test-curl-delta-01/afc-curl/tests/http/conftest.py b/local-test-curl-delta-01/afc-curl/tests/http/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..b29cf38bb7513e6159348b6f3eec9b136569d5b9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/conftest.py @@ -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 +# +########################################################################### +# +import logging +import os +import sys +import platform +from typing import Generator + +import pytest + +sys.path.append(os.path.join(os.path.dirname(__file__), '.')) + +from testenv import Env, Nghttpx, Httpd, NghttpxQuic, NghttpxFwd + +def pytest_report_header(config): + # Env inits its base properties only once, we can report them here + env = Env() + report = [ + f'Testing curl {env.curl_version()}', + f' platform: {platform.platform()}', + f' curl: Version: {env.curl_version_string()}', + f' curl: Features: {env.curl_features_string()}', + f' curl: Protocols: {env.curl_protocols_string()}', + f' httpd: {env.httpd_version()}, http:{env.http_port} https:{env.https_port}', + f' httpd-proxy: {env.httpd_version()}, http:{env.proxy_port} https:{env.proxys_port}' + ] + if env.have_h3(): + report.extend([ + f' nghttpx: {env.nghttpx_version()}, h3:{env.https_port}' + ]) + if env.has_caddy(): + report.extend([ + f' Caddy: {env.caddy_version()}, http:{env.caddy_http_port} https:{env.caddy_https_port}' + ]) + if env.has_vsftpd(): + report.extend([ + f' VsFTPD: {env.vsftpd_version()}, ftp:{env.ftp_port}, ftps:{env.ftps_port}' + ]) + buildinfo_fn = os.path.join(env.build_dir, 'buildinfo.txt') + if os.path.exists(buildinfo_fn): + with open(buildinfo_fn, 'r') as file_in: + for line in file_in: + line = line.strip() + if line and not line.startswith('#'): + report.extend([line]) + return '\n'.join(report) + +# TODO: remove this and repeat argument everywhere, pytest-repeat can be used to repeat tests +def pytest_generate_tests(metafunc): + if "repeat" in metafunc.fixturenames: + metafunc.parametrize('repeat', [0]) + +@pytest.fixture(scope="package") +def env(pytestconfig) -> Env: + env = Env(pytestconfig=pytestconfig) + level = logging.DEBUG if env.verbose > 0 else logging.INFO + logging.getLogger('').setLevel(level=level) + if not env.curl_has_protocol('http'): + pytest.skip("curl built without HTTP support") + if not env.curl_has_protocol('https'): + pytest.skip("curl built without HTTPS support") + if env.setup_incomplete(): + pytest.skip(env.incomplete_reason()) + + env.setup() + return env + +@pytest.fixture(scope="package", autouse=True) +def log_global_env_facts(record_testsuite_property, env): + record_testsuite_property("http-port", env.http_port) + + +@pytest.fixture(scope='package') +def httpd(env) -> Generator[Httpd, None, None]: + httpd = Httpd(env=env) + if not httpd.exists(): + pytest.skip(f'httpd not found: {env.httpd}') + httpd.clear_logs() + if not httpd.start(): + pytest.fail(f'failed to start httpd: {env.httpd}') + yield httpd + httpd.stop() + + +@pytest.fixture(scope='package') +def nghttpx(env, httpd) -> Generator[Nghttpx, None, None]: + nghttpx = NghttpxQuic(env=env) + if nghttpx.exists() and (env.have_h3() or nghttpx.https_port > 0): + nghttpx.clear_logs() + assert nghttpx.start() + yield nghttpx + nghttpx.stop() + +@pytest.fixture(scope='package') +def nghttpx_fwd(env, httpd) -> Generator[Nghttpx, None, None]: + nghttpx = NghttpxFwd(env=env) + if nghttpx.exists() and (env.have_h3() or nghttpx.https_port > 0): + nghttpx.clear_logs() + assert nghttpx.start() + yield nghttpx + nghttpx.stop() diff --git a/local-test-curl-delta-01/afc-curl/tests/http/requirements.txt b/local-test-curl-delta-01/afc-curl/tests/http/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb0e01383f3eae6692ccc09d3265cb861a29692d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/requirements.txt @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +pytest +cryptography +multipart +websockets +psutil diff --git a/local-test-curl-delta-01/afc-curl/tests/http/scorecard.py b/local-test-curl-delta-01/afc-curl/tests/http/scorecard.py new file mode 100644 index 0000000000000000000000000000000000000000..c675d9c5eec759846a9b238d4e673d07e6ecf449 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/scorecard.py @@ -0,0 +1,860 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import argparse +import json +import logging +import os +import re +import sys +from statistics import mean +from typing import Dict, Any, Optional, List + +from testenv import Env, Httpd, CurlClient, Caddy, ExecResult, NghttpxQuic, RunProfile + +log = logging.getLogger(__name__) + + +class ScoreCardError(Exception): + pass + + +class ScoreCard: + + def __init__(self, env: Env, + protocol: str, + server_descr: str, + server_port: int, + verbose: int, + curl_verbose: int, + download_parallel: int = 0, + server_addr: Optional[str] = None): + self.verbose = verbose + self.env = env + self.protocol = protocol + self.server_descr = server_descr + self.server_addr = server_addr + self.server_port = server_port + self._silent_curl = not curl_verbose + self._download_parallel = download_parallel + + def info(self, msg): + if self.verbose > 0: + sys.stderr.write(msg) + sys.stderr.flush() + + def handshakes(self) -> Dict[str, Any]: + props = {} + sample_size = 5 + self.info('TLS Handshake\n') + for authority in [ + 'curl.se', 'google.com', 'cloudflare.com', 'nghttp2.org' + ]: + self.info(f' {authority}...') + props[authority] = {} + for ipv in ['ipv4', 'ipv6']: + self.info(f'{ipv}...') + c_samples = [] + hs_samples = [] + errors = [] + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + args = [ + '--http3-only' if self.protocol == 'h3' else '--http2', + f'--{ipv}', f'https://{authority}/' + ] + r = curl.run_direct(args=args, with_stats=True) + if r.exit_code == 0 and len(r.stats) == 1: + c_samples.append(r.stats[0]['time_connect']) + hs_samples.append(r.stats[0]['time_appconnect']) + else: + errors.append(f'exit={r.exit_code}') + props[authority][f'{ipv}-connect'] = mean(c_samples) \ + if len(c_samples) else -1 + props[authority][f'{ipv}-handshake'] = mean(hs_samples) \ + if len(hs_samples) else -1 + props[authority][f'{ipv}-errors'] = errors + self.info('ok.\n') + return props + + def _make_docs_file(self, docs_dir: str, fname: str, fsize: int): + fpath = os.path.join(docs_dir, fname) + data1k = 1024*'x' + flen = 0 + with open(fpath, 'w') as fd: + while flen < fsize: + fd.write(data1k) + flen += len(data1k) + return fpath + + def setup_resources(self, server_docs: str, + downloads: Optional[List[int]] = None): + for fsize in downloads: + label = self.fmt_size(fsize) + fname = f'score{label}.data' + self._make_docs_file(docs_dir=server_docs, + fname=fname, fsize=fsize) + self._make_docs_file(docs_dir=server_docs, + fname='reqs10.data', fsize=10*1024) + + def _check_downloads(self, r: ExecResult, count: int): + error = '' + if r.exit_code != 0: + error += f'exit={r.exit_code} ' + if r.exit_code != 0 or len(r.stats) != count: + error += f'stats={len(r.stats)}/{count} ' + fails = [s for s in r.stats if s['response_code'] != 200] + if len(fails) > 0: + error += f'{len(fails)} failed' + return error if len(error) > 0 else None + + def transfer_single(self, url: str, count: int): + sample_size = count + count = 1 + samples = [] + errors = [] + profiles = [] + self.info('single...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_download(urls=[url], alpn_proto=self.protocol, + no_save=True, with_headers=False, + with_profile=True) + err = self._check_downloads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_download'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': 1, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles), + } + + def transfer_serial(self, url: str, count: int): + sample_size = 1 + samples = [] + errors = [] + profiles = [] + url = f'{url}?[0-{count - 1}]' + self.info('serial...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_download(urls=[url], alpn_proto=self.protocol, + no_save=True, + with_headers=False, with_profile=True) + err = self._check_downloads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_download'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': 1, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles), + } + + def transfer_parallel(self, url: str, count: int): + sample_size = 1 + samples = [] + errors = [] + profiles = [] + max_parallel = self._download_parallel if self._download_parallel > 0 else count + url = f'{url}?[0-{count - 1}]' + self.info('parallel...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_download(urls=[url], alpn_proto=self.protocol, + no_save=True, + with_headers=False, + with_profile=True, + extra_args=[ + '--parallel', + '--parallel-max', str(max_parallel) + ]) + err = self._check_downloads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_download'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': max_parallel, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles), + } + + def download_url(self, label: str, url: str, count: int): + self.info(f' {count}x{label}: ') + props = { + 'single': self.transfer_single(url=url, count=10), + } + if count > 1: + props['serial'] = self.transfer_serial(url=url, count=count) + props['parallel'] = self.transfer_parallel(url=url, count=count) + self.info('ok.\n') + return props + + def downloads(self, count: int, fsizes: List[int]) -> Dict[str, Any]: + scores = {} + for fsize in fsizes: + label = self.fmt_size(fsize) + fname = f'score{label}.data' + url = f'https://{self.env.domain1}:{self.server_port}/{fname}' + scores[label] = self.download_url(label=label, url=url, count=count) + return scores + + def _check_uploads(self, r: ExecResult, count: int): + error = '' + if r.exit_code != 0: + error += f'exit={r.exit_code} ' + if r.exit_code != 0 or len(r.stats) != count: + error += f'stats={len(r.stats)}/{count} ' + fails = [s for s in r.stats if s['response_code'] != 200] + if len(fails) > 0: + error += f'{len(fails)} failed' + for f in fails: + error += f'[{f["response_code"]}]' + return error if len(error) > 0 else None + + def upload_single(self, url: str, fpath: str, count: int): + sample_size = count + count = 1 + samples = [] + errors = [] + profiles = [] + self.info('single...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_put(urls=[url], fdata=fpath, alpn_proto=self.protocol, + with_headers=False, with_profile=True) + err = self._check_uploads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_upload'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': 1, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles) if len(profiles) else {}, + } + + def upload_serial(self, url: str, fpath: str, count: int): + sample_size = 1 + samples = [] + errors = [] + profiles = [] + url = f'{url}?id=[0-{count - 1}]' + self.info('serial...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_put(urls=[url], fdata=fpath, alpn_proto=self.protocol, + with_headers=False, with_profile=True) + err = self._check_uploads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_upload'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': 1, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles) if len(profiles) else {}, + } + + def upload_parallel(self, url: str, fpath: str, count: int): + sample_size = 1 + samples = [] + errors = [] + profiles = [] + max_parallel = count + url = f'{url}?id=[0-{count - 1}]' + self.info('parallel...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_put(urls=[url], fdata=fpath, alpn_proto=self.protocol, + with_headers=False, with_profile=True, + extra_args=[ + '--parallel', + '--parallel-max', str(max_parallel) + ]) + err = self._check_uploads(r, count) + if err: + errors.append(err) + else: + total_size = sum([s['size_upload'] for s in r.stats]) + samples.append(total_size / r.duration.total_seconds()) + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'max-parallel': max_parallel, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles) if len(profiles) else {}, + } + + def upload_url(self, label: str, url: str, fpath: str, count: int): + self.info(f' {count}x{label}: ') + props = { + 'single': self.upload_single(url=url, fpath=fpath, count=10), + } + if count > 1: + props['serial'] = self.upload_serial(url=url, fpath=fpath, count=count) + props['parallel'] = self.upload_parallel(url=url, fpath=fpath, count=count) + self.info('ok.\n') + return props + + def uploads(self, count: int, fsizes: List[int]) -> Dict[str, Any]: + scores = {} + url = f'https://{self.env.domain2}:{self.server_port}/curltest/put' + fpaths = {} + for fsize in fsizes: + label = self.fmt_size(fsize) + fname = f'upload{label}.data' + fpaths[label] = self._make_docs_file(docs_dir=self.env.gen_dir, + fname=fname, fsize=fsize) + + for label, fpath in fpaths.items(): + scores[label] = self.upload_url(label=label, url=url, fpath=fpath, + count=count) + return scores + + def do_requests(self, url: str, count: int, max_parallel: int = 1): + sample_size = 1 + samples = [] + errors = [] + profiles = [] + url = f'{url}?[0-{count - 1}]' + extra_args = [ + '-w', '%{response_code},\\n', + ] + if max_parallel > 1: + extra_args.extend([ + '--parallel', '--parallel-max', str(max_parallel) + ]) + self.info(f'{max_parallel}...') + for _ in range(sample_size): + curl = CurlClient(env=self.env, silent=self._silent_curl, + server_addr=self.server_addr) + r = curl.http_download(urls=[url], alpn_proto=self.protocol, no_save=True, + with_headers=False, with_profile=True, + with_stats=False, extra_args=extra_args) + if r.exit_code != 0: + errors.append(f'exit={r.exit_code}') + else: + samples.append(count / r.duration.total_seconds()) + non_200s = 0 + for line in r.stdout.splitlines(): + if not line.startswith('200,'): + non_200s += 1 + if non_200s > 0: + errors.append(f'responses != 200: {non_200s}') + profiles.append(r.profile) + return { + 'count': count, + 'samples': sample_size, + 'speed': mean(samples) if len(samples) else -1, + 'errors': errors, + 'stats': RunProfile.AverageStats(profiles), + } + + def requests_url(self, url: str, count: int): + self.info(f' {url}: ') + props = {} + # 300 is max in curl, see tool_main.h + for m in [1, 6, 25, 50, 100, 300]: + props[str(m)] = self.do_requests(url=url, count=count, max_parallel=m) + self.info('ok.\n') + return props + + def requests(self, req_count) -> Dict[str, Any]: + url = f'https://{self.env.domain1}:{self.server_port}/reqs10.data' + return { + 'count': req_count, + '10KB': self.requests_url(url=url, count=req_count), + } + + def score(self, + handshakes: bool = True, + downloads: Optional[List[int]] = None, + download_count: int = 50, + uploads: Optional[List[int]] = None, + upload_count: int = 50, + req_count=5000, + requests: bool = True): + self.info(f"scoring {self.protocol} against {self.server_descr}\n") + p = {} + if self.protocol == 'h3': + p['name'] = 'h3' + if not self.env.have_h3_curl(): + raise ScoreCardError('curl does not support HTTP/3') + for lib in ['ngtcp2', 'quiche', 'msh3', 'nghttp3']: + if self.env.curl_uses_lib(lib): + p['implementation'] = lib + break + elif self.protocol == 'h2': + p['name'] = 'h2' + if not self.env.have_h2_curl(): + raise ScoreCardError('curl does not support HTTP/2') + for lib in ['nghttp2', 'hyper']: + if self.env.curl_uses_lib(lib): + p['implementation'] = lib + break + elif self.protocol == 'h1' or self.protocol == 'http/1.1': + proto = 'http/1.1' + p['name'] = proto + p['implementation'] = 'hyper' if self.env.curl_uses_lib('hyper')\ + else 'native' + else: + raise ScoreCardError(f"unknown protocol: {self.protocol}") + + if 'implementation' not in p: + raise ScoreCardError(f'did not recognized {p} lib') + p['version'] = Env.curl_lib_version(p['implementation']) + + score = { + 'curl': self.env.curl_fullname(), + 'os': self.env.curl_os(), + 'protocol': p, + 'server': self.server_descr, + } + if handshakes: + score['handshakes'] = self.handshakes() + if downloads and len(downloads) > 0: + score['downloads'] = self.downloads(count=download_count, + fsizes=downloads) + if uploads and len(uploads) > 0: + score['uploads'] = self.uploads(count=upload_count, + fsizes=uploads) + if requests: + score['requests'] = self.requests(req_count=req_count) + self.info("\n") + return score + + def fmt_ms(self, tval): + return f'{int(tval*1000)} ms' if tval >= 0 else '--' + + def fmt_size(self, val): + if val >= (1024*1024*1024): + return f'{val / (1024*1024*1024):0.000f}GB' + elif val >= (1024 * 1024): + return f'{val / (1024*1024):0.000f}MB' + elif val >= 1024: + return f'{val / 1024:0.000f}KB' + else: + return f'{val:0.000f}B' + + def fmt_mbs(self, val): + return f'{val/(1024*1024):0.000f} MB/s' if val >= 0 else '--' + + def fmt_reqs(self, val): + return f'{val:0.000f} r/s' if val >= 0 else '--' + + def print_score(self, score): + print(f'{score["protocol"]["name"].upper()} in {score["curl"]}') + if 'handshakes' in score: + print(f'{"Handshakes":<24} {"ipv4":25} {"ipv6":28}') + print(f' {"Host":<17} {"Connect":>12} {"Handshake":>12} ' + f'{"Connect":>12} {"Handshake":>12} {"Errors":<20}') + for key, val in score["handshakes"].items(): + print(f' {key:<17} {self.fmt_ms(val["ipv4-connect"]):>12} ' + f'{self.fmt_ms(val["ipv4-handshake"]):>12} ' + f'{self.fmt_ms(val["ipv6-connect"]):>12} ' + f'{self.fmt_ms(val["ipv6-handshake"]):>12} ' + f'{"/".join(val["ipv4-errors"] + val["ipv6-errors"]):<20}' + ) + if 'downloads' in score: + # get the key names of all sizes and measurements made + sizes = [] + measures = [] + m_names = {} + mcol_width = 12 + mcol_sw = 17 + for sskey, ssval in score['downloads'].items(): + if isinstance(ssval, str): + continue + if sskey not in sizes: + sizes.append(sskey) + for mkey, mval in score['downloads'][sskey].items(): + if mkey not in measures: + measures.append(mkey) + m_names[mkey] = f'{mkey}({mval["count"]}x{mval["max-parallel"]})' + print(f'Downloads from {score["server"]}') + print(f' {"Size":>8}', end='') + for m in measures: + print(f' {m_names[m]:>{mcol_width}} {"[cpu/rss]":<{mcol_sw}}', end='') + print(f' {"Errors":^20}') + + for size in score['downloads']: + size_score = score['downloads'][size] + print(f' {size:>8}', end='') + errors = [] + for val in size_score.values(): + if 'errors' in val: + errors.extend(val['errors']) + for m in measures: + if m in size_score: + print(f' {self.fmt_mbs(size_score[m]["speed"]):>{mcol_width}}', end='') + s = f'[{size_score[m]["stats"]["cpu"]:>.1f}%'\ + f'/{self.fmt_size(size_score[m]["stats"]["rss"])}]' + print(f' {s:<{mcol_sw}}', end='') + else: + print(' '*mcol_width, end='') + if len(errors): + print(f' {"/".join(errors):<20}') + else: + print(f' {"-":^20}') + + if 'uploads' in score: + # get the key names of all sizes and measurements made + sizes = [] + measures = [] + m_names = {} + mcol_width = 12 + mcol_sw = 17 + for sskey, ssval in score['uploads'].items(): + if isinstance(ssval, str): + continue + if sskey not in sizes: + sizes.append(sskey) + for mkey, mval in ssval.items(): + if mkey not in measures: + measures.append(mkey) + m_names[mkey] = f'{mkey}({mval["count"]}x{mval["max-parallel"]})' + + print(f'Uploads to {score["server"]}') + print(f' {"Size":>8}', end='') + for m in measures: + print(f' {m_names[m]:>{mcol_width}} {"[cpu/rss]":<{mcol_sw}}', end='') + print(f' {"Errors":^20}') + + for size in sizes: + size_score = score['uploads'][size] + print(f' {size:>8}', end='') + errors = [] + for val in size_score.values(): + if 'errors' in val: + errors.extend(val['errors']) + for m in measures: + if m in size_score: + print(f' {self.fmt_mbs(size_score[m]["speed"]):>{mcol_width}}', end='') + stats = size_score[m]["stats"] + if 'cpu' in stats: + s = f'[{stats["cpu"]:>.1f}%/{self.fmt_size(stats["rss"])}]' + else: + s = '[???/???]' + print(f' {s:<{mcol_sw}}', end='') + else: + print(' '*mcol_width, end='') + if len(errors): + print(f' {"/".join(errors):<20}') + else: + print(f' {"-":^20}') + + if 'requests' in score: + sizes = [] + measures = [] + m_names = {} + mcol_width = 9 + mcol_sw = 13 + for sskey, ssval in score['requests'].items(): + if isinstance(ssval, (str, int)): + continue + if sskey not in sizes: + sizes.append(sskey) + for mkey in score['requests'][sskey]: + if mkey not in measures: + measures.append(mkey) + m_names[mkey] = f'{mkey}' + + print('Requests (max parallel) to {score["server"]}') + print(f' {"Size":>6} {"Reqs":>6}', end='') + for m in measures: + print(f' {m_names[m]:>{mcol_width}} {"[cpu/rss]":<{mcol_sw}}', end='') + print(f' {"Errors":^10}') + + for size in sizes: + size_score = score['requests'][size] + count = score['requests']['count'] + print(f' {size:>6} {count:>6}', end='') + errors = [] + for val in size_score.values(): + if 'errors' in val: + errors.extend(val['errors']) + for m in measures: + if m in size_score: + print(f' {self.fmt_reqs(size_score[m]["speed"]):>{mcol_width}}', end='') + s = f'[{size_score[m]["stats"]["cpu"]:>.1f}%'\ + f'/{self.fmt_size(size_score[m]["stats"]["rss"])}]' + print(f' {s:<{mcol_sw}}', end='') + else: + print(' '*mcol_width, end='') + if len(errors): + print(f' {"/".join(errors):<10}') + else: + print(f' {"-":^10}') + + +def parse_size(s): + m = re.match(r'(\d+)(mb|kb|gb)?', s, re.IGNORECASE) + if m is None: + raise Exception(f'unrecognized size: {s}') + size = int(m.group(1)) + if not m.group(2): + pass + elif m.group(2).lower() == 'kb': + size *= 1024 + elif m.group(2).lower() == 'mb': + size *= 1024 * 1024 + elif m.group(2).lower() == 'gb': + size *= 1024 * 1024 * 1024 + return size + + +def main(): + parser = argparse.ArgumentParser(prog='scorecard', description=""" + Run a range of tests to give a scorecard for a HTTP protocol + 'h3' or 'h2' implementation in curl. + """) + parser.add_argument("-v", "--verbose", action='count', default=1, + help="log more output on stderr") + parser.add_argument("-j", "--json", action='store_true', + default=False, help="print json instead of text") + parser.add_argument("-H", "--handshakes", action='store_true', + default=False, help="evaluate handshakes only") + parser.add_argument("-d", "--downloads", action='store_true', + default=False, help="evaluate downloads") + parser.add_argument("--download", action='append', type=str, + default=None, help="evaluate download size") + parser.add_argument("--download-count", action='store', type=int, + default=50, help="perform that many downloads") + parser.add_argument("--download-parallel", action='store', type=int, + default=0, help="perform that many downloads in parallel (default all)") + parser.add_argument("-u", "--uploads", action='store_true', + default=False, help="evaluate uploads") + parser.add_argument("--upload", action='append', type=str, + default=None, help="evaluate upload size") + parser.add_argument("--upload-count", action='store', type=int, + default=50, help="perform that many uploads") + parser.add_argument("-r", "--requests", action='store_true', + default=False, help="evaluate requests") + parser.add_argument("--request-count", action='store', type=int, + default=5000, help="perform that many requests") + parser.add_argument("--httpd", action='store_true', default=False, + help="evaluate httpd server only") + parser.add_argument("--caddy", action='store_true', default=False, + help="evaluate caddy server only") + parser.add_argument("--curl-verbose", action='store_true', + default=False, help="run curl with `-v`") + parser.add_argument("protocol", default='h2', nargs='?', + help="Name of protocol to score") + parser.add_argument("--start-only", action='store_true', default=False, + help="only start the servers") + parser.add_argument("--remote", action='store', type=str, + default=None, help="score against the remote server at :") + args = parser.parse_args() + + if args.verbose > 0: + console = logging.StreamHandler() + console.setLevel(logging.INFO) + console.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) + logging.getLogger('').addHandler(console) + + protocol = args.protocol + handshakes = True + downloads = [1024 * 1024, 10 * 1024 * 1024, 100 * 1024 * 1024] + if args.download is not None: + downloads = [] + for x in args.download: + downloads.extend([parse_size(s) for s in x.split(',')]) + + uploads = [1024 * 1024, 10 * 1024 * 1024, 100 * 1024 * 1024] + if args.upload is not None: + uploads = [] + for x in args.upload: + uploads.extend([parse_size(s) for s in x.split(',')]) + + requests = True + if args.downloads or args.uploads or args.requests or args.handshakes: + handshakes = args.handshakes + if not args.downloads: + downloads = None + if not args.uploads: + uploads = None + requests = args.requests + + test_httpd = protocol != 'h3' + test_caddy = True + if args.caddy or args.httpd: + test_caddy = args.caddy + test_httpd = args.httpd + + rv = 0 + env = Env() + env.setup() + env.test_timeout = None + httpd = None + nghttpx = None + caddy = None + try: + cards = [] + + if args.remote: + m = re.match(r'^(.+):(\d+)$', args.remote) + if m is None: + raise ScoreCardError(f'unable to parse ip:port from --remote {args.remote}') + test_httpd = False + test_caddy = False + remote_addr = m.group(1) + remote_port = int(m.group(2)) + card = ScoreCard(env=env, + protocol=protocol, + server_descr=f'Server at {args.remote}', + server_addr=remote_addr, + server_port=remote_port, + verbose=args.verbose, curl_verbose=args.curl_verbose, + download_parallel=args.download_parallel) + cards.append(card) + + if test_httpd: + httpd = Httpd(env=env) + assert httpd.exists(), \ + f'httpd not found: {env.httpd}' + httpd.clear_logs() + server_docs = httpd.docs_dir + assert httpd.start() + if protocol == 'h3': + nghttpx = NghttpxQuic(env=env) + nghttpx.clear_logs() + assert nghttpx.start() + server_descr = f'nghttpx: https:{env.h3_port} [backend httpd: {env.httpd_version()}, https:{env.https_port}]' + server_port = env.h3_port + else: + server_descr = f'httpd: {env.httpd_version()}, http:{env.http_port} https:{env.https_port}' + server_port = env.https_port + card = ScoreCard(env=env, + protocol=protocol, + server_descr=server_descr, + server_port=server_port, + verbose=args.verbose, curl_verbose=args.curl_verbose, + download_parallel=args.download_parallel) + card.setup_resources(server_docs, downloads) + cards.append(card) + + if test_caddy and env.caddy: + backend = '' + if uploads and httpd is None: + backend = f' [backend httpd: {env.httpd_version()}, http:{env.http_port} https:{env.https_port}]' + httpd = Httpd(env=env) + assert httpd.exists(), \ + f'httpd not found: {env.httpd}' + httpd.clear_logs() + assert httpd.start() + caddy = Caddy(env=env) + caddy.clear_logs() + assert caddy.start() + server_descr = f'Caddy: {env.caddy_version()}, http:{env.caddy_http_port} https:{env.caddy_https_port}{backend}' + server_port = caddy.port + server_docs = caddy.docs_dir + card = ScoreCard(env=env, + protocol=protocol, + server_descr=server_descr, + server_port=server_port, + verbose=args.verbose, curl_verbose=args.curl_verbose, + download_parallel=args.download_parallel) + card.setup_resources(server_docs, downloads) + cards.append(card) + + if args.start_only: + print('started servers:') + for card in cards: + print(f'{card.server_descr}') + sys.stderr.write('press [RETURN] to finish') + sys.stderr.flush() + sys.stdin.readline() + else: + for card in cards: + score = card.score(handshakes=handshakes, + downloads=downloads, + download_count=args.download_count, + uploads=uploads, + upload_count=args.upload_count, + req_count=args.request_count, + requests=requests) + if args.json: + print(json.JSONEncoder(indent=2).encode(score)) + else: + card.print_score(score) + + except ScoreCardError as ex: + sys.stderr.write(f"ERROR: {ex}\n") + rv = 1 + except KeyboardInterrupt: + log.warning("aborted") + rv = 1 + finally: + if caddy: + caddy.stop() + if nghttpx: + nghttpx.stop(wait_dead=False) + if httpd: + httpd.stop() + sys.exit(rv) + + +if __name__ == "__main__": + main() diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_01_basic.py b/local-test-curl-delta-01/afc-curl/tests/http/test_01_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..391c231516b1977fe9b478d850433647cad54353 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_01_basic.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import pytest + +from testenv import Env +from testenv import CurlClient + + +log = logging.getLogger(__name__) + + +class TestBasic: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + + # simple http: GET + def test_01_01_http_get(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url) + r.check_response(http_status=200) + assert r.json['server'] == env.domain1 + + # simple https: GET, any http version + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_01_02_https_get(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.https_port}/data.json' + r = curl.http_get(url=url) + r.check_response(http_status=200) + assert r.json['server'] == env.domain1 + + # simple https: GET, h2 wanted and got + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_01_03_h2_get(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.https_port}/data.json' + r = curl.http_get(url=url, extra_args=['--http2']) + r.check_response(http_status=200, protocol='HTTP/2') + assert r.json['server'] == env.domain1 + + # simple https: GET, h2 unsupported, fallback to h1 + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_01_04_h2_unsupported(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'https://{env.domain2}:{env.https_port}/data.json' + r = curl.http_get(url=url, extra_args=['--http2']) + r.check_response(http_status=200, protocol='HTTP/1.1') + assert r.json['server'] == env.domain2 + + # simple h3: GET, want h3 and get it + @pytest.mark.skipif(condition=not Env.have_h3(), reason="h3 not supported") + def test_01_05_h3_get(self, env: Env, httpd, nghttpx): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.h3_port}/data.json' + r = curl.http_get(url=url, extra_args=['--http3-only']) + r.check_response(http_status=200, protocol='HTTP/3') + assert r.json['server'] == env.domain1 + + # simple download, check connect/handshake timings + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_01_06_timings(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json' + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True) + r.check_stats(http_status=200, count=1, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + assert r.stats[0]['time_connect'] > 0, f'{r.stats[0]}' + assert r.stats[0]['time_appconnect'] > 0, f'{r.stats[0]}' + + # simple https: HEAD + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_01_07_head(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json' + r = curl.http_download(urls=[url], with_stats=True, with_headers=True, + extra_args=['-I']) + r.check_stats(http_status=200, count=1, exitcode=0, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + # got the Conten-Length: header, but did not download anything + assert r.responses[0]['header']['content-length'] == '30', f'{r.responses[0]}' + assert r.stats[0]['size_download'] == 0, f'{r.stats[0]}' + + # http: GET for HTTP/2, see Upgrade:, 101 switch + def test_01_08_h2_upgrade(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, extra_args=['--http2']) + r.check_exit_code(0) + assert len(r.responses) == 2, f'{r.responses}' + assert r.responses[0]['status'] == 101, f'{r.responses[0]}' + assert r.responses[1]['status'] == 200, f'{r.responses[1]}' + assert r.responses[1]['protocol'] == 'HTTP/2', f'{r.responses[1]}' + assert r.json['server'] == env.domain1 + + # http: GET for HTTP/2 with prior knowledge + def test_01_09_h2_prior_knowledge(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, extra_args=['--http2-prior-knowledge']) + r.check_exit_code(0) + assert len(r.responses) == 1, f'{r.responses}' + assert r.response['status'] == 200, f'{r.responsw}' + assert r.response['protocol'] == 'HTTP/2', f'{r.response}' + assert r.json['server'] == env.domain1 diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_02_download.py b/local-test-curl-delta-01/afc-curl/tests/http/test_02_download.py new file mode 100644 index 0000000000000000000000000000000000000000..e7910719b3ebdcddfa9cbc6d6028201c82ecb332 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_02_download.py @@ -0,0 +1,660 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import difflib +import filecmp +import logging +import math +import os +import re +from datetime import timedelta +import pytest + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +class TestDownload: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd): + indir = httpd.docs_dir + env.make_data_file(indir=indir, fname="data-10k", fsize=10*1024) + env.make_data_file(indir=indir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=indir, fname="data-1m", fsize=1024*1024) + env.make_data_file(indir=indir, fname="data-10m", fsize=10*1024*1024) + env.make_data_file(indir=indir, fname="data-50m", fsize=50*1024*1024) + + # download 1 file + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_01_download_1(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json' + r = curl.http_download(urls=[url], alpn_proto=proto) + r.check_response(http_status=200) + + # download 2 files + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_02_download_2(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]' + r = curl.http_download(urls=[url], alpn_proto=proto) + r.check_response(http_status=200, count=2) + + # download 100 files sequentially + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_03_download_sequential(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 10 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(http_status=200, count=count, connect_count=1) + + # download 100 files parallel + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_04_download_parallel(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 10 + max_parallel = 5 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel', '--parallel-max', f'{max_parallel}' + ]) + r.check_response(http_status=200, count=count) + if proto == 'http/1.1': + # http/1.1 parallel transfers will open multiple connections + assert r.total_connects > 1, r.dump_logs() + else: + # http2 parallel transfers will use one connection (common limit is 100) + assert r.total_connects == 1, r.dump_logs() + + # download 500 files sequential + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_05_download_many_sequential(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 shaky here") + count = 200 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(http_status=200, count=count) + if proto == 'http/1.1': + # http/1.1 parallel transfers will open multiple connections + assert r.total_connects > 1, r.dump_logs() + else: + # http2 parallel transfers will use one connection (common limit is 100) + assert r.total_connects == 1, r.dump_logs() + + # download 500 files parallel + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_06_download_many_parallel(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 200 + max_parallel = 50 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[000-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel', '--parallel-max', f'{max_parallel}' + ]) + r.check_response(http_status=200, count=count, connect_count=1) + + # download files parallel, check connection reuse/multiplex + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_07_download_reuse(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 200 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, + with_stats=True, extra_args=[ + '--parallel', '--parallel-max', '200' + ]) + r.check_response(http_status=200, count=count) + # should have used at most 2 connections only (test servers allow 100 req/conn) + # it may be just 1 on slow systems where request are answered faster than + # curl can exhaust the capacity or if curl runs with address-sanitizer speed + assert r.total_connects <= 2, "h2 should use fewer connections here" + + # download files parallel with http/1.1, check connection not reused + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_02_07b_download_reuse(self, env: Env, + httpd, nghttpx, repeat, proto): + count = 6 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, + with_stats=True, extra_args=[ + '--parallel' + ]) + r.check_response(count=count, http_status=200) + # http/1.1 should have used count connections + assert r.total_connects == count, "http/1.1 should use this many connections" + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_08_1MB_serial(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 5 + urln = f'https://{env.authority_for(env.domain1, proto)}/data-1m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200) + + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_09_1MB_parallel(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 5 + urln = f'https://{env.authority_for(env.domain1, proto)}/data-1m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel' + ]) + r.check_response(count=count, http_status=200) + + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + @pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_10_10MB_serial(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 3 + urln = f'https://{env.authority_for(env.domain1, proto)}/data-10m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200) + + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + @pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_11_10MB_parallel(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 3 + urln = f'https://{env.authority_for(env.domain1, proto)}/data-10m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel' + ]) + r.check_response(count=count, http_status=200) + + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_12_head_serial_https(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 5 + urln = f'https://{env.authority_for(env.domain1, proto)}/data-10m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--head' + ]) + r.check_response(count=count, http_status=200) + + @pytest.mark.parametrize("proto", ['h2']) + def test_02_13_head_serial_h2c(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 5 + urln = f'http://{env.domain1}:{env.http_port}/data-10m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--head', '--http2-prior-knowledge', '--fail-early' + ]) + r.check_response(count=count, http_status=200) + + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_14_not_found(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 5 + urln = f'https://{env.authority_for(env.domain1, proto)}/not-found?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel' + ]) + r.check_stats(count=count, http_status=404, exitcode=0, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_02_15_fail_not_found(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 5 + urln = f'https://{env.authority_for(env.domain1, proto)}/not-found?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--fail' + ]) + r.check_stats(count=count, http_status=404, exitcode=22, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + def test_02_20_h2_small_frames(self, env: Env, httpd, repeat): + # Test case to reproduce content corruption as observed in + # https://github.com/curl/curl/issues/10525 + # To reliably reproduce, we need an Apache httpd that supports + # setting smaller frame sizes. This is not released yet, we + # test if it works and back out if not. + httpd.set_extra_config(env.domain1, lines=[ + 'H2MaxDataFrameLen 1024', + ]) + assert httpd.stop() + if not httpd.start(): + # no, not supported, bail out + httpd.set_extra_config(env.domain1, lines=None) + assert httpd.start() + pytest.skip('H2MaxDataFrameLen not supported') + # ok, make 100 downloads with 2 parallel running and they + # are expected to stumble into the issue when using `lib/http2.c` + # from curl 7.88.0 + count = 5 + urln = f'https://{env.authority_for(env.domain1, "h2")}/data-1m?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto="h2", extra_args=[ + '--parallel', '--parallel-max', '2' + ]) + r.check_response(count=count, http_status=200) + srcfile = os.path.join(httpd.docs_dir, 'data-1m') + self.check_downloads(curl, srcfile, count) + # restore httpd defaults + httpd.set_extra_config(env.domain1, lines=None) + assert httpd.stop() + assert httpd.start() + + # download via lib client, 1 at a time, pause/resume at different offsets + @pytest.mark.parametrize("pause_offset", [0, 10*1024, 100*1023, 640000]) + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_21_lib_serial(self, env: Env, httpd, nghttpx, proto, pause_offset, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + docname = 'data-10m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-P', f'{pause_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + self.check_downloads(client, srcfile, count) + + # download via lib client, several at a time, pause/resume + @pytest.mark.parametrize("pause_offset", [100*1023]) + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_22_lib_parallel_resume(self, env: Env, httpd, nghttpx, proto, pause_offset, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + max_parallel = 5 + docname = 'data-10m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-m', f'{max_parallel}', + '-P', f'{pause_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + self.check_downloads(client, srcfile, count) + + # download, several at a time, pause and abort paused + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_23a_lib_abort_paused(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_ossl_quic(): + pytest.skip('OpenSSL QUIC fails here') + if proto == 'h3' and env.ci_run and env.curl_uses_lib('quiche'): + pytest.skip("fails in CI, but works locally for unknown reasons") + count = 10 + max_parallel = 5 + if proto in ['h2', 'h3']: + pause_offset = 64 * 1024 + else: + pause_offset = 12 * 1024 + docname = 'data-1m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-m', f'{max_parallel}', '-a', + '-P', f'{pause_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + # downloads should be there, but not necessarily complete + self.check_downloads(client, srcfile, count, complete=False) + + # download, several at a time, abort after n bytes + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_23b_lib_abort_offset(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_ossl_quic(): + pytest.skip('OpenSSL QUIC fails here') + if proto == 'h3' and env.ci_run and env.curl_uses_lib('quiche'): + pytest.skip("fails in CI, but works locally for unknown reasons") + count = 10 + max_parallel = 5 + if proto in ['h2', 'h3']: + abort_offset = 64 * 1024 + else: + abort_offset = 12 * 1024 + docname = 'data-1m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-m', f'{max_parallel}', '-a', + '-A', f'{abort_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + # downloads should be there, but not necessarily complete + self.check_downloads(client, srcfile, count, complete=False) + + # download, several at a time, abort after n bytes + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_23c_lib_fail_offset(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_ossl_quic(): + pytest.skip('OpenSSL QUIC fails here') + if proto == 'h3' and env.ci_run and env.curl_uses_lib('quiche'): + pytest.skip("fails in CI, but works locally for unknown reasons") + count = 10 + max_parallel = 5 + if proto in ['h2', 'h3']: + fail_offset = 64 * 1024 + else: + fail_offset = 12 * 1024 + docname = 'data-1m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-m', f'{max_parallel}', '-a', + '-F', f'{fail_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + # downloads should be there, but not necessarily complete + self.check_downloads(client, srcfile, count, complete=False) + + # speed limited download + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_24_speed_limit(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + url = f'https://{env.authority_for(env.domain1, proto)}/data-1m' + curl = CurlClient(env=env) + speed_limit = 384 * 1024 + min_duration = math.floor((1024 * 1024)/speed_limit) + r = curl.http_download(urls=[url], alpn_proto=proto, extra_args=[ + '--limit-rate', f'{speed_limit}' + ]) + r.check_response(count=count, http_status=200) + assert r.duration > timedelta(seconds=min_duration), \ + f'rate limited transfer should take more than {min_duration}s, '\ + f'not {r.duration}' + + # make extreme parallel h2 upgrades, check invalid conn reuse + # before protocol switch has happened + def test_02_25_h2_upgrade_x(self, env: Env, httpd, repeat): + url = f'http://localhost:{env.http_port}/data-100k' + client = LocalClient(name='h2-upgrade-extreme', env=env, timeout=15) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[url]) + assert r.exit_code == 0, f'{client.dump_logs()}' + + # Special client that tests TLS session reuse in parallel transfers + # TODO: just uses a single connection for h2/h3. Not sure how to prevent that + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_26_session_shared_reuse(self, env: Env, proto, httpd, nghttpx, repeat): + url = f'https://{env.authority_for(env.domain1, proto)}/data-100k' + client = LocalClient(name='tls-session-reuse', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[proto, url]) + r.check_exit_code(0) + + # test on paused transfers, based on issue #11982 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_27a_paused_no_cl(self, env: Env, httpd, nghttpx, proto, repeat): + url = f'https://{env.authority_for(env.domain1, proto)}' \ + '/curltest/tweak/?&chunks=6&chunk_size=8000' + client = LocalClient(env=env, name='h2-pausing') + r = client.run(args=['-V', proto, url]) + r.check_exit_code(0) + + # test on paused transfers, based on issue #11982 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_27b_paused_no_cl(self, env: Env, httpd, nghttpx, proto, repeat): + url = f'https://{env.authority_for(env.domain1, proto)}' \ + '/curltest/tweak/?error=502' + client = LocalClient(env=env, name='h2-pausing') + r = client.run(args=['-V', proto, url]) + r.check_exit_code(0) + + # test on paused transfers, based on issue #11982 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_27c_paused_no_cl(self, env: Env, httpd, nghttpx, proto, repeat): + url = f'https://{env.authority_for(env.domain1, proto)}' \ + '/curltest/tweak/?status=200&chunks=1&chunk_size=100' + client = LocalClient(env=env, name='h2-pausing') + r = client.run(args=['-V', proto, url]) + r.check_exit_code(0) + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_28_get_compressed(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + urln = f'https://{env.authority_for(env.domain1brotli, proto)}/data-100k?[0-{count-1}]' + curl = CurlClient(env=env) + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--compressed' + ]) + r.check_exit_code(code=0) + r.check_response(count=count, http_status=200) + + def check_downloads(self, client, srcfile: str, count: int, + complete: bool = True): + for i in range(count): + dfile = client.download_file(i) + assert os.path.exists(dfile) + if complete and not filecmp.cmp(srcfile, dfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dfile).readlines(), + fromfile=srcfile, + tofile=dfile, + n=1)) + assert False, f'download {dfile} differs:\n{diff}' + + # download via lib client, 1 at a time, pause/resume at different offsets + @pytest.mark.parametrize("pause_offset", [0, 10*1024, 100*1023, 640000]) + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_29_h2_lib_serial(self, env: Env, httpd, nghttpx, proto, pause_offset, repeat): + count = 2 + docname = 'data-10m' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-P', f'{pause_offset}', '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + self.check_downloads(client, srcfile, count) + + # download parallel with prior knowledge + def test_02_30_parallel_prior_knowledge(self, env: Env, httpd): + count = 3 + curl = CurlClient(env=env) + urln = f'http://{env.domain1}:{env.http_port}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], extra_args=[ + '--parallel', '--http2-prior-knowledge' + ]) + r.check_response(http_status=200, count=count) + assert r.total_connects == 1, r.dump_logs() + + # download parallel with h2 "Upgrade:" + def test_02_31_parallel_upgrade(self, env: Env, httpd, nghttpx): + count = 3 + curl = CurlClient(env=env) + urln = f'http://{env.domain1}:{env.http_port}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], extra_args=[ + '--parallel', '--http2' + ]) + r.check_response(http_status=200, count=count) + # we see 3 connections, because Apache only every serves a single + # request via Upgrade: and then closed the connection. + assert r.total_connects == 3, r.dump_logs() + + # nghttpx is the only server we have that supports TLS early data + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_02_32_earlydata(self, env: Env, httpd, nghttpx, proto): + if not env.curl_uses_lib('gnutls'): + pytest.skip('TLS earlydata only implemented in GnuTLS') + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + docname = 'data-10k' + # we want this test to always connect to nghttpx, since it is + # the only server we have that supports TLS earlydata + port = env.port_for(proto) + if proto != 'h3': + port = env.nghttpx_https_port + url = f'https://{env.domain1}:{port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', + '-e', # use TLS earlydata + '-f', # forbid reuse of connections + '-r', f'{env.domain1}:{port}:127.0.0.1', + '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + self.check_downloads(client, srcfile, count) + # check that TLS earlydata worked as expected + earlydata = {} + reused_session = False + for line in r.trace_lines: + m = re.match(r'^\[t-(\d+)] EarlyData: (\d+)', line) + if m: + earlydata[int(m.group(1))] = int(m.group(2)) + continue + m = re.match(r'\[1-1] \* SSL reusing session.*', line) + if m: + reused_session = True + assert reused_session, 'session was not reused for 2nd transfer' + assert earlydata[0] == 0, f'{earlydata}' + if proto == 'http/1.1': + assert earlydata[1] == 69, f'{earlydata}' + elif proto == 'h2': + assert earlydata[1] == 107, f'{earlydata}' + elif proto == 'h3': + # not implemented + assert earlydata[1] == 0, f'{earlydata}' + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("max_host_conns", [0, 1, 5]) + def test_02_33_max_host_conns(self, env: Env, httpd, nghttpx, proto, max_host_conns): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 100 + max_parallel = 100 + docname = 'data-10k' + port = env.port_for(proto) + url = f'https://{env.domain1}:{port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', + '-m', f'{max_parallel}', + '-x', # always use a fresh connection + '-M', str(max_host_conns), # limit conns per host + '-r', f'{env.domain1}:{port}:127.0.0.1', + '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(httpd.docs_dir, docname) + self.check_downloads(client, srcfile, count) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_03_goaway.py b/local-test-curl-delta-01/afc-curl/tests/http/test_03_goaway.py new file mode 100644 index 0000000000000000000000000000000000000000..26d57bbe32db480835d8afd4536ededbfea12bb3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_03_goaway.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import time +from datetime import timedelta +from threading import Thread +import pytest + +from testenv import Env, CurlClient, ExecResult + + +log = logging.getLogger(__name__) + + +class TestGoAway: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + # download files sequentially with delay, reload server for GOAWAY + def test_03_01_h2_goaway(self, env: Env, httpd, nghttpx, repeat): + proto = 'h2' + count = 3 + self.r = None + def long_run(): + curl = CurlClient(env=env) + # send 10 chunks of 1024 bytes in a response body with 100ms delay in between + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=10&chunk_size=1024&chunk_delay=100ms' + self.r = curl.http_download(urls=[urln], alpn_proto=proto) + + t = Thread(target=long_run) + t.start() + # each request will take a second, reload the server in the middle + # of the first one. + time.sleep(1.5) + assert httpd.reload() + t.join() + r: ExecResult = self.r + r.check_response(count=count, http_status=200) + # reload will shut down the connection gracefully with GOAWAY + # we expect to see a second connection opened afterwards + assert r.total_connects == 2 + for idx, s in enumerate(r.stats): + if s['num_connects'] > 0: + log.debug(f'request {idx} connected') + # this should take `count` seconds to retrieve + assert r.duration >= timedelta(seconds=count) + + # download files sequentially with delay, reload server for GOAWAY + @pytest.mark.skipif(condition=not Env.have_h3(), reason="h3 not supported") + def test_03_02_h3_goaway(self, env: Env, httpd, nghttpx, repeat): + proto = 'h3' + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + if proto == 'h3' and env.curl_uses_ossl_quic(): + pytest.skip('OpenSSL QUIC fails here') + count = 3 + self.r = None + def long_run(): + curl = CurlClient(env=env) + # send 10 chunks of 1024 bytes in a response body with 100ms delay in between + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=10&chunk_size=1024&chunk_delay=100ms' + self.r = curl.http_download(urls=[urln], alpn_proto=proto) + + t = Thread(target=long_run) + t.start() + # each request will take a second, reload the server in the middle + # of the first one. + time.sleep(1.5) + assert nghttpx.reload(timeout=timedelta(seconds=2)) + t.join() + r: ExecResult = self.r + # this should take `count` seconds to retrieve, maybe a little less + assert r.duration >= timedelta(seconds=count-1) + r.check_response(count=count, http_status=200, connect_count=2) + # reload will shut down the connection gracefully with GOAWAY + # we expect to see a second connection opened afterwards + for idx, s in enumerate(r.stats): + if s['num_connects'] > 0: + log.debug(f'request {idx} connected') + + # download files sequentially with delay, reload server for GOAWAY + def test_03_03_h1_goaway(self, env: Env, httpd, nghttpx, repeat): + proto = 'http/1.1' + count = 3 + self.r = None + def long_run(): + curl = CurlClient(env=env) + # send 10 chunks of 1024 bytes in a response body with 100ms delay in between + # pause 2 seconds between requests + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=10&chunk_size=1024&chunk_delay=100ms' + self.r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--rate', '30/m', + ]) + + t = Thread(target=long_run) + t.start() + # each request will take a second, reload the server in the middle + # of the first one. + time.sleep(1.5) + assert httpd.reload() + t.join() + r: ExecResult = self.r + r.check_response(count=count, http_status=200, connect_count=2) + # reload will shut down the connection gracefully + # we expect to see a second connection opened afterwards + for idx, s in enumerate(r.stats): + if s['num_connects'] > 0: + log.debug(f'request {idx} connected') + # this should take `count` seconds to retrieve + assert r.duration >= timedelta(seconds=count) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_04_stuttered.py b/local-test-curl-delta-01/afc-curl/tests/http/test_04_stuttered.py new file mode 100644 index 0000000000000000000000000000000000000000..c5463cc9432f1a42742dfe42caf024e6c42b037b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_04_stuttered.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +from typing import Tuple, List, Dict +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") +@pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") +class TestStuttered: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + # download 1 file, check that delayed response works in general + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_04_01_download_1(self, env: Env, httpd, nghttpx, repeat, + proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=100&chunk_size=100&chunk_delay=10ms' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=1, http_status=200) + + # download 50 files in 100 chunks a 100 bytes with 10ms delay between + # prepend 100 file requests to warm up connection processing limits + # (Apache2 increases # of parallel processed requests after successes) + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_04_02_100_100_10(self, env: Env, + httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 50 + warmups = 100 + curl = CurlClient(env=env) + url1 = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{warmups-1}]' + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count-1}]'\ + '&chunks=100&chunk_size=100&chunk_delay=10ms' + r = curl.http_download(urls=[url1, urln], alpn_proto=proto, + extra_args=['--parallel']) + r.check_response(count=warmups+count, http_status=200) + assert r.total_connects == 1 + t_avg, i_min, t_min, i_max, t_max = self.stats_spread(r.stats[warmups:], 'time_total') + if t_max < (5 * t_min) and t_min < 2: + log.warning(f'avg time of transfer: {t_avg} [{i_min}={t_min}, {i_max}={t_max}]') + + # download 50 files in 1000 chunks a 10 bytes with 1ms delay between + # prepend 100 file requests to warm up connection processing limits + # (Apache2 increases # of parallel processed requests after successes) + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_04_03_1000_10_1(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 50 + warmups = 100 + curl = CurlClient(env=env) + url1 = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{warmups-1}]' + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=1000&chunk_size=10&chunk_delay=100us' + r = curl.http_download(urls=[url1, urln], alpn_proto=proto, + extra_args=['--parallel']) + r.check_response(count=warmups+count, http_status=200) + assert r.total_connects == 1 + t_avg, i_min, t_min, i_max, t_max = self.stats_spread(r.stats[warmups:], 'time_total') + if t_max < (5 * t_min): + log.warning(f'avg time of transfer: {t_avg} [{i_min}={t_min}, {i_max}={t_max}]') + + # download 50 files in 10000 chunks a 1 byte with 10us delay between + # prepend 100 file requests to warm up connection processing limits + # (Apache2 increases # of parallel processed requests after successes) + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_04_04_1000_10_1(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 50 + warmups = 100 + curl = CurlClient(env=env) + url1 = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{warmups-1}]' + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=10000&chunk_size=1&chunk_delay=50us' + r = curl.http_download(urls=[url1, urln], alpn_proto=proto, + extra_args=['--parallel']) + r.check_response(count=warmups+count, http_status=200) + assert r.total_connects == 1 + t_avg, i_min, t_min, i_max, t_max = self.stats_spread(r.stats[warmups:], 'time_total') + if t_max < (5 * t_min): + log.warning(f'avg time of transfer: {t_avg} [{i_min}={t_min}, {i_max}={t_max}]') + + def stats_spread(self, stats: List[Dict], key: str) -> Tuple[float, int, float, int, float]: + stotals = 0.0 + s_min = 100.0 + i_min = -1 + s_max = 0.0 + i_max = -1 + for idx, s in enumerate(stats): + val = float(s[key]) + stotals += val + if val > s_max: + s_max = val + i_max = idx + if val < s_min: + s_min = val + i_min = idx + return stotals/len(stats), i_min, s_min, i_max, s_max diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_05_errors.py b/local-test-curl-delta-01/afc-curl/tests/http/test_05_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a496d6d8b5c1345c4eb740e71a303cc4cbc6f746 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_05_errors.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.httpd_is_at_least('2.4.55'), + reason=f"httpd version too old for this: {Env.httpd_version()}") +class TestErrors: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + # download 1 file, check that we get CURLE_PARTIAL_FILE + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_05_01_partial_1(self, env: Env, httpd, nghttpx, repeat, + proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 1 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=3&chunk_size=16000&body_error=reset' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--retry', '0' + ]) + r.check_exit_code(False) + invalid_stats = [] + for idx, s in enumerate(r.stats): + if 'exitcode' not in s or s['exitcode'] not in [18, 56, 92, 95]: + invalid_stats.append(f'request {idx} exit with {s["exitcode"]}') + assert len(invalid_stats) == 0, f'failed: {invalid_stats}' + + # download files, check that we get CURLE_PARTIAL_FILE for all + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_05_02_partial_20(self, env: Env, httpd, nghttpx, repeat, + proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 20 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}' \ + f'/curltest/tweak?id=[0-{count - 1}]'\ + '&chunks=5&chunk_size=16000&body_error=reset' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--retry', '0', '--parallel', + ]) + r.check_exit_code(False) + assert len(r.stats) == count, f'did not get all stats: {r}' + invalid_stats = [] + for idx, s in enumerate(r.stats): + if 'exitcode' not in s or s['exitcode'] not in [18, 55, 56, 92, 95]: + invalid_stats.append(f'request {idx} exit with {s["exitcode"]}\n{s}') + assert len(invalid_stats) == 0, f'failed: {invalid_stats}' + + # access a resource that, on h2, RST the stream with HTTP_1_1_REQUIRED + def test_05_03_required(self, env: Env, httpd, nghttpx, repeat): + curl = CurlClient(env=env) + proto = 'http/1.1' + urln = f'https://{env.authority_for(env.domain1, proto)}/curltest/1_1' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_exit_code(0) + r.check_response(http_status=200, count=1) + proto = 'h2' + urln = f'https://{env.authority_for(env.domain1, proto)}/curltest/1_1' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_exit_code(0) + r.check_response(http_status=200, count=1) + # check that we did a downgrade + assert r.stats[0]['http_version'] == '1.1', r.dump_logs() + + # On the URL used here, Apache is doing an "unclean" TLS shutdown, + # meaning it sends no shutdown notice and just closes TCP. + # The HTTP response delivers a body without Content-Length. We expect: + # - http/1.0 to fail since it relies on a clean connection close to + # detect the end of the body + # - http/1.1 to work since it will used "chunked" transfer encoding + # and stop receiving when that signals the end + # - h2 to work since it will signal the end of the response before + # and not see the "unclean" close either + @pytest.mark.parametrize("proto", ['http/1.0', 'http/1.1', 'h2']) + def test_05_04_unclean_tls_shutdown(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 10 if proto == 'h2' else 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}'\ + f'/curltest/shutdown_unclean?id=[0-{count-1}]&chunks=4' + r = curl.http_download(urls=[url], alpn_proto=proto, extra_args=[ + '--parallel', + ]) + if proto == 'http/1.0' and not env.curl_uses_lib('wolfssl') and \ + (env.curl_is_debug() or not env.curl_uses_lib('openssl')): + # we are inconsistent if we fail or not in missing TLS shutdown + # openssl code ignore such errors intentionally in non-debug builds + r.check_exit_code(56) + else: + r.check_exit_code(0) + r.check_response(http_status=200, count=count) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_06_eyeballs.py b/local-test-curl-delta-01/afc-curl/tests/http/test_06_eyeballs.py new file mode 100644 index 0000000000000000000000000000000000000000..0c553958d1b2527ac4b65121b507e36637e100f0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_06_eyeballs.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +class TestEyeballs: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + # download using only HTTP/3 on working server + @pytest.mark.skipif(condition=not Env.have_h3(), reason="missing HTTP/3 support") + def test_06_01_h3_only(self, env: Env, httpd, nghttpx, repeat): + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h3")}/data.json' + r = curl.http_download(urls=[urln], extra_args=['--http3-only']) + r.check_response(count=1, http_status=200) + assert r.stats[0]['http_version'] == '3' + + # download using only HTTP/3 on missing server + @pytest.mark.skipif(condition=not Env.have_h3(), reason="missing HTTP/3 support") + def test_06_02_h3_only(self, env: Env, httpd, nghttpx, repeat): + nghttpx.stop_if_running() + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h3")}/data.json' + r = curl.http_download(urls=[urln], extra_args=['--http3-only']) + r.check_response(exitcode=7, http_status=None) + + # download using HTTP/3 on missing server with fallback on h2 + @pytest.mark.skipif(condition=not Env.have_h3(), reason="missing HTTP/3 support") + def test_06_03_h3_fallback_h2(self, env: Env, httpd, nghttpx, repeat): + nghttpx.stop_if_running() + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h3")}/data.json' + r = curl.http_download(urls=[urln], extra_args=['--http3']) + r.check_response(count=1, http_status=200) + assert r.stats[0]['http_version'] == '2' + + # download using HTTP/3 on missing server with fallback on http/1.1 + @pytest.mark.skipif(condition=not Env.have_h3(), reason="missing HTTP/3 support") + def test_06_04_h3_fallback_h1(self, env: Env, httpd, nghttpx, repeat): + nghttpx.stop_if_running() + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain2, "h3")}/data.json' + r = curl.http_download(urls=[urln], extra_args=['--http3']) + r.check_response(count=1, http_status=200) + assert r.stats[0]['http_version'] == '1.1' + + # make a successful https: transfer and observer the timer stats + def test_06_10_stats_success(self, env: Env, httpd, nghttpx, repeat): + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json' + r = curl.http_download(urls=[urln]) + r.check_response(count=1, http_status=200) + assert r.stats[0]['time_connect'] > 0.0 + assert r.stats[0]['time_appconnect'] > 0.0 + + # make https: to a hostname that tcp connects, but will not verify + def test_06_11_stats_fail_verify(self, env: Env, httpd, nghttpx, repeat): + curl = CurlClient(env=env) + urln = f'https://not-valid.com:{env.https_port}/data.json' + r = curl.http_download(urls=[urln], extra_args=[ + '--resolve', f'not-valid.com:{env.https_port}:127.0.0.1' + ]) + r.check_response(count=1, http_status=0, exitcode=False) + assert r.stats[0]['time_connect'] > 0.0 # was tcp connected + assert r.stats[0]['time_appconnect'] == 0 # but not SSL verified + + # make https: to an invalid address + def test_06_12_stats_fail_tcp(self, env: Env, httpd, nghttpx, repeat): + curl = CurlClient(env=env) + urln = 'https://not-valid.com:1/data.json' + r = curl.http_download(urls=[urln], extra_args=[ + '--resolve', f'not-valid.com:{1}:127.0.0.1' + ]) + r.check_response(count=1, http_status=None, exitcode=False) + assert r.stats[0]['time_connect'] == 0 # no one should have listened + assert r.stats[0]['time_appconnect'] == 0 # did not happen either diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_07_upload.py b/local-test-curl-delta-01/afc-curl/tests/http/test_07_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..dcafe7c064e7c99780d1b3edb84267797862ac64 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_07_upload.py @@ -0,0 +1,747 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import difflib +import filecmp +import logging +import os +import re +import pytest +from typing import List + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +class TestUpload: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + env.make_data_file(indir=env.gen_dir, fname="data-10k", fsize=10*1024) + env.make_data_file(indir=env.gen_dir, fname="data-63k", fsize=63*1024) + env.make_data_file(indir=env.gen_dir, fname="data-64k", fsize=64*1024) + env.make_data_file(indir=env.gen_dir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=env.gen_dir, fname="data-1m+", fsize=(1024*1024)+1) + env.make_data_file(indir=env.gen_dir, fname="data-10m", fsize=10*1024*1024) + httpd.clear_extra_configs() + httpd.reload() + + # upload small data, check that this is what was echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_01_upload_1_small(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + data = '0123456789' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto) + r.check_stats(count=1, http_status=200, exitcode=0) + respdata = open(curl.response_file(0)).readlines() + assert respdata == [data] + + # upload large data, check that this is what was echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_02_upload_1_large(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-100k') + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto) + r.check_stats(count=1, http_status=200, exitcode=0) + indata = open(fdata).readlines() + respdata = open(curl.response_file(0)).readlines() + assert respdata == indata + + # upload data sequentially, check that they were echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_10_upload_sequential(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 20 + data = '0123456789' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto) + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == [data] + + # upload data parallel, check that they were echoed + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_07_11_upload_parallel(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + # limit since we use a separate connection in h1 + count = 20 + data = '0123456789' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, + extra_args=['--parallel']) + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == [data] + + # upload large data sequentially, check that this is what was echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_12_upload_seq_large(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + fdata = os.path.join(env.gen_dir, 'data-100k') + count = 10 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto) + r.check_response(count=count, http_status=200) + indata = open(fdata).readlines() + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == indata + + # upload very large data sequentially, check that this is what was echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_13_upload_seq_large(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + fdata = os.path.join(env.gen_dir, 'data-10m') + count = 2 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto) + r.check_stats(count=count, http_status=200, exitcode=0) + indata = open(fdata).readlines() + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == indata + + # upload from stdin, issue #14870 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + @pytest.mark.parametrize("indata", [ + '', '1', '123\n456andsomething\n\n' + ]) + def test_07_14_upload_stdin(self, env: Env, httpd, nghttpx, proto, indata): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-{count-1}]' + r = curl.http_put(urls=[url], data=indata, alpn_proto=proto) + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == [f'{len(indata)}'] + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_15_hx_put(self, env: Env, httpd, nghttpx, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + upload_size = 128*1024 + url = f'https://localhost:{env.https_port}/curltest/put?id=[0-{count-1}]' + client = LocalClient(name='hx-upload', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-S', f'{upload_size}', '-V', proto, url + ]) + r.check_exit_code(0) + self.check_downloads(client, [f"{upload_size}"], count) + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_16_hx_put_reuse(self, env: Env, httpd, nghttpx, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + upload_size = 128*1024 + url = f'https://localhost:{env.https_port}/curltest/put?id=[0-{count-1}]' + client = LocalClient(name='hx-upload', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-S', f'{upload_size}', '-R', '-V', proto, url + ]) + r.check_exit_code(0) + self.check_downloads(client, [f"{upload_size}"], count) + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_17_hx_post_reuse(self, env: Env, httpd, nghttpx, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + upload_size = 128*1024 + url = f'https://localhost:{env.https_port}/curltest/echo?id=[0-{count-1}]' + client = LocalClient(name='hx-upload', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-M', 'POST', '-S', f'{upload_size}', '-R', '-V', proto, url + ]) + r.check_exit_code(0) + self.check_downloads(client, ["x" * upload_size], count) + + # upload data parallel, check that they were echoed + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_07_20_upload_parallel(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + # limit since we use a separate connection in h1 + count = 10 + data = '0123456789' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, + extra_args=['--parallel']) + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == [data] + + # upload large data parallel, check that this is what was echoed + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_07_21_upload_parallel_large(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + fdata = os.path.join(env.gen_dir, 'data-100k') + # limit since we use a separate connection in h1 + count = 10 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, + extra_args=['--parallel']) + r.check_response(count=count, http_status=200) + self.check_download(count, fdata, curl) + + # upload large data parallel to a URL that denies uploads + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_07_22_upload_parallel_fail(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + fdata = os.path.join(env.gen_dir, 'data-10m') + count = 20 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}'\ + f'/curltest/tweak?status=400&delay=5ms&chunks=1&body_error=reset&id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, + extra_args=['--parallel']) + exp_exit = 92 if proto == 'h2' else 95 + r.check_stats(count=count, exitcode=exp_exit) + + # PUT 100k + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_30_put_100k(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-100k') + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-{count-1}]' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, + extra_args=['--parallel']) + r.check_stats(count=count, http_status=200, exitcode=0) + exp_data = [f'{os.path.getsize(fdata)}'] + r.check_response(count=count, http_status=200) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == exp_data + + # PUT 10m + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_31_put_10m(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-10m') + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-{count-1}]&chunk_delay=2ms' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, + extra_args=['--parallel']) + r.check_stats(count=count, http_status=200, exitcode=0) + exp_data = [f'{os.path.getsize(fdata)}'] + r.check_response(count=count, http_status=200) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == exp_data + + # issue #10591 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_32_issue_10591(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-10m') + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-{count-1}]' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto) + r.check_stats(count=count, http_status=200, exitcode=0) + + # issue #11157, upload that is 404'ed by server, needs to terminate + # correctly and not time out on sending + def test_07_33_issue_11157a(self, env: Env, httpd, nghttpx, repeat): + proto = 'h2' + fdata = os.path.join(env.gen_dir, 'data-10m') + # send a POST to our PUT handler which will send immediately a 404 back + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put' + curl = CurlClient(env=env) + r = curl.run_direct(with_stats=True, args=[ + '--resolve', f'{env.authority_for(env.domain1, proto)}:127.0.0.1', + '--cacert', env.ca.cert_file, + '--request', 'POST', + '--max-time', '5', '-v', + '--url', url, + '--form', 'idList=12345678', + '--form', 'pos=top', + '--form', 'name=mr_test', + '--form', f'fileSource=@{fdata};type=application/pdf', + ]) + assert r.exit_code == 0, f'{r}' + r.check_stats(1, 404) + + # issue #11157, send upload that is slowly read in + def test_07_33_issue_11157b(self, env: Env, httpd, nghttpx, repeat): + proto = 'h2' + fdata = os.path.join(env.gen_dir, 'data-10m') + # tell our test PUT handler to read the upload more slowly, so + # that the send buffering and transfer loop needs to wait + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?chunk_delay=2ms' + curl = CurlClient(env=env) + r = curl.run_direct(with_stats=True, args=[ + '--verbose', '--trace-config', 'ids,time', + '--resolve', f'{env.authority_for(env.domain1, proto)}:127.0.0.1', + '--cacert', env.ca.cert_file, + '--request', 'PUT', + '--max-time', '10', '-v', + '--url', url, + '--form', 'idList=12345678', + '--form', 'pos=top', + '--form', 'name=mr_test', + '--form', f'fileSource=@{fdata};type=application/pdf', + ]) + assert r.exit_code == 0, r.dump_logs() + r.check_stats(1, 200) + + def test_07_34_issue_11194(self, env: Env, httpd, nghttpx, repeat): + proto = 'h2' + # tell our test PUT handler to read the upload more slowly, so + # that the send buffering and transfer loop needs to wait + fdata = os.path.join(env.gen_dir, 'data-100k') + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put' + curl = CurlClient(env=env) + r = curl.run_direct(with_stats=True, args=[ + '--verbose', '--trace-config', 'ids,time', + '--resolve', f'{env.authority_for(env.domain1, proto)}:127.0.0.1', + '--cacert', env.ca.cert_file, + '--request', 'PUT', + '--digest', '--user', 'test:test', + '--data-binary', f'@{fdata}', + '--url', url, + ]) + assert r.exit_code == 0, r.dump_logs() + r.check_stats(1, 200) + + # upload large data on a h1 to h2 upgrade + def test_07_35_h1_h2_upgrade_upload(self, env: Env, httpd, nghttpx, repeat): + fdata = os.path.join(env.gen_dir, 'data-100k') + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', extra_args=[ + '--http2' + ]) + r.check_response(count=1, http_status=200) + # apache does not Upgrade on request with a body + assert r.stats[0]['http_version'] == '1.1', f'{r}' + indata = open(fdata).readlines() + respdata = open(curl.response_file(0)).readlines() + assert respdata == indata + + # upload to a 301,302,303 response + @pytest.mark.parametrize("redir", ['301', '302', '303']) + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_36_upload_30x(self, env: Env, httpd, nghttpx, repeat, redir, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + data = '0123456789' * 10 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo{redir}?id=[0-0]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, extra_args=[ + '-L', '--trace-config', 'http/2,http/3' + ]) + r.check_response(count=1, http_status=200) + respdata = open(curl.response_file(0)).readlines() + assert respdata == [] # was transformed to a GET + + # upload to a 307 response + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_37_upload_307(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + data = '0123456789' * 10 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo307?id=[0-0]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, extra_args=[ + '-L', '--trace-config', 'http/2,http/3' + ]) + r.check_response(count=1, http_status=200) + respdata = open(curl.response_file(0)).readlines() + assert respdata == [data] # was POST again + + # POST form data, yet another code path in transfer + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_38_form_small(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_form(urls=[url], alpn_proto=proto, form={ + 'name1': 'value1', + }) + r.check_stats(count=1, http_status=200, exitcode=0) + + # POST data urlencoded, small enough to be sent with request headers + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_39_post_urlenc_small(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-63k') + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, extra_args=[ + '--trace-config', 'http/2,http/3' + ]) + r.check_stats(count=1, http_status=200, exitcode=0) + indata = open(fdata).readlines() + respdata = open(curl.response_file(0)).readlines() + assert respdata == indata + + # POST data urlencoded, large enough to be sent separate from request headers + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_40_post_urlenc_large(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-64k') + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, extra_args=[ + '--trace-config', 'http/2,http/3' + ]) + r.check_stats(count=1, http_status=200, exitcode=0) + indata = open(fdata).readlines() + respdata = open(curl.response_file(0)).readlines() + assert respdata == indata + + # POST data urlencoded, small enough to be sent with request headers + # and request headers are so large that the first send is larger + # than our default upload buffer length (64KB). + # Unfixed, this will fail when run with CURL_DBG_SOCK_WBLOCK=80 most + # of the time + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_41_post_urlenc_small(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + if proto == 'h3' and env.curl_uses_lib('quiche'): + pytest.skip("quiche has CWND issues with large requests") + fdata = os.path.join(env.gen_dir, 'data-63k') + curl = CurlClient(env=env) + extra_args = ['--trace-config', 'http/2,http/3'] + # add enough headers so that the first send chunk is > 64KB + for i in range(63): + extra_args.extend(['-H', f'x{i:02d}: {"y"*1019}']) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, extra_args=extra_args) + r.check_stats(count=1, http_status=200, exitcode=0) + indata = open(fdata).readlines() + respdata = open(curl.response_file(0)).readlines() + assert respdata == indata + + def check_download(self, count, srcfile, curl): + for i in range(count): + dfile = curl.download_file(i) + assert os.path.exists(dfile) + if not filecmp.cmp(srcfile, dfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dfile).readlines(), + fromfile=srcfile, + tofile=dfile, + n=1)) + assert False, f'download {dfile} differs:\n{diff}' + + # upload data, pause, let connection die with an incomplete response + # issues #11769 #13260 + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_42a_upload_disconnect(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + client = LocalClient(name='upload-pausing', env=env, timeout=60) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]&die_after=0' + r = client.run(['-V', proto, url]) + if r.exit_code == 18: # PARTIAL_FILE is always ok + pass + elif proto == 'h2': + r.check_exit_code(92) # CURLE_HTTP2_STREAM also ok + elif proto == 'h3': + r.check_exit_code(95) # CURLE_HTTP3 also ok + else: + r.check_exit_code(18) # will fail as it should + + # upload data, pause, let connection die without any response at all + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_42b_upload_disconnect(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + client = LocalClient(name='upload-pausing', env=env, timeout=60) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]&just_die=1' + r = client.run(['-V', proto, url]) + exp_code = 52 # GOT_NOTHING + if proto == 'h2' or proto == 'h3': + exp_code = 0 # we get a 500 from the server + r.check_exit_code(exp_code) # GOT_NOTHING + + # upload data, pause, let connection die after 100 continue + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_42c_upload_disconnect(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + client = LocalClient(name='upload-pausing', env=env, timeout=60) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]&die_after_100=1' + r = client.run(['-V', proto, url]) + exp_code = 52 # GOT_NOTHING + if proto == 'h2' or proto == 'h3': + exp_code = 0 # we get a 500 from the server + r.check_exit_code(exp_code) # GOT_NOTHING + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_43_upload_denied(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 fails here") + fdata = os.path.join(env.gen_dir, 'data-10m') + count = 1 + max_upload = 128 * 1024 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?'\ + f'id=[0-{count-1}]&max_upload={max_upload}' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, + extra_args=['--trace-config', 'all']) + r.check_stats(count=count, http_status=413, exitcode=0) + + # speed limited on put handler + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_50_put_speed_limit(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + fdata = os.path.join(env.gen_dir, 'data-100k') + up_len = 100 * 1024 + speed_limit = 50 * 1024 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-0]' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, + with_headers=True, extra_args=[ + '--limit-rate', f'{speed_limit}' + ]) + r.check_response(count=count, http_status=200) + assert r.responses[0]['header']['received-length'] == f'{up_len}', f'{r.responses[0]}' + up_speed = r.stats[0]['speed_upload'] + assert (speed_limit * 0.5) <= up_speed <= (speed_limit * 1.5), f'{r.stats[0]}' + + # speed limited on echo handler + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_07_51_echo_speed_limit(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + fdata = os.path.join(env.gen_dir, 'data-100k') + speed_limit = 50 * 1024 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, + with_headers=True, extra_args=[ + '--limit-rate', f'{speed_limit}' + ]) + r.check_response(count=count, http_status=200) + up_speed = r.stats[0]['speed_upload'] + assert (speed_limit * 0.5) <= up_speed <= (speed_limit * 1.5), f'{r.stats[0]}' + + # upload larger data, triggering "Expect: 100-continue" code paths + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_07_60_upload_exp100(self, env: Env, httpd, nghttpx, repeat, proto): + fdata = os.path.join(env.gen_dir, 'data-1m+') + read_delay = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-0]'\ + f'&read_delay={read_delay}s' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, extra_args=[ + '--expect100-timeout', f'{read_delay+1}' + ]) + r.check_stats(count=1, http_status=200, exitcode=0) + + # upload larger data, triggering "Expect: 100-continue" code paths + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_07_61_upload_exp100_timeout(self, env: Env, httpd, nghttpx, repeat, proto): + fdata = os.path.join(env.gen_dir, 'data-1m+') + read_delay = 2 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/put?id=[0-0]'\ + f'&read_delay={read_delay}s' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto, extra_args=[ + '--expect100-timeout', f'{read_delay-1}' + ]) + r.check_stats(count=1, http_status=200, exitcode=0) + + # issue #15688 when posting a form and cr_mime_read() is called with + # length < 4, we did not progress + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_07_62_upload_issue_15688(self, env: Env, httpd, proto): + # this length leads to (including multipart formatting) to a + # client reader invocation with length 1. + upload_len = 196169 + fname = f'data-{upload_len}' + env.make_data_file(indir=env.gen_dir, fname=fname, fsize=upload_len) + fdata = os.path.join(env.gen_dir, fname) + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-0]' + r = curl.http_form(urls=[url], form={ + 'file': f'@{fdata}', + }, alpn_proto=proto, extra_args=[ + '--max-time', '10' + ]) + r.check_stats(count=1, http_status=200, exitcode=0) + + # nghttpx is the only server we have that supports TLS early data and + # has a limit of 16k it announces + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx") + @pytest.mark.parametrize("proto,upload_size,exp_early", [ + ['http/1.1', 100, 203], # headers+body + ['http/1.1', 10*1024, 10345], # headers+body + ['http/1.1', 32*1024, 16384], # headers+body, limited by server max + ['h2', 10*1024, 10378], # headers+body + ['h2', 32*1024, 16384], # headers+body, limited by server max + ['h3', 1024, 0], # earlydata not supported + ]) + def test_07_70_put_earlydata(self, env: Env, httpd, nghttpx, proto, upload_size, exp_early): + if not env.curl_uses_lib('gnutls'): + pytest.skip('TLS earlydata only implemented in GnuTLS') + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + # we want this test to always connect to nghttpx, since it is + # the only server we have that supports TLS earlydata + port = env.port_for(proto) + if proto != 'h3': + port = env.nghttpx_https_port + url = f'https://{env.domain1}:{port}/curltest/put?id=[0-{count-1}]' + client = LocalClient(name='hx-upload', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', + '-e', # use TLS earlydata + '-f', # forbid reuse of connections + '-l', # announce upload length, no 'Expect: 100' + '-S', f'{upload_size}', + '-r', f'{env.domain1}:{port}:127.0.0.1', + '-V', proto, url + ]) + r.check_exit_code(0) + self.check_downloads(client, [f"{upload_size}"], count) + earlydata = {} + for line in r.trace_lines: + m = re.match(r'^\[t-(\d+)] EarlyData: (\d+)', line) + if m: + earlydata[int(m.group(1))] = int(m.group(2)) + assert earlydata[0] == 0, f'{earlydata}' + assert earlydata[1] == exp_early, f'{earlydata}' + + def check_downloads(self, client, source: List[str], count: int, + complete: bool = True): + for i in range(count): + dfile = client.download_file(i) + assert os.path.exists(dfile) + if complete: + diff = "".join(difflib.unified_diff(a=source, + b=open(dfile).readlines(), + fromfile='-', + tofile=dfile, + n=1)) + assert not diff, f'download {dfile} differs:\n{diff}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_08_caddy.py b/local-test-curl-delta-01/afc-curl/tests/http/test_08_caddy.py new file mode 100644 index 0000000000000000000000000000000000000000..335f76e6fcec357b85bd265cf67dc6dea474bb12 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_08_caddy.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import difflib +import filecmp +import logging +import os +import re +import pytest + +from testenv import Env, CurlClient, Caddy, LocalClient + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.has_caddy(), reason="missing caddy") +@pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") +class TestCaddy: + + @pytest.fixture(autouse=True, scope='class') + def caddy(self, env): + caddy = Caddy(env=env) + assert caddy.start() + yield caddy + caddy.stop() + + def _make_docs_file(self, docs_dir: str, fname: str, fsize: int): + fpath = os.path.join(docs_dir, fname) + data1k = 1024*'x' + flen = 0 + with open(fpath, 'w') as fd: + while flen < fsize: + fd.write(data1k) + flen += len(data1k) + return flen + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, caddy): + self._make_docs_file(docs_dir=caddy.docs_dir, fname='data10k.data', fsize=10*1024) + self._make_docs_file(docs_dir=caddy.docs_dir, fname='data1.data', fsize=1024*1024) + self._make_docs_file(docs_dir=caddy.docs_dir, fname='data5.data', fsize=5*1024*1024) + self._make_docs_file(docs_dir=caddy.docs_dir, fname='data10.data', fsize=10*1024*1024) + self._make_docs_file(docs_dir=caddy.docs_dir, fname='data100.data', fsize=100*1024*1024) + env.make_data_file(indir=env.gen_dir, fname="data-10m", fsize=10*1024*1024) + + # download 1 file + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_08_01_download_1(self, env: Env, caddy: Caddy, repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{caddy.port}/data.json' + r = curl.http_download(urls=[url], alpn_proto=proto) + r.check_response(count=1, http_status=200) + + # download 1MB files sequentially + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_08_02_download_1mb_sequential(self, env: Env, caddy: Caddy, + repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + count = 50 + curl = CurlClient(env=env) + urln = f'https://{env.domain1}:{caddy.port}/data1.data?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200, connect_count=1) + + # download 1MB files parallel + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_08_03_download_1mb_parallel(self, env: Env, caddy: Caddy, + repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + count = 20 + curl = CurlClient(env=env) + urln = f'https://{env.domain1}:{caddy.port}/data1.data?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel' + ]) + r.check_response(count=count, http_status=200) + if proto == 'http/1.1': + # http/1.1 parallel transfers will open multiple connections + assert r.total_connects > 1, r.dump_logs() + else: + assert r.total_connects == 1, r.dump_logs() + + # download 5MB files sequentially + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + @pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_08_04a_download_10mb_sequential(self, env: Env, caddy: Caddy, + repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + count = 40 + curl = CurlClient(env=env) + urln = f'https://{env.domain1}:{caddy.port}/data5.data?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200, connect_count=1) + + # download 10MB files sequentially + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + @pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_08_04b_download_10mb_sequential(self, env: Env, caddy: Caddy, + repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + count = 20 + curl = CurlClient(env=env) + urln = f'https://{env.domain1}:{caddy.port}/data10.data?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200, connect_count=1) + + # download 10MB files parallel + @pytest.mark.skipif(condition=Env().slow_network, reason="not suitable for slow network tests") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + @pytest.mark.skipif(condition=Env().ci_run, reason="not suitable for CI runs") + def test_08_05_download_1mb_parallel(self, env: Env, caddy: Caddy, + repeat, proto): + if proto == 'h3' and not env.have_h3_curl(): + pytest.skip("h3 not supported in curl") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 itself crashes") + if proto == 'http/1.1' and env.curl_uses_lib('mbedtls'): + pytest.skip("mbedtls 3.6.0 fails on 50 connections with: "\ + "ssl_handshake returned: (-0x7F00) SSL - Memory allocation failed") + count = 50 + curl = CurlClient(env=env) + urln = f'https://{env.domain1}:{caddy.port}/data10.data?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--parallel' + ]) + r.check_response(count=count, http_status=200) + if proto == 'http/1.1': + # http/1.1 parallel transfers will open multiple connections + assert r.total_connects > 1, r.dump_logs() + else: + assert r.total_connects == 1, r.dump_logs() + + # post data parallel, check that they were echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_08_06_post_parallel(self, env: Env, httpd, caddy, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + # limit since we use a separate connection in h1 + count = 20 + data = '0123456789' + curl = CurlClient(env=env) + url = f'https://{env.domain2}:{caddy.port}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, + extra_args=['--parallel']) + r.check_stats(count=count, http_status=200, exitcode=0) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == [data] + + # put large file, check that they length were echoed + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_08_07_put_large(self, env: Env, httpd, caddy, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('msh3'): + pytest.skip("msh3 stalls here") + # limit since we use a separate connection in h1< + count = 1 + fdata = os.path.join(env.gen_dir, 'data-10m') + curl = CurlClient(env=env) + url = f'https://{env.domain2}:{caddy.port}/curltest/put?id=[0-{count-1}]' + r = curl.http_put(urls=[url], fdata=fdata, alpn_proto=proto) + exp_data = [f'{os.path.getsize(fdata)}'] + r.check_response(count=count, http_status=200) + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == exp_data + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + def test_08_08_earlydata(self, env: Env, httpd, caddy, proto): + count = 2 + docname = 'data10k.data' + url = f'https://{env.domain1}:{caddy.port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', + '-e', # use TLS earlydata + '-f', # forbid reuse of connections + '-r', f'{env.domain1}:{caddy.port}:127.0.0.1', + '-V', proto, url + ]) + r.check_exit_code(0) + srcfile = os.path.join(caddy.docs_dir, docname) + self.check_downloads(client, srcfile, count) + earlydata = {} + for line in r.trace_lines: + m = re.match(r'^\[t-(\d+)] EarlyData: (\d+)', line) + if m: + earlydata[int(m.group(1))] = int(m.group(2)) + # Caddy does not support early data + assert earlydata[0] == 0, f'{earlydata}' + assert earlydata[1] == 0, f'{earlydata}' + + def check_downloads(self, client, srcfile: str, count: int, + complete: bool = True): + for i in range(count): + dfile = client.download_file(i) + assert os.path.exists(dfile) + if complete and not filecmp.cmp(srcfile, dfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dfile).readlines(), + fromfile=srcfile, + tofile=dfile, + n=1)) + assert False, f'download {dfile} differs:\n{diff}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_09_push.py b/local-test-curl-delta-01/afc-curl/tests/http/test_09_push.py new file mode 100644 index 0000000000000000000000000000000000000000..6b36d2f276c0b9e2515dfd6ff06287ab0e5386ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_09_push.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import pytest + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +class TestPush: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd): + push_dir = os.path.join(httpd.docs_dir, 'push') + if not os.path.exists(push_dir): + os.makedirs(push_dir) + env.make_data_file(indir=push_dir, fname="data1", fsize=1*1024) + env.make_data_file(indir=push_dir, fname="data2", fsize=1*1024) + env.make_data_file(indir=push_dir, fname="data3", fsize=1*1024) + httpd.set_extra_config(env.domain1, [ + 'H2EarlyHints on', + '', + ' H2PushResource /push/data2', + '', + '', + ' H2PushResource /push/data1', + ' H2PushResource /push/data3', + '', + ]) + # activate the new config + httpd.reload() + yield + httpd.clear_extra_configs() + httpd.reload() + + # download a file that triggers a "103 Early Hints" response + def test_09_01_h2_early_hints(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.https_port}/push/data1' + r = curl.http_download(urls=[url], alpn_proto='h2', with_stats=False, + with_headers=True) + r.check_exit_code(0) + assert len(r.responses) == 2, f'{r.responses}' + assert r.responses[0]['status'] == 103, f'{r.responses}' + assert 'link' in r.responses[0]['header'], f'{r.responses[0]}' + assert r.responses[0]['header']['link'] == '; rel=preload', f'{r.responses[0]}' + + def test_09_02_h2_push(self, env: Env, httpd, repeat): + # use localhost as we do not have resolve support in local client + url = f'https://localhost:{env.https_port}/push/data1' + client = LocalClient(name='h2-serverpush', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[url]) + r.check_exit_code(0) + assert os.path.exists(client.download_file(0)) + assert os.path.exists(os.path.join(client.run_dir, 'push0')), r.dump_logs() diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_10_proxy.py b/local-test-curl-delta-01/afc-curl/tests/http/test_10_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebf66789c34c14e25bdc7590a9632bed86939d4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_10_proxy.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import filecmp +import logging +import os +import re +import pytest + +from testenv import Env, CurlClient, ExecResult + + +log = logging.getLogger(__name__) + + +class TestProxy: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx_fwd): + push_dir = os.path.join(httpd.docs_dir, 'push') + if not os.path.exists(push_dir): + os.makedirs(push_dir) + if env.have_nghttpx(): + nghttpx_fwd.start_if_needed() + env.make_data_file(indir=env.gen_dir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=env.gen_dir, fname="data-10m", fsize=10*1024*1024) + httpd.clear_extra_configs() + httpd.reload() + + def get_tunnel_proto_used(self, r: ExecResult): + for line in r.trace_lines: + m = re.match(r'.* CONNECT tunnel: (\S+) negotiated$', line) + if m: + return m.group(1) + assert False, f'tunnel protocol not found in:\n{"".join(r.trace_lines)}' + return None + + # download via http: proxy (no tunnel) + def test_10_01_proxy_http(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=curl.get_proxy_args(proxys=False)) + r.check_response(count=1, http_status=200) + + # download via https: proxy (no tunnel) + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + def test_10_02_proxys_down(self, env: Env, httpd, proto, repeat): + if proto == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proto=proto) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + + # upload via https: with proto (no tunnel) + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("fname, fcount", [ + ['data.json', 5], + ['data-100k', 5], + ['data-1m', 2] + ]) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), + reason="no nghttpx available") + def test_10_02_proxys_up(self, env: Env, httpd, nghttpx, proto, + fname, fcount, repeat): + if proto == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + count = fcount + srcfile = os.path.join(httpd.docs_dir, fname) + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/curltest/echo?id=[0-{count-1}]' + xargs = curl.get_proxy_args(proto=proto) + r = curl.http_upload(urls=[url], data=f'@{srcfile}', alpn_proto=proto, + extra_args=xargs) + r.check_response(count=count, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + indata = open(srcfile).readlines() + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == indata + + # download http: via http: proxytunnel + def test_10_03_proxytunnel_http(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=False, tunnel=True) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200) + + # download http: via https: proxytunnel + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_04_proxy_https(self, env: Env, httpd, nghttpx_fwd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(tunnel=True) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200) + + # download https: with proto via http: proxytunnel + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_10_05_proxytunnel_http(self, env: Env, httpd, proto, repeat): + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json' + xargs = curl.get_proxy_args(proxys=False, tunnel=True) + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + + # download https: with proto via https: proxytunnel + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_06_proxytunnel_https(self, env: Env, httpd, nghttpx_fwd, proto, tunnel, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json?[0-0]' + xargs = curl.get_proxy_args(tunnel=True, proto=tunnel) + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + srcfile = os.path.join(httpd.docs_dir, 'data.json') + dfile = curl.download_file(0) + assert filecmp.cmp(srcfile, dfile, shallow=False) + + # download many https: with proto via https: proxytunnel + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.parametrize("fname, fcount", [ + ['data.json', 100], + ['data-100k', 20], + ['data-1m', 5] + ]) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_07_pts_down_small(self, env: Env, httpd, nghttpx_fwd, proto, + tunnel, fname, fcount, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + count = fcount + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/{fname}?[0-{count-1}]' + xargs = curl.get_proxy_args(tunnel=True, proto=tunnel) + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, + extra_args=xargs) + r.check_response(count=count, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + srcfile = os.path.join(httpd.docs_dir, fname) + for i in range(count): + dfile = curl.download_file(i) + assert filecmp.cmp(srcfile, dfile, shallow=False) + assert r.total_connects == 1, r.dump_logs() + + # upload many https: with proto via https: proxytunnel + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.parametrize("fname, fcount", [ + ['data.json', 50], + ['data-100k', 20], + ['data-1m', 5] + ]) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_08_upload_seq_large(self, env: Env, httpd, nghttpx, proto, + tunnel, fname, fcount, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + count = fcount + srcfile = os.path.join(httpd.docs_dir, fname) + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/curltest/echo?id=[0-{count-1}]' + xargs = curl.get_proxy_args(tunnel=True, proto=tunnel) + r = curl.http_upload(urls=[url], data=f'@{srcfile}', alpn_proto=proto, + extra_args=xargs) + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + r.check_response(count=count, http_status=200) + indata = open(srcfile).readlines() + for i in range(count): + respdata = open(curl.response_file(i)).readlines() + assert respdata == indata, f'resonse {i} differs' + assert r.total_connects == 1, r.dump_logs() + + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_09_reuse_ser(self, env: Env, httpd, nghttpx_fwd, tunnel, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url1 = f'https://localhost:{env.https_port}/data.json' + url2 = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(tunnel=True, proto=tunnel) + r = curl.http_download(urls=[url1, url2], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=2, http_status=200) + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + if tunnel == 'h2': + # TODO: we would like to reuse the first connection for the + # second URL, but this is currently not possible + # assert r.total_connects == 1 + assert r.total_connects == 2 + else: + assert r.total_connects == 2 + + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_10_10_reuse_proxy(self, env: Env, httpd, nghttpx_fwd, tunnel, repeat): + # url twice via https: proxy separated with '--next', will reuse + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json' + proxy_args = curl.get_proxy_args(tunnel=True, proto=tunnel) + r1 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=proxy_args) + r1.check_response(count=1, http_status=200) + assert self.get_tunnel_proto_used(r1) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + # get the args, duplicate separated with '--next' + x2_args = r1.args[1:] + x2_args.append('--next') + x2_args.extend(proxy_args) + r2 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=x2_args) + r2.check_response(count=2, http_status=200) + assert r2.total_connects == 1 + + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + @pytest.mark.skipif(condition=not Env.curl_uses_lib('openssl'), reason="tls13-ciphers not supported") + def test_10_11_noreuse_proxy_https(self, env: Env, httpd, nghttpx_fwd, tunnel, repeat): + # different --proxy-tls13-ciphers, no reuse of connection for https: + curl = CurlClient(env=env) + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + url = f'https://localhost:{env.https_port}/data.json' + proxy_args = curl.get_proxy_args(tunnel=True, proto=tunnel) + r1 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=proxy_args) + r1.check_response(count=1, http_status=200) + assert self.get_tunnel_proto_used(r1) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + # get the args, duplicate separated with '--next' + x2_args = r1.args[1:] + x2_args.append('--next') + x2_args.extend(proxy_args) + x2_args.extend(['--proxy-tls13-ciphers', 'TLS_AES_256_GCM_SHA384']) + r2 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=x2_args) + r2.check_response(count=2, http_status=200) + assert r2.total_connects == 2 + + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + @pytest.mark.skipif(condition=not Env.curl_uses_lib('openssl'), reason="tls13-ciphers not supported") + def test_10_12_noreuse_proxy_http(self, env: Env, httpd, nghttpx_fwd, tunnel, repeat): + # different --proxy-tls13-ciphers, no reuse of connection for http: + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + proxy_args = curl.get_proxy_args(tunnel=True, proto=tunnel) + r1 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=proxy_args) + r1.check_response(count=1, http_status=200) + assert self.get_tunnel_proto_used(r1) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + # get the args, duplicate separated with '--next' + x2_args = r1.args[1:] + x2_args.append('--next') + x2_args.extend(proxy_args) + x2_args.extend(['--proxy-tls13-ciphers', 'TLS_AES_256_GCM_SHA384']) + r2 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=x2_args) + r2.check_response(count=2, http_status=200) + assert r2.total_connects == 2 + + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + @pytest.mark.skipif(condition=not Env.curl_uses_lib('openssl'), reason="tls13-ciphers not supported") + def test_10_13_noreuse_https(self, env: Env, httpd, nghttpx_fwd, tunnel, repeat): + # different --tls13-ciphers on https: same proxy config + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json' + proxy_args = curl.get_proxy_args(tunnel=True, proto=tunnel) + r1 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=proxy_args) + r1.check_response(count=1, http_status=200) + assert self.get_tunnel_proto_used(r1) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + # get the args, duplicate separated with '--next' + x2_args = r1.args[1:] + x2_args.append('--next') + x2_args.extend(proxy_args) + x2_args.extend(['--tls13-ciphers', 'TLS_AES_256_GCM_SHA384']) + r2 = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=x2_args) + r2.check_response(count=2, http_status=200) + assert r2.total_connects == 2 + + # download via https: proxy (no tunnel) using IP address + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.skipif(condition=Env.curl_uses_lib('bearssl'), reason="ip address cert verification not supported") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + def test_10_14_proxys_ip_addr(self, env: Env, httpd, proto, repeat): + if proto == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proto=proto, use_ip=True) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + if env.curl_uses_lib('mbedtls') and \ + not env.curl_lib_version_at_least('mbedtls', '3.5.0'): + r.check_exit_code(60) # CURLE_PEER_FAILED_VERIFICATION + else: + r.check_response(count=1, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_11_unix.py b/local-test-curl-delta-01/afc-curl/tests/http/test_11_unix.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe569279f1d1bc09ed03a3a3f4b890c2376e71c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_11_unix.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import socket +from threading import Thread +from typing import Generator + +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + +class UDSFaker: + + def __init__(self, path): + self._uds_path = path + self._done = False + self._socket = None + + @property + def path(self): + return self._uds_path + + def start(self): + def process(self): + self._socket.listen(1) + self._process() + + try: + os.unlink(self._uds_path) + except OSError: + if os.path.exists(self._uds_path): + raise + self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._socket.bind(self._uds_path) + self._thread = Thread(target=process, daemon=True, args=[self]) + self._thread.start() + + def stop(self): + self._done = True + self._socket.close() + + def _process(self): + while self._done is False: + try: + c, client_address = self._socket.accept() + try: + c.recv(16) + c.sendall("""HTTP/1.1 200 Ok +Server: UdsFaker +Content-Type: application/json +Content-Length: 19 + +{ "host": "faked" }""".encode()) + finally: + c.close() + + except ConnectionAbortedError: + self._done = True + except OSError: + self._done = True + + +class TestUnix: + + @pytest.fixture(scope="class") + def uds_faker(self, env: Env) -> Generator[UDSFaker, None, None]: + uds_path = os.path.join(env.gen_dir, 'uds_11.sock') + faker = UDSFaker(path=uds_path) + faker.start() + yield faker + faker.stop() + + # download http: via Unix socket + def test_11_01_unix_connect_http(self, env: Env, httpd, uds_faker, repeat): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_download(urls=[url], with_stats=True, + extra_args=[ + '--unix-socket', uds_faker.path, + ]) + r.check_response(count=1, http_status=200) + + # download https: via Unix socket + @pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") + def test_11_02_unix_connect_http(self, env: Env, httpd, uds_faker, repeat): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.https_port}/data.json' + r = curl.http_download(urls=[url], with_stats=True, + extra_args=[ + '--unix-socket', uds_faker.path, + ]) + r.check_response(exitcode=35, http_status=None) + + # download HTTP/3 via Unix socket + @pytest.mark.skipif(condition=not Env.have_h3(), reason='h3 not supported') + def test_11_03_unix_connect_quic(self, env: Env, httpd, uds_faker, repeat): + curl = CurlClient(env=env) + url = f'https://{env.domain1}:{env.https_port}/data.json' + r = curl.http_download(urls=[url], with_stats=True, + alpn_proto='h3', + extra_args=[ + '--unix-socket', uds_faker.path, + ]) + r.check_response(exitcode=96, http_status=None) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_12_reuse.py b/local-test-curl-delta-01/afc-curl/tests/http/test_12_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..9252f247454bafd286c003ba2716d1865677abd0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_12_reuse.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +from datetime import datetime, timedelta +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL") +class TestReuse: + + # check if HTTP/1.1 handles 'Connection: close' correctly + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_12_01_h1_conn_close(self, env: Env, + httpd, nghttpx, repeat, proto): + httpd.clear_extra_configs() + httpd.set_extra_config('base', [ + 'MaxKeepAliveRequests 1', + ]) + httpd.reload() + count = 100 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto) + r.check_response(count=count, http_status=200) + # Server sends `Connection: close` on every 2nd request, requiring + # a new connection + delta = 5 + assert (count/2 - delta) < r.total_connects < (count/2 + delta) + + @pytest.mark.skipif(condition=Env.httpd_is_at_least('2.5.0'), + reason="httpd 2.5+ handles KeepAlives different") + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_12_02_h1_conn_timeout(self, env: Env, + httpd, nghttpx, repeat, proto): + httpd.clear_extra_configs() + httpd.set_extra_config('base', [ + 'KeepAliveTimeout 1', + ]) + httpd.reload() + count = 5 + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[ + '--rate', '30/m', + ]) + r.check_response(count=count, http_status=200) + # Connections time out on server before we send another request, + assert r.total_connects == count + + @pytest.mark.skipif(condition=not Env.have_h3(), reason="h3 not supported") + def test_12_03_alt_svc_h2h3(self, env: Env, httpd, nghttpx): + httpd.clear_extra_configs() + httpd.reload() + count = 2 + # write a alt-svc file the advises h3 instead of h2 + asfile = os.path.join(env.gen_dir, 'alt-svc-12_03.txt') + ts = datetime.now() + timedelta(hours=24) + expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}' + with open(asfile, 'w') as fd: + fd.write(f'h2 {env.domain1} {env.https_port} h3 {env.domain1} {env.https_port} "{expires}" 0 0') + log.info(f'altscv: {open(asfile).readlines()}') + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], with_stats=True, extra_args=[ + '--alt-svc', f'{asfile}', + ]) + r.check_response(count=count, http_status=200) + # We expect the connection to be reused + assert r.total_connects == 1 + for s in r.stats: + assert s['http_version'] == '3', f'{s}' + + def test_12_04_alt_svc_h3h2(self, env: Env, httpd, nghttpx): + httpd.clear_extra_configs() + httpd.reload() + count = 2 + # write a alt-svc file the advises h2 instead of h3 + asfile = os.path.join(env.gen_dir, 'alt-svc-12_04.txt') + ts = datetime.now() + timedelta(hours=24) + expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}' + with open(asfile, 'w') as fd: + fd.write(f'h3 {env.domain1} {env.https_port} h2 {env.domain1} {env.https_port} "{expires}" 0 0') + log.info(f'altscv: {open(asfile).readlines()}') + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], with_stats=True, extra_args=[ + '--alt-svc', f'{asfile}', + ]) + r.check_response(count=count, http_status=200) + # We expect the connection to be reused + assert r.total_connects == 1 + for s in r.stats: + assert s['http_version'] == '2', f'{s}' + + def test_12_05_alt_svc_h3h1(self, env: Env, httpd, nghttpx): + httpd.clear_extra_configs() + httpd.reload() + count = 2 + # write a alt-svc file the advises h1 instead of h3 + asfile = os.path.join(env.gen_dir, 'alt-svc-12_05.txt') + ts = datetime.now() + timedelta(hours=24) + expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}' + with open(asfile, 'w') as fd: + fd.write(f'h3 {env.domain1} {env.https_port} http/1.1 {env.domain1} {env.https_port} "{expires}" 0 0') + log.info(f'altscv: {open(asfile).readlines()}') + curl = CurlClient(env=env) + urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[urln], with_stats=True, extra_args=[ + '--alt-svc', f'{asfile}', + ]) + r.check_response(count=count, http_status=200) + # We expect the connection to be reused + assert r.total_connects == 1 + # When using http/1.1 from alt-svc, we ALPN-negotiate 'h2,http/1.1' anyway + # which means our server gives us h2 + for s in r.stats: + assert s['http_version'] == '2', f'{s}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_13_proxy_auth.py b/local-test-curl-delta-01/afc-curl/tests/http/test_13_proxy_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..0979fbb7e20f06abd85b4664289eded81b3e59c7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_13_proxy_auth.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import re +import pytest + +from testenv import Env, CurlClient, ExecResult + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=Env.setup_incomplete(), + reason=f"missing: {Env.incomplete_reason()}") +class TestProxyAuth: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx_fwd): + if env.have_nghttpx(): + nghttpx_fwd.start_if_needed() + httpd.clear_extra_configs() + httpd.set_proxy_auth(True) + httpd.reload() + yield + httpd.set_proxy_auth(False) + httpd.reload() + + def get_tunnel_proto_used(self, r: ExecResult): + for line in r.trace_lines: + m = re.match(r'.* CONNECT tunnel: (\S+) negotiated$', line) + if m: + return m.group(1) + assert False, f'tunnel protocol not found in:\n{"".join(r.trace_lines)}' + return None + + # download via http: proxy (no tunnel), no auth + def test_13_01_proxy_no_auth(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=curl.get_proxy_args(proxys=False)) + r.check_response(count=1, http_status=407) + + # download via http: proxy (no tunnel), auth + def test_13_02_proxy_auth(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=False) + xargs.extend(['--proxy-user', 'proxy:proxy']) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200) + + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_13_03_proxys_no_auth(self, env: Env, httpd, nghttpx_fwd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=True) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=407) + + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + def test_13_04_proxys_auth(self, env: Env, httpd, nghttpx_fwd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=True) + xargs.extend(['--proxy-user', 'proxy:proxy']) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200) + + def test_13_05_tunnel_http_no_auth(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=False, tunnel=True) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + # expect "COULD_NOT_CONNECT" + r.check_response(exitcode=56, http_status=None) + + def test_13_06_tunnel_http_auth(self, env: Env, httpd, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.http_port}/data.json' + xargs = curl.get_proxy_args(proxys=False, tunnel=True) + xargs.extend(['--proxy-user', 'proxy:proxy']) + r = curl.http_download(urls=[url], alpn_proto='http/1.1', with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200) + + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + def test_13_07_tunnels_no_auth(self, env: Env, httpd, proto, tunnel, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json' + xargs = curl.get_proxy_args(proxys=True, tunnel=True, proto=tunnel) + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, + extra_args=xargs) + # expect "COULD_NOT_CONNECT" + r.check_response(exitcode=56, http_status=None) + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' + + @pytest.mark.skipif(condition=not Env.have_nghttpx(), reason="no nghttpx available") + @pytest.mark.skipif(condition=not Env.curl_has_feature('HTTPS-proxy'), + reason='curl lacks HTTPS-proxy support') + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + @pytest.mark.parametrize("tunnel", ['http/1.1', 'h2']) + def test_13_08_tunnels_auth(self, env: Env, httpd, proto, tunnel, repeat): + if tunnel == 'h2' and not env.curl_uses_lib('nghttp2'): + pytest.skip('only supported with nghttp2') + curl = CurlClient(env=env) + url = f'https://localhost:{env.https_port}/data.json' + xargs = curl.get_proxy_args(proxys=True, tunnel=True, proto=tunnel) + xargs.extend(['--proxy-user', 'proxy:proxy']) + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, + extra_args=xargs) + r.check_response(count=1, http_status=200, + protocol='HTTP/2' if proto == 'h2' else 'HTTP/1.1') + assert self.get_tunnel_proto_used(r) == 'HTTP/2' \ + if tunnel == 'h2' else 'HTTP/1.1' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_14_auth.py b/local-test-curl-delta-01/afc-curl/tests/http/test_14_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa6767b0d17985b5533a3e5824a90726a6c93d3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_14_auth.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +class TestAuth: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + env.make_data_file(indir=env.gen_dir, fname="data-10m", fsize=10*1024*1024) + httpd.clear_extra_configs() + httpd.reload() + + # download 1 file, not authenticated + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_14_01_digest_get_noauth(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_download(urls=[url], alpn_proto=proto) + r.check_response(http_status=401) + + # download 1 file, authenticated + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_14_02_digest_get_auth(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_download(urls=[url], alpn_proto=proto, extra_args=[ + '--digest', '--user', 'test:test' + ]) + r.check_response(http_status=200) + + # PUT data, authenticated + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_14_03_digest_put_auth(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + data='0123456789' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, extra_args=[ + '--digest', '--user', 'test:test' + ]) + r.check_response(http_status=200) + + # PUT data, digest auth large pw + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_14_04_digest_large_pw(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + data='0123456789' + password = 'x' * 65535 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_upload(urls=[url], data=data, alpn_proto=proto, extra_args=[ + '--digest', '--user', f'test:{password}', + '--trace-config', 'http/2,http/3' + ]) + # digest does not submit the password, but a hash of it, so all + # works and, since the pw is not correct, we get a 401 + r.check_response(http_status=401) + + # PUT data, basic auth large pw + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_14_05_basic_large_pw(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and not env.curl_uses_lib('ngtcp2'): + # See + pytest.skip("quiche/openssl-quic have problems with large requests") + # just large enough that nghttp2 will submit + password = 'x' * (47 * 1024) + fdata = os.path.join(env.gen_dir, 'data-10m') + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, extra_args=[ + '--basic', '--user', f'test:{password}', + '--trace-config', 'http/2,http/3' + ]) + # but apache denies on length limit + r.check_response(http_status=431) + + # PUT data, basic auth with very large pw + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_14_06_basic_very_large_pw(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if proto == 'h3' and env.curl_uses_lib('quiche'): + # See + pytest.skip("quiche has problems with large requests") + password = 'x' * (64 * 1024) + fdata = os.path.join(env.gen_dir, 'data-10m') + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/restricted/digest/data.json' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, extra_args=[ + '--basic', '--user', f'test:{password}' + ]) + # Depending on protocol, we might have an error sending or + # the server might shutdown the connection and we see the error + # on receiving + assert r.exit_code in [55, 56], f'{self.dump_logs()}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_15_tracing.py b/local-test-curl-delta-01/afc-curl/tests/http/test_15_tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..a82604423236c63521eec8ad661493c9a007ffe1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_15_tracing.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import re + +from testenv import Env +from testenv import CurlClient + + +log = logging.getLogger(__name__) + + +class TestTracing: + + # default verbose output + def test_15_01_trace_defaults(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, def_tracing=False, extra_args=[ + '-v' + ]) + r.check_response(http_status=200) + trace = r.trace_lines + assert len(trace) > 0 + + # trace ids + def test_15_02_trace_ids(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, def_tracing=False, extra_args=[ + '-v', '--trace-config', 'ids' + ]) + r.check_response(http_status=200) + for line in r.trace_lines: + m = re.match(r'^\[0-[0x]] .+', line) + if m is None: + assert False, f'no match: {line}' + + # trace ids+time + def test_15_03_trace_ids_time(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, def_tracing=False, extra_args=[ + '-v', '--trace-config', 'ids,time' + ]) + r.check_response(http_status=200) + for line in r.trace_lines: + m = re.match(r'^([0-9:.]+) \[0-[0x]] .+', line) + if m is None: + assert False, f'no match: {line}' + + # trace all + def test_15_04_trace_all(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, def_tracing=False, extra_args=[ + '-v', '--trace-config', 'all' + ]) + r.check_response(http_status=200) + found_tcp = False + for line in r.trace_lines: + m = re.match(r'^([0-9:.]+) \[0-[0x]] .+', line) + if m is None: + assert False, f'no match: {line}' + m = re.match(r'^([0-9:.]+) \[0-[0x]] . \[TCP].+', line) + if m is not None: + found_tcp = True + if not found_tcp: + assert False, f'TCP filter does not appear in trace "all": {r.stderr}' + + # trace all, no TCP, no time + def test_15_05_trace_all(self, env: Env, httpd): + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json' + r = curl.http_get(url=url, def_tracing=False, extra_args=[ + '-v', '--trace-config', 'all,-tcp,-time' + ]) + r.check_response(http_status=200) + found_tcp = False + for line in r.trace_lines: + m = re.match(r'^\[0-[0x]] .+', line) + if m is None: + assert False, f'no match: {line}' + m = re.match(r'^\[0-[0x]] . \[TCP].+', line) + if m is not None: + found_tcp = True + if found_tcp: + assert False, f'TCP filter appears in trace "all,-tcp": {r.stderr}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_16_info.py b/local-test-curl-delta-01/afc-curl/tests/http/test_16_info.py new file mode 100644 index 0000000000000000000000000000000000000000..06ab9503cf4e768f5d69aff7d4a23edde242d102 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_16_info.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +class TestInfo: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd): + indir = httpd.docs_dir + env.make_data_file(indir=indir, fname="data-10k", fsize=10*1024) + env.make_data_file(indir=indir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=indir, fname="data-1m", fsize=1024*1024) + + # download plain file + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_16_01_info_download(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True) + r.check_stats(count=count, http_status=200, exitcode=0, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + for idx, s in enumerate(r.stats): + self.check_stat(idx, s, r, dl_size=30, ul_size=0) + + # download plain file with a 302 redirect + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_16_02_info_302_download(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json.302?[0-{count-1}]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True, extra_args=[ + '--location' + ]) + r.check_stats(count=count, http_status=200, exitcode=0, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + for idx, s in enumerate(r.stats): + self.check_stat(idx, s, r, dl_size=30, ul_size=0) + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_16_03_info_upload(self, env: Env, httpd, nghttpx, proto, repeat): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 2 + fdata = os.path.join(env.gen_dir, 'data-100k') + fsize = 100 * 1024 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/echo?id=[0-{count-1}]' + r = curl.http_upload(urls=[url], data=f'@{fdata}', alpn_proto=proto, + with_headers=True, extra_args=[ + '--trace-config', 'http/2,http/3' + ]) + r.check_response(count=count, http_status=200) + r.check_stats(count=count, http_status=200, exitcode=0, + remote_port=env.port_for(alpn_proto=proto), + remote_ip='127.0.0.1') + for idx, s in enumerate(r.stats): + self.check_stat(idx, s, r, dl_size=fsize, ul_size=fsize) + + # download plain file via http: ('time_appconnect' is 0) + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_16_04_info_http_download(self, env: Env, httpd, nghttpx, repeat, proto): + count = 2 + curl = CurlClient(env=env) + url = f'http://{env.domain1}:{env.http_port}/data.json?[0-{count-1}]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_stats=True) + r.check_stats(count=count, http_status=200, exitcode=0, + remote_port=env.http_port, remote_ip='127.0.0.1') + for idx, s in enumerate(r.stats): + self.check_stat(idx, s, r, dl_size=30, ul_size=0) + + def check_stat(self, idx, s, r, dl_size=None, ul_size=None): + self.check_stat_times(s, idx) + # we always send something + self.check_stat_positive(s, idx, 'size_request') + # we always receive response headers + self.check_stat_positive(s, idx, 'size_header') + if ul_size is not None: + assert s['size_upload'] == ul_size, f'stat #{idx}\n{r.dump_logs()}' # the file we sent + assert s['size_request'] >= s['size_upload'], \ + f'stat #{idx}, "size_request" smaller than "size_upload", {s}\n{r.dump_logs()}' + if dl_size is not None: + assert s['size_download'] == dl_size, f'stat #{idx}\n{r.dump_logs()}' # the file we received + + def check_stat_positive(self, s, idx, key): + assert key in s, f'stat #{idx} "{key}" missing: {s}' + assert s[key] > 0, f'stat #{idx} "{key}" not positive: {s}' + + def check_stat_zero(self, s, key): + assert key in s, f'stat "{key}" missing: {s}' + assert s[key] == 0, f'stat "{key}" not zero: {s}' + + def check_stat_times(self, s, idx): + # check timings reported on a transfer for consistency + url = s['url_effective'] + # all stat keys which reporting timings + all_keys = { + 'time_appconnect', 'time_connect', 'time_redirect', + 'time_pretransfer', 'time_starttransfer', 'time_total' + } + # stat keys where we expect a positive value + pos_keys = {'time_pretransfer', 'time_starttransfer', 'time_total'} + if s['num_connects'] > 0: + pos_keys.add('time_connect') + if url.startswith('https:'): + pos_keys.add('time_appconnect') + if s['num_redirects'] > 0: + pos_keys.add('time_redirect') + zero_keys = all_keys - pos_keys + # assert all zeros are zeros and the others are positive + for key in zero_keys: + self.check_stat_zero(s, key) + for key in pos_keys: + self.check_stat_positive(s, idx, key) + # assert that all timers before "time_pretransfer" are less or equal + for key in ['time_appconnect', 'time_connect', 'time_namelookup']: + assert s[key] < s['time_pretransfer'], f'time "{key}" larger than' \ + f'"time_pretransfer": {s}' + # assert transfer start is after pretransfer + assert s['time_pretransfer'] <= s['time_starttransfer'], f'"time_pretransfer" '\ + f'greater than "time_starttransfer", {s}' + # assert that transfer start is before total + assert s['time_starttransfer'] <= s['time_total'], f'"time_starttransfer" '\ + f'greater than "time_total", {s}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_17_ssl_use.py b/local-test-curl-delta-01/afc-curl/tests/http/test_17_ssl_use.py new file mode 100644 index 0000000000000000000000000000000000000000..883d4a5f6f9e54a313a24b27563c5918eaa03556 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_17_ssl_use.py @@ -0,0 +1,392 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import json +import logging +import os +import re +import pytest + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +class TestSSLUse: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + env.make_data_file(indir=httpd.docs_dir, fname="data-10k", fsize=10*1024) + if env.have_h3(): + nghttpx.start_if_needed() + + @pytest.fixture(autouse=True, scope='function') + def _function_scope(self, request, env, httpd): + httpd.clear_extra_configs() + if 'httpd' not in request.node._fixtureinfo.argnames: + httpd.reload_if_config_changed() + + def test_17_01_sslinfo_plain(self, env: Env, nghttpx, repeat): + proto = 'http/1.1' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.json['HTTPS'] == 'on', f'{r.json}' + assert 'SSL_SESSION_ID' in r.json, f'{r.json}' + assert 'SSL_SESSION_RESUMED' in r.json, f'{r.json}' + assert r.json['SSL_SESSION_RESUMED'] == 'Initial', f'{r.json}' + + @pytest.mark.parametrize("tls_max", ['1.2', '1.3']) + def test_17_02_sslinfo_reconnect(self, env: Env, tls_max): + proto = 'http/1.1' + count = 3 + exp_resumed = 'Resumed' + xargs = ['--sessionid', '--tls-max', tls_max, f'--tlsv{tls_max}'] + if env.curl_uses_lib('libressl'): + if tls_max == '1.3': + exp_resumed = 'Initial' # 1.2 works in LibreSSL, but 1.3 does not, TODO + if env.curl_uses_lib('rustls-ffi'): + exp_resumed = 'Initial' # Rustls does not support sessions, TODO + if env.curl_uses_lib('bearssl') and tls_max == '1.3': + pytest.skip('BearSSL does not support TLSv1.3') + if env.curl_uses_lib('mbedtls') and tls_max == '1.3' and \ + not env.curl_lib_version_at_least('mbedtls', '3.6.0'): + pytest.skip('mbedtls TLSv1.3 session resume not working in 3.6.0') + + run_env = os.environ.copy() + run_env['CURL_DEBUG'] = 'ssl' + curl = CurlClient(env=env, run_env=run_env) + # tell the server to close the connection after each request + urln = f'https://{env.authority_for(env.domain1, proto)}/curltest/sslinfo?'\ + f'id=[0-{count-1}]&close' + r = curl.http_download(urls=[urln], alpn_proto=proto, with_stats=True, + extra_args=xargs) + r.check_response(count=count, http_status=200) + # should have used one connection for each request, sessions after + # first should have been resumed + assert r.total_connects == count, r.dump_logs() + for i in range(count): + dfile = curl.download_file(i) + assert os.path.exists(dfile) + with open(dfile) as f: + djson = json.load(f) + assert djson['HTTPS'] == 'on', f'{i}: {djson}' + if i == 0: + assert djson['SSL_SESSION_RESUMED'] == 'Initial', f'{i}: {djson}\n{r.dump_logs()}' + else: + assert djson['SSL_SESSION_RESUMED'] == exp_resumed, f'{i}: {djson}\n{r.dump_logs()}' + + # use host name with trailing dot, verify handshake + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_03_trailing_dot(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = f'{env.domain1}.' + url = f'https://{env.authority_for(domain, proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.exit_code == 0, f'{r}' + assert r.json, f'{r}' + if proto != 'h3': # we proxy h3 + # the SNI the server received is without trailing dot + assert r.json['SSL_TLS_SNI'] == env.domain1, f'{r.json}' + + # use host name with double trailing dot, verify handshake + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_04_double_dot(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = f'{env.domain1}..' + url = f'https://{env.authority_for(domain, proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto, extra_args=[ + '-H', f'Host: {env.domain1}', + ]) + if r.exit_code == 0: + assert r.json, f'{r.stdout}' + # the SNI the server received is without trailing dot + if proto != 'h3': # we proxy h3 + assert r.json['SSL_TLS_SNI'] == env.domain1, f'{r.json}' + assert False, f'should not have succeeded: {r.json}' + # 7 - Rustls rejects a servername with .. during setup + # 35 - LibreSSL rejects setting an SNI name with trailing dot + # 60 - peer name matching failed against certificate + assert r.exit_code in [7, 35, 60], f'{r}' + + # use ip address for connect + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_05_ip_addr(self, env: Env, proto): + if env.curl_uses_lib('bearssl'): + pytest.skip("BearSSL does not support cert verification with IP addresses") + if env.curl_uses_lib('mbedtls'): + pytest.skip("mbedTLS does use IP addresses in SNI") + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = '127.0.0.1' + url = f'https://{env.authority_for(domain, proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.exit_code == 0, f'{r}' + assert r.json, f'{r}' + if proto != 'h3': # we proxy h3 + # the SNI should not have been used + assert 'SSL_TLS_SNI' not in r.json, f'{r.json}' + + # use localhost for connect + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_06_localhost(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = 'localhost' + url = f'https://{env.authority_for(domain, proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.exit_code == 0, f'{r}' + assert r.json, f'{r}' + if proto != 'h3': # we proxy h3 + assert r.json['SSL_TLS_SNI'] == domain, f'{r.json}' + + @staticmethod + def gen_test_17_07_list(): + tls13_tests = [ + [None, True], + [['TLS_AES_128_GCM_SHA256'], True], + [['TLS_AES_256_GCM_SHA384'], False], + [['TLS_CHACHA20_POLY1305_SHA256'], True], + [['TLS_AES_256_GCM_SHA384', + 'TLS_CHACHA20_POLY1305_SHA256'], True], + ] + tls12_tests = [ + [None, True], + [['ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES128-GCM-SHA256'], True], + [['ECDHE-ECDSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES256-GCM-SHA384'], False], + [['ECDHE-ECDSA-CHACHA20-POLY1305', 'ECDHE-RSA-CHACHA20-POLY1305'], True], + [['ECDHE-ECDSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES256-GCM-SHA384', + 'ECDHE-ECDSA-CHACHA20-POLY1305', 'ECDHE-RSA-CHACHA20-POLY1305'], True], + ] + ret = [] + for tls_proto in ['TLSv1.3 +TLSv1.2', 'TLSv1.3', 'TLSv1.2']: + for [ciphers13, succeed13] in tls13_tests: + for [ciphers12, succeed12] in tls12_tests: + ret.append([tls_proto, ciphers13, ciphers12, succeed13, succeed12]) + return ret + + @pytest.mark.parametrize("tls_proto, ciphers13, ciphers12, succeed13, succeed12", gen_test_17_07_list()) + def test_17_07_ssl_ciphers(self, env: Env, httpd, tls_proto, ciphers13, ciphers12, succeed13, succeed12): + # to test setting cipher suites, the AES 256 ciphers are disabled in the test server + httpd.set_extra_config('base', [ + 'SSLCipherSuite SSL' + ' ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256' + ':ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305', + 'SSLCipherSuite TLSv1.3' + ' TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256', + f'SSLProtocol {tls_proto}' + ]) + httpd.reload_if_config_changed() + proto = 'http/1.1' + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/sslinfo' + # SSL backend specifics + if env.curl_uses_lib('gnutls'): + pytest.skip('GnuTLS does not support setting ciphers') + elif env.curl_uses_lib('boringssl'): + if ciphers13 is not None: + pytest.skip('BoringSSL does not support setting TLSv1.3 ciphers') + elif env.curl_uses_lib('schannel'): # not in CI, so untested + if ciphers12 is not None: + pytest.skip('Schannel does not support setting TLSv1.2 ciphers by name') + elif env.curl_uses_lib('bearssl'): + if tls_proto == 'TLSv1.3': + pytest.skip('BearSSL does not support TLSv1.3') + tls_proto = 'TLSv1.2' + elif env.curl_uses_lib('mbedtls') and not env.curl_lib_version_at_least('mbedtls', '3.6.0'): + if tls_proto == 'TLSv1.3': + pytest.skip('mbedTLS < 3.6.0 does not support TLSv1.3') + elif env.curl_uses_lib('sectransp'): # not in CI, so untested + if tls_proto == 'TLSv1.3': + pytest.skip('Secure Transport does not support TLSv1.3') + tls_proto = 'TLSv1.2' + # test + extra_args = ['--tls13-ciphers', ':'.join(ciphers13)] if ciphers13 else [] + extra_args += ['--ciphers', ':'.join(ciphers12)] if ciphers12 else [] + r = curl.http_get(url=url, alpn_proto=proto, extra_args=extra_args) + if tls_proto != 'TLSv1.2' and succeed13: + assert r.exit_code == 0, r.dump_logs() + assert r.json['HTTPS'] == 'on', r.dump_logs() + assert r.json['SSL_PROTOCOL'] == 'TLSv1.3', r.dump_logs() + assert ciphers13 is None or r.json['SSL_CIPHER'] in ciphers13, r.dump_logs() + elif tls_proto == 'TLSv1.2' and succeed12: + assert r.exit_code == 0, r.dump_logs() + assert r.json['HTTPS'] == 'on', r.dump_logs() + assert r.json['SSL_PROTOCOL'] == 'TLSv1.2', r.dump_logs() + assert ciphers12 is None or r.json['SSL_CIPHER'] in ciphers12, r.dump_logs() + else: + assert r.exit_code != 0, r.dump_logs() + + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_08_cert_status(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if not env.curl_uses_lib('openssl') and \ + not env.curl_uses_lib('gnutls') and \ + not env.curl_uses_lib('quictls'): + pytest.skip("TLS library does not support --cert-status") + curl = CurlClient(env=env) + domain = 'localhost' + url = f'https://{env.authority_for(domain, proto)}/' + r = curl.http_get(url=url, alpn_proto=proto, extra_args=[ + '--cert-status' + ]) + # CURLE_SSL_INVALIDCERTSTATUS, our certs have no OCSP info + assert r.exit_code == 91, f'{r}' + + @staticmethod + def gen_test_17_09_list(): + return [[tls_proto, max_ver, min_ver] + for tls_proto in ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3'] + for max_ver in range(5) + for min_ver in range(-2, 4)] + + @pytest.mark.parametrize("tls_proto, max_ver, min_ver", gen_test_17_09_list()) + def test_17_09_ssl_min_max(self, env: Env, httpd, tls_proto, max_ver, min_ver): + httpd.set_extra_config('base', [ + f'SSLProtocol {tls_proto}', + 'SSLCipherSuite ALL:@SECLEVEL=0', + ]) + httpd.reload_if_config_changed() + proto = 'http/1.1' + run_env = os.environ.copy() + if env.curl_uses_lib('gnutls'): + # we need to override any default system configuration since + # we want to test all protocol versions. Ubuntu (or the GH image) + # disable TSL1.0 and TLS1.1 system wide. We do not want. + our_config = os.path.join(env.gen_dir, 'gnutls_config') + if not os.path.exists(our_config): + with open(our_config, 'w') as fd: + fd.write('# empty\n') + run_env['GNUTLS_SYSTEM_PRIORITY_FILE'] = our_config + curl = CurlClient(env=env, run_env=run_env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/sslinfo' + # SSL backend specifics + if env.curl_uses_lib('bearssl'): + supported = ['TLSv1', 'TLSv1.1', 'TLSv1.2', None] + elif env.curl_uses_lib('sectransp'): # not in CI, so untested + supported = ['TLSv1', 'TLSv1.1', 'TLSv1.2', None] + elif env.curl_uses_lib('gnutls'): + supported = ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3'] + elif env.curl_uses_lib('quiche'): + supported = ['TLSv1', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3'] + else: # most SSL backends dropped support for TLSv1.0, TLSv1.1 + supported = [None, None, 'TLSv1.2', 'TLSv1.3'] + # test + extra_args = [[], ['--tlsv1'], ['--tlsv1.0'], ['--tlsv1.1'], ['--tlsv1.2'], ['--tlsv1.3']][min_ver+2] + \ + [['--tls-max', '1.0'], ['--tls-max', '1.1'], ['--tls-max', '1.2'], ['--tls-max', '1.3'], []][max_ver] + extra_args.extend(['--trace-config', 'ssl']) + r = curl.http_get(url=url, alpn_proto=proto, extra_args=extra_args) + if max_ver >= min_ver and tls_proto in supported[max(0, min_ver):min(max_ver, 3)+1]: + assert r.exit_code == 0, f'extra_args={extra_args}\n{r.dump_logs()}' + assert r.json['HTTPS'] == 'on', r.dump_logs() + assert r.json['SSL_PROTOCOL'] == tls_proto, r.dump_logs() + else: + assert r.exit_code != 0, f'extra_args={extra_args}\n{r.dump_logs()}' + + def test_17_10_h3_session_reuse(self, env: Env, httpd, nghttpx): + if not env.have_h3(): + pytest.skip("h3 not supported") + if not env.curl_uses_lib('quictls') and \ + not env.curl_uses_lib('gnutls') and \ + not env.curl_uses_lib('wolfssl'): + pytest.skip("QUIC session reuse not implemented") + count = 2 + docname = 'data-10k' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', + '-f', # forbid reuse of connections + '-r', f'{env.domain1}:{env.port_for("h3")}:127.0.0.1', + '-V', 'h3', url + ]) + r.check_exit_code(0) + # check that TLS session was reused as expected + reused_session = False + for line in r.trace_lines: + m = re.match(r'\[1-1] \* SSL reusing session.*', line) + if m: + reused_session = True + assert reused_session, f'{r}\n{r.dump_logs()}' + + # use host name server has no certificate for + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_11_wrong_host(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = f'insecure.{env.tld}' + url = f'https://{domain}:{env.port_for(proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.exit_code == 60, f'{r}' + + # use host name server has no cert for with --insecure + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_17_12_insecure(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + domain = f'insecure.{env.tld}' + url = f'https://{domain}:{env.port_for(proto)}/curltest/sslinfo' + r = curl.http_get(url=url, alpn_proto=proto, extra_args=[ + '--insecure' + ]) + assert r.exit_code == 0, f'{r}' + assert r.json, f'{r}' + + # connect to an expired certificate + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + def test_17_14_expired_cert(self, env: Env, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + curl = CurlClient(env=env) + url = f'https://{env.expired_domain}:{env.port_for(proto)}/' + r = curl.http_get(url=url, alpn_proto=proto) + assert r.exit_code == 60, f'{r}' # peer failed verification + exp_trace = None + match_trace = None + if env.curl_uses_lib('openssl') or env.curl_uses_lib('quictls'): + exp_trace = r'.*SSL certificate problem: certificate has expired$' + elif env.curl_uses_lib('gnutls'): + exp_trace = r'.*server verification failed: certificate has expired\..*' + elif env.curl_uses_lib('wolfssl'): + exp_trace = r'.*server verification failed: certificate has expired\.$' + if exp_trace is not None: + for line in r.trace_lines: + if re.match(exp_trace, line): + match_trace = line + break + assert match_trace, f'Did not find "{exp_trace}" in trace\n{r.dump_logs()}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_18_methods.py b/local-test-curl-delta-01/afc-curl/tests/http/test_18_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..f9399db4baec62455c2facec80b31372ef4fa041 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_18_methods.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import pytest + +from testenv import Env, CurlClient + + +log = logging.getLogger(__name__) + + +class TestMethods: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload_if_config_changed() + indir = httpd.docs_dir + env.make_data_file(indir=indir, fname="data-10k", fsize=10*1024) + env.make_data_file(indir=indir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=indir, fname="data-1m", fsize=1024*1024) + + # download 1 file + @pytest.mark.parametrize("proto", ['http/1.1', 'h2', 'h3']) + def test_18_01_delete(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak?id=[0-{count-1}]' + r = curl.http_delete(urls=[url], alpn_proto=proto) + r.check_stats(count=count, http_status=204, exitcode=0) + + # make HTTP/2 in the server send + # - HEADER frame with 204 and eos=0 + # - 10ms later DATA frame length=0 and eos=1 + # should be accepted + def test_18_02_delete_h2_special(self, env: Env, httpd, nghttpx, repeat): + proto = 'h2' + count = 1 + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak?id=[0-{count-1}]'\ + '&chunks=1&chunk_size=0&chunk_delay=10ms' + r = curl.http_delete(urls=[url], alpn_proto=proto) + r.check_stats(count=count, http_status=204, exitcode=0) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_19_shutdown.py b/local-test-curl-delta-01/afc-curl/tests/http/test_19_shutdown.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb67d360e1016139a50c068bdb9de4810b8140b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_19_shutdown.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import re +import pytest + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +class TestShutdown: + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd, nghttpx): + if env.have_h3(): + nghttpx.start_if_needed() + httpd.clear_extra_configs() + httpd.reload() + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, httpd): + indir = httpd.docs_dir + env.make_data_file(indir=indir, fname="data-10k", fsize=10*1024) + env.make_data_file(indir=indir, fname="data-100k", fsize=100*1024) + env.make_data_file(indir=indir, fname="data-1m", fsize=1024*1024) + + # check with `tcpdump` that we see curl TCP RST packets + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_19_01_check_tcp_rst(self, env: Env, httpd, repeat, proto): + if env.ci_run: + pytest.skip("seems not to work in CI") + curl = CurlClient(env=env) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[ + '--parallel' + ]) + r.check_response(http_status=200, count=2) + assert r.tcpdump + assert len(r.tcpdump.stats) != 0, f'Expected TCP RSTs packets: {r.tcpdump.stderr}' + + # check with `tcpdump` that we do NOT see TCP RST when CURL_GRACEFUL_SHUTDOWN set + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + @pytest.mark.parametrize("proto", ['http/1.1', 'h2']) + def test_19_02_check_shutdown(self, env: Env, httpd, repeat, proto): + if not env.curl_is_debug(): + pytest.skip('only works for curl debug builds') + curl = CurlClient(env=env, run_env={ + 'CURL_GRACEFUL_SHUTDOWN': '2000', + 'CURL_DEBUG': 'ssl,tcp' + }) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[ + '--parallel' + ]) + r.check_response(http_status=200, count=2) + assert r.tcpdump + assert len(r.tcpdump.stats) == 0, 'Unexpected TCP RSTs packets' + + # run downloads where the server closes the connection after each request + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_19_03_shutdown_by_server(self, env: Env, httpd, repeat, proto): + if not env.curl_is_debug(): + pytest.skip('only works for curl debug builds') + count = 10 + curl = CurlClient(env=env, run_env={ + 'CURL_GRACEFUL_SHUTDOWN': '2000', + 'CURL_DEBUG': 'ssl' + }) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak/?'\ + f'id=[0-{count-1}]&with_cl&close' + r = curl.http_download(urls=[url], alpn_proto=proto) + r.check_response(http_status=200, count=count) + shutdowns = [line for line in r.trace_lines + if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)] + assert len(shutdowns) == count, f'{shutdowns}' + + # run downloads with CURLOPT_FORBID_REUSE set, meaning *we* close + # the connection after each request + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_19_04_shutdown_by_curl(self, env: Env, httpd, proto, repeat): + if not env.curl_is_debug(): + pytest.skip('only works for curl debug builds') + count = 10 + docname = 'data.json' + url = f'https://localhost:{env.https_port}/{docname}' + client = LocalClient(name='hx-download', env=env, run_env={ + 'CURL_GRACEFUL_SHUTDOWN': '2000', + 'CURL_DEBUG': 'ssl' + }) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + r = client.run(args=[ + '-n', f'{count}', '-f', '-V', proto, url + ]) + r.check_exit_code(0) + shutdowns = [line for line in r.trace_lines + if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)] + assert len(shutdowns) == count, f'{shutdowns}' + + # run event-based downloads with CURLOPT_FORBID_REUSE set, meaning *we* close + # the connection after each request + @pytest.mark.parametrize("proto", ['http/1.1']) + def test_19_05_event_shutdown_by_server(self, env: Env, httpd, proto, repeat): + if not env.curl_is_debug(): + pytest.skip('only works for curl debug builds') + count = 10 + curl = CurlClient(env=env, run_env={ + # forbid connection reuse to trigger shutdowns after transfer + 'CURL_FORBID_REUSE': '1', + # make socket receives block 50% of the time to delay shutdown + 'CURL_DBG_SOCK_RBLOCK': '50', + 'CURL_DEBUG': 'ssl' + }) + url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak/?'\ + f'id=[0-{count-1}]&with_cl&' + r = curl.http_download(urls=[url], alpn_proto=proto, extra_args=[ + '--test-event' + ]) + r.check_response(http_status=200, count=count) + # check that we closed all connections + closings = [line for line in r.trace_lines + if re.match(r'.*CCACHE\] closing #\d+', line)] + assert len(closings) == count, f'{closings}' + # check that all connection sockets were removed from event + removes = [line for line in r.trace_lines + if re.match(r'.*socket cb: socket \d+ REMOVED', line)] + assert len(removes) == count, f'{removes}' + + # check graceful shutdown on multiplexed http + @pytest.mark.parametrize("proto", ['h2', 'h3']) + def test_19_06_check_shutdown(self, env: Env, httpd, nghttpx, repeat, proto): + if proto == 'h3' and not env.have_h3(): + pytest.skip("h3 not supported") + if not env.curl_is_debug(): + pytest.skip('only works for curl debug builds') + curl = CurlClient(env=env, run_env={ + 'CURL_GRACEFUL_SHUTDOWN': '2000', + 'CURL_DEBUG': 'all' + }) + url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]' + r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[ + '--parallel' + ]) + r.check_response(http_status=200, count=2) + # check connection cache closings + shutdowns = [line for line in r.trace_lines + if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)] + assert len(shutdowns) == 1, f'{shutdowns}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_20_websockets.py b/local-test-curl-delta-01/afc-curl/tests/http/test_20_websockets.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9df306b31c0405d673d780d7d97a956a703062 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_20_websockets.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import shutil +import subprocess +import time +from datetime import datetime, timedelta +import pytest + +from testenv import Env, CurlClient, LocalClient + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.curl_has_protocol('ws'), + reason='curl lacks ws protocol support') +class TestWebsockets: + + def check_alive(self, env, timeout=5): + curl = CurlClient(env=env) + url = f'http://localhost:{env.ws_port}/' + end = datetime.now() + timedelta(seconds=timeout) + while datetime.now() < end: + r = curl.http_download(urls=[url]) + if r.exit_code == 0: + return True + time.sleep(.1) + return False + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def _rmrf(self, path): + if os.path.exists(path): + return shutil.rmtree(path) + + @pytest.fixture(autouse=True, scope='class') + def ws_echo(self, env): + run_dir = os.path.join(env.gen_dir, 'ws-echo-server') + err_file = os.path.join(run_dir, 'stderr') + self._rmrf(run_dir) + self._mkpath(run_dir) + + with open(err_file, 'w') as cerr: + cmd = os.path.join(env.project_dir, + 'tests/http/testenv/ws_echo_server.py') + args = [cmd, '--port', str(env.ws_port)] + p = subprocess.Popen(args=args, cwd=run_dir, stderr=cerr, + stdout=cerr) + assert self.check_alive(env) + yield + p.terminate() + + def test_20_01_basic(self, env: Env, ws_echo, repeat): + curl = CurlClient(env=env) + url = f'http://localhost:{env.ws_port}/' + r = curl.http_download(urls=[url]) + r.check_response(http_status=426) + + def test_20_02_pingpong_small(self, env: Env, ws_echo, repeat): + payload = 125 * "x" + client = LocalClient(env=env, name='ws-pingpong') + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, payload]) + r.check_exit_code(0) + + # the python websocket server does not like 'large' control frames + def test_20_03_pingpong_too_large(self, env: Env, ws_echo, repeat): + payload = 127 * "x" + client = LocalClient(env=env, name='ws-pingpong') + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, payload]) + r.check_exit_code(56) + + # the python websocket server does not like 'large' control frames + def test_20_04_data_small(self, env: Env, ws_echo, repeat): + client = LocalClient(env=env, name='ws-data') + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, str(0), str(10)]) + r.check_exit_code(0) + + # the python websocket server does not like 'large' control frames + def test_20_05_data_med(self, env: Env, ws_echo, repeat): + client = LocalClient(env=env, name='ws-data') + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, str(120), str(130)]) + r.check_exit_code(0) + + # the python websocket server does not like 'large' control frames + def test_20_06_data_large(self, env: Env, ws_echo, repeat): + client = LocalClient(env=env, name='ws-data') + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, str(65535 - 5), str(65535 + 5)]) + r.check_exit_code(0) + + # the python websocket server does not like 'large' control frames + def test_20_07_data_large_small_recv(self, env: Env, ws_echo, repeat): + client = LocalClient(env=env, name='ws-data', run_env={ + 'CURL_WS_CHUNK_SIZE': '1024', + }) + if not client.exists(): + pytest.skip(f'example client not built: {client.name}') + url = f'ws://localhost:{env.ws_port}/' + r = client.run(args=[url, str(65535 - 5), str(65535 + 5)]) + r.check_exit_code(0) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_30_vsftpd.py b/local-test-curl-delta-01/afc-curl/tests/http/test_30_vsftpd.py new file mode 100644 index 0000000000000000000000000000000000000000..238184c2a4adf1ad421db921123148358e30e71c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_30_vsftpd.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import difflib +import filecmp +import logging +import os +import shutil +import pytest + +from testenv import Env, CurlClient, VsFTPD + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.has_vsftpd(), reason="missing vsftpd") +class TestVsFTPD: + + @pytest.fixture(autouse=True, scope='class') + def vsftpd(self, env): + vsftpd = VsFTPD(env=env) + assert vsftpd.start() + yield vsftpd + vsftpd.stop() + + def _make_docs_file(self, docs_dir: str, fname: str, fsize: int): + fpath = os.path.join(docs_dir, fname) + data1k = 1024*'x' + flen = 0 + with open(fpath, 'w') as fd: + while flen < fsize: + fd.write(data1k) + flen += len(data1k) + return flen + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, vsftpd): + if os.path.exists(vsftpd.docs_dir): + shutil.rmtree(vsftpd.docs_dir) + if not os.path.exists(vsftpd.docs_dir): + os.makedirs(vsftpd.docs_dir) + self._make_docs_file(docs_dir=vsftpd.docs_dir, fname='data-1k', fsize=1024) + self._make_docs_file(docs_dir=vsftpd.docs_dir, fname='data-10k', fsize=10*1024) + self._make_docs_file(docs_dir=vsftpd.docs_dir, fname='data-1m', fsize=1024*1024) + self._make_docs_file(docs_dir=vsftpd.docs_dir, fname='data-10m', fsize=10*1024*1024) + env.make_data_file(indir=env.gen_dir, fname="upload-1k", fsize=1024) + env.make_data_file(indir=env.gen_dir, fname="upload-100k", fsize=100*1024) + env.make_data_file(indir=env.gen_dir, fname="upload-1m", fsize=1024*1024) + + def test_30_01_list_dir(self, env: Env, vsftpd: VsFTPD, repeat): + curl = CurlClient(env=env) + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/' + r = curl.ftp_get(urls=[url], with_stats=True) + r.check_stats(count=1, http_status=226) + lines = open(os.path.join(curl.run_dir, 'download_#1.data')).readlines() + assert len(lines) == 4, f'list: {lines}' + + # download 1 file, no SSL + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_30_02_download_1(self, env: Env, vsftpd: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpd.docs_dir, f'{docname}') + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/{docname}?[0-{count-1}]' + r = curl.ftp_get(urls=[url], with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_30_03_download_10_serial(self, env: Env, vsftpd: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpd.docs_dir, f'{docname}') + count = 10 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/{docname}?[0-{count-1}]' + r = curl.ftp_get(urls=[url], with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_30_04_download_10_parallel(self, env: Env, vsftpd: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpd.docs_dir, f'{docname}') + count = 10 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/{docname}?[0-{count-1}]' + r = curl.ftp_get(urls=[url], with_stats=True, extra_args=[ + '--parallel' + ]) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'upload-1k', 'upload-100k', 'upload-1m' + ]) + def test_30_05_upload_1(self, env: Env, vsftpd: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpd.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/' + r = curl.ftp_upload(urls=[url], fupload=f'{srcfile}', with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_upload(env, vsftpd, docname=docname) + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + # check with `tcpdump` if curl causes any TCP RST packets + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + def test_30_06_shutdownh_download(self, env: Env, vsftpd: VsFTPD, repeat): + docname = 'data-1k' + curl = CurlClient(env=env) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/{docname}?[0-{count-1}]' + r = curl.ftp_get(urls=[url], with_stats=True, with_tcpdump=True) + r.check_stats(count=count, http_status=226) + assert r.tcpdump + assert len(r.tcpdump.stats) == 0, 'Unexpected TCP RSTs packets' + + # check with `tcpdump` if curl causes any TCP RST packets + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + def test_30_07_shutdownh_upload(self, env: Env, vsftpd: VsFTPD, repeat): + docname = 'upload-1k' + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpd.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/' + r = curl.ftp_upload(urls=[url], fupload=f'{srcfile}', with_stats=True, with_tcpdump=True) + r.check_stats(count=count, http_status=226) + assert r.tcpdump + assert len(r.tcpdump.stats) == 0, 'Unexpected TCP RSTs packets' + + def test_30_08_active_download(self, env: Env, vsftpd: VsFTPD): + docname = 'data-10k' + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpd.docs_dir, f'{docname}') + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/{docname}?[0-{count-1}]' + r = curl.ftp_get(urls=[url], with_stats=True, extra_args=[ + '--ftp-port', '127.0.0.1' + ]) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + def test_30_09_active_upload(self, env: Env, vsftpd: VsFTPD): + docname = 'upload-1k' + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpd.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpd.port}/' + r = curl.ftp_upload(urls=[url], fupload=f'{srcfile}', with_stats=True, extra_args=[ + '--ftp-port', '127.0.0.1' + ]) + r.check_stats(count=count, http_status=226) + self.check_upload(env, vsftpd, docname=docname) + + def check_downloads(self, client, srcfile: str, count: int, + complete: bool = True): + for i in range(count): + dfile = client.download_file(i) + assert os.path.exists(dfile) + if complete and not filecmp.cmp(srcfile, dfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dfile).readlines(), + fromfile=srcfile, + tofile=dfile, + n=1)) + assert False, f'download {dfile} differs:\n{diff}' + + def check_upload(self, env, vsftpd: VsFTPD, docname): + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpd.docs_dir, docname) + assert os.path.exists(srcfile) + assert os.path.exists(dstfile) + if not filecmp.cmp(srcfile, dstfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dstfile).readlines(), + fromfile=srcfile, + tofile=dstfile, + n=1)) + assert False, f'upload {dstfile} differs:\n{diff}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/test_31_vsftpds.py b/local-test-curl-delta-01/afc-curl/tests/http/test_31_vsftpds.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7b223ecccbb4821af8dfba71d1a50dd5cdd8f6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/test_31_vsftpds.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import difflib +import filecmp +import logging +import os +import shutil +import pytest + +from testenv import Env, CurlClient, VsFTPD + + +log = logging.getLogger(__name__) + + +@pytest.mark.skipif(condition=not Env.has_vsftpd(), reason="missing vsftpd") +class TestVsFTPD: + + SUPPORTS_SSL = True + + @pytest.fixture(autouse=True, scope='class') + def vsftpds(self, env): + if not TestVsFTPD.SUPPORTS_SSL: + pytest.skip('vsftpd does not seem to support SSL') + vsftpds = VsFTPD(env=env, with_ssl=True) + if not vsftpds.start(): + vsftpds.stop() + TestVsFTPD.SUPPORTS_SSL = False + pytest.skip('vsftpd does not seem to support SSL') + yield vsftpds + vsftpds.stop() + + def _make_docs_file(self, docs_dir: str, fname: str, fsize: int): + fpath = os.path.join(docs_dir, fname) + data1k = 1024*'x' + flen = 0 + with open(fpath, 'w') as fd: + while flen < fsize: + fd.write(data1k) + flen += len(data1k) + return flen + + @pytest.fixture(autouse=True, scope='class') + def _class_scope(self, env, vsftpds): + if os.path.exists(vsftpds.docs_dir): + shutil.rmtree(vsftpds.docs_dir) + if not os.path.exists(vsftpds.docs_dir): + os.makedirs(vsftpds.docs_dir) + self._make_docs_file(docs_dir=vsftpds.docs_dir, fname='data-1k', fsize=1024) + self._make_docs_file(docs_dir=vsftpds.docs_dir, fname='data-10k', fsize=10*1024) + self._make_docs_file(docs_dir=vsftpds.docs_dir, fname='data-1m', fsize=1024*1024) + self._make_docs_file(docs_dir=vsftpds.docs_dir, fname='data-10m', fsize=10*1024*1024) + env.make_data_file(indir=env.gen_dir, fname="upload-1k", fsize=1024) + env.make_data_file(indir=env.gen_dir, fname="upload-100k", fsize=100*1024) + env.make_data_file(indir=env.gen_dir, fname="upload-1m", fsize=1024*1024) + + def test_31_01_list_dir(self, env: Env, vsftpds: VsFTPD, repeat): + curl = CurlClient(env=env) + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/' + r = curl.ftp_ssl_get(urls=[url], with_stats=True) + r.check_stats(count=1, http_status=226) + lines = open(os.path.join(curl.run_dir, 'download_#1.data')).readlines() + assert len(lines) == 4, f'list: {lines}' + + # download 1 file, no SSL + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_31_02_download_1(self, env: Env, vsftpds: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpds.docs_dir, f'{docname}') + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}?[0-{count-1}]' + r = curl.ftp_ssl_get(urls=[url], with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_31_03_download_10_serial(self, env: Env, vsftpds: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpds.docs_dir, f'{docname}') + count = 10 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}?[0-{count-1}]' + r = curl.ftp_ssl_get(urls=[url], with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'data-1k', 'data-1m', 'data-10m' + ]) + def test_31_04_download_10_parallel(self, env: Env, vsftpds: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpds.docs_dir, f'{docname}') + count = 10 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}?[0-{count-1}]' + r = curl.ftp_ssl_get(urls=[url], with_stats=True, extra_args=[ + '--parallel' + ]) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + @pytest.mark.parametrize("docname", [ + 'upload-1k', 'upload-100k', 'upload-1m' + ]) + def test_31_05_upload_1(self, env: Env, vsftpds: VsFTPD, docname, repeat): + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpds.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/' + r = curl.ftp_ssl_upload(urls=[url], fupload=f'{srcfile}', with_stats=True) + r.check_stats(count=count, http_status=226) + self.check_upload(env, vsftpds, docname=docname) + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + # check with `tcpdump` if curl causes any TCP RST packets + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + def test_31_06_shutdownh_download(self, env: Env, vsftpds: VsFTPD, repeat): + docname = 'data-1k' + curl = CurlClient(env=env) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}?[0-{count-1}]' + r = curl.ftp_ssl_get(urls=[url], with_stats=True, with_tcpdump=True) + r.check_stats(count=count, http_status=226) + # vsftp closes control connection without niceties, + # disregard RST packets it sent from its port to curl + assert len(r.tcpdump.stats_excluding(src_port=env.ftps_port)) == 0, 'Unexpected TCP RSTs packets' + + # check with `tcpdump` if curl causes any TCP RST packets + @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available") + def test_31_07_shutdownh_upload(self, env: Env, vsftpds: VsFTPD, repeat): + docname = 'upload-1k' + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpds.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/' + r = curl.ftp_ssl_upload(urls=[url], fupload=f'{srcfile}', with_stats=True, with_tcpdump=True) + r.check_stats(count=count, http_status=226) + # vsftp closes control connection without niceties, + # disregard RST packets it sent from its port to curl + assert len(r.tcpdump.stats_excluding(src_port=env.ftps_port)) == 0, 'Unexpected TCP RSTs packets' + + def test_31_08_upload_ascii(self, env: Env, vsftpds: VsFTPD): + docname = 'upload-ascii' + line_length = 21 + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpds.docs_dir, docname) + env.make_data_file(indir=env.gen_dir, fname=docname, fsize=100*1024, + line_length=line_length) + srcsize = os.path.getsize(srcfile) + self._rmf(dstfile) + count = 1 + curl = CurlClient(env=env) + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/' + r = curl.ftp_ssl_upload(urls=[url], fupload=f'{srcfile}', with_stats=True, + extra_args=['--use-ascii']) + r.check_stats(count=count, http_status=226) + # expect the uploaded file to be number of converted newlines larger + dstsize = os.path.getsize(dstfile) + newlines = len(open(srcfile).readlines()) + assert (srcsize + newlines) == dstsize, \ + f'expected source with {newlines} lines to be that much larger,'\ + f'instead srcsize={srcsize}, upload size={dstsize}, diff={dstsize-srcsize}' + + def test_31_08_active_download(self, env: Env, vsftpds: VsFTPD): + docname = 'data-10k' + curl = CurlClient(env=env) + srcfile = os.path.join(vsftpds.docs_dir, f'{docname}') + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}?[0-{count-1}]' + r = curl.ftp_ssl_get(urls=[url], with_stats=True, extra_args=[ + '--ftp-port', '127.0.0.1' + ]) + r.check_stats(count=count, http_status=226) + self.check_downloads(curl, srcfile, count) + + def test_31_09_active_upload(self, env: Env, vsftpds: VsFTPD): + docname = 'upload-1k' + curl = CurlClient(env=env) + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpds.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/' + r = curl.ftp_ssl_upload(urls=[url], fupload=f'{srcfile}', with_stats=True, extra_args=[ + '--ftp-port', '127.0.0.1' + ]) + r.check_stats(count=count, http_status=226) + self.check_upload(env, vsftpds, docname=docname) + + @pytest.mark.parametrize("indata", [ + '1234567890', '' + ]) + def test_31_10_upload_stdin(self, env: Env, vsftpds: VsFTPD, indata): + curl = CurlClient(env=env) + docname = "upload_31_10" + dstfile = os.path.join(vsftpds.docs_dir, docname) + self._rmf(dstfile) + count = 1 + url = f'ftp://{env.ftp_domain}:{vsftpds.port}/{docname}' + r = curl.ftp_ssl_upload(urls=[url], updata=indata, with_stats=True) + r.check_stats(count=count, http_status=226) + assert os.path.exists(dstfile) + destdata = open(dstfile).readlines() + expdata = [indata] if len(indata) else [] + assert expdata == destdata, f'exected: {expdata}, got: {destdata}' + + def check_downloads(self, client, srcfile: str, count: int, + complete: bool = True): + for i in range(count): + dfile = client.download_file(i) + assert os.path.exists(dfile) + if complete and not filecmp.cmp(srcfile, dfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dfile).readlines(), + fromfile=srcfile, + tofile=dfile, + n=1)) + assert False, f'download {dfile} differs:\n{diff}' + + def check_upload(self, env, vsftpd: VsFTPD, docname): + srcfile = os.path.join(env.gen_dir, docname) + dstfile = os.path.join(vsftpd.docs_dir, docname) + assert os.path.exists(srcfile) + assert os.path.exists(dstfile) + if not filecmp.cmp(srcfile, dstfile, shallow=False): + diff = "".join(difflib.unified_diff(a=open(srcfile).readlines(), + b=open(dstfile).readlines(), + fromfile=srcfile, + tofile=dstfile, + n=1)) + assert False, f'upload {dstfile} differs:\n{diff}' diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/__init__.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..539af2aadfbf30e4263096e1109d39ee4ce37a38 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/__init__.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# ruff: noqa: F401, E402 +import pytest +pytest.register_assert_rewrite("testenv.env", "testenv.curl", "testenv.caddy", + "testenv.httpd", "testenv.nghttpx") + +from .env import Env +from .certs import TestCA, Credentials +from .caddy import Caddy +from .httpd import Httpd +from .curl import CurlClient, ExecResult, RunProfile +from .client import LocalClient +from .nghttpx import Nghttpx, NghttpxQuic, NghttpxFwd +from .vsftpd import VsFTPD diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/caddy.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/caddy.py new file mode 100644 index 0000000000000000000000000000000000000000..748ef3d5fe1d1b1f8e294b0194cb08ba6a8a2542 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/caddy.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import subprocess +import time +from datetime import timedelta, datetime +from json import JSONEncoder + +from .curl import CurlClient +from .env import Env + + +log = logging.getLogger(__name__) + + +class Caddy: + + def __init__(self, env: Env): + self.env = env + self._caddy = os.environ['CADDY'] if 'CADDY' in os.environ else env.caddy + self._caddy_dir = os.path.join(env.gen_dir, 'caddy') + self._docs_dir = os.path.join(self._caddy_dir, 'docs') + self._conf_file = os.path.join(self._caddy_dir, 'Caddyfile') + self._error_log = os.path.join(self._caddy_dir, 'caddy.log') + self._tmp_dir = os.path.join(self._caddy_dir, 'tmp') + self._process = None + self._rmf(self._error_log) + + @property + def docs_dir(self): + return self._docs_dir + + @property + def port(self) -> int: + return self.env.caddy_https_port + + def clear_logs(self): + self._rmf(self._error_log) + + def is_running(self): + if self._process: + self._process.poll() + return self._process.returncode is None + return False + + def start_if_needed(self): + if not self.is_running(): + return self.start() + return True + + def start(self, wait_live=True): + self._mkpath(self._tmp_dir) + if self._process: + self.stop() + self._write_config() + args = [ + self._caddy, 'run' + ] + caddyerr = open(self._error_log, 'a') + self._process = subprocess.Popen(args=args, cwd=self._caddy_dir, stderr=caddyerr) + if self._process.returncode is not None: + return False + return not wait_live or self.wait_live(timeout=timedelta(seconds=5)) + + def stop_if_running(self): + if self.is_running(): + return self.stop() + return True + + def stop(self, wait_dead=True): + self._mkpath(self._tmp_dir) + if self._process: + self._process.terminate() + self._process.wait(timeout=2) + self._process = None + return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5)) + return True + + def restart(self): + self.stop() + return self.start() + + def wait_dead(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'https://{self.env.domain1}:{self.port}/' + r = curl.http_get(url=check_url) + if r.exit_code != 0: + return True + log.debug(f'waiting for caddy to stop responding: {r}') + time.sleep(.1) + log.debug(f"Server still responding after {timeout}") + return False + + def wait_live(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'https://{self.env.domain1}:{self.port}/' + r = curl.http_get(url=check_url) + if r.exit_code == 0: + return True + time.sleep(.1) + log.error(f"Caddy still not responding after {timeout}") + return False + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def _write_config(self): + domain1 = self.env.domain1 + creds1 = self.env.get_credentials(domain1) + assert creds1 # convince pytype this isn't None + domain2 = self.env.domain2 + creds2 = self.env.get_credentials(domain2) + assert creds2 # convince pytype this isn't None + self._mkpath(self._docs_dir) + self._mkpath(self._tmp_dir) + with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd: + data = { + 'server': f'{domain1}', + } + fd.write(JSONEncoder().encode(data)) + with open(self._conf_file, 'w') as fd: + conf = [ # base server config + '{', + f' http_port {self.env.caddy_http_port}', + f' https_port {self.env.caddy_https_port}', + f' servers :{self.env.caddy_https_port} {{', + ' protocols h3 h2 h1', + ' }', + '}', + f'{domain1}:{self.env.caddy_https_port} {{', + ' file_server * {', + f' root {self._docs_dir}', + ' }', + f' tls {creds1.cert_file} {creds1.pkey_file}', + '}', + f'{domain2} {{', + f' reverse_proxy /* http://localhost:{self.env.http_port} {{', + ' }', + f' tls {creds2.cert_file} {creds2.pkey_file}', + '}', + ] + fd.write("\n".join(conf)) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/certs.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/certs.py new file mode 100644 index 0000000000000000000000000000000000000000..3795ba947a47804747c7805ec6619d60aed144f7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/certs.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import ipaddress +import os +import re +from datetime import timedelta, datetime, timezone +from typing import List, Any, Optional + +from cryptography import x509 +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, rsa +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption, load_pem_private_key +from cryptography.x509 import ExtendedKeyUsageOID, NameOID + + +EC_SUPPORTED = {} +EC_SUPPORTED.update([(curve.name.upper(), curve) for curve in [ + ec.SECP192R1, + ec.SECP224R1, + ec.SECP256R1, + ec.SECP384R1, +]]) + + +def _private_key(key_type): + if isinstance(key_type, str): + key_type = key_type.upper() + m = re.match(r'^(RSA)?(\d+)$', key_type) + if m: + key_type = int(m.group(2)) + + if isinstance(key_type, int): + return rsa.generate_private_key( + public_exponent=65537, + key_size=key_type, + backend=default_backend() + ) + if not isinstance(key_type, ec.EllipticCurve) and key_type in EC_SUPPORTED: + key_type = EC_SUPPORTED[key_type] + return ec.generate_private_key( + curve=key_type, + backend=default_backend() + ) + + +class CertificateSpec: + + def __init__(self, name: Optional[str] = None, + domains: Optional[List[str]] = None, + email: Optional[str] = None, + key_type: Optional[str] = None, + single_file: bool = False, + valid_from: timedelta = timedelta(days=-1), + valid_to: timedelta = timedelta(days=89), + client: bool = False, + check_valid: bool = True, + sub_specs: Optional[List['CertificateSpec']] = None): + self._name = name + self.domains = domains + self.client = client + self.email = email + self.key_type = key_type + self.single_file = single_file + self.valid_from = valid_from + self.valid_to = valid_to + self.sub_specs = sub_specs + self.check_valid = check_valid + + @property + def name(self) -> Optional[str]: + if self._name: + return self._name + elif self.domains: + return self.domains[0] + return None + + @property + def type(self) -> Optional[str]: + if self.domains and len(self.domains): + return "server" + elif self.client: + return "client" + elif self.name: + return "ca" + return None + + +class Credentials: + + def __init__(self, + name: str, + cert: Any, + pkey: Any, + issuer: Optional['Credentials'] = None): + self._name = name + self._cert = cert + self._pkey = pkey + self._issuer = issuer + self._cert_file = None + self._pkey_file = None + self._store = None + self._combined_file = None + + @property + def name(self) -> str: + return self._name + + @property + def subject(self) -> x509.Name: + return self._cert.subject + + @property + def key_type(self): + if isinstance(self._pkey, RSAPrivateKey): + return f"rsa{self._pkey.key_size}" + elif isinstance(self._pkey, EllipticCurvePrivateKey): + return f"{self._pkey.curve.name}" + else: + raise Exception(f"unknown key type: {self._pkey}") + + @property + def private_key(self) -> Any: + return self._pkey + + @property + def certificate(self) -> Any: + return self._cert + + @property + def cert_pem(self) -> bytes: + return self._cert.public_bytes(Encoding.PEM) + + @property + def pkey_pem(self) -> bytes: + return self._pkey.private_bytes( + Encoding.PEM, + PrivateFormat.TraditionalOpenSSL if self.key_type.startswith('rsa') else PrivateFormat.PKCS8, + NoEncryption()) + + @property + def issuer(self) -> Optional['Credentials']: + return self._issuer + + def set_store(self, store: 'CertStore'): + self._store = store + + def set_files(self, cert_file: str, pkey_file: Optional[str] = None, + combined_file: Optional[str] = None): + self._cert_file = cert_file + self._pkey_file = pkey_file + self._combined_file = combined_file + + @property + def cert_file(self) -> str: + return self._cert_file + + @property + def pkey_file(self) -> Optional[str]: + return self._pkey_file + + @property + def combined_file(self) -> Optional[str]: + return self._combined_file + + def get_first(self, name) -> Optional['Credentials']: + creds = self._store.get_credentials_for_name(name) if self._store else [] + return creds[0] if len(creds) else None + + def get_credentials_for_name(self, name) -> List['Credentials']: + return self._store.get_credentials_for_name(name) if self._store else [] + + def issue_certs(self, specs: List[CertificateSpec], + chain: Optional[List['Credentials']] = None) -> List['Credentials']: + return [self.issue_cert(spec=spec, chain=chain) for spec in specs] + + def issue_cert(self, spec: CertificateSpec, + chain: Optional[List['Credentials']] = None) -> 'Credentials': + key_type = spec.key_type if spec.key_type else self.key_type + creds = None + if self._store: + creds = self._store.load_credentials( + name=spec.name, key_type=key_type, single_file=spec.single_file, + issuer=self, check_valid=spec.check_valid) + if creds is None: + creds = TestCA.create_credentials(spec=spec, issuer=self, key_type=key_type, + valid_from=spec.valid_from, valid_to=spec.valid_to) + if self._store: + self._store.save(creds, single_file=spec.single_file) + if spec.type == "ca": + self._store.save_chain(creds, "ca", with_root=True) + + if spec.sub_specs: + if self._store: + sub_store = CertStore(fpath=os.path.join(self._store.path, creds.name)) + creds.set_store(sub_store) + subchain = chain.copy() if chain else [] + subchain.append(self) + creds.issue_certs(spec.sub_specs, chain=subchain) + return creds + + +class CertStore: + + def __init__(self, fpath: str): + self._store_dir = fpath + if not os.path.exists(self._store_dir): + os.makedirs(self._store_dir) + self._creds_by_name = {} + + @property + def path(self) -> str: + return self._store_dir + + def save(self, creds: Credentials, name: Optional[str] = None, + chain: Optional[List[Credentials]] = None, + single_file: bool = False) -> None: + name = name if name is not None else creds.name + cert_file = self.get_cert_file(name=name, key_type=creds.key_type) + pkey_file = self.get_pkey_file(name=name, key_type=creds.key_type) + comb_file = self.get_combined_file(name=name, key_type=creds.key_type) + if single_file: + pkey_file = None + with open(cert_file, "wb") as fd: + fd.write(creds.cert_pem) + if chain: + for c in chain: + fd.write(c.cert_pem) + if pkey_file is None: + fd.write(creds.pkey_pem) + if pkey_file is not None: + with open(pkey_file, "wb") as fd: + fd.write(creds.pkey_pem) + with open(comb_file, "wb") as fd: + fd.write(creds.cert_pem) + if chain: + for c in chain: + fd.write(c.cert_pem) + fd.write(creds.pkey_pem) + creds.set_files(cert_file, pkey_file, comb_file) + self._add_credentials(name, creds) + + def save_chain(self, creds: Credentials, infix: str, with_root=False): + name = creds.name + chain = [creds] + while creds.issuer is not None: + creds = creds.issuer + chain.append(creds) + if not with_root and len(chain) > 1: + chain = chain[:-1] + chain_file = os.path.join(self._store_dir, f'{name}-{infix}.pem') + with open(chain_file, "wb") as fd: + for c in chain: + fd.write(c.cert_pem) + + def _add_credentials(self, name: str, creds: Credentials): + if name not in self._creds_by_name: + self._creds_by_name[name] = [] + self._creds_by_name[name].append(creds) + + def get_credentials_for_name(self, name) -> List[Credentials]: + return self._creds_by_name[name] if name in self._creds_by_name else [] + + def get_cert_file(self, name: str, key_type=None) -> str: + key_infix = ".{0}".format(key_type) if key_type is not None else "" + return os.path.join(self._store_dir, f'{name}{key_infix}.cert.pem') + + def get_pkey_file(self, name: str, key_type=None) -> str: + key_infix = ".{0}".format(key_type) if key_type is not None else "" + return os.path.join(self._store_dir, f'{name}{key_infix}.pkey.pem') + + def get_combined_file(self, name: str, key_type=None) -> str: + return os.path.join(self._store_dir, f'{name}.pem') + + def load_pem_cert(self, fpath: str) -> x509.Certificate: + with open(fpath) as fd: + return x509.load_pem_x509_certificate("".join(fd.readlines()).encode()) + + def load_pem_pkey(self, fpath: str): + with open(fpath) as fd: + return load_pem_private_key("".join(fd.readlines()).encode(), password=None) + + def load_credentials(self, name: str, key_type=None, + single_file: bool = False, + issuer: Optional[Credentials] = None, + check_valid: bool = False): + cert_file = self.get_cert_file(name=name, key_type=key_type) + pkey_file = cert_file if single_file else self.get_pkey_file(name=name, key_type=key_type) + comb_file = self.get_combined_file(name=name, key_type=key_type) + if os.path.isfile(cert_file) and os.path.isfile(pkey_file): + cert = self.load_pem_cert(cert_file) + pkey = self.load_pem_pkey(pkey_file) + try: + now = datetime.now(tz=timezone.utc) + if check_valid and \ + ((cert.not_valid_after_utc < now) or + (cert.not_valid_before_utc > now)): + return None + except AttributeError: # older python + now = datetime.now() + if check_valid and \ + ((cert.not_valid_after < now) or + (cert.not_valid_before > now)): + return None + creds = Credentials(name=name, cert=cert, pkey=pkey, issuer=issuer) + creds.set_store(self) + creds.set_files(cert_file, pkey_file, comb_file) + self._add_credentials(name, creds) + return creds + return None + + +class TestCA: + + @classmethod + def create_root(cls, name: str, store_dir: str, key_type: str = "rsa2048") -> Credentials: + store = CertStore(fpath=store_dir) + creds = store.load_credentials(name="ca", key_type=key_type, issuer=None) + if creds is None: + creds = TestCA._make_ca_credentials(name=name, key_type=key_type) + store.save(creds, name="ca") + creds.set_store(store) + return creds + + @staticmethod + def create_credentials(spec: CertificateSpec, issuer: Credentials, key_type: Any, + valid_from: timedelta = timedelta(days=-1), + valid_to: timedelta = timedelta(days=89), + ) -> Credentials: + """ + Create a certificate signed by this CA for the given domains. + + :returns: the certificate and private key PEM file paths + """ + if spec.domains and len(spec.domains): + creds = TestCA._make_server_credentials(name=spec.name, domains=spec.domains, + issuer=issuer, valid_from=valid_from, + valid_to=valid_to, key_type=key_type) + elif spec.client: + creds = TestCA._make_client_credentials(name=spec.name, issuer=issuer, + email=spec.email, valid_from=valid_from, + valid_to=valid_to, key_type=key_type) + elif spec.name: + creds = TestCA._make_ca_credentials(name=spec.name, issuer=issuer, + valid_from=valid_from, valid_to=valid_to, + key_type=key_type) + else: + raise Exception(f"unrecognized certificate specification: {spec}") + return creds + + @staticmethod + def _make_x509_name(org_name: Optional[str] = None, common_name: Optional[str] = None, parent: x509.Name = None) -> x509.Name: + name_pieces = [] + if org_name: + oid = NameOID.ORGANIZATIONAL_UNIT_NAME if parent else NameOID.ORGANIZATION_NAME + name_pieces.append(x509.NameAttribute(oid, org_name)) + elif common_name: + name_pieces.append(x509.NameAttribute(NameOID.COMMON_NAME, common_name)) + if parent: + name_pieces.extend(list(parent)) + return x509.Name(name_pieces) + + @staticmethod + def _make_csr( + subject: x509.Name, + pkey: Any, + issuer_subject: Optional[Credentials], + valid_from_delta: Optional[timedelta] = None, + valid_until_delta: Optional[timedelta] = None + ): + pubkey = pkey.public_key() + issuer_subject = issuer_subject if issuer_subject is not None else subject + + valid_from = datetime.now() + if valid_until_delta is not None: + valid_from += valid_from_delta + valid_until = datetime.now() + if valid_until_delta is not None: + valid_until += valid_until_delta + + return ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer_subject) + .public_key(pubkey) + .not_valid_before(valid_from) + .not_valid_after(valid_until) + .serial_number(x509.random_serial_number()) + .add_extension( + x509.SubjectKeyIdentifier.from_public_key(pubkey), + critical=False, + ) + ) + + @staticmethod + def _add_ca_usages(csr: Any) -> Any: + return csr.add_extension( + x509.BasicConstraints(ca=True, path_length=9), + critical=True, + ).add_extension( + x509.KeyUsage( + digital_signature=True, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=True, + crl_sign=True, + encipher_only=False, + decipher_only=False), + critical=True + ).add_extension( + x509.ExtendedKeyUsage([ + ExtendedKeyUsageOID.CLIENT_AUTH, + ExtendedKeyUsageOID.SERVER_AUTH, + ExtendedKeyUsageOID.CODE_SIGNING, + ]), + critical=True + ) + + @staticmethod + def _add_leaf_usages(csr: Any, domains: List[str], issuer: Credentials) -> Any: + names = [] + for name in domains: + try: + names.append(x509.IPAddress(ipaddress.ip_address(name))) + # TODO: specify specific exceptions here + except: # noqa: E722 + names.append(x509.DNSName(name)) + + return csr.add_extension( + x509.BasicConstraints(ca=False, path_length=None), + critical=True, + ).add_extension( + x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier( + issuer.certificate.extensions.get_extension_for_class( + x509.SubjectKeyIdentifier).value), + critical=False + ).add_extension( + x509.SubjectAlternativeName(names), critical=True, + ).add_extension( + x509.ExtendedKeyUsage([ + ExtendedKeyUsageOID.SERVER_AUTH, + ]), + critical=False + ) + + @staticmethod + def _add_client_usages(csr: Any, issuer: Credentials, rfc82name: Optional[str] = None) -> Any: + cert = csr.add_extension( + x509.BasicConstraints(ca=False, path_length=None), + critical=True, + ).add_extension( + x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier( + issuer.certificate.extensions.get_extension_for_class( + x509.SubjectKeyIdentifier).value), + critical=False + ) + if rfc82name: + cert.add_extension( + x509.SubjectAlternativeName([x509.RFC822Name(rfc82name)]), + critical=True, + ) + cert.add_extension( + x509.ExtendedKeyUsage([ + ExtendedKeyUsageOID.CLIENT_AUTH, + ]), + critical=True + ) + return cert + + @staticmethod + def _make_ca_credentials(name, key_type: Any, + issuer: Optional[Credentials] = None, + valid_from: timedelta = timedelta(days=-1), + valid_to: timedelta = timedelta(days=89), + ) -> Credentials: + pkey = _private_key(key_type=key_type) + if issuer is not None: + issuer_subject = issuer.certificate.subject + issuer_key = issuer.private_key + else: + issuer_subject = None + issuer_key = pkey + subject = TestCA._make_x509_name(org_name=name, parent=issuer.subject if issuer else None) + csr = TestCA._make_csr(subject=subject, + issuer_subject=issuer_subject, pkey=pkey, + valid_from_delta=valid_from, valid_until_delta=valid_to) + csr = TestCA._add_ca_usages(csr) + cert = csr.sign(private_key=issuer_key, + algorithm=hashes.SHA256(), + backend=default_backend()) + return Credentials(name=name, cert=cert, pkey=pkey, issuer=issuer) + + @staticmethod + def _make_server_credentials(name: str, domains: List[str], issuer: Credentials, + key_type: Any, + valid_from: timedelta = timedelta(days=-1), + valid_to: timedelta = timedelta(days=89), + ) -> Credentials: + pkey = _private_key(key_type=key_type) + subject = TestCA._make_x509_name(common_name=name, parent=issuer.subject) + csr = TestCA._make_csr(subject=subject, + issuer_subject=issuer.certificate.subject, pkey=pkey, + valid_from_delta=valid_from, valid_until_delta=valid_to) + csr = TestCA._add_leaf_usages(csr, domains=domains, issuer=issuer) + cert = csr.sign(private_key=issuer.private_key, + algorithm=hashes.SHA256(), + backend=default_backend()) + return Credentials(name=name, cert=cert, pkey=pkey, issuer=issuer) + + @staticmethod + def _make_client_credentials(name: str, + issuer: Credentials, email: Optional[str], + key_type: Any, + valid_from: timedelta = timedelta(days=-1), + valid_to: timedelta = timedelta(days=89), + ) -> Credentials: + pkey = _private_key(key_type=key_type) + subject = TestCA._make_x509_name(common_name=name, parent=issuer.subject) + csr = TestCA._make_csr(subject=subject, + issuer_subject=issuer.certificate.subject, pkey=pkey, + valid_from_delta=valid_from, valid_until_delta=valid_to) + csr = TestCA._add_client_usages(csr, issuer=issuer, rfc82name=email) + cert = csr.sign(private_key=issuer.private_key, + algorithm=hashes.SHA256(), + backend=default_backend()) + return Credentials(name=name, cert=cert, pkey=pkey, issuer=issuer) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/client.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/client.py new file mode 100644 index 0000000000000000000000000000000000000000..3981752ec49e3e4a139641e765ce0da71e4541af --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/client.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import shutil +import subprocess +from datetime import datetime +from typing import Optional, Dict + +from . import ExecResult +from .env import Env + + +log = logging.getLogger(__name__) + + +class LocalClient: + + def __init__(self, name: str, env: Env, run_dir: Optional[str] = None, + timeout: Optional[float] = None, + run_env: Optional[Dict[str,str]] = None): + self.name = name + self.path = os.path.join(env.build_dir, f'tests/http/clients/{name}') + self.env = env + self._run_env = run_env + self._timeout = timeout if timeout else env.test_timeout + self._curl = os.environ['CURL'] if 'CURL' in os.environ else env.curl + self._run_dir = run_dir if run_dir else os.path.join(env.gen_dir, name) + self._stdoutfile = f'{self._run_dir}/stdout' + self._stderrfile = f'{self._run_dir}/stderr' + self._rmrf(self._run_dir) + self._mkpath(self._run_dir) + + @property + def run_dir(self) -> str: + return self._run_dir + + @property + def stderr_file(self) -> str: + return self._stderrfile + + def exists(self) -> bool: + return os.path.exists(self.path) + + def download_file(self, i: int) -> str: + return os.path.join(self._run_dir, f'download_{i}.data') + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _rmrf(self, path): + if os.path.exists(path): + return shutil.rmtree(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def run(self, args): + self._rmf(self._stdoutfile) + self._rmf(self._stderrfile) + start = datetime.now() + exception = None + myargs = [self.path] + myargs.extend(args) + run_env = None + if self._run_env: + run_env = self._run_env.copy() + for key in ['CURL_DEBUG']: + if key in os.environ and key not in run_env: + run_env[key] = os.environ[key] + try: + with open(self._stdoutfile, 'w') as cout, open(self._stderrfile, 'w') as cerr: + p = subprocess.run(myargs, stderr=cerr, stdout=cout, + cwd=self._run_dir, shell=False, + input=None, env=run_env, + timeout=self._timeout) + exitcode = p.returncode + except subprocess.TimeoutExpired: + log.warning(f'Timeout after {self._timeout}s: {args}') + exitcode = -1 + exception = 'TimeoutExpired' + coutput = open(self._stdoutfile).readlines() + cerrput = open(self._stderrfile).readlines() + return ExecResult(args=myargs, exit_code=exitcode, exception=exception, + stdout=coutput, stderr=cerrput, + duration=datetime.now() - start) + + def dump_logs(self): + lines = [] + lines.append('>>--stdout ----------------------------------------------\n') + lines.extend(open(self._stdoutfile).readlines()) + lines.append('>>--stderr ----------------------------------------------\n') + lines.extend(open(self._stderrfile).readlines()) + lines.append('<<-------------------------------------------------------\n') + return ''.join(lines) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/curl.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/curl.py new file mode 100644 index 0000000000000000000000000000000000000000..ee224d9a67d308b33d637d33de17a2c6d0912216 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/curl.py @@ -0,0 +1,945 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import json +import logging +import os +import sys +import time +from threading import Thread + +import psutil +import re +import shutil +import subprocess +from statistics import mean, fmean +from datetime import timedelta, datetime +from typing import List, Optional, Dict, Union, Any +from urllib.parse import urlparse + +from .env import Env + + +log = logging.getLogger(__name__) + + +class RunProfile: + + STAT_KEYS = ['cpu', 'rss', 'vsz'] + + @classmethod + def AverageStats(cls, profiles: List['RunProfile']): + avg = {} + stats = [p.stats for p in profiles] + for key in cls.STAT_KEYS: + vals = [s[key] for s in stats] + avg[key] = mean(vals) if len(vals) else 0.0 + return avg + + def __init__(self, pid: int, started_at: datetime, run_dir): + self._pid = pid + self._started_at = started_at + self._duration = timedelta(seconds=0) + self._run_dir = run_dir + self._samples = [] + self._psu = None + self._stats = None + + @property + def duration(self) -> timedelta: + return self._duration + + @property + def stats(self) -> Optional[Dict[str,Any]]: + return self._stats + + def sample(self): + elapsed = datetime.now() - self._started_at + try: + if self._psu is None: + self._psu = psutil.Process(pid=self._pid) + mem = self._psu.memory_info() + self._samples.append({ + 'time': elapsed, + 'cpu': self._psu.cpu_percent(), + 'vsz': mem.vms, + 'rss': mem.rss, + }) + except psutil.NoSuchProcess: + pass + + def finish(self): + self._duration = datetime.now() - self._started_at + if len(self._samples) > 0: + weights = [s['time'].total_seconds() for s in self._samples] + self._stats = {} + for key in self.STAT_KEYS: + self._stats[key] = fmean([s[key] for s in self._samples], weights) + else: + self._stats = None + self._psu = None + + def __repr__(self): + return f'RunProfile[pid={self._pid}, '\ + f'duration={self.duration.total_seconds():.3f}s, '\ + f'stats={self.stats}]' + + +class RunTcpDump: + + def __init__(self, env, run_dir): + self._env = env + self._run_dir = run_dir + self._proc = None + self._stdoutfile = os.path.join(self._run_dir, 'tcpdump.out') + self._stderrfile = os.path.join(self._run_dir, 'tcpdump.err') + + @property + def stats(self) -> Optional[List[str]]: + if self._proc: + raise Exception('tcpdump still running') + return [line + for line in open(self._stdoutfile) + if re.match(r'.* IP 127\.0\.0\.1\.\d+ [<>] 127\.0\.0\.1\.\d+:.*', line)] + + def stats_excluding(self, src_port) -> Optional[List[str]]: + if self._proc: + raise Exception('tcpdump still running') + return [line + for line in self.stats + if not re.match(r'.* IP 127\.0\.0\.1\.' + str(src_port) + ' >.*', line)] + + @property + def stderr(self) -> List[str]: + if self._proc: + raise Exception('tcpdump still running') + return open(self._stderrfile).readlines() + + def sample(self): + # not sure how to make that detection reliable for all platforms + local_if = 'lo0' if sys.platform.startswith('darwin') else 'lo' + try: + tcpdump = self._env.tcpdump() + if tcpdump is None: + raise Exception('tcpdump not available') + # look with tcpdump for TCP RST packets which indicate + # we did not shut down connections cleanly + args = [] + # at least on Linux, we need root permissions to run tcpdump + if sys.platform.startswith('linux'): + args.append('sudo') + args.extend([ + tcpdump, '-i', local_if, '-n', 'tcp[tcpflags] & (tcp-rst)!=0' + ]) + with open(self._stdoutfile, 'w') as cout, open(self._stderrfile, 'w') as cerr: + self._proc = subprocess.Popen(args, stdout=cout, stderr=cerr, + text=True, cwd=self._run_dir, + shell=False) + assert self._proc + assert self._proc.returncode is None + while self._proc: + try: + self._proc.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + except Exception: + log.exception('Tcpdump') + + def start(self): + def do_sample(): + self.sample() + t = Thread(target=do_sample) + t.start() + + def finish(self): + if self._proc: + time.sleep(1) + self._proc.terminate() + self._proc = None + + +class ExecResult: + + def __init__(self, args: List[str], exit_code: int, + stdout: List[str], stderr: List[str], + duration: Optional[timedelta] = None, + with_stats: bool = False, + exception: Optional[str] = None, + profile: Optional[RunProfile] = None, + tcpdump: Optional[RunTcpDump] = None): + self._args = args + self._exit_code = exit_code + self._exception = exception + self._stdout = stdout + self._stderr = stderr + self._profile = profile + self._tcpdump = tcpdump + self._duration = duration if duration is not None else timedelta() + self._response = None + self._responses = [] + self._results = {} + self._assets = [] + self._stats = [] + self._json_out = None + self._with_stats = with_stats + if with_stats: + self._parse_stats() + else: + # noinspection PyBroadException + try: + out = ''.join(self._stdout) + self._json_out = json.loads(out) + except: # noqa: E722 + pass + + def __repr__(self): + return f"ExecResult[code={self.exit_code}, exception={self._exception}, "\ + f"args={self._args}, stdout={self._stdout}, stderr={self._stderr}]" + + def _parse_stats(self): + self._stats = [] + for line in self._stdout: + try: + self._stats.append(json.loads(line)) + # TODO: specify specific exceptions here + except: # noqa: E722 + log.exception(f'not a JSON stat: {line}') + break + + @property + def exit_code(self) -> int: + return self._exit_code + + @property + def args(self) -> List[str]: + return self._args + + @property + def outraw(self) -> bytes: + return ''.join(self._stdout).encode() + + @property + def stdout(self) -> str: + return ''.join(self._stdout) + + @property + def json(self) -> Optional[Dict]: + """Output as JSON dictionary or None if not parseable.""" + return self._json_out + + @property + def stderr(self) -> str: + return ''.join(self._stderr) + + @property + def trace_lines(self) -> List[str]: + return self._stderr + + @property + def duration(self) -> timedelta: + return self._duration + + @property + def profile(self) -> Optional[RunProfile]: + return self._profile + + @property + def tcpdump(self) -> Optional[RunTcpDump]: + return self._tcpdump + + @property + def response(self) -> Optional[Dict]: + return self._response + + @property + def responses(self) -> List[Dict]: + return self._responses + + @property + def results(self) -> Dict: + return self._results + + @property + def assets(self) -> List: + return self._assets + + @property + def with_stats(self) -> bool: + return self._with_stats + + @property + def stats(self) -> List: + return self._stats + + @property + def total_connects(self) -> Optional[int]: + if len(self.stats): + n = 0 + for stat in self.stats: + n += stat['num_connects'] + return n + return None + + def add_response(self, resp: Dict): + self._response = resp + self._responses.append(resp) + + def add_results(self, results: Dict): + self._results.update(results) + if 'response' in results: + self.add_response(results['response']) + + def add_assets(self, assets: List): + self._assets.extend(assets) + + def check_exit_code(self, code: Union[int, bool]): + if code is True: + assert self.exit_code == 0, f'expected exit code {code}, '\ + f'got {self.exit_code}\n{self.dump_logs()}' + elif code is False: + assert self.exit_code != 0, f'expected exit code {code}, '\ + f'got {self.exit_code}\n{self.dump_logs()}' + else: + assert self.exit_code == code, f'expected exit code {code}, '\ + f'got {self.exit_code}\n{self.dump_logs()}' + + def check_response(self, http_status: Optional[int] = 200, + count: Optional[int] = 1, + protocol: Optional[str] = None, + exitcode: Optional[int] = 0, + connect_count: Optional[int] = None): + if exitcode: + self.check_exit_code(exitcode) + if self.with_stats and isinstance(exitcode, int): + for idx, x in enumerate(self.stats): + if 'exitcode' in x: + assert int(x['exitcode']) == exitcode, \ + f'response #{idx} exitcode: expected {exitcode}, '\ + f'got {x["exitcode"]}\n{self.dump_logs()}' + + if self.with_stats: + assert len(self.stats) == count, \ + f'response count: expected {count}, ' \ + f'got {len(self.stats)}\n{self.dump_logs()}' + else: + assert len(self.responses) == count, \ + f'response count: expected {count}, ' \ + f'got {len(self.responses)}\n{self.dump_logs()}' + if http_status is not None: + if self.with_stats: + for idx, x in enumerate(self.stats): + assert 'http_code' in x, \ + f'response #{idx} reports no http_code\n{self.dump_stat(x)}' + assert x['http_code'] == http_status, \ + f'response #{idx} http_code: expected {http_status}, '\ + f'got {x["http_code"]}\n{self.dump_stat(x)}' + else: + for idx, x in enumerate(self.responses): + assert x['status'] == http_status, \ + f'response #{idx} status: expected {http_status},'\ + f'got {x["status"]}\n{self.dump_stat(x)}' + if protocol is not None: + if self.with_stats: + http_version = None + if protocol == 'HTTP/1.1': + http_version = '1.1' + elif protocol == 'HTTP/2': + http_version = '2' + elif protocol == 'HTTP/3': + http_version = '3' + if http_version is not None: + for idx, x in enumerate(self.stats): + assert x['http_version'] == http_version, \ + f'response #{idx} protocol: expected http/{http_version},' \ + f'got version {x["http_version"]}\n{self.dump_stat(x)}' + else: + for idx, x in enumerate(self.responses): + assert x['protocol'] == protocol, \ + f'response #{idx} protocol: expected {protocol},'\ + f'got {x["protocol"]}\n{self.dump_logs()}' + if connect_count is not None: + assert self.total_connects == connect_count, \ + f'expected {connect_count}, but {self.total_connects} '\ + f'were made\n{self.dump_logs()}' + + def check_stats(self, count: int, http_status: Optional[int] = None, + exitcode: Optional[int] = None, + remote_port: Optional[int] = None, + remote_ip: Optional[str] = None): + if exitcode is None: + self.check_exit_code(0) + assert len(self.stats) == count, \ + f'stats count: expected {count}, got {len(self.stats)}\n{self.dump_logs()}' + if http_status is not None: + for idx, x in enumerate(self.stats): + assert 'http_code' in x, \ + f'status #{idx} reports no http_code\n{self.dump_stat(x)}' + assert x['http_code'] == http_status, \ + f'status #{idx} http_code: expected {http_status}, '\ + f'got {x["http_code"]}\n{self.dump_stat(x)}' + if exitcode is not None: + for idx, x in enumerate(self.stats): + if 'exitcode' in x: + assert x['exitcode'] == exitcode, \ + f'status #{idx} exitcode: expected {exitcode}, '\ + f'got {x["exitcode"]}\n{self.dump_stat(x)}' + if remote_port is not None: + for idx, x in enumerate(self.stats): + assert 'remote_port' in x, f'remote_port missing\n{self.dump_stat(x)}' + assert x['remote_port'] == remote_port, \ + f'status #{idx} remote_port: expected {remote_port}, '\ + f'got {x["remote_port"]}\n{self.dump_stat(x)}' + if remote_ip is not None: + for idx, x in enumerate(self.stats): + assert 'remote_ip' in x, f'remote_ip missing\n{self.dump_stat(x)}' + assert x['remote_ip'] == remote_ip, \ + f'status #{idx} remote_ip: expected {remote_ip}, '\ + f'got {x["remote_ip"]}\n{self.dump_stat(x)}' + + def dump_logs(self): + lines = ['>>--stdout ----------------------------------------------\n'] + lines.extend(self._stdout) + lines.append('>>--stderr ----------------------------------------------\n') + lines.extend(self._stderr) + lines.append('<<-------------------------------------------------------\n') + return ''.join(lines) + + def dump_stat(self, x): + lines = [ + 'json stat from curl:', + json.JSONEncoder(indent=2).encode(x), + ] + if 'xfer_id' in x: + xfer_id = x['xfer_id'] + lines.append(f'>>--xfer {xfer_id} trace:\n') + lines.extend(self.xfer_trace_for(xfer_id)) + else: + lines.append('>>--full trace-------------------------------------------\n') + lines.extend(self._stderr) + lines.append('<<-------------------------------------------------------\n') + return ''.join(lines) + + def xfer_trace_for(self, xfer_id) -> List[str]: + pat = re.compile(f'^[^[]* \\[{xfer_id}-.*$') + return [line for line in self._stderr if pat.match(line)] + + +class CurlClient: + + ALPN_ARG = { + 'http/0.9': '--http0.9', + 'http/1.0': '--http1.0', + 'http/1.1': '--http1.1', + 'h2': '--http2', + 'h2c': '--http2', + 'h3': '--http3-only', + } + + def __init__(self, env: Env, + run_dir: Optional[str] = None, + timeout: Optional[float] = None, + silent: bool = False, + run_env: Optional[Dict[str, str]] = None, + server_addr: Optional[str] = None): + self.env = env + self._timeout = timeout if timeout else env.test_timeout + self._curl = os.environ['CURL'] if 'CURL' in os.environ else env.curl + self._run_dir = run_dir if run_dir else os.path.join(env.gen_dir, 'curl') + self._stdoutfile = f'{self._run_dir}/curl.stdout' + self._stderrfile = f'{self._run_dir}/curl.stderr' + self._headerfile = f'{self._run_dir}/curl.headers' + self._log_path = f'{self._run_dir}/curl.log' + self._silent = silent + self._run_env = run_env + self._server_addr = server_addr if server_addr else '127.0.0.1' + self._rmrf(self._run_dir) + self._mkpath(self._run_dir) + + @property + def run_dir(self) -> str: + return self._run_dir + + def download_file(self, i: int) -> str: + return os.path.join(self.run_dir, f'download_{i}.data') + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _rmrf(self, path): + if os.path.exists(path): + return shutil.rmtree(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def get_proxy_args(self, proto: str = 'http/1.1', + proxys: bool = True, tunnel: bool = False, + use_ip: bool = False): + proxy_name = self._server_addr if use_ip else self.env.proxy_domain + if proxys: + pport = self.env.pts_port(proto) if tunnel else self.env.proxys_port + xargs = [ + '--proxy', f'https://{proxy_name}:{pport}/', + '--resolve', f'{proxy_name}:{pport}:{self._server_addr}', + '--proxy-cacert', self.env.ca.cert_file, + ] + if proto == 'h2': + xargs.append('--proxy-http2') + else: + xargs = [ + '--proxy', f'http://{proxy_name}:{self.env.proxy_port}/', + '--resolve', f'{proxy_name}:{self.env.proxy_port}:{self._server_addr}', + ] + if tunnel: + xargs.append('--proxytunnel') + return xargs + + def http_get(self, url: str, extra_args: Optional[List[str]] = None, + alpn_proto: Optional[str] = None, + def_tracing: bool = True, + with_stats: bool = False, + with_profile: bool = False, + with_tcpdump: bool = False): + return self._raw(url, options=extra_args, + with_stats=with_stats, + alpn_proto=alpn_proto, + def_tracing=def_tracing, + with_profile=with_profile, + with_tcpdump=with_tcpdump) + + def http_download(self, urls: List[str], + alpn_proto: Optional[str] = None, + with_stats: bool = True, + with_headers: bool = False, + with_profile: bool = False, + with_tcpdump: bool = False, + no_save: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + if no_save: + extra_args.extend([ + '-o', '/dev/null', + ]) + else: + extra_args.extend([ + '-o', 'download_#1.data', + ]) + # remove any existing ones + for i in range(100): + self._rmf(self.download_file(i)) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, alpn_proto=alpn_proto, options=extra_args, + with_stats=with_stats, + with_headers=with_headers, + with_profile=with_profile, + with_tcpdump=with_tcpdump) + + def http_upload(self, urls: List[str], data: str, + alpn_proto: Optional[str] = None, + with_stats: bool = True, + with_headers: bool = False, + with_profile: bool = False, + with_tcpdump: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + extra_args.extend([ + '--data-binary', data, '-o', 'download_#1.data', + ]) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, alpn_proto=alpn_proto, options=extra_args, + with_stats=with_stats, + with_headers=with_headers, + with_profile=with_profile, + with_tcpdump=with_tcpdump) + + def http_delete(self, urls: List[str], + alpn_proto: Optional[str] = None, + with_stats: bool = True, + with_profile: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + extra_args.extend([ + '-X', 'DELETE', '-o', '/dev/null', + ]) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, alpn_proto=alpn_proto, options=extra_args, + with_stats=with_stats, + with_headers=False, + with_profile=with_profile) + + def http_put(self, urls: List[str], data=None, fdata=None, + alpn_proto: Optional[str] = None, + with_stats: bool = True, + with_headers: bool = False, + with_profile: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + if fdata is not None: + extra_args.extend(['-T', fdata]) + elif data is not None: + extra_args.extend(['-T', '-']) + extra_args.extend([ + '-o', 'download_#1.data', + ]) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, intext=data, + alpn_proto=alpn_proto, options=extra_args, + with_stats=with_stats, + with_headers=with_headers, + with_profile=with_profile) + + def http_form(self, urls: List[str], form: Dict[str, str], + alpn_proto: Optional[str] = None, + with_stats: bool = True, + with_headers: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + for key, val in form.items(): + extra_args.extend(['-F', f'{key}={val}']) + extra_args.extend([ + '-o', 'download_#1.data', + ]) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, alpn_proto=alpn_proto, options=extra_args, + with_stats=with_stats, + with_headers=with_headers) + + def ftp_get(self, urls: List[str], + with_stats: bool = True, + with_profile: bool = False, + with_tcpdump: bool = False, + no_save: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + if no_save: + extra_args.extend([ + '-o', '/dev/null', + ]) + else: + extra_args.extend([ + '-o', 'download_#1.data', + ]) + # remove any existing ones + for i in range(100): + self._rmf(self.download_file(i)) + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, options=extra_args, + with_stats=with_stats, + with_headers=False, + with_profile=with_profile, + with_tcpdump=with_tcpdump) + + def ftp_ssl_get(self, urls: List[str], + with_stats: bool = True, + with_profile: bool = False, + with_tcpdump: bool = False, + no_save: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + extra_args.extend([ + '--ssl-reqd', + ]) + return self.ftp_get(urls=urls, with_stats=with_stats, + with_profile=with_profile, no_save=no_save, + with_tcpdump=with_tcpdump, + extra_args=extra_args) + + def ftp_upload(self, urls: List[str], + fupload: Optional[Any] = None, + updata: Optional[str] = None, + with_stats: bool = True, + with_profile: bool = False, + with_tcpdump: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + if fupload is not None: + extra_args.extend([ + '--upload-file', fupload + ]) + elif updata is not None: + extra_args.extend([ + '--upload-file', '-' + ]) + else: + raise Exception('need either file or data to upload') + if with_stats: + extra_args.extend([ + '-w', '%{json}\\n' + ]) + return self._raw(urls, options=extra_args, + intext=updata, + with_stats=with_stats, + with_headers=False, + with_profile=with_profile, + with_tcpdump=with_tcpdump) + + def ftp_ssl_upload(self, urls: List[str], + fupload: Optional[Any] = None, + updata: Optional[str] = None, + with_stats: bool = True, + with_profile: bool = False, + with_tcpdump: bool = False, + extra_args: Optional[List[str]] = None): + if extra_args is None: + extra_args = [] + extra_args.extend([ + '--ssl-reqd', + ]) + return self.ftp_upload(urls=urls, fupload=fupload, updata=updata, + with_stats=with_stats, with_profile=with_profile, + with_tcpdump=with_tcpdump, + extra_args=extra_args) + + def response_file(self, idx: int): + return os.path.join(self._run_dir, f'download_{idx}.data') + + def run_direct(self, args, with_stats: bool = False, with_profile: bool = False): + my_args = [self._curl] + if with_stats: + my_args.extend([ + '-w', '%{json}\\n' + ]) + my_args.extend([ + '-o', 'download.data', + ]) + my_args.extend(args) + return self._run(args=my_args, with_stats=with_stats, with_profile=with_profile) + + def _run(self, args, intext='', with_stats: bool = False, + with_profile: bool = True, with_tcpdump: bool = False): + self._rmf(self._stdoutfile) + self._rmf(self._stderrfile) + self._rmf(self._headerfile) + exception = None + profile = None + tcpdump = None + started_at = datetime.now() + if with_tcpdump: + tcpdump = RunTcpDump(self.env, self._run_dir) + tcpdump.start() + try: + with open(self._stdoutfile, 'w') as cout, open(self._stderrfile, 'w') as cerr: + if with_profile: + end_at = started_at + timedelta(seconds=self._timeout) \ + if self._timeout else None + log.info(f'starting: {args}') + p = subprocess.Popen(args, stderr=cerr, stdout=cout, + cwd=self._run_dir, shell=False, + env=self._run_env) + profile = RunProfile(p.pid, started_at, self._run_dir) + if intext is not None and False: + p.communicate(input=intext.encode(), timeout=1) + ptimeout = 0.0 + while True: + try: + p.wait(timeout=ptimeout) + break + except subprocess.TimeoutExpired: + if end_at and datetime.now() >= end_at: + p.kill() + raise subprocess.TimeoutExpired(cmd=args, timeout=self._timeout) + profile.sample() + ptimeout = 0.01 + exitcode = p.returncode + profile.finish() + log.info(f'done: exit={exitcode}, profile={profile}') + else: + p = subprocess.run(args, stderr=cerr, stdout=cout, + cwd=self._run_dir, shell=False, + input=intext.encode() if intext else None, + timeout=self._timeout, + env=self._run_env) + exitcode = p.returncode + except subprocess.TimeoutExpired: + now = datetime.now() + duration = now - started_at + log.warning(f'Timeout at {now} after {duration.total_seconds()}s ' + f'(configured {self._timeout}s): {args}') + exitcode = -1 + exception = 'TimeoutExpired' + if tcpdump: + tcpdump.finish() + coutput = open(self._stdoutfile).readlines() + cerrput = open(self._stderrfile).readlines() + return ExecResult(args=args, exit_code=exitcode, exception=exception, + stdout=coutput, stderr=cerrput, + duration=datetime.now() - started_at, + with_stats=with_stats, + profile=profile, tcpdump=tcpdump) + + def _raw(self, urls, intext='', timeout=None, options=None, insecure=False, + alpn_proto: Optional[str] = None, + force_resolve=True, + with_stats=False, + with_headers=True, + def_tracing=True, + with_profile=False, + with_tcpdump=False): + args = self._complete_args( + urls=urls, timeout=timeout, options=options, insecure=insecure, + alpn_proto=alpn_proto, force_resolve=force_resolve, + with_headers=with_headers, def_tracing=def_tracing) + r = self._run(args, intext=intext, with_stats=with_stats, + with_profile=with_profile, with_tcpdump=with_tcpdump) + if r.exit_code == 0 and with_headers: + self._parse_headerfile(self._headerfile, r=r) + return r + + def _complete_args(self, urls, timeout=None, options=None, + insecure=False, force_resolve=True, + alpn_proto: Optional[str] = None, + with_headers: bool = True, + def_tracing: bool = True): + if not isinstance(urls, list): + urls = [urls] + + args = [self._curl, "-s", "--path-as-is"] + if 'CURL_TEST_EVENT' in os.environ: + args.append('--test-event') + + if with_headers: + args.extend(["-D", self._headerfile]) + if def_tracing is not False and not self._silent: + args.extend(['-v', '--trace-ids', '--trace-time']) + if self.env.verbose > 1: + args.extend(['--trace-config', 'http/2,http/3,h2-proxy,h1-proxy']) + + active_options = options + if options is not None and '--next' in options: + active_options = options[options.index('--next') + 1:] + + for url in urls: + u = urlparse(urls[0]) + if options: + args.extend(options) + if alpn_proto is not None: + if alpn_proto not in self.ALPN_ARG: + raise Exception(f'unknown ALPN protocol: "{alpn_proto}"') + args.append(self.ALPN_ARG[alpn_proto]) + + if u.scheme == 'http': + pass + elif insecure: + args.append('--insecure') + elif active_options and "--cacert" in active_options: + pass + elif u.hostname: + args.extend(["--cacert", self.env.ca.cert_file]) + + if force_resolve and u.hostname and u.hostname != 'localhost' \ + and not re.match(r'^(\d+|\[|:).*', u.hostname): + port = u.port if u.port else 443 + args.extend([ + '--resolve', f'{u.hostname}:{port}:{self._server_addr}', + ]) + if timeout is not None and int(timeout) > 0: + args.extend(["--connect-timeout", str(int(timeout))]) + args.append(url) + return args + + def _parse_headerfile(self, headerfile: str, r: Optional[ExecResult] = None) -> ExecResult: + lines = open(headerfile).readlines() + if r is None: + r = ExecResult(args=[], exit_code=0, stdout=[], stderr=[]) + + response = None + + def fin_response(resp): + if resp: + r.add_response(resp) + + expected = ['status'] + for line in lines: + line = line.strip() + if re.match(r'^$', line): + if 'trailer' in expected: + # end of trailers + fin_response(response) + response = None + expected = ['status'] + elif 'header' in expected: + # end of header, another status or trailers might follow + expected = ['status', 'trailer'] + else: + assert False, f"unexpected line: '{line}'" + continue + if 'status' in expected: + # log.debug("reading 1st response line: %s", line) + m = re.match(r'^(\S+) (\d+)( .*)?$', line) + if m: + fin_response(response) + response = { + "protocol": m.group(1), + "status": int(m.group(2)), + "description": m.group(3), + "header": {}, + "trailer": {}, + "body": r.outraw + } + expected = ['header'] + continue + if 'trailer' in expected: + m = re.match(r'^([^:]+):\s*(.*)$', line) + if m: + response['trailer'][m.group(1).lower()] = m.group(2) + continue + if 'header' in expected: + m = re.match(r'^([^:]+):\s*(.*)$', line) + if m: + response['header'][m.group(1).lower()] = m.group(2) + continue + assert False, f"unexpected line: '{line}, expected: {expected}'" + + fin_response(response) + return r diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/env.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/env.py new file mode 100644 index 0000000000000000000000000000000000000000..5360c4605547032caa0cd6f6f24c9e9f80dfca91 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/env.py @@ -0,0 +1,628 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import re +import shutil +import socket +import subprocess +import tempfile +from configparser import ConfigParser, ExtendedInterpolation +from datetime import timedelta +from typing import Optional + +from .certs import CertificateSpec, Credentials, TestCA +from .ports import alloc_ports + + +log = logging.getLogger(__name__) + + +def init_config_from(conf_path): + if os.path.isfile(conf_path): + config = ConfigParser(interpolation=ExtendedInterpolation()) + config.read(conf_path) + return config + return None + + +TESTS_HTTPD_PATH = os.path.dirname(os.path.dirname(__file__)) +TOP_PATH = os.path.join(os.getcwd(), os.path.pardir) +DEF_CONFIG = init_config_from(os.path.join(TOP_PATH, 'tests', 'http', 'config.ini')) +CURL = os.path.join(TOP_PATH, 'src', 'curl') + + +class EnvConfig: + + def __init__(self): + self.tests_dir = TESTS_HTTPD_PATH + self.gen_dir = os.path.join(self.tests_dir, 'gen') + self.project_dir = os.path.dirname(os.path.dirname(self.tests_dir)) + self.build_dir = TOP_PATH + self.config = DEF_CONFIG + # check cur and its features + self.curl = CURL + if 'CURL' in os.environ: + self.curl = os.environ['CURL'] + self.curl_props = { + 'version_string': '', + 'version': '', + 'os': '', + 'fullname': '', + 'features_string': '', + 'features': set(), + 'protocols_string': '', + 'protocols': set(), + 'libs': set(), + 'lib_versions': set(), + } + self.curl_is_debug = False + self.curl_protos = [] + p = subprocess.run(args=[self.curl, '-V'], + capture_output=True, text=True) + if p.returncode != 0: + raise RuntimeError(f'{self.curl} -V failed with exit code: {p.returncode}') + if p.stderr.startswith('WARNING:'): + self.curl_is_debug = True + for line in p.stdout.splitlines(keepends=False): + if line.startswith('curl '): + self.curl_props['version_string'] = line + m = re.match(r'^curl (?P\S+) (?P\S+) (?P.*)$', line) + if m: + self.curl_props['fullname'] = m.group(0) + self.curl_props['version'] = m.group('version') + self.curl_props['os'] = m.group('os') + self.curl_props['lib_versions'] = { + lib.lower() for lib in m.group('libs').split(' ') + } + self.curl_props['libs'] = { + re.sub(r'/[a-z0-9.-]*', '', lib) for lib in self.curl_props['lib_versions'] + } + if line.startswith('Features: '): + self.curl_props['features_string'] = line[10:] + self.curl_props['features'] = { + feat.lower() for feat in line[10:].split(' ') + } + if line.startswith('Protocols: '): + self.curl_props['protocols_string'] = line[11:] + self.curl_props['protocols'] = { + prot.lower() for prot in line[11:].split(' ') + } + + self.ports = alloc_ports(port_specs={ + 'ftp': socket.SOCK_STREAM, + 'ftps': socket.SOCK_STREAM, + 'http': socket.SOCK_STREAM, + 'https': socket.SOCK_STREAM, + 'nghttpx_https': socket.SOCK_STREAM, + 'proxy': socket.SOCK_STREAM, + 'proxys': socket.SOCK_STREAM, + 'h2proxys': socket.SOCK_STREAM, + 'caddy': socket.SOCK_STREAM, + 'caddys': socket.SOCK_STREAM, + 'ws': socket.SOCK_STREAM, + }) + self.httpd = self.config['httpd']['httpd'] + self.apachectl = self.config['httpd']['apachectl'] + self.apxs = self.config['httpd']['apxs'] + if len(self.apxs) == 0: + self.apxs = None + self._httpd_version = None + + self.examples_pem = { + 'key': 'xxx', + 'cert': 'xxx', + } + self.htdocs_dir = os.path.join(self.gen_dir, 'htdocs') + self.tld = 'http.curl.se' + self.domain1 = f"one.{self.tld}" + self.domain1brotli = f"brotli.one.{self.tld}" + self.domain2 = f"two.{self.tld}" + self.ftp_domain = f"ftp.{self.tld}" + self.proxy_domain = f"proxy.{self.tld}" + self.expired_domain = f"expired.{self.tld}" + self.cert_specs = [ + CertificateSpec(domains=[self.domain1, self.domain1brotli, 'localhost', '127.0.0.1'], key_type='rsa2048'), + CertificateSpec(domains=[self.domain2], key_type='rsa2048'), + CertificateSpec(domains=[self.ftp_domain], key_type='rsa2048'), + CertificateSpec(domains=[self.proxy_domain, '127.0.0.1'], key_type='rsa2048'), + CertificateSpec(domains=[self.expired_domain], key_type='rsa2048', + valid_from=timedelta(days=-100), valid_to=timedelta(days=-10)), + CertificateSpec(name="clientsX", sub_specs=[ + CertificateSpec(name="user1", client=True), + ]), + ] + + self.nghttpx = self.config['nghttpx']['nghttpx'] + if len(self.nghttpx.strip()) == 0: + self.nghttpx = None + self._nghttpx_version = None + self.nghttpx_with_h3 = False + if self.nghttpx is not None: + p = subprocess.run(args=[self.nghttpx, '-v'], + capture_output=True, text=True) + if p.returncode != 0: + # not a working nghttpx + self.nghttpx = None + else: + self._nghttpx_version = re.sub(r'^nghttpx\s*', '', p.stdout.strip()) + self.nghttpx_with_h3 = re.match(r'.* nghttp3/.*', p.stdout.strip()) is not None + log.debug(f'nghttpx -v: {p.stdout}') + + self.caddy = self.config['caddy']['caddy'] + self._caddy_version = None + if len(self.caddy.strip()) == 0: + self.caddy = None + if self.caddy is not None: + try: + p = subprocess.run(args=[self.caddy, 'version'], + capture_output=True, text=True) + if p.returncode != 0: + # not a working caddy + self.caddy = None + m = re.match(r'v?(\d+\.\d+\.\d+).*', p.stdout) + if m: + self._caddy_version = m.group(1) + else: + raise RuntimeError(f'Unable to determine cadd version from: {p.stdout}') + # TODO: specify specific exceptions here + except: # noqa: E722 + self.caddy = None + + self.vsftpd = self.config['vsftpd']['vsftpd'] + self._vsftpd_version = None + if self.vsftpd is not None: + try: + with tempfile.TemporaryFile('w+') as tmp: + p = subprocess.run(args=[self.vsftpd, '-v'], + capture_output=True, text=True, stdin=tmp) + if p.returncode != 0: + # not a working vsftpd + self.vsftpd = None + if p.stderr: + ver_text = p.stderr + else: + # Oddly, some versions of vsftpd write to stdin (!) + # instead of stderr, which is odd but works. If there + # is nothing on stderr, read the file on stdin and use + # any data there instead. + tmp.seek(0) + ver_text = tmp.read() + m = re.match(r'vsftpd: version (\d+\.\d+\.\d+)', ver_text) + if m: + self._vsftpd_version = m.group(1) + elif len(p.stderr) == 0: + # vsftp does not use stdout or stderr for printing its version... -.- + self._vsftpd_version = 'unknown' + else: + raise Exception(f'Unable to determine VsFTPD version from: {p.stderr}') + except Exception: + self.vsftpd = None + + self._tcpdump = shutil.which('tcpdump') + + @property + def httpd_version(self): + if self._httpd_version is None and self.apxs is not None: + try: + p = subprocess.run(args=[self.apxs, '-q', 'HTTPD_VERSION'], + capture_output=True, text=True) + if p.returncode != 0: + log.error(f'{self.apxs} failed to query HTTPD_VERSION: {p}') + else: + self._httpd_version = p.stdout.strip() + except Exception: + log.exception(f'{self.apxs} failed to run') + return self._httpd_version + + def versiontuple(self, v): + v = re.sub(r'(\d+\.\d+(\.\d+)?)(-\S+)?', r'\1', v) + return tuple(map(int, v.split('.'))) + + def httpd_is_at_least(self, minv): + if self.httpd_version is None: + return False + hv = self.versiontuple(self.httpd_version) + return hv >= self.versiontuple(minv) + + def caddy_is_at_least(self, minv): + if self.caddy_version is None: + return False + hv = self.versiontuple(self.caddy_version) + return hv >= self.versiontuple(minv) + + def is_complete(self) -> bool: + return os.path.isfile(self.httpd) and \ + os.path.isfile(self.apachectl) and \ + self.apxs is not None and \ + os.path.isfile(self.apxs) + + def get_incomplete_reason(self) -> Optional[str]: + if self.httpd is None or len(self.httpd.strip()) == 0: + return 'httpd not configured, see `--with-test-httpd=`' + if not os.path.isfile(self.httpd): + return f'httpd ({self.httpd}) not found' + if not os.path.isfile(self.apachectl): + return f'apachectl ({self.apachectl}) not found' + if self.apxs is None: + return "command apxs not found (commonly provided in apache2-dev)" + if not os.path.isfile(self.apxs): + return f"apxs ({self.apxs}) not found" + return None + + @property + def nghttpx_version(self): + return self._nghttpx_version + + @property + def caddy_version(self): + return self._caddy_version + + @property + def vsftpd_version(self): + return self._vsftpd_version + + @property + def tcpdmp(self) -> Optional[str]: + return self._tcpdump + + +class Env: + + CONFIG = EnvConfig() + + @staticmethod + def setup_incomplete() -> bool: + return not Env.CONFIG.is_complete() + + @staticmethod + def incomplete_reason() -> Optional[str]: + return Env.CONFIG.get_incomplete_reason() + + @staticmethod + def have_nghttpx() -> bool: + return Env.CONFIG.nghttpx is not None + + @staticmethod + def have_h3_server() -> bool: + return Env.CONFIG.nghttpx_with_h3 + + @staticmethod + def have_ssl_curl() -> bool: + return Env.curl_has_feature('ssl') or Env.curl_has_feature('multissl') + + @staticmethod + def have_h2_curl() -> bool: + return 'http2' in Env.CONFIG.curl_props['features'] + + @staticmethod + def have_h3_curl() -> bool: + return 'http3' in Env.CONFIG.curl_props['features'] + + @staticmethod + def curl_uses_lib(libname: str) -> bool: + return libname.lower() in Env.CONFIG.curl_props['libs'] + + @staticmethod + def curl_uses_ossl_quic() -> bool: + if Env.have_h3_curl(): + return not Env.curl_uses_lib('ngtcp2') and Env.curl_uses_lib('nghttp3') + return False + + @staticmethod + def curl_version_string() -> str: + return Env.CONFIG.curl_props['version_string'] + + @staticmethod + def curl_features_string() -> str: + return Env.CONFIG.curl_props['features_string'] + + @staticmethod + def curl_has_feature(feature: str) -> bool: + return feature.lower() in Env.CONFIG.curl_props['features'] + + @staticmethod + def curl_protocols_string() -> str: + return Env.CONFIG.curl_props['protocols_string'] + + @staticmethod + def curl_has_protocol(protocol: str) -> bool: + return protocol.lower() in Env.CONFIG.curl_props['protocols'] + + @staticmethod + def curl_lib_version(libname: str) -> str: + prefix = f'{libname.lower()}/' + for lversion in Env.CONFIG.curl_props['lib_versions']: + if lversion.startswith(prefix): + return lversion[len(prefix):] + return 'unknown' + + @staticmethod + def curl_lib_version_at_least(libname: str, min_version) -> bool: + lversion = Env.curl_lib_version(libname) + if lversion != 'unknown': + return Env.CONFIG.versiontuple(min_version) <= \ + Env.CONFIG.versiontuple(lversion) + return False + + @staticmethod + def curl_os() -> str: + return Env.CONFIG.curl_props['os'] + + @staticmethod + def curl_fullname() -> str: + return Env.CONFIG.curl_props['fullname'] + + @staticmethod + def curl_version() -> str: + return Env.CONFIG.curl_props['version'] + + @staticmethod + def curl_is_debug() -> bool: + return Env.CONFIG.curl_is_debug + + @staticmethod + def have_h3() -> bool: + return Env.have_h3_curl() and Env.have_h3_server() + + @staticmethod + def httpd_version() -> str: + return Env.CONFIG.httpd_version + + @staticmethod + def nghttpx_version() -> str: + return Env.CONFIG.nghttpx_version + + @staticmethod + def caddy_version() -> str: + return Env.CONFIG.caddy_version + + @staticmethod + def caddy_is_at_least(minv) -> bool: + return Env.CONFIG.caddy_is_at_least(minv) + + @staticmethod + def httpd_is_at_least(minv) -> bool: + return Env.CONFIG.httpd_is_at_least(minv) + + @staticmethod + def has_caddy() -> bool: + return Env.CONFIG.caddy is not None + + @staticmethod + def has_vsftpd() -> bool: + return Env.CONFIG.vsftpd is not None + + @staticmethod + def vsftpd_version() -> str: + return Env.CONFIG.vsftpd_version + + @staticmethod + def tcpdump() -> Optional[str]: + return Env.CONFIG.tcpdmp + + def __init__(self, pytestconfig=None): + self._verbose = pytestconfig.option.verbose \ + if pytestconfig is not None else 0 + self._ca = None + self._test_timeout = 300.0 if self._verbose > 1 else 60.0 # seconds + + def issue_certs(self): + if self._ca is None: + ca_dir = os.path.join(self.CONFIG.gen_dir, 'ca') + self._ca = TestCA.create_root(name=self.CONFIG.tld, + store_dir=ca_dir, + key_type="rsa2048") + self._ca.issue_certs(self.CONFIG.cert_specs) + + def setup(self): + os.makedirs(self.gen_dir, exist_ok=True) + os.makedirs(self.htdocs_dir, exist_ok=True) + self.issue_certs() + + def get_credentials(self, domain) -> Optional[Credentials]: + creds = self.ca.get_credentials_for_name(domain) + if len(creds) > 0: + return creds[0] + return None + + @property + def verbose(self) -> int: + return self._verbose + + @property + def test_timeout(self) -> Optional[float]: + return self._test_timeout + + @test_timeout.setter + def test_timeout(self, val: Optional[float]): + self._test_timeout = val + + @property + def gen_dir(self) -> str: + return self.CONFIG.gen_dir + + @property + def project_dir(self) -> str: + return self.CONFIG.project_dir + + @property + def build_dir(self) -> str: + return self.CONFIG.build_dir + + @property + def ca(self): + return self._ca + + @property + def htdocs_dir(self) -> str: + return self.CONFIG.htdocs_dir + + @property + def tld(self) -> str: + return self.CONFIG.tld + + @property + def domain1(self) -> str: + return self.CONFIG.domain1 + + @property + def domain1brotli(self) -> str: + return self.CONFIG.domain1brotli + + @property + def domain2(self) -> str: + return self.CONFIG.domain2 + + @property + def ftp_domain(self) -> str: + return self.CONFIG.ftp_domain + + @property + def proxy_domain(self) -> str: + return self.CONFIG.proxy_domain + + @property + def expired_domain(self) -> str: + return self.CONFIG.expired_domain + + @property + def http_port(self) -> int: + return self.CONFIG.ports['http'] + + @property + def https_port(self) -> int: + return self.CONFIG.ports['https'] + + @property + def nghttpx_https_port(self) -> int: + return self.CONFIG.ports['nghttpx_https'] + + @property + def h3_port(self) -> int: + return self.https_port + + @property + def proxy_port(self) -> int: + return self.CONFIG.ports['proxy'] + + @property + def proxys_port(self) -> int: + return self.CONFIG.ports['proxys'] + + @property + def ftp_port(self) -> int: + return self.CONFIG.ports['ftp'] + + @property + def ftps_port(self) -> int: + return self.CONFIG.ports['ftps'] + + @property + def h2proxys_port(self) -> int: + return self.CONFIG.ports['h2proxys'] + + def pts_port(self, proto: str = 'http/1.1') -> int: + # proxy tunnel port + return self.CONFIG.ports['h2proxys' if proto == 'h2' else 'proxys'] + + @property + def caddy(self) -> str: + return self.CONFIG.caddy + + @property + def caddy_https_port(self) -> int: + return self.CONFIG.ports['caddys'] + + @property + def caddy_http_port(self) -> int: + return self.CONFIG.ports['caddy'] + + @property + def vsftpd(self) -> str: + return self.CONFIG.vsftpd + + @property + def ws_port(self) -> int: + return self.CONFIG.ports['ws'] + + @property + def curl(self) -> str: + return self.CONFIG.curl + + @property + def httpd(self) -> str: + return self.CONFIG.httpd + + @property + def apachectl(self) -> str: + return self.CONFIG.apachectl + + @property + def apxs(self) -> str: + return self.CONFIG.apxs + + @property + def nghttpx(self) -> Optional[str]: + return self.CONFIG.nghttpx + + @property + def slow_network(self) -> bool: + return "CURL_DBG_SOCK_WBLOCK" in os.environ or \ + "CURL_DBG_SOCK_WPARTIAL" in os.environ + + @property + def ci_run(self) -> bool: + return "CURL_CI" in os.environ + + def port_for(self, alpn_proto: Optional[str] = None): + if alpn_proto is None or \ + alpn_proto in ['h2', 'http/1.1', 'http/1.0', 'http/0.9']: + return self.https_port + if alpn_proto in ['h3']: + return self.h3_port + return self.http_port + + def authority_for(self, domain: str, alpn_proto: Optional[str] = None): + return f'{domain}:{self.port_for(alpn_proto=alpn_proto)}' + + def make_data_file(self, indir: str, fname: str, fsize: int, + line_length: int = 1024) -> str: + if line_length < 11: + raise RuntimeError('line_length less than 11 not supported') + fpath = os.path.join(indir, fname) + s10 = "0123456789" + s = round((line_length / 10) + 1) * s10 + s = s[0:line_length-11] + with open(fpath, 'w') as fd: + for i in range(int(fsize / line_length)): + fd.write(f"{i:09d}-{s}\n") + remain = int(fsize % line_length) + if remain != 0: + i = int(fsize / line_length) + 1 + fd.write(f"{i:09d}-{s}"[0:remain-1] + "\n") + return fpath diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/httpd.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/httpd.py new file mode 100644 index 0000000000000000000000000000000000000000..414f358ee2465ad9c31fb05b008cc390027c5b68 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/httpd.py @@ -0,0 +1,493 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import inspect +import logging +import os +import subprocess +from datetime import timedelta, datetime +from json import JSONEncoder +import time +from typing import List, Union, Optional +import copy + +from .curl import CurlClient, ExecResult +from .env import Env + + +log = logging.getLogger(__name__) + + +class Httpd: + + MODULES = [ + 'log_config', 'logio', 'unixd', 'version', 'watchdog', + 'authn_core', 'authn_file', + 'authz_user', 'authz_core', 'authz_host', + 'auth_basic', 'auth_digest', + 'alias', 'env', 'filter', 'headers', 'mime', 'setenvif', + 'socache_shmcb', + 'rewrite', 'http2', 'ssl', 'proxy', 'proxy_http', 'proxy_connect', + 'brotli', + 'mpm_event', + ] + COMMON_MODULES_DIRS = [ + '/usr/lib/apache2/modules', # debian + '/usr/libexec/apache2/', # macos + ] + + MOD_CURLTEST = None + + def __init__(self, env: Env, proxy_auth: bool = False): + self.env = env + self._cmd = env.apachectl + self._apache_dir = os.path.join(env.gen_dir, 'apache') + self._run_dir = os.path.join(self._apache_dir, 'run') + self._lock_dir = os.path.join(self._apache_dir, 'locks') + self._docs_dir = os.path.join(self._apache_dir, 'docs') + self._conf_dir = os.path.join(self._apache_dir, 'conf') + self._conf_file = os.path.join(self._conf_dir, 'test.conf') + self._logs_dir = os.path.join(self._apache_dir, 'logs') + self._error_log = os.path.join(self._logs_dir, 'error_log') + self._tmp_dir = os.path.join(self._apache_dir, 'tmp') + self._basic_passwords = os.path.join(self._conf_dir, 'basic.passwords') + self._digest_passwords = os.path.join(self._conf_dir, 'digest.passwords') + self._mods_dir = None + self._auth_digest = True + self._proxy_auth_basic = proxy_auth + self._extra_configs = {} + self._loaded_extra_configs = None + assert env.apxs + p = subprocess.run(args=[env.apxs, '-q', 'libexecdir'], + capture_output=True, text=True) + if p.returncode != 0: + raise Exception(f'{env.apxs} failed to query libexecdir: {p}') + self._mods_dir = p.stdout.strip() + if self._mods_dir is None: + raise Exception('apache modules dir cannot be found') + if not os.path.exists(self._mods_dir): + raise Exception(f'apache modules dir does not exist: {self._mods_dir}') + self._process = None + self._rmf(self._error_log) + self._init_curltest() + + @property + def docs_dir(self): + return self._docs_dir + + def clear_logs(self): + self._rmf(self._error_log) + + def exists(self): + return os.path.exists(self._cmd) + + def set_extra_config(self, domain: str, lines: Optional[Union[str, List[str]]]): + if lines is None: + self._extra_configs.pop(domain, None) + else: + self._extra_configs[domain] = lines + + def clear_extra_configs(self): + self._extra_configs = {} + + def set_proxy_auth(self, active: bool): + self._proxy_auth_basic = active + + def _run(self, args, intext=''): + env = os.environ.copy() + env['APACHE_RUN_DIR'] = self._run_dir + env['APACHE_RUN_USER'] = os.environ['USER'] + env['APACHE_LOCK_DIR'] = self._lock_dir + env['APACHE_CONFDIR'] = self._apache_dir + p = subprocess.run(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE, + cwd=self.env.gen_dir, + input=intext.encode() if intext else None, + env=env) + start = datetime.now() + return ExecResult(args=args, exit_code=p.returncode, + stdout=p.stdout.decode().splitlines(), + stderr=p.stderr.decode().splitlines(), + duration=datetime.now() - start) + + def _apachectl(self, cmd: str): + args = [self.env.apachectl, + "-d", self._apache_dir, + "-f", self._conf_file, + "-k", cmd] + return self._run(args=args) + + def start(self): + if self._process: + self.stop() + self._write_config() + with open(self._error_log, 'a') as fd: + fd.write('start of server\n') + with open(os.path.join(self._apache_dir, 'xxx'), 'a') as fd: + fd.write('start of server\n') + r = self._apachectl('start') + if r.exit_code != 0: + log.error(f'failed to start httpd: {r}') + return False + self._loaded_extra_configs = copy.deepcopy(self._extra_configs) + return self.wait_live(timeout=timedelta(seconds=5)) + + def stop(self): + r = self._apachectl('stop') + self._loaded_extra_configs = None + if r.exit_code == 0: + return self.wait_dead(timeout=timedelta(seconds=5)) + log.fatal(f'stopping httpd failed: {r}') + return r.exit_code == 0 + + def restart(self): + self.stop() + return self.start() + + def reload(self): + self._write_config() + r = self._apachectl("graceful") + self._loaded_extra_configs = None + if r.exit_code != 0: + log.error(f'failed to reload httpd: {r}') + self._loaded_extra_configs = copy.deepcopy(self._extra_configs) + return self.wait_live(timeout=timedelta(seconds=5)) + + def reload_if_config_changed(self): + if self._loaded_extra_configs == self._extra_configs: + return True + return self.reload() + + def wait_dead(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/') + if r.exit_code != 0: + return True + time.sleep(.1) + log.debug(f"Server still responding after {timeout}") + return False + + def wait_live(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir, + timeout=timeout.total_seconds()) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + r = curl.http_get(url=f'http://{self.env.domain1}:{self.env.http_port}/') + if r.exit_code == 0: + return True + time.sleep(.1) + log.debug(f"Server still not responding after {timeout}") + return False + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def _write_config(self): + domain1 = self.env.domain1 + domain1brotli = self.env.domain1brotli + creds1 = self.env.get_credentials(domain1) + assert creds1 # convince pytype this isn't None + domain2 = self.env.domain2 + creds2 = self.env.get_credentials(domain2) + assert creds2 # convince pytype this isn't None + exp_domain = self.env.expired_domain + exp_creds = self.env.get_credentials(exp_domain) + assert exp_creds # convince pytype this isn't None + proxy_domain = self.env.proxy_domain + proxy_creds = self.env.get_credentials(proxy_domain) + assert proxy_creds # convince pytype this isn't None + self._mkpath(self._conf_dir) + self._mkpath(self._logs_dir) + self._mkpath(self._tmp_dir) + self._mkpath(os.path.join(self._docs_dir, 'two')) + with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd: + data = { + 'server': f'{domain1}', + } + fd.write(JSONEncoder().encode(data)) + with open(os.path.join(self._docs_dir, 'two/data.json'), 'w') as fd: + data = { + 'server': f'{domain2}', + } + fd.write(JSONEncoder().encode(data)) + if self._proxy_auth_basic: + with open(self._basic_passwords, 'w') as fd: + fd.write('proxy:$apr1$FQfeInbs$WQZbODJlVg60j0ogEIlTW/\n') + if self._auth_digest: + with open(self._digest_passwords, 'w') as fd: + fd.write('test:restricted area:57123e269fd73d71ae0656594e938e2f\n') + self._mkpath(os.path.join(self.docs_dir, 'restricted/digest')) + with open(os.path.join(self.docs_dir, 'restricted/digest/data.json'), 'w') as fd: + fd.write('{"area":"digest"}\n') + with open(self._conf_file, 'w') as fd: + for m in self.MODULES: + if os.path.exists(os.path.join(self._mods_dir, f'mod_{m}.so')): + fd.write(f'LoadModule {m}_module "{self._mods_dir}/mod_{m}.so"\n') + if Httpd.MOD_CURLTEST is not None: + fd.write(f'LoadModule curltest_module "{Httpd.MOD_CURLTEST}"\n') + conf = [ # base server config + f'ServerRoot "{self._apache_dir}"', + 'DefaultRuntimeDir logs', + 'PidFile httpd.pid', + f'ErrorLog {self._error_log}', + f'LogLevel {self._get_log_level()}', + 'StartServers 4', + 'ReadBufferSize 16000', + 'H2MinWorkers 16', + 'H2MaxWorkers 256', + f'Listen {self.env.http_port}', + f'Listen {self.env.https_port}', + f'Listen {self.env.proxy_port}', + f'Listen {self.env.proxys_port}', + f'TypesConfig "{self._conf_dir}/mime.types', + 'SSLSessionCache "shmcb:ssl_gcache_data(32000)"', + ] + if 'base' in self._extra_configs: + conf.extend(self._extra_configs['base']) + conf.extend([ # plain http host for domain1 + f'', + f' ServerName {domain1}', + ' ServerAlias localhost', + f' DocumentRoot "{self._docs_dir}"', + ' Protocols h2c http/1.1', + ' H2Direct on', + ]) + conf.extend(self._curltest_conf(domain1)) + conf.extend([ + '', + '', + ]) + conf.extend([ # https host for domain1, h1 + h2 + f'', + f' ServerName {domain1}', + ' ServerAlias localhost', + ' Protocols h2 http/1.1', + ' SSLEngine on', + f' SSLCertificateFile {creds1.cert_file}', + f' SSLCertificateKeyFile {creds1.pkey_file}', + f' DocumentRoot "{self._docs_dir}"', + ]) + conf.extend(self._curltest_conf(domain1)) + if domain1 in self._extra_configs: + conf.extend(self._extra_configs[domain1]) + conf.extend([ + '', + '', + ]) + # Alternate to domain1 with BROTLI compression + conf.extend([ # https host for domain1, h1 + h2 + f'', + f' ServerName {domain1brotli}', + ' Protocols h2 http/1.1', + ' SSLEngine on', + f' SSLCertificateFile {creds1.cert_file}', + f' SSLCertificateKeyFile {creds1.pkey_file}', + f' DocumentRoot "{self._docs_dir}"', + ' SetOutputFilter BROTLI_COMPRESS', + ]) + conf.extend(self._curltest_conf(domain1)) + if domain1 in self._extra_configs: + conf.extend(self._extra_configs[domain1]) + conf.extend([ + '', + '', + ]) + conf.extend([ # plain http host for domain2 + f'', + f' ServerName {domain2}', + ' ServerAlias localhost', + f' DocumentRoot "{self._docs_dir}"', + ' Protocols h2c http/1.1', + ]) + conf.extend(self._curltest_conf(domain2)) + conf.extend([ + '', + '', + ]) + conf.extend([ # https host for domain2, no h2 + f'', + f' ServerName {domain2}', + ' Protocols http/1.1', + ' SSLEngine on', + f' SSLCertificateFile {creds2.cert_file}', + f' SSLCertificateKeyFile {creds2.pkey_file}', + f' DocumentRoot "{self._docs_dir}/two"', + ]) + conf.extend(self._curltest_conf(domain2)) + if domain2 in self._extra_configs: + conf.extend(self._extra_configs[domain2]) + conf.extend([ + '', + '', + ]) + conf.extend([ # https host for expired domain + f'', + f' ServerName {exp_domain}', + ' Protocols h2 http/1.1', + ' SSLEngine on', + f' SSLCertificateFile {exp_creds.cert_file}', + f' SSLCertificateKeyFile {exp_creds.pkey_file}', + f' DocumentRoot "{self._docs_dir}/expired"', + ]) + conf.extend(self._curltest_conf(exp_domain)) + if exp_domain in self._extra_configs: + conf.extend(self._extra_configs[exp_domain]) + conf.extend([ + '', + '', + ]) + conf.extend([ # http forward proxy + f'', + f' ServerName {proxy_domain}', + ' Protocols h2c http/1.1', + ' ProxyRequests On', + ' H2ProxyRequests On', + ' ProxyVia On', + f' AllowCONNECT {self.env.http_port} {self.env.https_port}', + ]) + conf.extend(self._get_proxy_conf()) + conf.extend([ + '', + '', + ]) + conf.extend([ # https forward proxy + f'', + f' ServerName {proxy_domain}', + ' Protocols h2 http/1.1', + ' SSLEngine on', + f' SSLCertificateFile {proxy_creds.cert_file}', + f' SSLCertificateKeyFile {proxy_creds.pkey_file}', + ' ProxyRequests On', + ' H2ProxyRequests On', + ' ProxyVia On', + f' AllowCONNECT {self.env.http_port} {self.env.https_port}', + ]) + conf.extend(self._get_proxy_conf()) + conf.extend([ + '', + '', + ]) + + fd.write("\n".join(conf)) + with open(os.path.join(self._conf_dir, 'mime.types'), 'w') as fd: + fd.write("\n".join([ + 'text/html html', + 'application/json json', + '' + ])) + + def _get_proxy_conf(self): + if self._proxy_auth_basic: + return [ + ' ', + ' AuthType Basic', + ' AuthName "Restricted Proxy"', + ' AuthBasicProvider file', + f' AuthUserFile "{self._basic_passwords}"', + ' Require user proxy', + ' ', + ] + else: + return [ + ' ', + ' Require ip 127.0.0.1', + ' ', + ] + + def _get_log_level(self): + if self.env.verbose > 3: + return 'trace2' + if self.env.verbose > 2: + return 'trace1' + if self.env.verbose > 1: + return 'debug' + return 'info' + + def _curltest_conf(self, servername) -> List[str]: + lines = [] + if Httpd.MOD_CURLTEST is not None: + lines.extend([ + ' Redirect 302 /data.json.302 /data.json', + ' Redirect 301 /curltest/echo301 /curltest/echo', + ' Redirect 302 /curltest/echo302 /curltest/echo', + ' Redirect 303 /curltest/echo303 /curltest/echo', + ' Redirect 307 /curltest/echo307 /curltest/echo', + ' ', + ' SSLOptions StdEnvVars', + ' SetHandler curltest-sslinfo', + ' ', + ' ', + ' SetHandler curltest-echo', + ' ', + ' ', + ' SetHandler curltest-put', + ' ', + ' ', + ' SetHandler curltest-tweak', + ' ', + ' Redirect 302 /tweak /curltest/tweak', + ' ', + ' SetHandler curltest-1_1-required', + ' ', + ' ', + ' SetHandler curltest-tweak', + ' SetEnv force-response-1.0 1', + ' ', + ' SetEnvIf Request_URI "/shutdown_unclean" ssl-unclean=1', + ]) + if self._auth_digest: + lines.extend([ + f' ', + ' AuthType Digest', + ' AuthName "restricted area"', + f' AuthDigestDomain "https://{servername}"', + ' AuthBasicProvider file', + f' AuthUserFile "{self._digest_passwords}"', + ' Require valid-user', + ' ', + + ]) + return lines + + def _init_curltest(self): + if Httpd.MOD_CURLTEST is not None: + return + local_dir = os.path.dirname(inspect.getfile(Httpd)) + p = subprocess.run([self.env.apxs, '-c', 'mod_curltest.c'], + capture_output=True, + cwd=os.path.join(local_dir, 'mod_curltest')) + rv = p.returncode + if rv != 0: + log.error(f"compiling mod_curltest failed: {p.stderr}") + raise Exception(f"compiling mod_curltest failed: {p.stderr}") + Httpd.MOD_CURLTEST = os.path.join( + local_dir, 'mod_curltest/.libs/mod_curltest.so') diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/.gitignore b/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8774a09325ee48c82d99a2abd5126d477a4a131c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/.gitignore @@ -0,0 +1,5 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +*.slo diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/mod_curltest.c b/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/mod_curltest.c new file mode 100644 index 0000000000000000000000000000000000000000..2b57a082b7172603f0f285b80790fab7ee4616ec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/mod_curltest/mod_curltest.c @@ -0,0 +1,836 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 +#include +#include +#include +#include + +#include +#include +#include +#include + +static void curltest_hooks(apr_pool_t *pool); +static int curltest_echo_handler(request_rec *r); +static int curltest_put_handler(request_rec *r); +static int curltest_tweak_handler(request_rec *r); +static int curltest_1_1_required(request_rec *r); +static int curltest_sslinfo_handler(request_rec *r); + +AP_DECLARE_MODULE(curltest) = +{ + STANDARD20_MODULE_STUFF, + NULL, /* func to create per dir config */ + NULL, /* func to merge per dir config */ + NULL, /* func to create per server config */ + NULL, /* func to merge per server config */ + NULL, /* command handlers */ + curltest_hooks, +#if defined(AP_MODULE_FLAG_NONE) + AP_MODULE_FLAG_ALWAYS_MERGE +#endif +}; + +static int curltest_post_config(apr_pool_t *p, apr_pool_t *plog, + apr_pool_t *ptemp, server_rec *s) +{ + void *data = NULL; + const char *key = "mod_curltest_init_counter"; + + (void)plog;(void)ptemp; + + apr_pool_userdata_get(&data, key, s->process->pool); + if(!data) { + /* dry run */ + apr_pool_userdata_set((const void *)1, key, + apr_pool_cleanup_null, s->process->pool); + return APR_SUCCESS; + } + + /* mess with the overall server here */ + + return APR_SUCCESS; +} + +static void curltest_hooks(apr_pool_t *pool) +{ + ap_log_perror(APLOG_MARK, APLOG_TRACE1, 0, pool, "installing hooks"); + + /* Run once after configuration is set, but before mpm children initialize. + */ + ap_hook_post_config(curltest_post_config, NULL, NULL, APR_HOOK_MIDDLE); + + /* curl test handlers */ + ap_hook_handler(curltest_echo_handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(curltest_put_handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(curltest_tweak_handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(curltest_1_1_required, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(curltest_sslinfo_handler, NULL, NULL, APR_HOOK_MIDDLE); +} + +#define SECS_PER_HOUR (60*60) +#define SECS_PER_DAY (24*SECS_PER_HOUR) + +static apr_status_t duration_parse(apr_interval_time_t *ptimeout, + const char *value, const char *def_unit) +{ + char *endp; + apr_int64_t n; + + n = apr_strtoi64(value, &endp, 10); + if(errno) { + return errno; + } + if(!endp || !*endp) { + if(!def_unit) + def_unit = "s"; + } + else if(endp == value) { + return APR_EINVAL; + } + else { + def_unit = endp; + } + + switch(*def_unit) { + case 'D': + case 'd': + *ptimeout = apr_time_from_sec(n * SECS_PER_DAY); + break; + case 's': + case 'S': + *ptimeout = (apr_interval_time_t) apr_time_from_sec(n); + break; + case 'h': + case 'H': + /* Time is in hours */ + *ptimeout = (apr_interval_time_t) apr_time_from_sec(n * SECS_PER_HOUR); + break; + case 'm': + case 'M': + switch(*(++def_unit)) { + /* Time is in milliseconds */ + case 's': + case 'S': + *ptimeout = (apr_interval_time_t) n * 1000; + break; + /* Time is in minutes */ + case 'i': + case 'I': + *ptimeout = (apr_interval_time_t) apr_time_from_sec(n * 60); + break; + default: + return APR_EGENERAL; + } + break; + case 'u': + case 'U': + switch(*(++def_unit)) { + /* Time is in microseconds */ + case 's': + case 'S': + *ptimeout = (apr_interval_time_t) n; + break; + default: + return APR_EGENERAL; + } + break; + default: + return APR_EGENERAL; + } + return APR_SUCCESS; +} + +static int status_from_str(const char *s, apr_status_t *pstatus) +{ + if(!strcmp("timeout", s)) { + *pstatus = APR_TIMEUP; + return 1; + } + else if(!strcmp("reset", s)) { + *pstatus = APR_ECONNRESET; + return 1; + } + return 0; +} + +static int curltest_echo_handler(request_rec *r) +{ + conn_rec *c = r->connection; + apr_bucket_brigade *bb; + apr_bucket *b; + apr_status_t rv; + char buffer[8192]; + const char *ct; + apr_off_t die_after_len = -1, total_read_len = 0; + int just_die = 0, die_after_100 = 0; + long l; + + if(strcmp(r->handler, "curltest-echo")) { + return DECLINED; + } + if(r->method_number != M_GET && r->method_number != M_POST) { + return DECLINED; + } + + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "echo_handler: processing"); + if(r->args) { + apr_array_header_t *args = NULL; + int i; + args = apr_cstr_split(r->args, "&", 1, r->pool); + for(i = 0; i < args->nelts; ++i) { + char *s, *val, *arg = APR_ARRAY_IDX(args, i, char *); + s = strchr(arg, '='); + if(s) { + *s = '\0'; + val = s + 1; + if(!strcmp("die_after", arg)) { + die_after_len = (apr_off_t)apr_atoi64(val); + continue; + } + else if(!strcmp("just_die", arg)) { + just_die = 1; + continue; + } + else if(!strcmp("die_after_100", arg)) { + die_after_100 = 1; + continue; + } + } + } + } + + if(just_die) { + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, + "echo_handler: dying right away"); + /* Generate no HTTP response at all. */ + ap_remove_output_filter_byhandle(r->output_filters, "HTTP_HEADER"); + r->connection->keepalive = AP_CONN_CLOSE; + return AP_FILTER_ERROR; + } + + r->status = 200; + if(die_after_len >= 0) { + r->clength = die_after_len + 1; + r->chunked = 0; + apr_table_set(r->headers_out, "Content-Length", + apr_ltoa(r->pool, (long)r->clength)); + } + else { + r->clength = -1; + r->chunked = 1; + apr_table_unset(r->headers_out, "Content-Length"); + } + /* Discourage content-encodings */ + apr_table_unset(r->headers_out, "Content-Encoding"); + apr_table_setn(r->subprocess_env, "no-brotli", "1"); + apr_table_setn(r->subprocess_env, "no-gzip", "1"); + + ct = apr_table_get(r->headers_in, "content-type"); + ap_set_content_type(r, ct ? ct : "application/octet-stream"); + + bb = apr_brigade_create(r->pool, c->bucket_alloc); + /* copy any request body into the response */ + rv = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); + if(rv) + goto cleanup; + if(die_after_100) { + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, + "echo_handler: dying after 100-continue"); + /* Generate no HTTP response at all. */ + ap_remove_output_filter_byhandle(r->output_filters, "HTTP_HEADER"); + r->connection->keepalive = AP_CONN_CLOSE; + return AP_FILTER_ERROR; + } + if(ap_should_client_block(r)) { + while(0 < (l = ap_get_client_block(r, &buffer[0], sizeof(buffer)))) { + total_read_len += l; + if(die_after_len >= 0 && total_read_len >= die_after_len) { + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, + "echo_handler: dying after %ld bytes as requested", + (long)total_read_len); + ap_pass_brigade(r->output_filters, bb); + ap_remove_output_filter_byhandle(r->output_filters, "HTTP_HEADER"); + r->connection->keepalive = AP_CONN_CLOSE; + return DONE; + } + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, + "echo_handler: copying %ld bytes from request body", l); + rv = apr_brigade_write(bb, NULL, NULL, buffer, l); + if(APR_SUCCESS != rv) + goto cleanup; + rv = ap_pass_brigade(r->output_filters, bb); + if(APR_SUCCESS != rv) + goto cleanup; + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, + "echo_handler: passed %ld bytes from request body", l); + } + } + /* we are done */ + b = apr_bucket_eos_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "echo_handler: request read"); + + if(r->trailers_in && !apr_is_empty_table(r->trailers_in)) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, + "echo_handler: seeing incoming trailers"); + apr_table_setn(r->trailers_out, "h2test-trailers-in", + apr_itoa(r->pool, 1)); + } + + rv = ap_pass_brigade(r->output_filters, bb); + +cleanup: + if(rv == APR_SUCCESS || + r->status != HTTP_OK || + c->aborted) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "echo_handler: done"); + return OK; + } + else { + /* no way to know what type of error occurred */ + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "echo_handler failed"); + return AP_FILTER_ERROR; + } + return DECLINED; +} + +static int curltest_tweak_handler(request_rec *r) +{ + conn_rec *c = r->connection; + apr_bucket_brigade *bb; + apr_bucket *b; + apr_status_t rv; + char buffer[16*1024]; + int i, chunks = 3, error_bucket = 1; + size_t chunk_size = sizeof(buffer); + const char *request_id = "none"; + apr_time_t delay = 0, chunk_delay = 0, close_delay = 0; + apr_array_header_t *args = NULL; + int http_status = 200; + apr_status_t error = APR_SUCCESS, body_error = APR_SUCCESS; + int close_conn = 0, with_cl = 0; + + if(strcmp(r->handler, "curltest-tweak")) { + return DECLINED; + } + if(r->method_number == M_DELETE) { + http_status = 204; + chunks = 0; + } + else if(r->method_number != M_GET && r->method_number != M_POST) { + return DECLINED; + } + + if(r->args) { + args = apr_cstr_split(r->args, "&", 1, r->pool); + for(i = 0; i < args->nelts; ++i) { + char *s, *val, *arg = APR_ARRAY_IDX(args, i, char *); + s = strchr(arg, '='); + if(s) { + *s = '\0'; + val = s + 1; + if(!strcmp("status", arg)) { + http_status = (int)apr_atoi64(val); + if(http_status > 0) { + continue; + } + } + else if(!strcmp("chunks", arg)) { + chunks = (int)apr_atoi64(val); + if(chunks >= 0) { + continue; + } + } + else if(!strcmp("chunk_size", arg)) { + chunk_size = (int)apr_atoi64(val); + if(chunk_size >= 0) { + if(chunk_size > sizeof(buffer)) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, + "chunk_size %zu too large", chunk_size); + ap_die(HTTP_BAD_REQUEST, r); + return OK; + } + continue; + } + } + else if(!strcmp("id", arg)) { + /* just an id for repeated requests with curl's url globbing */ + request_id = val; + continue; + } + else if(!strcmp("error", arg)) { + if(status_from_str(val, &error)) { + continue; + } + } + else if(!strcmp("error_bucket", arg)) { + error_bucket = (int)apr_atoi64(val); + if(error_bucket >= 0) { + continue; + } + } + else if(!strcmp("body_error", arg)) { + if(status_from_str(val, &body_error)) { + continue; + } + } + else if(!strcmp("delay", arg)) { + rv = duration_parse(&delay, val, "s"); + if(APR_SUCCESS == rv) { + continue; + } + } + else if(!strcmp("chunk_delay", arg)) { + rv = duration_parse(&chunk_delay, val, "s"); + if(APR_SUCCESS == rv) { + continue; + } + } + else if(!strcmp("close_delay", arg)) { + rv = duration_parse(&close_delay, val, "s"); + if(APR_SUCCESS == rv) { + continue; + } + } + } + else if(!strcmp("close", arg)) { + /* we are asked to close the connection */ + close_conn = 1; + continue; + } + else if(!strcmp("with_cl", arg)) { + with_cl = 1; + continue; + } + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "query parameter not " + "understood: '%s' in %s", + arg, r->args); + ap_die(HTTP_BAD_REQUEST, r); + return OK; + } + } + + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "error_handler: processing " + "request, %s", r->args? r->args : "(no args)"); + r->status = http_status; + r->clength = with_cl ? (chunks * chunk_size) : -1; + r->chunked = (r->proto_num >= HTTP_VERSION(1, 1)) && !with_cl; + apr_table_setn(r->headers_out, "request-id", request_id); + if(r->clength >= 0) { + apr_table_set(r->headers_out, "Content-Length", + apr_ltoa(r->pool, (long)r->clength)); + } + else + apr_table_unset(r->headers_out, "Content-Length"); + /* Discourage content-encodings */ + apr_table_unset(r->headers_out, "Content-Encoding"); + apr_table_setn(r->subprocess_env, "no-brotli", "1"); + apr_table_setn(r->subprocess_env, "no-gzip", "1"); + + ap_set_content_type(r, "application/octet-stream"); + bb = apr_brigade_create(r->pool, c->bucket_alloc); + + if(delay) { + apr_sleep(delay); + } + if(error != APR_SUCCESS) { + return ap_map_http_request_error(error, HTTP_BAD_REQUEST); + } + /* flush response */ + b = apr_bucket_flush_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + rv = ap_pass_brigade(r->output_filters, bb); + if(APR_SUCCESS != rv) + goto cleanup; + + memset(buffer, 'X', sizeof(buffer)); + for(i = 0; i < chunks; ++i) { + if(chunk_delay) { + apr_sleep(chunk_delay); + } + rv = apr_brigade_write(bb, NULL, NULL, buffer, chunk_size); + if(APR_SUCCESS != rv) + goto cleanup; + rv = ap_pass_brigade(r->output_filters, bb); + if(APR_SUCCESS != rv) + goto cleanup; + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, + "error_handler: passed %lu bytes as response body", + (unsigned long)chunk_size); + if(body_error != APR_SUCCESS) { + rv = body_error; + goto cleanup; + } + } + /* we are done */ + b = apr_bucket_eos_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + rv = ap_pass_brigade(r->output_filters, bb); + apr_brigade_cleanup(bb); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, + "error_handler: response passed"); + +cleanup: + if(close_conn) { + if(close_delay) { + b = apr_bucket_flush_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + rv = ap_pass_brigade(r->output_filters, bb); + apr_brigade_cleanup(bb); + apr_sleep(close_delay); + } + r->connection->keepalive = AP_CONN_CLOSE; + } + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, + "error_handler: request cleanup, r->status=%d, aborted=%d, " + "close=%d", r->status, c->aborted, close_conn); + if(rv == APR_SUCCESS) { + return OK; + } + if(error_bucket) { + http_status = ap_map_http_request_error(rv, HTTP_BAD_REQUEST); + b = ap_bucket_error_create(http_status, NULL, r->pool, c->bucket_alloc); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, + "error_handler: passing error bucket, status=%d", + http_status); + APR_BRIGADE_INSERT_TAIL(bb, b); + ap_pass_brigade(r->output_filters, bb); + } + return AP_FILTER_ERROR; +} + +static int curltest_put_handler(request_rec *r) +{ + conn_rec *c = r->connection; + apr_bucket_brigade *bb; + apr_bucket *b; + apr_status_t rv; + char buffer[128*1024]; + const char *ct; + apr_off_t rbody_len = 0; + apr_off_t rbody_max_len = -1; + const char *s_rbody_len; + const char *request_id = "none"; + apr_time_t read_delay = 0, chunk_delay = 0; + apr_array_header_t *args = NULL; + long l; + int i; + + if(strcmp(r->handler, "curltest-put")) { + return DECLINED; + } + if(r->method_number != M_PUT) { + return DECLINED; + } + + if(r->args) { + args = apr_cstr_split(r->args, "&", 1, r->pool); + for(i = 0; i < args->nelts; ++i) { + char *s, *val, *arg = APR_ARRAY_IDX(args, i, char *); + s = strchr(arg, '='); + if(s) { + *s = '\0'; + val = s + 1; + if(!strcmp("id", arg)) { + /* just an id for repeated requests with curl's url globbing */ + request_id = val; + continue; + } + else if(!strcmp("read_delay", arg)) { + rv = duration_parse(&read_delay, val, "s"); + if(APR_SUCCESS == rv) { + continue; + } + } + else if(!strcmp("chunk_delay", arg)) { + rv = duration_parse(&chunk_delay, val, "s"); + if(APR_SUCCESS == rv) { + continue; + } + } + else if(!strcmp("max_upload", arg)) { + rbody_max_len = (int)apr_atoi64(val); + continue; + } + } + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "query parameter not " + "understood: '%s' in %s", + arg, r->args); + ap_die(HTTP_BAD_REQUEST, r); + return OK; + } + } + + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "put_handler: processing"); + r->status = 200; + r->clength = -1; + r->chunked = 1; + apr_table_unset(r->headers_out, "Content-Length"); + /* Discourage content-encodings */ + apr_table_unset(r->headers_out, "Content-Encoding"); + apr_table_setn(r->subprocess_env, "no-brotli", "1"); + apr_table_setn(r->subprocess_env, "no-gzip", "1"); + + ct = apr_table_get(r->headers_in, "content-type"); + ap_set_content_type(r, ct ? ct : "text/plain"); + + if(read_delay) { + apr_sleep(read_delay); + } + bb = apr_brigade_create(r->pool, c->bucket_alloc); + /* copy any request body into the response */ + rv = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); + if(rv) + goto cleanup; + if(ap_should_client_block(r)) { + while(0 < (l = ap_get_client_block(r, &buffer[0], sizeof(buffer)))) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, + "put_handler: read %ld bytes from request body", l); + if(chunk_delay) { + apr_sleep(chunk_delay); + } + rbody_len += l; + if((rbody_max_len > 0) && (rbody_len > rbody_max_len)) { + r->status = 413; + break; + } + } + } + /* we are done */ + s_rbody_len = apr_psprintf(r->pool, "%"APR_OFF_T_FMT, rbody_len); + apr_table_setn(r->headers_out, "Received-Length", s_rbody_len); + rv = apr_brigade_puts(bb, NULL, NULL, s_rbody_len); + if(APR_SUCCESS != rv) + goto cleanup; + b = apr_bucket_eos_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "put_handler: request read"); + + rv = ap_pass_brigade(r->output_filters, bb); + + if(r->status == 413) { + apr_sleep(apr_time_from_sec(1)); + } + +cleanup: + if(rv == APR_SUCCESS + || r->status != HTTP_OK + || c->aborted) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "put_handler: done"); + return OK; + } + else { + /* no way to know what type of error occurred */ + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "put_handler failed"); + return AP_FILTER_ERROR; + } + return DECLINED; +} + +static int curltest_1_1_required(request_rec *r) +{ + conn_rec *c = r->connection; + apr_bucket_brigade *bb; + apr_bucket *b; + apr_status_t rv; + char buffer[16*1024]; + const char *ct; + const char *request_id = "none"; + apr_time_t chunk_delay = 0; + apr_array_header_t *args = NULL; + long l; + int i; + + if(strcmp(r->handler, "curltest-1_1-required")) { + return DECLINED; + } + + if(HTTP_VERSION_MAJOR(r->proto_num) > 1) { + apr_table_setn(r->notes, "ssl-renegotiate-forbidden", "1"); + ap_die(HTTP_FORBIDDEN, r); + return OK; + } + + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "1_1_handler: processing"); + r->status = 200; + r->clength = -1; + r->chunked = 1; + apr_table_unset(r->headers_out, "Content-Length"); + /* Discourage content-encodings */ + apr_table_unset(r->headers_out, "Content-Encoding"); + apr_table_setn(r->subprocess_env, "no-brotli", "1"); + apr_table_setn(r->subprocess_env, "no-gzip", "1"); + + ct = apr_table_get(r->headers_in, "content-type"); + ap_set_content_type(r, ct ? ct : "text/plain"); + + bb = apr_brigade_create(r->pool, c->bucket_alloc); + /* flush response */ + b = apr_bucket_flush_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + rv = ap_pass_brigade(r->output_filters, bb); + if(APR_SUCCESS != rv) + goto cleanup; + + /* we are done */ + rv = apr_brigade_printf(bb, NULL, NULL, "well done!"); + if(APR_SUCCESS != rv) + goto cleanup; + b = apr_bucket_eos_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "1_1_handler: request read"); + + rv = ap_pass_brigade(r->output_filters, bb); + +cleanup: + if(rv == APR_SUCCESS + || r->status != HTTP_OK + || c->aborted) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "1_1_handler: done"); + return OK; + } + else { + /* no way to know what type of error occurred */ + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "1_1_handler failed"); + return AP_FILTER_ERROR; + } + return DECLINED; +} + +static int brigade_env_var(request_rec *r, apr_bucket_brigade *bb, + const char *name) +{ + const char *s; + s = apr_table_get(r->subprocess_env, name); + if(s) + return apr_brigade_printf(bb, NULL, NULL, ",\n \"%s\": \"%s\"", name, s); + return 0; +} + +static int curltest_sslinfo_handler(request_rec *r) +{ + conn_rec *c = r->connection; + apr_bucket_brigade *bb; + apr_bucket *b; + apr_status_t rv; + apr_array_header_t *args = NULL; + const char *request_id = NULL; + int close_conn = 0; + long l; + int i; + + if(strcmp(r->handler, "curltest-sslinfo")) { + return DECLINED; + } + if(r->method_number != M_GET) { + return DECLINED; + } + + if(r->args) { + apr_array_header_t *args = apr_cstr_split(r->args, "&", 1, r->pool); + for(i = 0; i < args->nelts; ++i) { + char *s, *val, *arg = APR_ARRAY_IDX(args, i, char *); + s = strchr(arg, '='); + if(s) { + *s = '\0'; + val = s + 1; + if(!strcmp("id", arg)) { + /* just an id for repeated requests with curl's url globbing */ + request_id = val; + continue; + } + } + else if(!strcmp("close", arg)) { + /* we are asked to close the connection */ + close_conn = 1; + continue; + } + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "query parameter not " + "understood: '%s' in %s", + arg, r->args); + ap_die(HTTP_BAD_REQUEST, r); + return OK; + } + } + + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "sslinfo: processing"); + r->status = 200; + r->clength = -1; + r->chunked = 1; + apr_table_unset(r->headers_out, "Content-Length"); + /* Discourage content-encodings */ + apr_table_unset(r->headers_out, "Content-Encoding"); + apr_table_setn(r->subprocess_env, "no-brotli", "1"); + apr_table_setn(r->subprocess_env, "no-gzip", "1"); + + ap_set_content_type(r, "application/json"); + + bb = apr_brigade_create(r->pool, c->bucket_alloc); + + apr_brigade_puts(bb, NULL, NULL, "{\n \"Name\": \"SSL-Information\""); + brigade_env_var(r, bb, "HTTPS"); + brigade_env_var(r, bb, "SSL_PROTOCOL"); + brigade_env_var(r, bb, "SSL_CIPHER"); + brigade_env_var(r, bb, "SSL_SESSION_ID"); + brigade_env_var(r, bb, "SSL_SESSION_RESUMED"); + brigade_env_var(r, bb, "SSL_SRP_USER"); + brigade_env_var(r, bb, "SSL_SRP_USERINFO"); + brigade_env_var(r, bb, "SSL_TLS_SNI"); + apr_brigade_puts(bb, NULL, NULL, "}\n"); + + /* flush response */ + b = apr_bucket_flush_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + rv = ap_pass_brigade(r->output_filters, bb); + if(APR_SUCCESS != rv) + goto cleanup; + + /* we are done */ + b = apr_bucket_eos_create(c->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(bb, b); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "1_1_handler: request read"); + + rv = ap_pass_brigade(r->output_filters, bb); + +cleanup: + if(close_conn) + r->connection->keepalive = AP_CONN_CLOSE; + if(rv == APR_SUCCESS + || r->status != HTTP_OK + || c->aborted) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "1_1_handler: done"); + return OK; + } + else { + /* no way to know what type of error occurred */ + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r, "1_1_handler failed"); + return AP_FILTER_ERROR; + } + return DECLINED; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/nghttpx.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/nghttpx.py new file mode 100644 index 0000000000000000000000000000000000000000..801d9a63ad0bb160d3c3028ee7d0e0606cf88dd4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/nghttpx.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import signal +import subprocess +import time +from typing import Optional +from datetime import datetime, timedelta + +from .env import Env +from .curl import CurlClient + + +log = logging.getLogger(__name__) + + +class Nghttpx: + + def __init__(self, env: Env, port: int, https_port: int, name: str): + self.env = env + self._name = name + self._port = port + self._https_port = https_port + self._cmd = env.nghttpx + self._run_dir = os.path.join(env.gen_dir, name) + self._pid_file = os.path.join(self._run_dir, 'nghttpx.pid') + self._conf_file = os.path.join(self._run_dir, 'nghttpx.conf') + self._error_log = os.path.join(self._run_dir, 'nghttpx.log') + self._stderr = os.path.join(self._run_dir, 'nghttpx.stderr') + self._tmp_dir = os.path.join(self._run_dir, 'tmp') + self._process: Optional[subprocess.Popen] = None + self._rmf(self._pid_file) + self._rmf(self._error_log) + self._mkpath(self._run_dir) + self._write_config() + + @property + def https_port(self): + return self._https_port + + def exists(self): + return self._cmd and os.path.exists(self._cmd) + + def clear_logs(self): + self._rmf(self._error_log) + self._rmf(self._stderr) + + def is_running(self): + if self._process: + self._process.poll() + return self._process.returncode is None + return False + + def start_if_needed(self): + if not self.is_running(): + return self.start() + return True + + def start(self, wait_live=True): + pass + + def stop_if_running(self): + if self.is_running(): + return self.stop() + return True + + def stop(self, wait_dead=True): + self._mkpath(self._tmp_dir) + if self._process: + self._process.terminate() + self._process.wait(timeout=2) + self._process = None + return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5)) + return True + + def restart(self): + self.stop() + return self.start() + + def reload(self, timeout: timedelta): + if self._process: + running = self._process + self._process = None + os.kill(running.pid, signal.SIGQUIT) + end_wait = datetime.now() + timeout + if not self.start(wait_live=False): + self._process = running + return False + while datetime.now() < end_wait: + try: + log.debug(f'waiting for nghttpx({running.pid}) to exit.') + running.wait(2) + log.debug(f'nghttpx({running.pid}) terminated -> {running.returncode}') + break + except subprocess.TimeoutExpired: + log.warning(f'nghttpx({running.pid}), not shut down yet.') + os.kill(running.pid, signal.SIGQUIT) + if datetime.now() >= end_wait: + log.error(f'nghttpx({running.pid}), terminate forcefully.') + os.kill(running.pid, signal.SIGKILL) + running.terminate() + running.wait(1) + return self.wait_live(timeout=timedelta(seconds=5)) + return False + + def wait_dead(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + if self._https_port > 0: + check_url = f'https://{self.env.domain1}:{self._https_port}/' + r = curl.http_get(url=check_url, extra_args=[ + '--trace', 'curl.trace', '--trace-time', + '--connect-timeout', '1' + ]) + else: + check_url = f'https://{self.env.domain1}:{self._port}/' + r = curl.http_get(url=check_url, extra_args=[ + '--trace', 'curl.trace', '--trace-time', + '--http3-only', '--connect-timeout', '1' + ]) + if r.exit_code != 0: + return True + log.debug(f'waiting for nghttpx to stop responding: {r}') + time.sleep(.1) + log.debug(f"Server still responding after {timeout}") + return False + + def wait_live(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + if self._https_port > 0: + check_url = f'https://{self.env.domain1}:{self._https_port}/' + r = curl.http_get(url=check_url, extra_args=[ + '--trace', 'curl.trace', '--trace-time', + '--connect-timeout', '1' + ]) + else: + check_url = f'https://{self.env.domain1}:{self._port}/' + r = curl.http_get(url=check_url, extra_args=[ + '--http3-only', '--trace', 'curl.trace', '--trace-time', + '--connect-timeout', '1' + ]) + if r.exit_code == 0: + return True + log.debug(f'waiting for nghttpx to become responsive: {r}') + time.sleep(.1) + log.error(f"Server still not responding after {timeout}") + return False + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def _write_config(self): + with open(self._conf_file, 'w') as fd: + fd.write('# nghttpx test config') + fd.write("\n".join([ + '# do we need something here?' + ])) + + +class NghttpxQuic(Nghttpx): + + def __init__(self, env: Env): + super().__init__(env=env, name='nghttpx-quic', port=env.h3_port, + https_port=env.nghttpx_https_port) + + def start(self, wait_live=True): + self._mkpath(self._tmp_dir) + if self._process: + self.stop() + creds = self.env.get_credentials(self.env.domain1) + assert creds # convince pytype this isn't None + args = [ + self._cmd, + f'--frontend=*,{self.env.h3_port};quic', + f'--frontend=*,{self.env.nghttpx_https_port};tls', + f'--backend=127.0.0.1,{self.env.https_port};{self.env.domain1};sni={self.env.domain1};proto=h2;tls', + f'--backend=127.0.0.1,{self.env.http_port}', + '--log-level=INFO', + f'--pid-file={self._pid_file}', + f'--errorlog-file={self._error_log}', + f'--conf={self._conf_file}', + f'--cacert={self.env.ca.cert_file}', + creds.pkey_file, + creds.cert_file, + '--frontend-http3-window-size=1M', + '--frontend-http3-max-window-size=10M', + '--frontend-http3-connection-window-size=10M', + '--frontend-http3-max-connection-window-size=100M', + # f'--frontend-quic-debug-log', + ] + ngerr = open(self._stderr, 'a') + self._process = subprocess.Popen(args=args, stderr=ngerr) + if self._process.returncode is not None: + return False + return not wait_live or self.wait_live(timeout=timedelta(seconds=5)) + + +class NghttpxFwd(Nghttpx): + + def __init__(self, env: Env): + super().__init__(env=env, name='nghttpx-fwd', port=env.h2proxys_port, + https_port=0) + + def start(self, wait_live=True): + self._mkpath(self._tmp_dir) + if self._process: + self.stop() + creds = self.env.get_credentials(self.env.proxy_domain) + assert creds # convince pytype this isn't None + args = [ + self._cmd, + '--http2-proxy', + f'--frontend=*,{self.env.h2proxys_port}', + f'--backend=127.0.0.1,{self.env.proxy_port}', + '--log-level=INFO', + f'--pid-file={self._pid_file}', + f'--errorlog-file={self._error_log}', + f'--conf={self._conf_file}', + f'--cacert={self.env.ca.cert_file}', + creds.pkey_file, + creds.cert_file, + ] + ngerr = open(self._stderr, 'a') + self._process = subprocess.Popen(args=args, stderr=ngerr) + if self._process.returncode is not None: + return False + return not wait_live or self.wait_live(timeout=timedelta(seconds=5)) + + def wait_dead(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/' + r = curl.http_get(url=check_url) + if r.exit_code != 0: + return True + log.debug(f'waiting for nghttpx-fwd to stop responding: {r}') + time.sleep(.1) + log.debug(f"Server still responding after {timeout}") + return False + + def wait_live(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/' + r = curl.http_get(url=check_url, extra_args=[ + '--trace', 'curl.trace', '--trace-time' + ]) + if r.exit_code == 0: + return True + log.debug(f'waiting for nghttpx-fwd to become responsive: {r}') + time.sleep(.1) + log.error(f"Server still not responding after {timeout}") + return False diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/ports.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/ports.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f9a3c21843922885d0faef9ff456226ff80ded --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/ports.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import socket +from typing import Dict + +log = logging.getLogger(__name__) + + +def alloc_ports(port_specs: Dict[str, int]) -> Dict[str, int]: + ports = {} + socks = [] + for name, ptype in port_specs.items(): + try: + s = socket.socket(type=ptype) + s.bind(('', 0)) + ports[name] = s.getsockname()[1] + socks.append(s) + except Exception as e: + raise e + for s in socks: + s.close() + return ports diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/vsftpd.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/vsftpd.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4f0c0640c6bcc1debdc709af4b6ec7306968c0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/vsftpd.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import logging +import os +import subprocess +import time + +from datetime import datetime, timedelta + +from .curl import CurlClient +from .env import Env + + +log = logging.getLogger(__name__) + + +class VsFTPD: + + def __init__(self, env: Env, with_ssl=False): + self.env = env + self._cmd = env.vsftpd + self._scheme = 'ftp' + self._with_ssl = with_ssl + if self._with_ssl: + self._port = self.env.ftps_port + name = 'vsftpds' + else: + self._port = self.env.ftp_port + name = 'vsftpd' + self._vsftpd_dir = os.path.join(env.gen_dir, name) + self._run_dir = os.path.join(self._vsftpd_dir, 'run') + self._docs_dir = os.path.join(self._vsftpd_dir, 'docs') + self._tmp_dir = os.path.join(self._vsftpd_dir, 'tmp') + self._conf_file = os.path.join(self._vsftpd_dir, 'test.conf') + self._pid_file = os.path.join(self._vsftpd_dir, 'vsftpd.pid') + self._error_log = os.path.join(self._vsftpd_dir, 'vsftpd.log') + self._process = None + + self.clear_logs() + + @property + def domain(self): + return self.env.ftp_domain + + @property + def docs_dir(self): + return self._docs_dir + + @property + def port(self) -> int: + return self._port + + def clear_logs(self): + self._rmf(self._error_log) + + def exists(self): + return os.path.exists(self._cmd) + + def is_running(self): + if self._process: + self._process.poll() + return self._process.returncode is None + return False + + def start_if_needed(self): + if not self.is_running(): + return self.start() + return True + + def stop_if_running(self): + if self.is_running(): + return self.stop() + return True + + def stop(self, wait_dead=True): + self._mkpath(self._tmp_dir) + if self._process: + self._process.terminate() + self._process.wait(timeout=2) + self._process = None + return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5)) + return True + + def restart(self): + self.stop() + return self.start() + + def start(self, wait_live=True): + self._mkpath(self._tmp_dir) + if self._process: + self.stop() + self._write_config() + args = [ + self._cmd, + f'{self._conf_file}', + ] + procerr = open(self._error_log, 'a') + self._process = subprocess.Popen(args=args, stderr=procerr) + if self._process.returncode is not None: + return False + return not wait_live or self.wait_live(timeout=timedelta(seconds=5)) + + def wait_dead(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'{self._scheme}://{self.domain}:{self.port}/' + r = curl.ftp_get(urls=[check_url], extra_args=['-v']) + if r.exit_code != 0: + return True + log.debug(f'waiting for vsftpd to stop responding: {r}') + time.sleep(.1) + log.debug(f"Server still responding after {timeout}") + return False + + def wait_live(self, timeout: timedelta): + curl = CurlClient(env=self.env, run_dir=self._tmp_dir) + try_until = datetime.now() + timeout + while datetime.now() < try_until: + check_url = f'{self._scheme}://{self.domain}:{self.port}/' + r = curl.ftp_get(urls=[check_url], extra_args=[ + '--trace', 'curl-start.trace', '--trace-time' + ]) + if r.exit_code == 0: + return True + log.debug(f'waiting for vsftpd to become responsive: {r}') + time.sleep(.1) + log.error(f"Server still not responding after {timeout}") + return False + + def _rmf(self, path): + if os.path.exists(path): + return os.remove(path) + + def _mkpath(self, path): + if not os.path.exists(path): + return os.makedirs(path) + + def _write_config(self): + self._mkpath(self._docs_dir) + self._mkpath(self._tmp_dir) + conf = [ # base server config + 'listen=YES', + 'run_as_launching_user=YES', + '#listen_address=127.0.0.1', + f'listen_port={self.port}', + 'local_enable=NO', + 'anonymous_enable=YES', + f'anon_root={self._docs_dir}', + 'dirmessage_enable=YES', + 'write_enable=YES', + 'anon_upload_enable=YES', + 'log_ftp_protocol=YES', + 'xferlog_enable=YES', + 'xferlog_std_format=NO', + f'vsftpd_log_file={self._error_log}', + '\n', + ] + if self._with_ssl: + creds = self.env.get_credentials(self.domain) + assert creds # convince pytype this isn't None + conf.extend([ + 'ssl_enable=YES', + 'debug_ssl=YES', + 'allow_anon_ssl=YES', + f'rsa_cert_file={creds.cert_file}', + f'rsa_private_key_file={creds.pkey_file}', + # require_ssl_reuse=YES means ctrl and data connection need to use the same session + 'require_ssl_reuse=NO', + ]) + + with open(self._conf_file, 'w') as fd: + fd.write("\n".join(conf)) diff --git a/local-test-curl-delta-01/afc-curl/tests/http/testenv/ws_echo_server.py b/local-test-curl-delta-01/afc-curl/tests/http/testenv/ws_echo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99eaa628d2391746b1e1db33753081a58e89acd2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/http/testenv/ws_echo_server.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# +import argparse +import asyncio +import logging + +from websockets import server +from websockets.exceptions import ConnectionClosedError + + +async def echo(websocket): + try: + async for message in websocket: + await websocket.send(message) + except ConnectionClosedError: + pass + + +async def run_server(port): + async with server.serve(echo, "localhost", port): + await asyncio.Future() # run forever + + +def main(): + parser = argparse.ArgumentParser(prog='scorecard', description=""" + Run a websocket echo server. + """) + parser.add_argument("--port", type=int, + default=9876, help="port to listen on") + args = parser.parse_args() + + logging.basicConfig( + format="%(asctime)s %(message)s", + level=logging.DEBUG, + ) + + asyncio.run(run_server(args.port)) + + +if __name__ == "__main__": + main() diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/.checksrc b/local-test-curl-delta-01/afc-curl/tests/libtest/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..37f7909524a1e8337245a7fc3398cdab8c070966 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/.checksrc @@ -0,0 +1,2 @@ +disable TYPEDEFSTRUCT +disable BANNEDFUNC diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/.gitignore b/local-test-curl-delta-01/afc-curl/tests/libtest/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9fd1a098c7bcea72bc92eaca844af9316a825954 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/.gitignore @@ -0,0 +1,11 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +lib[1234][0-9][0-9][0-9] +lib[56][0-9][0-9] +lib1521.c +libtests.c +libauthretry +libntlmconnect +libprereq diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/libtest/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d60f7a33188e8a2dcdd1b3fb319417a0726e5fa1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/CMakeLists.txt @@ -0,0 +1,86 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# Get 'LIBTESTPROGS', '*_SOURCES', 'TESTUTIL', 'TSTTRACE', 'WARNLESS', 'MULTIBYTE', 'TIMEDIFF', 'THREADS', 'FIRSTFILES' variables +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + +set_source_files_properties("../../lib/curl_multibyte.c" PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) + +add_custom_command( + OUTPUT "lib1521.c" + COMMAND ${PERL_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/mk-lib1521.pl" < "${PROJECT_SOURCE_DIR}/include/curl/curl.h" "lib1521.c" + DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/mk-lib1521.pl" + "${PROJECT_SOURCE_DIR}/include/curl/curl.h" + VERBATIM) + +if(CURL_TEST_BUNDLES) + add_custom_command( + OUTPUT "libtest_bundle.c" + COMMAND ${PERL_EXECUTABLE} "${PROJECT_SOURCE_DIR}/tests/mk-bundle.pl" "${CMAKE_CURRENT_SOURCE_DIR}" > "libtest_bundle.c" + DEPENDS + "${PROJECT_SOURCE_DIR}/tests/mk-bundle.pl" ${FIRSTFILES} "lib1521.c" + "${CMAKE_CURRENT_SOURCE_DIR}/Makefile.inc" + VERBATIM) + + set(LIBTESTPROGS "libtests") + set(libtests_SOURCES "libtest_bundle.c") + list(APPEND libtests_SOURCES ${TESTUTIL} ${TSTTRACE}) + if(LIB_SELECTED STREQUAL LIB_SHARED) + # These are part of the libcurl static lib. Add them here when linking shared. + list(APPEND libtests_SOURCES ${WARNLESS} ${MULTIBYTE} ${TIMEDIFF} ${THREADS}) + endif() +endif() + +foreach(_target IN LISTS LIBTESTPROGS) + if(DEFINED ${_target}_SOURCES) + set(_sources ${${_target}_SOURCES}) + else() + set(_sources ${nodist_${_target}_SOURCES}) + endif() + + if(LIB_SELECTED STREQUAL LIB_STATIC) + # These are part of the libcurl static lib. Do not compile/link them again. + list(REMOVE_ITEM _sources ${WARNLESS} ${MULTIBYTE} ${TIMEDIFF} ${THREADS}) + endif() + + string(TOUPPER ${_target} _upper_target) + set(_target_name "${_target}") + add_executable(${_target_name} EXCLUDE_FROM_ALL ${_sources}) + add_dependencies(testdeps ${_target_name}) + target_link_libraries(${_target_name} ${LIB_SELECTED} ${CURL_LIBS}) + target_include_directories(${_target_name} PRIVATE + "${PROJECT_BINARY_DIR}/lib" # for "curl_config.h" + "${PROJECT_SOURCE_DIR}/lib" # for "curl_setup.h" + "${PROJECT_SOURCE_DIR}/tests/libtest" # to be able to build generated tests + ) + if(NOT CURL_TEST_BUNDLES) + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS ${_upper_target}) + endif() + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_NO_GETADDRINFO_OVERRIDE") + set_target_properties(${_target_name} PROPERTIES + OUTPUT_NAME "${_target}" + PROJECT_LABEL "Test libtest ${_target}") +endforeach() diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..809731d074a8923e5c266c006f86a9665177091a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.am @@ -0,0 +1,126 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 + +# 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 "borrowed" files + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib \ + -I$(top_srcdir)/tests/libtest + +EXTRA_DIST = test307.pl test610.pl test613.pl test1013.pl test1022.pl \ + CMakeLists.txt mk-lib1521.pl .checksrc + +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ + +CFLAGS += @CURL_CFLAG_EXTRAS@ + +CLEANFILES = lib1521.c + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +SUPPORTFILES_LIBS = $(top_builddir)/lib/libcurl.la @LIBCURL_PC_LIBS_PRIVATE@ +TESTUTIL_LIBS = $(top_builddir)/lib/libcurl.la @LIBCURL_PC_LIBS_PRIVATE@ + +# Dependencies (may need to be overridden) +LDADD = $(SUPPORTFILES_LIBS) + +# Makefile.inc provides the source defines (TESTUTIL, SUPPORTFILES, +# LIBTESTPROGS, lib*_SOURCES, and lib*_CFLAGS) +include Makefile.inc + +noinst_LTLIBRARIES = + +if USE_CPPFLAG_CURL_STATICLIB +AM_CPPFLAGS += -DCURL_STATICLIB +endif + +AM_LDFLAGS = +AM_CFLAGS = + +libstubgss_la_LDFLAGS_EXTRA = + +if CURL_LT_SHLIB_USE_NO_UNDEFINED +libstubgss_la_LDFLAGS_EXTRA += -no-undefined +endif + +# Build a stub gssapi implementation for testing +if BUILD_STUB_GSS +noinst_LTLIBRARIES += libstubgss.la + +libstubgss_la_CPPFLAGS = $(AM_CPPFLAGS) +libstubgss_la_LDFLAGS = $(AM_LDFLAGS) $(libstubgss_la_LDFLAGS_EXTRA) -avoid-version -rpath /nowhere +libstubgss_la_CFLAGS = $(AM_CFLAGS) -g + +libstubgss_la_SOURCES = stub_gssapi.c stub_gssapi.h + +libstubgss_la_LIBADD = +libstubgss_la_DEPENDENCIES = +endif + +if USE_TEST_BUNDLES +AM_CPPFLAGS += -DCURL_NO_GETADDRINFO_OVERRIDE + +libtest_bundle.c: $(top_srcdir)/tests/mk-bundle.pl lib1521.c + @PERL@ $(top_srcdir)/tests/mk-bundle.pl $(srcdir) > libtest_bundle.c + +noinst_PROGRAMS = libtests +nodist_libtests_SOURCES = libtest_bundle.c +libtests_SOURCES = $(TESTUTIL) $(TSTTRACE) +libtests_LDADD = $(TESTUTIL_LIBS) +CLEANFILES += libtest_bundle.c + +if USE_CPPFLAG_CURL_STATICLIB +else +# These are part of the libcurl static lib. Add them here when linking shared. +libtests_SOURCES += $(WARNLESS) $(MULTIBYTE) $(TIMEDIFF) $(THREADS) +endif +else +noinst_PROGRAMS = $(LIBTESTPROGS) +endif + +lib1521.c: $(top_srcdir)/tests/libtest/mk-lib1521.pl $(top_srcdir)/include/curl/curl.h + @PERL@ $(top_srcdir)/tests/libtest/mk-lib1521.pl < $(top_srcdir)/include/curl/curl.h lib1521.c + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) $(srcdir)/*.[ch] + +if DEBUGBUILD +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.inc b/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..8f58fd64229d5cbcebdb4949111b3c3184d82eb3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/Makefile.inc @@ -0,0 +1,726 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# files used only in some libcurl test programs +TESTUTIL = testutil.c testutil.h + +# files used only in some libcurl test programs +TSTTRACE = testtrace.c testtrace.h + +# files used only in some libcurl test programs +WARNLESS = ../../lib/warnless.c ../../lib/warnless.h + +# files used only in some libcurl test programs +MULTIBYTE = ../../lib/curl_multibyte.c ../../lib/curl_multibyte.h + +# these files are used in every single test program below +TIMEDIFF = ../../lib/timediff.c ../../lib/timediff.h +FIRSTFILES = first.c first.h +SUPPORTFILES = $(TIMEDIFF) $(FIRSTFILES) test.h + +THREADS = ../../lib/curl_threads.c ../../lib/curl_threads.h + +# These are all libcurl test programs +LIBTESTPROGS = libauthretry libntlmconnect libprereq \ + lib500 lib501 lib502 lib503 lib504 lib505 lib506 lib507 lib508 lib509 \ + lib510 lib511 lib512 lib513 lib514 lib515 lib516 lib517 lib518 lib519 \ + lib520 lib521 lib523 lib524 lib525 lib526 lib527 lib529 lib530 lib532 \ + lib533 lib536 lib537 lib539 lib540 lib541 lib542 lib543 \ + lib544 lib545 \ + lib547 lib548 lib549 lib552 lib553 lib554 lib555 lib556 lib557 lib558 \ + lib559 lib560 lib562 lib564 lib565 lib566 lib567 lib568 lib569 lib570 \ + lib571 lib572 lib573 lib574 lib575 lib576 lib578 lib579 lib582 \ + lib583 lib584 lib585 lib586 lib587 lib589 lib590 lib591 lib597 lib598 \ + lib599 \ + lib643 lib645 lib650 lib651 lib652 lib653 lib654 lib655 lib658 \ + lib659 lib661 lib666 lib667 lib668 \ + lib670 lib671 lib672 lib673 lib674 lib676 lib677 lib678 \ + lib1156 \ + lib1301 \ + lib1485 \ + lib1500 lib1501 lib1502 lib1503 lib1504 lib1505 lib1506 lib1507 lib1508 \ + lib1509 lib1510 lib1511 lib1512 lib1513 lib1514 lib1515 lib1517 \ + lib1518 lib1520 lib1521 lib1522 lib1523 \ + lib1525 lib1526 lib1527 lib1528 lib1529 lib1530 lib1531 lib1532 lib1533 \ + lib1534 lib1535 lib1536 lib1537 lib1538 lib1539 \ + lib1540 lib1541 lib1542 lib1543 lib1545 \ + lib1550 lib1551 lib1552 lib1553 lib1554 lib1555 lib1556 lib1557 \ + lib1558 lib1559 lib1560 lib1564 lib1565 lib1567 lib1568 lib1569 \ + lib1591 lib1592 lib1593 lib1594 lib1596 lib1597 lib1598 \ + \ + lib1662 \ + \ + lib1900 lib1901 \ + lib1903 lib1905 lib1906 lib1907 lib1908 lib1910 lib1911 lib1912 lib1913 \ + lib1915 lib1916 lib1917 lib1918 lib1919 \ + lib1933 lib1934 lib1935 lib1936 lib1937 lib1938 lib1939 lib1940 \ + lib1945 lib1946 lib1947 lib1948 lib1955 lib1956 lib1957 lib1958 lib1959 \ + lib1960 lib1964 \ + lib1970 lib1971 lib1972 lib1973 lib1974 lib1975 \ + lib2301 lib2302 lib2304 lib2305 lib2306 lib2308 lib2309 \ + lib2402 lib2404 lib2405 \ + lib2502 \ + lib3010 lib3025 lib3026 lib3027 \ + lib3100 lib3101 lib3102 lib3103 lib3207 + +libntlmconnect_SOURCES = libntlmconnect.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +libntlmconnect_LDADD = $(TESTUTIL_LIBS) + +libauthretry_SOURCES = libauthretry.c $(SUPPORTFILES) +libauthretry_LDADD = $(TESTUTIL_LIBS) + +libprereq_SOURCES = libprereq.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +libprereq_LDADD = $(TESTUTIL_LIBS) + +lib500_SOURCES = lib500.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(MULTIBYTE) +lib500_LDADD = $(TESTUTIL_LIBS) + +lib501_SOURCES = lib501.c $(SUPPORTFILES) + +lib502_SOURCES = lib502.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib502_LDADD = $(TESTUTIL_LIBS) + +lib503_SOURCES = lib503.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib503_LDADD = $(TESTUTIL_LIBS) + +lib504_SOURCES = lib504.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib504_LDADD = $(TESTUTIL_LIBS) + +lib505_SOURCES = lib505.c $(SUPPORTFILES) $(MULTIBYTE) + +lib506_SOURCES = lib506.c $(SUPPORTFILES) + +lib507_SOURCES = lib507.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib507_LDADD = $(TESTUTIL_LIBS) + +lib508_SOURCES = lib508.c $(SUPPORTFILES) + +lib509_SOURCES = lib509.c $(SUPPORTFILES) + +lib510_SOURCES = lib510.c $(SUPPORTFILES) + +lib511_SOURCES = lib511.c $(SUPPORTFILES) + +lib512_SOURCES = lib512.c $(SUPPORTFILES) + +lib513_SOURCES = lib513.c $(SUPPORTFILES) + +lib514_SOURCES = lib514.c $(SUPPORTFILES) + +lib515_SOURCES = lib515.c $(SUPPORTFILES) + +lib516_SOURCES = lib516.c $(SUPPORTFILES) + +lib517_SOURCES = lib517.c $(SUPPORTFILES) + +lib518_SOURCES = lib518.c $(SUPPORTFILES) $(WARNLESS) $(MULTIBYTE) + +lib519_SOURCES = lib519.c $(SUPPORTFILES) + +lib520_SOURCES = lib520.c $(SUPPORTFILES) + +lib521_SOURCES = lib521.c $(SUPPORTFILES) + +lib523_SOURCES = lib523.c $(SUPPORTFILES) + +lib524_SOURCES = lib524.c $(SUPPORTFILES) + +lib525_SOURCES = lib525.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib525_LDADD = $(TESTUTIL_LIBS) + +lib526_SOURCES = lib526.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib526_LDADD = $(TESTUTIL_LIBS) +lib526_CPPFLAGS = $(AM_CPPFLAGS) -DLIB526 + +lib527_SOURCES = lib526.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib527_LDADD = $(TESTUTIL_LIBS) +lib527_CPPFLAGS = $(AM_CPPFLAGS) -DLIB527 + +lib529_SOURCES = lib525.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib529_LDADD = $(TESTUTIL_LIBS) +lib529_CPPFLAGS = $(AM_CPPFLAGS) -DLIB529 + +lib530_SOURCES = lib530.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib530_LDADD = $(TESTUTIL_LIBS) + +lib532_SOURCES = lib526.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib532_LDADD = $(TESTUTIL_LIBS) +lib532_CPPFLAGS = $(AM_CPPFLAGS) -DLIB532 + +lib533_SOURCES = lib533.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib533_LDADD = $(TESTUTIL_LIBS) + +lib536_SOURCES = lib536.c $(SUPPORTFILES) + +lib537_SOURCES = lib537.c $(SUPPORTFILES) $(WARNLESS) $(MULTIBYTE) + +lib539_SOURCES = lib539.c $(SUPPORTFILES) + +lib540_SOURCES = lib540.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib540_LDADD = $(TESTUTIL_LIBS) + +lib541_SOURCES = lib541.c $(SUPPORTFILES) $(MULTIBYTE) + +lib542_SOURCES = lib542.c $(SUPPORTFILES) + +lib543_SOURCES = lib543.c $(SUPPORTFILES) + +lib544_SOURCES = lib544.c $(SUPPORTFILES) + +lib545_SOURCES = lib544.c $(SUPPORTFILES) +lib545_CPPFLAGS = $(AM_CPPFLAGS) -DLIB545 + +lib547_SOURCES = lib547.c $(SUPPORTFILES) + +lib548_SOURCES = lib547.c $(SUPPORTFILES) +lib548_CPPFLAGS = $(AM_CPPFLAGS) -DLIB548 + +lib549_SOURCES = lib549.c $(SUPPORTFILES) + +lib552_SOURCES = lib552.c $(SUPPORTFILES) $(WARNLESS) + +lib553_SOURCES = lib553.c $(SUPPORTFILES) + +lib554_SOURCES = lib554.c $(SUPPORTFILES) + +lib555_SOURCES = lib555.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib555_LDADD = $(TESTUTIL_LIBS) + +lib556_SOURCES = lib556.c $(SUPPORTFILES) $(WARNLESS) + +lib557_SOURCES = lib557.c $(SUPPORTFILES) + +lib558_SOURCES = lib558.c $(SUPPORTFILES) + +lib559_SOURCES = lib559.c $(SUPPORTFILES) + +lib560_SOURCES = lib560.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib560_LDADD = $(TESTUTIL_LIBS) + +lib562_SOURCES = lib562.c $(SUPPORTFILES) + +lib564_SOURCES = lib564.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib564_LDADD = $(TESTUTIL_LIBS) + +lib565_SOURCES = lib510.c $(SUPPORTFILES) +lib565_CPPFLAGS = $(AM_CPPFLAGS) -DLIB565 + +lib566_SOURCES = lib566.c $(SUPPORTFILES) $(MULTIBYTE) + +lib567_SOURCES = lib567.c $(SUPPORTFILES) + +lib568_SOURCES = lib568.c $(SUPPORTFILES) $(MULTIBYTE) + +lib569_SOURCES = lib569.c $(SUPPORTFILES) $(MULTIBYTE) + +lib570_SOURCES = lib570.c $(SUPPORTFILES) + +lib571_SOURCES = lib571.c $(SUPPORTFILES) $(WARNLESS) $(MULTIBYTE) + +lib572_SOURCES = lib572.c $(SUPPORTFILES) $(MULTIBYTE) + +lib573_SOURCES = lib573.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(TSTTRACE) +lib573_LDADD = $(TESTUTIL_LIBS) + +lib574_SOURCES = lib574.c $(SUPPORTFILES) + +lib575_SOURCES = lib575.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib575_LDADD = $(TESTUTIL_LIBS) + +lib576_SOURCES = lib576.c $(SUPPORTFILES) + +lib578_SOURCES = lib578.c $(SUPPORTFILES) $(MULTIBYTE) + +lib579_SOURCES = lib579.c $(SUPPORTFILES) $(MULTIBYTE) + +lib582_SOURCES = lib582.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib582_LDADD = $(TESTUTIL_LIBS) + +lib583_SOURCES = lib583.c $(SUPPORTFILES) + +lib584_SOURCES = lib589.c $(SUPPORTFILES) +lib584_CPPFLAGS = $(AM_CPPFLAGS) -DLIB584 + +lib585_SOURCES = lib500.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(MULTIBYTE) +lib585_LDADD = $(TESTUTIL_LIBS) +lib585_CPPFLAGS = $(AM_CPPFLAGS) -DLIB585 + +lib586_SOURCES = lib586.c $(SUPPORTFILES) + +lib587_SOURCES = lib554.c $(SUPPORTFILES) +lib587_CPPFLAGS = $(AM_CPPFLAGS) -DLIB587 + +lib589_SOURCES = lib589.c $(SUPPORTFILES) + +lib590_SOURCES = lib590.c $(SUPPORTFILES) + +lib591_SOURCES = lib591.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib591_LDADD = $(TESTUTIL_LIBS) + +lib597_SOURCES = lib597.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib597_LDADD = $(TESTUTIL_LIBS) + +lib598_SOURCES = lib598.c $(SUPPORTFILES) + +lib599_SOURCES = lib599.c $(SUPPORTFILES) $(MULTIBYTE) + +lib643_SOURCES = lib643.c $(SUPPORTFILES) + +lib645_SOURCES = lib643.c $(SUPPORTFILES) +lib645_CPPFLAGS = $(AM_CPPFLAGS) -DLIB645 + +lib650_SOURCES = lib650.c $(SUPPORTFILES) + +lib651_SOURCES = lib651.c $(SUPPORTFILES) + +lib652_SOURCES = lib652.c $(SUPPORTFILES) + +lib653_SOURCES = lib653.c $(SUPPORTFILES) + +lib654_SOURCES = lib654.c $(SUPPORTFILES) + +lib655_SOURCES = lib655.c $(SUPPORTFILES) + +lib658_SOURCES = lib658.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib658_LDADD = $(TESTUTIL_LIBS) + +lib659_SOURCES = lib659.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib659_LDADD = $(TESTUTIL_LIBS) + +lib661_SOURCES = lib661.c $(SUPPORTFILES) + +lib666_SOURCES = lib666.c $(SUPPORTFILES) + +lib667_SOURCES = lib667.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib667_LDADD = $(TESTUTIL_LIBS) + +lib668_SOURCES = lib668.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib668_LDADD = $(TESTUTIL_LIBS) + +lib670_SOURCES = lib670.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib670_LDADD = $(TESTUTIL_LIBS) +lib670_CPPFLAGS = $(AM_CPPFLAGS) -DLIB670 + +lib671_SOURCES = lib670.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib671_LDADD = $(TESTUTIL_LIBS) +lib671_CPPFLAGS = $(AM_CPPFLAGS) -DLIB671 + +lib672_SOURCES = lib670.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib672_LDADD = $(TESTUTIL_LIBS) +lib672_CPPFLAGS = $(AM_CPPFLAGS) -DLIB672 + +lib673_SOURCES = lib670.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib673_LDADD = $(TESTUTIL_LIBS) + +lib674_SOURCES = lib674.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib674_LDADD = $(TESTUTIL_LIBS) + +lib676_SOURCES = lib676.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib676_LDADD = $(TESTUTIL_LIBS) + +lib677_SOURCES = lib677.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib677_LDADD = $(TESTUTIL_LIBS) + +lib678_SOURCES = lib678.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) $(MULTIBYTE) +lib678_LDADD = $(TESTUTIL_LIBS) + +lib1301_SOURCES = lib1301.c $(SUPPORTFILES) $(TESTUTIL) +lib1301_LDADD = $(TESTUTIL_LIBS) + +lib1485_SOURCES = lib1485.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1485_LDADD = $(TESTUTIL_LIBS) + +lib1500_SOURCES = lib1500.c $(SUPPORTFILES) $(TESTUTIL) +lib1500_LDADD = $(TESTUTIL_LIBS) + +lib1501_SOURCES = lib1501.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1501_LDADD = $(TESTUTIL_LIBS) + +lib1502_SOURCES = lib1502.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1502_LDADD = $(TESTUTIL_LIBS) +lib1502_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1502 + +lib1503_SOURCES = lib1502.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1503_LDADD = $(TESTUTIL_LIBS) +lib1503_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1503 + +lib1504_SOURCES = lib1502.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1504_LDADD = $(TESTUTIL_LIBS) +lib1504_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1504 + +lib1505_SOURCES = lib1502.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1505_LDADD = $(TESTUTIL_LIBS) +lib1505_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1505 + +lib1506_SOURCES = lib1506.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1506_LDADD = $(TESTUTIL_LIBS) + +lib1156_SOURCES = lib1156.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1156_LDADD = $(TESTUTIL_LIBS) + +lib1507_SOURCES = lib1507.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1507_LDADD = $(TESTUTIL_LIBS) + +lib1508_SOURCES = lib1508.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1508_LDADD = $(TESTUTIL_LIBS) + +lib1509_SOURCES = lib1509.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1509_LDADD = $(TESTUTIL_LIBS) + +lib1510_SOURCES = lib1510.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1510_LDADD = $(TESTUTIL_LIBS) + +lib1511_SOURCES = lib1511.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1511_LDADD = $(TESTUTIL_LIBS) + +lib1512_SOURCES = lib1512.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1512_LDADD = $(TESTUTIL_LIBS) + +lib1513_SOURCES = lib1513.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1513_LDADD = $(TESTUTIL_LIBS) + +lib1514_SOURCES = lib1514.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1514_LDADD = $(TESTUTIL_LIBS) + +lib1515_SOURCES = lib1515.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(WARNLESS) +lib1515_LDADD = $(TESTUTIL_LIBS) + +lib1517_SOURCES = lib1517.c $(SUPPORTFILES) + +lib1518_SOURCES = lib1518.c $(SUPPORTFILES) + +lib1520_SOURCES = lib1520.c $(SUPPORTFILES) + +nodist_lib1521_SOURCES = lib1521.c $(SUPPORTFILES) +lib1521_CPPFLAGS = $(AM_CPPFLAGS) -I$(srcdir) + +lib1522_SOURCES = lib1522.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) +lib1522_LDADD = $(TESTUTIL_LIBS) + +lib1523_SOURCES = lib1523.c $(SUPPORTFILES) + +lib1525_SOURCES = lib1525.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1525_LDADD = $(TESTUTIL_LIBS) + +lib1526_SOURCES = lib1526.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1526_LDADD = $(TESTUTIL_LIBS) + +lib1527_SOURCES = lib1527.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1527_LDADD = $(TESTUTIL_LIBS) + +lib1528_SOURCES = lib1528.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1528_LDADD = $(TESTUTIL_LIBS) + +lib1529_SOURCES = lib1529.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1529_LDADD = $(TESTUTIL_LIBS) + +lib1530_SOURCES = lib1530.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1530_LDADD = $(TESTUTIL_LIBS) + +lib1531_SOURCES = lib1531.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1531_LDADD = $(TESTUTIL_LIBS) + +lib1532_SOURCES = lib1532.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1532_LDADD = $(TESTUTIL_LIBS) + +lib1533_SOURCES = lib1533.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1533_LDADD = $(TESTUTIL_LIBS) + +lib1534_SOURCES = lib1534.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1534_LDADD = $(TESTUTIL_LIBS) + +lib1535_SOURCES = lib1535.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1535_LDADD = $(TESTUTIL_LIBS) + +lib1536_SOURCES = lib1536.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1536_LDADD = $(TESTUTIL_LIBS) + +lib1537_SOURCES = lib1537.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1537_LDADD = $(TESTUTIL_LIBS) + +lib1538_SOURCES = lib1538.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1538_LDADD = $(TESTUTIL_LIBS) + +lib1539_SOURCES = lib1514.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1539_LDADD = $(TESTUTIL_LIBS) +lib1539_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1539 + +lib1540_SOURCES = lib1540.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(WARNLESS) +lib1540_LDADD = $(TESTUTIL_LIBS) + +lib1541_SOURCES = lib1541.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1541_LDADD = $(TESTUTIL_LIBS) + +lib1542_SOURCES = lib1542.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(WARNLESS) +lib1542_LDADD = $(TESTUTIL_LIBS) + +lib1543_SOURCES = lib1518.c $(SUPPORTFILES) +lib1543_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1543 + +lib1545_SOURCES = lib1545.c $(SUPPORTFILES) + +lib1550_SOURCES = lib1550.c $(SUPPORTFILES) + +lib1551_SOURCES = lib1551.c $(SUPPORTFILES) + +lib1552_SOURCES = lib1552.c $(SUPPORTFILES) $(TESTUTIL) +lib1552_LDADD = $(TESTUTIL_LIBS) + +lib1553_SOURCES = lib1553.c $(SUPPORTFILES) $(TSTTRACE) $(TESTUTIL) +lib1553_LDADD = $(TESTUTIL_LIBS) + +lib1554_SOURCES = lib1554.c $(SUPPORTFILES) + +lib1555_SOURCES = lib1555.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1555_LDADD = $(TESTUTIL_LIBS) + +lib1556_SOURCES = lib1556.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1556_LDADD = $(TESTUTIL_LIBS) + +lib1557_SOURCES = lib1557.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1557_LDADD = $(TESTUTIL_LIBS) + +lib1558_SOURCES = lib1558.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1558_LDADD = $(TESTUTIL_LIBS) + +lib1559_SOURCES = lib1559.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1559_LDADD = $(TESTUTIL_LIBS) + +lib1560_SOURCES = lib1560.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1560_LDADD = $(TESTUTIL_LIBS) + +lib1564_SOURCES = lib1564.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1564_LDADD = $(TESTUTIL_LIBS) + +lib1565_SOURCES = lib1565.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1565_LDADD = $(TESTUTIL_LIBS) + +lib1567_SOURCES = lib1567.c $(SUPPORTFILES) + +lib1568_SOURCES = lib1568.c $(SUPPORTFILES) + +lib1569_SOURCES = lib1569.c $(SUPPORTFILES) + +lib1591_SOURCES = lib1591.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1591_LDADD = $(TESTUTIL_LIBS) + +lib1592_SOURCES = lib1592.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1592_LDADD = $(TESTUTIL_LIBS) + +lib1593_SOURCES = lib1593.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1593_LDADD = $(TESTUTIL_LIBS) + +lib1594_SOURCES = lib1594.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1594_LDADD = $(TESTUTIL_LIBS) + +lib1596_SOURCES = lib1594.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1596_LDADD = $(TESTUTIL_LIBS) +lib1596_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1596 + +lib1597_SOURCES = lib1597.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1597_LDADD = $(TESTUTIL_LIBS) + +lib1598_SOURCES = lib1598.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1598_LDADD = $(TESTUTIL_LIBS) + +lib1662_SOURCES = lib1662.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1662_LDADD = $(TESTUTIL_LIBS) + +lib1900_SOURCES = lib1900.c $(SUPPORTFILES) + +lib1901_SOURCES = lib1901.c $(SUPPORTFILES) + +lib1903_SOURCES = lib1903.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1903_LDADD = $(TESTUTIL_LIBS) + +lib1905_SOURCES = lib1905.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1905_LDADD = $(TESTUTIL_LIBS) + +lib1906_SOURCES = lib1906.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1906_LDADD = $(TESTUTIL_LIBS) + +lib1907_SOURCES = lib1907.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1907_LDADD = $(TESTUTIL_LIBS) + +lib1908_SOURCES = lib1908.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1908_LDADD = $(TESTUTIL_LIBS) + +lib1910_SOURCES = lib1910.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1910_LDADD = $(TESTUTIL_LIBS) + +lib1911_SOURCES = lib1911.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1911_LDADD = $(TESTUTIL_LIBS) + +lib1912_SOURCES = lib1912.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1912_LDADD = $(TESTUTIL_LIBS) + +lib1913_SOURCES = lib1913.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1913_LDADD = $(TESTUTIL_LIBS) + +lib1915_SOURCES = lib1915.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(WARNLESS) +lib1915_LDADD = $(TESTUTIL_LIBS) + +lib1916_SOURCES = lib1916.c $(SUPPORTFILES) $(WARNLESS) + +lib1917_SOURCES = lib1916.c $(SUPPORTFILES) $(WARNLESS) +lib1917_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1917 + +lib1918_SOURCES = lib1918.c $(SUPPORTFILES) $(WARNLESS) + +lib1919_SOURCES = lib1919.c $(SUPPORTFILES) $(WARNLESS) + +lib1933_SOURCES = lib1933.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1933_LDADD = $(TESTUTIL_LIBS) + +lib1934_SOURCES = lib1934.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1934_LDADD = $(TESTUTIL_LIBS) + +lib1935_SOURCES = lib1935.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1935_LDADD = $(TESTUTIL_LIBS) + +lib1936_SOURCES = lib1936.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1936_LDADD = $(TESTUTIL_LIBS) + +lib1937_SOURCES = lib1937.c $(SUPPORTFILES) +lib1937_LDADD = $(TESTUTIL_LIBS) + +lib1938_SOURCES = lib1938.c $(SUPPORTFILES) +lib1938_LDADD = $(TESTUTIL_LIBS) + +lib1939_SOURCES = lib1939.c $(SUPPORTFILES) +lib1939_LDADD = $(TESTUTIL_LIBS) + +lib1940_SOURCES = lib1940.c $(SUPPORTFILES) +lib1940_LDADD = $(TESTUTIL_LIBS) + +lib1945_SOURCES = lib1945.c $(SUPPORTFILES) +lib1945_LDADD = $(TESTUTIL_LIBS) + +lib1946_SOURCES = lib1940.c $(SUPPORTFILES) +lib1946_LDADD = $(TESTUTIL_LIBS) +lib1946_CPPFLAGS = $(AM_CPPFLAGS) -DLIB1946 + +lib1947_SOURCES = lib1947.c $(SUPPORTFILES) +lib1947_LDADD = $(TESTUTIL_LIBS) + +lib1948_SOURCES = lib1948.c $(SUPPORTFILES) +lib1948_LDADD = $(TESTUTIL_LIBS) + +lib1955_SOURCES = lib1955.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1955_LDADD = $(TESTUTIL_LIBS) + +lib1956_SOURCES = lib1956.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1956_LDADD = $(TESTUTIL_LIBS) + +lib1957_SOURCES = lib1957.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1957_LDADD = $(TESTUTIL_LIBS) + +lib1958_SOURCES = lib1958.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1958_LDADD = $(TESTUTIL_LIBS) + +lib1959_SOURCES = lib1959.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1959_LDADD = $(TESTUTIL_LIBS) + +lib1960_SOURCES = lib1960.c $(SUPPORTFILES) +lib1960_LDADD = $(TESTUTIL_LIBS) + +lib1964_SOURCES = lib1964.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1964_LDADD = $(TESTUTIL_LIBS) + +lib1970_SOURCES = lib1970.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1970_LDADD = $(TESTUTIL_LIBS) + +lib1971_SOURCES = lib1971.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1971_LDADD = $(TESTUTIL_LIBS) + +lib1972_SOURCES = lib1972.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1972_LDADD = $(TESTUTIL_LIBS) + +lib1973_SOURCES = lib1973.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1973_LDADD = $(TESTUTIL_LIBS) + +lib1974_SOURCES = lib1974.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1974_LDADD = $(TESTUTIL_LIBS) + +lib1975_SOURCES = lib1975.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib1975_LDADD = $(TESTUTIL_LIBS) + +lib2301_SOURCES = lib2301.c $(SUPPORTFILES) +lib2301_LDADD = $(TESTUTIL_LIBS) + +lib2302_SOURCES = lib2302.c $(SUPPORTFILES) +lib2302_LDADD = $(TESTUTIL_LIBS) + +lib2304_SOURCES = lib2304.c $(SUPPORTFILES) +lib2304_LDADD = $(TESTUTIL_LIBS) + +lib2305_SOURCES = lib2305.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(MULTIBYTE) +lib2305_LDADD = $(TESTUTIL_LIBS) + +lib2306_SOURCES = lib2306.c $(SUPPORTFILES) +lib2306_LDADD = $(TESTUTIL_LIBS) + +lib2308_SOURCES = lib2308.c $(SUPPORTFILES) +lib2308_LDADD = $(TESTUTIL_LIBS) + +lib2309_SOURCES = lib2309.c $(SUPPORTFILES) +lib2309_LDADD = $(TESTUTIL_LIBS) + +lib2402_SOURCES = lib2402.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib2402_LDADD = $(TESTUTIL_LIBS) + +lib2404_SOURCES = lib2404.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib2404_LDADD = $(TESTUTIL_LIBS) + +lib2405_SOURCES = lib2405.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib2405_LDADD = $(TESTUTIL_LIBS) + +lib2502_SOURCES = lib2502.c $(SUPPORTFILES) $(TESTUTIL) $(TSTTRACE) $(WARNLESS) +lib2502_LDADD = $(TESTUTIL_LIBS) + +lib3010_SOURCES = lib3010.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3010_LDADD = $(TESTUTIL_LIBS) + +lib3025_SOURCES = lib3025.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3025_LDADD = $(TESTUTIL_LIBS) + +lib3026_SOURCES = lib3026.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3026_LDADD = $(TESTUTIL_LIBS) + +lib3027_SOURCES = lib3027.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3027_LDADD = $(TESTUTIL_LIBS) + +lib3100_SOURCES = lib3100.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3100_LDADD = $(TESTUTIL_LIBS) + +lib3101_SOURCES = lib3101.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3101_LDADD = $(TESTUTIL_LIBS) + +lib3102_SOURCES = lib3102.c $(SUPPORTFILES) $(TESTUTIL) $(WARNLESS) +lib3102_LDADD = $(TESTUTIL_LIBS) + +lib3103_SOURCES = lib3103.c $(SUPPORTFILES) +lib3103_LDADD = $(TESTUTIL_LIBS) + +lib3207_SOURCES = lib3207.c $(SUPPORTFILES) $(TESTUTIL) $(THREADS) $(WARNLESS) $(MULTIBYTE) +lib3207_LDADD = $(TESTUTIL_LIBS) diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/first.c b/local-test-curl-delta-01/afc-curl/tests/libtest/first.c new file mode 100644 index 0000000000000000000000000000000000000000..68c649e08bd237148bf9db49ad904279ac98795e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/first.c @@ -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 + * + ***************************************************************************/ +#include "test.h" +#include "first.h" + +#ifdef HAVE_LOCALE_H +# include /* for setlocale() */ +#endif + +#ifdef HAVE_IO_H +# include /* for setmode() */ +#endif + +#ifdef HAVE_FCNTL_H +# include /* for setmode() */ +#endif + +#ifdef CURLDEBUG +# define MEMDEBUG_NODEFINES +# include "memdebug.h" +#endif + +#include "timediff.h" + +int select_wrapper(int nfds, fd_set *rd, fd_set *wr, fd_set *exc, + struct timeval *tv) +{ + if(nfds < 0) { + SET_SOCKERRNO(EINVAL); + return -1; + } +#ifdef USE_WINSOCK + /* + * Winsock select() requires that at least one of the three fd_set + * pointers is not NULL and points to a non-empty fdset. IOW Winsock + * select() can not be used to sleep without a single fd_set. + */ + if(!nfds) { + Sleep((DWORD)curlx_tvtoms(tv)); + return 0; + } +#endif + return select(nfds, rd, wr, exc, tv); +} + +void wait_ms(int ms) +{ + if(ms < 0) + return; +#ifdef USE_WINSOCK + Sleep((DWORD)ms); +#else + { + struct timeval t; + curlx_mstotv(&t, ms); + select_wrapper(0, NULL, NULL, NULL, &t); + } +#endif +} + +char *libtest_arg2 = NULL; +char *libtest_arg3 = NULL; +int test_argc; +char **test_argv; + +struct timeval tv_test_start; /* for test timing */ + +int unitfail; /* for unittests */ + +#ifdef CURLDEBUG +static void memory_tracking_init(void) +{ + char *env; + /* if CURL_MEMDEBUG is set, this starts memory tracking message logging */ + env = curl_getenv("CURL_MEMDEBUG"); + if(env) { + /* use the value as file name */ + char fname[CURL_MT_LOGFNAME_BUFSIZE]; + if(strlen(env) >= CURL_MT_LOGFNAME_BUFSIZE) + env[CURL_MT_LOGFNAME_BUFSIZE-1] = '\0'; + strcpy(fname, env); + curl_free(env); + curl_dbg_memdebug(fname); + /* this weird stuff here is to make curl_free() get called before + curl_dbg_memdebug() as otherwise memory tracking will log a free() + without an alloc! */ + } + /* if CURL_MEMLIMIT is set, this enables fail-on-alloc-number-N feature */ + env = curl_getenv("CURL_MEMLIMIT"); + if(env) { + char *endptr; + long num = strtol(env, &endptr, 10); + if((endptr != env) && (endptr == env + strlen(env)) && (num > 0)) + curl_dbg_memlimit(num); + curl_free(env); + } +} +#else +# define memory_tracking_init() Curl_nop_stmt +#endif + +/* returns a hexdump in a static memory area */ +char *hexdump(const unsigned char *buf, size_t len) +{ + static char dump[200 * 3 + 1]; + char *p = dump; + size_t i; + if(len > 200) + return NULL; + for(i = 0; i < len; i++, p += 3) + msnprintf(p, 4, "%02x ", buf[i]); + return dump; +} + + +int main(int argc, char **argv) +{ + char *URL; + CURLcode result; + int basearg; + test_func_t test_func; + +#ifdef O_BINARY +# ifdef __HIGHC__ + _setmode(stdout, O_BINARY); +# else + setmode(fileno(stdout), O_BINARY); +# endif +#endif + + memory_tracking_init(); + + /* + * Setup proper locale from environment. This is needed to enable locale- + * specific behavior by the C library in order to test for undesired side + * effects that could cause in libcurl. + */ +#ifdef HAVE_SETLOCALE + setlocale(LC_ALL, ""); +#endif + + test_argc = argc; + test_argv = argv; + +#ifdef CURLTESTS_BUNDLED + { + char *test_name; + + --test_argc; + ++test_argv; + + basearg = 2; + + if(argc < (basearg + 1)) { + fprintf(stderr, "Pass testname and URL as arguments please\n"); + return 1; + } + + test_name = argv[basearg - 1]; + test_func = NULL; + { + size_t tmp; + for(tmp = 0; tmp < (sizeof(s_tests)/sizeof((s_tests)[0])); ++tmp) { + if(strcmp(test_name, s_tests[tmp].name) == 0) { + test_func = s_tests[tmp].ptr; + break; + } + } + } + + if(!test_func) { + fprintf(stderr, "Test '%s' not found.\n", test_name); + return 1; + } + + fprintf(stderr, "Test: %s\n", test_name); + } +#else + basearg = 1; + + if(argc < (basearg + 1)) { + fprintf(stderr, "Pass URL as argument please\n"); + return 1; + } + + test_func = test; +#endif + + if(argc > (basearg + 1)) + libtest_arg2 = argv[basearg + 1]; + + if(argc > (basearg + 2)) + libtest_arg3 = argv[basearg + 2]; + + URL = argv[basearg]; /* provide this to the rest */ + + fprintf(stderr, "URL: %s\n", URL); + + result = test_func(URL); + fprintf(stderr, "Test ended with result %d\n", result); + +#ifdef _WIN32 + /* flush buffers of all streams regardless of mode */ + _flushall(); +#endif + + /* Regular program status codes are limited to 0..127 and 126 and 127 have + * special meanings by the shell, so limit a normal return code to 125 */ + return (int)result <= 125 ? (int)result : 125; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/first.h b/local-test-curl-delta-01/afc-curl/tests/libtest/first.h new file mode 100644 index 0000000000000000000000000000000000000000..1e4ae5fc37da8662dd1b93d5c0d8ff4c7055fa18 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/first.h @@ -0,0 +1,38 @@ +#ifndef HEADER_LIBTEST_FIRST_H +#define HEADER_LIBTEST_FIRST_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 CURLcode (*test_func_t)(char *); + +#ifdef CURLTESTS_BUNDLED +struct onetest { + const char *name; + test_func_t ptr; +}; +#endif + +#endif /* HEADER_LIBTEST_FIRST_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1156.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1156.c new file mode 100644 index 0000000000000000000000000000000000000000..6854e3bc445265b6200e12b4fe568cd1c0909dec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1156.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 + * + ***************************************************************************/ +#include "test.h" + +/* + Check range/resume returned error codes and data presence. + + The input parameters are: + - CURLOPT_RANGE/CURLOPT_RESUME_FROM + - CURLOPT_FAILONERROR + - Returned http code (2xx/416) + - Content-Range header present in reply. + +*/ + +#include "memdebug.h" + +#define F_RESUME (1 << 0) /* resume/range. */ +#define F_HTTP416 (1 << 1) /* Server returns http code 416. */ +#define F_FAIL (1 << 2) /* Fail on error. */ +#define F_CONTENTRANGE (1 << 3) /* Server sends content-range hdr. */ +#define F_IGNOREBODY (1 << 4) /* Body should be ignored. */ + +struct testparams { + unsigned int flags; /* ORed flags as above. */ + CURLcode result; /* Code that should be returned by curl_easy_perform(). */ +}; + +static const struct testparams testparams[] = { + { 0, CURLE_OK }, + { F_CONTENTRANGE, CURLE_OK }, + { F_FAIL, CURLE_OK }, + { F_FAIL | F_CONTENTRANGE, CURLE_OK }, + { F_HTTP416, CURLE_OK }, + { F_HTTP416 | F_CONTENTRANGE, CURLE_OK }, + { F_HTTP416 | F_FAIL | F_IGNOREBODY, + CURLE_HTTP_RETURNED_ERROR }, + { F_HTTP416 | F_FAIL | F_CONTENTRANGE | F_IGNOREBODY, + CURLE_HTTP_RETURNED_ERROR }, + { F_RESUME | F_IGNOREBODY, + CURLE_RANGE_ERROR }, + { F_RESUME | F_CONTENTRANGE, CURLE_OK }, + { F_RESUME | F_FAIL | F_IGNOREBODY, + CURLE_RANGE_ERROR }, + { F_RESUME | F_FAIL | F_CONTENTRANGE, CURLE_OK }, + { F_RESUME | F_HTTP416 | F_IGNOREBODY, CURLE_OK }, + { F_RESUME | F_HTTP416 | F_CONTENTRANGE | F_IGNOREBODY, CURLE_OK }, + { F_RESUME | F_HTTP416 | F_FAIL | F_IGNOREBODY, CURLE_OK }, + { F_RESUME | F_HTTP416 | F_FAIL | F_CONTENTRANGE | F_IGNOREBODY, + CURLE_OK } +}; + +static int hasbody; + +static size_t writedata(char *data, size_t size, size_t nmemb, void *userdata) +{ + (void) data; + (void) userdata; + + if(size && nmemb) + hasbody = 1; + return size * nmemb; +} + +static int onetest(CURL *curl, const char *url, const struct testparams *p, + size_t num) +{ + CURLcode res; + unsigned int replyselector; + char urlbuf[256]; + + replyselector = (p->flags & F_CONTENTRANGE) ? 1 : 0; + if(p->flags & F_HTTP416) + replyselector += 2; + msnprintf(urlbuf, sizeof(urlbuf), "%s%04u", url, replyselector); + test_setopt(curl, CURLOPT_URL, urlbuf); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_RESUME_FROM, (p->flags & F_RESUME) ? 3 : 0); + test_setopt(curl, CURLOPT_RANGE, !(p->flags & F_RESUME) ? + "3-1000000": (char *) NULL); + test_setopt(curl, CURLOPT_FAILONERROR, (p->flags & F_FAIL) ? 1 : 0); + hasbody = 0; + res = curl_easy_perform(curl); + if(res != p->result) { + printf("%zd: bad error code (%d): resume=%s, fail=%s, http416=%s, " + "content-range=%s, expected=%d\n", num, res, + (p->flags & F_RESUME) ? "yes": "no", + (p->flags & F_FAIL) ? "yes": "no", + (p->flags & F_HTTP416) ? "yes": "no", + (p->flags & F_CONTENTRANGE) ? "yes": "no", + p->result); + return 1; + } + if(hasbody && (p->flags & F_IGNOREBODY)) { + printf("body should be ignored and is not: resume=%s, fail=%s, " + "http416=%s, content-range=%s\n", + (p->flags & F_RESUME) ? "yes": "no", + (p->flags & F_FAIL) ? "yes": "no", + (p->flags & F_HTTP416) ? "yes": "no", + (p->flags & F_CONTENTRANGE) ? "yes": "no"); + return 1; + } + return 0; + +test_cleanup: + + return 1; +} + +/* for debugging: */ +/* #define SINGLETEST 9 */ + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + size_t i; + int status = 0; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + for(i = 0; i < sizeof(testparams) / sizeof(testparams[0]); i++) { + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_WRITEFUNCTION, writedata); + +#ifdef SINGLETEST + if(SINGLETEST == i) +#endif + status |= onetest(curl, URL, testparams + i, i); + curl_easy_cleanup(curl); + } + + curl_global_cleanup(); + printf("%d\n", status); + return (CURLcode)status; + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1301.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1301.c new file mode 100644 index 0000000000000000000000000000000000000000..de3aaeac6a9ea62a8c5038cbfed32268210c0545 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1301.c @@ -0,0 +1,62 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#define fail_unless(expr, msg) \ + do { \ + if(!(expr)) { \ + fprintf(stderr, "%s:%d Assertion '%s' failed: %s\n", \ + __FILE__, __LINE__, #expr, msg); \ + return (CURLcode)1; \ + } \ + } while(0) + +CURLcode test(char *URL) +{ + int rc; + (void)URL; + + rc = curl_strequal("iii", "III"); + fail_unless(rc != 0, "return code should be non-zero"); + + rc = curl_strequal("iiia", "III"); + fail_unless(rc == 0, "return code should be zero"); + + rc = curl_strequal("iii", "IIIa"); + fail_unless(rc == 0, "return code should be zero"); + + rc = curl_strequal("iiiA", "IIIa"); + fail_unless(rc != 0, "return code should be non-zero"); + + rc = curl_strnequal("iii", "III", 3); + fail_unless(rc != 0, "return code should be non-zero"); + + rc = curl_strnequal("iiiABC", "IIIcba", 3); + fail_unless(rc != 0, "return code should be non-zero"); + + rc = curl_strnequal("ii", "II", 3); + fail_unless(rc != 0, "return code should be non-zero"); + + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1485.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1485.c new file mode 100644 index 0000000000000000000000000000000000000000..650746a37816ca8ffe54d15fb76f87a0017a0413 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1485.c @@ -0,0 +1,120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +struct transfer_status { + CURL *easy; + curl_off_t out_len; + size_t hd_line; + CURLcode result; + int http_status; +}; + +static size_t header_callback(char *ptr, size_t size, size_t nmemb, + void *userp) +{ + struct transfer_status *st = (struct transfer_status *)userp; + const char *hd = ptr; + size_t len = size * nmemb; + CURLcode result; + + (void)fwrite(ptr, size, nmemb, stdout); + ++st->hd_line; + if(len == 2 && hd[0] == '\r' && hd[1] == '\n') { + curl_off_t clen; + long httpcode = 0; + /* end of a response */ + result = curl_easy_getinfo(st->easy, CURLINFO_RESPONSE_CODE, &httpcode); + fprintf(stderr, "header_callback, get status: %ld, %d\n", + httpcode, result); + if(httpcode < 100 || httpcode >= 1000) { + fprintf(stderr, "header_callback, invalid status: %ld, %d\n", + httpcode, result); + return CURLE_WRITE_ERROR; + } + st->http_status = (int)httpcode; + if(st->http_status >= 200 && st->http_status < 300) { + result = curl_easy_getinfo(st->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, + &clen); + fprintf(stderr, "header_callback, info Content-Length: %ld, %d\n", + (long)clen, result); + if(result) { + st->result = result; + return CURLE_WRITE_ERROR; + } + if(clen < 0) { + fprintf(stderr, "header_callback, expected known Content-Length, " + "got: %ld\n", (long)clen); + return CURLE_WRITE_ERROR; + } + } + } + return len; +} + +static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct transfer_status *st = (struct transfer_status *)userp; + size_t len = size * nmemb; + fwrite(ptr, size, nmemb, stdout); + st->out_len += (curl_off_t)len; + return len; +} + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLcode res = CURLE_OK; + struct transfer_status st; + + start_test_timing(); + + memset(&st, 0, sizeof(st)); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curls); + st.easy = curls; /* to allow callbacks access */ + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_WRITEFUNCTION, write_callback); + easy_setopt(curls, CURLOPT_WRITEDATA, &st); + easy_setopt(curls, CURLOPT_HEADERFUNCTION, header_callback); + easy_setopt(curls, CURLOPT_HEADERDATA, &st); + + easy_setopt(curls, CURLOPT_NOPROGRESS, 1L); + + res = curl_easy_perform(curls); + +test_cleanup: + + curl_easy_cleanup(curls); + curl_global_cleanup(); + + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1500.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1500.c new file mode 100644 index 0000000000000000000000000000000000000000..9f4ff07eac017008d43b237a2fbf3f980f526e7f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1500.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLM *multi = NULL; + int still_running; + CURLcode i = TEST_ERR_FAILURE; + CURLcode res = CURLE_OK; + CURLMsg *msg; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multi); + + easy_init(curls); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_HEADER, 1L); + + multi_add_handle(multi, curls); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + CURLMcode mres; + int num; + mres = curl_multi_wait(multi, NULL, 0, TEST_HANG_TIMEOUT, &num); + if(mres != CURLM_OK) { + printf("curl_multi_wait() returned %d\n", mres); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + } + + msg = curl_multi_info_read(multi, &still_running); + if(msg) + /* this should now contain a result code from the easy handle, + get it */ + i = msg->data.result; + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi); + curl_easy_cleanup(curls); + curl_global_cleanup(); + + if(res) + i = res; + + return i; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1501.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1501.c new file mode 100644 index 0000000000000000000000000000000000000000..ced1d5d987f09b4d27fad47956be285f0f69f5db --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1501.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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 30 * 1000 + +/* 500 milliseconds allowed. An extreme number but lets be really conservative + to allow old and slow machines to run this test too */ +#define MAX_BLOCKED_TIME_MS 500 + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURLM *mhandle = NULL; + CURLcode res = CURLE_OK; + int still_running = 0; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(handle); + + easy_setopt(handle, CURLOPT_URL, URL); + easy_setopt(handle, CURLOPT_VERBOSE, 1L); + + multi_init(mhandle); + + multi_add_handle(mhandle, handle); + + multi_perform(mhandle, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -99; + struct timeval before; + struct timeval after; + long e; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(mhandle, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + + fprintf(stderr, "ping\n"); + before = tutil_tvnow(); + + multi_perform(mhandle, &still_running); + + abort_on_test_timeout(); + + after = tutil_tvnow(); + e = tutil_tvdiff(after, before); + fprintf(stderr, "pong = %ld\n", e); + + if(e > MAX_BLOCKED_TIME_MS) { + res = (CURLcode) 100; + break; + } + } + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(mhandle); + curl_easy_cleanup(handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1502.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1502.c new file mode 100644 index 0000000000000000000000000000000000000000..d4ebdf50157252a2f57a21daa5b5e6f5436b512d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1502.c @@ -0,0 +1,159 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 used for lib1502, lib1503, lib1504 and lib1505 with + * only #ifdefs controlling the cleanup sequence. + * + * Test case 1502 converted from bug report #3575448, identifying a memory + * leak in the CURLOPT_RESOLVE handling with the multi interface. + */ + +#include "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURL *dup; + CURLM *multi = NULL; + int still_running; + CURLcode res = CURLE_OK; + + char redirect[160]; + + /* DNS cache injection */ + struct curl_slist *dns_cache_list; + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + return res; + } + + msnprintf(redirect, sizeof(redirect), "google.com:%s:%s", libtest_arg2, + libtest_arg3); + + start_test_timing(); + + dns_cache_list = curl_slist_append(NULL, redirect); + if(!dns_cache_list) { + fprintf(stderr, "curl_slist_append() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + easy_init(easy); + + easy_setopt(easy, CURLOPT_URL, URL); + easy_setopt(easy, CURLOPT_HEADER, 1L); + easy_setopt(easy, CURLOPT_RESOLVE, dns_cache_list); + + dup = curl_easy_duphandle(easy); + if(dup) { + curl_easy_cleanup(easy); + easy = dup; + } + else { + curl_slist_free_all(dns_cache_list); + curl_easy_cleanup(easy); + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + + multi_init(multi); + + multi_add_handle(multi, easy); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -99; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + } + +test_cleanup: + +#ifdef LIB1502 + /* undocumented cleanup sequence - type UA */ + curl_multi_cleanup(multi); + curl_easy_cleanup(easy); + curl_global_cleanup(); +#endif + +#ifdef LIB1503 + /* proper cleanup sequence - type PA */ + curl_multi_remove_handle(multi, easy); + curl_multi_cleanup(multi); + curl_easy_cleanup(easy); + curl_global_cleanup(); +#endif + +#ifdef LIB1504 + /* undocumented cleanup sequence - type UB */ + curl_easy_cleanup(easy); + curl_multi_cleanup(multi); + curl_global_cleanup(); +#endif + +#ifdef LIB1505 + /* proper cleanup sequence - type PB */ + curl_multi_remove_handle(multi, easy); + curl_easy_cleanup(easy); + curl_multi_cleanup(multi); + curl_global_cleanup(); +#endif + + curl_slist_free_all(dns_cache_list); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1506.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1506.c new file mode 100644 index 0000000000000000000000000000000000000000..2dbda6d0d07060661b0ad17f30834fb6a6592546 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1506.c @@ -0,0 +1,139 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_HANDLES 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES] = {0}; + int running; + CURLM *m = NULL; + int i; + char target_url[256]; + char dnsentry[256]; + struct curl_slist *slist = NULL, *slist2; + char *port = libtest_arg3; + char *address = libtest_arg2; + + (void)URL; + + /* Create fake DNS entries for serverX.example.com for all handles */ + for(i = 0; i < NUM_HANDLES; i++) { + msnprintf(dnsentry, sizeof(dnsentry), "server%d.example.com:%s:%s", + i + 1, port, address); + printf("%s\n", dnsentry); + slist2 = curl_slist_append(slist, dnsentry); + if(!slist2) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + slist = slist2; + } + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(m); + + multi_setopt(m, CURLMOPT_MAXCONNECTS, 3L); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + /* get an easy handle */ + easy_init(curl[i]); + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "http://server%d.example.com:%s/path/1506%04i", + i + 1, port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl[i], CURLOPT_URL, target_url); + /* go verbose */ + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl[i], CURLOPT_HEADER, 1L); + + easy_setopt(curl[i], CURLOPT_RESOLVE, slist); + } + + fprintf(stderr, "Start at URL 0\n"); + + for(i = 0; i < NUM_HANDLES; i++) { + /* add handle to multi */ + multi_add_handle(m, curl[i]); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + wait_ms(1); /* to ensure different end times */ + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(m, curl[i]); + curl_easy_cleanup(curl[i]); + } + + curl_slist_free_all(slist); + + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1507.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1507.c new file mode 100644 index 0000000000000000000000000000000000000000..fc788459cd66a5bf087c0f6e640ef711f42f117e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1507.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 "test.h" + +#include "testutil.h" +#include "timediff.h" +#include "warnless.h" +#include "memdebug.h" + +/* + * This is the list of basic details you need to tweak to get things right. + */ +#define USERNAME "user@example.com" +#define PASSWORD "123qwerty" +#define RECIPIENT "<1507-recipient@example.com>" +#define MAILFROM "<1507-realuser@example.com>" + +#define MULTI_PERFORM_HANG_TIMEOUT 60 * 1000 + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + (void)ptr; + (void)size; + (void)nmemb; + (void)userp; + return CURL_READFUNC_ABORT; +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + CURLM *mcurl = NULL; + int still_running = 1; + struct timeval mp_start; + struct curl_slist *rcpt_list = NULL; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + easy_init(curl); + + multi_init(mcurl); + + rcpt_list = curl_slist_append(rcpt_list, RECIPIENT); + /* more addresses can be added here + rcpt_list = curl_slist_append(rcpt_list, ""); + */ + + curl_easy_setopt(curl, CURLOPT_URL, URL); +#if 0 + curl_easy_setopt(curl, CURLOPT_USERNAME, USERNAME); + curl_easy_setopt(curl, CURLOPT_PASSWORD, PASSWORD); +#endif + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, MAILFROM); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, rcpt_list); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + multi_add_handle(mcurl, curl); + + mp_start = tutil_tvnow(); + + /* we start some action by calling perform right away */ + curl_multi_perform(mcurl, &still_running); + + while(still_running) { + struct timeval timeout; + int rc; /* select() return code */ + + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -1; + + long curl_timeo = -1; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + /* set a suitable timeout to play around with */ + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + curl_multi_timeout(mcurl, &curl_timeo); + if(curl_timeo >= 0) { + curlx_mstotv(&timeout, curl_timeo); + if(timeout.tv_sec > 1) { + timeout.tv_sec = 1; + timeout.tv_usec = 0; + } + } + + /* get file descriptors from the transfers */ + curl_multi_fdset(mcurl, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* In a real-world program you OF COURSE check the return code of the + function calls. On success, the value of maxfd is guaranteed to be + greater or equal than -1. We call select(maxfd + 1, ...), specially in + case of (maxfd == -1), we call select(0, ...), which is basically equal + to sleep. */ + + rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + if(tutil_tvdiff(tutil_tvnow(), mp_start) > MULTI_PERFORM_HANG_TIMEOUT) { + fprintf(stderr, "ABORTING TEST, since it seems " + "that it would have run forever.\n"); + break; + } + + switch(rc) { + case -1: + /* select error */ + break; + case 0: /* timeout */ + default: /* action */ + curl_multi_perform(mcurl, &still_running); + break; + } + } + +test_cleanup: + + curl_slist_free_all(rcpt_list); + curl_multi_remove_handle(mcurl, curl); + curl_multi_cleanup(mcurl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1508.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1508.c new file mode 100644 index 0000000000000000000000000000000000000000..bece5fc927446d875ac8234e9b657f7aff83c68d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1508.c @@ -0,0 +1,51 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURLM *m = NULL; + + (void)URL; + + global_init(CURL_GLOBAL_ALL); + + multi_init(m); + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + curl_multi_cleanup(m); + curl_global_cleanup(); + + printf("We are done\n"); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1509.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1509.c new file mode 100644 index 0000000000000000000000000000000000000000..328ebd5d066f6f1aaba6ca78f45f45c47dc6a249 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1509.c @@ -0,0 +1,99 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +size_t WriteOutput(char *ptr, size_t size, size_t nmemb, void *stream); +size_t WriteHeader(char *ptr, size_t size, size_t nmemb, void *stream); + +static unsigned long realHeaderSize = 0; + +CURLcode test(char *URL) +{ + long headerSize; + CURLcode code; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_PROXY, libtest_arg2); /* set in first.c */ + + easy_setopt(curl, CURLOPT_WRITEFUNCTION, *WriteOutput); + easy_setopt(curl, CURLOPT_HEADERFUNCTION, *WriteHeader); + + easy_setopt(curl, CURLOPT_HEADER, 1L); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L); + + code = curl_easy_perform(curl); + if(CURLE_OK != code) { + fprintf(stderr, "%s:%d curl_easy_perform() failed, " + "with code %d (%s)\n", + __FILE__, __LINE__, code, curl_easy_strerror(code)); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + code = curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &headerSize); + if(CURLE_OK != code) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed, " + "with code %d (%s)\n", + __FILE__, __LINE__, code, curl_easy_strerror(code)); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + printf("header length is ........: %ld\n", headerSize); + printf("header length should be..: %lu\n", realHeaderSize); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} + +size_t WriteOutput(char *ptr, size_t size, size_t nmemb, void *stream) +{ + fwrite(ptr, size, nmemb, stream); + return nmemb * size; +} + +size_t WriteHeader(char *ptr, size_t size, size_t nmemb, void *stream) +{ + (void)ptr; + (void)stream; + + realHeaderSize += curlx_uztoul(size * nmemb); + + return nmemb * size; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1510.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1510.c new file mode 100644 index 0000000000000000000000000000000000000000..b3764b8b64ee962760cbd78c3df03a15980a93cd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1510.c @@ -0,0 +1,103 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_URLS 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + int i; + char target_url[256]; + char dnsentry[256]; + struct curl_slist *slist = NULL, *slist2; + char *port = libtest_arg3; + char *address = libtest_arg2; + + (void)URL; + + /* Create fake DNS entries for serverX.example.com for all handles */ + for(i = 0; i < NUM_URLS; i++) { + msnprintf(dnsentry, sizeof(dnsentry), "server%d.example.com:%s:%s", i + 1, + port, address); + printf("%s\n", dnsentry); + slist2 = curl_slist_append(slist, dnsentry); + if(!slist2) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + slist = slist2; + } + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + /* get an easy handle */ + easy_init(curl); + + /* go verbose */ + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl, CURLOPT_HEADER, 1L); + + easy_setopt(curl, CURLOPT_RESOLVE, slist); + + easy_setopt(curl, CURLOPT_MAXCONNECTS, 3L); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_URLS; i++) { + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "http://server%d.example.com:%s/path/1510%04i", + i + 1, port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl, CURLOPT_URL, target_url); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + curl_easy_cleanup(curl); + + curl_slist_free_all(slist); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1511.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1511.c new file mode 100644 index 0000000000000000000000000000000000000000..abc1356e5b54860c511f82079a0359c702745663 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1511.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + long unmet; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_HEADER, 1L); + easy_setopt(curl, CURLOPT_TIMECONDITION, (long)CURL_TIMECOND_IFMODSINCE); + + /* TIMEVALUE in the future */ + easy_setopt(curl, CURLOPT_TIMEVALUE, 1566210680L); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &unmet); + if(unmet != 1L) { + res = TEST_ERR_FAILURE; /* not correct */ + goto test_cleanup; + } + + /* TIMEVALUE in the past */ + easy_setopt(curl, CURLOPT_TIMEVALUE, 1L); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &unmet); + if(unmet) { + res = TEST_ERR_FAILURE; /* not correct */ + goto test_cleanup; + } + + res = TEST_ERR_SUCCESS; /* this is where we should be */ + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1512.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1512.c new file mode 100644 index 0000000000000000000000000000000000000000..a93bfc029a3018ece53a738f058deb12a5d1ed16 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1512.c @@ -0,0 +1,97 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ + +/* + * Use global DNS cache (while deprecated it should still work), populate it + * with CURLOPT_RESOLVE in the first request and then make sure a subsequent + * easy transfer finds and uses the populated stuff. + */ + +#include "test.h" + +#include "memdebug.h" + +#define NUM_HANDLES 2 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES] = {NULL, NULL}; + char *port = libtest_arg3; + char *address = libtest_arg2; + char dnsentry[256]; + struct curl_slist *slist = NULL; + int i; + char target_url[256]; + (void)URL; /* URL is setup in the code */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + msnprintf(dnsentry, sizeof(dnsentry), "server.example.curl:%s:%s", + port, address); + printf("%s\n", dnsentry); + slist = curl_slist_append(slist, dnsentry); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + /* get an easy handle */ + easy_init(curl[i]); + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "http://server.example.curl:%s/path/1512%04i", + port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl[i], CURLOPT_URL, target_url); + /* go verbose */ + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl[i], CURLOPT_HEADER, 1L); + + CURL_IGNORE_DEPRECATION( + easy_setopt(curl[i], CURLOPT_DNS_USE_GLOBAL_CACHE, 1L); + ) + } + + /* make the first one populate the GLOBAL cache */ + easy_setopt(curl[0], CURLOPT_RESOLVE, slist); + + /* run NUM_HANDLES transfers */ + for(i = 0; (i < NUM_HANDLES) && !res; i++) { + res = curl_easy_perform(curl[i]); + if(res) + goto test_cleanup; + } + +test_cleanup: + + curl_easy_cleanup(curl[0]); + curl_easy_cleanup(curl[1]); + curl_slist_free_all(slist); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1513.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1513.c new file mode 100644 index 0000000000000000000000000000000000000000..392e6c6121f5f76320ded4e8dfb87f0714e9f734 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1513.c @@ -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 + * + ***************************************************************************/ +/* + * Test case converted from bug report #1318 by Petr Novak. + * + * Before the fix, this test program returned 52 (CURLE_GOT_NOTHING) instead + * of 42 (CURLE_ABORTED_BY_CALLBACK). + */ + +#include "test.h" + +#include "memdebug.h" + +static int progressKiller(void *arg, + double dltotal, + double dlnow, + double ultotal, + double ulnow) +{ + (void)arg; + (void)dltotal; + (void)dlnow; + (void)ultotal; + (void)ulnow; + printf("PROGRESSFUNCTION called\n"); + return 1; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_TIMEOUT, (long)7); + easy_setopt(curl, CURLOPT_NOSIGNAL, (long)1); + CURL_IGNORE_DEPRECATION( + easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progressKiller); + easy_setopt(curl, CURLOPT_PROGRESSDATA, NULL); + ) + easy_setopt(curl, CURLOPT_NOPROGRESS, (long)0); + + res = curl_easy_perform(curl); + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1514.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1514.c new file mode 100644 index 0000000000000000000000000000000000000000..6b4e18bac0f7a2aa63539e285623532ec0e0627b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1514.c @@ -0,0 +1,86 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + * Make sure libcurl does not send a `Content-Length: -1` header when HTTP POST + * size is unknown. + */ + +#include "test.h" + +#include "memdebug.h" + +static char testdata[]="dummy"; + +struct WriteThis { + char *readptr; + size_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + + if(size*nmemb < 1) + return 0; + + if(pooh->sizeleft) { + *ptr = pooh->readptr[0]; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + pooh->sizeleft--; /* less data left */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode result = CURLE_OK; + CURLcode res = CURLE_OK; + struct WriteThis pooh = { testdata, sizeof(testdata)-1 }; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_POST, 1L); + /* Purposely omit to set CURLOPT_POSTFIELDSIZE */ + easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + easy_setopt(curl, CURLOPT_READDATA, &pooh); +#ifdef LIB1539 + /* speak HTTP 1.0 - no chunked! */ + easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); +#endif + + result = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return result; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1515.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1515.c new file mode 100644 index 0000000000000000000000000000000000000000..f772d9e38b2f9ae9cab3c59a91e0432ebf885c49 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1515.c @@ -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 + * + ***************************************************************************/ + +/* + * Check for bugs #1303 and #1327: libcurl should never remove DNS entries + * created via CURLOPT_RESOLVE, neither after DNS_CACHE_TIMEOUT elapses + * (test1515) nor a dead connection is detected (test1616). + */ + +#include "test.h" +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define DNS_TIMEOUT 1 + +static CURLcode do_one_request(CURLM *m, char *URL, char *resolve) +{ + CURL *curls; + struct curl_slist *resolve_list = NULL; + int still_running; + CURLcode res = CURLE_OK; + CURLMsg *msg; + int msgs_left; + + resolve_list = curl_slist_append(resolve_list, resolve); + + easy_init(curls); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_RESOLVE, resolve_list); + easy_setopt(curls, CURLOPT_DNS_CACHE_TIMEOUT, DNS_TIMEOUT); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + easy_setopt(curls, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(curls, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + + multi_add_handle(m, curls); + multi_perform(m, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + fd_set fdread, fdwrite, fdexcep; + int maxfd = -99; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + multi_perform(m, &still_running); + + abort_on_test_timeout(); + } + + do { + msg = curl_multi_info_read(m, &msgs_left); + if(msg && msg->msg == CURLMSG_DONE && msg->easy_handle == curls) { + res = msg->data.result; + break; + } + } while(msg); + +test_cleanup: + + curl_multi_remove_handle(m, curls); + curl_easy_cleanup(curls); + curl_slist_free_all(resolve_list); + + return res; +} + +CURLcode test(char *URL) +{ + CURLM *multi = NULL; + CURLcode res = CURLE_OK; + char *address = libtest_arg2; + char *port = libtest_arg3; + char *path = URL; + char dns_entry[256]; + int i; + int count = 2; + + msnprintf(dns_entry, sizeof(dns_entry), "testserver.example.com:%s:%s", + port, address); + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + curl_global_trace("all"); + multi_init(multi); + + for(i = 1; i <= count; i++) { + char target_url[256]; + msnprintf(target_url, sizeof(target_url), + "http://testserver.example.com:%s/%s%04d", port, path, i); + + /* second request must succeed like the first one */ + res = do_one_request(multi, target_url, dns_entry); + if(res != CURLE_OK) { + fprintf(stderr, "request %s failed with %d\n", target_url, res); + goto test_cleanup; + } + + if(i < count) + sleep(DNS_TIMEOUT + 1); + } + +test_cleanup: + + curl_multi_cleanup(multi); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1517.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1517.c new file mode 100644 index 0000000000000000000000000000000000000000..3957eb19904ddc446bcd50a5aa0537c841518411 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1517.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 "test.h" + +#include "memdebug.h" + +static char testdata[]="this is what we post to the silly web server\n"; + +struct WriteThis { + char *readptr; + size_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + size_t tocopy = size * nmemb; + + /* Wait one second before return POST data * + * so libcurl will wait before sending request body */ + wait_ms(1000); + + if(tocopy < 1 || !pooh->sizeleft) + return 0; + + if(pooh->sizeleft < tocopy) + tocopy = pooh->sizeleft; + + memcpy(ptr, pooh->readptr, tocopy);/* copy requested data */ + pooh->readptr += tocopy; /* advance pointer */ + pooh->sizeleft -= tocopy; /* less data left */ + return tocopy; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + struct WriteThis pooh; + + if(!strcmp(URL, "check")) { +#if (defined(_WIN32) || defined(__CYGWIN__)) + printf("Windows TCP does not deliver response data but reports " + "CONNABORTED\n"); + return (CURLcode)1; /* skip since it fails on Windows without workaround */ +#else + return CURLE_OK; /* sure, run this! */ +#endif + } + + pooh.readptr = testdata; + pooh.sizeleft = strlen(testdata); + + if(curl_global_init(CURL_GLOBAL_ALL)) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Set the expected POST size */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)pooh.sizeleft); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* pointer to pass to our read function */ + test_setopt(curl, CURLOPT_READDATA, &pooh); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* detect HTTP error codes >= 400 */ + /* test_setopt(curl, CURLOPT_FAILONERROR, 1L); */ + + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1518.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1518.c new file mode 100644 index 0000000000000000000000000000000000000000..560d79ce23f38025a28620888299f8e78a7fee37 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1518.c @@ -0,0 +1,106 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test inspired by github issue 3340 */ + +static size_t writecb(char *buffer, size_t size, size_t nitems, + void *outstream) +{ + (void)buffer; + (void)size; + (void)nitems; + (void)outstream; + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + long curlResponseCode; + long curlRedirectCount; + char *effectiveUrl = NULL; + char *redirectUrl = NULL; +#ifdef LIB1543 + CURLU *urlu = NULL; +#endif + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } +#ifdef LIB1543 + /* set CURLOPT_URLU */ + { + CURLUcode rc = CURLUE_OK; + urlu = curl_url(); + if(urlu) + rc = curl_url_set(urlu, CURLUPART_URL, URL, CURLU_ALLOW_SPACE); + if(!urlu || rc) { + goto test_cleanup; + } + test_setopt(curl, CURLOPT_CURLU, urlu); + } + test_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); +#else + test_setopt(curl, CURLOPT_URL, URL); + /* just to make it explicit and visible in this test: */ + test_setopt(curl, CURLOPT_FOLLOWLOCATION, 0L); +#endif + + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &curlResponseCode); + curl_easy_getinfo(curl, CURLINFO_REDIRECT_COUNT, &curlRedirectCount); + curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveUrl); + curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &redirectUrl); + test_setopt(curl, CURLOPT_WRITEFUNCTION, writecb); + + printf("res %d\n" + "status %ld\n" + "redirects %ld\n" + "effectiveurl %s\n" + "redirecturl %s\n", + res, + curlResponseCode, + curlRedirectCount, + effectiveUrl, + redirectUrl ? redirectUrl : "blank"); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); +#ifdef LIB1543 + curl_url_cleanup(urlu); +#endif + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1520.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1520.c new file mode 100644 index 0000000000000000000000000000000000000000..8e5f6a9be04f48b096de8be5ed57496aa2ff0fd8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1520.c @@ -0,0 +1,115 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "test.h" + +#include "memdebug.h" + +/* + * This is the list of basic details you need to tweak to get things right. + */ +#define TO "" +#define FROM "" + +static const char *payload_text[] = { + "From: different\r\n", + "To: another\r\n", + "\r\n", + "\r\n", + ".\r\n", + ".\r\n", + "\r\n", + ".\r\n", + "\r\n", + "body", + NULL +}; + +struct upload_status { + int lines_read; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = payload_text[upload_ctx->lines_read]; + + if(data) { + size_t len = strlen(data); + memcpy(ptr, data, len); + upload_ctx->lines_read++; + + return len; + } + + return 0; +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + struct curl_slist *rcpt_list = NULL; + struct upload_status upload_ctx = {0}; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + rcpt_list = curl_slist_append(rcpt_list, TO); + /* more addresses can be added here + rcpt_list = curl_slist_append(rcpt_list, ""); + */ + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_READDATA, &upload_ctx); + test_setopt(curl, CURLOPT_MAIL_FROM, FROM); + test_setopt(curl, CURLOPT_MAIL_RCPT, rcpt_list); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(rcpt_list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1522.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1522.c new file mode 100644 index 0000000000000000000000000000000000000000..3d171009b75589c29db1e21d7cbcceb63a92506d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1522.c @@ -0,0 +1,101 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +/* test case and code based on https://github.com/curl/curl/issues/2847 */ + +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +static char g_Data[40 * 1024]; /* POST 40KB */ + +static int sockopt_callback(void *clientp, curl_socket_t curlfd, + curlsocktype purpose) +{ +#if defined(SOL_SOCKET) && defined(SO_SNDBUF) + int sndbufsize = 4 * 1024; /* 4KB send buffer */ + (void) clientp; + (void) purpose; + setsockopt(curlfd, SOL_SOCKET, SO_SNDBUF, + (char *)&sndbufsize, sizeof(sndbufsize)); +#else + (void)clientp; + (void)curlfd; + (void)purpose; +#endif + return CURL_SOCKOPT_OK; +} + +CURLcode test(char *URL) +{ + CURLcode code = TEST_ERR_MAJOR_BAD; + CURLcode res; + struct curl_slist *pHeaderList = NULL; + CURL *curl = curl_easy_init(); + memset(g_Data, 'A', sizeof(g_Data)); /* send As! */ + + curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_callback); + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, g_Data); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)sizeof(g_Data)); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + test_setopt(curl, CURLOPT_DEBUGDATA, &libtest_debug_config); + test_setopt(curl, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Remove "Expect: 100-continue" */ + pHeaderList = curl_slist_append(pHeaderList, "Expect:"); + + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, pHeaderList); + + code = curl_easy_perform(curl); + + if(code == CURLE_OK) { + curl_off_t uploadSize; + curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD_T, &uploadSize); + + printf("uploadSize = %ld\n", (long)uploadSize); + + if((size_t) uploadSize == sizeof(g_Data)) { + printf("!!!!!!!!!! PASS\n"); + } + else { + printf("sent %d, libcurl says %d\n", + (int)sizeof(g_Data), (int)uploadSize); + } + } + else { + printf("curl_easy_perform() failed. e = %d\n", code); + } +test_cleanup: + curl_slist_free_all(pHeaderList); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return code; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1523.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1523.c new file mode 100644 index 0000000000000000000000000000000000000000..529bbf83dc6374e2f2f2768755ad541e9de0058a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1523.c @@ -0,0 +1,85 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +/* test case and code based on https://github.com/curl/curl/issues/3927 */ + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +static int dload_progress_cb(void *a, curl_off_t b, curl_off_t c, + curl_off_t d, curl_off_t e) +{ + (void)a; + (void)b; + (void)c; + (void)d; + (void)e; + return 0; +} + +static size_t write_cb(char *d, size_t n, size_t l, void *p) +{ + /* take care of the data here, ignored in this example */ + (void)d; + (void)p; + return n*l; +} + +static CURLcode run(CURL *hnd, long limit, long time) +{ + curl_easy_setopt(hnd, CURLOPT_LOW_SPEED_LIMIT, limit); + curl_easy_setopt(hnd, CURLOPT_LOW_SPEED_TIME, time); + return curl_easy_perform(hnd); +} + +CURLcode test(char *URL) +{ + CURLcode ret; + CURL *hnd; + char buffer[CURL_ERROR_SIZE]; + curl_global_init(CURL_GLOBAL_ALL); + hnd = curl_easy_init(); + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, write_cb); + curl_easy_setopt(hnd, CURLOPT_ERRORBUFFER, buffer); + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(hnd, CURLOPT_XFERINFOFUNCTION, dload_progress_cb); + + ret = run(hnd, 1, 2); + if(ret) + fprintf(stderr, "error %d: %s\n", ret, buffer); + + ret = run(hnd, 12000, 1); + if(ret != CURLE_OPERATION_TIMEDOUT) + fprintf(stderr, "error %d: %s\n", ret, buffer); + else + ret = CURLE_OK; + + curl_easy_cleanup(hnd); + curl_global_cleanup(); + + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1525.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1525.c new file mode 100644 index 0000000000000000000000000000000000000000..c8a3063f362f7493e9dea1378e9b16b0a310dde3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1525.c @@ -0,0 +1,100 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Vijay Panghal, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 unit test PUT http data over proxy. Proxy header will be different + * from server http header + */ + +#include "test.h" + +#include "memdebug.h" + +static char testdata[] = "Hello Cloud!\n"; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t amount = nmemb * size; /* Total bytes curl wants */ + if(amount < strlen(testdata)) { + return strlen(testdata); + } + (void)stream; + memcpy(ptr, testdata, strlen(testdata)); + return strlen(testdata); +} + + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http and proxy header list */ + struct curl_slist *hhl = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "User-Agent: Http Agent"); + + if(!hhl) { + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_PROXYHEADER, hhl); + test_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_UNIFIED); + test_setopt(curl, CURLOPT_POST, 0L); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L); + test_setopt(curl, CURLOPT_INFILESIZE, (long)strlen(testdata)); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(hhl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1526.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1526.c new file mode 100644 index 0000000000000000000000000000000000000000..8093079f553ac898b39f16c3b7b1d6ddb2ede861 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1526.c @@ -0,0 +1,105 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Vijay Panghal, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 unit test PUT http data over proxy. Proxy header will be different + * from server http header + */ + +#include "test.h" + +#include "memdebug.h" + +static char testdata[] = "Hello Cloud!\n"; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t amount = nmemb * size; /* Total bytes curl wants */ + if(amount < strlen(testdata)) { + return strlen(testdata); + } + (void)stream; + memcpy(ptr, testdata, strlen(testdata)); + return strlen(testdata); +} + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http and proxy header list */ + struct curl_slist *hhl = NULL, *phl = NULL, *tmp = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "User-Agent: Http Agent"); + phl = curl_slist_append(phl, "User-Agent: Proxy Agent"); + if(!hhl || !phl) { + goto test_cleanup; + } + tmp = curl_slist_append(phl, "Expect:"); + if(!tmp) { + goto test_cleanup; + } + phl = tmp; + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_PROXYHEADER, phl); + test_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE); + test_setopt(curl, CURLOPT_POST, 0L); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L); + test_setopt(curl, CURLOPT_INFILESIZE, (long)strlen(testdata)); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(hhl); + + curl_slist_free_all(phl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1527.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1527.c new file mode 100644 index 0000000000000000000000000000000000000000..26581b2a3e364240499c3695190332bc2bcf1fd5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1527.c @@ -0,0 +1,102 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Vijay Panghal, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 unit test PUT http data over proxy. Same http header will be generated + * for server and proxy + */ + +#include "test.h" + +#include "memdebug.h" + +static char testdata[] = "Hello Cloud!\n"; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t amount = nmemb * size; /* Total bytes curl wants */ + if(amount < strlen(testdata)) { + return strlen(testdata); + } + (void)stream; + memcpy(ptr, testdata, strlen(testdata)); + return strlen(testdata); +} + + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http header list */ + struct curl_slist *hhl = NULL, *tmp = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "User-Agent: Http Agent"); + if(!hhl) { + goto test_cleanup; + } + tmp = curl_slist_append(hhl, "Expect: 100-continue"); + if(!tmp) { + goto test_cleanup; + } + hhl = tmp; + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_POST, 0L); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1L); + test_setopt(curl, CURLOPT_INFILESIZE, (long)strlen(testdata)); + test_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_UNIFIED); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(hhl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1528.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1528.c new file mode 100644 index 0000000000000000000000000000000000000000..396910a5e923a4d0c5b128262338b2f1e953e2ef --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1528.c @@ -0,0 +1,75 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http header list */ + struct curl_slist *hhl = NULL; + struct curl_slist *phl = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "User-Agent: Http Agent"); + phl = curl_slist_append(phl, "Proxy-User-Agent: Http Agent2"); + + if(!hhl) { + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_PROXYHEADER, phl); + test_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + test_setopt(curl, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_slist_free_all(hhl); + curl_slist_free_all(phl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1529.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1529.c new file mode 100644 index 0000000000000000000000000000000000000000..8a1f52cd36347e209500551959c3d6e8a337fe70 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1529.c @@ -0,0 +1,63 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + char bURL[512]; + msnprintf(bURL, sizeof(bURL), + "%s HTTP/1.1\r\nGET http://1529.com/1529", URL); + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, bURL); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + test_setopt(curl, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1530.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1530.c new file mode 100644 index 0000000000000000000000000000000000000000..6b86cdb6fd646cd7609c81b694a48c4c9839f99d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1530.c @@ -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 + * + ***************************************************************************/ + +#include "test.h" + +#include "memdebug.h" + +static curl_socket_t opensocket(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address) +{ + (void)purpose; + (void)address; + (void)clientp; + fprintf(stderr, "opensocket() returns CURL_SOCKET_BAD\n"); + return CURL_SOCKET_BAD; +} + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + (void)URL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, "http://99.99.99.99:9999"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1531.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1531.c new file mode 100644 index 0000000000000000000000000000000000000000..f4814f1222f23b5ec8badd43b832ecdc8be0e3f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1531.c @@ -0,0 +1,160 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "timediff.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +static char const testData[] = ".abc\0xyz"; +static off_t const testDataSize = sizeof(testData) - 1; + +CURLcode test(char *URL) +{ + CURL *easy; + CURLM *multi_handle; + int still_running; /* keep number of running handles */ + CURLMsg *msg; /* for picking up messages with the transfer status */ + int msgs_left; /* how many messages are left */ + CURLcode res = CURLE_OK; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + /* Allocate one CURL handle per transfer */ + easy = curl_easy_init(); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfer */ + curl_multi_add_handle(multi_handle, easy); + + /* set the options (I left out a few, you'll get the point anyway) */ + curl_easy_setopt(easy, CURLOPT_URL, URL); + curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, + (curl_off_t)testDataSize); + curl_easy_setopt(easy, CURLOPT_POSTFIELDS, testData); + + /* we start some action by calling perform right away */ + curl_multi_perform(multi_handle, &still_running); + + abort_on_test_timeout(); + + do { + struct timeval timeout; + int rc; /* select() return code */ + CURLMcode mc; /* curl_multi_fdset() return code */ + + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -1; + + long curl_timeo = -1; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + /* set a suitable timeout to play around with */ + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + curl_multi_timeout(multi_handle, &curl_timeo); + if(curl_timeo >= 0) { + curlx_mstotv(&timeout, curl_timeo); + if(timeout.tv_sec > 1) { + timeout.tv_sec = 1; + timeout.tv_usec = 0; + } + } + + /* get file descriptors from the transfers */ + mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc); + break; + } + + /* On success the value of maxfd is guaranteed to be >= -1. We call + select(maxfd + 1, ...); specially in case of (maxfd == -1) there are + no fds ready yet so we call select(0, ...) --or Sleep() on Windows-- + to sleep 100ms, which is the minimum suggested value in the + curl_multi_fdset() doc. */ + + if(maxfd == -1) { +#if defined(_WIN32) + Sleep(100); + rc = 0; +#else + /* Portable sleep for platforms other than Windows. */ + struct timeval wait = { 0, 100 * 1000 }; /* 100ms */ + rc = select(0, NULL, NULL, NULL, &wait); +#endif + } + else { + /* Note that on some platforms 'timeout' may be modified by select(). + If you need access to the original value save a copy beforehand. */ + rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + } + + switch(rc) { + case -1: + /* select error */ + break; + case 0: /* timeout */ + default: /* action */ + curl_multi_perform(multi_handle, &still_running); + break; + } + + abort_on_test_timeout(); + } while(still_running); + + /* See how the transfers went */ + do { + msg = curl_multi_info_read(multi_handle, &msgs_left); + if(msg && msg->msg == CURLMSG_DONE) { + printf("HTTP transfer completed with status %d\n", msg->data.result); + break; + } + + abort_on_test_timeout(); + } while(msg); + +test_cleanup: + curl_multi_cleanup(multi_handle); + + /* Free the CURL handles */ + curl_easy_cleanup(easy); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1532.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1532.c new file mode 100644 index 0000000000000000000000000000000000000000..22b1aadaa3ae403f33e03ccde778f069e9cb540e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1532.c @@ -0,0 +1,82 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test CURLINFO_RESPONSE_CODE */ + +CURLcode test(char *URL) +{ + CURL *curl; + long httpcode; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + + res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(httpcode != 200) { + fprintf(stderr, "%s:%d unexpected response code %ld\n", + __FILE__, __LINE__, httpcode); + res = CURLE_HTTP_RETURNED_ERROR; + goto test_cleanup; + } + + /* Test for a regression of github bug 1017 (response code does not reset) */ + curl_easy_reset(curl); + + res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(httpcode) { + fprintf(stderr, "%s:%d curl_easy_reset failed to zero the response code\n" + "possible regression of github bug 1017\n", __FILE__, __LINE__); + res = CURLE_HTTP_RETURNED_ERROR; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1533.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1533.c new file mode 100644 index 0000000000000000000000000000000000000000..e1dd16c9ceb67743a531ccc6290e72dee9b4a6e4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1533.c @@ -0,0 +1,206 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 test sends data with CURLOPT_KEEP_SENDING_ON_ERROR. + * The server responds with an early error response. + * The test is successful if the connection can be reused for the next request, + * because this implies that the data has been sent completely to the server. + */ + +#include "test.h" + +#include "memdebug.h" + +struct cb_data { + CURL *easy_handle; + int response_received; + int paused; + size_t remaining_bytes; +}; + + +static void reset_data(struct cb_data *data, CURL *curl) +{ + data->easy_handle = curl; + data->response_received = 0; + data->paused = 0; + data->remaining_bytes = 3; +} + + +static size_t read_callback(char *ptr, size_t size, size_t nitems, + void *userdata) +{ + struct cb_data *data = (struct cb_data *)userdata; + + /* wait until the server has sent all response headers */ + if(data->response_received) { + size_t totalsize = nitems * size; + + size_t bytes_to_send = data->remaining_bytes; + if(bytes_to_send > totalsize) { + bytes_to_send = totalsize; + } + + memset(ptr, 'a', bytes_to_send); + data->remaining_bytes -= bytes_to_send; + + return bytes_to_send; + } + else { + data->paused = 1; + return CURL_READFUNC_PAUSE; + } +} + + +static size_t write_callback(char *ptr, size_t size, size_t nmemb, + void *userdata) +{ + struct cb_data *data = (struct cb_data *)userdata; + size_t totalsize = nmemb * size; + + /* unused parameter */ + (void)ptr; + + /* all response headers have been received */ + data->response_received = 1; + + if(data->paused) { + /* continue to send request body data */ + data->paused = 0; + curl_easy_pause(data->easy_handle, CURLPAUSE_CONT); + } + + return totalsize; +} + + +static int perform_and_check_connections(CURL *curl, const char *description, + long expected_connections) +{ + CURLcode res; + long connections = 0; + + res = curl_easy_perform(curl); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed with %d\n", res); + return TEST_ERR_MAJOR_BAD; + } + + res = curl_easy_getinfo(curl, CURLINFO_NUM_CONNECTS, &connections); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_getinfo() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + fprintf(stderr, "%s: expected: %ld connections; actual: %ld connections\n", + description, expected_connections, connections); + + if(connections != expected_connections) { + return TEST_ERR_FAILURE; + } + + return TEST_ERR_SUCCESS; +} + + +CURLcode test(char *URL) +{ + struct cb_data data; + CURL *curl = NULL; + CURLcode res = TEST_ERR_FAILURE; + int result; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + reset_data(&data, curl); + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_POST, 1L); + test_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, + (curl_off_t)data.remaining_bytes); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_READDATA, &data); + test_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); + test_setopt(curl, CURLOPT_WRITEDATA, &data); + + result = perform_and_check_connections(curl, + "First request without CURLOPT_KEEP_SENDING_ON_ERROR", 1); + if(result != TEST_ERR_SUCCESS) { + res = (CURLcode) result; + goto test_cleanup; + } + + reset_data(&data, curl); + + result = perform_and_check_connections(curl, + "Second request without CURLOPT_KEEP_SENDING_ON_ERROR", 1); + if(result != TEST_ERR_SUCCESS) { + res = (CURLcode) result; + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_KEEP_SENDING_ON_ERROR, 1L); + + reset_data(&data, curl); + + result = perform_and_check_connections(curl, + "First request with CURLOPT_KEEP_SENDING_ON_ERROR", 1); + if(result != TEST_ERR_SUCCESS) { + res = (CURLcode) result; + goto test_cleanup; + } + + reset_data(&data, curl); + + result = perform_and_check_connections(curl, + "Second request with CURLOPT_KEEP_SENDING_ON_ERROR", 0); + if(result != TEST_ERR_SUCCESS) { + res = (CURLcode) result; + goto test_cleanup; + } + + res = TEST_ERR_SUCCESS; + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1534.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1534.c new file mode 100644 index 0000000000000000000000000000000000000000..a9a7d73d857e7bb008b732d8d69f6e4d2db27791 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1534.c @@ -0,0 +1,131 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test CURLINFO_FILETIME */ + +CURLcode test(char *URL) +{ + CURL *curl, *dupe = NULL; + long filetime; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + /* Test that a filetime is properly initialized on curl_easy_init. + */ + + res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(filetime != -1) { + fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n", + __FILE__, __LINE__, filetime); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_FILETIME, 1L); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + + /* Test that a filetime is properly set after receiving an HTTP resource. + */ + + res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(filetime != 30) { + fprintf(stderr, "%s:%d filetime of http resource is incorrect; " + "expected 30 but is %ld\n", + __FILE__, __LINE__, filetime); + res = CURLE_HTTP_RETURNED_ERROR; + goto test_cleanup; + } + + /* Test that a filetime is properly initialized on curl_easy_duphandle. + */ + + dupe = curl_easy_duphandle(curl); + if(!dupe) { + fprintf(stderr, "%s:%d curl_easy_duphandle() failed\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + res = curl_easy_getinfo(dupe, CURLINFO_FILETIME, &filetime); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(filetime != -1) { + fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n", + __FILE__, __LINE__, filetime); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + + /* Test that a filetime is properly initialized on curl_easy_reset. + */ + + curl_easy_reset(curl); + + res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(filetime != -1) { + fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n", + __FILE__, __LINE__, filetime); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_easy_cleanup(dupe); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1535.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1535.c new file mode 100644 index 0000000000000000000000000000000000000000..80589d8938fc810d2c79e0483806249b8c56fd6f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1535.c @@ -0,0 +1,138 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test CURLINFO_PROTOCOL */ + +CURLcode test(char *URL) +{ + CURL *curl, *dupe = NULL; + long protocol; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + /* Test that protocol is properly initialized on curl_easy_init. + */ + + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_PROTOCOL, &protocol); + ) + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(protocol) { + fprintf(stderr, "%s:%d protocol init failed; expected 0 but is %ld\n", + __FILE__, __LINE__, protocol); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + easy_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + + /* Test that a protocol is properly set after receiving an HTTP resource. + */ + + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_PROTOCOL, &protocol); + ) + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(protocol != CURLPROTO_HTTP) { + fprintf(stderr, "%s:%d protocol of http resource is incorrect; " + "expected %d but is %ld\n", + __FILE__, __LINE__, CURLPROTO_HTTP, protocol); + res = CURLE_HTTP_RETURNED_ERROR; + goto test_cleanup; + } + + /* Test that a protocol is properly initialized on curl_easy_duphandle. + */ + + dupe = curl_easy_duphandle(curl); + if(!dupe) { + fprintf(stderr, "%s:%d curl_easy_duphandle() failed\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(dupe, CURLINFO_PROTOCOL, &protocol); + ) + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(protocol) { + fprintf(stderr, "%s:%d protocol init failed; expected 0 but is %ld\n", + __FILE__, __LINE__, protocol); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + + /* Test that a protocol is properly initialized on curl_easy_reset. + */ + + curl_easy_reset(curl); + + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_PROTOCOL, &protocol); + ) + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(protocol) { + fprintf(stderr, "%s:%d protocol init failed; expected 0 but is %ld\n", + __FILE__, __LINE__, protocol); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_easy_cleanup(dupe); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1536.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1536.c new file mode 100644 index 0000000000000000000000000000000000000000..7bc9e718b6fed9703538e1322a73aa292664ec11 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1536.c @@ -0,0 +1,131 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test CURLINFO_SCHEME */ + +CURLcode test(char *URL) +{ + CURL *curl, *dupe = NULL; + char *scheme; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + /* Test that scheme is properly initialized on curl_easy_init. + */ + + res = curl_easy_getinfo(curl, CURLINFO_SCHEME, &scheme); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(scheme) { + fprintf(stderr, "%s:%d scheme init failed; expected NULL\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + easy_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + + /* Test that a scheme is properly set after receiving an HTTP resource. + */ + + res = curl_easy_getinfo(curl, CURLINFO_SCHEME, &scheme); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(!scheme || memcmp(scheme, "http", 5) != 0) { + fprintf(stderr, "%s:%d scheme of http resource is incorrect; " + "expected 'http' but is %s\n", + __FILE__, __LINE__, + (scheme == NULL ? "NULL" : "invalid")); + res = CURLE_HTTP_RETURNED_ERROR; + goto test_cleanup; + } + + /* Test that a scheme is properly initialized on curl_easy_duphandle. + */ + + dupe = curl_easy_duphandle(curl); + if(!dupe) { + fprintf(stderr, "%s:%d curl_easy_duphandle() failed\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + res = curl_easy_getinfo(dupe, CURLINFO_SCHEME, &scheme); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(scheme) { + fprintf(stderr, "%s:%d scheme init failed; expected NULL\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + + + /* Test that a scheme is properly initialized on curl_easy_reset. + */ + + curl_easy_reset(curl); + + res = curl_easy_getinfo(curl, CURLINFO_SCHEME, &scheme); + if(res) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + if(scheme) { + fprintf(stderr, "%s:%d scheme init failed; expected NULL\n", + __FILE__, __LINE__); + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_easy_cleanup(dupe); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1537.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1537.c new file mode 100644 index 0000000000000000000000000000000000000000..9c991e830c87118d9c44293bb392d06a7e2a08a8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1537.c @@ -0,0 +1,91 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + const unsigned char a[] = {0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe6, 0xf7}; + CURLcode res = CURLE_OK; + char *ptr = NULL; + int asize; + int outlen = 0; + char *raw; + + (void)URL; /* we don't use this */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + asize = (int)sizeof(a); + ptr = curl_easy_escape(NULL, (char *)a, asize); + printf("%s\n", ptr); + curl_free(ptr); + + /* deprecated API */ + ptr = curl_escape((char *)a, asize); + if(!ptr) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + printf("%s\n", ptr); + + raw = curl_easy_unescape(NULL, ptr, (int)strlen(ptr), &outlen); + printf("outlen == %d\n", outlen); + printf("unescape == original? %s\n", + memcmp(raw, a, outlen) ? "no" : "YES"); + curl_free(raw); + + /* deprecated API */ + raw = curl_unescape(ptr, (int)strlen(ptr)); + if(!raw) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + outlen = (int)strlen(raw); + printf("[old] outlen == %d\n", outlen); + printf("[old] unescape == original? %s\n", + memcmp(raw, a, outlen) ? "no" : "YES"); + curl_free(raw); + curl_free(ptr); + + /* weird input length */ + ptr = curl_easy_escape(NULL, (char *)a, -1); + printf("escape -1 length: %s\n", ptr); + + /* weird input length */ + outlen = 2017; /* just a value */ + ptr = curl_easy_unescape(NULL, (char *)"moahahaha", -1, &outlen); + printf("unescape -1 length: %s %d\n", ptr, outlen); + +test_cleanup: + curl_free(ptr); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1538.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1538.c new file mode 100644 index 0000000000000000000000000000000000000000..ebc68573f1f066a03b3cfcc0ae08dda49204e299 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1538.c @@ -0,0 +1,60 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURLcode easyret; + CURLMcode multiret; + CURLSHcode shareret; + CURLUcode urlret; + (void)URL; + + curl_easy_strerror((CURLcode)INT_MAX); + curl_multi_strerror((CURLMcode)INT_MAX); + curl_share_strerror((CURLSHcode)INT_MAX); + curl_url_strerror((CURLUcode)INT_MAX); + curl_easy_strerror((CURLcode)-INT_MAX); + curl_multi_strerror((CURLMcode)-INT_MAX); + curl_share_strerror((CURLSHcode)-INT_MAX); + curl_url_strerror((CURLUcode)-INT_MAX); + for(easyret = CURLE_OK; easyret <= CURL_LAST; easyret++) { + printf("e%d: %s\n", (int)easyret, curl_easy_strerror(easyret)); + } + for(multiret = CURLM_CALL_MULTI_PERFORM; multiret <= CURLM_LAST; + multiret++) { + printf("m%d: %s\n", (int)multiret, curl_multi_strerror(multiret)); + } + for(shareret = CURLSHE_OK; shareret <= CURLSHE_LAST; shareret++) { + printf("s%d: %s\n", (int)shareret, curl_share_strerror(shareret)); + } + for(urlret = CURLUE_OK; urlret <= CURLUE_LAST; urlret++) { + printf("u%d: %s\n", (int)urlret, curl_url_strerror(urlret)); + } + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1540.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1540.c new file mode 100644 index 0000000000000000000000000000000000000000..210879447ec508b0039abc621c7c9320f81df0ff --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1540.c @@ -0,0 +1,125 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +struct transfer_status { + CURL *easy; + int halted; + int counter; /* count write callback invokes */ + int please; /* number of times xferinfo is called while halted */ +}; + +static int please_continue(void *userp, + curl_off_t dltotal, + curl_off_t dlnow, + curl_off_t ultotal, + curl_off_t ulnow) +{ + struct transfer_status *st = (struct transfer_status *)userp; + (void)dltotal; + (void)dlnow; + (void)ultotal; + (void)ulnow; + if(st->halted) { + st->please++; + if(st->please == 2) { + /* waited enough, unpause! */ + curl_easy_pause(st->easy, CURLPAUSE_CONT); + } + } + fprintf(stderr, "xferinfo: paused %d\n", st->halted); + return 0; /* go on */ +} + +static size_t header_callback(char *ptr, size_t size, size_t nmemb, + void *userp) +{ + size_t len = size * nmemb; + (void)userp; + (void)fwrite(ptr, size, nmemb, stdout); + return len; +} + +static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct transfer_status *st = (struct transfer_status *)userp; + size_t len = size * nmemb; + st->counter++; + if(st->counter > 1) { + /* the first call puts us on pause, so subsequent calls are after + unpause */ + fwrite(ptr, size, nmemb, stdout); + return len; + } + if(len) + printf("Got bytes but pausing!\n"); + st->halted = 1; + return CURL_WRITEFUNC_PAUSE; +} + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLcode res = CURLE_OK; + struct transfer_status st; + + start_test_timing(); + + memset(&st, 0, sizeof(st)); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curls); + st.easy = curls; /* to allow callbacks access */ + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_WRITEFUNCTION, write_callback); + easy_setopt(curls, CURLOPT_WRITEDATA, &st); + easy_setopt(curls, CURLOPT_HEADERFUNCTION, header_callback); + easy_setopt(curls, CURLOPT_HEADERDATA, &st); + + easy_setopt(curls, CURLOPT_XFERINFOFUNCTION, please_continue); + easy_setopt(curls, CURLOPT_XFERINFODATA, &st); + easy_setopt(curls, CURLOPT_NOPROGRESS, 0L); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + test_setopt(curls, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(curls, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curls); + +test_cleanup: + + curl_easy_cleanup(curls); + curl_global_cleanup(); + + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1541.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1541.c new file mode 100644 index 0000000000000000000000000000000000000000..a60d61a7eca4ae3329e6fca729da280207004870 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1541.c @@ -0,0 +1,153 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +struct transfer_status { + CURL *easy; + int hd_count; + int bd_count; + CURLcode result; +}; + +#define KN(a) a, #a + +static int geterr(const char *name, CURLcode val, int lineno) +{ + printf("CURLINFO_%s returned %d, \"%s\" on line %d\n", + name, val, curl_easy_strerror(val), lineno); + return (int)val; +} + +static void report_time(const char *key, const char *where, curl_off_t time, + bool ok) +{ + if(ok) + printf("%s on %s is OK\n", key, where); + else + printf("%s on %s is WRONG: %" CURL_FORMAT_CURL_OFF_T "\n", + key, where, time); +} + +static void check_time(CURL *easy, int key, const char *name, + const char *where) +{ + curl_off_t tval; + CURLcode res = curl_easy_getinfo(easy, (CURLINFO)key, &tval); + if(res) { + geterr(name, res, __LINE__); + } + else + report_time(name, where, tval, tval > 0); +} + +static void check_time0(CURL *easy, int key, const char *name, + const char *where) +{ + curl_off_t tval; + CURLcode res = curl_easy_getinfo(easy, (CURLINFO)key, &tval); + if(res) { + geterr(name, res, __LINE__); + } + else + report_time(name, where, tval, !tval); +} + +static size_t header_callback(char *ptr, size_t size, size_t nmemb, + void *userp) +{ + struct transfer_status *st = (struct transfer_status *)userp; + size_t len = size * nmemb; + + (void)ptr; + if(!st->hd_count++) { + /* first header, check some CURLINFO value to be reported. See #13125 */ + check_time(st->easy, KN(CURLINFO_CONNECT_TIME_T), "1st header"); + check_time(st->easy, KN(CURLINFO_PRETRANSFER_TIME_T), "1st header"); + check_time(st->easy, KN(CURLINFO_STARTTRANSFER_TIME_T), "1st header"); + /* continuously updated */ + check_time(st->easy, KN(CURLINFO_TOTAL_TIME_T), "1st header"); + /* no SSL, must be 0 */ + check_time0(st->easy, KN(CURLINFO_APPCONNECT_TIME_T), "1st header"); + /* download not really started */ + check_time0(st->easy, KN(CURLINFO_SPEED_DOWNLOAD_T), "1st header"); + } + (void)fwrite(ptr, size, nmemb, stdout); + return len; +} + +static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct transfer_status *st = (struct transfer_status *)userp; + + (void)ptr; + (void)st; + fwrite(ptr, size, nmemb, stdout); + return size * nmemb; +} + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLcode res = CURLE_OK; + struct transfer_status st; + + start_test_timing(); + + memset(&st, 0, sizeof(st)); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curls); + st.easy = curls; /* to allow callbacks access */ + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_WRITEFUNCTION, write_callback); + easy_setopt(curls, CURLOPT_WRITEDATA, &st); + easy_setopt(curls, CURLOPT_HEADERFUNCTION, header_callback); + easy_setopt(curls, CURLOPT_HEADERDATA, &st); + + easy_setopt(curls, CURLOPT_NOPROGRESS, 0L); + + res = curl_easy_perform(curls); + + check_time(curls, KN(CURLINFO_CONNECT_TIME_T), "done"); + check_time(curls, KN(CURLINFO_PRETRANSFER_TIME_T), "done"); + check_time(curls, KN(CURLINFO_POSTTRANSFER_TIME_T), "done"); + check_time(curls, KN(CURLINFO_STARTTRANSFER_TIME_T), "done"); + /* no SSL, must be 0 */ + check_time0(curls, KN(CURLINFO_APPCONNECT_TIME_T), "done"); + check_time(curls, KN(CURLINFO_SPEED_DOWNLOAD_T), "done"); + check_time(curls, KN(CURLINFO_TOTAL_TIME_T), "done"); + +test_cleanup: + + curl_easy_cleanup(curls); + curl_global_cleanup(); + + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1542.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1542.c new file mode 100644 index 0000000000000000000000000000000000000000..5a8926585d8e6f8a0fdd093c4684f83687decef7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1542.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 + * + ***************************************************************************/ + +/* + * Test CURLOPT_MAXLIFETIME_CONN: + * Send four requests, sleeping between the second and third and setting + * MAXLIFETIME_CONN between the third and fourth. The first three requests + * should use the same connection, and the fourth request should close the + * first connection and open a second. + */ + +#include "test.h" +#include "testutil.h" +#include "testtrace.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + res_easy_init(easy); + + easy_setopt(easy, CURLOPT_URL, URL); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 0; + easy_setopt(easy, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(easy, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(easy, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(easy); + if(res) + goto test_cleanup; + + res = curl_easy_perform(easy); + if(res) + goto test_cleanup; + + /* CURLOPT_MAXLIFETIME_CONN is inclusive - the connection needs to be 2 + * seconds old */ + sleep(2); + + res = curl_easy_perform(easy); + if(res) + goto test_cleanup; + + easy_setopt(easy, CURLOPT_MAXLIFETIME_CONN, 1L); + + res = curl_easy_perform(easy); + if(res) + goto test_cleanup; + +test_cleanup: + + curl_easy_cleanup(easy); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1545.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1545.c new file mode 100644 index 0000000000000000000000000000000000000000..a1891375b3e208669d3494d0bcee67e64bfbdd05 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1545.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +CURLcode test(char *URL) +{ + CURL *eh = NULL; + CURLcode res = CURLE_OK; + struct curl_httppost *lastptr = NULL; + struct curl_httppost *m_formpost = NULL; + + global_init(CURL_GLOBAL_ALL); + + easy_init(eh); + + easy_setopt(eh, CURLOPT_URL, URL); + CURL_IGNORE_DEPRECATION( + curl_formadd(&m_formpost, &lastptr, CURLFORM_COPYNAME, "file", + CURLFORM_FILE, "missing-file", CURLFORM_END); + curl_easy_setopt(eh, CURLOPT_HTTPPOST, m_formpost); + ) + + (void)curl_easy_perform(eh); + (void)curl_easy_perform(eh); + +test_cleanup: + + CURL_IGNORE_DEPRECATION( + curl_formfree(m_formpost); + ) + curl_easy_cleanup(eh); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1550.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1550.c new file mode 100644 index 0000000000000000000000000000000000000000..ddc0c16ab5a8602ceface8770d2f280afb21017f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1550.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +#include + +CURLcode test(char *URL) +{ + CURLM *handle; + CURLcode res = CURLE_OK; + static const char * const bl_servers[] = + {"Microsoft-IIS/6.0", "nginx/0.8.54", NULL}; + static const char * const bl_sites[] = + {"curl.se:443", "example.com:80", NULL}; + + global_init(CURL_GLOBAL_ALL); + handle = curl_multi_init(); + (void)URL; /* unused */ + + curl_multi_setopt(handle, CURLMOPT_PIPELINING_SERVER_BL, bl_servers); + curl_multi_setopt(handle, CURLMOPT_PIPELINING_SITE_BL, bl_sites); + curl_multi_cleanup(handle); + curl_global_cleanup(); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1551.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1551.c new file mode 100644 index 0000000000000000000000000000000000000000..20e938ece6aa65ddd4a71d04924b875c2552ee75 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1551.c @@ -0,0 +1,53 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +#include + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + fprintf(stderr, "****************************** Do it again\n"); + res = curl_easy_perform(curl); + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1552.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1552.c new file mode 100644 index 0000000000000000000000000000000000000000..821fba27a37500f2ad370fe00613322e4f9fafcf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1552.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLM *multi = NULL; + int still_running; + CURLcode i = CURLE_OK; + CURLcode res = CURLE_OK; + CURLMsg *msg; + int counter = 3; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multi); + + easy_init(curls); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_HEADER, 1L); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + easy_setopt(curls, CURLOPT_USERPWD, "u:s"); + + multi_add_handle(multi, curls); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + + while(still_running && counter--) { + CURLMcode mres; + int num; + mres = curl_multi_wait(multi, NULL, 0, TEST_HANG_TIMEOUT, &num); + if(mres != CURLM_OK) { + printf("curl_multi_wait() returned %d\n", mres); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + } + + msg = curl_multi_info_read(multi, &still_running); + if(msg) + /* this should now contain a result code from the easy handle, + get it */ + i = msg->data.result; + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi); + curl_easy_cleanup(curls); + curl_global_cleanup(); + + if(res) + i = res; + + return i; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1553.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1553.c new file mode 100644 index 0000000000000000000000000000000000000000..998c0762aaf5319bcb460ddcfb497f11a03566ca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1553.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "testtrace.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +static int xferinfo(void *p, + curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + (void)p; + (void)dlnow; + (void)dltotal; + (void)ulnow; + (void)ultotal; + fprintf(stderr, "xferinfo fail!\n"); + return 1; /* fail as fast as we can */ +} + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLM *multi = NULL; + int still_running; + CURLcode i = CURLE_OK; + CURLcode res = CURLE_OK; + curl_mimepart *field = NULL; + curl_mime *mime = NULL; + int counter = 1; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multi); + + easy_init(curls); + + mime = curl_mime_init(curls); + field = curl_mime_addpart(mime); + curl_mime_name(field, "name"); + curl_mime_data(field, "value", CURL_ZERO_TERMINATED); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_HEADER, 1L); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + easy_setopt(curls, CURLOPT_MIMEPOST, mime); + easy_setopt(curls, CURLOPT_USERPWD, "u:s"); + easy_setopt(curls, CURLOPT_XFERINFOFUNCTION, xferinfo); + easy_setopt(curls, CURLOPT_NOPROGRESS, 1L); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + test_setopt(curls, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(curls, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + + multi_add_handle(multi, curls); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + + while(still_running && counter--) { + CURLMcode mres; + int num; + mres = curl_multi_wait(multi, NULL, 0, TEST_HANG_TIMEOUT, &num); + if(mres != CURLM_OK) { + printf("curl_multi_wait() returned %d\n", mres); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + } + +test_cleanup: + + curl_mime_free(mime); + curl_multi_remove_handle(multi, curls); + curl_multi_cleanup(multi); + curl_easy_cleanup(curls); + curl_global_cleanup(); + + if(res) + i = res; + + return i; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1554.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1554.c new file mode 100644 index 0000000000000000000000000000000000000000..3c48f3fe0851f0f0faafa1740ad58806a97aa161 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1554.c @@ -0,0 +1,107 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "memdebug.h" + +static const char *ldata_names[] = { + "NONE", + "SHARE", + "COOKIE", + "DNS", + "SESSION", + "CONNECT", + "PSL", + "HSTS", + "NULL", +}; + +static void test_lock(CURL *handle, curl_lock_data data, + curl_lock_access laccess, void *useptr) +{ + (void)handle; + (void)data; + (void)laccess; + (void)useptr; + printf("-> Mutex lock %s\n", ldata_names[data]); +} + +static void test_unlock(CURL *handle, curl_lock_data data, void *useptr) +{ + (void)handle; + (void)data; + (void)useptr; + printf("<- Mutex unlock %s\n", ldata_names[data]); +} + +/* test function */ +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURLSH *share = NULL; + int i; + + global_init(CURL_GLOBAL_ALL); + + share = curl_share_init(); + if(!share) { + fprintf(stderr, "curl_share_init() failed\n"); + goto test_cleanup; + } + + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT); + curl_share_setopt(share, CURLSHOPT_LOCKFUNC, test_lock); + curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, test_unlock); + + /* Loop the transfer and cleanup the handle properly every lap. This will + still reuse connections since the pool is in the shared object! */ + + for(i = 0; i < 3; i++) { + CURL *curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + + /* use the share object */ + curl_easy_setopt(curl, CURLOPT_SHARE, share); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* Check for errors */ + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + goto test_cleanup; + } + } + } + +test_cleanup: + curl_share_cleanup(share); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1555.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1555.c new file mode 100644 index 0000000000000000000000000000000000000000..59db1fbdbe3b883b615e32c697817eb45e0d4783 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1555.c @@ -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 + * + ***************************************************************************/ +/* + * Verify that some API functions are locked from being called inside callback + */ + +#include "test.h" + +#include "memdebug.h" + +static CURL *curl; + +static int progressCallback(void *arg, + double dltotal, + double dlnow, + double ultotal, + double ulnow) +{ + CURLcode res = CURLE_OK; + char buffer[256]; + size_t n = 0; + (void)arg; + (void)dltotal; + (void)dlnow; + (void)ultotal; + (void)ulnow; + res = curl_easy_recv(curl, buffer, 256, &n); + printf("curl_easy_recv returned %d\n", res); + res = curl_easy_send(curl, buffer, n, &n); + printf("curl_easy_send returned %d\n", res); + + return 1; +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_TIMEOUT, (long)7); + easy_setopt(curl, CURLOPT_NOSIGNAL, (long)1); + CURL_IGNORE_DEPRECATION( + easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progressCallback); + easy_setopt(curl, CURLOPT_PROGRESSDATA, NULL); + ) + easy_setopt(curl, CURLOPT_NOPROGRESS, (long)0); + + res = curl_easy_perform(curl); + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1556.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1556.c new file mode 100644 index 0000000000000000000000000000000000000000..25be5e50fa8a37a35d656392be527adcd99cc47d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1556.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +struct headerinfo { + size_t largest; +}; + +static size_t header(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t headersize = size * nmemb; + struct headerinfo *info = (struct headerinfo *)stream; + (void)ptr; + + if(headersize > info->largest) + /* remember the longest header */ + info->largest = headersize; + + return nmemb * size; +} + +CURLcode test(char *URL) +{ + CURLcode code; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + struct headerinfo info = {0}; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_HEADERFUNCTION, header); + easy_setopt(curl, CURLOPT_HEADERDATA, &info); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_URL, URL); + + code = curl_easy_perform(curl); + if(CURLE_OK != code) { + fprintf(stderr, "%s:%d curl_easy_perform() failed, " + "with code %d (%s)\n", + __FILE__, __LINE__, code, curl_easy_strerror(code)); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + printf("Max = %ld\n", (long)info.largest); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1557.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1557.c new file mode 100644 index 0000000000000000000000000000000000000000..6f0b99ac50daefc59df2f9552dc5800b1ecfb03d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1557.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLM *curlm = NULL; + CURL *curl1 = NULL; + CURL *curl2 = NULL; + int running_handles = 0; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + multi_init(curlm); + multi_setopt(curlm, CURLMOPT_MAX_HOST_CONNECTIONS, 1); + + easy_init(curl1); + easy_setopt(curl1, CURLOPT_URL, URL); + multi_add_handle(curlm, curl1); + + easy_init(curl2); + easy_setopt(curl2, CURLOPT_URL, URL); + multi_add_handle(curlm, curl2); + + multi_perform(curlm, &running_handles); + + multi_remove_handle(curlm, curl2); + + /* If curl2 is still in the connect-pending list, this will crash */ + multi_remove_handle(curlm, curl1); + +test_cleanup: + curl_easy_cleanup(curl1); + curl_easy_cleanup(curl2); + curl_multi_cleanup(curlm); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1558.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1558.c new file mode 100644 index 0000000000000000000000000000000000000000..e3a648f395a8dda6d7047bfee9b3ae7ab03cc746 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1558.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + long protocol = 0; + + global_init(CURL_GLOBAL_ALL); + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() returned %d (%s)\n", + res, curl_easy_strerror(res)); + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_PROTOCOL, &protocol); + ) + if(res) { + fprintf(stderr, "curl_easy_getinfo() returned %d (%s)\n", + res, curl_easy_strerror(res)); + goto test_cleanup; + } + + printf("Protocol: %lx\n", protocol); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return CURLE_OK; + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1559.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1559.c new file mode 100644 index 0000000000000000000000000000000000000000..37c0b8aace4c24e417158b8bc4a7764d6cf82e7e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1559.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define EXCESSIVE 10*1000*1000 +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + char *longurl = malloc(EXCESSIVE); + CURLU *u; + (void)URL; + + if(!longurl) + return (CURLcode)1; + + memset(longurl, 'a', EXCESSIVE); + longurl[EXCESSIVE-1] = 0; + + global_init(CURL_GLOBAL_ALL); + easy_init(curl); + + res = curl_easy_setopt(curl, CURLOPT_URL, longurl); + printf("CURLOPT_URL %d bytes URL == %d\n", + EXCESSIVE, res); + + res = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, longurl); + printf("CURLOPT_POSTFIELDS %d bytes data == %d\n", + EXCESSIVE, res); + + u = curl_url(); + if(u) { + CURLUcode uc = curl_url_set(u, CURLUPART_URL, longurl, 0); + printf("CURLUPART_URL %d bytes URL == %d (%s)\n", + EXCESSIVE, (int)uc, curl_url_strerror(uc)); + uc = curl_url_set(u, CURLUPART_SCHEME, longurl, CURLU_NON_SUPPORT_SCHEME); + printf("CURLUPART_SCHEME %d bytes scheme == %d (%s)\n", + EXCESSIVE, (int)uc, curl_url_strerror(uc)); + uc = curl_url_set(u, CURLUPART_USER, longurl, 0); + printf("CURLUPART_USER %d bytes user == %d (%s)\n", + EXCESSIVE, (int)uc, curl_url_strerror(uc)); + curl_url_cleanup(u); + } + +test_cleanup: + free(longurl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1560.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1560.c new file mode 100644 index 0000000000000000000000000000000000000000..d5253a739a107469858e5b225979b3a6463a5db3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1560.c @@ -0,0 +1,1907 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Note: + * + * Since the URL parser by default only accepts schemes that *this instance* + * of libcurl supports, make sure that the test1560 file lists all the schemes + * that this test will assume to be present! + */ + +#include "test.h" +#if defined(USE_LIBIDN2) || defined(USE_WIN32_IDN) || defined(USE_APPLE_IDN) +#define USE_IDN +#endif + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" /* LAST include file */ + +struct part { + CURLUPart part; + const char *name; +}; + + +static int checkparts(CURLU *u, const char *in, const char *wanted, + unsigned int getflags) +{ + int i; + CURLUcode rc; + char buf[256]; + char *bufp = &buf[0]; + size_t len = sizeof(buf); + struct part parts[] = { + {CURLUPART_SCHEME, "scheme"}, + {CURLUPART_USER, "user"}, + {CURLUPART_PASSWORD, "password"}, + {CURLUPART_OPTIONS, "options"}, + {CURLUPART_HOST, "host"}, + {CURLUPART_PORT, "port"}, + {CURLUPART_PATH, "path"}, + {CURLUPART_QUERY, "query"}, + {CURLUPART_FRAGMENT, "fragment"}, + {CURLUPART_URL, NULL} + }; + memset(buf, 0, sizeof(buf)); + + for(i = 0; parts[i].name; i++) { + char *p = NULL; + size_t n; + rc = curl_url_get(u, parts[i].part, &p, getflags); + if(!rc && p) { + msnprintf(bufp, len, "%s%s", buf[0]?" | ":"", p); + } + else + msnprintf(bufp, len, "%s[%d]", buf[0]?" | ":"", (int)rc); + + n = strlen(bufp); + bufp += n; + len -= n; + curl_free(p); + } + if(strcmp(buf, wanted)) { + fprintf(stderr, "in: %s\nwanted: %s\ngot: %s\n", in, wanted, buf); + return 1; + } + return 0; +} + +struct redircase { + const char *in; + const char *set; + const char *out; + unsigned int urlflags; + unsigned int setflags; + CURLUcode ucode; +}; + +struct setcase { + const char *in; + const char *set; + const char *out; + unsigned int urlflags; + unsigned int setflags; + CURLUcode ucode; /* for the main URL set */ + CURLUcode pcode; /* for updating parts */ +}; + +struct setgetcase { + const char *in; + const char *set; + const char *out; + unsigned int urlflags; /* for setting the URL */ + unsigned int setflags; /* for updating parts */ + unsigned int getflags; /* for getting parts */ + CURLUcode pcode; /* for updating parts */ +}; + +struct testcase { + const char *in; + const char *out; + unsigned int urlflags; + unsigned int getflags; + CURLUcode ucode; +}; + +struct urltestcase { + const char *in; + const char *out; + unsigned int urlflags; /* pass to curl_url() */ + unsigned int getflags; /* pass to curl_url_get() */ + CURLUcode ucode; +}; + +struct querycase { + const char *in; + const char *q; + const char *out; + unsigned int urlflags; /* pass to curl_url() */ + unsigned int qflags; /* pass to curl_url_get() */ + CURLUcode ucode; +}; + +struct clearurlcase { + CURLUPart part; + const char *in; + const char *out; + CURLUcode ucode; +}; + +static const struct testcase get_parts_list[] ={ + {"curl.se", + "[10] | [11] | [12] | [13] | curl.se | [15] | / | [16] | [17]", + CURLU_GUESS_SCHEME, CURLU_NO_GUESS_SCHEME, CURLUE_OK}, + {"https://curl.se:0/#", + "https | [11] | [12] | [13] | curl.se | 0 | / | [16] | ", + 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://curl.se/#", + "https | [11] | [12] | [13] | curl.se | [15] | / | [16] | ", + 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://curl.se/?#", + "https | [11] | [12] | [13] | curl.se | [15] | / | | ", + 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://curl.se/?", + "https | [11] | [12] | [13] | curl.se | [15] | / | | [17]", + 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://curl.se/?", + "https | [11] | [12] | [13] | curl.se | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + {"https://curl.se/?#", + "https | [11] | [12] | [13] | curl.se | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + {"https://curl.se/# ", + "https | [11] | [12] | [13] | curl.se | [15] | / | [16] | %20%20", + CURLU_URLENCODE|CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {" ", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {"1h://example.net", "", 0, 0, CURLUE_BAD_SCHEME}, + {"..://example.net", "", 0, 0, CURLUE_BAD_SCHEME}, + {"-ht://example.net", "", 0, 0, CURLUE_BAD_SCHEME}, + {"+ftp://example.net", "", 0, 0, CURLUE_BAD_SCHEME}, + {"hej.hej://example.net", + "hej.hej | [11] | [12] | [13] | example.net | [15] | / | [16] | [17]", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"ht-tp://example.net", + "ht-tp | [11] | [12] | [13] | example.net | [15] | / | [16] | [17]", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"ftp+more://example.net", + "ftp+more | [11] | [12] | [13] | example.net | [15] | / | [16] | [17]", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"f1337://example.net", + "f1337 | [11] | [12] | [13] | example.net | [15] | / | [16] | [17]", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"https://user@example.net?hello# space ", + "https | user | [12] | [13] | example.net | [15] | / | hello | %20space%20", + CURLU_ALLOW_SPACE|CURLU_URLENCODE, 0, CURLUE_OK}, + {"https://test%test", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example.com%252f%40@example.net", + "https | example.com%2f@ | [12] | [13] | example.net | [15] | / " + "| [16] | [17]", + 0, CURLU_URLDECODE, CURLUE_OK }, +#ifdef USE_IDN + {"https://räksmörgÃ¥s.se", + "https | [11] | [12] | [13] | xn--rksmrgs-5wao1o.se | " + "[15] | / | [16] | [17]", 0, CURLU_PUNYCODE, CURLUE_OK}, + {"https://xn--rksmrgs-5wao1o.se", + "https | [11] | [12] | [13] | räksmörgÃ¥s.se | " + "[15] | / | [16] | [17]", 0, CURLU_PUNY2IDN, CURLUE_OK}, +#else + {"https://räksmörgÃ¥s.se", + "https | [11] | [12] | [13] | [30] | [15] | / | [16] | [17]", + 0, CURLU_PUNYCODE, CURLUE_OK}, +#endif + /* https://ℂᵤⓇℒ。ð’🄴 */ + {"https://" + "%e2%84%82%e1%b5%a4%e2%93%87%e2%84%92%e3%80%82%f0%9d%90%92%f0%9f%84%b4", + "https | [11] | [12] | [13] | ℂᵤⓇℒ。ð’🄴 | [15] |" + " / | [16] | [17]", + 0, 0, CURLUE_OK}, + {"https://" + "%e2%84%82%e1%b5%a4%e2%93%87%e2%84%92%e3%80%82%f0%9d%90%92%f0%9f%84%b4", + "https | [11] | [12] | [13] | " + "%e2%84%82%e1%b5%a4%e2%93%87%e2%84%92%e3%80%82%f0%9d%90%92%f0%9f%84%b4 " + "| [15] | / | [16] | [17]", + 0, CURLU_URLENCODE, CURLUE_OK}, + {"https://" + "\xe2\x84\x82\xe1\xb5\xa4\xe2\x93\x87\xe2\x84\x92" + "\xe3\x80\x82\xf0\x9d\x90\x92\xf0\x9f\x84\xb4", + "https | [11] | [12] | [13] | " + "%e2%84%82%e1%b5%a4%e2%93%87%e2%84%92%e3%80%82%f0%9d%90%92%f0%9f%84%b4 " + "| [15] | / | [16] | [17]", + 0, CURLU_URLENCODE, CURLUE_OK}, + {"https://user@example.net?he l lo", + "https | user | [12] | [13] | example.net | [15] | / | he+l+lo | [17]", + CURLU_ALLOW_SPACE, CURLU_URLENCODE, CURLUE_OK}, + {"https://user@example.net?he l lo", + "https | user | [12] | [13] | example.net | [15] | / | he l lo | [17]", + CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"https://exam{}[]ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam{ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam}ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam]ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam\\ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam$ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam'ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam\"ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam^ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam`ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam*ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam=ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://exam;ple.net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example,net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example&net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example+net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example(net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example)net", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://example.net/}", + "https | [11] | [12] | [13] | example.net | [15] | /} | [16] | [17]", + 0, 0, CURLUE_OK}, + + /* blank user is blank */ + {"https://:password@example.net", + "https | | password | [13] | example.net | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + /* blank user + blank password */ + {"https://:@example.net", + "https | | | [13] | example.net | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + /* user-only (no password) */ + {"https://user@example.net", + "https | user | [12] | [13] | example.net | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, +#ifndef CURL_DISABLE_WEBSOCKETS + {"ws://example.com/color/?green", + "ws | [11] | [12] | [13] | example.com | [15] | /color/ | green |" + " [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"wss://example.com/color/?green", + "wss | [11] | [12] | [13] | example.com | [15] | /color/ | green |" + " [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, +#endif + + {"https://user:password@example.net/get?this=and#but frag then", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://user:password@example.net/get?this=and what", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://user:password@example.net/ge t?this=and-what", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://user:pass word@example.net/get?this=and-what", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://u ser:password@example.net/get?this=and-what", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"imap://user:pass;opt ion@server/path", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + /* no space allowed in scheme */ + {"htt ps://user:password@example.net/get?this=and-what", "", + CURLU_NON_SUPPORT_SCHEME|CURLU_ALLOW_SPACE, 0, CURLUE_BAD_SCHEME}, + {"https://user:password@example.net/get?this=and what", + "https | user | password | [13] | example.net | [15] | /get | " + "this=and what | [17]", + CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"https://user:password@example.net/ge t?this=and-what", + "https | user | password | [13] | example.net | [15] | /ge t | " + "this=and-what | [17]", + CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"https://user:pass word@example.net/get?this=and-what", + "https | user | pass word | [13] | example.net | [15] | /get | " + "this=and-what | [17]", + CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"https://u ser:password@example.net/get?this=and-what", + "https | u ser | password | [13] | example.net | [15] | /get | " + "this=and-what | [17]", + CURLU_ALLOW_SPACE, 0, CURLUE_OK}, + {"https://user:password@example.net/ge t?this=and-what", + "https | user | password | [13] | example.net | [15] | /ge%20t | " + "this=and-what | [17]", + CURLU_ALLOW_SPACE | CURLU_URLENCODE, 0, CURLUE_OK}, + {"[0:0:0:0:0:0:0:1]", + "http | [11] | [12] | [13] | [::1] | [15] | / | [16] | [17]", + CURLU_GUESS_SCHEME, 0, CURLUE_OK }, + {"[::1]", + "http | [11] | [12] | [13] | [::1] | [15] | / | [16] | [17]", + CURLU_GUESS_SCHEME, 0, CURLUE_OK }, + {"[::]", + "http | [11] | [12] | [13] | [::] | [15] | / | [16] | [17]", + CURLU_GUESS_SCHEME, 0, CURLUE_OK }, + {"https://[::1]", + "https | [11] | [12] | [13] | [::1] | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK }, + {"user:moo@ftp.example.com/color/#green?no-red", + "ftp | user | moo | [13] | ftp.example.com | [15] | /color/ | [16] | " + "green?no-red", + CURLU_GUESS_SCHEME, 0, CURLUE_OK }, + {"ftp.user:moo@example.com/color/#green?no-red", + "http | ftp.user | moo | [13] | example.com | [15] | /color/ | [16] | " + "green?no-red", + CURLU_GUESS_SCHEME, 0, CURLUE_OK }, +#ifdef _WIN32 + {"file:/C:\\programs\\foo", + "file | [11] | [12] | [13] | [14] | [15] | C:\\programs\\foo | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"file://C:\\programs\\foo", + "file | [11] | [12] | [13] | [14] | [15] | C:\\programs\\foo | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"file:///C:\\programs\\foo", + "file | [11] | [12] | [13] | [14] | [15] | C:\\programs\\foo | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"file://host.example.com/Share/path/to/file.txt", + "file | [11] | [12] | [13] | host.example.com | [15] | " + "//host.example.com/Share/path/to/file.txt | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, +#endif + {"https://example.com/color/#green?no-red", + "https | [11] | [12] | [13] | example.com | [15] | /color/ | [16] | " + "green?no-red", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"https://example.com/color/#green#no-red", + "https | [11] | [12] | [13] | example.com | [15] | /color/ | [16] | " + "green#no-red", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"https://example.com/color/?green#no-red", + "https | [11] | [12] | [13] | example.com | [15] | /color/ | green | " + "no-red", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"https://example.com/#color/?green#no-red", + "https | [11] | [12] | [13] | example.com | [15] | / | [16] | " + "color/?green#no-red", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"https://example.#com/color/?green#no-red", + "https | [11] | [12] | [13] | example. | [15] | / | [16] | " + "com/color/?green#no-red", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK }, + {"http://[ab.be:1]/x", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_BAD_IPV6}, + {"http://[ab.be]/x", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_BAD_IPV6}, + /* URL without host name */ + {"http://a:b@/x", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_NO_HOST}, + {"boing:80", + "https | [11] | [12] | [13] | boing | 80 | / | [16] | [17]", + CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"http://[fd00:a41::50]:8080", + "http | [11] | [12] | [13] | [fd00:a41::50] | 8080 | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://[fd00:a41::50]/", + "http | [11] | [12] | [13] | [fd00:a41::50] | [15] | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://[fd00:a41::50]", + "http | [11] | [12] | [13] | [fd00:a41::50] | [15] | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://[::1%252]:1234", + "https | [11] | [12] | [13] | [::1] | 1234 | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + + /* here's "bad" zone id */ + {"https://[fe80::20c:29ff:fe9c:409b%eth0]:1234", + "https | [11] | [12] | [13] | [fe80::20c:29ff:fe9c:409b] | 1234 " + "| / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://127.0.0.1:443", + "https | [11] | [12] | [13] | 127.0.0.1 | [15] | / | [16] | [17]", + 0, CURLU_NO_DEFAULT_PORT, CURLUE_OK}, + {"http://%3a:%3a@ex4mple/%3f+?+%3f+%23#+%23%3f%g7", + "http | : | : | [13] | ex4mple | [15] | /?+ | ? # | +#?%g7", + 0, CURLU_URLDECODE, CURLUE_OK}, + {"http://%3a:%3a@ex4mple/%3f?%3f%35#%35%3f%g7", + "http | %3a | %3a | [13] | ex4mple | [15] | /%3f | %3f%35 | %35%3f%g7", + 0, 0, CURLUE_OK}, + {"http://HO0_-st%41/", + "http | [11] | [12] | [13] | HO0_-stA | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file://hello.html", + "", + 0, 0, CURLUE_BAD_FILE_URL}, + {"http://HO0_-st/", + "http | [11] | [12] | [13] | HO0_-st | [15] | / | [16] | [17]", + 0, 0, CURLUE_OK}, + {"imap://user:pass;option@server/path", + "imap | user | pass | option | server | [15] | /path | [16] | [17]", + 0, 0, CURLUE_OK}, + {"http://user:pass;option@server/path", + "http | user | pass;option | [13] | server | [15] | /path | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file:/hello.html", + "file | [11] | [12] | [13] | [14] | [15] | /hello.html | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file:/h", + "file | [11] | [12] | [13] | [14] | [15] | /h | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file:/", + "file | [11] | [12] | [13] | [14] | [15] | | [16] | [17]", + 0, 0, CURLUE_BAD_FILE_URL}, + {"file://127.0.0.1/hello.html", + "file | [11] | [12] | [13] | [14] | [15] | /hello.html | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file:////hello.html", + "file | [11] | [12] | [13] | [14] | [15] | //hello.html | [16] | [17]", + 0, 0, CURLUE_OK}, + {"file:///hello.html", + "file | [11] | [12] | [13] | [14] | [15] | /hello.html | [16] | [17]", + 0, 0, CURLUE_OK}, + {"https://127.0.0.1", + "https | [11] | [12] | [13] | 127.0.0.1 | 443 | / | [16] | [17]", + 0, CURLU_DEFAULT_PORT, CURLUE_OK}, + {"https://127.0.0.1", + "https | [11] | [12] | [13] | 127.0.0.1 | [15] | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://[::1]:1234", + "https | [11] | [12] | [13] | [::1] | 1234 | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://127abc.com", + "https | [11] | [12] | [13] | 127abc.com | [15] | / | [16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https:// example.com?check", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://e x a m p l e.com?check", "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {"https://example.com?check", + "https | [11] | [12] | [13] | example.com | [15] | / | check | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://example.com:65536", + "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_BAD_PORT_NUMBER}, + {"https://example.com:-1#moo", + "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_BAD_PORT_NUMBER}, + {"https://example.com:0#moo", + "https | [11] | [12] | [13] | example.com | 0 | / | " + "[16] | moo", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://example.com:01#moo", + "https | [11] | [12] | [13] | example.com | 1 | / | " + "[16] | moo", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://example.com:1#moo", + "https | [11] | [12] | [13] | example.com | 1 | / | " + "[16] | moo", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com#moo", + "http | [11] | [12] | [13] | example.com | [15] | / | " + "[16] | moo", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com", + "http | [11] | [12] | [13] | example.com | [15] | / | " + "[16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com/path/html", + "http | [11] | [12] | [13] | example.com | [15] | /path/html | " + "[16] | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com/path/html?query=name", + "http | [11] | [12] | [13] | example.com | [15] | /path/html | " + "query=name | [17]", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com/path/html?query=name#anchor", + "http | [11] | [12] | [13] | example.com | [15] | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://example.com:1234/path/html?query=name#anchor", + "http | [11] | [12] | [13] | example.com | 1234 | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http:///user:password@example.com:1234/path/html?query=name#anchor", + "http | user | password | [13] | example.com | 1234 | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"https://user:password@example.com:1234/path/html?query=name#anchor", + "https | user | password | [13] | example.com | 1234 | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http://user:password@example.com:1234/path/html?query=name#anchor", + "http | user | password | [13] | example.com | 1234 | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http:/user:password@example.com:1234/path/html?query=name#anchor", + "http | user | password | [13] | example.com | 1234 | /path/html | " + "query=name | anchor", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"http:////user:password@example.com:1234/path/html?query=name#anchor", + "", + CURLU_DEFAULT_SCHEME, 0, CURLUE_BAD_SLASHES}, + {NULL, NULL, 0, 0, CURLUE_OK}, +}; + +static const struct urltestcase get_url_list[] = { + {"example.com", + "example.com/", + CURLU_GUESS_SCHEME, CURLU_NO_GUESS_SCHEME, CURLUE_OK}, + {"http://user@example.com?#", + "http://user@example.com/?#", + 0, CURLU_GET_EMPTY, CURLUE_OK}, + /* WHATWG disgrees, it wants "https:/0.0.0.0/" */ + {"https://0x.0x.0", "https://0x.0x.0/", 0, 0, CURLUE_OK}, + + {"https://example.com:000000000000000000000443/foo", + "https://example.com/foo", + 0, CURLU_NO_DEFAULT_PORT, CURLUE_OK}, + {"https://example.com:000000000000000000000/foo", + "https://example.com:0/foo", + 0, CURLU_NO_DEFAULT_PORT, CURLUE_OK}, + {"https://192.0x0000A80001", "https://192.168.0.1/", 0, 0, CURLUE_OK}, + {"https://0xffffffff", "https://255.255.255.255/", 0, 0, CURLUE_OK}, + {"https://1.0x1000000", "https://1.0x1000000/", 0, 0, CURLUE_OK}, + {"https://0x7f.1", "https://127.0.0.1/", 0, 0, CURLUE_OK}, + {"https://1.2.3.256.com", "https://1.2.3.256.com/", 0, 0, CURLUE_OK}, + {"https://10.com", "https://10.com/", 0, 0, CURLUE_OK}, + {"https://1.2.com", "https://1.2.com/", 0, 0, CURLUE_OK}, + {"https://1.2.3.com", "https://1.2.3.com/", 0, 0, CURLUE_OK}, + {"https://1.2.com.99", "https://1.2.com.99/", 0, 0, CURLUE_OK}, + {"https://[fe80::0000:20c:29ff:fe9c:409b]:80/moo", + "https://[fe80::20c:29ff:fe9c:409b]:80/moo", + 0, 0, CURLUE_OK}, + {"https://[fe80::020c:29ff:fe9c:409b]:80/moo", + "https://[fe80::20c:29ff:fe9c:409b]:80/moo", + 0, 0, CURLUE_OK}, + {"https://[fe80:0000:0000:0000:020c:29ff:fe9c:409b]:80/moo", + "https://[fe80::20c:29ff:fe9c:409b]:80/moo", + 0, 0, CURLUE_OK}, + {"https://[fe80:0:0:0:409b::]:80/moo", + "https://[fe80::409b:0:0:0]:80/moo", + 0, 0, CURLUE_OK}, + /* normalize to lower case */ + {"https://[FE80:0:A:0:409B:0:0:0]:80/moo", + "https://[fe80:0:a:0:409b::]:80/moo", + 0, 0, CURLUE_OK}, + {"https://[::%25fakeit];80/moo", + "", + 0, 0, CURLUE_BAD_PORT_NUMBER}, + {"https://[fe80::20c:29ff:fe9c:409b]-80/moo", + "", + 0, 0, CURLUE_BAD_PORT_NUMBER}, +#ifdef USE_IDN + {"https://räksmörgÃ¥s.se/path?q#frag", + "https://xn--rksmrgs-5wao1o.se/path?q#frag", 0, CURLU_PUNYCODE, CURLUE_OK}, +#endif + /* unsupported schemes with no guessing enabled */ + {"data:text/html;charset=utf-8;base64,PCFET0NUWVBFIEhUTUw+PG1ldGEgY", + "", 0, 0, CURLUE_UNSUPPORTED_SCHEME}, + {"d:anything-really", "", 0, 0, CURLUE_UNSUPPORTED_SCHEME}, + {"about:config", "", 0, 0, CURLUE_UNSUPPORTED_SCHEME}, + {"example://foo", "", 0, 0, CURLUE_UNSUPPORTED_SCHEME}, + {"mailto:infobot@example.com?body=send%20current-issue", "", 0, 0, + CURLUE_UNSUPPORTED_SCHEME}, + {"about:80", "https://about:80/", CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + /* percent encoded host names */ + {"http://example.com%40127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%21127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%3f127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%23127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%3a127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%09127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"http://example.com%2F127.0.0.1/", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://%41", "https://A/", 0, 0, CURLUE_OK}, + {"https://%20", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://%41%0d", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://%25", "", 0, 0, CURLUE_BAD_HOSTNAME}, + {"https://_%c0_", "https://_\xC0_/", 0, 0, CURLUE_OK}, + {"https://_%c0_", "https://_%C0_/", 0, CURLU_URLENCODE, CURLUE_OK}, + + /* IPv4 trickeries */ + {"https://16843009", "https://1.1.1.1/", 0, 0, CURLUE_OK}, + {"https://0177.1", "https://127.0.0.1/", 0, 0, CURLUE_OK}, + {"https://0111.02.0x3", "https://73.2.0.3/", 0, 0, CURLUE_OK}, + {"https://0111.02.0x3.", "https://0111.02.0x3./", 0, 0, CURLUE_OK}, + {"https://0111.02.030", "https://73.2.0.24/", 0, 0, CURLUE_OK}, + {"https://0111.02.030.", "https://0111.02.030./", 0, 0, CURLUE_OK}, + {"https://0xff.0xff.0377.255", "https://255.255.255.255/", 0, 0, CURLUE_OK}, + {"https://1.0xffffff", "https://1.255.255.255/", 0, 0, CURLUE_OK}, + /* IPv4 numerical overflows or syntax errors will not normalize */ + {"https://a127.0.0.1", "https://a127.0.0.1/", 0, 0, CURLUE_OK}, + {"https://\xff.127.0.0.1", "https://%FF.127.0.0.1/", 0, CURLU_URLENCODE, + CURLUE_OK}, + {"https://127.-0.0.1", "https://127.-0.0.1/", 0, 0, CURLUE_OK}, + {"https://127.0. 1", "https://127.0.0.1/", 0, 0, CURLUE_MALFORMED_INPUT}, + {"https://1.2.3.256", "https://1.2.3.256/", 0, 0, CURLUE_OK}, + {"https://1.2.3.256.", "https://1.2.3.256./", 0, 0, CURLUE_OK}, + {"https://1.2.3.4.5", "https://1.2.3.4.5/", 0, 0, CURLUE_OK}, + {"https://1.2.0x100.3", "https://1.2.0x100.3/", 0, 0, CURLUE_OK}, + {"https://4294967296", "https://4294967296/", 0, 0, CURLUE_OK}, + {"https://123host", "https://123host/", 0, 0, CURLUE_OK}, + /* 40 bytes scheme is the max allowed */ + {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA://hostname/path", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa://hostname/path", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + /* 41 bytes scheme is not allowed */ + {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA://hostname/path", + "", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_BAD_SCHEME}, + {"https://[fe80::20c:29ff:fe9c:409b%]:1234", + "", + 0, 0, CURLUE_BAD_IPV6}, + {"https://[fe80::20c:29ff:fe9c:409b%25]:1234", + "https://[fe80::20c:29ff:fe9c:409b%2525]:1234/", + 0, 0, CURLUE_OK}, + {"https://[fe80::20c:29ff:fe9c:409b%eth0]:1234", + "https://[fe80::20c:29ff:fe9c:409b%25eth0]:1234/", + 0, 0, CURLUE_OK}, + {"https://[::%25fakeit]/moo", + "https://[::%25fakeit]/moo", + 0, 0, CURLUE_OK}, + {"smtp.example.com/path/html", + "smtp://smtp.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"https.example.com/path/html", + "http://https.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"dict.example.com/path/html", + "dict://dict.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"pop3.example.com/path/html", + "pop3://pop3.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ldap.example.com/path/html", + "ldap://ldap.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"imap.example.com/path/html", + "imap://imap.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ftp.example.com/path/html", + "ftp://ftp.example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"example.com/path/html", + "http://example.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"smtp.com/path/html", + "smtp://smtp.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"dict.com/path/html", + "dict://dict.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"pop3.com/path/html", + "pop3://pop3.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ldap.com/path/html", + "ldap://ldap.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"imap.com/path/html", + "imap://imap.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ftp.com/path/html", + "ftp://ftp.com/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"smtp/path/html", + "http://smtp/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"dict/path/html", + "http://dict/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"pop3/path/html", + "http://pop3/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ldap/path/html", + "http://ldap/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"imap/path/html", + "http://imap/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"ftp/path/html", + "http://ftp/path/html", + CURLU_GUESS_SCHEME, 0, CURLUE_OK}, + {"HTTP://test/", "http://test/", 0, 0, CURLUE_OK}, + {"http://HO0_-st..~./", "http://HO0_-st..~./", 0, 0, CURLUE_OK}, + {"http:/@example.com: 123/", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {"http:/@example.com:123 /", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {"http:/@example.com:123a/", "", 0, 0, CURLUE_BAD_PORT_NUMBER}, + {"http://host/file\r", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {"http://host/file\n\x03", "", 0, 0, CURLUE_MALFORMED_INPUT}, + {"htt\x02://host/file", "", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_MALFORMED_INPUT}, + {" http://host/file", "", 0, 0, CURLUE_MALFORMED_INPUT}, + /* here the password ends at the semicolon and options is 'word' */ + {"imap://user:pass;word@host/file", + "imap://user:pass;word@host/file", + 0, 0, CURLUE_OK}, + /* here the password has the semicolon */ + {"http://user:pass;word@host/file", + "http://user:pass;word@host/file", 0, 0, CURLUE_OK}, + {"file:///file.txt#moo", "file:///file.txt#moo", 0, 0, CURLUE_OK}, + {"file:////file.txt", "file:////file.txt", 0, 0, CURLUE_OK}, + {"file:///file.txt", "file:///file.txt", 0, 0, CURLUE_OK}, + {"file:./", "file://", 0, 0, CURLUE_OK}, + {"http://example.com/hello/../here", + "http://example.com/hello/../here", + CURLU_PATH_AS_IS, 0, CURLUE_OK}, + {"http://example.com/hello/../here", + "http://example.com/here", + 0, 0, CURLUE_OK}, + {"http://example.com:80", + "http://example.com/", + 0, CURLU_NO_DEFAULT_PORT, CURLUE_OK}, + {"tp://example.com/path/html", + "", + 0, 0, CURLUE_UNSUPPORTED_SCHEME}, + {"http://hello:fool@example.com", + "", + CURLU_DISALLOW_USER, 0, CURLUE_USER_NOT_ALLOWED}, + {"http:/@example.com:123", + "http://@example.com:123/", + 0, 0, CURLUE_OK}, + {"http:/:password@example.com", + "http://:password@example.com/", + 0, 0, CURLUE_OK}, + {"http://user@example.com?#", + "http://user@example.com/", + 0, 0, CURLUE_OK}, + {"http://user@example.com?", + "http://user@example.com/", + 0, 0, CURLUE_OK}, + {"http://user@example.com#anchor", + "http://user@example.com/#anchor", + 0, 0, CURLUE_OK}, + {"example.com/path/html", + "https://example.com/path/html", + CURLU_DEFAULT_SCHEME, 0, CURLUE_OK}, + {"example.com/path/html", + "", + 0, 0, CURLUE_BAD_SCHEME}, + {"http://user:password@example.com:1234/path/html?query=name#anchor", + "http://user:password@example.com:1234/path/html?query=name#anchor", + 0, 0, CURLUE_OK}, + {"http://example.com:1234/path/html?query=name#anchor", + "http://example.com:1234/path/html?query=name#anchor", + 0, 0, CURLUE_OK}, + {"http://example.com/path/html?query=name#anchor", + "http://example.com/path/html?query=name#anchor", + 0, 0, CURLUE_OK}, + {"http://example.com/path/html?query=name", + "http://example.com/path/html?query=name", + 0, 0, CURLUE_OK}, + {"http://example.com/path/html", + "http://example.com/path/html", + 0, 0, CURLUE_OK}, + {"tp://example.com/path/html", + "tp://example.com/path/html", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"custom-scheme://host?expected=test-good", + "custom-scheme://host/?expected=test-good", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_OK}, + {"custom-scheme://?expected=test-bad", + "", + CURLU_NON_SUPPORT_SCHEME, 0, CURLUE_NO_HOST}, + {"custom-scheme://?expected=test-new-good", + "custom-scheme:///?expected=test-new-good", + CURLU_NON_SUPPORT_SCHEME | CURLU_NO_AUTHORITY, 0, CURLUE_OK}, + {"custom-scheme://host?expected=test-still-good", + "custom-scheme://host/?expected=test-still-good", + CURLU_NON_SUPPORT_SCHEME | CURLU_NO_AUTHORITY, 0, CURLUE_OK}, + {NULL, NULL, 0, 0, CURLUE_OK} +}; + +static int checkurl(const char *org, const char *url, const char *out) +{ + if(strcmp(out, url)) { + fprintf(stderr, + "Org: %s\n" + "Wanted: %s\n" + "Got : %s\n", + org, out, url); + return 1; + } + return 0; +} + +/* 1. Set the URL + 2. Set components + 3. Extract all components (not URL) +*/ +static const struct setgetcase setget_parts_list[] = { + {"https://example.com/", + "query=\"\",", + "https | [11] | [12] | [13] | example.com | [15] | / | | [17]", + 0, 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://example.com/", + "fragment=\"\",", + "https | [11] | [12] | [13] | example.com | [15] | / | [16] | ", + 0, 0, CURLU_GET_EMPTY, CURLUE_OK}, + {"https://example.com/", + "query=\"\",", + "https | [11] | [12] | [13] | example.com | [15] | / | [16] | [17]", + 0, 0, 0, CURLUE_OK}, + {"https://example.com", + "path=get,", + "https | [11] | [12] | [13] | example.com | [15] | /get | [16] | [17]", + 0, 0, 0, CURLUE_OK}, + {"https://example.com", + "path=/get,", + "https | [11] | [12] | [13] | example.com | [15] | /get | [16] | [17]", + 0, 0, 0, CURLUE_OK}, + {"https://example.com", + "path=g e t,", + "https | [11] | [12] | [13] | example.com | [15] | /g%20e%20t | " + "[16] | [17]", + 0, CURLU_URLENCODE, 0, CURLUE_OK}, + {NULL, NULL, NULL, 0, 0, 0, CURLUE_OK} +}; + +/* !checksrc! disable SPACEBEFORECOMMA 1 */ +static const struct setcase set_parts_list[] = { + {"https://example.com/", + "host=%43url.se,", + "https://%43url.se/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://example.com/", + "host=%25url.se,", + "", + 0, 0, CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/?param=value", + "query=\"\",", + "https://example.com/", + 0, CURLU_APPENDQUERY | CURLU_URLENCODE, CURLUE_OK, CURLUE_OK}, + {"https://example.com/", + "host=\"\",", + "https://example.com/", + 0, CURLU_URLENCODE, CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/", + "host=\"\",", + "https://example.com/", + 0, 0, CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com", + "path=get,", + "https://example.com/get", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://example.com/", + "scheme=ftp+-.123,", + "ftp+-.123://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_OK}, + {"https://example.com/", + "scheme=1234,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + "scheme=1http,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + "scheme=-ftp,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + "scheme=+ftp,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + "scheme=.ftp,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + "host=example.com%2fmoo,", + "", + 0, /* get */ + 0, /* set */ + CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/", + "host=http://fake,", + "", + 0, /* get */ + 0, /* set */ + CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/", + "host=test%,", + "", + 0, /* get */ + 0, /* set */ + CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/", + "host=te st,", + "", + 0, /* get */ + 0, /* set */ + CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {"https://example.com/", + "host=0xff,", /* '++' there's no automatic URL decode when setting this + part */ + "https://0xff/", + 0, /* get */ + 0, /* set */ + CURLUE_OK, CURLUE_OK}, + + {"https://example.com/", + "query=Al2cO3tDkcDZ3EWE5Lh+LX8TPHs,", /* contains '+' */ + "https://example.com/?Al2cO3tDkcDZ3EWE5Lh%2bLX8TPHs", + CURLU_URLDECODE, /* decode on get */ + CURLU_URLENCODE, /* encode on set */ + CURLUE_OK, CURLUE_OK}, + + {"https://example.com/", + /* Set a bad scheme *including* :// */ + "scheme=https://,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + /* Set a 41 bytes scheme. That's too long so the old scheme remains set. */ + "scheme=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbc,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_BAD_SCHEME}, + {"https://example.com/", + /* set a 40 bytes scheme */ + "scheme=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_OK}, + {"https://[::1%25fake]:1234/", + "zoneid=NULL,", + "https://[::1]:1234/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://host:1234/", + "port=NULL,", + "https://host/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://host:1234/", + "port=\"\",", + "https://host:1234/", + 0, 0, CURLUE_OK, CURLUE_BAD_PORT_NUMBER}, + {"https://host:1234/", + "port=56 78,", + "https://host:1234/", + 0, 0, CURLUE_OK, CURLUE_BAD_PORT_NUMBER}, + {"https://host:1234/", + "port=0,", + "https://host:0/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://host:1234/", + "port=65535,", + "https://host:65535/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://host:1234/", + "port=65536,", + "https://host:1234/", + 0, 0, CURLUE_OK, CURLUE_BAD_PORT_NUMBER}, + {"https://host/", + "path=%4A%4B%4C,", + "https://host/%4a%4b%4c", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://host/mooo?q#f", + "path=NULL,query=NULL,fragment=NULL,", + "https://host/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"https://user:secret@host/", + "user=NULL,password=NULL,", + "https://host/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {NULL, + "scheme=https,user= @:,host=foobar,", + "https://%20%20%20%40%3a@foobar/", + 0, CURLU_URLENCODE, CURLUE_OK, CURLUE_OK}, + /* Setting a host name with spaces is not OK: */ + {NULL, + "scheme=https,host= ,path= ,user= ,password= ,query= ,fragment= ,", + "[nothing]", + 0, CURLU_URLENCODE, CURLUE_OK, CURLUE_BAD_HOSTNAME}, + {NULL, + "scheme=https,host=foobar,path=/this /path /is /here,", + "https://foobar/this%20/path%20/is%20/here", + 0, CURLU_URLENCODE, CURLUE_OK, CURLUE_OK}, + {NULL, + "scheme=https,host=foobar,path=\xc3\xa4\xc3\xb6\xc3\xbc,", + "https://foobar/%c3%a4%c3%b6%c3%bc", + 0, CURLU_URLENCODE, CURLUE_OK, CURLUE_OK}, + {"imap://user:secret;opt@host/", + "options=updated,scheme=imaps,password=p4ssw0rd,", + "imaps://user:p4ssw0rd;updated@host/", + 0, 0, CURLUE_NO_HOST, CURLUE_OK}, + {"imap://user:secret;optit@host/", + "scheme=https,", + "https://user:secret@host/", + 0, 0, CURLUE_NO_HOST, CURLUE_OK}, + {"file:///file#anchor", + "scheme=https,host=example,", + "https://example/file#anchor", + 0, 0, CURLUE_NO_HOST, CURLUE_OK}, + {NULL, /* start fresh! */ + "scheme=file,host=127.0.0.1,path=/no,user=anonymous,", + "file:///no", + 0, 0, CURLUE_OK, CURLUE_OK}, + {NULL, /* start fresh! */ + "scheme=ftp,host=127.0.0.1,path=/no,user=anonymous,", + "ftp://anonymous@127.0.0.1/no", + 0, 0, CURLUE_OK, CURLUE_OK}, + {NULL, /* start fresh! */ + "scheme=https,host=example.com,", + "https://example.com/", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_OK}, + {"http://user:foo@example.com/path?query#frag", + "fragment=changed,", + "http://user:foo@example.com/path?query#changed", + 0, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, CURLUE_OK}, + {"http://example.com/", + "scheme=foo,", /* not accepted */ + "http://example.com/", + 0, 0, CURLUE_OK, CURLUE_UNSUPPORTED_SCHEME}, + {"http://example.com/", + "scheme=https,path=/hello,fragment=snippet,", + "https://example.com/hello#snippet", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"http://example.com:80", + "user=foo,port=1922,", + "http://foo@example.com:1922/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"http://example.com:80", + "user=foo,password=bar,", + "http://foo:bar@example.com:80/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"http://example.com:80", + "user=foo,", + "http://foo@example.com:80/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"http://example.com", + "host=www.example.com,", + "http://www.example.com/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"http://example.com:80", + "scheme=ftp,", + "ftp://example.com:80/", + 0, 0, CURLUE_OK, CURLUE_OK}, + {"custom-scheme://host", + "host=\"\",", + "custom-scheme://host/", + CURLU_NON_SUPPORT_SCHEME, CURLU_NON_SUPPORT_SCHEME, CURLUE_OK, + CURLUE_BAD_HOSTNAME}, + {"custom-scheme://host", + "host=\"\",", + "custom-scheme:///", + CURLU_NON_SUPPORT_SCHEME, CURLU_NON_SUPPORT_SCHEME | CURLU_NO_AUTHORITY, + CURLUE_OK, CURLUE_OK}, + + {NULL, NULL, NULL, 0, 0, CURLUE_OK, CURLUE_OK} +}; + +static CURLUPart part2id(char *part) +{ + if(!strcmp("url", part)) + return CURLUPART_URL; + if(!strcmp("scheme", part)) + return CURLUPART_SCHEME; + if(!strcmp("user", part)) + return CURLUPART_USER; + if(!strcmp("password", part)) + return CURLUPART_PASSWORD; + if(!strcmp("options", part)) + return CURLUPART_OPTIONS; + if(!strcmp("host", part)) + return CURLUPART_HOST; + if(!strcmp("port", part)) + return CURLUPART_PORT; + if(!strcmp("path", part)) + return CURLUPART_PATH; + if(!strcmp("query", part)) + return CURLUPART_QUERY; + if(!strcmp("fragment", part)) + return CURLUPART_FRAGMENT; + if(!strcmp("zoneid", part)) + return CURLUPART_ZONEID; + return (CURLUPart)9999; /* bad input => bad output */ +} + +static CURLUcode updateurl(CURLU *u, const char *cmd, unsigned int setflags) +{ + const char *p = cmd; + CURLUcode uc; + + /* make sure the last command ends with a comma too! */ + while(p) { + char *e = strchr(p, ','); + if(e) { + size_t n = (size_t)(e - p); + char buf[80]; + char part[80]; + char value[80]; + + memset(part, 0, sizeof(part)); /* Avoid valgrind false positive. */ + memset(value, 0, sizeof(value)); /* Avoid valgrind false positive. */ + memcpy(buf, p, n); + buf[n] = 0; + if(2 == sscanf(buf, "%79[^=]=%79[^,]", part, value)) { + CURLUPart what = part2id(part); +#if 0 + /* for debugging this */ + fprintf(stderr, "%s = \"%s\" [%d]\n", part, value, (int)what); +#endif + if(what > CURLUPART_ZONEID) + fprintf(stderr, "UNKNOWN part '%s'\n", part); + + if(!strcmp("NULL", value)) + uc = curl_url_set(u, what, NULL, setflags); + else if(!strcmp("\"\"", value)) + uc = curl_url_set(u, what, "", setflags); + else + uc = curl_url_set(u, what, value, setflags); + if(uc) + return uc; + } + p = e + 1; + continue; + } + break; + } + return CURLUE_OK; +} + +static const struct redircase set_url_list[] = { + {"http://example.org/", + "../path/././../../moo", + "http://example.org/moo", + 0, 0, CURLUE_OK}, + {"http://example.org/", + "//example.org/../path/../../", + "http://example.org/", + 0, 0, CURLUE_OK}, + {"http://example.org/", + "///example.org/../path/../../", + "http://example.org/", + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + ":23", + "http://example.org/foo/:23", + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "\\x", + "http://example.org/foo/\\x", + /* WHATWG disagrees */ + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "#/", + "http://example.org/foo/bar#/", + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "?/", + "http://example.org/foo/bar?/", + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "#;?", + "http://example.org/foo/bar#;?", + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "#", + "http://example.org/foo/bar", + /* This happens because the parser removes empty fragments */ + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "?", + "http://example.org/foo/bar", + /* This happens because the parser removes empty queries */ + 0, 0, CURLUE_OK}, + {"http://example.org/foo/bar", + "?#", + "http://example.org/foo/bar", + /* This happens because the parser removes empty queries and fragments */ + 0, 0, CURLUE_OK}, + {"http://example.com/please/../gimme/%TESTNUMBER?foobar#hello", + "http://example.net/there/it/is/../../tes t case=/%TESTNUMBER0002? yes no", + "http://example.net/there/tes%20t%20case=/%TESTNUMBER0002?+yes+no", + 0, CURLU_URLENCODE|CURLU_ALLOW_SPACE, CURLUE_OK}, + {"http://local.test?redirect=http://local.test:80?-321", + "http://local.test:80?-123", + "http://local.test:80/?-123", + 0, CURLU_URLENCODE|CURLU_ALLOW_SPACE, CURLUE_OK}, + {"http://local.test?redirect=http://local.test:80?-321", + "http://local.test:80?-123", + "http://local.test:80/?-123", + 0, 0, CURLUE_OK}, + {"http://example.org/static/favicon/wikipedia.ico", + "//fake.example.com/licenses/by-sa/3.0/", + "http://fake.example.com/licenses/by-sa/3.0/", + 0, 0, CURLUE_OK}, + {"https://example.org/static/favicon/wikipedia.ico", + "//fake.example.com/licenses/by-sa/3.0/", + "https://fake.example.com/licenses/by-sa/3.0/", + 0, 0, CURLUE_OK}, + {"file://localhost/path?query#frag", + "foo#another", + "file:///foo#another", + 0, 0, CURLUE_OK}, + {"http://example.com/path?query#frag", + "https://two.example.com/bradnew", + "https://two.example.com/bradnew", + 0, 0, CURLUE_OK}, + {"http://example.com/path?query#frag", + "../../newpage#foo", + "http://example.com/newpage#foo", + 0, 0, CURLUE_OK}, + {"http://user:foo@example.com/path?query#frag", + "../../newpage", + "http://user:foo@example.com/newpage", + 0, 0, CURLUE_OK}, + {"http://user:foo@example.com/path?query#frag", + "../newpage", + "http://user:foo@example.com/newpage", + 0, 0, CURLUE_OK}, + {"http://user:foo@example.com/path?query#frag", + "http://?hi", + "http:///?hi", + 0, CURLU_NO_AUTHORITY, CURLUE_OK}, + {NULL, NULL, NULL, 0, 0, CURLUE_OK} +}; + +static int set_url(void) +{ + int i; + int error = 0; + + for(i = 0; set_url_list[i].in && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) + break; + rc = curl_url_set(urlp, CURLUPART_URL, set_url_list[i].in, + set_url_list[i].urlflags); + if(!rc) { + rc = curl_url_set(urlp, CURLUPART_URL, set_url_list[i].set, + set_url_list[i].setflags); + if(rc) { + fprintf(stderr, "%s:%d Set URL %s returned %d (%s)\n", + __FILE__, __LINE__, set_url_list[i].set, + (int)rc, curl_url_strerror(rc)); + error++; + } + else { + char *url = NULL; + rc = curl_url_get(urlp, CURLUPART_URL, &url, 0); + if(rc) { + fprintf(stderr, "%s:%d Get URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + if(checkurl(set_url_list[i].in, url, set_url_list[i].out)) { + error++; + } + } + curl_free(url); + } + } + else if(rc != set_url_list[i].ucode) { + fprintf(stderr, "Set URL\nin: %s\nreturned %d (expected %d)\n", + set_url_list[i].in, (int)rc, set_url_list[i].ucode); + error++; + } + curl_url_cleanup(urlp); + } + return error; +} + +/* 1. Set a URL + 2. Set one or more parts + 3. Extract and compare all parts - not the URL +*/ +static int setget_parts(void) +{ + int i; + int error = 0; + + for(i = 0; setget_parts_list[i].set && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) { + error++; + break; + } + if(setget_parts_list[i].in) + rc = curl_url_set(urlp, CURLUPART_URL, setget_parts_list[i].in, + setget_parts_list[i].urlflags); + else + rc = CURLUE_OK; + if(!rc) { + char *url = NULL; + CURLUcode uc = updateurl(urlp, setget_parts_list[i].set, + setget_parts_list[i].setflags); + + if(uc != setget_parts_list[i].pcode) { + fprintf(stderr, "updateurl\nin: %s\nreturned %d (expected %d)\n", + setget_parts_list[i].set, (int)uc, setget_parts_list[i].pcode); + error++; + } + if(!uc) { + if(checkparts(urlp, setget_parts_list[i].set, setget_parts_list[i].out, + setget_parts_list[i].getflags)) + error++; /* add */ + } + curl_free(url); + } + else if(rc != CURLUE_OK) { + fprintf(stderr, "Set parts\nin: %s\nreturned %d (expected %d)\n", + setget_parts_list[i].in, (int)rc, 0); + error++; + } + curl_url_cleanup(urlp); + } + return error; +} + +static int set_parts(void) +{ + int i; + int error = 0; + + for(i = 0; set_parts_list[i].set && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) { + error++; + break; + } + if(set_parts_list[i].in) + rc = curl_url_set(urlp, CURLUPART_URL, set_parts_list[i].in, + set_parts_list[i].urlflags); + else + rc = CURLUE_OK; + if(!rc) { + char *url = NULL; + CURLUcode uc = updateurl(urlp, set_parts_list[i].set, + set_parts_list[i].setflags); + + if(uc != set_parts_list[i].pcode) { + fprintf(stderr, "updateurl\nin: %s\nreturned %d (expected %d)\n", + set_parts_list[i].set, (int)uc, set_parts_list[i].pcode); + error++; + } + if(!uc) { + /* only do this if it worked */ + rc = curl_url_get(urlp, CURLUPART_URL, &url, 0); + + if(rc) { + fprintf(stderr, "%s:%d Get URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else if(checkurl(set_parts_list[i].in, url, set_parts_list[i].out)) { + error++; + } + } + curl_free(url); + } + else if(rc != set_parts_list[i].ucode) { + fprintf(stderr, "Set parts\nin: %s\nreturned %d (expected %d)\n", + set_parts_list[i].in, (int)rc, set_parts_list[i].ucode); + error++; + } + curl_url_cleanup(urlp); + } + return error; +} + +static int get_url(void) +{ + int i; + int error = 0; + for(i = 0; get_url_list[i].in && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) { + error++; + break; + } + rc = curl_url_set(urlp, CURLUPART_URL, get_url_list[i].in, + get_url_list[i].urlflags); + if(!rc) { + char *url = NULL; + rc = curl_url_get(urlp, CURLUPART_URL, &url, get_url_list[i].getflags); + + if(rc) { + fprintf(stderr, "%s:%d returned %d (%s). URL: '%s'\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc), + get_url_list[i].in); + error++; + } + else { + if(checkurl(get_url_list[i].in, url, get_url_list[i].out)) { + error++; + } + } + curl_free(url); + } + if(rc != get_url_list[i].ucode) { + fprintf(stderr, "Get URL\nin: %s\nreturned %d (expected %d)\n", + get_url_list[i].in, (int)rc, get_url_list[i].ucode); + error++; + } + curl_url_cleanup(urlp); + } + return error; +} + +static int get_parts(void) +{ + int i; + int error = 0; + for(i = 0; get_parts_list[i].in && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) { + error++; + break; + } + rc = curl_url_set(urlp, CURLUPART_URL, + get_parts_list[i].in, + get_parts_list[i].urlflags); + if(rc != get_parts_list[i].ucode) { + fprintf(stderr, "Get parts\nin: %s\nreturned %d (expected %d)\n", + get_parts_list[i].in, (int)rc, get_parts_list[i].ucode); + error++; + } + else if(get_parts_list[i].ucode) { + /* the expected error happened */ + } + else if(checkparts(urlp, get_parts_list[i].in, get_parts_list[i].out, + get_parts_list[i].getflags)) + error++; + curl_url_cleanup(urlp); + } + return error; +} + +static const struct querycase append_list[] = { + {"HTTP://test/?s", "name=joe\x02", "http://test/?s&name=joe%02", + 0, CURLU_URLENCODE, CURLUE_OK}, + {"HTTP://test/?size=2#f", "name=joe=", "http://test/?size=2&name=joe%3d#f", + 0, CURLU_URLENCODE, CURLUE_OK}, + {"HTTP://test/?size=2#f", "name=joe doe", + "http://test/?size=2&name=joe+doe#f", + 0, CURLU_URLENCODE, CURLUE_OK}, + {"HTTP://test/", "name=joe", "http://test/?name=joe", 0, 0, CURLUE_OK}, + {"HTTP://test/?size=2", "name=joe", "http://test/?size=2&name=joe", + 0, 0, CURLUE_OK}, + {"HTTP://test/?size=2&", "name=joe", "http://test/?size=2&name=joe", + 0, 0, CURLUE_OK}, + {"HTTP://test/?size=2#f", "name=joe", "http://test/?size=2&name=joe#f", + 0, 0, CURLUE_OK}, + {NULL, NULL, NULL, 0, 0, CURLUE_OK} +}; + +static int append(void) +{ + int i; + int error = 0; + for(i = 0; append_list[i].in && !error; i++) { + CURLUcode rc; + CURLU *urlp = curl_url(); + if(!urlp) { + error++; + break; + } + rc = curl_url_set(urlp, CURLUPART_URL, + append_list[i].in, + append_list[i].urlflags); + if(rc) + error++; + else + rc = curl_url_set(urlp, CURLUPART_QUERY, + append_list[i].q, + append_list[i].qflags | CURLU_APPENDQUERY); + if(error) + ; + else if(rc != append_list[i].ucode) { + fprintf(stderr, "Append\nin: %s\nreturned %d (expected %d)\n", + append_list[i].in, (int)rc, append_list[i].ucode); + error++; + } + else if(append_list[i].ucode) { + /* the expected error happened */ + } + else { + char *url; + rc = curl_url_get(urlp, CURLUPART_URL, &url, 0); + if(rc) { + fprintf(stderr, "%s:%d Get URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + if(checkurl(append_list[i].in, url, append_list[i].out)) { + error++; + } + curl_free(url); + } + } + curl_url_cleanup(urlp); + } + return error; +} + +static int scopeid(void) +{ + CURLU *u = curl_url(); + int error = 0; + CURLUcode rc; + char *url; + + rc = curl_url_set(u, CURLUPART_URL, + "https://[fe80::20c:29ff:fe9c:409b%25eth0]/hello.html", 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_set returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + + rc = curl_url_get(u, CURLUPART_HOST, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_HOST returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_set(u, CURLUPART_HOST, "[::1]", 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_set CURLUPART_HOST returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + + rc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_set(u, CURLUPART_HOST, "example.com", 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_set CURLUPART_HOST returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + + rc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_set(u, CURLUPART_HOST, + "[fe80::20c:29ff:fe9c:409b%25eth0]", 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_set CURLUPART_HOST returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + + rc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_get(u, CURLUPART_HOST, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_HOST returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_get(u, CURLUPART_ZONEID, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_ZONEID returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + rc = curl_url_set(u, CURLUPART_ZONEID, "clown", 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_set CURLUPART_ZONEID returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + + rc = curl_url_get(u, CURLUPART_URL, &url, 0); + if(rc != CURLUE_OK) { + fprintf(stderr, "%s:%d curl_url_get CURLUPART_URL returned %d (%s)\n", + __FILE__, __LINE__, (int)rc, curl_url_strerror(rc)); + error++; + } + else { + curl_free(url); + } + + curl_url_cleanup(u); + + return error; +} + +static int get_nothing(void) +{ + CURLU *u = curl_url(); + if(u) { + char *p; + CURLUcode rc; + + rc = curl_url_get(u, CURLUPART_SCHEME, &p, 0); + if(rc != CURLUE_NO_SCHEME) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_HOST, &p, 0); + if(rc != CURLUE_NO_HOST) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_USER, &p, 0); + if(rc != CURLUE_NO_USER) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_PASSWORD, &p, 0); + if(rc != CURLUE_NO_PASSWORD) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_OPTIONS, &p, 0); + if(rc != CURLUE_NO_OPTIONS) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_PATH, &p, 0); + if(rc != CURLUE_OK) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + else + curl_free(p); + + rc = curl_url_get(u, CURLUPART_QUERY, &p, 0); + if(rc != CURLUE_NO_QUERY) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_FRAGMENT, &p, 0); + if(rc != CURLUE_NO_FRAGMENT) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, CURLUPART_ZONEID, &p, 0); + if(rc != CURLUE_NO_ZONEID) + fprintf(stderr, "unexpected return code %u on line %u\n", (int)rc, + __LINE__); + + curl_url_cleanup(u); + } + return 0; +} + +static const struct clearurlcase clear_url_list[] ={ + {CURLUPART_SCHEME, "http", NULL, CURLUE_NO_SCHEME}, + {CURLUPART_USER, "user", NULL, CURLUE_NO_USER}, + {CURLUPART_PASSWORD, "password", NULL, CURLUE_NO_PASSWORD}, + {CURLUPART_OPTIONS, "options", NULL, CURLUE_NO_OPTIONS}, + {CURLUPART_HOST, "host", NULL, CURLUE_NO_HOST}, + {CURLUPART_ZONEID, "eth0", NULL, CURLUE_NO_ZONEID}, + {CURLUPART_PORT, "1234", NULL, CURLUE_NO_PORT}, + {CURLUPART_PATH, "/hello", "/", CURLUE_OK}, + {CURLUPART_QUERY, "a=b", NULL, CURLUE_NO_QUERY}, + {CURLUPART_FRAGMENT, "anchor", NULL, CURLUE_NO_FRAGMENT}, + {CURLUPART_URL, NULL, NULL, CURLUE_OK}, +}; + +static int clear_url(void) +{ + CURLU *u = curl_url(); + int i, error = 0; + if(u) { + char *p = NULL; + CURLUcode rc; + + for(i = 0; clear_url_list[i].in && !error; i++) { + rc = curl_url_set(u, clear_url_list[i].part, clear_url_list[i].in, 0); + if(rc != CURLUE_OK) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_set(u, CURLUPART_URL, NULL, 0); + if(rc != CURLUE_OK) + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + + rc = curl_url_get(u, clear_url_list[i].part, &p, 0); + if(rc != clear_url_list[i].ucode || (clear_url_list[i].out && + 0 != strcmp(p, clear_url_list[i].out))) { + + fprintf(stderr, "unexpected return code line %u\n", __LINE__); + error++; + } + if(rc == CURLUE_OK) + curl_free(p); + } + } + + curl_url_cleanup(u); + + return error; +} + +static char total[128000]; +static char bigpart[120000]; + +/* + * verify ridiculous URL part sizes + */ +static int huge(void) +{ + const char *smallpart = "c"; + int i; + CURLU *urlp = curl_url(); + CURLUcode rc; + CURLUPart part[]= { + CURLUPART_SCHEME, + CURLUPART_USER, + CURLUPART_PASSWORD, + CURLUPART_HOST, + CURLUPART_PATH, + CURLUPART_QUERY, + CURLUPART_FRAGMENT + }; + int error = 0; + if(!urlp) + return 1; + bigpart[0] = '/'; /* for the path */ + memset(&bigpart[1], 'a', sizeof(bigpart) - 2); + bigpart[sizeof(bigpart) - 1] = 0; + + for(i = 0; i < 7; i++) { + char *partp; + msnprintf(total, sizeof(total), + "%s://%s:%s@%s/%s?%s#%s", + (i == 0) ? &bigpart[1] : smallpart, + (i == 1) ? &bigpart[1] : smallpart, + (i == 2) ? &bigpart[1] : smallpart, + (i == 3) ? &bigpart[1] : smallpart, + (i == 4) ? &bigpart[1] : smallpart, + (i == 5) ? &bigpart[1] : smallpart, + (i == 6) ? &bigpart[1] : smallpart); + rc = curl_url_set(urlp, CURLUPART_URL, total, CURLU_NON_SUPPORT_SCHEME); + if((!i && (rc != CURLUE_BAD_SCHEME)) || + (i && rc)) { + printf("URL %u: failed to parse [%s]\n", i, total); + error++; + } + + /* only extract if the parse worked */ + if(!rc) { + curl_url_get(urlp, part[i], &partp, 0); + if(!partp || strcmp(partp, &bigpart[1 - (i == 4)])) { + printf("URL %u part %u: failure\n", i, part[i]); + error++; + } + curl_free(partp); + } + } + curl_url_cleanup(urlp); + return error; +} + +static int urldup(void) +{ + const char *url[] = { + "http://" + "user:pwd@" + "[2a04:4e42:e00::347%25eth0]" + ":80" + "/path" + "?query" + "#fraggie", + "https://example.com", + "https://user@example.com", + "https://user.pwd@example.com", + "https://user.pwd@example.com:1234", + "https://example.com:1234", + "example.com:1234", + "https://user.pwd@example.com:1234/path?query#frag", + NULL + }; + CURLU *copy = NULL; + char *h_str = NULL, *copy_str = NULL; + CURLU *h = curl_url(); + int i; + + if(!h) + goto err; + + for(i = 0; url[i]; i++) { + CURLUcode rc = curl_url_set(h, CURLUPART_URL, url[i], + CURLU_GUESS_SCHEME); + if(rc) + goto err; + copy = curl_url_dup(h); + + rc = curl_url_get(h, CURLUPART_URL, &h_str, 0); + if(rc) + goto err; + + rc = curl_url_get(copy, CURLUPART_URL, ©_str, 0); + if(rc) + goto err; + + if(strcmp(h_str, copy_str)) { + printf("Original: %s\nParsed: %s\nCopy: %s\n", + url[i], h_str, copy_str); + goto err; + } + curl_free(copy_str); + curl_free(h_str); + curl_url_cleanup(copy); + copy_str = NULL; + h_str = NULL; + copy = NULL; + } + curl_url_cleanup(h); + return 0; +err: + curl_free(copy_str); + curl_free(h_str); + curl_url_cleanup(copy); + curl_url_cleanup(h); + return 1; +} + +CURLcode test(char *URL) +{ + (void)URL; /* not used */ + + if(urldup()) + return (CURLcode)11; + + if(setget_parts()) + return (CURLcode)10; + + if(get_url()) + return (CURLcode)3; + + if(huge()) + return (CURLcode)9; + + if(get_nothing()) + return (CURLcode)7; + + if(scopeid()) + return (CURLcode)6; + + if(append()) + return (CURLcode)5; + + if(set_url()) + return (CURLcode)1; + + if(set_parts()) + return (CURLcode)2; + + if(get_parts()) + return (CURLcode)4; + + if(clear_url()) + return (CURLcode)8; + + printf("success\n"); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1564.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1564.c new file mode 100644 index 0000000000000000000000000000000000000000..851d02c403fb6bfafa798e7853b79ac1f316bfa3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1564.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 +#define WAKEUP_NUM 10 + +CURLcode test(char *URL) +{ + CURLM *multi = NULL; + int numfds; + int i; + CURLcode res = CURLE_OK; + struct timeval time_before_wait, time_after_wait; + + (void)URL; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multi); + + /* no wakeup */ + + time_before_wait = tutil_tvnow(); + multi_poll(multi, NULL, 0, 1000, &numfds); + time_after_wait = tutil_tvnow(); + + if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) { + fprintf(stderr, "%s:%d curl_multi_poll returned too early\n", + __FILE__, __LINE__); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + /* try a single wakeup */ + + res_multi_wakeup(multi); + + time_before_wait = tutil_tvnow(); + multi_poll(multi, NULL, 0, 1000, &numfds); + time_after_wait = tutil_tvnow(); + + if(tutil_tvdiff(time_after_wait, time_before_wait) > 500) { + fprintf(stderr, "%s:%d curl_multi_poll returned too late\n", + __FILE__, __LINE__); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + /* previous wakeup should not wake up this */ + + time_before_wait = tutil_tvnow(); + multi_poll(multi, NULL, 0, 1000, &numfds); + time_after_wait = tutil_tvnow(); + + if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) { + fprintf(stderr, "%s:%d curl_multi_poll returned too early\n", + __FILE__, __LINE__); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + /* try lots of wakeup */ + + for(i = 0; i < WAKEUP_NUM; ++i) + res_multi_wakeup(multi); + + time_before_wait = tutil_tvnow(); + multi_poll(multi, NULL, 0, 1000, &numfds); + time_after_wait = tutil_tvnow(); + + if(tutil_tvdiff(time_after_wait, time_before_wait) > 500) { + fprintf(stderr, "%s:%d curl_multi_poll returned too late\n", + __FILE__, __LINE__); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + + /* Even lots of previous wakeups should not wake up this. */ + + time_before_wait = tutil_tvnow(); + multi_poll(multi, NULL, 0, 1000, &numfds); + time_after_wait = tutil_tvnow(); + + if(tutil_tvdiff(time_after_wait, time_before_wait) < 500) { + fprintf(stderr, "%s:%d curl_multi_poll returned too early\n", + __FILE__, __LINE__); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + +test_cleanup: + + curl_multi_cleanup(multi); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1565.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1565.c new file mode 100644 index 0000000000000000000000000000000000000000..b6b8ecf12df02ee8f739d88fad64bba15a0eea7c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1565.c @@ -0,0 +1,210 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#ifdef HAVE_PTHREAD_H +#include +#include + +#define TEST_HANG_TIMEOUT 60 * 1000 +#define CONN_NUM 3 +#define TIME_BETWEEN_START_SECS 2 + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static CURL *pending_handles[CONN_NUM]; +static int pending_num = 0; +static CURLcode test_failure = CURLE_OK; + +static CURLM *testmulti = NULL; +static const char *url; + +static void *run_thread(void *ptr) +{ + CURL *easy = NULL; + CURLcode res = CURLE_OK; + int i; + + (void)ptr; + + for(i = 0; i < CONN_NUM; i++) { + wait_ms(TIME_BETWEEN_START_SECS * 1000); + + easy_init(easy); + + easy_setopt(easy, CURLOPT_URL, url); + easy_setopt(easy, CURLOPT_VERBOSE, 0L); + + pthread_mutex_lock(&lock); + + if(test_failure) { + pthread_mutex_unlock(&lock); + goto test_cleanup; + } + + pending_handles[pending_num] = easy; + pending_num++; + easy = NULL; + + pthread_mutex_unlock(&lock); + + res_multi_wakeup(testmulti); + } + +test_cleanup: + + curl_easy_cleanup(easy); + + pthread_mutex_lock(&lock); + + if(!test_failure) + test_failure = res; + + pthread_mutex_unlock(&lock); + + return NULL; +} + +CURLcode test(char *URL) +{ + int still_running; + int num; + int i; + int result; + CURLcode res = CURLE_OK; + CURL *started_handles[CONN_NUM]; + int started_num = 0; + int finished_num = 0; + pthread_t tid; + bool tid_valid = false; + struct CURLMsg *message; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(testmulti); + + url = URL; + + result = pthread_create(&tid, NULL, run_thread, NULL); + if(!result) + tid_valid = true; + else { + fprintf(stderr, "%s:%d Couldn't create thread, errno %d\n", + __FILE__, __LINE__, result); + goto test_cleanup; + } + + while(1) { + multi_perform(testmulti, &still_running); + + abort_on_test_timeout(); + + while((message = curl_multi_info_read(testmulti, &num))) { + if(message->msg == CURLMSG_DONE) { + res = message->data.result; + if(res) + goto test_cleanup; + multi_remove_handle(testmulti, message->easy_handle); + finished_num++; + } + else { + fprintf(stderr, "%s:%d Got an unexpected message from curl: %i\n", + __FILE__, __LINE__, (int)message->msg); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + } + + if(CONN_NUM == finished_num) + break; + + multi_poll(testmulti, NULL, 0, TEST_HANG_TIMEOUT, &num); + + abort_on_test_timeout(); + + pthread_mutex_lock(&lock); + + while(pending_num > 0) { + res_multi_add_handle(testmulti, pending_handles[pending_num - 1]); + if(res) { + pthread_mutex_unlock(&lock); + goto test_cleanup; + } + + started_handles[started_num] = pending_handles[pending_num - 1]; + started_num++; + pending_num--; + } + + pthread_mutex_unlock(&lock); + + abort_on_test_timeout(); + } + + if(CONN_NUM != started_num) { + fprintf(stderr, "%s:%d Not all connections started: %d of %d\n", + __FILE__, __LINE__, started_num, CONN_NUM); + goto test_cleanup; + } + + if(CONN_NUM != finished_num) { + fprintf(stderr, "%s:%d Not all connections finished: %d of %d\n", + __FILE__, __LINE__, started_num, CONN_NUM); + goto test_cleanup; + } + +test_cleanup: + + pthread_mutex_lock(&lock); + if(!test_failure) + test_failure = res; + pthread_mutex_unlock(&lock); + + if(tid_valid) + pthread_join(tid, NULL); + + curl_multi_cleanup(testmulti); + for(i = 0; i < pending_num; i++) + curl_easy_cleanup(pending_handles[i]); + for(i = 0; i < started_num; i++) + curl_easy_cleanup(started_handles[i]); + curl_global_cleanup(); + + return test_failure; +} + +#else /* without pthread, this test doesn't work */ +CURLcode test(char *URL) +{ + (void)URL; + return 0; +} +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1567.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1567.c new file mode 100644 index 0000000000000000000000000000000000000000..fae8cc12e8f72d488f14923e9aa1dbfc4c0943ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1567.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +#include + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_OK; + CURLU *u = NULL; + + global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + u = curl_url(); + if(u) { + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_url_set(u, CURLUPART_URL, URL, 0); + curl_easy_setopt(curl, CURLOPT_CURLU, u); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + fprintf(stderr, "****************************** Do it again\n"); + res = curl_easy_perform(curl); + } + } + +test_cleanup: + curl_url_cleanup(u); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1568.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1568.c new file mode 100644 index 0000000000000000000000000000000000000000..383d517a47501648219b327c80f47df40d9fccdb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1568.c @@ -0,0 +1,52 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testtrace.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret; + CURL *hnd; + curl_global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_HEADER, 1L); + curl_easy_setopt(hnd, CURLOPT_USERPWD, "testuser:testpass"); + curl_easy_setopt(hnd, CURLOPT_USERAGENT, "lib1568"); + curl_easy_setopt(hnd, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST); + curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); + curl_easy_setopt(hnd, CURLOPT_PORT, strtol(libtest_arg2, NULL, 10)); + + ret = curl_easy_perform(hnd); + + curl_easy_cleanup(hnd); + hnd = NULL; + + curl_global_cleanup(); + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1569.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1569.c new file mode 100644 index 0000000000000000000000000000000000000000..767d8816822bd326503be1bd6d7a3c7f6907102f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1569.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "testtrace.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *hnd; + global_init(CURL_GLOBAL_ALL); + + easy_init(hnd); + easy_setopt(hnd, CURLOPT_URL, URL); + easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + easy_setopt(hnd, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(hnd); + if(res) + goto test_cleanup; + + curl_easy_setopt(hnd, CURLOPT_URL, libtest_arg2); + res = curl_easy_perform(hnd); + +test_cleanup: + curl_easy_cleanup(hnd); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1591.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1591.c new file mode 100644 index 0000000000000000000000000000000000000000..c0200d5429b2f73403742c47ecdfdbb2d9d78358 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1591.c @@ -0,0 +1,120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 unit test PUT http data over proxy. Proxy header will be different + * from server http header + */ + +#include "test.h" +#include +#include "memdebug.h" + +static char testdata[] = "Hello Cloud!\r\n"; +static size_t consumed = 0; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t amount = nmemb * size; /* Total bytes curl wants */ + + if(consumed == strlen(testdata)) { + return 0; + } + + if(amount > strlen(testdata)-consumed) { + amount = strlen(testdata); + } + + consumed += amount; + (void)stream; + memcpy(ptr, testdata, amount); + return amount; +} + +/* + * carefully not leak memory on OOM + */ +static int trailers_callback(struct curl_slist **list, void *userdata) +{ + struct curl_slist *nlist = NULL; + struct curl_slist *nlist2 = NULL; + (void)userdata; + nlist = curl_slist_append(*list, "my-super-awesome-trailer: trail1"); + if(nlist) + nlist2 = curl_slist_append(nlist, "my-other-awesome-trailer: trail2"); + if(nlist2) { + *list = nlist2; + return CURL_TRAILERFUNC_OK; + } + else { + curl_slist_free_all(nlist); + return CURL_TRAILERFUNC_ABORT; + } +} + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http and proxy header list */ + struct curl_slist *hhl = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "Trailer: my-super-awesome-trailer," + " my-other-awesome-trailer"); + if(!hhl) { + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_TRAILERFUNCTION, trailers_callback); + test_setopt(curl, CURLOPT_TRAILERDATA, NULL); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(hhl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1592.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1592.c new file mode 100644 index 0000000000000000000000000000000000000000..ebfcf74b5c132f3fa0819f52359e120cefa75774 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1592.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 + * + ***************************************************************************/ +/* + * See https://github.com/curl/curl/issues/3371 + * + * This test case checks whether curl_multi_remove_handle() cancels + * asynchronous DNS resolvers without blocking where possible. Obviously, it + * only tests whichever resolver cURL is actually built with. + */ + +/* We're willing to wait a very generous two seconds for the removal. This is + as low as we can go while still easily supporting SIGALRM timing for the + non-threaded blocking resolver. It doesn't matter that much because when + the test passes, we never wait this long. We set it much higher to avoid + issues when running on overloaded CI machines. */ +#define TEST_HANG_TIMEOUT 60 * 1000 + +#include "test.h" +#include "testutil.h" + +#include + +CURLcode test(char *URL) +{ + int stillRunning; + CURLM *multiHandle = NULL; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + CURLMcode mres; + int timeout; + + global_init(CURL_GLOBAL_ALL); + + multi_init(multiHandle); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_URL, URL); + + /* Set a DNS server that hopefully will not respond when using c-ares. */ + if(curl_easy_setopt(curl, CURLOPT_DNS_SERVERS, "0.0.0.0") == CURLE_OK) + /* Since we could set the DNS server, presume we are working with a + resolver that can be cancelled (i.e. c-ares). Thus, + curl_multi_remove_handle() should not block even when the resolver + request is outstanding. So, set a request timeout _longer_ than the + test hang timeout so we will fail if the handle removal call incorrectly + blocks. */ + timeout = TEST_HANG_TIMEOUT * 2; + else { + /* If we can't set the DNS server, presume that we are configured to use a + resolver that can't be cancelled (i.e. the threaded resolver or the + non-threaded blocking resolver). So, we just test that the + curl_multi_remove_handle() call does finish well within our test + timeout. + + But, it is very unlikely that the resolver request will take any time at + all because we haven't been able to configure the resolver to use an + non-responsive DNS server. At least we exercise the flow. + */ + fprintf(stderr, + "CURLOPT_DNS_SERVERS not supported; " + "assuming curl_multi_remove_handle() will block\n"); + timeout = TEST_HANG_TIMEOUT / 2; + } + + /* Setting a timeout on the request should ensure that even if we have to + wait for the resolver during curl_multi_remove_handle(), it won't take + longer than this, because the resolver request inherits its timeout from + this. */ + easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout); + + multi_add_handle(multiHandle, curl); + + /* This should move the handle from INIT => CONNECT => WAITRESOLVE. */ + fprintf(stderr, "curl_multi_perform()...\n"); + multi_perform(multiHandle, &stillRunning); + fprintf(stderr, "curl_multi_perform() succeeded\n"); + + /* Start measuring how long it takes to remove the handle. */ + fprintf(stderr, "curl_multi_remove_handle()...\n"); + start_test_timing(); + mres = curl_multi_remove_handle(multiHandle, curl); + if(mres) { + fprintf(stderr, "curl_multi_remove_handle() failed, with code %d\n", mres); + res = TEST_ERR_MULTI; + goto test_cleanup; + } + fprintf(stderr, "curl_multi_remove_handle() succeeded\n"); + + /* Fail the test if it took too long to remove. This happens after the fact, + and says "it seems that it would have run forever", which isn't true, but + it's close enough, and simple to do. */ + abort_on_test_timeout(); + +test_cleanup: + curl_easy_cleanup(curl); + curl_multi_cleanup(multiHandle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1593.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1593.c new file mode 100644 index 0000000000000000000000000000000000000000..f5239fda4b7a84b6371eef223d3ef632e2c2817c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1593.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 + * + ***************************************************************************/ + +/* Test suppressing the If-Modified-Since header */ + +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + struct curl_slist *header = NULL; + long unmet; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_TIMECONDITION, (long)CURL_TIMECOND_IFMODSINCE); + /* Some TIMEVALUE; it doesn't matter. */ + easy_setopt(curl, CURLOPT_TIMEVALUE, 1566210680L); + + header = curl_slist_append(NULL, "If-Modified-Since:"); + if(!header) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + easy_setopt(curl, CURLOPT_HTTPHEADER, header); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* Confirm that the condition checking still worked, even though we + * suppressed the actual header. + * The server returns 304, which means the condition is "unmet". + */ + + res = curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &unmet); + if(res) + goto test_cleanup; + + if(unmet != 1L) { + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_slist_free_all(header); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1594.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1594.c new file mode 100644 index 0000000000000000000000000000000000000000..bf25ffbeb50a4309034514a4a9656c773d2a0b53 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1594.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 + * + ***************************************************************************/ + +/* Testing Retry-After header parser */ + +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + struct curl_slist *header = NULL; + curl_off_t retry; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + res = curl_easy_getinfo(curl, CURLINFO_RETRY_AFTER, &retry); + if(res) + goto test_cleanup; + +#ifdef LIB1596 + /* we get a relative number of seconds, so add the number of seconds + we're at to make it a somewhat stable number. Then remove accuracy. */ + retry += time(NULL); + retry /= 10000; +#endif + printf("Retry-After %" CURL_FORMAT_CURL_OFF_T "\n", retry); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_slist_free_all(header); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1597.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1597.c new file mode 100644 index 0000000000000000000000000000000000000000..fa09e71d6cb398734ac07324650eee6e20533f20 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1597.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 + * + ***************************************************************************/ + +/* Testing CURLOPT_PROTOCOLS_STR */ + +#include "test.h" + +#include "memdebug.h" + +struct pair { + const char *in; + CURLcode *exp; +}; + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_OK; + CURLcode result = CURLE_OK; + curl_version_info_data *curlinfo; + const char *const *proto; + int n; + int i; + static CURLcode ok = CURLE_OK; + static CURLcode bad = CURLE_BAD_FUNCTION_ARGUMENT; + static CURLcode unsup = CURLE_UNSUPPORTED_PROTOCOL; + static CURLcode httpcode = CURLE_UNSUPPORTED_PROTOCOL; + static CURLcode httpscode = CURLE_UNSUPPORTED_PROTOCOL; + static char protolist[1024]; + + static const struct pair prots[] = { + {"goobar", &unsup}, + {"http ", &unsup}, + {" http", &unsup}, + {"http", &httpcode}, + {"http,", &httpcode}, + {"https,", &httpscode}, + {"https,http", &httpscode}, + {"http,http", &httpcode}, + {"HTTP,HTTP", &httpcode}, + {",HTTP,HTTP", &httpcode}, + {"http,http,ft", &unsup}, + {"", &bad}, + {",,", &bad}, + {protolist, &ok}, + {"all", &ok}, + {NULL, NULL}, + }; + (void)URL; + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + /* Get enabled protocols.*/ + curlinfo = curl_version_info(CURLVERSION_NOW); + if(!curlinfo) { + fputs("curl_version_info failed\n", stderr); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + + n = 0; + for(proto = curlinfo->protocols; *proto; proto++) { + if((size_t) n >= sizeof(protolist)) { + puts("protolist buffer too small\n"); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + n += msnprintf(protolist + n, sizeof(protolist) - n, ",%s", *proto); + if(curl_strequal(*proto, "http")) + httpcode = CURLE_OK; + if(curl_strequal(*proto, "https")) + httpscode = CURLE_OK; + } + + /* Run the tests. */ + for(i = 0; prots[i].in; i++) { + result = curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, prots[i].in); + if(result != *prots[i].exp) { + printf("unexpectedly '%s' returned %d\n", prots[i].in, result); + break; + } + } + printf("Tested %u strings\n", i); + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return result; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1598.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1598.c new file mode 100644 index 0000000000000000000000000000000000000000..904ba65b0ed85745fa7e2208dcd5f3dd752275b1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1598.c @@ -0,0 +1,107 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 unit test PUT http data over proxy. Proxy header will be different + * from server http header + */ + +#include "test.h" +#include +#include "memdebug.h" + +/* + * carefully not leak memory on OOM + */ +static int trailers_callback(struct curl_slist **list, void *userdata) +{ + struct curl_slist *nlist = NULL; + struct curl_slist *nlist2 = NULL; + (void)userdata; + nlist = curl_slist_append(*list, "my-super-awesome-trailer: trail1"); + if(nlist) + nlist2 = curl_slist_append(nlist, "my-other-awesome-trailer: trail2"); + if(nlist2) { + *list = nlist2; + return CURL_TRAILERFUNC_OK; + } + else { + curl_slist_free_all(nlist); + return CURL_TRAILERFUNC_ABORT; + } +} + +static const char *post_data = "xxx=yyy&aaa=bbbbb"; + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_FAILED_INIT; + /* http and proxy header list */ + struct curl_slist *hhl = NULL, *list; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + hhl = curl_slist_append(hhl, "Trailer: my-super-awesome-trailer," + " my-other-awesome-trailer"); + if(!hhl) + goto test_cleanup; + if(hhl) { + list = curl_slist_append(hhl, "Transfer-Encoding: chunked"); + if(!list) + goto test_cleanup; + hhl = list; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HTTPHEADER, hhl); + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(post_data)); + test_setopt(curl, CURLOPT_POSTFIELDS, post_data); + test_setopt(curl, CURLOPT_TRAILERFUNCTION, trailers_callback); + test_setopt(curl, CURLOPT_TRAILERDATA, NULL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(hhl); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1662.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1662.c new file mode 100644 index 0000000000000000000000000000000000000000..1e9e2b061754abe294c9769206c95f0e9c655148 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1662.c @@ -0,0 +1,90 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +static char testdata[]="mooaaa"; + +struct WriteThis { + size_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + size_t len = strlen(testdata); + + if(size*nmemb < len) + return 0; + + if(pooh->sizeleft) { + memcpy(ptr, testdata, strlen(testdata)); + pooh->sizeleft = 0; + return len; + } + + return 0; /* no more data left to deliver */ +} + + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *hnd; + curl_mime *mime1; + curl_mimepart *part1; + struct WriteThis pooh = { 1 }; + + mime1 = NULL; + + global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + if(hnd) { + curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L); + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L); + mime1 = curl_mime_init(hnd); + if(mime1) { + part1 = curl_mime_addpart(mime1); + curl_mime_data_cb(part1, -1, read_callback, NULL, NULL, &pooh); + curl_mime_filename(part1, "poetry.txt"); + curl_mime_name(part1, "content"); + curl_easy_setopt(hnd, CURLOPT_MIMEPOST, mime1); + curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/2000"); + curl_easy_setopt(hnd, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L); + curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, + (long)CURL_HTTP_VERSION_2TLS); + curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(hnd, CURLOPT_FTP_SKIP_PASV_IP, 1L); + curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L); + res = curl_easy_perform(hnd); + } + } + + curl_easy_cleanup(hnd); + curl_mime_free(mime1); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1900.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1900.c new file mode 100644 index 0000000000000000000000000000000000000000..1b26e7b9867842fa66e44148d83c0199d5ce3c35 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1900.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *hnd = NULL; + CURL *second = NULL; + + global_init(CURL_GLOBAL_ALL); + + easy_init(hnd); + easy_setopt(hnd, CURLOPT_URL, URL); + easy_setopt(hnd, CURLOPT_HSTS, "first-hsts.txt"); + easy_setopt(hnd, CURLOPT_HSTS, "second-hsts.txt"); + + second = curl_easy_duphandle(hnd); + + curl_easy_cleanup(hnd); + curl_easy_cleanup(second); + curl_global_cleanup(); + return CURLE_OK; + +test_cleanup: + curl_easy_cleanup(hnd); + curl_easy_cleanup(second); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1901.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1901.c new file mode 100644 index 0000000000000000000000000000000000000000..314f0354d8ffd16169f9b4589961d61c9401efef --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1901.c @@ -0,0 +1,95 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + + + +static const char *chunks[]={ + "one", + "two", + "three", + "four", + NULL +}; + + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + static int ix = 0; + (void)size; + (void)nmemb; + (void)stream; + if(chunks[ix]) { + size_t len = strlen(chunks[ix]); + strcpy(ptr, chunks[ix]); + ix++; + return len; + } + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *chunk = NULL; + + curl_global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + /* deliberately setting the size - to a wrong value to make sure libcurl + ignores it */ + easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 4L); + easy_setopt(curl, CURLOPT_POSTFIELDS, NULL); + easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + easy_setopt(curl, CURLOPT_POST, 1L); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_1_1); + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_READDATA, NULL); + + chunk = curl_slist_append(chunk, "Expect:"); + if(chunk) { + struct curl_slist *n = + curl_slist_append(chunk, "Transfer-Encoding: chunked"); + if(n) + chunk = n; + if(n) + easy_setopt(curl, CURLOPT_HTTPHEADER, n); + } + + res = curl_easy_perform(curl); + } +test_cleanup: + curl_easy_cleanup(curl); + curl_slist_free_all(chunk); + + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1903.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1903.c new file mode 100644 index 0000000000000000000000000000000000000000..0ffbb14adc2de3cdbb3b716d33cae5f001fbf5ea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1903.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "timediff.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *ch = NULL; + global_init(CURL_GLOBAL_ALL); + + easy_init(ch); + + easy_setopt(ch, CURLOPT_URL, URL); + easy_setopt(ch, CURLOPT_COOKIEFILE, libtest_arg2); + res = curl_easy_perform(ch); + if(res) + goto test_cleanup; + + curl_easy_reset(ch); + + easy_setopt(ch, CURLOPT_URL, URL); + easy_setopt(ch, CURLOPT_COOKIEFILE, libtest_arg2); + easy_setopt(ch, CURLOPT_COOKIEJAR, libtest_arg3); + res = curl_easy_perform(ch); + +test_cleanup: + curl_easy_cleanup(ch); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1905.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1905.c new file mode 100644 index 0000000000000000000000000000000000000000..bba0400cbbcc45362a64e10d2f724c6305a88392 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1905.c @@ -0,0 +1,100 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "timediff.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLSH *sh = NULL; + CURL *ch = NULL; + int unfinished; + CURLM *cm; + + curl_global_init(CURL_GLOBAL_ALL); + + cm = curl_multi_init(); + if(!cm) { + curl_global_cleanup(); + return (CURLcode)1; + } + sh = curl_share_init(); + if(!sh) + goto cleanup; + + curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + + ch = curl_easy_init(); + if(!ch) + goto cleanup; + + curl_easy_setopt(ch, CURLOPT_SHARE, sh); + curl_easy_setopt(ch, CURLOPT_URL, URL); + curl_easy_setopt(ch, CURLOPT_COOKIEFILE, libtest_arg2); + curl_easy_setopt(ch, CURLOPT_COOKIEJAR, libtest_arg2); + + curl_multi_add_handle(cm, ch); + + unfinished = 1; + while(unfinished) { + int MAX = 0; + long max_tout; + fd_set R, W, E; + struct timeval timeout; + + FD_ZERO(&R); + FD_ZERO(&W); + FD_ZERO(&E); + curl_multi_perform(cm, &unfinished); + + curl_multi_fdset(cm, &R, &W, &E, &MAX); + curl_multi_timeout(cm, &max_tout); + + if(max_tout > 0) { + curlx_mstotv(&timeout, max_tout); + } + else { + timeout.tv_sec = 0; + timeout.tv_usec = 1000; + } + + select(MAX + 1, &R, &W, &E, &timeout); + } + + curl_easy_setopt(ch, CURLOPT_COOKIELIST, "FLUSH"); + curl_easy_setopt(ch, CURLOPT_SHARE, NULL); + + curl_multi_remove_handle(cm, ch); +cleanup: + curl_easy_cleanup(ch); + curl_share_cleanup(sh); + curl_multi_cleanup(cm); + curl_global_cleanup(); + + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1906.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1906.c new file mode 100644 index 0000000000000000000000000000000000000000..fded3bfb17d072d24d35757299e2070955f88c1b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1906.c @@ -0,0 +1,85 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + char *url_after = NULL; + CURLU *curlu = curl_url(); + char error_buffer[CURL_ERROR_SIZE] = ""; + CURL *curl; + + easy_init(curl); + + curl_url_set(curlu, CURLUPART_URL, URL, CURLU_DEFAULT_SCHEME); + easy_setopt(curl, CURLOPT_CURLU, curlu); + easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + /* msys2 times out instead of CURLE_COULDNT_CONNECT, so make it faster */ + easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 5000L); + /* set a port number that makes this request fail */ + easy_setopt(curl, CURLOPT_PORT, 1L); + res = curl_easy_perform(curl); + if(res != CURLE_COULDNT_CONNECT && res != CURLE_OPERATION_TIMEDOUT) { + fprintf(stderr, "failure expected, " + "curl_easy_perform returned %d: <%s>, <%s>\n", + res, curl_easy_strerror(res), error_buffer); + if(res == CURLE_OK) + res = TEST_ERR_MAJOR_BAD; /* force an error return */ + goto test_cleanup; + } + res = CURLE_OK; /* reset for next use */ + + /* print the used url */ + curl_url_get(curlu, CURLUPART_URL, &url_after, 0); + fprintf(stderr, "curlu now: <%s>\n", url_after); + curl_free(url_after); + url_after = NULL; + + /* now reset CURLOP_PORT to go back to originally set port number */ + easy_setopt(curl, CURLOPT_PORT, 0L); + + res = curl_easy_perform(curl); + if(res) + fprintf(stderr, "success expected, " + "curl_easy_perform returned %d: <%s>, <%s>\n", + res, curl_easy_strerror(res), error_buffer); + + /* print url */ + curl_url_get(curlu, CURLUPART_URL, &url_after, 0); + fprintf(stderr, "curlu now: <%s>\n", url_after); + +test_cleanup: + curl_free(url_after); + curl_easy_cleanup(curl); + curl_url_cleanup(curlu); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1907.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1907.c new file mode 100644 index 0000000000000000000000000000000000000000..82026f23cd62bf6b352e3a1ddba365b38656c2c4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1907.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + char *url_after; + CURL *curl; + CURLcode res = CURLE_OK; + char error_buffer[CURL_ERROR_SIZE] = ""; + + curl_global_init(CURL_GLOBAL_DEFAULT); + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + res = curl_easy_perform(curl); + if(!res) + fprintf(stderr, "failure expected, " + "curl_easy_perform returned %ld: <%s>, <%s>\n", + (long) res, curl_easy_strerror(res), error_buffer); + + /* print the used url */ + if(!curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url_after)) + printf("Effective URL: %s\n", url_after); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1908.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1908.c new file mode 100644 index 0000000000000000000000000000000000000000..3c7187c5bc0884469583c65c25c681a917bdca5c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1908.c @@ -0,0 +1,64 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret = CURLE_OK; + CURL *hnd; + start_test_timing(); + + curl_global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + if(hnd) { + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L); + curl_easy_setopt(hnd, CURLOPT_ALTSVC, libtest_arg2); + ret = curl_easy_perform(hnd); + + if(!ret) { + /* make a copy and check that this also has alt-svc activated */ + CURL *also = curl_easy_duphandle(hnd); + if(also) { + ret = curl_easy_perform(also); + /* we close the second handle first, which makes it store the alt-svc + file only to get overwritten when the next handle is closed! */ + curl_easy_cleanup(also); + } + } + + curl_easy_reset(hnd); + + /* using the same file name for the alt-svc cache, this clobbers the + content just written from the 'also' handle */ + curl_easy_cleanup(hnd); + } + curl_global_cleanup(); + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1910.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1910.c new file mode 100644 index 0000000000000000000000000000000000000000..9d3f1b3ab0ed6dff3939882a138071579b5e67c7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1910.c @@ -0,0 +1,49 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret = CURLE_OK; + CURL *hnd; + start_test_timing(); + + curl_global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + if(hnd) { + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L); + curl_easy_setopt(hnd, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(hnd, CURLOPT_USERPWD, "user\nname:pass\nword"); + ret = curl_easy_perform(hnd); + curl_easy_cleanup(hnd); + } + curl_global_cleanup(); + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1911.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1911.c new file mode 100644 index 0000000000000000000000000000000000000000..0fd62a8b92ae83b1205303078968ddff8bab9adc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1911.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +/* The maximum string length limit (CURL_MAX_INPUT_LENGTH) is an internal + define not publicly exposed so we set our own */ +#define MAX_INPUT_LENGTH 8000000 + +static char testbuf[MAX_INPUT_LENGTH + 2]; + +CURLcode test(char *URL) +{ + const struct curl_easyoption *o; + CURL *easy; + int error = 0; + (void)URL; + + curl_global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return (CURLcode)1; + } + + /* make it a null-terminated C string with just As */ + memset(testbuf, 'A', MAX_INPUT_LENGTH + 1); + testbuf[MAX_INPUT_LENGTH + 1] = 0; + + printf("string length: %d\n", (int)strlen(testbuf)); + + for(o = curl_easy_option_next(NULL); + o; + o = curl_easy_option_next(o)) { + if(o->type == CURLOT_STRING) { + CURLcode result; + /* + * Whitelist string options that are safe for abuse + */ + CURL_IGNORE_DEPRECATION( + switch(o->id) { + case CURLOPT_PROXY_TLSAUTH_TYPE: + case CURLOPT_TLSAUTH_TYPE: + case CURLOPT_RANDOM_FILE: + case CURLOPT_EGDSOCKET: + continue; + default: + /* check this */ + break; + } + ) + + /* This is a string. Make sure that passing in a string longer + CURL_MAX_INPUT_LENGTH returns an error */ + result = curl_easy_setopt(easy, o->id, testbuf); + switch(result) { + case CURLE_BAD_FUNCTION_ARGUMENT: /* the most normal */ + case CURLE_UNKNOWN_OPTION: /* left out from the build */ + case CURLE_NOT_BUILT_IN: /* not supported */ + case CURLE_UNSUPPORTED_PROTOCOL: /* detected by protocol2num() */ + break; + default: + /* all other return codes are unexpected */ + fprintf(stderr, "curl_easy_setopt(%s...) returned %d\n", + o->name, result); + error++; + break; + } + } + } + curl_easy_cleanup(easy); + curl_global_cleanup(); + return error == 0 ? CURLE_OK : TEST_ERR_FAILURE; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1912.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1912.c new file mode 100644 index 0000000000000000000000000000000000000000..b6667c004146f5e428fb34fa6081abc78096bf6d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1912.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define print_err(name, exp) \ + fprintf(stderr, "Type mismatch for CURLOPT_%s (expected %s)\n", name, exp); + +CURLcode test(char *URL) +{ +/* Only test if GCC typechecking is available */ + int error = 0; +#ifdef CURLINC_TYPECHECK_GCC_H + const struct curl_easyoption *o; + for(o = curl_easy_option_next(NULL); + o; + o = curl_easy_option_next(o)) { + CURL_IGNORE_DEPRECATION( + /* Test for mismatch OR missing typecheck macros */ + if(curlcheck_long_option(o->id) != + (o->type == CURLOT_LONG || o->type == CURLOT_VALUES)) { + print_err(o->name, "CURLOT_LONG or CURLOT_VALUES"); + error++; + } + if(curlcheck_off_t_option(o->id) != (o->type == CURLOT_OFF_T)) { + print_err(o->name, "CURLOT_OFF_T"); + error++; + } + if(curlcheck_string_option(o->id) != (o->type == CURLOT_STRING)) { + print_err(o->name, "CURLOT_STRING"); + error++; + } + if(curlcheck_slist_option(o->id) != (o->type == CURLOT_SLIST)) { + print_err(o->name, "CURLOT_SLIST"); + error++; + } + if(curlcheck_cb_data_option(o->id) != (o->type == CURLOT_CBPTR)) { + print_err(o->name, "CURLOT_CBPTR"); + error++; + } + /* From here: only test that the type matches if macro is known */ + if(curlcheck_write_cb_option(o->id) && (o->type != CURLOT_FUNCTION)) { + print_err(o->name, "CURLOT_FUNCTION"); + error++; + } + if(curlcheck_conv_cb_option(o->id) && (o->type != CURLOT_FUNCTION)) { + print_err(o->name, "CURLOT_FUNCTION"); + error++; + } + if(curlcheck_postfields_option(o->id) && (o->type != CURLOT_OBJECT)) { + print_err(o->name, "CURLOT_OBJECT"); + error++; + } + /* Todo: no gcc typecheck for CURLOPTTYPE_BLOB types? */ + ) + } +#endif + (void)URL; + return error == 0 ? CURLE_OK : TEST_ERR_FAILURE; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1913.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1913.c new file mode 100644 index 0000000000000000000000000000000000000000..84684200574f4d78e91b1e4a296eb0e548151cea --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1913.c @@ -0,0 +1,50 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret = CURLE_OK; + CURL *hnd; + start_test_timing(); + + curl_global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + if(hnd) { + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_NOBODY, 1L); + if(libtest_arg2) + /* test1914 sets this extra arg */ + curl_easy_setopt(hnd, CURLOPT_FILETIME, 1L); + ret = curl_easy_perform(hnd); + curl_easy_cleanup(hnd); + } + curl_global_cleanup(); + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1915.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1915.c new file mode 100644 index 0000000000000000000000000000000000000000..ead6713a0e840d06ab148fe6f03a11165c9b6307 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1915.c @@ -0,0 +1,150 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +struct entry { + const char *name; + const char *exp; +}; + +static const struct entry preload_hosts[] = { +#if (SIZEOF_TIME_T < 5) + { "1.example.com", "20370320 01:02:03" }, + { "2.example.com", "20370320 03:02:01" }, + { "3.example.com", "20370319 01:02:03" }, +#else + { "1.example.com", "25250320 01:02:03" }, + { "2.example.com", "25250320 03:02:01" }, + { "3.example.com", "25250319 01:02:03" }, +#endif + { "4.example.com", "" }, + { NULL, NULL } /* end of list marker */ +}; + +struct state { + int index; +}; + +/* "read" is from the point of the library, it wants data from us */ +static CURLSTScode hstsread(CURL *easy, struct curl_hstsentry *e, + void *userp) +{ + const char *host; + const char *expire; + struct state *s = (struct state *)userp; + (void)easy; + host = preload_hosts[s->index].name; + expire = preload_hosts[s->index++].exp; + + if(host && (strlen(host) < e->namelen)) { + strcpy(e->name, host); + e->includeSubDomains = FALSE; + strcpy(e->expire, expire); + fprintf(stderr, "add '%s'\n", host); + } + else + return CURLSTS_DONE; + return CURLSTS_OK; +} + +/* verify error from callback */ +static CURLSTScode hstsreadfail(CURL *easy, struct curl_hstsentry *e, + void *userp) +{ + (void)easy; + (void)e; + (void)userp; + return CURLSTS_FAIL; +} + +/* check that we get the hosts back in the save */ +static CURLSTScode hstswrite(CURL *easy, struct curl_hstsentry *e, + struct curl_index *i, void *userp) +{ + (void)easy; + (void)userp; + printf("[%zu/%zu] %s %s\n", i->index, i->total, e->name, e->expire); + return CURLSTS_OK; +} + +/* + * Read/write HSTS cache entries via callback. + */ + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *hnd; + struct state st = {0}; + + global_init(CURL_GLOBAL_ALL); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + + easy_init(hnd); + easy_setopt(hnd, CURLOPT_URL, URL); + easy_setopt(hnd, CURLOPT_CONNECTTIMEOUT, 1L); + easy_setopt(hnd, CURLOPT_HSTSREADFUNCTION, hstsread); + easy_setopt(hnd, CURLOPT_HSTSREADDATA, &st); + easy_setopt(hnd, CURLOPT_HSTSWRITEFUNCTION, hstswrite); + easy_setopt(hnd, CURLOPT_HSTSWRITEDATA, &st); + easy_setopt(hnd, CURLOPT_HSTS_CTRL, CURLHSTS_ENABLE); + easy_setopt(hnd, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + res = curl_easy_perform(hnd); + curl_easy_cleanup(hnd); + hnd = NULL; + if(res == CURLE_OPERATION_TIMEDOUT) /* we expect that on Windows */ + res = CURLE_COULDNT_CONNECT; + printf("First request returned %d\n", res); + res = CURLE_OK; + + easy_init(hnd); + easy_setopt(hnd, CURLOPT_URL, URL); + easy_setopt(hnd, CURLOPT_CONNECTTIMEOUT, 1L); + easy_setopt(hnd, CURLOPT_HSTSREADFUNCTION, hstsreadfail); + easy_setopt(hnd, CURLOPT_HSTSREADDATA, &st); + easy_setopt(hnd, CURLOPT_HSTSWRITEFUNCTION, hstswrite); + easy_setopt(hnd, CURLOPT_HSTSWRITEDATA, &st); + easy_setopt(hnd, CURLOPT_HSTS_CTRL, CURLHSTS_ENABLE); + easy_setopt(hnd, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(hnd, CURLOPT_VERBOSE, 1L); + res = curl_easy_perform(hnd); + curl_easy_cleanup(hnd); + hnd = NULL; + printf("Second request returned %d\n", res); + +test_cleanup: + curl_easy_cleanup(hnd); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1916.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1916.c new file mode 100644 index 0000000000000000000000000000000000000000..36a938b61d99ef5da41c70c62479e404af8c606a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1916.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); +#ifdef LIB1917 + /* without any postfields set! */ + curl_easy_setopt(curl, CURLOPT_POST, 1L); +#else + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ""); +#endif + res = curl_easy_perform(curl); + if(res) { + printf("res: %d\n", res); + } + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1918.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1918.c new file mode 100644 index 0000000000000000000000000000000000000000..7eaf41bd4f03c3d314cf9ca70978b203470f53bc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1918.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + const struct curl_easyoption *o; + (void)URL; + + curl_global_init(CURL_GLOBAL_ALL); + + for(o = curl_easy_option_next(NULL); + o; + o = curl_easy_option_next(o)) { + const struct curl_easyoption *ename = + curl_easy_option_by_name(o->name); + const struct curl_easyoption *eid = + curl_easy_option_by_id(o->id); + + if(ename->id != o->id) { + printf("name lookup id %d doesn't match %d\n", + ename->id, o->id); + } + else if(eid->id != o->id) { + printf("ID lookup %d doesn't match %d\n", + ename->id, o->id); + } + } + curl_global_cleanup(); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1919.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1919.c new file mode 100644 index 0000000000000000000000000000000000000000..68ce7a194bcc808baf6f8526a0b60852e4fb79c0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1919.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl; + int i; + + global_init(CURL_GLOBAL_ALL); + easy_init(curl); + easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); + easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, + "c4e448d652a961fda0ab64f882c8c161d5985f805d45d80c9ddca1"); + easy_setopt(curl, CURLOPT_SASL_AUTHZID, + "c4e448d652a961fda0ab64f882c8c161d5985f805d45d80c9ddca2"); + easy_setopt(curl, CURLOPT_URL, URL); + + for(i = 0; i < 2; i++) { + /* the second request needs to do connection reuse */ + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1933.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1933.c new file mode 100644 index 0000000000000000000000000000000000000000..554756c3ca4b52c390dca8932fcadc6fa0dbe289 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1933.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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1934.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1934.c new file mode 100644 index 0000000000000000000000000000000000000000..6257759fe33084eb04a5f553fe7b2447568e7c69 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1934.c @@ -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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx:yyy"); + test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1935.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1935.c new file mode 100644 index 0000000000000000000000000000000000000000..8800916c8696762911ac440471813bd6eaf99491 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1935.c @@ -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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx:yyy:rrr"); + test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1936.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1936.c new file mode 100644 index 0000000000000000000000000000000000000000..c136fc0a25d989f5511576235307bc2801e8d6e3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1936.c @@ -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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx:yyy:rrr:sss"); + test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1937.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1937.c new file mode 100644 index 0000000000000000000000000000000000000000..61f71127b4861837754db8f7e356498c3b22071a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1937.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_POST, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "provider1:provider2:region:service"); + test_setopt(curl, CURLOPT_USERPWD, "keyId:SecretKey"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + test_setopt(curl, CURLOPT_POSTFIELDS, "postData"); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1938.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1938.c new file mode 100644 index 0000000000000000000000000000000000000000..02ab6cc20192ca9df7efca606c66b7bb3d4b3751 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1938.c @@ -0,0 +1,74 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL; + unsigned char data[] = {0x70, 0x6f, 0x73, 0x74, 0, 0x44, 0x61, 0x74, 0x61}; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_POST, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "provider1:provider2:region:service"); + test_setopt(curl, CURLOPT_USERPWD, "keyId:SecretKey"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + test_setopt(curl, CURLOPT_POSTFIELDS, data); + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)sizeof(data)); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1939.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1939.c new file mode 100644 index 0000000000000000000000000000000000000000..c7365e5fec5d7ef9f232d6584f0621eda39f6485 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1939.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLM *multi; + CURL *easy; + int running_handles; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + multi = curl_multi_init(); + if(multi) { + easy = curl_easy_init(); + if(easy) { + CURLcode c; + CURLMcode m; + + /* Crash only happens when using HTTPS */ + c = curl_easy_setopt(easy, CURLOPT_URL, URL); + if(!c) + /* Any old HTTP tunneling proxy will do here */ + c = curl_easy_setopt(easy, CURLOPT_PROXY, libtest_arg2); + + if(!c) { + + /* We're going to drive the transfer using multi interface here, + because we want to stop during the middle. */ + m = curl_multi_add_handle(multi, easy); + + if(!m) + /* Run the multi handle once, just enough to start establishing an + HTTPS connection. */ + m = curl_multi_perform(multi, &running_handles); + + if(m) + fprintf(stderr, "curl_multi_perform failed\n"); + } + /* Close the easy handle *before* the multi handle. Doing it the other + way around avoids the issue. */ + curl_easy_cleanup(easy); + } + curl_multi_cleanup(multi); /* double-free happens here */ + } + curl_global_cleanup(); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1940.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1940.c new file mode 100644 index 0000000000000000000000000000000000000000..e8dbcdd13f95d65dc295f06297615ba3594d2aaf --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1940.c @@ -0,0 +1,120 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +static const char *testdata[]={ + "daTE", + "Server", + "content-type", + "content-length", + "location", + "set-cookie", + "silly-thing", + "fold", + "blank", + "Blank2", + NULL +}; + +#ifdef LIB1946 +#define HEADER_REQUEST 0 +#else +#define HEADER_REQUEST -1 +#endif + +static void showem(CURL *easy, unsigned int type) +{ + int i; + struct curl_header *header; + for(i = 0; testdata[i]; i++) { + if(CURLHE_OK == curl_easy_header(easy, testdata[i], 0, type, + HEADER_REQUEST, &header)) { + if(header->amount > 1) { + /* more than one, iterate over them */ + size_t index = 0; + size_t amount = header->amount; + do { + printf("- %s == %s (%u/%u)\n", header->name, header->value, + (int)index, (int)amount); + + if(++index == amount) + break; + if(CURLHE_OK != curl_easy_header(easy, testdata[i], index, type, + HEADER_REQUEST, &header)) + break; + } while(1); + } + else { + /* only one of this */ + printf(" %s == %s\n", header->name, header->value); + } + } + } +} + +static size_t write_cb(char *data, size_t n, size_t l, void *userp) +{ + /* take care of the data here, ignored in this example */ + (void)data; + (void)userp; + return n*l; +} +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_DEFAULT); + easy_init(easy); + easy_setopt(easy, CURLOPT_URL, URL); + easy_setopt(easy, CURLOPT_VERBOSE, 1L); + easy_setopt(easy, CURLOPT_FOLLOWLOCATION, 1L); + /* ignores any content */ + easy_setopt(easy, CURLOPT_WRITEFUNCTION, write_cb); + + /* if there's a proxy set, use it */ + if(libtest_arg2 && *libtest_arg2) { + easy_setopt(easy, CURLOPT_PROXY, libtest_arg2); + easy_setopt(easy, CURLOPT_HTTPPROXYTUNNEL, 1L); + } + res = curl_easy_perform(easy); + if(res) + goto test_cleanup; + + showem(easy, CURLH_HEADER); + if(libtest_arg2 && *libtest_arg2) { + /* now show connect headers only */ + showem(easy, CURLH_CONNECT); + } + showem(easy, CURLH_1XX); + showem(easy, CURLH_TRAILER); + +test_cleanup: + curl_easy_cleanup(easy); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1945.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1945.c new file mode 100644 index 0000000000000000000000000000000000000000..8cbb01ec6ce16760dbf2f57699adbb6f274af141 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1945.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.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 "test.h" + +#include "memdebug.h" + +#ifdef _MSC_VER +/* warning C4706: assignment within conditional expression */ +#pragma warning(disable:4706) +#endif +static void showem(CURL *easy, unsigned int type) +{ + struct curl_header *header = NULL; + struct curl_header *prev = NULL; + + while((header = curl_easy_nextheader(easy, type, 0, prev))) { + printf(" %s == %s (%u/%u)\n", header->name, header->value, + (int)header->index, (int)header->amount); + prev = header; + } +} + +static size_t write_cb(char *data, size_t n, size_t l, void *userp) +{ + /* take care of the data here, ignored in this example */ + (void)data; + (void)userp; + return n*l; +} +CURLcode test(char *URL) +{ + CURL *easy; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_DEFAULT); + + easy_init(easy); + curl_easy_setopt(easy, CURLOPT_URL, URL); + curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(easy, CURLOPT_FOLLOWLOCATION, 1L); + /* ignores any content */ + curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, write_cb); + + /* if there's a proxy set, use it */ + if(libtest_arg2 && *libtest_arg2) { + curl_easy_setopt(easy, CURLOPT_PROXY, libtest_arg2); + curl_easy_setopt(easy, CURLOPT_HTTPPROXYTUNNEL, 1L); + } + res = curl_easy_perform(easy); + if(res) { + printf("badness: %d\n", res); + } + showem(easy, CURLH_CONNECT|CURLH_HEADER|CURLH_TRAILER|CURLH_1XX); + +test_cleanup: + curl_easy_cleanup(easy); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1947.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1947.c new file mode 100644 index 0000000000000000000000000000000000000000..cd14e266196888048d09811dcdfcb43618264bd8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1947.c @@ -0,0 +1,92 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +static size_t writecb(char *data, size_t n, size_t l, void *userp) +{ + /* ignore the data */ + (void)data; + (void)userp; + return n*l; +} +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_header *h; + int count = 0; + unsigned int origins; + + global_init(CURL_GLOBAL_DEFAULT); + + easy_init(curl); + + /* perform a request that involves redirection */ + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecb); + easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + goto test_cleanup; + } + + /* count the number of requests by reading the first header of each + request. */ + origins = (CURLH_HEADER|CURLH_TRAILER|CURLH_CONNECT| + CURLH_1XX|CURLH_PSEUDO); + do { + h = curl_easy_nextheader(curl, origins, count, NULL); + if(h) + count++; + } while(h); + printf("count = %u\n", count); + + /* perform another request - without redirect */ + easy_setopt(curl, CURLOPT_URL, libtest_arg2); + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + goto test_cleanup; + } + + /* count the number of requests again. */ + count = 0; + do { + h = curl_easy_nextheader(curl, origins, count, NULL); + if(h) + count++; + } while(h); + printf("count = %u\n", count); + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1948.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1948.c new file mode 100644 index 0000000000000000000000000000000000000000..45c7f199bfca5149527f0cd0d8bb2ba90848f45d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1948.c @@ -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.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 "test.h" + +typedef struct +{ + char *buf; + size_t len; +} put_buffer; + +static size_t put_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + put_buffer *putdata = (put_buffer *)stream; + size_t totalsize = size * nmemb; + size_t tocopy = (putdata->len < totalsize) ? putdata->len : totalsize; + memcpy(ptr, putdata->buf, tocopy); + putdata->len -= tocopy; + putdata->buf += tocopy; + return tocopy; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + const char *testput = "This is test PUT data\n"; + put_buffer pbuf; + + curl_global_init(CURL_GLOBAL_DEFAULT); + + easy_init(curl); + + /* PUT */ + easy_setopt(curl, CURLOPT_UPLOAD, 1L); + easy_setopt(curl, CURLOPT_HEADER, 1L); + easy_setopt(curl, CURLOPT_READFUNCTION, put_callback); + pbuf.buf = (char *)testput; + pbuf.len = strlen(testput); + easy_setopt(curl, CURLOPT_READDATA, &pbuf); + easy_setopt(curl, CURLOPT_INFILESIZE, (long)strlen(testput)); + easy_setopt(curl, CURLOPT_URL, URL); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* POST */ + easy_setopt(curl, CURLOPT_POST, 1L); + easy_setopt(curl, CURLOPT_POSTFIELDS, testput); + easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(testput)); + res = curl_easy_perform(curl); + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1955.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1955.c new file mode 100644 index 0000000000000000000000000000000000000000..39b5754ad133c302aba83418652978e84e4bb281 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1955.c @@ -0,0 +1,90 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "test3: 1234"); + if(!list) + goto test_cleanup; + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + curl_slist_append(list, "Content-Type: application/json"); + + /* 'name;' user headers with no value are used to send an empty header in the + format 'name:' (note the semi-colon becomes a colon). this entry should + show in SignedHeaders without an additional semi-colon, as any other + header would. eg 'foo;test2;test3' and not 'foo;test2;;test3'. */ + curl_slist_append(list, "test2;"); + + /* 'name:' user headers with no value are used to signal an internal header + of that name should be removed and are not sent as a header. this entry + should not show in SignedHeaders. */ + curl_slist_append(list, "test1:"); + + /* 'name' user headers with no separator or value are invalid and ignored. + this entry should not show in SignedHeaders. */ + curl_slist_append(list, "test0"); + + curl_slist_append(list, "test_space: t\ts m\t end "); + curl_slist_append(list, "tesMixCase: MixCase"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1956.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1956.c new file mode 100644 index 0000000000000000000000000000000000000000..669e143931dc23209fff8e1a6669f5956b03205a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1956.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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + curl_slist_append(list, "X-Xxx-Content-Sha256: " + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1957.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1957.c new file mode 100644 index 0000000000000000000000000000000000000000..7cc35e42b6decb069247f2cd2a03d7576200a492 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1957.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + curl_slist_append(list, "X-Xxx-Content-Sha256: arbitrary"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1958.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1958.c new file mode 100644 index 0000000000000000000000000000000000000000..58b4ea79b17d38dbd7e1d2a654829b27a0f1c280 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1958.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + curl_slist_append(list, "X-Xxx-Content-Sha256: \tarbitrary "); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1959.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1959.c new file mode 100644 index 0000000000000000000000000000000000000000..1fbf26c0be50db9f696e6547591ce61186e2cac3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1959.c @@ -0,0 +1,74 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + curl_slist_append(list, "X-Xxx-Content-Sha256: " + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1960.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1960.c new file mode 100644 index 0000000000000000000000000000000000000000..020ee4ba69b4c599fc7ee038bf5fdec4fe73eab2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1960.c @@ -0,0 +1,149 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#ifdef HAVE_INET_PTON + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "memdebug.h" + +/* to prevent libcurl from closing our socket */ +static int closesocket_cb(void *clientp, curl_socket_t item) +{ + (void)clientp; + (void)item; + return 0; +} + +/* provide our own socket */ +static curl_socket_t socket_cb(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address) +{ + int s = *(int *)clientp; + (void)purpose; + (void)address; + return (curl_socket_t)s; +} + +/* tell libcurl the socket is connected */ +static int sockopt_cb(void *clientp, + curl_socket_t curlfd, + curlsocktype purpose) +{ + (void)clientp; + (void)curlfd; + (void)purpose; + return CURL_SOCKOPT_ALREADY_CONNECTED; +} + +/* Expected args: URL IP PORT */ +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = TEST_ERR_MAJOR_BAD; + int status; + curl_socket_t client_fd = CURL_SOCKET_BAD; + struct sockaddr_in serv_addr; + unsigned short port; + + if(!strcmp("check", URL)) + return CURLE_OK; /* no output makes it not skipped */ + + port = (unsigned short)atoi(libtest_arg3); + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* + * This code connects to the TCP port "manually" so that we then can hand + * over this socket as "already connected" to libcurl and make sure that + * this works. + */ + client_fd = socket(AF_INET, SOCK_STREAM, 0); + if(client_fd == CURL_SOCKET_BAD) { + fprintf(stderr, "socket creation error\n"); + goto test_cleanup; + } + + serv_addr.sin_family = AF_INET; + serv_addr.sin_port = htons(port); + + if(inet_pton(AF_INET, libtest_arg2, &serv_addr.sin_addr) <= 0) { + fprintf(stderr, "inet_pton failed\n"); + goto test_cleanup; + } + + status = connect(client_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); + if(status < 0) { + fprintf(stderr, "connection failed\n"); + goto test_cleanup; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, socket_cb); + test_setopt(curl, CURLOPT_OPENSOCKETDATA, &client_fd); + test_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_cb); + test_setopt(curl, CURLOPT_SOCKOPTDATA, NULL); + test_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, closesocket_cb); + test_setopt(curl, CURLOPT_CLOSESOCKETDATA, NULL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + +test_cleanup: + if(client_fd != CURL_SOCKET_BAD) + sclose(client_fd); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} +#else +CURLcode test(char *URL) +{ + (void)URL; + printf("lacks inet_pton\n"); + return CURLE_OK; +} +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1964.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1964.c new file mode 100644 index 0000000000000000000000000000000000000000..9e17f926c4c208ed48c588f2f1a02acf1f740f2a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1964.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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *connect_to = NULL; + struct curl_slist *list = NULL, *tmp; + + global_init(CURL_GLOBAL_ALL); + easy_init(curl); + + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_AWS_SIGV4, "xxx"); + easy_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + if(!connect_to) { + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + } + easy_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + list = curl_slist_append(list, "Content-Type: application/json"); + tmp = curl_slist_append(list, "X-Xxx-Date: 19700101T000000Z"); + if(!list || !tmp) { + res = CURLE_FAILED_INIT; + goto test_cleanup; + } + list = tmp; + easy_setopt(curl, CURLOPT_HTTPHEADER, list); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1970.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1970.c new file mode 100644 index 0000000000000000000000000000000000000000..f0b9d517bf737976533c0a941767e7723936fd21 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1970.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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_INFILESIZE, 0L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + test_setopt(curl, CURLOPT_HTTPHEADER, list); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1971.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1971.c new file mode 100644 index 0000000000000000000000000000000000000000..8f4be08b2a9e85a534ac3423fd0ba24eec4f3d27 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1971.c @@ -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.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 "test.h" + +#include "memdebug.h" + +static size_t read_callback(char *buffer, size_t size, size_t nitems, + void *userdata) +{ + (void)buffer; /* unused */ + (void)size; /* unused */ + (void)nitems; /* unused */ + (void)userdata; /* unused */ + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + test_setopt(curl, CURLOPT_HTTPHEADER, list); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1972.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1972.c new file mode 100644 index 0000000000000000000000000000000000000000..a51c45018bf2205c13749fad00ae15796e722aed --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1972.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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + curl_mime *mime = NULL; + curl_mimepart *part = NULL; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + mime = curl_mime_init(curl); + if(!mime) + goto test_cleanup; + part = curl_mime_addpart(mime); + if(!part) + goto test_cleanup; + curl_mime_name(part, "foo"); + curl_mime_data(part, "bar", CURL_ZERO_TERMINATED); + + test_setopt(curl, CURLOPT_MIMEPOST, mime); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + test_setopt(curl, CURLOPT_HTTPHEADER, list); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_mime_free(mime); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1973.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1973.c new file mode 100644 index 0000000000000000000000000000000000000000..4b2ba95c6dc8a89c5b1a0c988bb385f93459eea6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1973.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_POSTFIELDS, "post fields\n"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + test_setopt(curl, CURLOPT_HTTPHEADER, list); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1974.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1974.c new file mode 100644 index 0000000000000000000000000000000000000000..41922fa607e10e3a90913e0b34984256810b212a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1974.c @@ -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.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib1975.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1975.c new file mode 100644 index 0000000000000000000000000000000000000000..0cd9be24b0a04e94fe517ba0a2527a1a0dce22c9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib1975.c @@ -0,0 +1,85 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed 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 "test.h" + +#include "memdebug.h" + +static size_t read_callback(char *buffer, size_t size, size_t nitems, + void *userdata) +{ + (void)buffer; /* unused */ + (void)size; /* unused */ + (void)nitems; /* unused */ + (void)userdata; /* unused */ + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = TEST_ERR_MAJOR_BAD; + struct curl_slist *list = NULL; + struct curl_slist *connect_to = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_AWS_SIGV4, "aws:amz:us-east-1:s3"); + test_setopt(curl, CURLOPT_USERPWD, "xxx"); + test_setopt(curl, CURLOPT_HEADER, 0L); + test_setopt(curl, CURLOPT_URL, URL); + list = curl_slist_append(list, "Content-Type: application/json"); + if(!list) + goto test_cleanup; + curl_slist_append(list, "X-Amz-Content-Sha256: " + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + test_setopt(curl, CURLOPT_HTTPHEADER, list); + if(libtest_arg2) { + connect_to = curl_slist_append(connect_to, libtest_arg2); + } + test_setopt(curl, CURLOPT_CONNECT_TO, connect_to); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(connect_to); + curl_slist_free_all(list); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2301.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2301.c new file mode 100644 index 0000000000000000000000000000000000000000..15615145f2b6f5b091ff3882452de556fcd9b363 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2301.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 "test.h" + +#ifndef CURL_DISABLE_WEBSOCKETS +#if 0 + +static CURLcode send_ping(CURL *curl, const char *send_payload) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, send_payload, strlen(send_payload), &sent, CURLWS_PING); + fprintf(stderr, + "ws: curl_ws_send returned %d, sent %d\n", result, (int)sent); + + return result; +} + +static CURLcode recv_pong(CURL *curl, const char *expected_payload) +{ + size_t rlen; + unsigned int rflags; + char buffer[256]; + CURLcode result = + curl_ws_recv(curl, buffer, sizeof(buffer), &rlen, &rflags); + if(rflags & CURLWS_PONG) { + int same = 0; + fprintf(stderr, "ws: got PONG back\n"); + if(rlen == strlen(expected_payload)) { + if(!memcmp(expected_payload, buffer, rlen)) { + fprintf(stderr, "ws: got the same payload back\n"); + same = 1; + } + } + if(!same) + fprintf(stderr, "ws: did NOT get the same payload back\n"); + } + else { + fprintf(stderr, "recv_pong: got %d bytes rflags %x\n", (int)rlen, rflags); + } + fprintf(stderr, "ws: curl_ws_recv returned %d, received %d\n", result, + (int)rlen); + return result; +} + +/* just close the connection */ +static void websocket_close(CURL *curl) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, "", 0, &sent, CURLWS_CLOSE); + fprintf(stderr, + "ws: curl_ws_send returned %d, sent %d\n", result, (int)sent); +} + +static void websocket(CURL *curl) +{ + int i = 0; + fprintf(stderr, "ws: websocket() starts\n"); + do { + if(send_ping(curl, "foobar")) + return; + if(recv_pong(curl, "foobar")) + return; + sleep(2); + } while(i++ < 10); + websocket_close(curl); +} + +#endif + +static size_t writecb(char *b, size_t size, size_t nitems, void *p) +{ + CURL *easy = p; + unsigned char *buffer = (unsigned char *)b; + size_t i; + size_t sent; + unsigned char pong[] = { + 0x8a, 0x0 + }; + size_t incoming = nitems; + fprintf(stderr, "Called CURLOPT_WRITEFUNCTION with %d bytes: ", + (int)nitems); + for(i = 0; i < nitems; i++) + fprintf(stderr, "%02x ", (unsigned char)buffer[i]); + fprintf(stderr, "\n"); + (void)size; + if(buffer[0] == 0x89) { + CURLcode result; + fprintf(stderr, "send back a simple PONG\n"); + result = curl_ws_send(easy, pong, 2, &sent, 0, 0); + if(result) + nitems = 0; + } + if(nitems != incoming) + fprintf(stderr, "returns error from callback\n"); + return nitems; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "webbie-sox/3"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_WS_OPTIONS, CURLWS_RAW_MODE); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, curl); + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %d\n", res); +#if 0 + if(res == CURLE_OK) + websocket(curl); +#endif + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return res; +} + +#else /* no WebSockets */ +NO_SUPPORT_BUILT_IN +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2302.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2302.c new file mode 100644 index 0000000000000000000000000000000000000000..415ab9ff1f134019f3209204740e25878313b468 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2302.c @@ -0,0 +1,126 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifndef CURL_DISABLE_WEBSOCKETS + +struct ws_data { + CURL *easy; + char buf[1024*1024]; + size_t blen; + size_t nwrites; + int has_meta; + int meta_flags; +}; + +static void flush_data(struct ws_data *wd) +{ + size_t i; + + if(!wd->nwrites) + return; + + for(i = 0; i < wd->blen; ++i) + printf("%02x ", (unsigned char)wd->buf[i]); + + printf("\n"); + if(wd->has_meta) + printf("RECFLAGS: %x\n", wd->meta_flags); + else + fprintf(stderr, "RECFLAGS: NULL\n"); + wd->blen = 0; + wd->nwrites = 0; +} + +static size_t add_data(struct ws_data *wd, const char *buf, size_t blen, + const struct curl_ws_frame *meta) +{ + if((wd->nwrites == 0) || + (!!meta != !!wd->has_meta) || + (meta && meta->flags != wd->meta_flags)) { + if(wd->nwrites > 0) + flush_data(wd); + wd->has_meta = (meta != NULL); + wd->meta_flags = meta ? meta->flags : 0; + } + + if(wd->blen + blen > sizeof(wd->buf)) { + return 0; + } + memcpy(wd->buf + wd->blen, buf, blen); + wd->blen += blen; + wd->nwrites++; + return blen; +} + + +static size_t writecb(char *buffer, size_t size, size_t nitems, void *p) +{ + struct ws_data *ws_data = p; + size_t incoming = nitems; + const struct curl_ws_frame *meta; + (void)size; + + meta = curl_ws_meta(ws_data->easy); + incoming = add_data(ws_data, buffer, incoming, meta); + + if(nitems != incoming) + fprintf(stderr, "returns error from callback\n"); + return nitems; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct ws_data ws_data; + + + global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + memset(&ws_data, 0, sizeof(ws_data)); + ws_data.easy = curl; + + curl_easy_setopt(curl, CURLOPT_URL, URL); + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "webbie-sox/3"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ws_data); + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %d\n", res); + /* always cleanup */ + curl_easy_cleanup(curl); + flush_data(&ws_data); + } + curl_global_cleanup(); + return res; +} + +#else +NO_SUPPORT_BUILT_IN +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2304.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2304.c new file mode 100644 index 0000000000000000000000000000000000000000..bc8a1f343628e41aa98ce1a444887ea99be66fca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2304.c @@ -0,0 +1,142 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifndef CURL_DISABLE_WEBSOCKETS + +static CURLcode send_ping(CURL *curl, const char *send_payload) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, send_payload, strlen(send_payload), &sent, 0, + CURLWS_PING); + fprintf(stderr, + "ws: curl_ws_send returned %d, sent %d\n", result, (int)sent); + + return result; +} + +static CURLcode recv_pong(CURL *curl, const char *expected_payload) +{ + size_t rlen; + const struct curl_ws_frame *meta; + char buffer[256]; + CURLcode result = curl_ws_recv(curl, buffer, sizeof(buffer), &rlen, &meta); + if(!result) { + if(meta->flags & CURLWS_PONG) { + int same = 0; + fprintf(stderr, "ws: got PONG back\n"); + if(rlen == strlen(expected_payload)) { + if(!memcmp(expected_payload, buffer, rlen)) { + fprintf(stderr, "ws: got the same payload back\n"); + same = 1; + } + } + if(!same) + fprintf(stderr, "ws: did NOT get the same payload back\n"); + } + else { + fprintf(stderr, "recv_pong: got %d bytes rflags %x\n", (int)rlen, + meta->flags); + } + } + fprintf(stderr, "ws: curl_ws_recv returned %d, received %d\n", result, + (int)rlen); + return result; +} + +static CURLcode recv_any(CURL *curl) +{ + size_t rlen; + const struct curl_ws_frame *meta; + char buffer[256]; + CURLcode result = curl_ws_recv(curl, buffer, sizeof(buffer), &rlen, &meta); + if(result) + return result; + + fprintf(stderr, "recv_any: got %u bytes rflags %x\n", (int)rlen, + meta->flags); + return CURLE_OK; +} + +/* just close the connection */ +static void websocket_close(CURL *curl) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, "", 0, &sent, 0, CURLWS_CLOSE); + fprintf(stderr, + "ws: curl_ws_send returned %d, sent %u\n", result, (int)sent); +} + +static void websocket(CURL *curl) +{ + int i = 0; + fprintf(stderr, "ws: websocket() starts\n"); + do { + recv_any(curl); + fprintf(stderr, "Send ping\n"); + if(send_ping(curl, "foobar")) + return; + fprintf(stderr, "Receive pong\n"); + if(recv_pong(curl, "foobar")) { + printf("Connection closed\n"); + return; + } + sleep(2); + } while(i++ < 10); + websocket_close(curl); +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "websocket/2304"); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */ + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %d\n", res); + if(res == CURLE_OK) + websocket(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return res; +} + +#else +NO_SUPPORT_BUILT_IN +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2305.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2305.c new file mode 100644 index 0000000000000000000000000000000000000000..71ee19496a3a2459d4219399795411341674b862 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2305.c @@ -0,0 +1,109 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "testtrace.h" +#include "memdebug.h" + +#ifndef CURL_DISABLE_WEBSOCKETS + +/* just close the connection */ +static void websocket_close(CURL *curl) +{ + size_t sent; + CURLcode result = + curl_ws_send(curl, "", 0, &sent, 0, CURLWS_CLOSE); + fprintf(stderr, + "ws: curl_ws_send returned %d, sent %d\n", result, (int)sent); +} + +static void websocket(CURL *curl) +{ + char buffer[256]; + const struct curl_ws_frame *meta; + size_t nread; + size_t i = 0; + FILE *save = fopen(libtest_arg2, FOPEN_WRITETEXT); + if(!save) + return; + + /* Three 4097-bytes frames are expected, 12291 bytes */ + while(i < 12291) { + CURLcode result = + curl_ws_recv(curl, buffer, sizeof(buffer), &nread, &meta); + if(result) { + if(result == CURLE_AGAIN) + /* crude busy-loop */ + continue; + fclose(save); + printf("curl_ws_recv returned %d\n", result); + return; + } + printf("%d: nread %zu Age %d Flags %x " + "Offset %" CURL_FORMAT_CURL_OFF_T " " + "Bytesleft %" CURL_FORMAT_CURL_OFF_T "\n", + (int)i, + nread, meta->age, meta->flags, meta->offset, meta->bytesleft); + i += meta->len; + fwrite(buffer, 1, nread, save); + } + fclose(save); + + websocket_close(curl); +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + + /* use the callback style */ + curl_easy_setopt(curl, CURLOPT_USERAGENT, "websocket/2304"); + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &libtest_debug_config); + curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */ + res = curl_easy_perform(curl); + fprintf(stderr, "curl_easy_perform() returned %d\n", res); + if(res == CURLE_OK) + websocket(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return res; +} + +#else +NO_SUPPORT_BUILT_IN +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2306.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2306.c new file mode 100644 index 0000000000000000000000000000000000000000..cde75193315892531ed28d5198abec50f41d1f55 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2306.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 "test.h" +#include "testtrace.h" + +#include + +#define URL2 libtest_arg2 + +CURLcode test(char *URL) +{ + /* first a fine GET response, then a bad one */ + CURL *cl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + easy_init(cl); + easy_setopt(cl, CURLOPT_URL, URL); + easy_setopt(cl, CURLOPT_VERBOSE, 1L); + res = curl_easy_perform(cl); + if(res) + goto test_cleanup; + + /* reuse handle, do a second transfer */ + easy_setopt(cl, CURLOPT_URL, URL2); + res = curl_easy_perform(cl); + +test_cleanup: + curl_easy_cleanup(cl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2308.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2308.c new file mode 100644 index 0000000000000000000000000000000000000000..47e0763c81515912a81faa61b2ce4d6de6f0e819 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2308.c @@ -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 + * + ***************************************************************************/ + +#include "test.h" +#include "testtrace.h" + +#include + +static size_t cb_curl(char *buffer, size_t size, size_t nmemb, void *userp) +{ + (void)buffer; + (void)size; + (void)nmemb; + (void)userp; + return CURL_WRITEFUNC_ERROR; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb_curl); + curl_easy_setopt(curl, CURLOPT_URL, URL); + res = curl_easy_perform(curl); + printf("Returned %d, should be %d.\n", res, CURLE_WRITE_ERROR); + fflush(stdout); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2309.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2309.c new file mode 100644 index 0000000000000000000000000000000000000000..11f1c1fbd886846d5901b03ba9cd0314672fec99 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2309.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "testtrace.h" + +#include + +static size_t cb_ignore(char *buffer, size_t size, size_t nmemb, void *userp) +{ + (void)buffer; + (void)size; + (void)nmemb; + (void)userp; + return CURL_WRITEFUNC_ERROR; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURL *curldupe; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb_ignore); + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_PROXY, libtest_arg3); + curl_easy_setopt(curl, CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED); + curl_easy_setopt(curl, CURLOPT_NETRC_FILE, libtest_arg2); + + curldupe = curl_easy_duphandle(curl); + if(curldupe) { + res = curl_easy_perform(curldupe); + printf("Returned %d, should be %d.\n", res, CURLE_WRITE_ERROR); + fflush(stdout); + curl_easy_cleanup(curldupe); + } + curl_easy_cleanup(curl); + } + curl_global_cleanup(); + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2402.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2402.c new file mode 100644 index 0000000000000000000000000000000000000000..c58946bb1bbfad6936e5985bb58adba46a583fd0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2402.c @@ -0,0 +1,142 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_HANDLES 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES] = {0}; + int running; + CURLM *m = NULL; + int i; + char target_url[256]; + char dnsentry[256]; + struct curl_slist *slist = NULL; + char *port = libtest_arg3; + char *address = libtest_arg2; + + (void)URL; + + msnprintf(dnsentry, sizeof(dnsentry), "localhost:%s:%s", + port, address); + printf("%s\n", dnsentry); + slist = curl_slist_append(slist, dnsentry); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(m); + + multi_setopt(m, CURLMOPT_MAXCONNECTS, 1L); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + /* get an easy handle */ + easy_init(curl[i]); + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "https://localhost:%s/path/2402%04i", + port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl[i], CURLOPT_URL, target_url); + /* go http2 */ + easy_setopt(curl[i], CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + /* no peer verify */ + easy_setopt(curl[i], CURLOPT_SSL_VERIFYPEER, 0L); + easy_setopt(curl[i], CURLOPT_SSL_VERIFYHOST, 0L); + /* wait for first connection established to see if we can share it */ + easy_setopt(curl[i], CURLOPT_PIPEWAIT, 1L); + /* go verbose */ + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl[i], CURLOPT_HEADER, 1L); + + easy_setopt(curl[i], CURLOPT_RESOLVE, slist); + } + + fprintf(stderr, "Start at URL 0\n"); + + for(i = 0; i < NUM_HANDLES; i++) { + /* add handle to multi */ + multi_add_handle(m, curl[i]); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + wait_ms(1); /* to ensure different end times */ + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(m, curl[i]); + curl_easy_cleanup(curl[i]); + } + + curl_slist_free_all(slist); + + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2404.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2404.c new file mode 100644 index 0000000000000000000000000000000000000000..ed47d42578bcff8a3a2a48dc3dc5995d053453ba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2404.c @@ -0,0 +1,144 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_HANDLES 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES] = {0}; + int running; + CURLM *m = NULL; + int i; + char target_url[256]; + char dnsentry[256]; + struct curl_slist *slist = NULL; + char *port = libtest_arg3; + char *address = libtest_arg2; + + (void)URL; + + msnprintf(dnsentry, sizeof(dnsentry), "localhost:%s:%s", + port, address); + printf("%s\n", dnsentry); + slist = curl_slist_append(slist, dnsentry); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(m); + + multi_setopt(m, CURLMOPT_MAXCONNECTS, 1L); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + /* get an easy handle */ + easy_init(curl[i]); + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "https://localhost:%s/path/2404%04i", + port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl[i], CURLOPT_URL, target_url); + /* go http2 */ + easy_setopt(curl[i], CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + /* no peer verify */ + easy_setopt(curl[i], CURLOPT_SSL_VERIFYPEER, 0L); + easy_setopt(curl[i], CURLOPT_SSL_VERIFYHOST, 0L); + /* wait for first connection established to see if we can share it */ + easy_setopt(curl[i], CURLOPT_PIPEWAIT, 1L); + /* go verbose */ + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl[i], CURLOPT_HEADER, 1L); + + easy_setopt(curl[i], CURLOPT_RESOLVE, slist); + + easy_setopt(curl[i], CURLOPT_STREAM_WEIGHT, (long)128 + i); + } + + fprintf(stderr, "Start at URL 0\n"); + + for(i = 0; i < NUM_HANDLES; i++) { + /* add handle to multi */ + multi_add_handle(m, curl[i]); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + wait_ms(1); /* to ensure different end times */ + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(m, curl[i]); + curl_easy_cleanup(curl[i]); + } + + curl_slist_free_all(slist); + + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2405.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2405.c new file mode 100644 index 0000000000000000000000000000000000000000..5b01cd8ce7afd27604ed1a7a7a035c3a353150dc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2405.c @@ -0,0 +1,310 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Dmitry Karpov + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 purpose of this test is to test behavior of curl_multi_waitfds + * function in different scenarios: + * empty multi handle (expected zero descriptors), + * HTTP1 amd HTTP2 (no multiplexing) two transfers (expected two descriptors), + * HTTP2 with multiplexing (expected one descriptors) + * + * It is also expected that all transfers run by multi-handle should complete + * successfully. + */ + +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + + + /* ---------------------------------------------------------------- */ + +#define test_check(expected_fds) \ + if(res != CURLE_OK) { \ + fprintf(stderr, "test failed with code: %d\n", res); \ + goto test_cleanup; \ + } \ + else if(fd_count != expected_fds) { \ + fprintf(stderr, "Max number of waitfds: %d not as expected: %d\n", \ + fd_count, expected_fds); \ + res = TEST_ERR_FAILURE; \ + goto test_cleanup; \ + } + +#define test_run_check(option, expected_fds) do { \ + res = test_run(URL, option, &fd_count); \ + test_check(expected_fds); \ +} while(0) + + /* ---------------------------------------------------------------- */ + +enum { + TEST_USE_HTTP1 = 0, + TEST_USE_HTTP2, + TEST_USE_HTTP2_MPLEX +}; + +static size_t emptyWriteFunc(void *ptr, size_t size, size_t nmemb, + void *data) { + (void)ptr; (void)data; + return size * nmemb; +} + +static CURLcode set_easy(char *URL, CURL *easy, long option) +{ + CURLcode res = CURLE_OK; + + /* First set the URL that is about to receive our POST. */ + easy_setopt(easy, CURLOPT_URL, URL); + + /* get verbose debug output please */ + easy_setopt(easy, CURLOPT_VERBOSE, 1L); + + switch(option) { + case TEST_USE_HTTP1: + /* go http1 */ + easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); + break; + + case TEST_USE_HTTP2: + /* go http2 */ + easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + break; + + case TEST_USE_HTTP2_MPLEX: + /* go http2 with multiplexing */ + easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + easy_setopt(easy, CURLOPT_PIPEWAIT, 1L); + break; + } + + /* no peer verify */ + easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 0L); + easy_setopt(easy, CURLOPT_SSL_VERIFYHOST, 0L); + + /* include headers */ + easy_setopt(easy, CURLOPT_HEADER, 1L); + + /* empty write function */ + easy_setopt(easy, CURLOPT_WRITEFUNCTION, emptyWriteFunc); + +test_cleanup: + return res; +} + +static CURLcode test_run(char *URL, long option, unsigned int *max_fd_count) +{ + CURLMcode mc = CURLM_OK; + CURLM *multi = NULL; + CURLM *multi1 = NULL; + + CURL *easy1 = NULL; + CURL *easy2 = NULL; + + unsigned int max_count = 0; + + int still_running; /* keep number of running handles */ + CURLMsg *msg; /* for picking up messages with the transfer status */ + int msgs_left; /* how many messages are left */ + + CURLcode result; + CURLcode res = CURLE_OK; + + struct curl_waitfd ufds[10]; + struct curl_waitfd ufds1[10]; + int numfds; + + easy_init(easy1); + easy_init(easy2); + + if(set_easy(URL, easy1, option) != CURLE_OK) + goto test_cleanup; + + if(set_easy(URL, easy2, option) != CURLE_OK) + goto test_cleanup; + + multi_init(multi); + multi_init(multi1); + + if(option == TEST_USE_HTTP2_MPLEX) + multi_setopt(multi, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX); + + multi_add_handle(multi, easy1); + multi_add_handle(multi, easy2); + + while(!mc) { + /* get the count of file descriptors from the transfers */ + unsigned int fd_count = 0; + + mc = curl_multi_perform(multi, &still_running); + if(!still_running || mc != CURLM_OK) + break; + + mc = curl_multi_waitfds(multi, ufds, 10, &fd_count); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_waitfds() failed, code %d.\n", mc); + res = TEST_ERR_FAILURE; + break; + } + + if(!fd_count) + continue; /* no descriptors yet */ + + /* checking case when we don't have enough space for waitfds */ + mc = curl_multi_waitfds(multi, ufds1, fd_count - 1, NULL); + + if(mc != CURLM_OUT_OF_MEMORY) { + fprintf(stderr, "curl_multi_waitfds() return code %d instead of " + "CURLM_OUT_OF_MEMORY.\n", mc); + res = TEST_ERR_FAILURE; + break; + } + + if(fd_count > max_count) + max_count = fd_count; + + /* Do polling on descriptors in ufds in Multi 1 */ + mc = curl_multi_poll(multi1, ufds, fd_count, 500, &numfds); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_poll() failed, code %d.\\n", mc); + res = TEST_ERR_FAILURE; + break; + } + } + + for(;;) { + msg = curl_multi_info_read(multi, &msgs_left); + if(!msg) + break; + if(msg->msg == CURLMSG_DONE) { + result = msg->data.result; + + if(!res) + res = result; + } + } + + curl_multi_remove_handle(multi, easy1); + curl_multi_remove_handle(multi, easy2); + +test_cleanup: + curl_easy_cleanup(easy1); + curl_easy_cleanup(easy2); + + curl_multi_cleanup(multi); + curl_multi_cleanup(multi1); + + if(max_fd_count) + *max_fd_count = max_count; + + return res; +} + +static CURLcode empty_multi_test(void) +{ + CURLMcode mc = CURLM_OK; + CURLM *multi = NULL; + CURL *easy = NULL; + + struct curl_waitfd ufds[10]; + + CURLcode res = CURLE_OK; + unsigned int fd_count = 0; + + multi_init(multi); + + /* calling curl_multi_waitfds() on an empty multi handle. */ + mc = curl_multi_waitfds(multi, ufds, 10, &fd_count); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_waitfds() failed, code %d.\n", mc); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + else if(fd_count > 0) { + fprintf(stderr, "curl_multi_waitfds() returned non-zero count of " + "waitfds: %d.\n", fd_count); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + + /* calling curl_multi_waitfds() on multi handle with added easy handle. */ + easy_init(easy); + + if(set_easy((char *)"http://example.com", easy, TEST_USE_HTTP1) != CURLE_OK) + goto test_cleanup; + + multi_add_handle(multi, easy); + + mc = curl_multi_waitfds(multi, ufds, 10, &fd_count); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_waitfds() failed, code %d.\n", mc); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + else if(fd_count > 0) { + fprintf(stderr, "curl_multi_waitfds() returned non-zero count of " + "waitfds: %d.\n", fd_count); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + + curl_multi_remove_handle(multi, easy); + +test_cleanup: + curl_easy_cleanup(easy); + curl_multi_cleanup(multi); + return res; +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + unsigned int fd_count = 0; + + global_init(CURL_GLOBAL_ALL); + + /* Testing curl_multi_waitfds on empty and not started handles */ + res = empty_multi_test(); + if(res != CURLE_OK) + goto test_cleanup; + + /* HTTP1, expected 2 waitfds - one for each transfer */ + test_run_check(TEST_USE_HTTP1, 2); + + /* HTTP2, expected 2 waitfds - one for each transfer */ + test_run_check(TEST_USE_HTTP2, 2); + + /* HTTP2 with multiplexing, expected 1 waitfds - one for all transfers */ + test_run_check(TEST_USE_HTTP2_MPLEX, 1); + +test_cleanup: + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib2502.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2502.c new file mode 100644 index 0000000000000000000000000000000000000000..f01fbe0c5cecf63ec686c099bf444f5fd0d32133 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib2502.c @@ -0,0 +1,146 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * 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 + * + ***************************************************************************/ +#include "test.h" + +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_HANDLES 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES] = {0}; + int running; + CURLM *m = NULL; + int i; + char target_url[256]; + char dnsentry[256]; + struct curl_slist *slist = NULL; + char *port = libtest_arg3; + char *address = libtest_arg2; + + (void)URL; + + msnprintf(dnsentry, sizeof(dnsentry), "localhost:%s:%s", + port, address); + printf("%s\n", dnsentry); + slist = curl_slist_append(slist, dnsentry); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(m); + + multi_setopt(m, CURLMOPT_MAXCONNECTS, 1L); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + /* get an easy handle */ + easy_init(curl[i]); + /* specify target */ + msnprintf(target_url, sizeof(target_url), + "https://localhost:%s/path/2502%04i", + port, i + 1); + target_url[sizeof(target_url) - 1] = '\0'; + easy_setopt(curl[i], CURLOPT_URL, target_url); + /* go http2 */ + easy_setopt(curl[i], CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3ONLY); + easy_setopt(curl[i], CURLOPT_CONNECTTIMEOUT_MS, (long)5000); + easy_setopt(curl[i], CURLOPT_CAINFO, "./certs/EdelCurlRoot-ca.cacert"); + /* wait for first connection established to see if we can share it */ + easy_setopt(curl[i], CURLOPT_PIPEWAIT, 1L); + /* go verbose */ + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 0; + test_setopt(curl[i], CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(curl[i], CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + /* include headers */ + easy_setopt(curl[i], CURLOPT_HEADER, 1L); + + easy_setopt(curl[i], CURLOPT_RESOLVE, slist); + } + + fprintf(stderr, "Start at URL 0\n"); + + for(i = 0; i < NUM_HANDLES; i++) { + /* add handle to multi */ + multi_add_handle(m, curl[i]); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + wait_ms(1); /* to ensure different end times */ + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(m, curl[i]); + curl_easy_cleanup(curl[i]); + } + + curl_slist_free_all(slist); + + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3010.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3010.c new file mode 100644 index 0000000000000000000000000000000000000000..ce0fa30505eef86c90e3a5bd76c501b4073faba2 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3010.c @@ -0,0 +1,67 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Nicolas Sterchele, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret = CURLE_OK; + CURL *curl = NULL; + curl_off_t retry_after; + char *follow_url = NULL; + + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + ret = curl_easy_perform(curl); + if(ret) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, ret, curl_easy_strerror(ret)); + goto test_cleanup; + } + curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &follow_url); + curl_easy_getinfo(curl, CURLINFO_RETRY_AFTER, &retry_after); + printf("Retry-After %" CURL_FORMAT_CURL_OFF_T "\n", retry_after); + curl_easy_setopt(curl, CURLOPT_URL, follow_url); + ret = curl_easy_perform(curl); + if(ret) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, ret, curl_easy_strerror(ret)); + goto test_cleanup; + } + + curl_easy_reset(curl); + curl_easy_getinfo(curl, CURLINFO_RETRY_AFTER, &retry_after); + printf("Retry-After %" CURL_FORMAT_CURL_OFF_T "\n", retry_after); + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3025.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3025.c new file mode 100644 index 0000000000000000000000000000000000000000..80f80eae01e64bfab8af21ea5691eb22b207d304 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3025.c @@ -0,0 +1,61 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + struct curl_slist *icy = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + icy = curl_slist_append(icy, "ICY 200 OK"); + test_setopt(curl, CURLOPT_HTTP200ALIASES, icy); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_URL, URL); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_slist_free_all(icy); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3026.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3026.c new file mode 100644 index 0000000000000000000000000000000000000000..61c70eb3b9b1704bd1cf69e86b7a6d2ebc592d0f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3026.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 "test.h" + +#include "testutil.h" +#include "warnless.h" + +#define NUM_THREADS 100 + +#ifdef _WIN32 +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) +static DWORD WINAPI run_thread(LPVOID ptr) +#else +#include +static unsigned int WINAPI run_thread(void *ptr) +#endif +{ + CURLcode *result = ptr; + + *result = curl_global_init(CURL_GLOBAL_ALL); + if(*result == CURLE_OK) + curl_global_cleanup(); + + return 0; +} + +CURLcode test(char *URL) +{ +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) + typedef HANDLE curl_win_thread_handle_t; +#else + typedef uintptr_t curl_win_thread_handle_t; +#endif + CURLcode results[NUM_THREADS]; + curl_win_thread_handle_t ths[NUM_THREADS]; + unsigned tid_count = NUM_THREADS, i; + int test_failure = 0; + curl_version_info_data *ver; + (void) URL; + + ver = curl_version_info(CURLVERSION_NOW); + if((ver->features & CURL_VERSION_THREADSAFE) == 0) { + fprintf(stderr, "%s:%d On Windows but the " + "CURL_VERSION_THREADSAFE feature flag is not set\n", + __FILE__, __LINE__); + return (CURLcode)-1; + } + + /* On Windows libcurl global init/cleanup calls LoadLibrary/FreeLibrary for + secur32.dll and iphlpapi.dll. Here we load them beforehand so that when + libcurl calls LoadLibrary/FreeLibrary it only increases/decreases the + library's refcount rather than actually loading/unloading the library, + which would affect the test runtime. */ + (void)win32_load_system_library(TEXT("secur32.dll")); + (void)win32_load_system_library(TEXT("iphlpapi.dll")); + + for(i = 0; i < tid_count; i++) { + curl_win_thread_handle_t th; + results[i] = CURL_LAST; /* initialize with invalid value */ +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) + th = CreateThread(NULL, 0, run_thread, &results[i], 0, NULL); +#else + th = _beginthreadex(NULL, 0, run_thread, &results[i], 0, NULL); +#endif + if(!th) { + fprintf(stderr, "%s:%d Couldn't create thread, errno %lu\n", + __FILE__, __LINE__, GetLastError()); + tid_count = i; + test_failure = -1; + goto cleanup; + } + ths[i] = th; + } + +cleanup: + for(i = 0; i < tid_count; i++) { + WaitForSingleObject((HANDLE)ths[i], INFINITE); + CloseHandle((HANDLE)ths[i]); + if(results[i] != CURLE_OK) { + fprintf(stderr, "%s:%d thread[%u]: curl_global_init() failed," + "with code %d (%s)\n", __FILE__, __LINE__, + i, (int) results[i], curl_easy_strerror(results[i])); + test_failure = -1; + } + } + + return (CURLcode)test_failure; +} + +#elif defined(HAVE_PTHREAD_H) +#include +#include + +static void *run_thread(void *ptr) +{ + CURLcode *result = ptr; + + *result = curl_global_init(CURL_GLOBAL_ALL); + if(*result == CURLE_OK) + curl_global_cleanup(); + + return NULL; +} + +CURLcode test(char *URL) +{ + CURLcode results[NUM_THREADS]; + pthread_t tids[NUM_THREADS]; + unsigned tid_count = NUM_THREADS, i; + CURLcode test_failure = CURLE_OK; + curl_version_info_data *ver; + (void) URL; + + ver = curl_version_info(CURLVERSION_NOW); + if((ver->features & CURL_VERSION_THREADSAFE) == 0) { + fprintf(stderr, "%s:%d Have pthread but the " + "CURL_VERSION_THREADSAFE feature flag is not set\n", + __FILE__, __LINE__); + return (CURLcode)-1; + } + + for(i = 0; i < tid_count; i++) { + int res; + results[i] = CURL_LAST; /* initialize with invalid value */ + res = pthread_create(&tids[i], NULL, run_thread, &results[i]); + if(res) { + fprintf(stderr, "%s:%d Couldn't create thread, errno %d\n", + __FILE__, __LINE__, res); + tid_count = i; + test_failure = (CURLcode)-1; + goto cleanup; + } + } + +cleanup: + for(i = 0; i < tid_count; i++) { + pthread_join(tids[i], NULL); + if(results[i] != CURLE_OK) { + fprintf(stderr, "%s:%d thread[%u]: curl_global_init() failed," + "with code %d (%s)\n", __FILE__, __LINE__, + i, (int) results[i], curl_easy_strerror(results[i])); + test_failure = (CURLcode)-1; + } + } + + return test_failure; +} + +#else /* without pthread or Windows, this test doesn't work */ +CURLcode test(char *URL) +{ + curl_version_info_data *ver; + (void)URL; + + ver = curl_version_info(CURLVERSION_NOW); + if((ver->features & CURL_VERSION_THREADSAFE) != 0) { + fprintf(stderr, "%s:%d No pthread but the " + "CURL_VERSION_THREADSAFE feature flag is set\n", + __FILE__, __LINE__); + return (CURLcode)-1; + } + return CURLE_OK; +} +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3027.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3027.c new file mode 100644 index 0000000000000000000000000000000000000000..4ddee1b6b29f155f5000bf1e43a69c625c473c5b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3027.c @@ -0,0 +1,56 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode ret = CURLE_OK; + CURL *hnd; + start_test_timing(); + + curl_global_init(CURL_GLOBAL_ALL); + + hnd = curl_easy_init(); + if(hnd) { + curl_easy_setopt(hnd, CURLOPT_URL, URL); + curl_easy_setopt(hnd, CURLOPT_FILETIME, 1L); + ret = curl_easy_perform(hnd); + if(CURLE_OK == ret) { + long filetime; + ret = curl_easy_getinfo(hnd, CURLINFO_FILETIME, &filetime); + /* MTDM fails with 550, so filetime should be -1 */ + if((CURLE_OK == ret) && (filetime != -1)) { + /* we just need to return something which is not CURLE_OK */ + ret = CURLE_UNSUPPORTED_PROTOCOL; + } + } + curl_easy_cleanup(hnd); + } + curl_global_cleanup(); + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3100.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3100.c new file mode 100644 index 0000000000000000000000000000000000000000..82132b9476d4d04e12087024f5d630e78f475b84 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3100.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 "test.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, URL); + + test_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + test_setopt(curl, CURLOPT_USERNAME, "user"); + test_setopt(curl, CURLOPT_PASSWORD, "password"); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); + + res = curl_easy_perform(curl); + if(res != CURLE_OK) { + fprintf(stderr, "Failed to send DESCRIBE: %d\n", res); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3101.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3101.c new file mode 100644 index 0000000000000000000000000000000000000000..3f2e97711aa022d33401826d9f3b9a78f43d829b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3101.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 "test.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); + test_setopt(curl, CURLOPT_USERNAME, "user"); + test_setopt(curl, CURLOPT_PASSWORD, "password"); + test_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "https"); + + res = curl_easy_perform(curl); + if(res != CURLE_OK) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3102.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3102.c new file mode 100644 index 0000000000000000000000000000000000000000..7f1b0562720f1b335c2e9173a310cfd750ac2bdb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3102.c @@ -0,0 +1,141 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* + * Verify correct order of certificates in the chain by comparing the + * subject and issuer attributes of each certificate. + */ +static bool is_chain_in_order(struct curl_certinfo *cert_info) +{ + char *last_issuer = NULL; + int cert; + + /* Chains with only a single certificate are always in order */ + if(cert_info->num_of_certs <= 1) + return 1; + + /* Enumerate each certificate in the chain */ + for(cert = 0; cert < cert_info->num_of_certs; cert++) { + struct curl_slist *slist = cert_info->certinfo[cert]; + char *issuer = NULL; + char *subject = NULL; + + /* Find the certificate issuer and subject by enumerating each field */ + for(; slist && (!issuer || !subject); slist = slist->next) { + const char issuer_prefix[] = "Issuer:"; + const char subject_prefix[] = "Subject:"; + + if(!strncmp(slist->data, issuer_prefix, sizeof(issuer_prefix)-1)) { + issuer = slist->data + sizeof(issuer_prefix)-1; + } + if(!strncmp(slist->data, subject_prefix, sizeof(subject_prefix)-1)) { + subject = slist->data + sizeof(subject_prefix)-1; + } + } + + if(subject && issuer) { + printf("cert %d\n", cert); + printf(" subject: %s\n", subject); + printf(" issuer: %s\n", issuer); + + if(last_issuer) { + /* If the last certificate's issuer matches the current certificate's + * subject, then the chain is in order */ + if(strcmp(last_issuer, subject) != 0) { + fprintf(stderr, "cert %d issuer does not match cert %d subject\n", + cert - 1, cert); + fprintf(stderr, "certificate chain is not in order\n"); + return false; + } + } + } + + last_issuer = issuer; + } + + printf("certificate chain is in order\n"); + return true; +} + +static size_t wrfu(void *ptr, size_t size, size_t nmemb, void *stream) +{ + (void)stream; + (void)ptr; + return size * nmemb; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* Set the HTTPS url to retrieve. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Capture certificate information */ + test_setopt(curl, CURLOPT_CERTINFO, 1L); + + /* Ignore output */ + test_setopt(curl, CURLOPT_WRITEFUNCTION, wrfu); + + /* No peer verify */ + test_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + test_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + if(!res || res == CURLE_GOT_NOTHING) { + struct curl_certinfo *cert_info = NULL; + /* Get the certificate information */ + res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &cert_info); + if(!res) { + /* Check to see if the certificate chain is ordered correctly */ + if(!is_chain_in_order(cert_info)) + res = TEST_ERR_FAILURE; + } + } + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3103.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3103.c new file mode 100644 index 0000000000000000000000000000000000000000..8d602849935c0b9404b0a601489faddc0180491d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3103.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURLSH *share; + CURL *curl; + + curl_global_init(CURL_GLOBAL_ALL); + + share = curl_share_init(); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + + curl = curl_easy_init(); + test_setopt(curl, CURLOPT_SHARE, share); + + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_PROXY, URL); + test_setopt(curl, CURLOPT_URL, "http://localhost/"); + + test_setopt(curl, CURLOPT_COOKIEFILE, ""); + + /* Set a cookie without Max-age or Expires */ + test_setopt(curl, CURLOPT_COOKIELIST, "Set-Cookie: c1=v1; domain=localhost"); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + } + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_share_cleanup(share); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib3207.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3207.c new file mode 100644 index 0000000000000000000000000000000000000000..a78608156d2c5bdbbc79d5d01167d9a1866f2561 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib3207.c @@ -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 + * + ***************************************************************************/ +#include "test.h" +#include "testutil.h" +#include "memdebug.h" + +#include + +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) +#if defined(USE_THREADS_POSIX) +#include +#endif +#include "curl_threads.h" +#endif + +#define CAINFO libtest_arg2 +#define THREAD_SIZE 16 +#define PER_THREAD_SIZE 8 + +struct Ctx { + const char *URL; + CURLSH *share; + int result; + int thread_id; + struct curl_slist *contents; +}; + +static size_t write_memory_callback(char *contents, size_t size, + size_t nmemb, void *userp) +{ + /* append the data to contents */ + size_t realsize = size * nmemb; + struct Ctx *mem = (struct Ctx *)userp; + char *data = (char *)malloc(realsize + 1); + struct curl_slist *item_append = NULL; + if(!data) { + printf("not enough memory (malloc returned NULL)\n"); + return 0; + } + memcpy(data, contents, realsize); + data[realsize] = '\0'; + item_append = curl_slist_append(mem->contents, data); + free(data); + if(item_append) { + mem->contents = item_append; + } + else { + printf("not enough memory (curl_slist_append returned NULL)\n"); + return 0; + } + return realsize; +} + +static +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) +DWORD +#else +unsigned int +#endif +CURL_STDCALL +#else +unsigned int +#endif +test_thread(void *ptr) +{ + struct Ctx *ctx = (struct Ctx *)ptr; + CURLcode res = CURLE_OK; + + int i; + + /* Loop the transfer and cleanup the handle properly every lap. This will + still reuse ssl session since the pool is in the shared object! */ + for(i = 0; i < PER_THREAD_SIZE; i++) { + CURL *curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, (char *)ctx->URL); + + /* use the share object */ + curl_easy_setopt(curl, CURLOPT_SHARE, ctx->share); + curl_easy_setopt(curl, CURLOPT_CAINFO, CAINFO); + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, ptr); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + + /* always cleanup */ + curl_easy_cleanup(curl); + /* Check for errors */ + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + goto test_cleanup; + } + } + } + +test_cleanup: + ctx->result = (int)res; + return 0; +} + +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) + +static void test_lock(CURL *handle, curl_lock_data data, + curl_lock_access laccess, void *useptr) +{ + curl_mutex_t *mutexes = (curl_mutex_t*) useptr; + (void)handle; + (void)laccess; + Curl_mutex_acquire(&mutexes[data]); +} + +static void test_unlock(CURL *handle, curl_lock_data data, void *useptr) +{ + curl_mutex_t *mutexes = (curl_mutex_t*) useptr; + (void)handle; + Curl_mutex_release(&mutexes[data]); +} + +static void execute(CURLSH *share, struct Ctx *ctx) +{ + int i; + curl_mutex_t mutexes[CURL_LOCK_DATA_LAST - 1]; + curl_thread_t thread[THREAD_SIZE]; + for(i = 0; i < CURL_LOCK_DATA_LAST - 1; i++) { + Curl_mutex_init(&mutexes[i]); + } + curl_share_setopt(share, CURLSHOPT_LOCKFUNC, test_lock); + curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, test_unlock); + curl_share_setopt(share, CURLSHOPT_USERDATA, (void *)mutexes); + curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); + + for(i = 0; i < THREAD_SIZE; i++) { + thread[i] = Curl_thread_create(test_thread, (void *)&ctx[i]); + } + for(i = 0; i < THREAD_SIZE; i++) { + if(thread[i]) { + Curl_thread_join(&thread[i]); + Curl_thread_destroy(thread[i]); + } + } + curl_share_setopt(share, CURLSHOPT_LOCKFUNC, NULL); + curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, NULL); + for(i = 0; i < CURL_LOCK_DATA_LAST - 1; i++) { + Curl_mutex_destroy(&mutexes[i]); + } +} + +#else /* without pthread, run serially */ + +static void execute(CURLSH *share, struct Ctx *ctx) +{ + int i; + (void) share; + for(i = 0; i < THREAD_SIZE; i++) { + test_thread((void *)&ctx[i]); + } +} + +#endif + +CURLcode test(char *URL) +{ + int res = 0; + int i; + CURLSH* share; + struct Ctx ctx[THREAD_SIZE]; + + curl_global_init(CURL_GLOBAL_ALL); + + share = curl_share_init(); + if(!share) { + fprintf(stderr, "curl_share_init() failed\n"); + goto test_cleanup; + } + + for(i = 0; i < THREAD_SIZE; i++) { + ctx[i].share = share; + ctx[i].URL = URL; + ctx[i].thread_id = i; + ctx[i].result = 0; + ctx[i].contents = NULL; + } + + execute(share, ctx); + + for(i = 0; i < THREAD_SIZE; i++) { + if(ctx[i].result) { + res = ctx[i].result; + } + else { + struct curl_slist *item = ctx[i].contents; + while(item) { + printf("%s", item->data); + item = item->next; + } + } + curl_slist_free_all(ctx[i].contents); + } + +test_cleanup: + if(share) + curl_share_cleanup(share); + curl_global_cleanup(); + return (CURLcode)res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib500.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib500.c new file mode 100644 index 0000000000000000000000000000000000000000..9aa3466698fa4cd8544970832d1879bad91fe3a5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib500.c @@ -0,0 +1,178 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testtrace.h" +#include "memdebug.h" + +#ifdef LIB585 + +static int testcounter; + +static curl_socket_t tst_opensocket(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *addr) +{ + (void)clientp; + (void)purpose; + printf("[OPEN] counter: %d\n", ++testcounter); + return socket(addr->family, addr->socktype, addr->protocol); +} + +static int tst_closesocket(void *clientp, curl_socket_t sock) +{ + (void)clientp; + printf("[CLOSE] counter: %d\n", testcounter--); + return sclose(sock); +} + +static void setupcallbacks(CURL *curl) +{ + curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, tst_opensocket); + curl_easy_setopt(curl, CURLOPT_CLOSESOCKETFUNCTION, tst_closesocket); + testcounter = 0; +} + +#else +#define setupcallbacks(x) Curl_nop_stmt +#endif + + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + char *ipstr = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + test_setopt(curl, CURLOPT_DEBUGDATA, &libtest_debug_config); + test_setopt(curl, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + if(libtest_arg3 && !strcmp(libtest_arg3, "activeftp")) + test_setopt(curl, CURLOPT_FTPPORT, "-"); + + setupcallbacks(curl); + + res = curl_easy_perform(curl); + + if(!res) { + res = curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &ipstr); + if(libtest_arg2) { + FILE *moo = fopen(libtest_arg2, "wb"); + if(moo) { + curl_off_t time_namelookup; + curl_off_t time_connect; + curl_off_t time_pretransfer; + curl_off_t time_posttransfer; + curl_off_t time_starttransfer; + curl_off_t time_total; + fprintf(moo, "IP %s\n", ipstr); + curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME_T, &time_namelookup); + curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME_T, &time_connect); + curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME_T, + &time_pretransfer); + curl_easy_getinfo(curl, CURLINFO_POSTTRANSFER_TIME_T, + &time_posttransfer); + curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME_T, + &time_starttransfer); + curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME_T, &time_total); + + /* since the timing will always vary we only compare relative + differences between these 5 times */ + if(time_namelookup > time_connect) { + fprintf(moo, "namelookup vs connect: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_namelookup / 1000000), + (long)(time_namelookup % 1000000), + (time_connect / 1000000), (long)(time_connect % 1000000)); + } + if(time_connect > time_pretransfer) { + fprintf(moo, "connect vs pretransfer: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_connect / 1000000), (long)(time_connect % 1000000), + (time_pretransfer / 1000000), + (long)(time_pretransfer % 1000000)); + } + if(time_pretransfer > time_posttransfer) { + fprintf(moo, "pretransfer vs posttransfer: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_pretransfer / 1000000), + (long)(time_pretransfer % 1000000), + (time_posttransfer / 1000000), + (long)(time_posttransfer % 1000000)); + } + if(time_pretransfer > time_starttransfer) { + fprintf(moo, "pretransfer vs starttransfer: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_pretransfer / 1000000), + (long)(time_pretransfer % 1000000), + (time_starttransfer / 1000000), + (long)(time_starttransfer % 1000000)); + } + if(time_starttransfer > time_total) { + fprintf(moo, "starttransfer vs total: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_starttransfer / 1000000), + (long)(time_starttransfer % 1000000), + (time_total / 1000000), (long)(time_total % 1000000)); + } + if(time_posttransfer > time_total) { + fprintf(moo, "posttransfer vs total: %" CURL_FORMAT_CURL_OFF_T + ".%06ld %" CURL_FORMAT_CURL_OFF_T ".%06ld\n", + (time_posttransfer / 1000000), + (long)(time_posttransfer % 1000000), + (time_total / 1000000), (long)(time_total % 1000000)); + } + + fclose(moo); + } + } + } + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} + +#undef setupcallbacks diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib501.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib501.c new file mode 100644 index 0000000000000000000000000000000000000000..94c9adb482c91ddcabc1efd491e03a952aba1480 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib501.c @@ -0,0 +1,60 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + (void)URL; /* we don't use this */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* just verify that setting this to -1 is fine */ + test_setopt(curl, CURLOPT_MAXREDIRS, -1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib502.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib502.c new file mode 100644 index 0000000000000000000000000000000000000000..44ad6f6790210083f5d7dc00c2323fee508882ce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib502.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Get a single URL without select(). + */ + +CURLcode test(char *URL) +{ + CURL *c = NULL; + CURLM *m = NULL; + CURLcode res = CURLE_OK; + int running; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(c); + + easy_setopt(c, CURLOPT_URL, URL); + + multi_init(m); + + multi_add_handle(m, c); + + for(;;) { + struct timeval timeout; + fd_set fdread, fdwrite, fdexcep; + int maxfd = -99; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, c); + curl_multi_cleanup(m); + curl_easy_cleanup(c); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib503.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib503.c new file mode 100644 index 0000000000000000000000000000000000000000..cac2a755cbce515cb592a2ebc81041df5e3b04c0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib503.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Source code in here hugely as reported in bug report 651460 by + * Christopher R. Palmer. + * + * Use multi interface to get HTTPS document over proxy, and provide + * auth info. + */ + +CURLcode test(char *URL) +{ + CURL *c = NULL; + CURLM *m = NULL; + CURLcode res = CURLE_OK; + int running; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(c); + + easy_setopt(c, CURLOPT_PROXY, libtest_arg2); /* set in first.c */ + easy_setopt(c, CURLOPT_URL, URL); + easy_setopt(c, CURLOPT_USERPWD, "test:ing"); + easy_setopt(c, CURLOPT_PROXYUSERNAME, "test%20"); + easy_setopt(c, CURLOPT_PROXYPASSWORD, "ing%41"); + easy_setopt(c, CURLOPT_HTTPPROXYTUNNEL, 1L); + easy_setopt(c, CURLOPT_HEADER, 1L); + easy_setopt(c, CURLOPT_VERBOSE, 1L); + + multi_init(m); + + multi_add_handle(m, c); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, c); + curl_multi_cleanup(m); + curl_easy_cleanup(c); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib504.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib504.c new file mode 100644 index 0000000000000000000000000000000000000000..a9f96c8ddeab32eaace6bb8399c92bbf636903d6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib504.c @@ -0,0 +1,130 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Source code in here hugely as reported in bug report 651464 by + * Christopher R. Palmer. + * + * Use multi interface to get document over proxy with bad port number. + * This caused the interface to "hang" in libcurl 7.10.2. + */ +CURLcode test(char *URL) +{ + CURL *c = NULL; + CURLcode res = CURLE_OK; + CURLM *m = NULL; + fd_set rd, wr, exc; + int running; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(c); + + /* The point here is that there must not be anything running on the given + proxy port */ + if(libtest_arg2) + easy_setopt(c, CURLOPT_PROXY, libtest_arg2); + easy_setopt(c, CURLOPT_URL, URL); + easy_setopt(c, CURLOPT_VERBOSE, 1L); + + multi_init(m); + + multi_add_handle(m, c); + + for(;;) { + struct timeval interval; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + fprintf(stderr, "curl_multi_perform()\n"); + + multi_perform(m, &running); + + while(running) { + CURLMcode mres; + int num; + mres = curl_multi_wait(m, NULL, 0, TEST_HANG_TIMEOUT, &num); + if(mres != CURLM_OK) { + printf("curl_multi_wait() returned %d\n", mres); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + abort_on_test_timeout(); + multi_perform(m, &running); + abort_on_test_timeout(); + } + + abort_on_test_timeout(); + + if(!running) { + /* This is where this code is expected to reach */ + int numleft; + CURLMsg *msg = curl_multi_info_read(m, &numleft); + fprintf(stderr, "Expected: not running\n"); + if(msg && !numleft) + res = TEST_ERR_SUCCESS; /* this is where we should be */ + else + res = TEST_ERR_FAILURE; /* not correct */ + break; /* done */ + } + fprintf(stderr, "running == %d\n", running); + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + fprintf(stderr, "curl_multi_fdset()\n"); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, c); + curl_multi_cleanup(m); + curl_easy_cleanup(c); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib505.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib505.c new file mode 100644 index 0000000000000000000000000000000000000000..de383232ca2069f97f6a14e957ca031c05e499ee --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib505.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 "test.h" + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* + * This example shows an FTP upload, with a rename of the file just after + * a successful upload. + * + * Example based on source code provided by Erick Nuwendam. Thanks! + */ + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + FILE *hd_src; + int hd; + struct_stat file_info; + struct curl_slist *hl; + + struct curl_slist *headerlist = NULL; + const char *buf_1 = "RNFR 505"; + const char *buf_2 = "RNTO 505-forreal"; + + if(!libtest_arg2) { + fprintf(stderr, "Usage: \n"); + return TEST_ERR_USAGE; + } + + hd_src = fopen(libtest_arg2, "rb"); + if(!hd_src) { + fprintf(stderr, "fopen failed with error: %d %s\n", + errno, strerror(errno)); + fprintf(stderr, "Error opening file: %s\n", libtest_arg2); + return TEST_ERR_MAJOR_BAD; /* if this happens things are major weird */ + } + + /* get the file size of the local file */ + hd = fstat(fileno(hd_src), &file_info); + if(hd == -1) { + /* can't open file, bail out */ + fprintf(stderr, "fstat() failed with error: %d %s\n", + errno, strerror(errno)); + fprintf(stderr, "ERROR: cannot open file %s\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + if(!file_info.st_size) { + fprintf(stderr, "ERROR: file %s has zero size!\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + /* get a curl handle */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + /* build a list of commands to pass to libcurl */ + + hl = curl_slist_append(headerlist, buf_1); + if(!hl) { + fprintf(stderr, "curl_slist_append() failed\n"); + curl_easy_cleanup(curl); + curl_global_cleanup(); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + headerlist = curl_slist_append(hl, buf_2); + if(!headerlist) { + fprintf(stderr, "curl_slist_append() failed\n"); + curl_slist_free_all(hl); + curl_easy_cleanup(curl); + curl_global_cleanup(); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + headerlist = hl; + + /* enable uploading */ + test_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* enable verbose */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* specify target */ + test_setopt(curl, CURLOPT_URL, URL); + + /* pass in that last of FTP commands to run after the transfer */ + test_setopt(curl, CURLOPT_POSTQUOTE, headerlist); + + /* now specify which file to upload */ + test_setopt(curl, CURLOPT_READDATA, hd_src); + + /* and give the size of the upload (optional) */ + test_setopt(curl, CURLOPT_INFILESIZE_LARGE, + (curl_off_t)file_info.st_size); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* clean up the FTP commands list */ + curl_slist_free_all(headerlist); + + /* close the local file */ + fclose(hd_src); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib506.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib506.c new file mode 100644 index 0000000000000000000000000000000000000000..03eb11ddda210250f99de1590a3d9c7d06305c31 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib506.c @@ -0,0 +1,382 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "memdebug.h" + +static const char * const HOSTHEADER = "Host: www.host.foo.com"; +#define JAR libtest_arg2 +#define THREADS 2 + +/* struct containing data of a thread */ +struct Tdata { + CURLSH *share; + char *url; +}; + +struct userdata { + const char *text; + int counter; +}; + +static int locks[3]; + +/* lock callback */ +static void test_lock(CURL *handle, curl_lock_data data, + curl_lock_access laccess, void *useptr) +{ + const char *what; + struct userdata *user = (struct userdata *)useptr; + int locknum; + + (void)handle; + (void)laccess; + + switch(data) { + case CURL_LOCK_DATA_SHARE: + what = "share"; + locknum = 0; + break; + case CURL_LOCK_DATA_DNS: + what = "dns"; + locknum = 1; + break; + case CURL_LOCK_DATA_COOKIE: + what = "cookie"; + locknum = 2; + break; + default: + fprintf(stderr, "lock: no such data: %d\n", (int)data); + return; + } + + /* detect locking of locked locks */ + if(locks[locknum]) { + printf("lock: double locked %s\n", what); + return; + } + locks[locknum]++; + + printf("lock: %-6s [%s]: %d\n", what, user->text, user->counter); + user->counter++; +} + +/* unlock callback */ +static void test_unlock(CURL *handle, curl_lock_data data, void *useptr) +{ + const char *what; + struct userdata *user = (struct userdata *)useptr; + int locknum; + (void)handle; + switch(data) { + case CURL_LOCK_DATA_SHARE: + what = "share"; + locknum = 0; + break; + case CURL_LOCK_DATA_DNS: + what = "dns"; + locknum = 1; + break; + case CURL_LOCK_DATA_COOKIE: + what = "cookie"; + locknum = 2; + break; + default: + fprintf(stderr, "unlock: no such data: %d\n", (int)data); + return; + } + + /* detect unlocking of unlocked locks */ + if(!locks[locknum]) { + printf("unlock: double unlocked %s\n", what); + return; + } + locks[locknum]--; + + printf("unlock: %-6s [%s]: %d\n", what, user->text, user->counter); + user->counter++; +} + + +/* build host entry */ +static struct curl_slist *sethost(struct curl_slist *headers) +{ + (void)headers; + return curl_slist_append(NULL, HOSTHEADER); +} + + +/* the dummy thread function */ +static void *test_fire(void *ptr) +{ + CURLcode code; + struct curl_slist *headers; + struct Tdata *tdata = (struct Tdata*)ptr; + CURL *curl; + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + return NULL; + } + + headers = sethost(NULL); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl, CURLOPT_URL, tdata->url); + curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); + printf("CURLOPT_SHARE\n"); + curl_easy_setopt(curl, CURLOPT_SHARE, tdata->share); + + printf("PERFORM\n"); + code = curl_easy_perform(curl); + if(code) { + int i = 0; + fprintf(stderr, "perform url '%s' repeat %d failed, curlcode %d\n", + tdata->url, i, (int)code); + } + + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + curl_slist_free_all(headers); + + return NULL; +} + + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + + +/* test function */ +CURLcode test(char *URL) +{ + CURLcode res; + CURLSHcode scode = CURLSHE_OK; + CURLcode code = CURLE_OK; + char *url = NULL; + struct Tdata tdata; + CURL *curl; + CURLSH *share; + struct curl_slist *headers = NULL; + struct curl_slist *cookies = NULL; + struct curl_slist *next_cookie = NULL; + int i; + struct userdata user; + + user.text = "Pigs in space"; + user.counter = 0; + + printf("GLOBAL_INIT\n"); + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* prepare share */ + printf("SHARE_INIT\n"); + share = curl_share_init(); + if(!share) { + fprintf(stderr, "curl_share_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_LOCKFUNC\n"); + scode = curl_share_setopt(share, CURLSHOPT_LOCKFUNC, test_lock); + } + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_UNLOCKFUNC\n"); + scode = curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, test_unlock); + } + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_USERDATA\n"); + scode = curl_share_setopt(share, CURLSHOPT_USERDATA, &user); + } + if(CURLSHE_OK == scode) { + printf("CURL_LOCK_DATA_COOKIE\n"); + scode = curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); + } + if(CURLSHE_OK == scode) { + printf("CURL_LOCK_DATA_DNS\n"); + scode = curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); + } + + if(CURLSHE_OK != scode) { + fprintf(stderr, "curl_share_setopt() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* initial cookie manipulation */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + printf("CURLOPT_SHARE\n"); + test_setopt(curl, CURLOPT_SHARE, share); + printf("CURLOPT_COOKIELIST injected_and_clobbered\n"); + test_setopt(curl, CURLOPT_COOKIELIST, + "Set-Cookie: injected_and_clobbered=yes; " + "domain=host.foo.com; expires=Sat Feb 2 11:56:27 GMT 2030"); + printf("CURLOPT_COOKIELIST ALL\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "ALL"); + printf("CURLOPT_COOKIELIST session\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "Set-Cookie: session=elephants"); + printf("CURLOPT_COOKIELIST injected\n"); + test_setopt(curl, CURLOPT_COOKIELIST, + "Set-Cookie: injected=yes; domain=host.foo.com; " + "expires=Sat Feb 2 11:56:27 GMT 2030"); + printf("CURLOPT_COOKIELIST SESS\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "SESS"); + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + + + res = CURLE_OK; + + /* start treads */ + for(i = 1; i <= THREADS; i++) { + + /* set thread data */ + tdata.url = suburl(URL, i); /* must be curl_free()d */ + tdata.share = share; + + /* simulate thread, direct call of "thread" function */ + printf("*** run %d\n",i); + test_fire(&tdata); + + curl_free(tdata.url); + } + + + /* fetch another one and save cookies */ + printf("*** run %d\n", i); + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + url = suburl(URL, i); + headers = sethost(NULL); + test_setopt(curl, CURLOPT_HTTPHEADER, headers); + test_setopt(curl, CURLOPT_URL, url); + printf("CURLOPT_SHARE\n"); + test_setopt(curl, CURLOPT_SHARE, share); + printf("CURLOPT_COOKIEJAR\n"); + test_setopt(curl, CURLOPT_COOKIEJAR, JAR); + printf("CURLOPT_COOKIELIST FLUSH\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "FLUSH"); + + printf("PERFORM\n"); + curl_easy_perform(curl); + + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + curl_free(url); + curl_slist_free_all(headers); + + /* load cookies */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + url = suburl(URL, i); + headers = sethost(NULL); + test_setopt(curl, CURLOPT_HTTPHEADER, headers); + test_setopt(curl, CURLOPT_URL, url); + printf("CURLOPT_SHARE\n"); + test_setopt(curl, CURLOPT_SHARE, share); + printf("CURLOPT_COOKIELIST ALL\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "ALL"); + printf("CURLOPT_COOKIEJAR\n"); + test_setopt(curl, CURLOPT_COOKIEFILE, JAR); + printf("CURLOPT_COOKIELIST RELOAD\n"); + test_setopt(curl, CURLOPT_COOKIELIST, "RELOAD"); + + code = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies); + if(code != CURLE_OK) { + fprintf(stderr, "curl_easy_getinfo() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + printf("loaded cookies:\n"); + if(!cookies) { + fprintf(stderr, " reloading cookies from '%s' failed\n", JAR); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + printf("-----------------\n"); + next_cookie = cookies; + while(next_cookie) { + printf(" %s\n", next_cookie->data); + next_cookie = next_cookie->next; + } + printf("-----------------\n"); + curl_slist_free_all(cookies); + + /* try to free share, expect to fail because share is in use */ + printf("try SHARE_CLEANUP...\n"); + scode = curl_share_cleanup(share); + if(scode == CURLSHE_OK) { + fprintf(stderr, "curl_share_cleanup succeed but error expected\n"); + share = NULL; + } + else { + printf("SHARE_CLEANUP failed, correct\n"); + } + +test_cleanup: + + /* clean up last handle */ + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + curl_slist_free_all(headers); + curl_free(url); + + /* free share */ + printf("SHARE_CLEANUP\n"); + scode = curl_share_cleanup(share); + if(scode != CURLSHE_OK) + fprintf(stderr, "curl_share_cleanup failed, code errno %d\n", + (int)scode); + + printf("GLOBAL_CLEANUP\n"); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib507.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib507.c new file mode 100644 index 0000000000000000000000000000000000000000..a228d08aa4b5f7632867d274763cad6632c5b7b7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib507.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLM *multi = NULL; + int still_running; + CURLcode i = (CURLcode)-1; + CURLcode res = CURLE_OK; + CURLMsg *msg; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multi); + + easy_init(curls); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_HEADER, 1L); + + multi_add_handle(multi, curls); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -99; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + + multi_perform(multi, &still_running); + + abort_on_test_timeout(); + } + + msg = curl_multi_info_read(multi, &still_running); + if(msg) + /* this should now contain a result code from the easy handle, + get it */ + i = msg->data.result; + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi); + curl_easy_cleanup(curls); + curl_global_cleanup(); + + if(res) + i = res; + + return i; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib508.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib508.c new file mode 100644 index 0000000000000000000000000000000000000000..fc25a0df60f9db5132ec4872497f826c4046ff43 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib508.c @@ -0,0 +1,105 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]="this is what we post to the silly web server\n"; + +struct WriteThis { + char *readptr; + size_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + + if(size*nmemb < 1) + return 0; + + if(pooh->sizeleft) { + *ptr = pooh->readptr[0]; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + pooh->sizeleft--; /* less data left */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + struct WriteThis pooh; + + pooh.readptr = testdata; + pooh.sizeleft = strlen(testdata); + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Set the expected POST size */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)pooh.sizeleft); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* pointer to pass to our read function */ + test_setopt(curl, CURLOPT_READDATA, &pooh); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib509.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib509.c new file mode 100644 index 0000000000000000000000000000000000000000..8a03b3b19d679858d48164cc956b1b8e7fb2baba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib509.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include + +/* + * This test uses these funny custom memory callbacks for the only purpose + * of verifying that curl_global_init_mem() functionality is present in + * libcurl and that it works unconditionally no matter how libcurl is built, + * nothing more. + * + * Do not include memdebug.h in this source file, and do not use directly + * memory related functions in this file except those used inside custom + * memory callbacks which should be calling 'the real thing'. + */ + +static int seen; + +static void *custom_calloc(size_t nmemb, size_t size) +{ + seen++; + return (calloc)(nmemb, size); +} + +static void *custom_malloc(size_t size) +{ + seen++; + return (malloc)(size); +} + +static char *custom_strdup(const char *ptr) +{ + seen++; + return (strdup)(ptr); +} + +static void *custom_realloc(void *ptr, size_t size) +{ + seen++; + return (realloc)(ptr, size); +} + +static void custom_free(void *ptr) +{ + seen++; + (free)(ptr); +} + + +CURLcode test(char *URL) +{ + unsigned char a[] = {0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe6, 0xf7}; + CURLcode res; + CURL *curl; + int asize; + char *str = NULL; + (void)URL; + + res = curl_global_init_mem(CURL_GLOBAL_ALL, + custom_malloc, + custom_free, + custom_realloc, + custom_strdup, + custom_calloc); + if(res != CURLE_OK) { + fprintf(stderr, "curl_global_init_mem() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_USERAGENT, "test509"); /* uses strdup() */ + + asize = (int)sizeof(a); + str = curl_easy_escape(curl, (char *)a, asize); /* uses realloc() */ + + if(seen) + printf("Callbacks were invoked!\n"); + +test_cleanup: + + if(str) + curl_free(str); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib510.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib510.c new file mode 100644 index 0000000000000000000000000000000000000000..2abd1cb7ed299778ff87b6ab8e1112b572f9e17e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib510.c @@ -0,0 +1,132 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static const char * const testpost[]={ + "one", + "two", + "three", + "and a final longer crap: four", + NULL +}; + + +struct WriteThis { + int counter; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + const char *data; + + if(size*nmemb < 1) + return 0; + + data = testpost[pooh->counter]; + + if(data) { + size_t len = strlen(data); + if(size*nmemb < len) { + fprintf(stderr, "read buffer is too small to run test\n"); + return 0; + } + memcpy(ptr, data, len); + pooh->counter++; /* advance pointer */ + return len; + } + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *slist = NULL; + struct WriteThis pooh; + pooh.counter = 0; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + slist = curl_slist_append(slist, "Transfer-Encoding: chunked"); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* pointer to pass to our read function */ + test_setopt(curl, CURLOPT_READDATA, &pooh); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* enforce chunked transfer by setting the header */ + test_setopt(curl, CURLOPT_HTTPHEADER, slist); + +#ifdef LIB565 + test_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST); + test_setopt(curl, CURLOPT_USERPWD, "foo:bar"); +#endif + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* clean up the headers list */ + if(slist) + curl_slist_free_all(slist); + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib511.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib511.c new file mode 100644 index 0000000000000000000000000000000000000000..b357e4d683a53c509f488a4f49a503ca8d953c17 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib511.c @@ -0,0 +1,58 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_FILETIME, 1L); + test_setopt(curl, CURLOPT_NOBODY, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib512.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib512.c new file mode 100644 index 0000000000000000000000000000000000000000..02e0d487c3e1e7e28131c6e6045b7547d52af3ec --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib512.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* Test case code based on source in a bug report filed by James Bursa on + 28 Apr 2004 */ + +CURLcode test(char *URL) +{ + CURLcode code; + int rc = 99; + + code = curl_global_init(CURL_GLOBAL_ALL); + if(code == CURLE_OK) { + CURL *curl = curl_easy_init(); + if(curl) { + CURL *curl2; + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_HEADER, 1L); + + curl2 = curl_easy_duphandle(curl); + if(curl2) { + + code = curl_easy_setopt(curl2, CURLOPT_URL, URL); + if(code == CURLE_OK) { + + code = curl_easy_perform(curl2); + if(code == CURLE_OK) + rc = 0; + else + rc = 1; + } + else + rc = 2; + + curl_easy_cleanup(curl2); + } + else + rc = 3; + + curl_easy_cleanup(curl); + } + else + rc = 4; + + curl_global_cleanup(); + } + else + rc = 5; + + return (CURLcode)rc; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib513.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib513.c new file mode 100644 index 0000000000000000000000000000000000000000..208245acfa617218c1faab6b33b49e168f15fa83 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib513.c @@ -0,0 +1,85 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + (void)ptr; + (void)size; + (void)nmemb; + (void)userp; + return CURL_READFUNC_ABORT; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Set the expected POST size */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, 1L); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* pointer to pass to our read function */ + test_setopt(curl, CURLOPT_READDATA, NULL); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib514.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib514.c new file mode 100644 index 0000000000000000000000000000000000000000..73877061315edc5f866cf3435ebbb5dc4a5959a1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib514.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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Based on a bug report by Niels van Tongeren on June 29, 2004: + + A weird situation occurs when request 1 is a POST request and the request + 2 is a HEAD request. For the POST request we set the CURLOPT_POSTFIELDS, + CURLOPT_POSTFIELDSIZE and CURLOPT_POST options. For the HEAD request we + set the CURLOPT_NOBODY option to '1'. + + */ + + test_setopt(curl, CURLOPT_POSTFIELDS, "moo"); + test_setopt(curl, CURLOPT_POSTFIELDSIZE, 3L); + test_setopt(curl, CURLOPT_POST, 1L); + + /* this is where transfer 1 would take place, but skip that and change + options right away instead */ + + test_setopt(curl, CURLOPT_NOBODY, 1L); + + test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */ + test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */ + + /* Now, we should be making a fine HEAD request */ + + /* Perform the request 2, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib515.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib515.c new file mode 100644 index 0000000000000000000000000000000000000000..7edfe4e5ed47cdf56359eb14ce4e6976f316050a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib515.c @@ -0,0 +1,62 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_POSTFIELDS, NULL); + test_setopt(curl, CURLOPT_POSTFIELDSIZE, 0L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */ + test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */ + + /* Now, we should be making a zero byte POST request */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib516.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib516.c new file mode 100644 index 0000000000000000000000000000000000000000..fc94eaabc0b81d48e9f6dae1571da9dd4b074fc5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib516.c @@ -0,0 +1,63 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_HTTPPOST, NULL); + ) + test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */ + test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */ + + /* Now, we should be making a zero byte POST request */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib517.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib517.c new file mode 100644 index 0000000000000000000000000000000000000000..e769ae5af5aac84692b4e43078c94631d4d80a90 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib517.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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +struct dcheck { + const char *input; + time_t output; +}; + +static const struct dcheck dates[] = { + {"Sun, 06 Nov 1994 08:49:37 GMT", 784111777 }, + {"Sunday, 06-Nov-94 08:49:37 GMT", 784111777 }, + {"Sun Nov 6 08:49:37 1994", 784111777 }, + {"Sun Nov 6 8:49:37 1994", 784111777 }, + {"Sun Nov 6 8:9:37 1994", 784109377 }, + {"Sun Nov 6 008:09:37 1994", -1 }, + {"Nov Sun 6 8:9:7 1994", 784109347 }, + {"06 Nov 1994 08:49:37 GMT", 784111777 }, + {"06-Nov-94 08:49:37 GMT", 784111777 }, + {"Nov 6 08:49:37 1994", 784111777 }, + {"06 Nov 1994 08:49:37", 784111777 }, + {"06-Nov-94 08:49:37", 784111777 }, + {"1994 Nov 6 08:49:37", 784111777 }, + {"GMT 08:49:37 06-Nov-94 Sunday", 784111777 }, + {"94 6 Nov 08:49:37", 784111777 }, + {"1994 Nov 6", 784080000 }, + {"06-Nov-94", 784080000 }, + {"Sun Nov 6 94", 784080000 }, + {"1994.Nov.6", 784080000 }, + {"Sun/Nov/6/94/GMT", 784080000 }, + {"Sun, 06 Nov 1994 08:49:37 CET", 784108177 }, + {"06 Nov 1994 08:49:37 EST", 784129777 }, + {"Sun, 06 Nov 1994 08:49:37 UT", 784111777 }, + {"Sun, 12 Sep 2004 15:05:58 -0700", 1095026758 }, + {"Sat, 11 Sep 2004 21:32:11 +0200", 1094931131 }, + {"20040912 15:05:58 -0700", 1095026758 }, + {"20040911 +0200", 1094853600 }, + {"Thu, 01-Jan-1970 00:59:59 GMT", 3599 }, + {"Thu, 01-Jan-1970 01:00:00 GMT", 3600 }, + {"Sat, 15-Apr-17 21:01:22 GMT", 1492290082 }, + {"Thu, 19-Apr-2007 16:00:00 GMT", 1176998400 }, + {"Wed, 25 Apr 2007 21:02:13 GMT", 1177534933 }, + {"Thu, 19/Apr\\2007 16:00:00 GMT", 1176998400 }, + {"Fri, 1 Jan 2010 01:01:50 GMT", 1262307710 }, + {"Wednesday, 1-Jan-2003 00:00:00 GMT", 1041379200 }, + {", 1-Jan-2003 00:00:00 GMT", 1041379200 }, + {"1-Jan-2003 00:00:00 GMT", 1041379200 }, + {"1-Jan-2003 00:00:00 GMT", 1041379200 }, + {"Wed,18-Apr-07 22:50:12 GMT", 1176936612 }, + {"WillyWonka , 18-Apr-07 22:50:12 GMT", -1 }, + {"WillyWonka , 18-Apr-07 22:50:12", -1 }, + {"WillyWonka , 18-apr-07 22:50:12", -1 }, + {"Mon, 18-Apr-1977 22:50:13 GMT", 230251813 }, + {"Mon, 18-Apr-77 22:50:13 GMT", 230251813 }, + {"Sat, 15-Apr-17\"21:01:22\"GMT", 1492290082 }, + {"Partyday, 18- April-07 22:50:12", -1 }, + {"Partyday, 18 - Apri-07 22:50:12", -1 }, + {"Wednes, 1-Januar-2003 00:00:00 GMT", -1 }, + {"Sat, 15-Apr-17 21:01:22", 1492290082 }, + {"Sat, 15-Apr-17 21:01:22 GMT-2", 1492290082 }, + {"Sat, 15-Apr-17 21:01:22 GMT BLAH", 1492290082 }, + {"Sat, 15-Apr-17 21:01:22 GMT-0400", 1492290082 }, + {"Sat, 15-Apr-17 21:01:22 GMT-0400 (EDT)", 1492290082 }, + {"Sat, 15-Apr-17 21:01:22 DST", -1 }, + {"Sat, 15-Apr-17 21:01:22 -0400", 1492304482 }, + {"Sat, 15-Apr-17 21:01:22 (hello there)", -1 }, + {"Sat, 15-Apr-17 21:01:22 11:22:33", -1 }, + {"Sat, 15-Apr-17 ::00 21:01:22", -1 }, + {"Sat, 15-Apr-17 boink:z 21:01:22", -1 }, + {"Sat, 15-Apr-17 91:22:33 21:01:22", -1 }, + {"Thu Apr 18 22:50:12 2007 GMT", 1176936612 }, + {"22:50:12 Thu Apr 18 2007 GMT", 1176936612 }, + {"Thu 22:50:12 Apr 18 2007 GMT", 1176936612 }, + {"Thu Apr 22:50:12 18 2007 GMT", 1176936612 }, + {"Thu Apr 18 22:50:12 2007 GMT", 1176936612 }, + {"Thu Apr 18 2007 22:50:12 GMT", 1176936612 }, + {"Thu Apr 18 2007 GMT 22:50:12", 1176936612 }, + {"Sat, 15-Apr-17 21:01:22 GMT", 1492290082 }, + {"15-Sat, Apr-17 21:01:22 GMT", 1492290082 }, + {"15-Sat, Apr 21:01:22 GMT 17", 1492290082 }, + {"15-Sat, Apr 21:01:22 GMT 2017", 1492290082 }, + {"15 Apr 21:01:22 2017", 1492290082 }, + {"15 17 Apr 21:01:22", 1492290082 }, + {"Apr 15 17 21:01:22", 1492290082 }, + {"Apr 15 21:01:22 17", 1492290082 }, + {"2017 April 15 21:01:22", -1 }, + {"15 April 2017 21:01:22", -1 }, + {"98 April 17 21:01:22", -1 }, + {"Thu, 012-Aug-2008 20:49:07 GMT", 1218574147 }, + {"Thu, 999999999999-Aug-2007 20:49:07 GMT", -1 }, + {"Thu, 12-Aug-2007 20:61:99999999999 GMT", -1 }, + {"IAintNoDateFool", -1 }, + {"Thu Apr 18 22:50 2007 GMT", 1176936600 }, + {"20110623 12:34:56", 1308832496 }, + {"20110632 12:34:56", -1 }, + {"20110623 56:34:56", -1 }, + {"20111323 12:34:56", -1 }, + {"20110623 12:34:79", -1 }, + {"Wed, 31 Dec 2008 23:59:60 GMT", 1230768000 }, + {"Wed, 31 Dec 2008 23:59:61 GMT", -1 }, + {"Wed, 31 Dec 2008 24:00:00 GMT", -1 }, + {"Wed, 31 Dec 2008 23:60:59 GMT", -1 }, + {"20110623 12:3", 1308830580 }, + {"20110623 1:3", 1308790980 }, + {"20110623 1:30", 1308792600 }, + {"20110623 12:12:3", 1308831123 }, + {"20110623 01:12:3", 1308791523 }, + {"20110623 01:99:30", -1 }, + {"Thu, 01-Jan-1970 00:00:00 GMT", 0 }, + {"Thu, 31-Dec-1969 23:59:58 GMT", -2 }, + {"Thu, 31-Dec-1969 23:59:59 GMT", 0 }, /* avoids -1 ! */ +#if SIZEOF_TIME_T > 4 + {"Sun, 06 Nov 2044 08:49:37 GMT", (time_t) CURL_OFF_TU_C(2362034977) }, + {"Sun, 06 Nov 3144 08:49:37 GMT", 37074617377 }, +#ifndef HAVE_TIME_T_UNSIGNED +#if 0 + /* causes warning on MSVC */ + {"Sun, 06 Nov 1900 08:49:37 GMT", -2182259423 }, +#endif + {"Sun, 06 Nov 1800 08:49:37 GMT", -5337933023 }, + {"Thu, 01-Jan-1583 00:00:00 GMT", -12212553600 }, +#endif + {"Thu, 01-Jan-1499 00:00:00 GMT", -1 }, +#else + {"Sun, 06 Nov 2044 08:49:37 GMT", -1 }, +#endif +#ifndef HAVE_TIME_T_UNSIGNED + {"Sun, 06 Nov 1968 08:49:37 GMT", -36342623 }, +#endif + { NULL, 0 } +}; + +CURLcode test(char *URL) +{ + int i; + int error = 0; + + (void)URL; /* not used */ + + for(i = 0; dates[i].input; i++) { + time_t out = curl_getdate(dates[i].input, NULL); + if(out != dates[i].output) { + printf("WRONGLY %s => %ld (instead of %ld)\n", + dates[i].input, (long)out, (long)dates[i].output); + error++; + } + } + + return error == 0 ? CURLE_OK : TEST_ERR_FAILURE; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib518.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib518.c new file mode 100644 index 0000000000000000000000000000000000000000..289692c3f9ce572e6fc98ef53ac0f239536590c7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib518.c @@ -0,0 +1,507 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif +#include + +#include "warnless.h" +#include "memdebug.h" + +#ifndef FD_SETSIZE +#error "this test requires FD_SETSIZE" +#endif + +#define SAFETY_MARGIN (16) +#define NUM_OPEN (FD_SETSIZE + 10) +#define NUM_NEEDED (NUM_OPEN + SAFETY_MARGIN) + +#if defined(_WIN32) || defined(MSDOS) +#define DEV_NULL "NUL" +#else +#define DEV_NULL "/dev/null" +#endif + +#if defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) + +static int *testfd = NULL; +static struct rlimit num_open; +static char msgbuff[256]; + +static void store_errmsg(const char *msg, int err) +{ + if(!err) + msnprintf(msgbuff, sizeof(msgbuff), "%s", msg); + else + msnprintf(msgbuff, sizeof(msgbuff), "%s, errno %d, %s", msg, + err, strerror(err)); +} + +static void close_file_descriptors(void) +{ + for(num_open.rlim_cur = 0; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) + if(testfd[num_open.rlim_cur] > 0) + close(testfd[num_open.rlim_cur]); + free(testfd); + testfd = NULL; +} + +static int fopen_works(void) +{ + FILE *fpa[3]; + int i; + int ret = 1; + + for(i = 0; i < 3; i++) { + fpa[i] = NULL; + } + for(i = 0; i < 3; i++) { + fpa[i] = fopen(DEV_NULL, FOPEN_READTEXT); + if(!fpa[i]) { + store_errmsg("fopen failed", errno); + fprintf(stderr, "%s\n", msgbuff); + ret = 0; + break; + } + } + for(i = 0; i < 3; i++) { + if(fpa[i]) + fclose(fpa[i]); + } + return ret; +} + +static void rlim2str(char *buf, size_t len, rlim_t val) +{ +#ifdef RLIM_INFINITY + if(val == RLIM_INFINITY) { + msnprintf(buf, len, "INFINITY"); + return; + } +#endif +#ifdef HAVE_LONGLONG + if(sizeof(rlim_t) > sizeof(long)) + msnprintf(buf, len, "%llu", (unsigned long long)val); + else +#endif + { + if(sizeof(rlim_t) < sizeof(long)) + msnprintf(buf, len, "%u", (unsigned int)val); + else + msnprintf(buf, len, "%lu", (unsigned long)val); + } +} + +static int test_rlimit(int keep_open) +{ + rlim_t nitems, i; + int *memchunk = NULL; + struct rlimit rl; + char strbuff[256]; + char strbuff1[81]; + char strbuff2[81]; + + /* get initial open file limits */ + + if(getrlimit(RLIMIT_NOFILE, &rl) != 0) { + store_errmsg("getrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -1; + } + + /* show initial open file limits */ + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_cur); + fprintf(stderr, "initial soft limit: %s\n", strbuff); + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_max); + fprintf(stderr, "initial hard limit: %s\n", strbuff); + + /* show our constants */ + + fprintf(stderr, "test518 FD_SETSIZE: %d\n", FD_SETSIZE); + fprintf(stderr, "test518 NUM_OPEN : %d\n", NUM_OPEN); + fprintf(stderr, "test518 NUM_NEEDED: %d\n", NUM_NEEDED); + + /* + * if soft limit and hard limit are different we ask the + * system to raise soft limit all the way up to the hard + * limit. Due to some other system limit the soft limit + * might not be raised up to the hard limit. So from this + * point the resulting soft limit is our limit. Trying to + * open more than soft limit file descriptors will fail. + */ + + if(rl.rlim_cur != rl.rlim_max) { + +#ifdef OPEN_MAX + if((rl.rlim_cur > 0) && + (rl.rlim_cur < OPEN_MAX)) { + fprintf(stderr, "raising soft limit up to OPEN_MAX\n"); + rl.rlim_cur = OPEN_MAX; + if(setrlimit(RLIMIT_NOFILE, &rl) != 0) { + /* on failure don't abort just issue a warning */ + store_errmsg("setrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + msgbuff[0] = '\0'; + } + } +#endif + + fprintf(stderr, "raising soft limit up to hard limit\n"); + rl.rlim_cur = rl.rlim_max; + if(setrlimit(RLIMIT_NOFILE, &rl) != 0) { + /* on failure don't abort just issue a warning */ + store_errmsg("setrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + msgbuff[0] = '\0'; + } + + /* get current open file limits */ + + if(getrlimit(RLIMIT_NOFILE, &rl) != 0) { + store_errmsg("getrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -3; + } + + /* show current open file limits */ + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_cur); + fprintf(stderr, "current soft limit: %s\n", strbuff); + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_max); + fprintf(stderr, "current hard limit: %s\n", strbuff); + + } /* (rl.rlim_cur != rl.rlim_max) */ + + /* + * test 518 is all about testing libcurl functionality + * when more than FD_SETSIZE file descriptors are open. + * This means that if for any reason we are not able to + * open more than FD_SETSIZE file descriptors then test + * 518 should not be run. + */ + + /* + * verify that soft limit is higher than NUM_NEEDED, + * which is the number of file descriptors we would + * try to open plus SAFETY_MARGIN to not exhaust the + * file descriptor pool + */ + + num_open.rlim_cur = NUM_NEEDED; + + if((rl.rlim_cur > 0) && +#ifdef RLIM_INFINITY + (rl.rlim_cur != RLIM_INFINITY) && +#endif + (rl.rlim_cur <= num_open.rlim_cur)) { + rlim2str(strbuff2, sizeof(strbuff2), rl.rlim_cur); + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "fds needed %s > system limit %s", + strbuff1, strbuff2); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + return -4; + } + + /* + * reserve a chunk of memory before opening file descriptors to + * avoid a low memory condition once the file descriptors are + * open. System conditions that could make the test fail should + * be addressed in the precheck phase. This chunk of memory shall + * be always free()ed before exiting the test_rlimit() function so + * that it becomes available to the test. + */ + + for(nitems = i = 1; nitems <= i; i *= 2) + nitems = i; + if(nitems > 0x7fff) + nitems = 0x40000; + do { + num_open.rlim_max = sizeof(*memchunk) * nitems; + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "allocating memchunk %s byte array\n", strbuff); + memchunk = malloc(sizeof(*memchunk) * (size_t)nitems); + if(!memchunk) { + fprintf(stderr, "memchunk, malloc() failed\n"); + nitems /= 2; + } + } while(nitems && !memchunk); + if(!memchunk) { + store_errmsg("memchunk, malloc() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -5; + } + + /* initialize it to fight lazy allocation */ + + fprintf(stderr, "initializing memchunk array\n"); + + for(i = 0; i < nitems; i++) + memchunk[i] = -1; + + /* set the number of file descriptors we will try to open */ + + num_open.rlim_max = NUM_OPEN; + + /* verify that we won't overflow size_t in malloc() */ + + if((size_t)(num_open.rlim_max) > ((size_t)-1) / sizeof(*testfd)) { + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_max); + msnprintf(strbuff, sizeof(strbuff), "unable to allocate an array for %s " + "file descriptors, would overflow size_t", strbuff1); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + free(memchunk); + return -6; + } + + /* allocate array for file descriptors */ + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "allocating array for %s file descriptors\n", strbuff); + + testfd = malloc(sizeof(*testfd) * (size_t)(num_open.rlim_max)); + if(!testfd) { + store_errmsg("testfd, malloc() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + free(memchunk); + return -7; + } + + /* initialize it to fight lazy allocation */ + + fprintf(stderr, "initializing testfd array\n"); + + for(num_open.rlim_cur = 0; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) + testfd[num_open.rlim_cur] = -1; + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "trying to open %s file descriptors\n", strbuff); + + /* open a dummy descriptor */ + + testfd[0] = open(DEV_NULL, O_RDONLY); + if(testfd[0] < 0) { + msnprintf(strbuff, sizeof(strbuff), "opening of %s failed", DEV_NULL); + store_errmsg(strbuff, errno); + fprintf(stderr, "%s\n", msgbuff); + free(testfd); + testfd = NULL; + free(memchunk); + return -8; + } + + /* create a bunch of file descriptors */ + + for(num_open.rlim_cur = 1; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) { + + testfd[num_open.rlim_cur] = dup(testfd[0]); + + if(testfd[num_open.rlim_cur] < 0) { + + testfd[num_open.rlim_cur] = -1; + + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "dup() attempt %s failed", strbuff1); + fprintf(stderr, "%s\n", strbuff); + + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "fds system limit seems close to %s", + strbuff1); + fprintf(stderr, "%s\n", strbuff); + + num_open.rlim_max = NUM_NEEDED; + + rlim2str(strbuff2, sizeof(strbuff2), num_open.rlim_max); + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "fds needed %s > system limit %s", + strbuff2, strbuff1); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + + for(num_open.rlim_cur = 0; + testfd[num_open.rlim_cur] >= 0; + num_open.rlim_cur++) + close(testfd[num_open.rlim_cur]); + free(testfd); + testfd = NULL; + free(memchunk); + return -9; + } + } + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "%s file descriptors open\n", strbuff); + +#if !defined(HAVE_POLL) && !defined(USE_WINSOCK) + + /* + * when using select() instead of poll() we cannot test + * libcurl functionality with a socket number equal or + * greater than FD_SETSIZE. In any case, macro VERIFY_SOCK + * in lib/select.c enforces this check and protects libcurl + * from a possible crash. The effect of this protection + * is that test 518 will always fail, since the actual + * call to select() never takes place. We skip test 518 + * with an indication that select limit would be exceeded. + */ + + num_open.rlim_cur = FD_SETSIZE - SAFETY_MARGIN; + if(num_open.rlim_max > num_open.rlim_cur) { + msnprintf(strbuff, sizeof(strbuff), "select limit is FD_SETSIZE %d", + FD_SETSIZE); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + close_file_descriptors(); + free(memchunk); + return -10; + } + + num_open.rlim_cur = FD_SETSIZE - SAFETY_MARGIN; + for(rl.rlim_cur = 0; + rl.rlim_cur < num_open.rlim_max; + rl.rlim_cur++) { + if((testfd[rl.rlim_cur] > 0) && + ((unsigned int)testfd[rl.rlim_cur] > num_open.rlim_cur)) { + msnprintf(strbuff, sizeof(strbuff), "select limit is FD_SETSIZE %d", + FD_SETSIZE); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + close_file_descriptors(); + free(memchunk); + return -11; + } + } + +#endif /* using a FD_SETSIZE bound select() */ + + /* + * Old or 'backwards compatible' implementations of stdio do not allow + * handling of streams with an underlying file descriptor number greater + * than 255, even when allowing high numbered file descriptors for sockets. + * At this point we have a big number of file descriptors which have been + * opened using dup(), so lets test the stdio implementation and discover + * if it is capable of fopen()ing some additional files. + */ + + if(!fopen_works()) { + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_max); + msnprintf(strbuff, sizeof(strbuff), "fopen fails with %s fds open", + strbuff1); + fprintf(stderr, "%s\n", msgbuff); + msnprintf(strbuff, sizeof(strbuff), "fopen fails with lots of fds open"); + store_errmsg(strbuff, 0); + close_file_descriptors(); + free(memchunk); + return -12; + } + + /* free the chunk of memory we were reserving so that it + becomes available to the test */ + + free(memchunk); + + /* close file descriptors unless instructed to keep them */ + + if(!keep_open) { + close_file_descriptors(); + } + + return 0; +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(!strcmp(URL, "check")) { + /* used by the test script to ask if we can run this test or not */ + if(test_rlimit(FALSE)) { + fprintf(stdout, "test_rlimit problem: %s\n", msgbuff); + return (CURLcode)1; + } + return CURLE_OK; /* sure, run this! */ + } + + if(test_rlimit(TRUE)) { + /* failure */ + return TEST_ERR_MAJOR_BAD; + } + + /* run the test with the bunch of open file descriptors + and close them all once the test is over */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + close_file_descriptors(); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + close_file_descriptors(); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + close_file_descriptors(); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} + +#else /* defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) */ + +CURLcode test(char *URL) +{ + (void)URL; + printf("system lacks necessary system function(s)"); + return 1; /* skip test */ +} + +#endif /* defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) */ diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib519.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib519.c new file mode 100644 index 0000000000000000000000000000000000000000..fcc8a6a0407dac0ab985eb7ad45df00e0f2bbb71 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib519.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_USERPWD, "monster:underbed"); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* get first page */ + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_USERPWD, "anothermonster:inwardrobe"); + + /* get second page */ + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib520.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib520.c new file mode 100644 index 0000000000000000000000000000000000000000..13257c4706cecbe0ce3ff223a53189865854b11d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib520.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_FILETIME, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib521.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib521.c new file mode 100644 index 0000000000000000000000000000000000000000..dc884437519efab37b014e7a8d4aa9e4771e89ca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib521.c @@ -0,0 +1,58 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PORT, strtol(libtest_arg2, NULL, 10)); + test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib523.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib523.c new file mode 100644 index 0000000000000000000000000000000000000000..5c7338e7c925cf4c33aa40271449514551d98249 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib523.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PORT, 19999L); + test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib524.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib524.c new file mode 100644 index 0000000000000000000000000000000000000000..ec721bee251152a3bfc5c3b8d24c644c4d4bad4c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib524.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib525.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib525.c new file mode 100644 index 0000000000000000000000000000000000000000..f64070b56b86a16acd907d982790253bf3823662 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib525.c @@ -0,0 +1,164 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + FILE *hd_src = NULL; + int hd; + struct_stat file_info; + CURLM *m = NULL; + int running; + + start_test_timing(); + + if(!libtest_arg2) { +#ifdef LIB529 + /* test 529 */ + fprintf(stderr, "Usage: lib529 [url] [uploadfile]\n"); +#else + /* test 525 */ + fprintf(stderr, "Usage: lib525 [url] [uploadfile]\n"); +#endif + return TEST_ERR_USAGE; + } + + hd_src = fopen(libtest_arg2, "rb"); + if(!hd_src) { + fprintf(stderr, "fopen failed with error: %d (%s)\n", + errno, strerror(errno)); + fprintf(stderr, "Error opening file: (%s)\n", libtest_arg2); + return TEST_ERR_FOPEN; + } + + /* get the file size of the local file */ + hd = fstat(fileno(hd_src), &file_info); + if(hd == -1) { + /* can't open file, bail out */ + fprintf(stderr, "fstat() failed with error: %d (%s)\n", + errno, strerror(errno)); + fprintf(stderr, "ERROR: cannot open file (%s)\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_FSTAT; + } + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + fclose(hd_src); + return res; + } + + easy_init(curl); + + /* enable uploading */ + easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target */ + easy_setopt(curl, CURLOPT_URL, URL); + + /* go verbose */ + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* use active FTP */ + easy_setopt(curl, CURLOPT_FTPPORT, "-"); + + /* now specify which file to upload */ + easy_setopt(curl, CURLOPT_READDATA, hd_src); + + /* NOTE: if you want this code to work on Windows with libcurl as a DLL, you + MUST also provide a read callback with CURLOPT_READFUNCTION. Failing to + do so will give you a crash since a DLL may not use the variable's memory + when passed in to it from an app like this. */ + + /* Set the size of the file to upload (optional). If you give a *_LARGE + option you MUST make sure that the type of the passed-in argument is a + curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must + make sure that to pass in a type 'long' argument. */ + easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size); + + multi_init(m); + + multi_add_handle(m, curl); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + +#ifdef LIB529 + /* test 529 */ + /* proper cleanup sequence - type PA */ + curl_multi_remove_handle(m, curl); + curl_multi_cleanup(m); + curl_easy_cleanup(curl); + curl_global_cleanup(); +#else + /* test 525 */ + /* proper cleanup sequence - type PB */ + curl_multi_remove_handle(m, curl); + curl_easy_cleanup(curl); + curl_multi_cleanup(m); + curl_global_cleanup(); +#endif + + /* close the local file */ + fclose(hd_src); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib526.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib526.c new file mode 100644 index 0000000000000000000000000000000000000000..5fd81b51eb84189526793b5e60656f3eec4adab7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib526.c @@ -0,0 +1,186 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 code sets up multiple easy handles that transfer a single file from + * the same URL, in a serial manner after each other. Due to the connection + * sharing within the multi handle all transfers are performed on the same + * persistent connection. + * + * This source code is used for lib526, lib527 and lib532 with only #ifdefs + * controlling the small differences. + * + * - lib526 closes all easy handles after + * they all have transferred the file over the single connection + * - lib527 closes each easy handle after each single transfer. + * - lib532 uses only a single easy handle that is removed, reset and then + * re-added for each transfer + * + * Test case 526, 527 and 532 use FTP, while test 528 uses the lib526 tool but + * with HTTP. + */ + +#include "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define NUM_HANDLES 4 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl[NUM_HANDLES]; + int running; + CURLM *m = NULL; + int current = 0; + int i; + + for(i = 0; i < NUM_HANDLES; i++) + curl[i] = NULL; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + /* get NUM_HANDLES easy handles */ + for(i = 0; i < NUM_HANDLES; i++) { + easy_init(curl[i]); + /* specify target */ + easy_setopt(curl[i], CURLOPT_URL, URL); + /* go verbose */ + easy_setopt(curl[i], CURLOPT_VERBOSE, 1L); + } + + multi_init(m); + + multi_add_handle(m, curl[current]); + + fprintf(stderr, "Start at URL 0\n"); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) { +#ifdef LIB527 + /* NOTE: this code does not remove the handle from the multi handle + here, which would be the nice, sane and documented way of working. + This however tests that the API survives this abuse gracefully. */ + curl_easy_cleanup(curl[current]); + curl[current] = NULL; +#endif + if(++current < NUM_HANDLES) { + fprintf(stderr, "Advancing to URL %d\n", current); +#ifdef LIB532 + /* first remove the only handle we use */ + curl_multi_remove_handle(m, curl[0]); + + /* make us reuse the same handle all the time, and try resetting + the handle first too */ + curl_easy_reset(curl[0]); + easy_setopt(curl[0], CURLOPT_URL, URL); + /* go verbose */ + easy_setopt(curl[0], CURLOPT_VERBOSE, 1L); + + /* re-add it */ + multi_add_handle(m, curl[0]); +#else + multi_add_handle(m, curl[current]); +#endif + } + else { + break; /* done */ + } + } + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + +#if defined(LIB526) + + /* test 526 and 528 */ + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(m, curl[i]); + curl_easy_cleanup(curl[i]); + } + curl_multi_cleanup(m); + curl_global_cleanup(); + +#elif defined(LIB527) + + /* test 527 */ + + /* Upon non-failure test flow the easy's have already been cleanup'ed. In + case there is a failure we arrive here with easy's that have not been + cleanup'ed yet, in this case we have to cleanup them or otherwise these + will be leaked, let's use undocumented cleanup sequence - type UB */ + + if(res != CURLE_OK) + for(i = 0; i < NUM_HANDLES; i++) + curl_easy_cleanup(curl[i]); + + curl_multi_cleanup(m); + curl_global_cleanup(); + +#elif defined(LIB532) + + /* test 532 */ + /* undocumented cleanup sequence - type UB */ + + for(i = 0; i < NUM_HANDLES; i++) + curl_easy_cleanup(curl[i]); + curl_multi_cleanup(m); + curl_global_cleanup(); + +#endif + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib530.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib530.c new file mode 100644 index 0000000000000000000000000000000000000000..5f24c904bc5a2291dd3384bde3d6f47a7e14860b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib530.c @@ -0,0 +1,393 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 purpose of this test is to make sure that if CURLMOPT_SOCKETFUNCTION or + * CURLMOPT_TIMERFUNCTION returns error, the associated transfer should be + * aborted correctly. + */ + +#include "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +struct Sockets { + curl_socket_t *sockets; + int count; /* number of sockets actually stored in array */ + int max_count; /* max number of sockets that fit in allocated array */ +}; + +struct ReadWriteSockets { + struct Sockets read, write; +}; + +/** + * Remove a file descriptor from a sockets array. + */ +static void removeFd(struct Sockets *sockets, curl_socket_t fd, int mention) +{ + int i; + + if(mention) + fprintf(stderr, "Remove socket fd %d\n", (int) fd); + + for(i = 0; i < sockets->count; ++i) { + if(sockets->sockets[i] == fd) { + if(i < sockets->count - 1) + memmove(&sockets->sockets[i], &sockets->sockets[i + 1], + sizeof(curl_socket_t) * (sockets->count - (i + 1))); + --sockets->count; + } + } +} + +/** + * Add a file descriptor to a sockets array. + * Return 0 on success, 1 on error. + */ +static int addFd(struct Sockets *sockets, curl_socket_t fd, const char *what) +{ + /** + * To ensure we only have each file descriptor once, we remove it then add + * it again. + */ + fprintf(stderr, "Add socket fd %d for %s\n", (int) fd, what); + removeFd(sockets, fd, 0); + /* + * Allocate array storage when required. + */ + if(!sockets->sockets) { + sockets->sockets = malloc(sizeof(curl_socket_t) * 20U); + if(!sockets->sockets) + return 1; + sockets->max_count = 20; + } + else if(sockets->count + 1 > sockets->max_count) { + curl_socket_t *ptr = realloc(sockets->sockets, sizeof(curl_socket_t) * + (sockets->max_count + 20)); + if(!ptr) + /* cleanup in test_cleanup */ + return 1; + sockets->sockets = ptr; + sockets->max_count += 20; + } + /* + * Add file descriptor to array. + */ + sockets->sockets[sockets->count] = fd; + ++sockets->count; + return 0; +} + +static int max_socket_calls; +static int socket_calls = 0; + +/** + * Callback invoked by curl to poll reading / writing of a socket. + */ +static int curlSocketCallback(CURL *easy, curl_socket_t s, int action, + void *userp, void *socketp) +{ + struct ReadWriteSockets *sockets = userp; + + (void)easy; /* unused */ + (void)socketp; /* unused */ + + fprintf(stderr, "CURLMOPT_SOCKETFUNCTION called: %u\n", socket_calls++); + if(socket_calls == max_socket_calls) { + fprintf(stderr, "curlSocketCallback returns error\n"); + return -1; + } + + if(action == CURL_POLL_IN || action == CURL_POLL_INOUT) + if(addFd(&sockets->read, s, "read")) + return -1; /* bail out */ + + if(action == CURL_POLL_OUT || action == CURL_POLL_INOUT) + if(addFd(&sockets->write, s, "write")) + return -1; + + if(action == CURL_POLL_REMOVE) { + removeFd(&sockets->read, s, 1); + removeFd(&sockets->write, s, 0); + } + + return 0; +} + +static int max_timer_calls; +static int timer_calls = 0; + +/** + * Callback invoked by curl to set a timeout. + */ +static int curlTimerCallback(CURLM *multi, long timeout_ms, void *userp) +{ + struct timeval *timeout = userp; + + (void)multi; /* unused */ + fprintf(stderr, "CURLMOPT_TIMERFUNCTION called: %u\n", timer_calls++); + if(timer_calls == max_timer_calls) { + fprintf(stderr, "curlTimerCallback returns error\n"); + return -1; + } + if(timeout_ms != -1) { + *timeout = tutil_tvnow(); + timeout->tv_usec += (int)timeout_ms * 1000; + } + else { + timeout->tv_sec = -1; + } + return 0; +} + +/** + * Check for curl completion. + */ +static int checkForCompletion(CURLM *curl, int *success) +{ + int result = 0; + *success = 0; + while(1) { + int numMessages; + CURLMsg *message = curl_multi_info_read(curl, &numMessages); + if(!message) + break; + if(message->msg == CURLMSG_DONE) { + result = 1; + if(message->data.result == CURLE_OK) + *success = 1; + else + *success = 0; + } + else { + fprintf(stderr, "Got an unexpected message from curl: %i\n", + message->msg); + result = 1; + *success = 0; + } + } + return result; +} + +static int getMicroSecondTimeout(struct timeval *timeout) +{ + struct timeval now; + ssize_t result; + now = tutil_tvnow(); + result = (ssize_t)((timeout->tv_sec - now.tv_sec) * 1000000 + + timeout->tv_usec - now.tv_usec); + if(result < 0) + result = 0; + + return curlx_sztosi(result); +} + +/** + * Update a fd_set with all of the sockets in use. + */ +static void updateFdSet(struct Sockets *sockets, fd_set* fdset, + curl_socket_t *maxFd) +{ + int i; + for(i = 0; i < sockets->count; ++i) { + FD_SET(sockets->sockets[i], fdset); + if(*maxFd < sockets->sockets[i] + 1) { + *maxFd = sockets->sockets[i] + 1; + } + } +} + +static int socket_action(CURLM *curl, curl_socket_t s, int evBitmask, + const char *info) +{ + int numhandles = 0; + CURLMcode result = curl_multi_socket_action(curl, s, evBitmask, &numhandles); + if(result != CURLM_OK) { + fprintf(stderr, "Curl error on %s: %i (%s)\n", + info, result, curl_multi_strerror(result)); + } + return (int)result; +} + +/** + * Invoke curl when a file descriptor is set. + */ +static int checkFdSet(CURLM *curl, + struct Sockets *sockets, fd_set *fdset, + int evBitmask, const char *name) +{ + int i; + int result = 0; + for(i = 0; i < sockets->count; ++i) { + if(FD_ISSET(sockets->sockets[i], fdset)) { + result = socket_action(curl, sockets->sockets[i], evBitmask, name); + if(result) + break; + } + } + return result; +} + +static CURLcode testone(char *URL, int timercb, int socketcb) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; CURLM *m = NULL; + struct ReadWriteSockets sockets = {{NULL, 0, 0}, {NULL, 0, 0}}; + struct timeval timeout = {-1, 0}; + int success = 0; + + /* set the limits */ + max_timer_calls = timercb; + max_socket_calls = socketcb; + timer_calls = 0; /* reset the globals */ + socket_calls = 0; + + fprintf(stderr, "start test: %d %d\n", timercb, socketcb); + start_test_timing(); + + res_global_init(CURL_GLOBAL_ALL); + if(res != CURLE_OK) + return res; + + easy_init(curl); + + /* specify target */ + easy_setopt(curl, CURLOPT_URL, URL); + + /* go verbose */ + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + multi_init(m); + + multi_setopt(m, CURLMOPT_SOCKETFUNCTION, curlSocketCallback); + multi_setopt(m, CURLMOPT_SOCKETDATA, &sockets); + + multi_setopt(m, CURLMOPT_TIMERFUNCTION, curlTimerCallback); + multi_setopt(m, CURLMOPT_TIMERDATA, &timeout); + + multi_add_handle(m, curl); + + if(socket_action(m, CURL_SOCKET_TIMEOUT, 0, "timeout")) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + while(!checkForCompletion(m, &success)) { + fd_set readSet, writeSet; + curl_socket_t maxFd = 0; + struct timeval tv = {10, 0}; + + FD_ZERO(&readSet); + FD_ZERO(&writeSet); + updateFdSet(&sockets.read, &readSet, &maxFd); + updateFdSet(&sockets.write, &writeSet, &maxFd); + + if(timeout.tv_sec != -1) { + int usTimeout = getMicroSecondTimeout(&timeout); + tv.tv_sec = usTimeout / 1000000; + tv.tv_usec = usTimeout % 1000000; + } + else if(maxFd <= 0) { + tv.tv_sec = 0; + tv.tv_usec = 100000; + } + + assert(maxFd); + select_test((int)maxFd, &readSet, &writeSet, NULL, &tv); + + /* Check the sockets for reading / writing */ + if(checkFdSet(m, &sockets.read, &readSet, CURL_CSELECT_IN, "read")) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + if(checkFdSet(m, &sockets.write, &writeSet, CURL_CSELECT_OUT, "write")) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + if(timeout.tv_sec != -1 && getMicroSecondTimeout(&timeout) == 0) { + /* Curl's timer has elapsed. */ + if(socket_action(m, CURL_SOCKET_TIMEOUT, 0, "timeout")) { + res = TEST_ERR_BAD_TIMEOUT; + goto test_cleanup; + } + } + + abort_on_test_timeout(); + } + + if(!success) { + fprintf(stderr, "Error getting file.\n"); + res = TEST_ERR_MAJOR_BAD; + } + +test_cleanup: + + /* proper cleanup sequence */ + fprintf(stderr, "cleanup: %d %d\n", timercb, socketcb); + curl_multi_remove_handle(m, curl); + curl_easy_cleanup(curl); + curl_multi_cleanup(m); + curl_global_cleanup(); + + /* free local memory */ + free(sockets.read.sockets); + free(sockets.write.sockets); + return res; +} + +CURLcode test(char *URL) +{ + CURLcode rc; + /* rerun the same transfer multiple times and make it fail in different + callback calls */ + rc = testone(URL, 0, 0); + if(rc) + fprintf(stderr, "test 0/0 failed: %d\n", rc); + + rc = testone(URL, 1, 0); + if(!rc) + fprintf(stderr, "test 1/0 failed: %d\n", rc); + + rc = testone(URL, 2, 0); + if(!rc) + fprintf(stderr, "test 2/0 failed: %d\n", rc); + + rc = testone(URL, 0, 1); + if(!rc) + fprintf(stderr, "test 0/1 failed: %d\n", rc); + + rc = testone(URL, 0, 2); + if(!rc) + fprintf(stderr, "test 0/2 failed: %d\n", rc); + + return CURLE_OK; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib533.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib533.c new file mode 100644 index 0000000000000000000000000000000000000000..dc48bb46255bed94f4d7e5e883e44cae432f297d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib533.c @@ -0,0 +1,114 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* used for test case 533, 534 and 535 */ + +#include "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + int running; + CURLM *m = NULL; + int current = 0; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_FAILONERROR, 1L); + + multi_init(m); + + multi_add_handle(m, curl); + + fprintf(stderr, "Start at URL 0\n"); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) { + if(!current++) { + fprintf(stderr, "Advancing to URL 1\n"); + /* remove the handle we use */ + curl_multi_remove_handle(m, curl); + + /* make us reuse the same handle all the time, and try resetting + the handle first too */ + curl_easy_reset(curl); + easy_setopt(curl, CURLOPT_URL, libtest_arg2); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_FAILONERROR, 1L); + + /* re-add it */ + multi_add_handle(m, curl); + } + else + break; /* done */ + } + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* undocumented cleanup sequence - type UB */ + + curl_easy_cleanup(curl); + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib536.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib536.c new file mode 100644 index 0000000000000000000000000000000000000000..73edf43d4102104347e9663add64898e2e193db3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib536.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 "test.h" + +#include "memdebug.h" + +#define WITH_PROXY "http://usingproxy.com/" +#define WITHOUT_PROXY libtest_arg2 + +static void proxystat(CURL *curl) +{ + long wasproxy; + if(!curl_easy_getinfo(curl, CURLINFO_USED_PROXY, &wasproxy)) { + printf("This %sthe proxy\n", wasproxy ? "used ": + "DID NOT use "); + } +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl; + struct curl_slist *host = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + host = curl_slist_append(NULL, libtest_arg3); + if(!host) + goto test_cleanup; + + test_setopt(curl, CURLOPT_RESOLVE, host); + test_setopt(curl, CURLOPT_PROXY, URL); + test_setopt(curl, CURLOPT_URL, WITH_PROXY); + test_setopt(curl, CURLOPT_NOPROXY, "goingdirect.com"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + if(!res) { + proxystat(curl); + test_setopt(curl, CURLOPT_URL, WITHOUT_PROXY); + res = curl_easy_perform(curl); + if(!res) + proxystat(curl); + } + +test_cleanup: + + curl_easy_cleanup(curl); + curl_slist_free_all(host); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib537.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib537.c new file mode 100644 index 0000000000000000000000000000000000000000..6e1baee7ed4b5ab5a7b367c830c4c7e87539b925 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib537.c @@ -0,0 +1,518 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif +#include + +#include "warnless.h" +#include "memdebug.h" + +#if !defined(HAVE_POLL) && !defined(USE_WINSOCK) && !defined(FD_SETSIZE) +#error "this test requires FD_SETSIZE" +#endif + +#define SAFETY_MARGIN (11) + +#if defined(_WIN32) || defined(MSDOS) +#define DEV_NULL "NUL" +#else +#define DEV_NULL "/dev/null" +#endif + +#if defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) + +static int *testfd = NULL; +static struct rlimit num_open; +static char msgbuff[256]; + +static void store_errmsg(const char *msg, int err) +{ + if(!err) + msnprintf(msgbuff, sizeof(msgbuff), "%s", msg); + else + msnprintf(msgbuff, sizeof(msgbuff), "%s, errno %d, %s", msg, + err, strerror(err)); +} + +static void close_file_descriptors(void) +{ + for(num_open.rlim_cur = 0; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) + if(testfd[num_open.rlim_cur] > 0) + close(testfd[num_open.rlim_cur]); + free(testfd); + testfd = NULL; +} + +static int fopen_works(void) +{ + FILE *fpa[3]; + int i; + int ret = 1; + + for(i = 0; i < 3; i++) { + fpa[i] = NULL; + } + for(i = 0; i < 3; i++) { + fpa[i] = fopen(DEV_NULL, FOPEN_READTEXT); + if(!fpa[i]) { + store_errmsg("fopen failed", errno); + fprintf(stderr, "%s\n", msgbuff); + ret = 0; + break; + } + } + for(i = 0; i < 3; i++) { + if(fpa[i]) + fclose(fpa[i]); + } + return ret; +} + +static void rlim2str(char *buf, size_t len, rlim_t val) +{ +#ifdef RLIM_INFINITY + if(val == RLIM_INFINITY) { + msnprintf(buf, len, "INFINITY"); + return; + } +#endif +#ifdef HAVE_LONGLONG + if(sizeof(rlim_t) > sizeof(long)) + msnprintf(buf, len, "%llu", (unsigned long long)val); + else +#endif + { + if(sizeof(rlim_t) < sizeof(long)) + msnprintf(buf, len, "%u", (unsigned int)val); + else + msnprintf(buf, len, "%lu", (unsigned long)val); + } +} + +static int test_rlimit(int keep_open) +{ + int *tmpfd; + rlim_t nitems, i; + int *memchunk = NULL; + struct rlimit rl; + char strbuff[256]; + char strbuff1[81]; + + /* get initial open file limits */ + + if(getrlimit(RLIMIT_NOFILE, &rl) != 0) { + store_errmsg("getrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -1; + } + + /* show initial open file limits */ + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_cur); + fprintf(stderr, "initial soft limit: %s\n", strbuff); + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_max); + fprintf(stderr, "initial hard limit: %s\n", strbuff); + + /* If the OS allows a HUGE number of open files, we do not run. + * Modern debian sid reports a limit of 134217724 and this tests + * takes minutes. */ +#define LIMIT_CAP (256*1024) + if(rl.rlim_cur > LIMIT_CAP) { + fprintf(stderr, "soft limit above %ld, not running\n", (long)LIMIT_CAP); + return -2; + } + + /* + * if soft limit and hard limit are different we ask the + * system to raise soft limit all the way up to the hard + * limit. Due to some other system limit the soft limit + * might not be raised up to the hard limit. So from this + * point the resulting soft limit is our limit. Trying to + * open more than soft limit file descriptors will fail. + */ + + if(rl.rlim_cur != rl.rlim_max) { + +#ifdef OPEN_MAX + if((rl.rlim_cur > 0) && + (rl.rlim_cur < OPEN_MAX)) { + fprintf(stderr, "raising soft limit up to OPEN_MAX\n"); + rl.rlim_cur = OPEN_MAX; + if(setrlimit(RLIMIT_NOFILE, &rl) != 0) { + /* on failure don't abort just issue a warning */ + store_errmsg("setrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + msgbuff[0] = '\0'; + } + } +#endif + + fprintf(stderr, "raising soft limit up to hard limit\n"); + rl.rlim_cur = rl.rlim_max; + if(setrlimit(RLIMIT_NOFILE, &rl) != 0) { + /* on failure don't abort just issue a warning */ + store_errmsg("setrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + msgbuff[0] = '\0'; + } + + /* get current open file limits */ + + if(getrlimit(RLIMIT_NOFILE, &rl) != 0) { + store_errmsg("getrlimit() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -3; + } + + /* show current open file limits */ + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_cur); + fprintf(stderr, "current soft limit: %s\n", strbuff); + + rlim2str(strbuff, sizeof(strbuff), rl.rlim_max); + fprintf(stderr, "current hard limit: %s\n", strbuff); + + } /* (rl.rlim_cur != rl.rlim_max) */ + + /* + * test 537 is all about testing libcurl functionality + * when the system has nearly exhausted the number of + * available file descriptors. Test 537 will try to run + * with a very small number of file descriptors available. + * This implies that any file descriptor which is open + * when the test runs will have a number in the high range + * of whatever the system supports. + */ + + /* + * reserve a chunk of memory before opening file descriptors to + * avoid a low memory condition once the file descriptors are + * open. System conditions that could make the test fail should + * be addressed in the precheck phase. This chunk of memory shall + * be always free()ed before exiting the test_rlimit() function so + * that it becomes available to the test. + */ + + for(nitems = i = 1; nitems <= i; i *= 2) + nitems = i; + if(nitems > 0x7fff) + nitems = 0x40000; + do { + num_open.rlim_max = sizeof(*memchunk) * nitems; + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "allocating memchunk %s byte array\n", strbuff); + memchunk = malloc(sizeof(*memchunk) * (size_t)nitems); + if(!memchunk) { + fprintf(stderr, "memchunk, malloc() failed\n"); + nitems /= 2; + } + } while(nitems && !memchunk); + if(!memchunk) { + store_errmsg("memchunk, malloc() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + return -4; + } + + /* initialize it to fight lazy allocation */ + + fprintf(stderr, "initializing memchunk array\n"); + + for(i = 0; i < nitems; i++) + memchunk[i] = -1; + + /* set the number of file descriptors we will try to open */ + +#ifdef RLIM_INFINITY + if((rl.rlim_cur > 0) && (rl.rlim_cur != RLIM_INFINITY)) { +#else + if(rl.rlim_cur > 0) { +#endif + /* soft limit minus SAFETY_MARGIN */ + num_open.rlim_max = rl.rlim_cur - SAFETY_MARGIN; + } + else { + /* a huge number of file descriptors */ + for(nitems = i = 1; nitems <= i; i *= 2) + nitems = i; + if(nitems > 0x7fff) + nitems = 0x40000; + num_open.rlim_max = nitems; + } + + /* verify that we won't overflow size_t in malloc() */ + + if((size_t)(num_open.rlim_max) > ((size_t)-1) / sizeof(*testfd)) { + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_max); + msnprintf(strbuff, sizeof(strbuff), "unable to allocate an array for %s " + "file descriptors, would overflow size_t", strbuff1); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + free(memchunk); + return -5; + } + + /* allocate array for file descriptors */ + + do { + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "allocating array for %s file descriptors\n", strbuff); + + testfd = malloc(sizeof(*testfd) * (size_t)(num_open.rlim_max)); + if(!testfd) { + fprintf(stderr, "testfd, malloc() failed\n"); + num_open.rlim_max /= 2; + } + } while(num_open.rlim_max && !testfd); + if(!testfd) { + store_errmsg("testfd, malloc() failed", errno); + fprintf(stderr, "%s\n", msgbuff); + free(memchunk); + return -6; + } + + /* initialize it to fight lazy allocation */ + + fprintf(stderr, "initializing testfd array\n"); + + for(num_open.rlim_cur = 0; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) + testfd[num_open.rlim_cur] = -1; + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "trying to open %s file descriptors\n", strbuff); + + /* open a dummy descriptor */ + + testfd[0] = open(DEV_NULL, O_RDONLY); + if(testfd[0] < 0) { + msnprintf(strbuff, sizeof(strbuff), "opening of %s failed", DEV_NULL); + store_errmsg(strbuff, errno); + fprintf(stderr, "%s\n", msgbuff); + free(testfd); + testfd = NULL; + free(memchunk); + return -7; + } + + /* create a bunch of file descriptors */ + + for(num_open.rlim_cur = 1; + num_open.rlim_cur < num_open.rlim_max; + num_open.rlim_cur++) { + + testfd[num_open.rlim_cur] = dup(testfd[0]); + + if(testfd[num_open.rlim_cur] < 0) { + + testfd[num_open.rlim_cur] = -1; + + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "dup() attempt %s failed", strbuff1); + fprintf(stderr, "%s\n", strbuff); + + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "fds system limit seems close to %s", + strbuff1); + fprintf(stderr, "%s\n", strbuff); + + num_open.rlim_max = num_open.rlim_cur - SAFETY_MARGIN; + + num_open.rlim_cur -= num_open.rlim_max; + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_cur); + msnprintf(strbuff, sizeof(strbuff), "closing %s file descriptors", + strbuff1); + fprintf(stderr, "%s\n", strbuff); + + for(num_open.rlim_cur = num_open.rlim_max; + testfd[num_open.rlim_cur] >= 0; + num_open.rlim_cur++) { + close(testfd[num_open.rlim_cur]); + testfd[num_open.rlim_cur] = -1; + } + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "shrinking array for %s file descriptors\n", strbuff); + + /* we don't care if we can't shrink it */ + + tmpfd = realloc(testfd, sizeof(*testfd) * (size_t)(num_open.rlim_max)); + if(tmpfd) { + testfd = tmpfd; + tmpfd = NULL; + } + + break; + } + } + + rlim2str(strbuff, sizeof(strbuff), num_open.rlim_max); + fprintf(stderr, "%s file descriptors open\n", strbuff); + +#if !defined(HAVE_POLL) && !defined(USE_WINSOCK) + + /* + * when using select() instead of poll() we cannot test + * libcurl functionality with a socket number equal or + * greater than FD_SETSIZE. In any case, macro VERIFY_SOCK + * in lib/select.c enforces this check and protects libcurl + * from a possible crash. The effect of this protection + * is that test 537 will always fail, since the actual + * call to select() never takes place. We skip test 537 + * with an indication that select limit would be exceeded. + */ + + num_open.rlim_cur = FD_SETSIZE - SAFETY_MARGIN; + if(num_open.rlim_max > num_open.rlim_cur) { + msnprintf(strbuff, sizeof(strbuff), "select limit is FD_SETSIZE %d", + FD_SETSIZE); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + close_file_descriptors(); + free(memchunk); + return -8; + } + + num_open.rlim_cur = FD_SETSIZE - SAFETY_MARGIN; + for(rl.rlim_cur = 0; + rl.rlim_cur < num_open.rlim_max; + rl.rlim_cur++) { + if((testfd[rl.rlim_cur] > 0) && + ((unsigned int)testfd[rl.rlim_cur] > num_open.rlim_cur)) { + msnprintf(strbuff, sizeof(strbuff), "select limit is FD_SETSIZE %d", + FD_SETSIZE); + store_errmsg(strbuff, 0); + fprintf(stderr, "%s\n", msgbuff); + close_file_descriptors(); + free(memchunk); + return -9; + } + } + +#endif /* using a FD_SETSIZE bound select() */ + + /* + * Old or 'backwards compatible' implementations of stdio do not allow + * handling of streams with an underlying file descriptor number greater + * than 255, even when allowing high numbered file descriptors for sockets. + * At this point we have a big number of file descriptors which have been + * opened using dup(), so lets test the stdio implementation and discover + * if it is capable of fopen()ing some additional files. + */ + + if(!fopen_works()) { + rlim2str(strbuff1, sizeof(strbuff1), num_open.rlim_max); + msnprintf(strbuff, sizeof(strbuff), "fopen fails with %s fds open", + strbuff1); + fprintf(stderr, "%s\n", msgbuff); + msnprintf(strbuff, sizeof(strbuff), "fopen fails with lots of fds open"); + store_errmsg(strbuff, 0); + close_file_descriptors(); + free(memchunk); + return -10; + } + + /* free the chunk of memory we were reserving so that it + becomes available to the test */ + + free(memchunk); + + /* close file descriptors unless instructed to keep them */ + + if(!keep_open) { + close_file_descriptors(); + } + + return 0; +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(!strcmp(URL, "check")) { + /* used by the test script to ask if we can run this test or not */ + if(test_rlimit(FALSE)) { + fprintf(stdout, "test_rlimit problem: %s\n", msgbuff); + return (CURLcode)1; + } + return CURLE_OK; /* sure, run this! */ + } + + if(test_rlimit(TRUE)) { + /* failure */ + return TEST_ERR_MAJOR_BAD; + } + + /* run the test with the bunch of open file descriptors + and close them all once the test is over */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + close_file_descriptors(); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + close_file_descriptors(); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(curl); + +test_cleanup: + + close_file_descriptors(); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} + +#else /* defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) */ + +CURLcode test(char *URL) +{ + (void)URL; + printf("system lacks necessary system function(s)"); + return (CURLcode)1; /* skip test */ +} + +#endif /* defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) */ diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib539.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib539.c new file mode 100644 index 0000000000000000000000000000000000000000..2e079fae368d9fd9d7b041d41c86b94b171fc266 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib539.c @@ -0,0 +1,86 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + char *newURL = NULL; + struct curl_slist *slist = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* + * Begin with curl set to use a single CWD to the URL's directory. + */ + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD); + + res = curl_easy_perform(curl); + + /* + * Change the FTP_FILEMETHOD option to use full paths rather than a CWD + * command. Use an innocuous QUOTE command, after which curl will CWD to + * ftp_conn->entrypath and then (on the next call to ftp_statemach_act) + * find a non-zero ftpconn->dirdepth even though no directories are stored + * in the ftpconn->dirs array (after a call to freedirs). + */ + + slist = curl_slist_append(NULL, "SYST"); + if(!slist) { + curl_free(newURL); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, libtest_arg2); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD); + test_setopt(curl, CURLOPT_QUOTE, slist); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_slist_free_all(slist); + curl_free(newURL); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib540.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib540.c new file mode 100644 index 0000000000000000000000000000000000000000..b53b955639f801c92c3b26fc5e736a3521c70cb1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib540.c @@ -0,0 +1,256 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 the 'proxyauth.c' test app posted by Shmulik Regev on the libcurl + * mailing list on 10 Jul 2007, converted to a test case. + * + * argv1 = URL + * argv2 = proxy + * argv3 = proxyuser:password + * argv4 = host name to use for the custom Host: header + */ + +#include "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +#define PROXY libtest_arg2 +#define PROXYUSERPWD libtest_arg3 +#define HOST test_argv[4] + +#define NUM_HANDLES 2 + +static CURL *testeh[NUM_HANDLES]; + +static CURLcode init(int num, CURLM *cm, const char *url, const char *userpwd, + struct curl_slist *headers) +{ + CURLcode res = CURLE_OK; + + res_easy_init(testeh[num]); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_URL, url); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_PROXY, PROXY); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_PROXYUSERPWD, userpwd); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_PROXYAUTH, (long)CURLAUTH_ANY); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_VERBOSE, 1L); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_HEADER, 1L); + if(res) + goto init_failed; + + res_easy_setopt(testeh[num], CURLOPT_HTTPHEADER, headers); /* custom Host: */ + if(res) + goto init_failed; + + res_multi_add_handle(cm, testeh[num]); + if(res) + goto init_failed; + + return CURLE_OK; /* success */ + +init_failed: + + curl_easy_cleanup(testeh[num]); + testeh[num] = NULL; + + return res; /* failure */ +} + +static CURLcode loop(int num, CURLM *cm, const char *url, const char *userpwd, + struct curl_slist *headers) +{ + CURLMsg *msg; + long L; + int Q, U = -1; + fd_set R, W, E; + struct timeval T; + CURLcode res = CURLE_OK; + + res = init(num, cm, url, userpwd, headers); + if(res) + return res; + + while(U) { + + int M = -99; + + res_multi_perform(cm, &U); + if(res) + return res; + + res_test_timedout(); + if(res) + return res; + + if(U) { + FD_ZERO(&R); + FD_ZERO(&W); + FD_ZERO(&E); + + res_multi_fdset(cm, &R, &W, &E, &M); + if(res) + return res; + + /* At this point, M is guaranteed to be greater or equal than -1. */ + + res_multi_timeout(cm, &L); + if(res) + return res; + + /* At this point, L is guaranteed to be greater or equal than -1. */ + + if(L != -1) { + int itimeout; +#if LONG_MAX > INT_MAX + itimeout = (L > INT_MAX) ? INT_MAX : (int)L; +#else + itimeout = (int)L; +#endif + T.tv_sec = itimeout/1000; + T.tv_usec = (itimeout%1000)*1000; + } + else { + T.tv_sec = 5; + T.tv_usec = 0; + } + + res_select_test(M + 1, &R, &W, &E, &T); + if(res) + return res; + } + + while(1) { + msg = curl_multi_info_read(cm, &Q); + if(!msg) + break; + if(msg->msg == CURLMSG_DONE) { + int i; + CURL *e = msg->easy_handle; + fprintf(stderr, "R: %d - %s\n", (int)msg->data.result, + curl_easy_strerror(msg->data.result)); + curl_multi_remove_handle(cm, e); + curl_easy_cleanup(e); + for(i = 0; i < NUM_HANDLES; i++) { + if(testeh[i] == e) { + testeh[i] = NULL; + break; + } + } + } + else + fprintf(stderr, "E: CURLMsg (%d)\n", (int)msg->msg); + } + + res_test_timedout(); + if(res) + return res; + } + + return CURLE_OK; +} + +CURLcode test(char *URL) +{ + CURLM *cm = NULL; + struct curl_slist *headers = NULL; + char buffer[246]; /* naively fixed-size */ + CURLcode res = CURLE_OK; + int i; + + for(i = 0; i < NUM_HANDLES; i++) + testeh[i] = NULL; + + start_test_timing(); + + if(test_argc < 4) + return (CURLcode)99; + + msnprintf(buffer, sizeof(buffer), "Host: %s", HOST); + + /* now add a custom Host: header */ + headers = curl_slist_append(headers, buffer); + if(!headers) { + fprintf(stderr, "curl_slist_append() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + curl_slist_free_all(headers); + return res; + } + + res_multi_init(cm); + if(res) { + curl_global_cleanup(); + curl_slist_free_all(headers); + return res; + } + + res = loop(0, cm, URL, PROXYUSERPWD, headers); + if(res) + goto test_cleanup; + + fprintf(stderr, "lib540: now we do the request again\n"); + + res = loop(1, cm, URL, PROXYUSERPWD, headers); + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < NUM_HANDLES; i++) { + curl_multi_remove_handle(cm, testeh[i]); + curl_easy_cleanup(testeh[i]); + } + + curl_multi_cleanup(cm); + curl_global_cleanup(); + + curl_slist_free_all(headers); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib541.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib541.c new file mode 100644 index 0000000000000000000000000000000000000000..7dd53195e7e16fc5334076d4176692415a3c268d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib541.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* + * Two FTP uploads, the second with no content sent. + */ + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + FILE *hd_src; + int hd; + struct_stat file_info; + + if(!libtest_arg2) { + fprintf(stderr, "Usage: \n"); + return TEST_ERR_USAGE; + } + + hd_src = fopen(libtest_arg2, "rb"); + if(!hd_src) { + fprintf(stderr, "fopen failed with error: %d %s\n", + errno, strerror(errno)); + fprintf(stderr, "Error opening file: %s\n", libtest_arg2); + return (CURLcode)-2; /* if this happens things are major weird */ + } + + /* get the file size of the local file */ + hd = fstat(fileno(hd_src), &file_info); + if(hd == -1) { + /* can't open file, bail out */ + fprintf(stderr, "fstat() failed with error: %d %s\n", + errno, strerror(errno)); + fprintf(stderr, "ERROR: cannot open file %s\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + if(!file_info.st_size) { + fprintf(stderr, "ERROR: file %s has zero size!\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + /* get a curl handle */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + fclose(hd_src); + return TEST_ERR_MAJOR_BAD; + } + + /* enable uploading */ + test_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* enable verbose */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* specify target */ + test_setopt(curl, CURLOPT_URL, URL); + + /* now specify which file to upload */ + test_setopt(curl, CURLOPT_READDATA, hd_src); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* and now upload the exact same again, but without rewinding so it already + is at end of file */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* close the local file */ + fclose(hd_src); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib542.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib542.c new file mode 100644 index 0000000000000000000000000000000000000000..2be67488ed0688c9e86b194ac47f07a92dbf58d9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib542.c @@ -0,0 +1,75 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* + * FTP get with NOBODY but no HEADER + */ + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* get a curl handle */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* enable verbose */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* enable NOBODY */ + test_setopt(curl, CURLOPT_NOBODY, 1L); + + /* disable HEADER */ + test_setopt(curl, CURLOPT_HEADER, 0L); + + /* specify target */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib543.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib543.c new file mode 100644 index 0000000000000000000000000000000000000000..077cf16b6d638236813731ee24e77381a21a0787 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib543.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* Based on Alex Fishman's bug report on September 30, 2007 */ + +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + static const unsigned char a[] = { + 0x9c, 0x26, 0x4b, 0x3d, 0x49, 0x4, 0xa1, 0x1, + 0xe0, 0xd8, 0x7c, 0x20, 0xb7, 0xef, 0x53, 0x29, 0xfa, + 0x1d, 0x57, 0xe1}; + + CURL *easy; + CURLcode res = CURLE_OK; + (void)URL; + + global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + } + else { + int asize = (int)sizeof(a); + char *s = curl_easy_escape(easy, (const char *)a, asize); + + if(s) { + printf("%s\n", s); + curl_free(s); + } + + s = curl_easy_escape(easy, "", 0); + if(s) { + printf("IN: '' OUT: '%s'\n", s); + curl_free(s); + } + s = curl_easy_escape(easy, " 123", 3); + if(s) { + printf("IN: ' 12' OUT: '%s'\n", s); + curl_free(s); + } + + curl_easy_cleanup(easy); + } + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib544.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib544.c new file mode 100644 index 0000000000000000000000000000000000000000..6228e7d9f7b2c5322a681fcdf89d42e74e5dbad1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib544.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 "test.h" + +#include "memdebug.h" + +static char teststring[] = +{ 'T', 'h', 'i', 's', '\0', ' ', 'i', 's', ' ', 't', 'e', 's', 't', ' ', + 'b', 'i', 'n', 'a', 'r', 'y', ' ', 'd', 'a', 't', 'a', ' ', + 'w', 'i', 't', 'h', ' ', 'a', 'n', ' ', + 'e', 'm', 'b', 'e', 'd', 'd', 'e', 'd', ' ', 'N', 'U', 'L'}; + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + +#ifdef LIB545 + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) sizeof(teststring)); +#endif + + test_setopt(curl, CURLOPT_COPYPOSTFIELDS, teststring); + + test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */ + test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */ + + /* Update the original data to detect non-copy. */ + strcpy(teststring, "FAIL"); + + { + CURL *handle2; + handle2 = curl_easy_duphandle(curl); + curl_easy_cleanup(curl); + + curl = handle2; + } + + /* Now, this is a POST request with binary 0 embedded in POST data. */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib547.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib547.c new file mode 100644 index 0000000000000000000000000000000000000000..a84ce999c85fd601c4f139f718e4a9fa3d97e36d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib547.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 + * + ***************************************************************************/ +/* argv1 = URL + * argv2 = proxy + * argv3 = proxyuser:password + */ + +#include "test.h" + +#include "memdebug.h" + +#define UPLOADTHIS "this is the blurb we want to upload\n" + +#ifndef LIB548 +static size_t readcallback(char *ptr, + size_t size, + size_t nmemb, + void *clientp) +{ + int *counter = (int *)clientp; + + if(*counter) { + /* only do this once and then require a clearing of this */ + fprintf(stderr, "READ ALREADY DONE!\n"); + return 0; + } + (*counter)++; /* bump */ + + if(size * nmemb >= strlen(UPLOADTHIS)) { + fprintf(stderr, "READ!\n"); + strcpy(ptr, UPLOADTHIS); + return strlen(UPLOADTHIS); + } + fprintf(stderr, "READ NOT FINE!\n"); + return 0; +} +static curlioerr ioctlcallback(CURL *handle, + int cmd, + void *clientp) +{ + int *counter = (int *)clientp; + (void)handle; /* unused */ + if(cmd == CURLIOCMD_RESTARTREAD) { + fprintf(stderr, "REWIND!\n"); + *counter = 0; /* clear counter to make the read callback restart */ + } + return CURLIOE_OK; +} + + + +#endif + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; +#ifndef LIB548 + int counter = 0; +#endif + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); +#ifdef LIB548 + /* set the data to POST with a mere pointer to a null-terminated string */ + test_setopt(curl, CURLOPT_POSTFIELDS, UPLOADTHIS); +#else + /* 547 style, which means reading the POST data from a callback */ + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctlcallback); + test_setopt(curl, CURLOPT_IOCTLDATA, &counter); + ) + test_setopt(curl, CURLOPT_READFUNCTION, readcallback); + test_setopt(curl, CURLOPT_READDATA, &counter); + /* We CANNOT do the POST fine without setting the size (or choose + chunked)! */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(UPLOADTHIS)); +#endif + test_setopt(curl, CURLOPT_POST, 1L); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_PROXYUSERPWD, libtest_arg3); + test_setopt(curl, CURLOPT_PROXYAUTH, + (long) (CURLAUTH_NTLM | CURLAUTH_DIGEST | CURLAUTH_BASIC) ); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib549.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib549.c new file mode 100644 index 0000000000000000000000000000000000000000..7bd67093f246ebc772c9a9302852503517b3bccb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib549.c @@ -0,0 +1,67 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* argv1 = URL + * argv2 = proxy + * argv3 = non-zero means ASCII transfer + */ + +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_PROXY_TRANSFER_MODE, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + if(libtest_arg3) { + /* enable ASCII/text mode */ + test_setopt(curl, CURLOPT_TRANSFERTEXT, 1L); + } + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib552.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib552.c new file mode 100644 index 0000000000000000000000000000000000000000..0920b025a8ae30fd94b3d6ff4101544ab3da82c3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib552.c @@ -0,0 +1,221 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* argv1 = URL + * argv2 = proxy with embedded user+password + */ + +#include "test.h" + +#include "warnless.h" +#include "memdebug.h" + +struct testdata { + char trace_ascii; /* 1 or 0 */ +}; + +static +void dump(const char *text, + FILE *stream, unsigned char *ptr, size_t size, + char nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stream, "%s, %zu bytes (0x%zx)\n", text, size, size); + + for(i = 0; i < size; i += width) { + + fprintf(stream, "%04zx: ", i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stream, "%02x ", ptr[i + c]); + else + fputs(" ", stream); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D && + ptr[i + c + 1] == 0x0A) { + i += (c + 2 - width); + break; + } + fprintf(stream, "%c", + (ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80) ? ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && + ptr[i + c + 2] == 0x0A) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stream); /* newline */ + } + fflush(stream); +} + +static +int my_trace(CURL *handle, curl_infotype type, + char *data, size_t size, + void *userp) +{ + struct testdata *config = (struct testdata *)userp; + const char *text; + (void)handle; /* prevent compiler warning */ + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "== Info: %s", (char *)data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + dump(text, stderr, (unsigned char *)data, size, config->trace_ascii); + return 0; +} + + +static size_t current_offset = 0; +static char databuf[70000]; /* MUST be more than 64k OR + MAX_INITIAL_POST_SIZE */ + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *stream) +{ + size_t amount = nmemb * size; /* Total bytes curl wants */ + size_t available = sizeof(databuf) - current_offset; /* What we have to + give */ + size_t given = amount < available ? amount : available; /* What is given */ + (void)stream; + memcpy(ptr, databuf + current_offset, given); + current_offset += given; + return given; +} + + +static size_t write_callback(char *ptr, size_t size, size_t nmemb, + void *stream) +{ + int amount = curlx_uztosi(size * nmemb); + printf("%.*s", amount, (char *)ptr); + (void)stream; + return size * nmemb; +} + + +static curlioerr ioctl_callback(CURL *handle, int cmd, void *clientp) +{ + (void)clientp; + if(cmd == CURLIOCMD_RESTARTREAD) { + printf("APPLICATION received a CURLIOCMD_RESTARTREAD request\n"); + printf("APPLICATION ** REWINDING! **\n"); + current_offset = 0; + return CURLIOE_OK; + } + (void)handle; + return CURLIOE_UNKNOWNCMD; +} + + + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct testdata config; + size_t i; + static const char fill[] = "test data"; + + config.trace_ascii = 1; /* enable ASCII tracing */ + + global_init(CURL_GLOBAL_ALL); + easy_init(curl); + + test_setopt(curl, CURLOPT_DEBUGFUNCTION, my_trace); + test_setopt(curl, CURLOPT_DEBUGDATA, &config); + /* the DEBUGFUNCTION has no effect until we enable VERBOSE */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* setup repeated data string */ + for(i = 0; i < sizeof(databuf); ++i) + databuf[i] = fill[i % sizeof(fill)]; + + /* Post */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Setup read callback */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) sizeof(databuf)); + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* Write callback */ + test_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); + + /* Ioctl function */ + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctl_callback); + ) + + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); + + test_setopt(curl, CURLOPT_URL, URL); + + /* Accept any auth. But for this bug configure proxy with DIGEST, basic + might work too, not NTLM */ + test_setopt(curl, CURLOPT_PROXYAUTH, (long)CURLAUTH_ANY); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib553.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib553.c new file mode 100644 index 0000000000000000000000000000000000000000..e33cf148ff9e1da9e99969dc57d7359d3a38977b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib553.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 + * + ***************************************************************************/ + +/* This test case and code is based on the bug recipe Joe Malicki provided for + * bug report #1871269, fixed on Jan 14 2008 before the 7.18.0 release. + */ + +#include "test.h" + +#include "memdebug.h" + +#define POSTLEN 40960 + +static size_t myreadfunc(char *ptr, size_t size, size_t nmemb, void *stream) +{ + static size_t total = POSTLEN; + static char buf[1024]; + (void)stream; + + memset(buf, 'A', sizeof(buf)); + + size *= nmemb; + if(size > total) + size = total; + + if(size > sizeof(buf)) + size = sizeof(buf); + + memcpy(ptr, buf, size); + total -= size; + return size; +} + +#define NUM_HEADERS 8 +#define SIZE_HEADERS 5000 + +static char testbuf[SIZE_HEADERS + 100]; + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_FAILED_INIT; + int i; + struct curl_slist *headerlist = NULL, *hl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + for(i = 0; i < NUM_HEADERS; i++) { + int len = msnprintf(testbuf, sizeof(testbuf), "Header%d: ", i); + memset(&testbuf[len], 'A', SIZE_HEADERS); + testbuf[len + SIZE_HEADERS] = 0; /* null-terminate */ + hl = curl_slist_append(headerlist, testbuf); + if(!hl) + goto test_cleanup; + headerlist = hl; + } + + hl = curl_slist_append(headerlist, "Expect: "); + if(!hl) + goto test_cleanup; + headerlist = hl; + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HTTPHEADER, headerlist); + test_setopt(curl, CURLOPT_POST, 1L); + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)POSTLEN); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_READFUNCTION, myreadfunc); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + + curl_slist_free_all(headerlist); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib554.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib554.c new file mode 100644 index 0000000000000000000000000000000000000000..10c19a38045a0df25969af92e8d9551b9ae983dc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib554.c @@ -0,0 +1,223 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]= + "this is what we post to the silly web server\n"; + +struct WriteThis { + char *readptr; + size_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ +#ifdef LIB587 + (void)ptr; + (void)size; + (void)nmemb; + (void)userp; + return CURL_READFUNC_ABORT; +#else + + struct WriteThis *pooh = (struct WriteThis *)userp; + + if(size*nmemb < 1) + return 0; + + if(pooh->sizeleft) { + *ptr = pooh->readptr[0]; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + pooh->sizeleft--; /* less data left */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +#endif +} + +static CURLcode test_once(char *URL, bool oldstyle) +{ + CURL *curl; + CURLcode res = CURLE_OK; + CURLFORMcode formrc; + + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + struct WriteThis pooh; + struct WriteThis pooh2; + + pooh.readptr = testdata; + pooh.sizeleft = strlen(testdata); + + /* Fill in the file upload field */ + if(oldstyle) { + CURL_IGNORE_DEPRECATION( + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "sendfile", + CURLFORM_STREAM, &pooh, + CURLFORM_CONTENTSLENGTH, (long)pooh.sizeleft, + CURLFORM_FILENAME, "postit2.c", + CURLFORM_END); + ) + } + else { + CURL_IGNORE_DEPRECATION( + /* new style */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "sendfile alternative", + CURLFORM_STREAM, &pooh, + CURLFORM_CONTENTLEN, (curl_off_t)pooh.sizeleft, + CURLFORM_FILENAME, "file name 2", + CURLFORM_END); + ) + } + + if(formrc) + printf("curl_formadd(1) = %d\n", (int)formrc); + + /* Now add the same data with another name and make it not look like + a file upload but still using the callback */ + + pooh2.readptr = testdata; + pooh2.sizeleft = strlen(testdata); + + CURL_IGNORE_DEPRECATION( + /* Fill in the file upload field */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "callbackdata", + CURLFORM_STREAM, &pooh2, + CURLFORM_CONTENTSLENGTH, (long)pooh2.sizeleft, + CURLFORM_END); + ) + if(formrc) + printf("curl_formadd(2) = %d\n", (int)formrc); + + CURL_IGNORE_DEPRECATION( + /* Fill in the filename field */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "filename", + CURLFORM_COPYCONTENTS, "postit2.c", + CURLFORM_END); + ) + if(formrc) + printf("curl_formadd(3) = %d\n", (int)formrc); + + CURL_IGNORE_DEPRECATION( + /* Fill in a submit field too */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "submit", + CURLFORM_COPYCONTENTS, "send", + CURLFORM_CONTENTTYPE, "text/plain", + CURLFORM_END); + ) + if(formrc) + printf("curl_formadd(4) = %d\n", (int)formrc); + + CURL_IGNORE_DEPRECATION( + formrc = curl_formadd(&formpost, &lastptr, + CURLFORM_COPYNAME, "somename", + CURLFORM_BUFFER, "somefile.txt", + CURLFORM_BUFFERPTR, "blah blah", + CURLFORM_BUFFERLENGTH, (long)9, + CURLFORM_END); + ) + if(formrc) + printf("curl_formadd(5) = %d\n", (int)formrc); + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + CURL_IGNORE_DEPRECATION( + curl_formfree(formpost); + ) + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Set the expected POST size */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)pooh.sizeleft); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + CURL_IGNORE_DEPRECATION( + /* send a multi-part formpost */ + test_setopt(curl, CURLOPT_HTTPPOST, formpost); + ) + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + CURL_IGNORE_DEPRECATION( + /* always cleanup */ + curl_easy_cleanup(curl); + ) + + CURL_IGNORE_DEPRECATION( + /* now cleanup the formpost chain */ + curl_formfree(formpost); + ) + + return res; +} + +CURLcode test(char *URL) +{ + CURLcode res; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + res = test_once(URL, TRUE); /* old */ + if(!res) + res = test_once(URL, FALSE); /* new */ + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib555.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib555.c new file mode 100644 index 0000000000000000000000000000000000000000..7a16e2e2c8c718581f8077976a6dbaf4237aa787 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib555.c @@ -0,0 +1,156 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 test case is supposed to be identical to 547 except that this uses the + * multi interface and 547 is easy interface. + * + * argv1 = URL + * argv2 = proxy + * argv3 = proxyuser:password + */ + +#include "test.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +static const char uploadthis[] = + "this is the blurb we want to upload\n"; + +static size_t readcallback(char *ptr, + size_t size, + size_t nmemb, + void *clientp) +{ + int *counter = (int *)clientp; + + if(*counter) { + /* only do this once and then require a clearing of this */ + fprintf(stderr, "READ ALREADY DONE!\n"); + return 0; + } + (*counter)++; /* bump */ + + if(size * nmemb >= strlen(uploadthis)) { + fprintf(stderr, "READ!\n"); + strcpy(ptr, uploadthis); + return strlen(uploadthis); + } + fprintf(stderr, "READ NOT FINE!\n"); + return 0; +} +static curlioerr ioctlcallback(CURL *handle, + int cmd, + void *clientp) +{ + int *counter = (int *)clientp; + (void)handle; /* unused */ + if(cmd == CURLIOCMD_RESTARTREAD) { + fprintf(stderr, "REWIND!\n"); + *counter = 0; /* clear counter to make the read callback restart */ + } + return CURLIOE_OK; +} + + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + int counter = 0; + CURLM *m = NULL; + int running = 1; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_HEADER, 1L); + + /* read the POST data from a callback */ + CURL_IGNORE_DEPRECATION( + easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctlcallback); + easy_setopt(curl, CURLOPT_IOCTLDATA, &counter); + ) + easy_setopt(curl, CURLOPT_READFUNCTION, readcallback); + easy_setopt(curl, CURLOPT_READDATA, &counter); + /* We CANNOT do the POST fine without setting the size (or choose + chunked)! */ + easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(uploadthis)); + + easy_setopt(curl, CURLOPT_POST, 1L); + easy_setopt(curl, CURLOPT_PROXY, libtest_arg2); + easy_setopt(curl, CURLOPT_PROXYUSERPWD, libtest_arg3); + easy_setopt(curl, CURLOPT_PROXYAUTH, + (long) (CURLAUTH_NTLM | CURLAUTH_DIGEST | CURLAUTH_BASIC) ); + + multi_init(m); + + multi_add_handle(m, curl); + + while(running) { + struct timeval timeout; + fd_set fdread, fdwrite, fdexcep; + int maxfd = -99; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, curl); + curl_multi_cleanup(m); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib556.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib556.c new file mode 100644 index 0000000000000000000000000000000000000000..06532c6161d9c761fc15d9a806630320b63d9090 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib556.c @@ -0,0 +1,106 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "warnless.h" +#include "memdebug.h" + +/* For Windows, mainly (may be moved in a config file?) */ +#ifndef STDIN_FILENO + #define STDIN_FILENO 0 +#endif +#ifndef STDOUT_FILENO + #define STDOUT_FILENO 1 +#endif +#ifndef STDERR_FILENO + #define STDERR_FILENO 2 +#endif + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_CONNECT_ONLY, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + + if(!res) { + /* we are connected, now get an HTTP document the raw way */ + const char *request = + "GET /556 HTTP/1.1\r\n" + "Host: ninja\r\n\r\n"; + const char *sbuf = request; + size_t sblen = strlen(request); + size_t nwritten = 0, nread = 0; + + do { + char buf[1024]; + + if(sblen) { + res = curl_easy_send(curl, sbuf, sblen, &nwritten); + if(res && res != CURLE_AGAIN) + break; + if(nwritten > 0) { + sbuf += nwritten; + sblen -= nwritten; + } + } + + /* busy-read like crazy */ + res = curl_easy_recv(curl, buf, sizeof(buf), &nread); + + if(nread) { + /* send received stuff to stdout */ + if(!write(STDOUT_FILENO, buf, nread)) + break; + } + + } while((res == CURLE_OK && nread) || (res == CURLE_AGAIN)); + + if(res && res != CURLE_AGAIN) + res = TEST_ERR_FAILURE; + } + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib557.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib557.c new file mode 100644 index 0000000000000000000000000000000000000000..d84626036f24556426ce04bef34461e889bdffe3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib557.c @@ -0,0 +1,1564 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 purpose of this test is to minimally exercise libcurl's internal + * curl_m*printf formatting capabilities and handling of some data types. + */ + +#include "test.h" + +#include + +#ifdef HAVE_LOCALE_H +# include /* for setlocale() */ +#endif + +#include "memdebug.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat" +#pragma GCC diagnostic ignored "-Wformat-extra-args" +#if !defined(__clang__) && __GNUC__ >= 7 +#pragma GCC diagnostic ignored "-Wformat-overflow" +#endif +#endif + +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) +# define MPRNT_SUFFIX_CURL_OFF_T LL +#else +# define MPRNT_SUFFIX_CURL_OFF_T L +#endif + + +#ifdef CURL_ISOCPP +# define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val ## Suffix +#else +# define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val/**/Suffix +#endif +#define MPRNT_OFF_T_C_HELPER1(Val,Suffix) MPRNT_OFF_T_C_HELPER2(Val,Suffix) +#define MPRNT_OFF_T_C(Val) MPRNT_OFF_T_C_HELPER1(Val,MPRNT_SUFFIX_CURL_OFF_T) + + +#define BUFSZ 256 +#define USHORT_TESTS_ARRSZ 1 + 100 +#define SSHORT_TESTS_ARRSZ 1 + 100 +#define UINT_TESTS_ARRSZ 1 + 100 +#define SINT_TESTS_ARRSZ 1 + 100 +#define ULONG_TESTS_ARRSZ 1 + 100 +#define SLONG_TESTS_ARRSZ 1 + 100 +#define COFFT_TESTS_ARRSZ 1 + 100 + + +struct unsshort_st { + unsigned short num; /* unsigned short */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct sigshort_st { + short num; /* signed short */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct unsint_st { + unsigned int num; /* unsigned int */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct sigint_st { + int num; /* signed int */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct unslong_st { + unsigned long num; /* unsigned long */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct siglong_st { + long num; /* signed long */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +struct curloff_st { + curl_off_t num; /* curl_off_t */ + const char *expected; /* expected string */ + char result[BUFSZ]; /* result string */ +}; + + +static struct unsshort_st us_test[USHORT_TESTS_ARRSZ]; +static struct sigshort_st ss_test[SSHORT_TESTS_ARRSZ]; +static struct unsint_st ui_test[UINT_TESTS_ARRSZ]; +static struct sigint_st si_test[SINT_TESTS_ARRSZ]; +static struct unslong_st ul_test[ULONG_TESTS_ARRSZ]; +static struct siglong_st sl_test[SLONG_TESTS_ARRSZ]; +static struct curloff_st co_test[COFFT_TESTS_ARRSZ]; + + +static int test_unsigned_short_formatting(void) +{ + int i, j; + int num_ushort_tests = 0; + int failed = 0; + + i = 1; us_test[i].num = 0xFFFFU; us_test[i].expected = "65535"; + i++; us_test[i].num = 0xFF00U; us_test[i].expected = "65280"; + i++; us_test[i].num = 0x00FFU; us_test[i].expected = "255"; + + i++; us_test[i].num = 0xF000U; us_test[i].expected = "61440"; + i++; us_test[i].num = 0x0F00U; us_test[i].expected = "3840"; + i++; us_test[i].num = 0x00F0U; us_test[i].expected = "240"; + i++; us_test[i].num = 0x000FU; us_test[i].expected = "15"; + + i++; us_test[i].num = 0xC000U; us_test[i].expected = "49152"; + i++; us_test[i].num = 0x0C00U; us_test[i].expected = "3072"; + i++; us_test[i].num = 0x00C0U; us_test[i].expected = "192"; + i++; us_test[i].num = 0x000CU; us_test[i].expected = "12"; + + i++; us_test[i].num = 0x0001U; us_test[i].expected = "1"; + i++; us_test[i].num = 0x0000U; us_test[i].expected = "0"; + + num_ushort_tests = i; + + for(i = 1; i <= num_ushort_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + us_test[i].result[j] = 'X'; + us_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(us_test[i].result, "%hu", us_test[i].num); + + if(memcmp(us_test[i].result, + us_test[i].expected, + strlen(us_test[i].expected))) { + printf("unsigned short test #%.2d: Failed (Expected: %s Got: %s)\n", + i, us_test[i].expected, us_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() unsigned short tests OK!\n"); + else + printf("Some curl_mprintf() unsigned short tests Failed!\n"); + + return failed; +} + + +static int test_signed_short_formatting(void) +{ + int i, j; + int num_sshort_tests = 0; + int failed = 0; + + i = 1; ss_test[i].num = 0x7FFF; ss_test[i].expected = "32767"; + i++; ss_test[i].num = 0x7FFE; ss_test[i].expected = "32766"; + i++; ss_test[i].num = 0x7FFD; ss_test[i].expected = "32765"; + i++; ss_test[i].num = 0x7F00; ss_test[i].expected = "32512"; + i++; ss_test[i].num = 0x07F0; ss_test[i].expected = "2032"; + i++; ss_test[i].num = 0x007F; ss_test[i].expected = "127"; + + i++; ss_test[i].num = 0x7000; ss_test[i].expected = "28672"; + i++; ss_test[i].num = 0x0700; ss_test[i].expected = "1792"; + i++; ss_test[i].num = 0x0070; ss_test[i].expected = "112"; + i++; ss_test[i].num = 0x0007; ss_test[i].expected = "7"; + + i++; ss_test[i].num = 0x5000; ss_test[i].expected = "20480"; + i++; ss_test[i].num = 0x0500; ss_test[i].expected = "1280"; + i++; ss_test[i].num = 0x0050; ss_test[i].expected = "80"; + i++; ss_test[i].num = 0x0005; ss_test[i].expected = "5"; + + i++; ss_test[i].num = 0x0001; ss_test[i].expected = "1"; + i++; ss_test[i].num = 0x0000; ss_test[i].expected = "0"; + + i++; ss_test[i].num = -0x7FFF -1; ss_test[i].expected = "-32768"; + i++; ss_test[i].num = -0x7FFE -1; ss_test[i].expected = "-32767"; + i++; ss_test[i].num = -0x7FFD -1; ss_test[i].expected = "-32766"; + i++; ss_test[i].num = -0x7F00 -1; ss_test[i].expected = "-32513"; + i++; ss_test[i].num = -0x07F0 -1; ss_test[i].expected = "-2033"; + i++; ss_test[i].num = -0x007F -1; ss_test[i].expected = "-128"; + + i++; ss_test[i].num = -0x7000 -1; ss_test[i].expected = "-28673"; + i++; ss_test[i].num = -0x0700 -1; ss_test[i].expected = "-1793"; + i++; ss_test[i].num = -0x0070 -1; ss_test[i].expected = "-113"; + i++; ss_test[i].num = -0x0007 -1; ss_test[i].expected = "-8"; + + i++; ss_test[i].num = -0x5000 -1; ss_test[i].expected = "-20481"; + i++; ss_test[i].num = -0x0500 -1; ss_test[i].expected = "-1281"; + i++; ss_test[i].num = -0x0050 -1; ss_test[i].expected = "-81"; + i++; ss_test[i].num = -0x0005 -1; ss_test[i].expected = "-6"; + + i++; ss_test[i].num = 0x0000 -1; ss_test[i].expected = "-1"; + + num_sshort_tests = i; + + for(i = 1; i <= num_sshort_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + ss_test[i].result[j] = 'X'; + ss_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(ss_test[i].result, "%hd", ss_test[i].num); + + if(memcmp(ss_test[i].result, + ss_test[i].expected, + strlen(ss_test[i].expected))) { + printf("signed short test #%.2d: Failed (Expected: %s Got: %s)\n", + i, ss_test[i].expected, ss_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() signed short tests OK!\n"); + else + printf("Some curl_mprintf() signed short tests Failed!\n"); + + return failed; +} + + +static int test_unsigned_int_formatting(void) +{ + int i, j; + int num_uint_tests = 0; + int failed = 0; + +#if (SIZEOF_INT == 2) + + i = 1; ui_test[i].num = 0xFFFFU; ui_test[i].expected = "65535"; + i++; ui_test[i].num = 0xFF00U; ui_test[i].expected = "65280"; + i++; ui_test[i].num = 0x00FFU; ui_test[i].expected = "255"; + + i++; ui_test[i].num = 0xF000U; ui_test[i].expected = "61440"; + i++; ui_test[i].num = 0x0F00U; ui_test[i].expected = "3840"; + i++; ui_test[i].num = 0x00F0U; ui_test[i].expected = "240"; + i++; ui_test[i].num = 0x000FU; ui_test[i].expected = "15"; + + i++; ui_test[i].num = 0xC000U; ui_test[i].expected = "49152"; + i++; ui_test[i].num = 0x0C00U; ui_test[i].expected = "3072"; + i++; ui_test[i].num = 0x00C0U; ui_test[i].expected = "192"; + i++; ui_test[i].num = 0x000CU; ui_test[i].expected = "12"; + + i++; ui_test[i].num = 0x0001U; ui_test[i].expected = "1"; + i++; ui_test[i].num = 0x0000U; ui_test[i].expected = "0"; + + num_uint_tests = i; + +#elif (SIZEOF_INT == 4) + + i = 1; ui_test[i].num = 0xFFFFFFFFU; ui_test[i].expected = "4294967295"; + i++; ui_test[i].num = 0xFFFF0000U; ui_test[i].expected = "4294901760"; + i++; ui_test[i].num = 0x0000FFFFU; ui_test[i].expected = "65535"; + + i++; ui_test[i].num = 0xFF000000U; ui_test[i].expected = "4278190080"; + i++; ui_test[i].num = 0x00FF0000U; ui_test[i].expected = "16711680"; + i++; ui_test[i].num = 0x0000FF00U; ui_test[i].expected = "65280"; + i++; ui_test[i].num = 0x000000FFU; ui_test[i].expected = "255"; + + i++; ui_test[i].num = 0xF0000000U; ui_test[i].expected = "4026531840"; + i++; ui_test[i].num = 0x0F000000U; ui_test[i].expected = "251658240"; + i++; ui_test[i].num = 0x00F00000U; ui_test[i].expected = "15728640"; + i++; ui_test[i].num = 0x000F0000U; ui_test[i].expected = "983040"; + i++; ui_test[i].num = 0x0000F000U; ui_test[i].expected = "61440"; + i++; ui_test[i].num = 0x00000F00U; ui_test[i].expected = "3840"; + i++; ui_test[i].num = 0x000000F0U; ui_test[i].expected = "240"; + i++; ui_test[i].num = 0x0000000FU; ui_test[i].expected = "15"; + + i++; ui_test[i].num = 0xC0000000U; ui_test[i].expected = "3221225472"; + i++; ui_test[i].num = 0x0C000000U; ui_test[i].expected = "201326592"; + i++; ui_test[i].num = 0x00C00000U; ui_test[i].expected = "12582912"; + i++; ui_test[i].num = 0x000C0000U; ui_test[i].expected = "786432"; + i++; ui_test[i].num = 0x0000C000U; ui_test[i].expected = "49152"; + i++; ui_test[i].num = 0x00000C00U; ui_test[i].expected = "3072"; + i++; ui_test[i].num = 0x000000C0U; ui_test[i].expected = "192"; + i++; ui_test[i].num = 0x0000000CU; ui_test[i].expected = "12"; + + i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; + i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; + + num_uint_tests = i; + +#elif (SIZEOF_INT == 8) + + /* !checksrc! disable LONGLINE all */ + i = 1; ui_test[i].num = 0xFFFFFFFFFFFFFFFFU; ui_test[i].expected = "18446744073709551615"; + i++; ui_test[i].num = 0xFFFFFFFF00000000U; ui_test[i].expected = "18446744069414584320"; + i++; ui_test[i].num = 0x00000000FFFFFFFFU; ui_test[i].expected = "4294967295"; + + i++; ui_test[i].num = 0xFFFF000000000000U; ui_test[i].expected = "18446462598732840960"; + i++; ui_test[i].num = 0x0000FFFF00000000U; ui_test[i].expected = "281470681743360"; + i++; ui_test[i].num = 0x00000000FFFF0000U; ui_test[i].expected = "4294901760"; + i++; ui_test[i].num = 0x000000000000FFFFU; ui_test[i].expected = "65535"; + + i++; ui_test[i].num = 0xFF00000000000000U; ui_test[i].expected = "18374686479671623680"; + i++; ui_test[i].num = 0x00FF000000000000U; ui_test[i].expected = "71776119061217280"; + i++; ui_test[i].num = 0x0000FF0000000000U; ui_test[i].expected = "280375465082880"; + i++; ui_test[i].num = 0x000000FF00000000U; ui_test[i].expected = "1095216660480"; + i++; ui_test[i].num = 0x00000000FF000000U; ui_test[i].expected = "4278190080"; + i++; ui_test[i].num = 0x0000000000FF0000U; ui_test[i].expected = "16711680"; + i++; ui_test[i].num = 0x000000000000FF00U; ui_test[i].expected = "65280"; + i++; ui_test[i].num = 0x00000000000000FFU; ui_test[i].expected = "255"; + + i++; ui_test[i].num = 0xF000000000000000U; ui_test[i].expected = "17293822569102704640"; + i++; ui_test[i].num = 0x0F00000000000000U; ui_test[i].expected = "1080863910568919040"; + i++; ui_test[i].num = 0x00F0000000000000U; ui_test[i].expected = "67553994410557440"; + i++; ui_test[i].num = 0x000F000000000000U; ui_test[i].expected = "4222124650659840"; + i++; ui_test[i].num = 0x0000F00000000000U; ui_test[i].expected = "263882790666240"; + i++; ui_test[i].num = 0x00000F0000000000U; ui_test[i].expected = "16492674416640"; + i++; ui_test[i].num = 0x000000F000000000U; ui_test[i].expected = "1030792151040"; + i++; ui_test[i].num = 0x0000000F00000000U; ui_test[i].expected = "64424509440"; + i++; ui_test[i].num = 0x00000000F0000000U; ui_test[i].expected = "4026531840"; + i++; ui_test[i].num = 0x000000000F000000U; ui_test[i].expected = "251658240"; + i++; ui_test[i].num = 0x0000000000F00000U; ui_test[i].expected = "15728640"; + i++; ui_test[i].num = 0x00000000000F0000U; ui_test[i].expected = "983040"; + i++; ui_test[i].num = 0x000000000000F000U; ui_test[i].expected = "61440"; + i++; ui_test[i].num = 0x0000000000000F00U; ui_test[i].expected = "3840"; + i++; ui_test[i].num = 0x00000000000000F0U; ui_test[i].expected = "240"; + i++; ui_test[i].num = 0x000000000000000FU; ui_test[i].expected = "15"; + + i++; ui_test[i].num = 0xC000000000000000U; ui_test[i].expected = "13835058055282163712"; + i++; ui_test[i].num = 0x0C00000000000000U; ui_test[i].expected = "864691128455135232"; + i++; ui_test[i].num = 0x00C0000000000000U; ui_test[i].expected = "54043195528445952"; + i++; ui_test[i].num = 0x000C000000000000U; ui_test[i].expected = "3377699720527872"; + i++; ui_test[i].num = 0x0000C00000000000U; ui_test[i].expected = "211106232532992"; + i++; ui_test[i].num = 0x00000C0000000000U; ui_test[i].expected = "13194139533312"; + i++; ui_test[i].num = 0x000000C000000000U; ui_test[i].expected = "824633720832"; + i++; ui_test[i].num = 0x0000000C00000000U; ui_test[i].expected = "51539607552"; + i++; ui_test[i].num = 0x00000000C0000000U; ui_test[i].expected = "3221225472"; + i++; ui_test[i].num = 0x000000000C000000U; ui_test[i].expected = "201326592"; + i++; ui_test[i].num = 0x0000000000C00000U; ui_test[i].expected = "12582912"; + i++; ui_test[i].num = 0x00000000000C0000U; ui_test[i].expected = "786432"; + i++; ui_test[i].num = 0x000000000000C000U; ui_test[i].expected = "49152"; + i++; ui_test[i].num = 0x0000000000000C00U; ui_test[i].expected = "3072"; + i++; ui_test[i].num = 0x00000000000000C0U; ui_test[i].expected = "192"; + i++; ui_test[i].num = 0x000000000000000CU; ui_test[i].expected = "12"; + + i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; + i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; + + num_uint_tests = i; + +#endif + + for(i = 1; i <= num_uint_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + ui_test[i].result[j] = 'X'; + ui_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(ui_test[i].result, "%u", ui_test[i].num); + + if(memcmp(ui_test[i].result, + ui_test[i].expected, + strlen(ui_test[i].expected))) { + printf("unsigned int test #%.2d: Failed (Expected: %s Got: %s)\n", + i, ui_test[i].expected, ui_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() unsigned int tests OK!\n"); + else + printf("Some curl_mprintf() unsigned int tests Failed!\n"); + + return failed; +} + + +static int test_signed_int_formatting(void) +{ + int i, j; + int num_sint_tests = 0; + int failed = 0; + +#if (SIZEOF_INT == 2) + + i = 1; si_test[i].num = 0x7FFF; si_test[i].expected = "32767"; + i++; si_test[i].num = 0x7FFE; si_test[i].expected = "32766"; + i++; si_test[i].num = 0x7FFD; si_test[i].expected = "32765"; + i++; si_test[i].num = 0x7F00; si_test[i].expected = "32512"; + i++; si_test[i].num = 0x07F0; si_test[i].expected = "2032"; + i++; si_test[i].num = 0x007F; si_test[i].expected = "127"; + + i++; si_test[i].num = 0x7000; si_test[i].expected = "28672"; + i++; si_test[i].num = 0x0700; si_test[i].expected = "1792"; + i++; si_test[i].num = 0x0070; si_test[i].expected = "112"; + i++; si_test[i].num = 0x0007; si_test[i].expected = "7"; + + i++; si_test[i].num = 0x5000; si_test[i].expected = "20480"; + i++; si_test[i].num = 0x0500; si_test[i].expected = "1280"; + i++; si_test[i].num = 0x0050; si_test[i].expected = "80"; + i++; si_test[i].num = 0x0005; si_test[i].expected = "5"; + + i++; si_test[i].num = 0x0001; si_test[i].expected = "1"; + i++; si_test[i].num = 0x0000; si_test[i].expected = "0"; + + i++; si_test[i].num = -0x7FFF -1; si_test[i].expected = "-32768"; + i++; si_test[i].num = -0x7FFE -1; si_test[i].expected = "-32767"; + i++; si_test[i].num = -0x7FFD -1; si_test[i].expected = "-32766"; + i++; si_test[i].num = -0x7F00 -1; si_test[i].expected = "-32513"; + i++; si_test[i].num = -0x07F0 -1; si_test[i].expected = "-2033"; + i++; si_test[i].num = -0x007F -1; si_test[i].expected = "-128"; + + i++; si_test[i].num = -0x7000 -1; si_test[i].expected = "-28673"; + i++; si_test[i].num = -0x0700 -1; si_test[i].expected = "-1793"; + i++; si_test[i].num = -0x0070 -1; si_test[i].expected = "-113"; + i++; si_test[i].num = -0x0007 -1; si_test[i].expected = "-8"; + + i++; si_test[i].num = -0x5000 -1; si_test[i].expected = "-20481"; + i++; si_test[i].num = -0x0500 -1; si_test[i].expected = "-1281"; + i++; si_test[i].num = -0x0050 -1; si_test[i].expected = "-81"; + i++; si_test[i].num = -0x0005 -1; si_test[i].expected = "-6"; + + i++; si_test[i].num = 0x0000 -1; si_test[i].expected = "-1"; + + num_sint_tests = i; + +#elif (SIZEOF_INT == 4) + + i = 1; si_test[i].num = 0x7FFFFFFF; si_test[i].expected = "2147483647"; + i++; si_test[i].num = 0x7FFFFFFE; si_test[i].expected = "2147483646"; + i++; si_test[i].num = 0x7FFFFFFD; si_test[i].expected = "2147483645"; + i++; si_test[i].num = 0x7FFF0000; si_test[i].expected = "2147418112"; + i++; si_test[i].num = 0x00007FFF; si_test[i].expected = "32767"; + + i++; si_test[i].num = 0x7F000000; si_test[i].expected = "2130706432"; + i++; si_test[i].num = 0x007F0000; si_test[i].expected = "8323072"; + i++; si_test[i].num = 0x00007F00; si_test[i].expected = "32512"; + i++; si_test[i].num = 0x0000007F; si_test[i].expected = "127"; + + i++; si_test[i].num = 0x70000000; si_test[i].expected = "1879048192"; + i++; si_test[i].num = 0x07000000; si_test[i].expected = "117440512"; + i++; si_test[i].num = 0x00700000; si_test[i].expected = "7340032"; + i++; si_test[i].num = 0x00070000; si_test[i].expected = "458752"; + i++; si_test[i].num = 0x00007000; si_test[i].expected = "28672"; + i++; si_test[i].num = 0x00000700; si_test[i].expected = "1792"; + i++; si_test[i].num = 0x00000070; si_test[i].expected = "112"; + i++; si_test[i].num = 0x00000007; si_test[i].expected = "7"; + + i++; si_test[i].num = 0x50000000; si_test[i].expected = "1342177280"; + i++; si_test[i].num = 0x05000000; si_test[i].expected = "83886080"; + i++; si_test[i].num = 0x00500000; si_test[i].expected = "5242880"; + i++; si_test[i].num = 0x00050000; si_test[i].expected = "327680"; + i++; si_test[i].num = 0x00005000; si_test[i].expected = "20480"; + i++; si_test[i].num = 0x00000500; si_test[i].expected = "1280"; + i++; si_test[i].num = 0x00000050; si_test[i].expected = "80"; + i++; si_test[i].num = 0x00000005; si_test[i].expected = "5"; + + i++; si_test[i].num = 0x00000001; si_test[i].expected = "1"; + i++; si_test[i].num = 0x00000000; si_test[i].expected = "0"; + + i++; si_test[i].num = -0x7FFFFFFF -1; si_test[i].expected = "-2147483648"; + i++; si_test[i].num = -0x7FFFFFFE -1; si_test[i].expected = "-2147483647"; + i++; si_test[i].num = -0x7FFFFFFD -1; si_test[i].expected = "-2147483646"; + i++; si_test[i].num = -0x7FFF0000 -1; si_test[i].expected = "-2147418113"; + i++; si_test[i].num = -0x00007FFF -1; si_test[i].expected = "-32768"; + + i++; si_test[i].num = -0x7F000000 -1; si_test[i].expected = "-2130706433"; + i++; si_test[i].num = -0x007F0000 -1; si_test[i].expected = "-8323073"; + i++; si_test[i].num = -0x00007F00 -1; si_test[i].expected = "-32513"; + i++; si_test[i].num = -0x0000007F -1; si_test[i].expected = "-128"; + + i++; si_test[i].num = -0x70000000 -1; si_test[i].expected = "-1879048193"; + i++; si_test[i].num = -0x07000000 -1; si_test[i].expected = "-117440513"; + i++; si_test[i].num = -0x00700000 -1; si_test[i].expected = "-7340033"; + i++; si_test[i].num = -0x00070000 -1; si_test[i].expected = "-458753"; + i++; si_test[i].num = -0x00007000 -1; si_test[i].expected = "-28673"; + i++; si_test[i].num = -0x00000700 -1; si_test[i].expected = "-1793"; + i++; si_test[i].num = -0x00000070 -1; si_test[i].expected = "-113"; + i++; si_test[i].num = -0x00000007 -1; si_test[i].expected = "-8"; + + i++; si_test[i].num = -0x50000000 -1; si_test[i].expected = "-1342177281"; + i++; si_test[i].num = -0x05000000 -1; si_test[i].expected = "-83886081"; + i++; si_test[i].num = -0x00500000 -1; si_test[i].expected = "-5242881"; + i++; si_test[i].num = -0x00050000 -1; si_test[i].expected = "-327681"; + i++; si_test[i].num = -0x00005000 -1; si_test[i].expected = "-20481"; + i++; si_test[i].num = -0x00000500 -1; si_test[i].expected = "-1281"; + i++; si_test[i].num = -0x00000050 -1; si_test[i].expected = "-81"; + i++; si_test[i].num = -0x00000005 -1; si_test[i].expected = "-6"; + + i++; si_test[i].num = 0x00000000 -1; si_test[i].expected = "-1"; + + num_sint_tests = i; + +#elif (SIZEOF_INT == 8) + + i = 1; si_test[i].num = 0x7FFFFFFFFFFFFFFF; si_test[i].expected = "9223372036854775807"; + i++; si_test[i].num = 0x7FFFFFFFFFFFFFFE; si_test[i].expected = "9223372036854775806"; + i++; si_test[i].num = 0x7FFFFFFFFFFFFFFD; si_test[i].expected = "9223372036854775805"; + i++; si_test[i].num = 0x7FFFFFFF00000000; si_test[i].expected = "9223372032559808512"; + i++; si_test[i].num = 0x000000007FFFFFFF; si_test[i].expected = "2147483647"; + + i++; si_test[i].num = 0x7FFF000000000000; si_test[i].expected = "9223090561878065152"; + i++; si_test[i].num = 0x00007FFF00000000; si_test[i].expected = "140733193388032"; + i++; si_test[i].num = 0x000000007FFF0000; si_test[i].expected = "2147418112"; + i++; si_test[i].num = 0x0000000000007FFF; si_test[i].expected = "32767"; + + i++; si_test[i].num = 0x7F00000000000000; si_test[i].expected = "9151314442816847872"; + i++; si_test[i].num = 0x007F000000000000; si_test[i].expected = "35747322042253312"; + i++; si_test[i].num = 0x00007F0000000000; si_test[i].expected = "139637976727552"; + i++; si_test[i].num = 0x0000007F00000000; si_test[i].expected = "545460846592"; + i++; si_test[i].num = 0x000000007F000000; si_test[i].expected = "2130706432"; + i++; si_test[i].num = 0x00000000007F0000; si_test[i].expected = "8323072"; + i++; si_test[i].num = 0x0000000000007F00; si_test[i].expected = "32512"; + i++; si_test[i].num = 0x000000000000007F; si_test[i].expected = "127"; + + i++; si_test[i].num = 0x7000000000000000; si_test[i].expected = "8070450532247928832"; + i++; si_test[i].num = 0x0700000000000000; si_test[i].expected = "504403158265495552"; + i++; si_test[i].num = 0x0070000000000000; si_test[i].expected = "31525197391593472"; + i++; si_test[i].num = 0x0007000000000000; si_test[i].expected = "1970324836974592"; + i++; si_test[i].num = 0x0000700000000000; si_test[i].expected = "123145302310912"; + i++; si_test[i].num = 0x0000070000000000; si_test[i].expected = "7696581394432"; + i++; si_test[i].num = 0x0000007000000000; si_test[i].expected = "481036337152"; + i++; si_test[i].num = 0x0000000700000000; si_test[i].expected = "30064771072"; + i++; si_test[i].num = 0x0000000070000000; si_test[i].expected = "1879048192"; + i++; si_test[i].num = 0x0000000007000000; si_test[i].expected = "117440512"; + i++; si_test[i].num = 0x0000000000700000; si_test[i].expected = "7340032"; + i++; si_test[i].num = 0x0000000000070000; si_test[i].expected = "458752"; + i++; si_test[i].num = 0x0000000000007000; si_test[i].expected = "28672"; + i++; si_test[i].num = 0x0000000000000700; si_test[i].expected = "1792"; + i++; si_test[i].num = 0x0000000000000070; si_test[i].expected = "112"; + i++; si_test[i].num = 0x0000000000000007; si_test[i].expected = "7"; + + i++; si_test[i].num = 0x0000000000000001; si_test[i].expected = "1"; + i++; si_test[i].num = 0x0000000000000000; si_test[i].expected = "0"; + + i++; si_test[i].num = -0x7FFFFFFFFFFFFFFF -1; si_test[i].expected = "-9223372036854775808"; + i++; si_test[i].num = -0x7FFFFFFFFFFFFFFE -1; si_test[i].expected = "-9223372036854775807"; + i++; si_test[i].num = -0x7FFFFFFFFFFFFFFD -1; si_test[i].expected = "-9223372036854775806"; + i++; si_test[i].num = -0x7FFFFFFF00000000 -1; si_test[i].expected = "-9223372032559808513"; + i++; si_test[i].num = -0x000000007FFFFFFF -1; si_test[i].expected = "-2147483648"; + + i++; si_test[i].num = -0x7FFF000000000000 -1; si_test[i].expected = "-9223090561878065153"; + i++; si_test[i].num = -0x00007FFF00000000 -1; si_test[i].expected = "-140733193388033"; + i++; si_test[i].num = -0x000000007FFF0000 -1; si_test[i].expected = "-2147418113"; + i++; si_test[i].num = -0x0000000000007FFF -1; si_test[i].expected = "-32768"; + + i++; si_test[i].num = -0x7F00000000000000 -1; si_test[i].expected = "-9151314442816847873"; + i++; si_test[i].num = -0x007F000000000000 -1; si_test[i].expected = "-35747322042253313"; + i++; si_test[i].num = -0x00007F0000000000 -1; si_test[i].expected = "-139637976727553"; + i++; si_test[i].num = -0x0000007F00000000 -1; si_test[i].expected = "-545460846593"; + i++; si_test[i].num = -0x000000007F000000 -1; si_test[i].expected = "-2130706433"; + i++; si_test[i].num = -0x00000000007F0000 -1; si_test[i].expected = "-8323073"; + i++; si_test[i].num = -0x0000000000007F00 -1; si_test[i].expected = "-32513"; + i++; si_test[i].num = -0x000000000000007F -1; si_test[i].expected = "-128"; + + i++; si_test[i].num = -0x7000000000000000 -1; si_test[i].expected = "-8070450532247928833"; + i++; si_test[i].num = -0x0700000000000000 -1; si_test[i].expected = "-504403158265495553"; + i++; si_test[i].num = -0x0070000000000000 -1; si_test[i].expected = "-31525197391593473"; + i++; si_test[i].num = -0x0007000000000000 -1; si_test[i].expected = "-1970324836974593"; + i++; si_test[i].num = -0x0000700000000000 -1; si_test[i].expected = "-123145302310913"; + i++; si_test[i].num = -0x0000070000000000 -1; si_test[i].expected = "-7696581394433"; + i++; si_test[i].num = -0x0000007000000000 -1; si_test[i].expected = "-481036337153"; + i++; si_test[i].num = -0x0000000700000000 -1; si_test[i].expected = "-30064771073"; + i++; si_test[i].num = -0x0000000070000000 -1; si_test[i].expected = "-1879048193"; + i++; si_test[i].num = -0x0000000007000000 -1; si_test[i].expected = "-117440513"; + i++; si_test[i].num = -0x0000000000700000 -1; si_test[i].expected = "-7340033"; + i++; si_test[i].num = -0x0000000000070000 -1; si_test[i].expected = "-458753"; + i++; si_test[i].num = -0x0000000000007000 -1; si_test[i].expected = "-28673"; + i++; si_test[i].num = -0x0000000000000700 -1; si_test[i].expected = "-1793"; + i++; si_test[i].num = -0x0000000000000070 -1; si_test[i].expected = "-113"; + i++; si_test[i].num = -0x0000000000000007 -1; si_test[i].expected = "-8"; + + i++; si_test[i].num = 0x0000000000000000 -1; si_test[i].expected = "-1"; + + num_sint_tests = i; + +#endif + + for(i = 1; i <= num_sint_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + si_test[i].result[j] = 'X'; + si_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(si_test[i].result, "%d", si_test[i].num); + + if(memcmp(si_test[i].result, + si_test[i].expected, + strlen(si_test[i].expected))) { + printf("signed int test #%.2d: Failed (Expected: %s Got: %s)\n", + i, si_test[i].expected, si_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() signed int tests OK!\n"); + else + printf("Some curl_mprintf() signed int tests Failed!\n"); + + return failed; +} + + +static int test_unsigned_long_formatting(void) +{ + int i, j; + int num_ulong_tests = 0; + int failed = 0; + +#if (SIZEOF_LONG == 2) + + i = 1; ul_test[i].num = 0xFFFFUL; ul_test[i].expected = "65535"; + i++; ul_test[i].num = 0xFF00UL; ul_test[i].expected = "65280"; + i++; ul_test[i].num = 0x00FFUL; ul_test[i].expected = "255"; + + i++; ul_test[i].num = 0xF000UL; ul_test[i].expected = "61440"; + i++; ul_test[i].num = 0x0F00UL; ul_test[i].expected = "3840"; + i++; ul_test[i].num = 0x00F0UL; ul_test[i].expected = "240"; + i++; ul_test[i].num = 0x000FUL; ul_test[i].expected = "15"; + + i++; ul_test[i].num = 0xC000UL; ul_test[i].expected = "49152"; + i++; ul_test[i].num = 0x0C00UL; ul_test[i].expected = "3072"; + i++; ul_test[i].num = 0x00C0UL; ul_test[i].expected = "192"; + i++; ul_test[i].num = 0x000CUL; ul_test[i].expected = "12"; + + i++; ul_test[i].num = 0x0001UL; ul_test[i].expected = "1"; + i++; ul_test[i].num = 0x0000UL; ul_test[i].expected = "0"; + + num_ulong_tests = i; + +#elif (SIZEOF_LONG == 4) + + i = 1; ul_test[i].num = 0xFFFFFFFFUL; ul_test[i].expected = "4294967295"; + i++; ul_test[i].num = 0xFFFF0000UL; ul_test[i].expected = "4294901760"; + i++; ul_test[i].num = 0x0000FFFFUL; ul_test[i].expected = "65535"; + + i++; ul_test[i].num = 0xFF000000UL; ul_test[i].expected = "4278190080"; + i++; ul_test[i].num = 0x00FF0000UL; ul_test[i].expected = "16711680"; + i++; ul_test[i].num = 0x0000FF00UL; ul_test[i].expected = "65280"; + i++; ul_test[i].num = 0x000000FFUL; ul_test[i].expected = "255"; + + i++; ul_test[i].num = 0xF0000000UL; ul_test[i].expected = "4026531840"; + i++; ul_test[i].num = 0x0F000000UL; ul_test[i].expected = "251658240"; + i++; ul_test[i].num = 0x00F00000UL; ul_test[i].expected = "15728640"; + i++; ul_test[i].num = 0x000F0000UL; ul_test[i].expected = "983040"; + i++; ul_test[i].num = 0x0000F000UL; ul_test[i].expected = "61440"; + i++; ul_test[i].num = 0x00000F00UL; ul_test[i].expected = "3840"; + i++; ul_test[i].num = 0x000000F0UL; ul_test[i].expected = "240"; + i++; ul_test[i].num = 0x0000000FUL; ul_test[i].expected = "15"; + + i++; ul_test[i].num = 0xC0000000UL; ul_test[i].expected = "3221225472"; + i++; ul_test[i].num = 0x0C000000UL; ul_test[i].expected = "201326592"; + i++; ul_test[i].num = 0x00C00000UL; ul_test[i].expected = "12582912"; + i++; ul_test[i].num = 0x000C0000UL; ul_test[i].expected = "786432"; + i++; ul_test[i].num = 0x0000C000UL; ul_test[i].expected = "49152"; + i++; ul_test[i].num = 0x00000C00UL; ul_test[i].expected = "3072"; + i++; ul_test[i].num = 0x000000C0UL; ul_test[i].expected = "192"; + i++; ul_test[i].num = 0x0000000CUL; ul_test[i].expected = "12"; + + i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; + i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; + + num_ulong_tests = i; + +#elif (SIZEOF_LONG == 8) + + i = 1; ul_test[i].num = 0xFFFFFFFFFFFFFFFFUL; ul_test[i].expected = "18446744073709551615"; + i++; ul_test[i].num = 0xFFFFFFFF00000000UL; ul_test[i].expected = "18446744069414584320"; + i++; ul_test[i].num = 0x00000000FFFFFFFFUL; ul_test[i].expected = "4294967295"; + + i++; ul_test[i].num = 0xFFFF000000000000UL; ul_test[i].expected = "18446462598732840960"; + i++; ul_test[i].num = 0x0000FFFF00000000UL; ul_test[i].expected = "281470681743360"; + i++; ul_test[i].num = 0x00000000FFFF0000UL; ul_test[i].expected = "4294901760"; + i++; ul_test[i].num = 0x000000000000FFFFUL; ul_test[i].expected = "65535"; + + i++; ul_test[i].num = 0xFF00000000000000UL; ul_test[i].expected = "18374686479671623680"; + i++; ul_test[i].num = 0x00FF000000000000UL; ul_test[i].expected = "71776119061217280"; + i++; ul_test[i].num = 0x0000FF0000000000UL; ul_test[i].expected = "280375465082880"; + i++; ul_test[i].num = 0x000000FF00000000UL; ul_test[i].expected = "1095216660480"; + i++; ul_test[i].num = 0x00000000FF000000UL; ul_test[i].expected = "4278190080"; + i++; ul_test[i].num = 0x0000000000FF0000UL; ul_test[i].expected = "16711680"; + i++; ul_test[i].num = 0x000000000000FF00UL; ul_test[i].expected = "65280"; + i++; ul_test[i].num = 0x00000000000000FFUL; ul_test[i].expected = "255"; + + i++; ul_test[i].num = 0xF000000000000000UL; ul_test[i].expected = "17293822569102704640"; + i++; ul_test[i].num = 0x0F00000000000000UL; ul_test[i].expected = "1080863910568919040"; + i++; ul_test[i].num = 0x00F0000000000000UL; ul_test[i].expected = "67553994410557440"; + i++; ul_test[i].num = 0x000F000000000000UL; ul_test[i].expected = "4222124650659840"; + i++; ul_test[i].num = 0x0000F00000000000UL; ul_test[i].expected = "263882790666240"; + i++; ul_test[i].num = 0x00000F0000000000UL; ul_test[i].expected = "16492674416640"; + i++; ul_test[i].num = 0x000000F000000000UL; ul_test[i].expected = "1030792151040"; + i++; ul_test[i].num = 0x0000000F00000000UL; ul_test[i].expected = "64424509440"; + i++; ul_test[i].num = 0x00000000F0000000UL; ul_test[i].expected = "4026531840"; + i++; ul_test[i].num = 0x000000000F000000UL; ul_test[i].expected = "251658240"; + i++; ul_test[i].num = 0x0000000000F00000UL; ul_test[i].expected = "15728640"; + i++; ul_test[i].num = 0x00000000000F0000UL; ul_test[i].expected = "983040"; + i++; ul_test[i].num = 0x000000000000F000UL; ul_test[i].expected = "61440"; + i++; ul_test[i].num = 0x0000000000000F00UL; ul_test[i].expected = "3840"; + i++; ul_test[i].num = 0x00000000000000F0UL; ul_test[i].expected = "240"; + i++; ul_test[i].num = 0x000000000000000FUL; ul_test[i].expected = "15"; + + i++; ul_test[i].num = 0xC000000000000000UL; ul_test[i].expected = "13835058055282163712"; + i++; ul_test[i].num = 0x0C00000000000000UL; ul_test[i].expected = "864691128455135232"; + i++; ul_test[i].num = 0x00C0000000000000UL; ul_test[i].expected = "54043195528445952"; + i++; ul_test[i].num = 0x000C000000000000UL; ul_test[i].expected = "3377699720527872"; + i++; ul_test[i].num = 0x0000C00000000000UL; ul_test[i].expected = "211106232532992"; + i++; ul_test[i].num = 0x00000C0000000000UL; ul_test[i].expected = "13194139533312"; + i++; ul_test[i].num = 0x000000C000000000UL; ul_test[i].expected = "824633720832"; + i++; ul_test[i].num = 0x0000000C00000000UL; ul_test[i].expected = "51539607552"; + i++; ul_test[i].num = 0x00000000C0000000UL; ul_test[i].expected = "3221225472"; + i++; ul_test[i].num = 0x000000000C000000UL; ul_test[i].expected = "201326592"; + i++; ul_test[i].num = 0x0000000000C00000UL; ul_test[i].expected = "12582912"; + i++; ul_test[i].num = 0x00000000000C0000UL; ul_test[i].expected = "786432"; + i++; ul_test[i].num = 0x000000000000C000UL; ul_test[i].expected = "49152"; + i++; ul_test[i].num = 0x0000000000000C00UL; ul_test[i].expected = "3072"; + i++; ul_test[i].num = 0x00000000000000C0UL; ul_test[i].expected = "192"; + i++; ul_test[i].num = 0x000000000000000CUL; ul_test[i].expected = "12"; + + i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; + i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; + + num_ulong_tests = i; + +#endif + + for(i = 1; i <= num_ulong_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + ul_test[i].result[j] = 'X'; + ul_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(ul_test[i].result, "%lu", ul_test[i].num); + + if(memcmp(ul_test[i].result, + ul_test[i].expected, + strlen(ul_test[i].expected))) { + printf("unsigned long test #%.2d: Failed (Expected: %s Got: %s)\n", + i, ul_test[i].expected, ul_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() unsigned long tests OK!\n"); + else + printf("Some curl_mprintf() unsigned long tests Failed!\n"); + + return failed; +} + + +static int test_signed_long_formatting(void) +{ + int i, j; + int num_slong_tests = 0; + int failed = 0; + +#if (SIZEOF_LONG == 2) + + i = 1; sl_test[i].num = 0x7FFFL; sl_test[i].expected = "32767"; + i++; sl_test[i].num = 0x7FFEL; sl_test[i].expected = "32766"; + i++; sl_test[i].num = 0x7FFDL; sl_test[i].expected = "32765"; + i++; sl_test[i].num = 0x7F00L; sl_test[i].expected = "32512"; + i++; sl_test[i].num = 0x07F0L; sl_test[i].expected = "2032"; + i++; sl_test[i].num = 0x007FL; sl_test[i].expected = "127"; + + i++; sl_test[i].num = 0x7000L; sl_test[i].expected = "28672"; + i++; sl_test[i].num = 0x0700L; sl_test[i].expected = "1792"; + i++; sl_test[i].num = 0x0070L; sl_test[i].expected = "112"; + i++; sl_test[i].num = 0x0007L; sl_test[i].expected = "7"; + + i++; sl_test[i].num = 0x5000L; sl_test[i].expected = "20480"; + i++; sl_test[i].num = 0x0500L; sl_test[i].expected = "1280"; + i++; sl_test[i].num = 0x0050L; sl_test[i].expected = "80"; + i++; sl_test[i].num = 0x0005L; sl_test[i].expected = "5"; + + i++; sl_test[i].num = 0x0001L; sl_test[i].expected = "1"; + i++; sl_test[i].num = 0x0000L; sl_test[i].expected = "0"; + + i++; sl_test[i].num = -0x7FFFL -1L; sl_test[i].expected = "-32768"; + i++; sl_test[i].num = -0x7FFEL -1L; sl_test[i].expected = "-32767"; + i++; sl_test[i].num = -0x7FFDL -1L; sl_test[i].expected = "-32766"; + i++; sl_test[i].num = -0x7F00L -1L; sl_test[i].expected = "-32513"; + i++; sl_test[i].num = -0x07F0L -1L; sl_test[i].expected = "-2033"; + i++; sl_test[i].num = -0x007FL -1L; sl_test[i].expected = "-128"; + + i++; sl_test[i].num = -0x7000L -1L; sl_test[i].expected = "-28673"; + i++; sl_test[i].num = -0x0700L -1L; sl_test[i].expected = "-1793"; + i++; sl_test[i].num = -0x0070L -1L; sl_test[i].expected = "-113"; + i++; sl_test[i].num = -0x0007L -1L; sl_test[i].expected = "-8"; + + i++; sl_test[i].num = -0x5000L -1L; sl_test[i].expected = "-20481"; + i++; sl_test[i].num = -0x0500L -1L; sl_test[i].expected = "-1281"; + i++; sl_test[i].num = -0x0050L -1L; sl_test[i].expected = "-81"; + i++; sl_test[i].num = -0x0005L -1L; sl_test[i].expected = "-6"; + + i++; sl_test[i].num = 0x0000L -1L; sl_test[i].expected = "-1"; + + num_slong_tests = i; + +#elif (SIZEOF_LONG == 4) + + i = 1; sl_test[i].num = 0x7FFFFFFFL; sl_test[i].expected = "2147483647"; + i++; sl_test[i].num = 0x7FFFFFFEL; sl_test[i].expected = "2147483646"; + i++; sl_test[i].num = 0x7FFFFFFDL; sl_test[i].expected = "2147483645"; + i++; sl_test[i].num = 0x7FFF0000L; sl_test[i].expected = "2147418112"; + i++; sl_test[i].num = 0x00007FFFL; sl_test[i].expected = "32767"; + + i++; sl_test[i].num = 0x7F000000L; sl_test[i].expected = "2130706432"; + i++; sl_test[i].num = 0x007F0000L; sl_test[i].expected = "8323072"; + i++; sl_test[i].num = 0x00007F00L; sl_test[i].expected = "32512"; + i++; sl_test[i].num = 0x0000007FL; sl_test[i].expected = "127"; + + i++; sl_test[i].num = 0x70000000L; sl_test[i].expected = "1879048192"; + i++; sl_test[i].num = 0x07000000L; sl_test[i].expected = "117440512"; + i++; sl_test[i].num = 0x00700000L; sl_test[i].expected = "7340032"; + i++; sl_test[i].num = 0x00070000L; sl_test[i].expected = "458752"; + i++; sl_test[i].num = 0x00007000L; sl_test[i].expected = "28672"; + i++; sl_test[i].num = 0x00000700L; sl_test[i].expected = "1792"; + i++; sl_test[i].num = 0x00000070L; sl_test[i].expected = "112"; + i++; sl_test[i].num = 0x00000007L; sl_test[i].expected = "7"; + + i++; sl_test[i].num = 0x50000000L; sl_test[i].expected = "1342177280"; + i++; sl_test[i].num = 0x05000000L; sl_test[i].expected = "83886080"; + i++; sl_test[i].num = 0x00500000L; sl_test[i].expected = "5242880"; + i++; sl_test[i].num = 0x00050000L; sl_test[i].expected = "327680"; + i++; sl_test[i].num = 0x00005000L; sl_test[i].expected = "20480"; + i++; sl_test[i].num = 0x00000500L; sl_test[i].expected = "1280"; + i++; sl_test[i].num = 0x00000050L; sl_test[i].expected = "80"; + i++; sl_test[i].num = 0x00000005L; sl_test[i].expected = "5"; + + i++; sl_test[i].num = 0x00000001L; sl_test[i].expected = "1"; + i++; sl_test[i].num = 0x00000000L; sl_test[i].expected = "0"; + + i++; sl_test[i].num = -0x7FFFFFFFL -1L; sl_test[i].expected = "-2147483648"; + i++; sl_test[i].num = -0x7FFFFFFEL -1L; sl_test[i].expected = "-2147483647"; + i++; sl_test[i].num = -0x7FFFFFFDL -1L; sl_test[i].expected = "-2147483646"; + i++; sl_test[i].num = -0x7FFF0000L -1L; sl_test[i].expected = "-2147418113"; + i++; sl_test[i].num = -0x00007FFFL -1L; sl_test[i].expected = "-32768"; + + i++; sl_test[i].num = -0x7F000000L -1L; sl_test[i].expected = "-2130706433"; + i++; sl_test[i].num = -0x007F0000L -1L; sl_test[i].expected = "-8323073"; + i++; sl_test[i].num = -0x00007F00L -1L; sl_test[i].expected = "-32513"; + i++; sl_test[i].num = -0x0000007FL -1L; sl_test[i].expected = "-128"; + + i++; sl_test[i].num = -0x70000000L -1L; sl_test[i].expected = "-1879048193"; + i++; sl_test[i].num = -0x07000000L -1L; sl_test[i].expected = "-117440513"; + i++; sl_test[i].num = -0x00700000L -1L; sl_test[i].expected = "-7340033"; + i++; sl_test[i].num = -0x00070000L -1L; sl_test[i].expected = "-458753"; + i++; sl_test[i].num = -0x00007000L -1L; sl_test[i].expected = "-28673"; + i++; sl_test[i].num = -0x00000700L -1L; sl_test[i].expected = "-1793"; + i++; sl_test[i].num = -0x00000070L -1L; sl_test[i].expected = "-113"; + i++; sl_test[i].num = -0x00000007L -1L; sl_test[i].expected = "-8"; + + i++; sl_test[i].num = -0x50000000L -1L; sl_test[i].expected = "-1342177281"; + i++; sl_test[i].num = -0x05000000L -1L; sl_test[i].expected = "-83886081"; + i++; sl_test[i].num = -0x00500000L -1L; sl_test[i].expected = "-5242881"; + i++; sl_test[i].num = -0x00050000L -1L; sl_test[i].expected = "-327681"; + i++; sl_test[i].num = -0x00005000L -1L; sl_test[i].expected = "-20481"; + i++; sl_test[i].num = -0x00000500L -1L; sl_test[i].expected = "-1281"; + i++; sl_test[i].num = -0x00000050L -1L; sl_test[i].expected = "-81"; + i++; sl_test[i].num = -0x00000005L -1L; sl_test[i].expected = "-6"; + + i++; sl_test[i].num = 0x00000000L -1L; sl_test[i].expected = "-1"; + + num_slong_tests = i; + +#elif (SIZEOF_LONG == 8) + + i = 1; sl_test[i].num = 0x7FFFFFFFFFFFFFFFL; sl_test[i].expected = "9223372036854775807"; + i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFEL; sl_test[i].expected = "9223372036854775806"; + i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFDL; sl_test[i].expected = "9223372036854775805"; + i++; sl_test[i].num = 0x7FFFFFFF00000000L; sl_test[i].expected = "9223372032559808512"; + i++; sl_test[i].num = 0x000000007FFFFFFFL; sl_test[i].expected = "2147483647"; + + i++; sl_test[i].num = 0x7FFF000000000000L; sl_test[i].expected = "9223090561878065152"; + i++; sl_test[i].num = 0x00007FFF00000000L; sl_test[i].expected = "140733193388032"; + i++; sl_test[i].num = 0x000000007FFF0000L; sl_test[i].expected = "2147418112"; + i++; sl_test[i].num = 0x0000000000007FFFL; sl_test[i].expected = "32767"; + + i++; sl_test[i].num = 0x7F00000000000000L; sl_test[i].expected = "9151314442816847872"; + i++; sl_test[i].num = 0x007F000000000000L; sl_test[i].expected = "35747322042253312"; + i++; sl_test[i].num = 0x00007F0000000000L; sl_test[i].expected = "139637976727552"; + i++; sl_test[i].num = 0x0000007F00000000L; sl_test[i].expected = "545460846592"; + i++; sl_test[i].num = 0x000000007F000000L; sl_test[i].expected = "2130706432"; + i++; sl_test[i].num = 0x00000000007F0000L; sl_test[i].expected = "8323072"; + i++; sl_test[i].num = 0x0000000000007F00L; sl_test[i].expected = "32512"; + i++; sl_test[i].num = 0x000000000000007FL; sl_test[i].expected = "127"; + + i++; sl_test[i].num = 0x7000000000000000L; sl_test[i].expected = "8070450532247928832"; + i++; sl_test[i].num = 0x0700000000000000L; sl_test[i].expected = "504403158265495552"; + i++; sl_test[i].num = 0x0070000000000000L; sl_test[i].expected = "31525197391593472"; + i++; sl_test[i].num = 0x0007000000000000L; sl_test[i].expected = "1970324836974592"; + i++; sl_test[i].num = 0x0000700000000000L; sl_test[i].expected = "123145302310912"; + i++; sl_test[i].num = 0x0000070000000000L; sl_test[i].expected = "7696581394432"; + i++; sl_test[i].num = 0x0000007000000000L; sl_test[i].expected = "481036337152"; + i++; sl_test[i].num = 0x0000000700000000L; sl_test[i].expected = "30064771072"; + i++; sl_test[i].num = 0x0000000070000000L; sl_test[i].expected = "1879048192"; + i++; sl_test[i].num = 0x0000000007000000L; sl_test[i].expected = "117440512"; + i++; sl_test[i].num = 0x0000000000700000L; sl_test[i].expected = "7340032"; + i++; sl_test[i].num = 0x0000000000070000L; sl_test[i].expected = "458752"; + i++; sl_test[i].num = 0x0000000000007000L; sl_test[i].expected = "28672"; + i++; sl_test[i].num = 0x0000000000000700L; sl_test[i].expected = "1792"; + i++; sl_test[i].num = 0x0000000000000070L; sl_test[i].expected = "112"; + i++; sl_test[i].num = 0x0000000000000007L; sl_test[i].expected = "7"; + + i++; sl_test[i].num = 0x0000000000000001L; sl_test[i].expected = "1"; + i++; sl_test[i].num = 0x0000000000000000L; sl_test[i].expected = "0"; + + i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFFL -1L; sl_test[i].expected = "-9223372036854775808"; + i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFEL -1L; sl_test[i].expected = "-9223372036854775807"; + i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFDL -1L; sl_test[i].expected = "-9223372036854775806"; + i++; sl_test[i].num = -0x7FFFFFFF00000000L -1L; sl_test[i].expected = "-9223372032559808513"; + i++; sl_test[i].num = -0x000000007FFFFFFFL -1L; sl_test[i].expected = "-2147483648"; + + i++; sl_test[i].num = -0x7FFF000000000000L -1L; sl_test[i].expected = "-9223090561878065153"; + i++; sl_test[i].num = -0x00007FFF00000000L -1L; sl_test[i].expected = "-140733193388033"; + i++; sl_test[i].num = -0x000000007FFF0000L -1L; sl_test[i].expected = "-2147418113"; + i++; sl_test[i].num = -0x0000000000007FFFL -1L; sl_test[i].expected = "-32768"; + + i++; sl_test[i].num = -0x7F00000000000000L -1L; sl_test[i].expected = "-9151314442816847873"; + i++; sl_test[i].num = -0x007F000000000000L -1L; sl_test[i].expected = "-35747322042253313"; + i++; sl_test[i].num = -0x00007F0000000000L -1L; sl_test[i].expected = "-139637976727553"; + i++; sl_test[i].num = -0x0000007F00000000L -1L; sl_test[i].expected = "-545460846593"; + i++; sl_test[i].num = -0x000000007F000000L -1L; sl_test[i].expected = "-2130706433"; + i++; sl_test[i].num = -0x00000000007F0000L -1L; sl_test[i].expected = "-8323073"; + i++; sl_test[i].num = -0x0000000000007F00L -1L; sl_test[i].expected = "-32513"; + i++; sl_test[i].num = -0x000000000000007FL -1L; sl_test[i].expected = "-128"; + + i++; sl_test[i].num = -0x7000000000000000L -1L; sl_test[i].expected = "-8070450532247928833"; + i++; sl_test[i].num = -0x0700000000000000L -1L; sl_test[i].expected = "-504403158265495553"; + i++; sl_test[i].num = -0x0070000000000000L -1L; sl_test[i].expected = "-31525197391593473"; + i++; sl_test[i].num = -0x0007000000000000L -1L; sl_test[i].expected = "-1970324836974593"; + i++; sl_test[i].num = -0x0000700000000000L -1L; sl_test[i].expected = "-123145302310913"; + i++; sl_test[i].num = -0x0000070000000000L -1L; sl_test[i].expected = "-7696581394433"; + i++; sl_test[i].num = -0x0000007000000000L -1L; sl_test[i].expected = "-481036337153"; + i++; sl_test[i].num = -0x0000000700000000L -1L; sl_test[i].expected = "-30064771073"; + i++; sl_test[i].num = -0x0000000070000000L -1L; sl_test[i].expected = "-1879048193"; + i++; sl_test[i].num = -0x0000000007000000L -1L; sl_test[i].expected = "-117440513"; + i++; sl_test[i].num = -0x0000000000700000L -1L; sl_test[i].expected = "-7340033"; + i++; sl_test[i].num = -0x0000000000070000L -1L; sl_test[i].expected = "-458753"; + i++; sl_test[i].num = -0x0000000000007000L -1L; sl_test[i].expected = "-28673"; + i++; sl_test[i].num = -0x0000000000000700L -1L; sl_test[i].expected = "-1793"; + i++; sl_test[i].num = -0x0000000000000070L -1L; sl_test[i].expected = "-113"; + i++; sl_test[i].num = -0x0000000000000007L -1L; sl_test[i].expected = "-8"; + + i++; sl_test[i].num = 0x0000000000000000L -1L; sl_test[i].expected = "-1"; + + num_slong_tests = i; + +#endif + + for(i = 1; i <= num_slong_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + sl_test[i].result[j] = 'X'; + sl_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(sl_test[i].result, "%ld", sl_test[i].num); + + if(memcmp(sl_test[i].result, + sl_test[i].expected, + strlen(sl_test[i].expected))) { + printf("signed long test #%.2d: Failed (Expected: %s Got: %s)\n", + i, sl_test[i].expected, sl_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() signed long tests OK!\n"); + else + printf("Some curl_mprintf() signed long tests Failed!\n"); + + return failed; +} + + +static int test_curl_off_t_formatting(void) +{ + int i, j; + int num_cofft_tests = 0; + int failed = 0; + + i = 1; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF); co_test[i].expected = "9223372036854775807"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE); co_test[i].expected = "9223372036854775806"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD); co_test[i].expected = "9223372036854775805"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFF00000000); co_test[i].expected = "9223372032559808512"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFFFFFF); co_test[i].expected = "2147483647"; + + i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFF000000000000); co_test[i].expected = "9223090561878065152"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x00007FFF00000000); co_test[i].expected = "140733193388032"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFF0000); co_test[i].expected = "2147418112"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007FFF); co_test[i].expected = "32767"; + + i++; co_test[i].num = MPRNT_OFF_T_C(0x7F00000000000000); co_test[i].expected = "9151314442816847872"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x007F000000000000); co_test[i].expected = "35747322042253312"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x00007F0000000000); co_test[i].expected = "139637976727552"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007F00000000); co_test[i].expected = "545460846592"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007F000000); co_test[i].expected = "2130706432"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000007F0000); co_test[i].expected = "8323072"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007F00); co_test[i].expected = "32512"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x000000000000007F); co_test[i].expected = "127"; + + i++; co_test[i].num = MPRNT_OFF_T_C(0x7000000000000000); co_test[i].expected = "8070450532247928832"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0700000000000000); co_test[i].expected = "504403158265495552"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0070000000000000); co_test[i].expected = "31525197391593472"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0007000000000000); co_test[i].expected = "1970324836974592"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000700000000000); co_test[i].expected = "123145302310912"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000070000000000); co_test[i].expected = "7696581394432"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007000000000); co_test[i].expected = "481036337152"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000700000000); co_test[i].expected = "30064771072"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000070000000); co_test[i].expected = "1879048192"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000007000000); co_test[i].expected = "117440512"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000700000); co_test[i].expected = "7340032"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000070000); co_test[i].expected = "458752"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007000); co_test[i].expected = "28672"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000700); co_test[i].expected = "1792"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000070); co_test[i].expected = "112"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000007); co_test[i].expected = "7"; + + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000001); co_test[i].expected = "1"; + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000); co_test[i].expected = "0"; + + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775808"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775807"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775806"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372032559808513"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483648"; + + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223090561878065153"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007FFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-140733193388033"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFF0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147418113"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768"; + + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F00000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9151314442816847873"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-35747322042253313"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007F0000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-139637976727553"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007F00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-545460846593"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007F000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2130706433"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000000007F0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8323073"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000000000007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128"; + + i++; co_test[i].num = -MPRNT_OFF_T_C(0x7000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8070450532247928833"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0700000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-504403158265495553"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0070000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-31525197391593473"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0007000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1970324836974593"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000700000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-123145302310913"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000070000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7696581394433"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-481036337153"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000700000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-30064771073"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000070000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1879048193"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000007000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-117440513"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000700000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7340033"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000070000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-458753"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113"; + i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8"; + + i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1"; + + num_cofft_tests = i; + + for(i = 1; i <= num_cofft_tests; i++) { + + for(j = 0; j < BUFSZ; j++) + co_test[i].result[j] = 'X'; + co_test[i].result[BUFSZ-1] = '\0'; + + (void)curl_msprintf(co_test[i].result, "%" CURL_FORMAT_CURL_OFF_T, + co_test[i].num); + + if(memcmp(co_test[i].result, + co_test[i].expected, + strlen(co_test[i].expected))) { + printf("curl_off_t test #%.2d: Failed (Expected: %s Got: %s)\n", + i, co_test[i].expected, co_test[i].result); + failed++; + } + + } + + if(!failed) + printf("All curl_mprintf() curl_off_t tests OK!\n"); + else + printf("Some curl_mprintf() curl_off_t tests Failed!\n"); + + return failed; +} + +static int _string_check(int linenumber, char *buf, const char *buf2) +{ + if(strcmp(buf, buf2)) { + /* they shouldn't differ */ + printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n", + linenumber, buf, buf2); + return 1; + } + return 0; +} +#define string_check(x,y) _string_check(__LINE__, x, y) + +static int _strlen_check(int linenumber, char *buf, size_t len) +{ + size_t buflen = strlen(buf); + if(len != buflen) { + /* they shouldn't differ */ + printf("sprintf strlen:%d failed:\nwe '%zu'\nsystem: '%zu'\n", + linenumber, buflen, len); + return 1; + } + return 0; +} + +#define strlen_check(x,y) _strlen_check(__LINE__, x, y) + +/* + * The output strings in this test need to have been verified with a system + * sprintf() before used here. + */ +static int test_string_formatting(void) +{ + int errors = 0; + char buf[256]; + curl_msnprintf(buf, sizeof(buf), "%0*d%s", 2, 9, "foo"); + errors += string_check(buf, "09foo"); + + curl_msnprintf(buf, sizeof(buf), "%*.*s", 5, 2, "foo"); + errors += string_check(buf, " fo"); + + curl_msnprintf(buf, sizeof(buf), "%*.*s", 2, 5, "foo"); + errors += string_check(buf, "foo"); + + curl_msnprintf(buf, sizeof(buf), "%*.*s", 0, 10, "foo"); + errors += string_check(buf, "foo"); + + curl_msnprintf(buf, sizeof(buf), "%-10s", "foo"); + errors += string_check(buf, "foo "); + + curl_msnprintf(buf, sizeof(buf), "%10s", "foo"); + errors += string_check(buf, " foo"); + + curl_msnprintf(buf, sizeof(buf), "%*.*s", -10, -10, "foo"); + errors += string_check(buf, "foo "); + + if(!errors) + printf("All curl_mprintf() strings tests OK!\n"); + else + printf("Some curl_mprintf() string tests Failed!\n"); + + return errors; +} + +static int test_pos_arguments(void) +{ + int errors = 0; + char buf[256]; + + curl_msnprintf(buf, sizeof(buf), "%3$d %2$d %1$d", 500, 501, 502); + errors += string_check(buf, "502 501 500"); + + curl_msnprintf(buf, sizeof(buf), "%3$d %1$d %2$d", 500, 501, 502); + errors += string_check(buf, "502 500 501"); + + /* this is in invalid sequence but the output does not match + what glibc does */ + curl_msnprintf(buf, sizeof(buf), "%3$d %d %2$d", 500, 501, 502); + errors += string_check(buf, ""); + + return errors; +} + +static int test_weird_arguments(void) +{ + int errors = 0; + char buf[256]; + int rc; + + /* verify %% */ + rc = curl_msnprintf(buf, sizeof(buf), "%-20d%% right? %%", 500); + errors += string_check(buf, "500 % right? %"); + + /* 100 x % */ + rc = curl_msnprintf(buf, sizeof(buf), "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + "%%%%%%%%%%%%%%%%%%%%%%"); + /* 50 x % */ + errors += string_check(buf, "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + "%%%%%%%%%%%%%%%"); + + rc = curl_msnprintf(buf, sizeof(buf), "%2 AA %d %K", 500, 501, 502); + errors += string_check(buf, "%2 AA 500 %K"); + + rc = curl_msnprintf(buf, sizeof(buf), "%2 %d %K", 500, 501, 502); + errors += string_check(buf, "%2 500 %K"); + + /* MAX_PARAMETERS is 128, try exact 128! */ + rc = curl_msnprintf(buf, sizeof(buf), + "%d%d%d%d%d%d%d%d%d%d" /* 10 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 1 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 2 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 3 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 4 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 5 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 6 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 7 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 8 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 9 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 10 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 11 */ + "%d%d%d%d%d%d%d%d" /* 8 */ + , + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */ + 0, 1, 2, 3, 4, 5, 6, 7); /* 8 */ + + if(rc != 128) { + printf("curl_mprintf() returned %d and not 128!\n", rc); + errors++; + } + + errors += string_check(buf, + "0123456789" /* 10 */ + "0123456789" /* 10 1 */ + "0123456789" /* 10 2 */ + "0123456789" /* 10 3 */ + "0123456789" /* 10 4 */ + "0123456789" /* 10 5 */ + "0123456789" /* 10 6 */ + "0123456789" /* 10 7 */ + "0123456789" /* 10 8 */ + "0123456789" /* 10 9 */ + "0123456789" /* 10 10 */ + "0123456789" /* 10 11 */ + "01234567" /* 8 */ + ); + + /* MAX_PARAMETERS is 128, try more! */ + buf[0] = 0; + rc = curl_msnprintf(buf, sizeof(buf), + "%d%d%d%d%d%d%d%d%d%d" /* 10 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 1 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 2 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 3 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 4 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 5 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 6 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 7 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 8 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 9 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 10 */ + "%d%d%d%d%d%d%d%d%d%d" /* 10 11 */ + "%d%d%d%d%d%d%d%d%d" /* 9 */ + , + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */ + 0, 1, 2, 3, 4, 5, 6, 7, 8); /* 9 */ + + if(rc) { + printf("curl_mprintf() returned %d and not 0\n", rc); + errors++; + } + + errors += string_check(buf, ""); + + if(errors) + printf("Some curl_mprintf() weird arguments tests failed!\n"); + + return errors; +} + +/* DBL_MAX value from Linux */ +#define MAXIMIZE -1.7976931348623157081452E+308 + +static int test_float_formatting(void) +{ + int errors = 0; + char buf[512]; /* larger than max float size */ + curl_msnprintf(buf, sizeof(buf), "%f", 9.0); + errors += string_check(buf, "9.000000"); + + curl_msnprintf(buf, sizeof(buf), "%.1f", 9.1); + errors += string_check(buf, "9.1"); + + curl_msnprintf(buf, sizeof(buf), "%.2f", 9.1); + errors += string_check(buf, "9.10"); + + curl_msnprintf(buf, sizeof(buf), "%.0f", 9.1); + errors += string_check(buf, "9"); + + curl_msnprintf(buf, sizeof(buf), "%0f", 9.1); + errors += string_check(buf, "9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%10f", 9.1); + errors += string_check(buf, " 9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%10.3f", 9.1); + errors += string_check(buf, " 9.100"); + + curl_msnprintf(buf, sizeof(buf), "%-10.3f", 9.1); + errors += string_check(buf, "9.100 "); + + curl_msnprintf(buf, sizeof(buf), "%-10.3f", 9.123456); + errors += string_check(buf, "9.123 "); + + curl_msnprintf(buf, sizeof(buf), "%.-2f", 9.1); + errors += string_check(buf, "9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%*f", 10, 9.1); + errors += string_check(buf, " 9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%*f", 3, 9.1); + errors += string_check(buf, "9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.2987654); + errors += string_check(buf, "9.298765"); + + curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.298765); + errors += string_check(buf, "9.298765"); + + curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.29876); + errors += string_check(buf, "9.298760"); + + curl_msnprintf(buf, sizeof(buf), "%.*f", 6, 9.2987654); + errors += string_check(buf, "9.298765"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 5, 9.2987654); + errors += string_check(buf, "9.29877"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 4, 9.2987654); + errors += string_check(buf, "9.2988"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 3, 9.2987654); + errors += string_check(buf, "9.299"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 2, 9.2987654); + errors += string_check(buf, "9.30"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 1, 9.2987654); + errors += string_check(buf, "9.3"); + curl_msnprintf(buf, sizeof(buf), "%.*f", 0, 9.2987654); + errors += string_check(buf, "9"); + + /* very large precisions easily turn into system specific outputs so we only + check the output buffer length here as we know the internal limit */ + + curl_msnprintf(buf, sizeof(buf), "%.*f", (1 << 30), 9.2987654); + errors += strlen_check(buf, 325); + + curl_msnprintf(buf, sizeof(buf), "%10000.10000f", 9.2987654); + errors += strlen_check(buf, 325); + + curl_msnprintf(buf, sizeof(buf), "%240.10000f", + 123456789123456789123456789.2987654); + errors += strlen_check(buf, 325); + + /* check negative width argument when used signed, is treated as positive + and maxes out the internal float width == 325 */ + curl_msnprintf(buf, sizeof(buf), "%*f", INT_MIN, 9.1); + errors += string_check(buf, "9.100000 "); + + /* curl_msnprintf() limits a single float output to 325 bytes maximum + width */ + curl_msnprintf(buf, sizeof(buf), "%*f", (1 << 30), 9.1); + errors += string_check(buf, " 9.100000"); + curl_msnprintf(buf, sizeof(buf), "%100000f", 9.1); + errors += string_check(buf, " 9.100000"); + + curl_msnprintf(buf, sizeof(buf), "%f", MAXIMIZE); + errors += strlen_check(buf, 317); + + curl_msnprintf(buf, 2, "%f", MAXIMIZE); + errors += strlen_check(buf, 1); + curl_msnprintf(buf, 3, "%f", MAXIMIZE); + errors += strlen_check(buf, 2); + curl_msnprintf(buf, 4, "%f", MAXIMIZE); + errors += strlen_check(buf, 3); + curl_msnprintf(buf, 5, "%f", MAXIMIZE); + errors += strlen_check(buf, 4); + curl_msnprintf(buf, 6, "%f", MAXIMIZE); + errors += strlen_check(buf, 5); + + if(!errors) + printf("All float strings tests OK!\n"); + else + printf("test_float_formatting Failed!\n"); + + return errors; +} + +static int test_oct_hex_formatting(void) +{ + int errors = 0; + char buf[256]; + + curl_msnprintf(buf, sizeof(buf), "%ho %hx %hX", 0xFA10U, 0xFA10U, 0xFA10U); + errors += string_check(buf, "175020 fa10 FA10"); + +#if (SIZEOF_INT == 2) + curl_msnprintf(buf, sizeof(buf), "%o %x %X", 0xFA10U, 0xFA10U, 0xFA10U); + errors += string_check(buf, "175020 fa10 FA10"); +#elif (SIZEOF_INT == 4) + curl_msnprintf(buf, sizeof(buf), "%o %x %X", + 0xFABC1230U, 0xFABC1230U, 0xFABC1230U); + errors += string_check(buf, "37257011060 fabc1230 FABC1230"); +#elif (SIZEOF_INT == 8) + curl_msnprintf(buf, sizeof(buf), "%o %x %X", + 0xFABCDEF123456780U, 0xFABCDEF123456780U, 0xFABCDEF123456780U); + errors += string_check(buf, "1752746757044321263600 fabcdef123456780 FABCDEF123456780"); +#endif + +#if (SIZEOF_LONG == 2) + curl_msnprintf(buf, sizeof(buf), "%lo %lx %lX", 0xFA10UL, 0xFA10UL, 0xFA10UL); + errors += string_check(buf, "175020 fa10 FA10"); +#elif (SIZEOF_LONG == 4) + curl_msnprintf(buf, sizeof(buf), "%lo %lx %lX", + 0xFABC1230UL, 0xFABC1230UL, 0xFABC1230UL); + errors += string_check(buf, "37257011060 fabc1230 FABC1230"); +#elif (SIZEOF_LONG == 8) + curl_msnprintf(buf, sizeof(buf), "%lo %lx %lX", + 0xFABCDEF123456780UL, 0xFABCDEF123456780UL, 0xFABCDEF123456780UL); + errors += string_check(buf, "1752746757044321263600 fabcdef123456780 FABCDEF123456780"); +#endif + + if(!errors) + printf("All curl_mprintf() octal & hexadecimal tests OK!\n"); + else + printf("Some curl_mprintf() octal & hexadecimal tests Failed!\n"); + + return errors; +} +/* !checksrc! enable LONGLINE */ + +static int test_return_codes(void) +{ + char buf[128]; + int rc; + + rc = curl_msnprintf(buf, 100, "%d", 9999); + if(rc != 4) + return 1; + + rc = curl_msnprintf(buf, 100, "%d", 99999); + if(rc != 5) + return 1; + + /* returns the length excluding the nul byte */ + rc = curl_msnprintf(buf, 5, "%d", 99999); + if(rc != 4) + return 1; + + /* returns the length excluding the nul byte */ + rc = curl_msnprintf(buf, 5, "%s", "helloooooooo"); + if(rc != 4) + return 1; + + /* returns the length excluding the nul byte */ + rc = curl_msnprintf(buf, 6, "%s", "helloooooooo"); + if(rc != 5) + return 1; + + return 0; +} + +CURLcode test(char *URL) +{ + int errors = 0; + (void)URL; /* not used */ + +#ifdef HAVE_SETLOCALE + /* + * The test makes assumptions about the numeric locale (specifically, + * RADIXCHAR) so set it to a known working (and portable) one. + */ + setlocale(LC_NUMERIC, "C"); +#endif + + errors += test_pos_arguments(); + + errors += test_weird_arguments(); + + errors += test_unsigned_short_formatting(); + + errors += test_signed_short_formatting(); + + errors += test_unsigned_int_formatting(); + + errors += test_signed_int_formatting(); + + errors += test_unsigned_long_formatting(); + + errors += test_signed_long_formatting(); + + errors += test_curl_off_t_formatting(); + + errors += test_string_formatting(); + + errors += test_float_formatting(); + + errors += test_oct_hex_formatting(); + + errors += test_return_codes(); + + if(errors) + return TEST_ERR_MAJOR_BAD; + else + return CURLE_OK; +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib558.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib558.c new file mode 100644 index 0000000000000000000000000000000000000000..3fdc3b508da748e84c39f28be57b5d58268baf3b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib558.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + unsigned char a[] = {0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe6, 0xf7}; + CURLcode res = CURLE_OK; + char *ptr = NULL; + int asize; + + (void)URL; /* we don't use this */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + ptr = malloc(558); + Curl_safefree(ptr); + + asize = (int)sizeof(a); + ptr = curl_easy_escape(NULL, (char *)a, asize); + if(ptr) + curl_free(ptr); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib559.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib559.c new file mode 100644 index 0000000000000000000000000000000000000000..aee660bb4f1851d368004605ba2b7d5a1b396b28 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib559.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "testtrace.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_BUFFERSIZE, 1L); /* the smallest! */ + + res = curl_easy_perform(curl); +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib560.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib560.c new file mode 100644 index 0000000000000000000000000000000000000000..95b62ce784b650d0cb0026a64af8a22dc0eae623 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib560.c @@ -0,0 +1,115 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Simply download an HTTPS file! + * + * This test was added after the HTTPS-using-multi-interface with OpenSSL + * regression of 7.19.1 to hopefully prevent this embarrassing mistake from + * appearing again... Unfortunately the bug wasn't triggered by this test, + * which presumably is because the connect to a local server is too + * fast/different compared to the real/distant servers we saw the bug happen + * with. + */ +CURLcode test(char *URL) +{ + CURL *http_handle = NULL; + CURLM *multi_handle = NULL; + CURLcode res = CURLE_OK; + + int still_running; /* keep number of running handles */ + + start_test_timing(); + + /* + ** curl_global_init called indirectly from curl_easy_init. + */ + + easy_init(http_handle); + + /* set options */ + easy_setopt(http_handle, CURLOPT_URL, URL); + easy_setopt(http_handle, CURLOPT_HEADER, 1L); + easy_setopt(http_handle, CURLOPT_SSL_VERIFYPEER, 0L); + easy_setopt(http_handle, CURLOPT_SSL_VERIFYHOST, 0L); + + /* init a multi stack */ + multi_init(multi_handle); + + /* add the individual transfers */ + multi_add_handle(multi_handle, http_handle); + + /* we start some action by calling perform right away */ + multi_perform(multi_handle, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -99; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + /* set a suitable timeout to play around with */ + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + /* get file descriptors from the transfers */ + multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + + /* timeout or readable/writable sockets */ + multi_perform(multi_handle, &still_running); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi_handle); + curl_easy_cleanup(http_handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib562.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib562.c new file mode 100644 index 0000000000000000000000000000000000000000..92cfbe962aa87208033f5b8f2964eb2a251c479a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib562.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* + * From "KNOWN_BUGS" April 2009: + + 59. If the CURLOPT_PORT option is used on an FTP URL like + "ftp://example.com/file;type=A" the ";type=A" is stripped off. + + */ + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* get a curl handle */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* enable verbose */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* set port number */ + test_setopt(curl, CURLOPT_PORT, strtol(libtest_arg2, NULL, 10)); + + /* specify target */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib564.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib564.c new file mode 100644 index 0000000000000000000000000000000000000000..7d0cf8d59d0d4d41cdf3e9ff6f62ad75af51e221 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib564.c @@ -0,0 +1,95 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + int running; + CURLM *m = NULL; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_PROXY, libtest_arg2); + easy_setopt(curl, CURLOPT_PROXYTYPE, (long)CURLPROXY_SOCKS4); + + multi_init(m); + + multi_add_handle(m, curl); + + fprintf(stderr, "Start at URL 0\n"); + + for(;;) { + struct timeval interval; + fd_set rd, wr, exc; + int maxfd = -99; + + interval.tv_sec = 1; + interval.tv_usec = 0; + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&rd); + FD_ZERO(&wr); + FD_ZERO(&exc); + + multi_fdset(m, &rd, &wr, &exc, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &rd, &wr, &exc, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* undocumented cleanup sequence - type UB */ + + curl_easy_cleanup(curl); + curl_multi_cleanup(m); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib566.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib566.c new file mode 100644 index 0000000000000000000000000000000000000000..89ad0c40df95272b327c48cee266b1628d222f9b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib566.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + double content_length = 3; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + + res = curl_easy_perform(curl); + + if(!res) { + FILE *moo; + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, + &content_length); + ) + moo = fopen(libtest_arg2, "wb"); + if(moo) { + fprintf(moo, "CL %.0f\n", content_length); + fclose(moo); + } + } + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib567.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib567.c new file mode 100644 index 0000000000000000000000000000000000000000..21338e03ecd384c273b61991a9f39d7aa1c1ab3a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib567.c @@ -0,0 +1,72 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +/* + * Test a simple OPTIONS request with a custom header + */ +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + struct curl_slist *custom_headers = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* Dump data to stdout for protocol verification */ + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, URL); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); + test_setopt(curl, CURLOPT_USERAGENT, "test567"); + + custom_headers = curl_slist_append(custom_headers, "Test-Number: 567"); + test_setopt(curl, CURLOPT_RTSPHEADER, custom_headers); + + res = curl_easy_perform(curl); + +test_cleanup: + + if(custom_headers) + curl_slist_free_all(custom_headers); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib568.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib568.c new file mode 100644 index 0000000000000000000000000000000000000000..ae29c06415335cc3688c109f82b41b629a5f1eb8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib568.c @@ -0,0 +1,180 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + +/* + * Test the Client->Server ANNOUNCE functionality (PUT style) + */ +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + int sdp; + FILE *sdpf = NULL; + struct_stat file_info; + char *stream_uri = NULL; + int request = 1; + struct curl_slist *custom_headers = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + + test_setopt(curl, CURLOPT_URL, URL); + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + sdp = open(libtest_arg2, O_RDONLY); + fstat(sdp, &file_info); + close(sdp); + + sdpf = fopen(libtest_arg2, "rb"); + if(!sdpf) { + fprintf(stderr, "can't open %s\n", libtest_arg2); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_ANNOUNCE); + + test_setopt(curl, CURLOPT_READDATA, sdpf); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) file_info.st_size); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Do the ANNOUNCE */ + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_UPLOAD, 0L); + fclose(sdpf); + sdpf = NULL; + + /* Make sure we can do a normal request now */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* Now do a POST style one */ + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + custom_headers = curl_slist_append(custom_headers, + "Content-Type: posty goodness"); + if(!custom_headers) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSPHEADER, custom_headers); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_ANNOUNCE); + test_setopt(curl, CURLOPT_POSTFIELDS, + "postyfield=postystuff&project=curl\n"); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_POSTFIELDS, NULL); + test_setopt(curl, CURLOPT_RTSPHEADER, NULL); + curl_slist_free_all(custom_headers); + custom_headers = NULL; + + /* Make sure we can do a normal request now */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); + res = curl_easy_perform(curl); + +test_cleanup: + + if(sdpf) + fclose(sdpf); + + curl_free(stream_uri); + + if(custom_headers) + curl_slist_free_all(custom_headers); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib569.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib569.c new file mode 100644 index 0000000000000000000000000000000000000000..847116a34ab0af218018511e5954264f4053b6ba --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib569.c @@ -0,0 +1,128 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "memdebug.h" + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + +/* + * Test Session ID capture + */ +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + char *stream_uri = NULL; + char *rtsp_session_id; + int request = 1; + int i; + + FILE *idfile = fopen(libtest_arg2, "wb"); + if(!idfile) { + fprintf(stderr, "couldn't open the Session ID File\n"); + return TEST_ERR_MAJOR_BAD; + } + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + fclose(idfile); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + fclose(idfile); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_URL, URL); + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); + res = curl_easy_perform(curl); + if(res != (int)CURLE_BAD_FUNCTION_ARGUMENT) { + fprintf(stderr, "This should have failed. " + "Cannot setup without a Transport: header"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + /* Go through the various Session IDs */ + for(i = 0; i < 3; i++) { + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); + test_setopt(curl, CURLOPT_RTSP_TRANSPORT, + "Fake/NotReal/JustATest;foo=baz"); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + curl_easy_getinfo(curl, CURLINFO_RTSP_SESSION_ID, &rtsp_session_id); + fprintf(idfile, "Got Session ID: [%s]\n", rtsp_session_id); + rtsp_session_id = NULL; + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_TEARDOWN); + res = curl_easy_perform(curl); + + /* Clear for the next go-round */ + test_setopt(curl, CURLOPT_RTSP_SESSION_ID, NULL); + } + +test_cleanup: + + if(idfile) + fclose(idfile); + + curl_free(stream_uri); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib570.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib570.c new file mode 100644 index 0000000000000000000000000000000000000000..3d15e9bcf87cd1b51f7af2e5033aa40f322d8c4f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib570.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 + * + ***************************************************************************/ +#include "test.h" +#include "memdebug.h" + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + int request = 1; + char *stream_uri = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_URL, URL); + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + res = curl_easy_perform(curl); + if(res != (int)CURLE_RTSP_CSEQ_ERROR) { + fprintf(stderr, "Failed to detect CSeq mismatch"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_RTSP_CLIENT_CSEQ, 999L); + test_setopt(curl, CURLOPT_RTSP_TRANSPORT, + "RAW/RAW/UDP;unicast;client_port=3056-3057"); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY); + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + res = curl_easy_perform(curl); + if(res == CURLE_RTSP_SESSION_ERROR) { + res = CURLE_OK; + } + else { + fprintf(stderr, "Failed to detect a Session ID mismatch"); + res = (CURLcode)1; + } + +test_cleanup: + curl_free(stream_uri); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib571.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib571.c new file mode 100644 index 0000000000000000000000000000000000000000..b7868e0a32f73d2f7d9d9a5fc05078d4b36fac4d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib571.c @@ -0,0 +1,215 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef HAVE_FCNTL_H +# include +#endif + +#include "warnless.h" +#include "memdebug.h" + +#define RTP_PKT_CHANNEL(p) ((int)((unsigned char)((p)[1]))) + +#define RTP_PKT_LENGTH(p) ((((int)((unsigned char)((p)[2]))) << 8) | \ + ((int)((unsigned char)((p)[3])))) + +#define RTP_DATA_SIZE 12 +static const char *RTP_DATA = "$_1234\n\0Rsdf"; + +static int rtp_packet_count = 0; + +static size_t rtp_write(char *ptr, size_t size, size_t nmemb, void *stream) +{ + char *data = (char *)ptr; + int channel = RTP_PKT_CHANNEL(data); + int message_size; + int coded_size = RTP_PKT_LENGTH(data); + size_t failure = (size && nmemb) ? 0 : 1; + int i; + (void)stream; + + message_size = curlx_uztosi(size * nmemb) - 4; + + printf("RTP: message size %d, channel %d\n", message_size, channel); + if(message_size != coded_size) { + printf("RTP embedded size (%d) does not match the write size (%d).\n", + coded_size, message_size); + return failure; + } + + data += 4; + for(i = 0; i < message_size; i += RTP_DATA_SIZE) { + if(message_size - i > RTP_DATA_SIZE) { + if(memcmp(RTP_DATA, data + i, RTP_DATA_SIZE) != 0) { + printf("RTP PAYLOAD CORRUPTED [%s]\n", data + i); + /* return failure; */ + } + } + else { + if(memcmp(RTP_DATA, data + i, message_size - i) != 0) { + printf("RTP PAYLOAD END CORRUPTED (%d), [%s]\n", + message_size - i, data + i); + /* return failure; */ + } + } + } + + rtp_packet_count++; + fprintf(stderr, "packet count is %d\n", rtp_packet_count); + + return size * nmemb; +} + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + char *stream_uri = NULL; + int request = 1; + + FILE *protofile = fopen(libtest_arg2, "wb"); + if(!protofile) { + fprintf(stderr, "Couldn't open the protocol dump file\n"); + return TEST_ERR_MAJOR_BAD; + } + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + fclose(protofile); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + fclose(protofile); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + test_setopt(curl, CURLOPT_URL, URL); + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_INTERLEAVEFUNCTION, rtp_write); + test_setopt(curl, CURLOPT_TIMEOUT, 30L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_WRITEDATA, protofile); + + test_setopt(curl, CURLOPT_RTSP_TRANSPORT, "RTP/AVP/TCP;interleaved=0-1"); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* This PLAY starts the interleave */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* The DESCRIBE request will try to consume data after the Content */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_DESCRIBE); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_PLAY); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + fprintf(stderr, "PLAY COMPLETE\n"); + + /* Use Receive to get the rest of the data */ + while(!res && rtp_packet_count < 19) { + fprintf(stderr, "LOOPY LOOP!\n"); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_RECEIVE); + res = curl_easy_perform(curl); + } + +test_cleanup: + curl_free(stream_uri); + + if(protofile) + fclose(protofile); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib572.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib572.c new file mode 100644 index 0000000000000000000000000000000000000000..f28b741b0bee9260d48a03cdf88ff93d0715f30a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib572.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 "test.h" + +#ifdef HAVE_SYS_STAT_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "memdebug.h" + +/* build request url */ +static char *suburl(const char *base, int i) +{ + return curl_maprintf("%s%.4d", base, i); +} + +/* + * Test GET_PARAMETER: PUT, HEARTBEAT, and POST + */ +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + int params; + FILE *paramsf = NULL; + struct_stat file_info; + char *stream_uri = NULL; + int request = 1; + struct curl_slist *custom_headers = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + + test_setopt(curl, CURLOPT_HEADERDATA, stdout); + test_setopt(curl, CURLOPT_WRITEDATA, stdout); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_URL, URL); + + /* SETUP */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_TRANSPORT, "Planes/Trains/Automobiles"); + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + /* PUT style GET_PARAMETERS */ + params = open(libtest_arg2, O_RDONLY); + fstat(params, &file_info); + close(params); + + paramsf = fopen(libtest_arg2, "rb"); + if(!paramsf) { + fprintf(stderr, "can't open %s\n", libtest_arg2); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_GET_PARAMETER); + + test_setopt(curl, CURLOPT_READDATA, paramsf); + test_setopt(curl, CURLOPT_UPLOAD, 1L); + test_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) file_info.st_size); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_UPLOAD, 0L); + fclose(paramsf); + paramsf = NULL; + + /* Heartbeat GET_PARAMETERS */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* POST GET_PARAMETERS */ + + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_GET_PARAMETER); + test_setopt(curl, CURLOPT_POSTFIELDS, "packets_received\njitter\n"); + + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + test_setopt(curl, CURLOPT_POSTFIELDS, NULL); + + /* Make sure we can do a normal request now */ + stream_uri = suburl(URL, request++); + if(!stream_uri) { + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri); + curl_free(stream_uri); + stream_uri = NULL; + + test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_OPTIONS); + res = curl_easy_perform(curl); + +test_cleanup: + + if(paramsf) + fclose(paramsf); + + curl_free(stream_uri); + + if(custom_headers) + curl_slist_free_all(custom_headers); + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib573.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib573.c new file mode 100644 index 0000000000000000000000000000000000000000..04bc9ded77c4a60bf6e47fb9e1a50fc203cc78ca --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib573.c @@ -0,0 +1,115 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testtrace.h" +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Get a single URL without select(). + */ + +CURLcode test(char *URL) +{ + CURL *c = NULL; + CURLM *m = NULL; + CURLcode res = CURLE_OK; + int running = 1; + double connect_time = 0.0; + double dbl_epsilon; + + dbl_epsilon = 1.0; + do { + dbl_epsilon /= 2.0; + } while((double)(1.0 + (dbl_epsilon/2.0)) > (double)1.0); + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(c); + + easy_setopt(c, CURLOPT_HEADER, 1L); + easy_setopt(c, CURLOPT_URL, URL); + + libtest_debug_config.nohex = 1; + libtest_debug_config.tracetime = 1; + easy_setopt(c, CURLOPT_DEBUGDATA, &libtest_debug_config); + easy_setopt(c, CURLOPT_DEBUGFUNCTION, libtest_debug_cb); + easy_setopt(c, CURLOPT_VERBOSE, 1L); + + multi_init(m); + + multi_add_handle(m, c); + + while(running) { + struct timeval timeout; + fd_set fdread, fdwrite, fdexcep; + int maxfd = -99; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + } + + curl_easy_getinfo(c, CURLINFO_CONNECT_TIME, &connect_time); + if(connect_time < dbl_epsilon) { + fprintf(stderr, "connect time %e is < epsilon %e\n", + connect_time, dbl_epsilon); + res = TEST_ERR_MAJOR_BAD; + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, c); + curl_multi_cleanup(m); + curl_easy_cleanup(c); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib574.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib574.c new file mode 100644 index 0000000000000000000000000000000000000000..0d107ef11385bdb0d2a5580115794f2bcaf8489e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib574.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT (60 * 1000) + +static int new_fnmatch(void *ptr, + const char *pattern, const char *string) +{ + (void)ptr; + fprintf(stderr, "lib574: match string '%s' against pattern '%s'\n", + string, pattern); + return CURL_FNMATCHFUNC_MATCH; +} + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_WILDCARDMATCH, 1L); + test_setopt(curl, CURLOPT_FNMATCH_FUNCTION, new_fnmatch); + test_setopt(curl, CURLOPT_TIMEOUT_MS, (long) TEST_HANG_TIMEOUT); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() failed %d\n", res); + goto test_cleanup; + } + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform() failed %d\n", res); + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib575.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib575.c new file mode 100644 index 0000000000000000000000000000000000000000..d64f70d737d1320531a613307848a9eb3be38f9c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib575.c @@ -0,0 +1,116 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* 3x download! + * 1. normal + * 2. dup handle + * 3. with multi interface + */ + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURL *duphandle = NULL; + CURLM *mhandle = NULL; + CURLcode res = CURLE_OK; + int still_running = 0; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(handle); + + easy_setopt(handle, CURLOPT_URL, URL); + easy_setopt(handle, CURLOPT_WILDCARDMATCH, 1L); + easy_setopt(handle, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(handle); + if(res) + goto test_cleanup; + + res = curl_easy_perform(handle); + if(res) + goto test_cleanup; + + duphandle = curl_easy_duphandle(handle); + if(!duphandle) + goto test_cleanup; + curl_easy_cleanup(handle); + handle = duphandle; + + multi_init(mhandle); + + multi_add_handle(mhandle, handle); + + multi_perform(mhandle, &still_running); + + abort_on_test_timeout(); + + while(still_running) { + struct timeval timeout; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -99; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(mhandle, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + + multi_perform(mhandle, &still_running); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(mhandle); + curl_easy_cleanup(handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib576.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib576.c new file mode 100644 index 0000000000000000000000000000000000000000..db5a41aad6ccc2dbbb8bc3f5992537dd1ff1a3b4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib576.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 "test.h" + +#include "testutil.h" +#include "memdebug.h" + +struct chunk_data { + int remains; + int print_content; +}; + +static +long chunk_bgn(const void *f, void *ptr, int remains) +{ + const struct curl_fileinfo *finfo = f; + struct chunk_data *ch_d = ptr; + ch_d->remains = remains; + + printf("=============================================================\n"); + printf("Remains: %d\n", remains); + printf("Filename: %s\n", finfo->filename); + if(finfo->strings.perm) { + printf("Permissions: %s", finfo->strings.perm); + if(finfo->flags & CURLFINFOFLAG_KNOWN_PERM) + printf(" (parsed => %o)", finfo->perm); + printf("\n"); + } + printf("Size: %ldB\n", (long)finfo->size); + if(finfo->strings.user) + printf("User: %s\n", finfo->strings.user); + if(finfo->strings.group) + printf("Group: %s\n", finfo->strings.group); + if(finfo->strings.time) + printf("Time: %s\n", finfo->strings.time); + printf("Filetype: "); + switch(finfo->filetype) { + case CURLFILETYPE_FILE: + printf("regular file\n"); + break; + case CURLFILETYPE_DIRECTORY: + printf("directory\n"); + break; + case CURLFILETYPE_SYMLINK: + printf("symlink\n"); + printf("Target: %s\n", finfo->strings.target); + break; + default: + printf("other type\n"); + break; + } + if(finfo->filetype == CURLFILETYPE_FILE) { + ch_d->print_content = 1; + printf("Content:\n" + "-------------------------------------------------------------\n"); + } + if(strcmp(finfo->filename, "someothertext.txt") == 0) { + printf("# THIS CONTENT WAS SKIPPED IN CHUNK_BGN CALLBACK #\n"); + return CURL_CHUNK_BGN_FUNC_SKIP; + } + return CURL_CHUNK_BGN_FUNC_OK; +} + +static +long chunk_end(void *ptr) +{ + struct chunk_data *ch_d = ptr; + if(ch_d->print_content) { + ch_d->print_content = 0; + printf("-------------------------------------------------------------\n"); + } + if(ch_d->remains == 1) + printf("=============================================================\n"); + return CURL_CHUNK_END_FUNC_OK; +} + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURLcode res = CURLE_OK; + struct chunk_data chunk_data = {0, 0}; + curl_global_init(CURL_GLOBAL_ALL); + handle = curl_easy_init(); + if(!handle) { + res = CURLE_OUT_OF_MEMORY; + goto test_cleanup; + } + + test_setopt(handle, CURLOPT_URL, URL); + test_setopt(handle, CURLOPT_WILDCARDMATCH, 1L); + test_setopt(handle, CURLOPT_CHUNK_BGN_FUNCTION, chunk_bgn); + test_setopt(handle, CURLOPT_CHUNK_END_FUNCTION, chunk_end); + test_setopt(handle, CURLOPT_CHUNK_DATA, &chunk_data); + + res = curl_easy_perform(handle); + +test_cleanup: + if(handle) + curl_easy_cleanup(handle); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib578.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib578.c new file mode 100644 index 0000000000000000000000000000000000000000..6be64a1aa1df2902baa0809c2179f03987cfa7e0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib578.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 "test.h" + +#include "memdebug.h" + +/* The size of data should be kept below MAX_INITIAL_POST_SIZE! */ +static char testdata[]="this is a short string.\n"; + +static size_t data_size = sizeof(testdata) / sizeof(char); + +static int progress_callback(void *clientp, double dltotal, double dlnow, + double ultotal, double ulnow) +{ + FILE *moo = fopen(libtest_arg2, "wb"); + + (void)clientp; /* UNUSED */ + (void)dltotal; /* UNUSED */ + (void)dlnow; /* UNUSED */ + + if(moo) { + if((size_t)ultotal == data_size && (size_t)ulnow == data_size) + fprintf(moo, "PASSED, UL data matched data size\n"); + else + fprintf(moo, "Progress callback called with UL %f out of %f\n", + ulnow, ultotal); + fclose(moo); + } + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* Set the expected POST size */ + test_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)data_size); + test_setopt(curl, CURLOPT_POSTFIELDS, testdata); + + /* we want to use our own progress function */ + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_NOPROGRESS, 0L); + test_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); + ) + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib579.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib579.c new file mode 100644 index 0000000000000000000000000000000000000000..9b1591fad1be2154a74104b869c6b65f249d631c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib579.c @@ -0,0 +1,169 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static const char * const testpost[]={ + "one", + "two", + "three", + "and a final longer crap: four", + NULL +}; + + +struct WriteThis { + int counter; +}; + +static bool started = FALSE; +static size_t last_ul = 0; +static size_t last_ul_total = 0; + +static void progress_final_report(void) +{ + FILE *moo = fopen(libtest_arg2, "ab"); + fprintf(moo, "Progress: end UL %zu/%zu\n", last_ul, last_ul_total); + started = FALSE; + fclose(moo); +} + +static int progress_callback(void *clientp, double dltotal, double dlnow, + double ultotal, double ulnow) +{ + (void)clientp; /* UNUSED */ + (void)dltotal; /* UNUSED */ + (void)dlnow; /* UNUSED */ + + if(started && ulnow <= 0.0 && last_ul) { + progress_final_report(); + } + + last_ul = (size_t)ulnow; + last_ul_total = (size_t)ultotal; + if(!started) { + FILE *moo = fopen(libtest_arg2, "ab"); + fprintf(moo, "Progress: start UL %zu/%zu\n", last_ul, last_ul_total); + started = TRUE; + fclose(moo); + } + + return 0; +} + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + const char *data; + + if(size*nmemb < 1) + return 0; + + data = testpost[pooh->counter]; + + if(data) { + size_t len = strlen(data); + memcpy(ptr, data, len); + pooh->counter++; /* advance pointer */ + return len; + } + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *slist = NULL; + struct WriteThis pooh; + pooh.counter = 0; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + slist = curl_slist_append(slist, "Transfer-Encoding: chunked"); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Now specify we want to POST data */ + test_setopt(curl, CURLOPT_POST, 1L); + + /* we want to use our own read function */ + test_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* pointer to pass to our read function */ + test_setopt(curl, CURLOPT_READDATA, &pooh); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* enforce chunked transfer by setting the header */ + test_setopt(curl, CURLOPT_HTTPHEADER, slist); + + test_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST); + test_setopt(curl, CURLOPT_USERPWD, "foo:bar"); + + /* we want to use our own progress function */ + test_setopt(curl, CURLOPT_NOPROGRESS, 0L); + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); + ) + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + + progress_final_report(); + +test_cleanup: + + /* clean up the headers list */ + if(slist) + curl_slist_free_all(slist); + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib582.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib582.c new file mode 100644 index 0000000000000000000000000000000000000000..d1609a83d3ff4fc76d0bdcfb427fa779fcdb08bc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib582.c @@ -0,0 +1,355 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +struct Sockets { + curl_socket_t *sockets; + int count; /* number of sockets actually stored in array */ + int max_count; /* max number of sockets that fit in allocated array */ +}; + +struct ReadWriteSockets { + struct Sockets read, write; +}; + +/** + * Remove a file descriptor from a sockets array. + */ +static void removeFd(struct Sockets *sockets, curl_socket_t fd, int mention) +{ + int i; + + if(mention) + fprintf(stderr, "Remove socket fd %d\n", (int) fd); + + for(i = 0; i < sockets->count; ++i) { + if(sockets->sockets[i] == fd) { + if(i < sockets->count - 1) + memmove(&sockets->sockets[i], &sockets->sockets[i + 1], + sizeof(curl_socket_t) * (sockets->count - (i + 1))); + --sockets->count; + } + } +} + +/** + * Add a file descriptor to a sockets array. + */ +static void addFd(struct Sockets *sockets, curl_socket_t fd, const char *what) +{ + /** + * To ensure we only have each file descriptor once, we remove it then add + * it again. + */ + fprintf(stderr, "Add socket fd %d for %s\n", (int) fd, what); + removeFd(sockets, fd, 0); + /* + * Allocate array storage when required. + */ + if(!sockets->sockets) { + sockets->sockets = malloc(sizeof(curl_socket_t) * 20U); + if(!sockets->sockets) + return; + sockets->max_count = 20; + } + else if(sockets->count >= sockets->max_count) { + /* this can't happen in normal cases */ + fprintf(stderr, "too many file handles error\n"); + exit(2); + } + /* + * Add file descriptor to array. + */ + sockets->sockets[sockets->count] = fd; + ++sockets->count; +} + +/** + * Callback invoked by curl to poll reading / writing of a socket. + */ +static int curlSocketCallback(CURL *easy, curl_socket_t s, int action, + void *userp, void *socketp) +{ + struct ReadWriteSockets *sockets = userp; + + (void)easy; /* unused */ + (void)socketp; /* unused */ + + if(action == CURL_POLL_IN || action == CURL_POLL_INOUT) + addFd(&sockets->read, s, "read"); + + if(action == CURL_POLL_OUT || action == CURL_POLL_INOUT) + addFd(&sockets->write, s, "write"); + + if(action == CURL_POLL_REMOVE) { + removeFd(&sockets->read, s, 1); + removeFd(&sockets->write, s, 0); + } + + return 0; +} + +/** + * Callback invoked by curl to set a timeout. + */ +static int curlTimerCallback(CURLM *multi, long timeout_ms, void *userp) +{ + struct timeval *timeout = userp; + + (void)multi; /* unused */ + if(timeout_ms != -1) { + *timeout = tutil_tvnow(); + timeout->tv_usec += (int)timeout_ms * 1000; + } + else { + timeout->tv_sec = -1; + } + return 0; +} + +/** + * Check for curl completion. + */ +static int checkForCompletion(CURLM *curl, int *success) +{ + int result = 0; + *success = 0; + while(1) { + int numMessages; + CURLMsg *message = curl_multi_info_read(curl, &numMessages); + if(!message) + break; + if(message->msg == CURLMSG_DONE) { + result = 1; + if(message->data.result == CURLE_OK) + *success = 1; + else + *success = 0; + } + else { + fprintf(stderr, "Got an unexpected message from curl: %i\n", + (int)message->msg); + result = 1; + *success = 0; + } + } + return result; +} + +static int getMicroSecondTimeout(struct timeval *timeout) +{ + struct timeval now; + ssize_t result; + now = tutil_tvnow(); + result = (ssize_t)((timeout->tv_sec - now.tv_sec) * 1000000 + + timeout->tv_usec - now.tv_usec); + if(result < 0) + result = 0; + + return curlx_sztosi(result); +} + +/** + * Update a fd_set with all of the sockets in use. + */ +static void updateFdSet(struct Sockets *sockets, fd_set* fdset, + curl_socket_t *maxFd) +{ + int i; + for(i = 0; i < sockets->count; ++i) { + FD_SET(sockets->sockets[i], fdset); + if(*maxFd < sockets->sockets[i] + 1) { + *maxFd = sockets->sockets[i] + 1; + } + } +} + +static void notifyCurl(CURLM *curl, curl_socket_t s, int evBitmask, + const char *info) +{ + int numhandles = 0; + CURLMcode result = curl_multi_socket_action(curl, s, evBitmask, &numhandles); + if(result != CURLM_OK) { + fprintf(stderr, "Curl error on %s: %i (%s)\n", + info, result, curl_multi_strerror(result)); + } +} + +/** + * Invoke curl when a file descriptor is set. + */ +static void checkFdSet(CURLM *curl, struct Sockets *sockets, fd_set *fdset, + int evBitmask, const char *name) +{ + int i; + for(i = 0; i < sockets->count; ++i) { + if(FD_ISSET(sockets->sockets[i], fdset)) { + notifyCurl(curl, sockets->sockets[i], evBitmask, name); + } + } +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURL *curl = NULL; + FILE *hd_src = NULL; + int hd; + struct_stat file_info; + CURLM *m = NULL; + struct ReadWriteSockets sockets = {{NULL, 0, 0}, {NULL, 0, 0}}; + struct timeval timeout = {-1, 0}; + int success = 0; + + assert(test_argc >= 5); + + start_test_timing(); + + if(!libtest_arg3) { + fprintf(stderr, "Usage: lib582 [url] [filename] [username]\n"); + return TEST_ERR_USAGE; + } + + hd_src = fopen(libtest_arg2, "rb"); + if(!hd_src) { + fprintf(stderr, "fopen() failed with error: %d (%s)\n", + errno, strerror(errno)); + fprintf(stderr, "Error opening file: (%s)\n", libtest_arg2); + return TEST_ERR_FOPEN; + } + + /* get the file size of the local file */ + hd = fstat(fileno(hd_src), &file_info); + if(hd == -1) { + /* can't open file, bail out */ + fprintf(stderr, "fstat() failed with error: %d (%s)\n", + errno, strerror(errno)); + fprintf(stderr, "ERROR: cannot open file (%s)\n", libtest_arg2); + fclose(hd_src); + return TEST_ERR_FSTAT; + } + fprintf(stderr, "Set to upload %d bytes\n", (int)file_info.st_size); + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + fclose(hd_src); + return res; + } + + easy_init(curl); + + /* enable uploading */ + easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target */ + easy_setopt(curl, CURLOPT_URL, URL); + + /* go verbose */ + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* now specify which file to upload */ + easy_setopt(curl, CURLOPT_READDATA, hd_src); + + easy_setopt(curl, CURLOPT_USERPWD, libtest_arg3); + easy_setopt(curl, CURLOPT_SSH_PUBLIC_KEYFILE, test_argv[4]); + easy_setopt(curl, CURLOPT_SSH_PRIVATE_KEYFILE, test_argv[5]); + easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size); + + multi_init(m); + + multi_setopt(m, CURLMOPT_SOCKETFUNCTION, curlSocketCallback); + multi_setopt(m, CURLMOPT_SOCKETDATA, &sockets); + + multi_setopt(m, CURLMOPT_TIMERFUNCTION, curlTimerCallback); + multi_setopt(m, CURLMOPT_TIMERDATA, &timeout); + + multi_add_handle(m, curl); + + while(!checkForCompletion(m, &success)) { + fd_set readSet, writeSet; + curl_socket_t maxFd = 0; + struct timeval tv = {10, 0}; + + FD_ZERO(&readSet); + FD_ZERO(&writeSet); + updateFdSet(&sockets.read, &readSet, &maxFd); + updateFdSet(&sockets.write, &writeSet, &maxFd); + + if(timeout.tv_sec != -1) { + int usTimeout = getMicroSecondTimeout(&timeout); + tv.tv_sec = usTimeout / 1000000; + tv.tv_usec = usTimeout % 1000000; + } + else if(maxFd <= 0) { + tv.tv_sec = 0; + tv.tv_usec = 100000; + } + + select_test((int)maxFd, &readSet, &writeSet, NULL, &tv); + + /* Check the sockets for reading / writing */ + checkFdSet(m, &sockets.read, &readSet, CURL_CSELECT_IN, "read"); + checkFdSet(m, &sockets.write, &writeSet, CURL_CSELECT_OUT, "write"); + + if(timeout.tv_sec != -1 && getMicroSecondTimeout(&timeout) == 0) { + /* Curl's timer has elapsed. */ + notifyCurl(m, CURL_SOCKET_TIMEOUT, 0, "timeout"); + } + + abort_on_test_timeout(); + } + + if(!success) { + fprintf(stderr, "Error uploading file.\n"); + res = TEST_ERR_MAJOR_BAD; + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + curl_multi_remove_handle(m, curl); + curl_easy_cleanup(curl); + curl_multi_cleanup(m); + curl_global_cleanup(); + + /* close the local file */ + fclose(hd_src); + + /* free local memory */ + free(sockets.read.sockets); + free(sockets.write.sockets); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib583.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib583.c new file mode 100644 index 0000000000000000000000000000000000000000..0ccf5c65a6fe674bdda1a1af92288d5f36d515fe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib583.c @@ -0,0 +1,91 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 test case is based on the sample code provided by Saqib Ali + * https://curl.se/mail/lib-2011-03/0066.html + */ + +#include "test.h" + +#include + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + int stillRunning; + CURLM *multiHandle = NULL; + CURL *curl = NULL; + CURLcode res = CURLE_OK; + CURLMcode mres; + + assert(test_argc >= 4); + + global_init(CURL_GLOBAL_ALL); + + multi_init(multiHandle); + + easy_init(curl); + + easy_setopt(curl, CURLOPT_USERPWD, libtest_arg2); + easy_setopt(curl, CURLOPT_SSH_PUBLIC_KEYFILE, test_argv[3]); + easy_setopt(curl, CURLOPT_SSH_PRIVATE_KEYFILE, test_argv[4]); + + easy_setopt(curl, CURLOPT_UPLOAD, 1L); + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_INFILESIZE, (long)5); + + multi_add_handle(multiHandle, curl); + + /* this tests if removing an easy handle immediately after multi + perform has been called succeeds or not. */ + + fprintf(stderr, "curl_multi_perform()...\n"); + + multi_perform(multiHandle, &stillRunning); + + fprintf(stderr, "curl_multi_perform() succeeded\n"); + + fprintf(stderr, "curl_multi_remove_handle()...\n"); + mres = curl_multi_remove_handle(multiHandle, curl); + if(mres) { + fprintf(stderr, "curl_multi_remove_handle() failed, " + "with code %d\n", (int)mres); + res = TEST_ERR_MULTI; + } + else + fprintf(stderr, "curl_multi_remove_handle() succeeded\n"); + +test_cleanup: + + /* undocumented cleanup sequence - type UB */ + + curl_easy_cleanup(curl); + curl_multi_cleanup(multiHandle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib586.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib586.c new file mode 100644 index 0000000000000000000000000000000000000000..c6d9f7d7f178dca59428623a335b7d9e8f24ade1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib586.c @@ -0,0 +1,246 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "memdebug.h" + +#define THREADS 2 + +/* struct containing data of a thread */ +struct Tdata { + CURLSH *share; + char *url; +}; + +struct userdata { + const char *text; + int counter; +}; + +/* lock callback */ +static void test_lock(CURL *handle, curl_lock_data data, + curl_lock_access laccess, void *useptr) +{ + const char *what; + struct userdata *user = (struct userdata *)useptr; + + (void)handle; + (void)laccess; + + switch(data) { + case CURL_LOCK_DATA_SHARE: + what = "share"; + break; + case CURL_LOCK_DATA_DNS: + what = "dns"; + break; + case CURL_LOCK_DATA_COOKIE: + what = "cookie"; + break; + case CURL_LOCK_DATA_SSL_SESSION: + what = "ssl_session"; + break; + default: + fprintf(stderr, "lock: no such data: %d\n", (int)data); + return; + } + printf("lock: %-6s [%s]: %d\n", what, user->text, user->counter); + user->counter++; +} + +/* unlock callback */ +static void test_unlock(CURL *handle, curl_lock_data data, void *useptr) +{ + const char *what; + struct userdata *user = (struct userdata *)useptr; + (void)handle; + switch(data) { + case CURL_LOCK_DATA_SHARE: + what = "share"; + break; + case CURL_LOCK_DATA_DNS: + what = "dns"; + break; + case CURL_LOCK_DATA_COOKIE: + what = "cookie"; + break; + case CURL_LOCK_DATA_SSL_SESSION: + what = "ssl_session"; + break; + default: + fprintf(stderr, "unlock: no such data: %d\n", (int)data); + return; + } + printf("unlock: %-6s [%s]: %d\n", what, user->text, user->counter); + user->counter++; +} + +/* the dummy thread function */ +static void *test_fire(void *ptr) +{ + CURLcode code; + struct Tdata *tdata = (struct Tdata*)ptr; + CURL *curl; + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + return NULL; + } + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_URL, tdata->url); + printf("CURLOPT_SHARE\n"); + curl_easy_setopt(curl, CURLOPT_SHARE, tdata->share); + + printf("PERFORM\n"); + code = curl_easy_perform(curl); + if(code != CURLE_OK) { + int i = 0; + fprintf(stderr, "perform url '%s' repeat %d failed, curlcode %d\n", + tdata->url, i, (int)code); + } + + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + + return NULL; +} + +/* test function */ +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + CURLSHcode scode = CURLSHE_OK; + char *url; + struct Tdata tdata; + CURL *curl; + CURLSH *share; + int i; + struct userdata user; + + user.text = "Pigs in space"; + user.counter = 0; + + printf("GLOBAL_INIT\n"); + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* prepare share */ + printf("SHARE_INIT\n"); + share = curl_share_init(); + if(!share) { + fprintf(stderr, "curl_share_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_LOCKFUNC\n"); + scode = curl_share_setopt(share, CURLSHOPT_LOCKFUNC, test_lock); + } + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_UNLOCKFUNC\n"); + scode = curl_share_setopt(share, CURLSHOPT_UNLOCKFUNC, test_unlock); + } + if(CURLSHE_OK == scode) { + printf("CURLSHOPT_USERDATA\n"); + scode = curl_share_setopt(share, CURLSHOPT_USERDATA, &user); + } + if(CURLSHE_OK == scode) { + printf("CURL_LOCK_DATA_SSL_SESSION\n"); + scode = curl_share_setopt(share, CURLSHOPT_SHARE, + CURL_LOCK_DATA_SSL_SESSION); + } + + if(CURLSHE_OK != scode) { + fprintf(stderr, "curl_share_setopt() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + + /* start treads */ + for(i = 1; i <= THREADS; i++) { + + /* set thread data */ + tdata.url = URL; + tdata.share = share; + + /* simulate thread, direct call of "thread" function */ + printf("*** run %d\n",i); + test_fire(&tdata); + } + + + /* fetch another one */ + printf("*** run %d\n", i); + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_share_cleanup(share); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + url = URL; + test_setopt(curl, CURLOPT_URL, url); + printf("CURLOPT_SHARE\n"); + test_setopt(curl, CURLOPT_SHARE, share); + + printf("PERFORM\n"); + res = curl_easy_perform(curl); + + /* try to free share, expect to fail because share is in use */ + printf("try SHARE_CLEANUP...\n"); + scode = curl_share_cleanup(share); + if(scode == CURLSHE_OK) { + fprintf(stderr, "curl_share_cleanup succeed but error expected\n"); + share = NULL; + } + else { + printf("SHARE_CLEANUP failed, correct\n"); + } + +test_cleanup: + + /* clean up last handle */ + printf("CLEANUP\n"); + curl_easy_cleanup(curl); + + /* free share */ + printf("SHARE_CLEANUP\n"); + scode = curl_share_cleanup(share); + if(scode != CURLSHE_OK) + fprintf(stderr, "curl_share_cleanup failed, code errno %d\n", + (int)scode); + + printf("GLOBAL_CLEANUP\n"); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib589.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib589.c new file mode 100644 index 0000000000000000000000000000000000000000..eb800f8574edc1da5661d96fa7af9824b7d91163 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib589.c @@ -0,0 +1,76 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */ + test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */ + +#ifdef LIB584 + { + curl_mime *mime = curl_mime_init(curl); + curl_mimepart *part = curl_mime_addpart(mime); + curl_mime_name(part, "fake"); + curl_mime_data(part, "party", 5); + test_setopt(curl, CURLOPT_MIMEPOST, mime); + res = curl_easy_perform(curl); + curl_mime_free(mime); + if(res) + goto test_cleanup; + } +#endif + + test_setopt(curl, CURLOPT_MIMEPOST, NULL); + + /* Now, we should be making a zero byte POST request */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib590.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib590.c new file mode 100644 index 0000000000000000000000000000000000000000..cda3b029e34701681cda1030f337a7995f5dba15 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib590.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 "test.h" + +/* + Based on a bug report recipe by Rene Bernhardt in + https://curl.se/mail/lib-2011-10/0323.html + + It is reproducible by the following steps: + + - Use a proxy that offers NTLM and Negotiate ( CURLOPT_PROXY and + CURLOPT_PROXYPORT) + - Tell libcurl NOT to use Negotiate CURL_EASY_SETOPT(CURLOPT_PROXYAUTH, + CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM) + - Start the request +*/ + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_PROXYAUTH, + (long) (CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM)); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); /* set in first.c */ + test_setopt(curl, CURLOPT_PROXYUSERPWD, "me:password"); + + res = curl_easy_perform(curl); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib591.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib591.c new file mode 100644 index 0000000000000000000000000000000000000000..742baf2022dd065ad7a39e7b8042b1b0d7d3416b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib591.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 "test.h" + +/* lib591 is used for test cases 591, 592, 593 and 594 */ + +#include + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURLM *multi = NULL; + CURLcode res = CURLE_OK; + int running; + int msgs_left; + CURLMsg *msg; + FILE *upload = NULL; + + start_test_timing(); + + upload = fopen(libtest_arg3, "rb"); + if(!upload) { + fprintf(stderr, "fopen() failed with error: %d (%s)\n", + errno, strerror(errno)); + fprintf(stderr, "Error opening file: (%s)\n", libtest_arg3); + return TEST_ERR_FOPEN; + } + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + fclose(upload); + return res; + } + + easy_init(easy); + + /* go verbose */ + easy_setopt(easy, CURLOPT_VERBOSE, 1L); + + /* specify target */ + easy_setopt(easy, CURLOPT_URL, URL); + + /* enable uploading */ + easy_setopt(easy, CURLOPT_UPLOAD, 1L); + + /* data pointer for the file read function */ + easy_setopt(easy, CURLOPT_READDATA, upload); + + /* use active mode FTP */ + easy_setopt(easy, CURLOPT_FTPPORT, "-"); + + /* server connection timeout */ + easy_setopt(easy, CURLOPT_ACCEPTTIMEOUT_MS, + strtol(libtest_arg2, NULL, 10)*1000); + + multi_init(multi); + + multi_add_handle(multi, easy); + + for(;;) { + struct timeval interval; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + long timeout = -99; + int maxfd = -99; + + multi_perform(multi, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + multi_timeout(multi, &timeout); + + /* At this point, timeout is guaranteed to be greater or equal than -1. */ + + if(timeout != -1L) { + int itimeout; +#if LONG_MAX > INT_MAX + itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; +#else + itimeout = (int)timeout; +#endif + interval.tv_sec = itimeout/1000; + interval.tv_usec = (itimeout%1000)*1000; + } + else { + interval.tv_sec = 0; + interval.tv_usec = 100000L; /* 100 ms */ + } + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &interval); + + abort_on_test_timeout(); + } + + msg = curl_multi_info_read(multi, &msgs_left); + if(msg) + res = msg->data.result; + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi); + curl_easy_cleanup(easy); + curl_global_cleanup(); + + /* close the local file */ + fclose(upload); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib597.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib597.c new file mode 100644 index 0000000000000000000000000000000000000000..71535b041d3c2e17330dcd7e38418fc658414995 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib597.c @@ -0,0 +1,133 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Test case for below scenario: + * - Connect to an FTP server using CONNECT_ONLY option + * + * The test case originated for verifying CONNECT_ONLY option shall not + * block after protocol connect is done, but it returns the message + * with function curl_multi_info_read(). + */ + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURLM *multi = NULL; + CURLcode res = CURLE_OK; + int running; + int msgs_left; + CURLMsg *msg; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(easy); + + multi_init(multi); + + /* go verbose */ + easy_setopt(easy, CURLOPT_VERBOSE, 1L); + + /* specify target */ + easy_setopt(easy, CURLOPT_URL, URL); + + easy_setopt(easy, CURLOPT_CONNECT_ONLY, 1L); + + multi_add_handle(multi, easy); + + for(;;) { + struct timeval interval; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + long timeout = -99; + int maxfd = -99; + + multi_perform(multi, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + multi_timeout(multi, &timeout); + + /* At this point, timeout is guaranteed to be greater or equal than + -1. */ + + if(timeout != -1L) { + int itimeout; +#if LONG_MAX > INT_MAX + itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; +#else + itimeout = (int)timeout; +#endif + interval.tv_sec = itimeout/1000; + interval.tv_usec = (itimeout%1000)*1000; + } + else { + interval.tv_sec = TEST_HANG_TIMEOUT/1000 - 1; + interval.tv_usec = 0; + } + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &interval); + + abort_on_test_timeout(); + } + + msg = curl_multi_info_read(multi, &msgs_left); + if(msg) + res = msg->data.result; + + multi_remove_handle(multi, easy); + +test_cleanup: + + /* undocumented cleanup sequence - type UA */ + + curl_multi_cleanup(multi); + curl_easy_cleanup(easy); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib598.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib598.c new file mode 100644 index 0000000000000000000000000000000000000000..8c67076b495d1c50e022023803b7d401e97f2763 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib598.c @@ -0,0 +1,74 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_REFERER, "http://example.com/the-moo"); + test_setopt(curl, CURLOPT_USERAGENT, "the-moo agent next generation"); + test_setopt(curl, CURLOPT_COOKIE, "name=moo"); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "retrieve 1 failed\n"); + goto test_cleanup; + } + + curl_easy_reset(curl); + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + if(res) + fprintf(stderr, "retrieve 2 failed\n"); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib599.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib599.c new file mode 100644 index 0000000000000000000000000000000000000000..391b9f2d54d9bd87d8ccb2f7b2f8f3a3700a9a99 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib599.c @@ -0,0 +1,103 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static int progress_callback(void *clientp, double dltotal, + double dlnow, double ultotal, double ulnow) +{ + (void)clientp; + (void)ulnow; + (void)ultotal; + + if((dltotal > 0.0) && (dlnow > dltotal)) { + /* this should not happen with test case 599 */ + printf("%.0f > %.0f !!\n", dltotal, dlnow); + return -1; + } + + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + double content_length = 0.0; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* we want to use our own progress function */ + test_setopt(curl, CURLOPT_NOPROGRESS, 0L); + CURL_IGNORE_DEPRECATION( + test_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); + ) + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* follow redirects */ + test_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + + if(!res) { + FILE *moo; + CURL_IGNORE_DEPRECATION( + res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, + &content_length); + ) + moo = fopen(libtest_arg2, "wb"); + if(moo) { + fprintf(moo, "CL %.0f\n", content_length); + fclose(moo); + } + } + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib643.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib643.c new file mode 100644 index 0000000000000000000000000000000000000000..bd7f5e0f8c1c53b5b0f2199f34e035c400cbf268 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib643.c @@ -0,0 +1,269 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]= + "dummy\n"; + +struct WriteThis { + char *readptr; + curl_off_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + int eof = !*pooh->readptr; + + if(size*nmemb < 1) + return 0; + +#ifndef LIB645 + eof = pooh->sizeleft <= 0; + if(!eof) + pooh->sizeleft--; +#endif + + if(!eof) { + *ptr = *pooh->readptr; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +} + +static CURLcode test_once(char *URL, bool oldstyle) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl_mime *mime = NULL; + curl_mimepart *part = NULL; + struct WriteThis pooh; + struct WriteThis pooh2; + curl_off_t datasize = -1; + + pooh.readptr = testdata; +#ifndef LIB645 + datasize = (curl_off_t)strlen(testdata); +#endif + pooh.sizeleft = datasize; + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + mime = curl_mime_init(curl); + if(!mime) { + fprintf(stderr, "curl_mime_init() failed\n"); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart(1) failed\n"); + curl_mime_free(mime); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* Fill in the file upload part */ + if(oldstyle) { + res = curl_mime_name(part, "sendfile"); + if(!res) + res = curl_mime_data_cb(part, datasize, read_callback, + NULL, NULL, &pooh); + if(!res) + res = curl_mime_filename(part, "postit2.c"); + } + else { + /* new style */ + res = curl_mime_name(part, "sendfile alternative"); + if(!res) + res = curl_mime_data_cb(part, datasize, read_callback, + NULL, NULL, &pooh); + if(!res) + res = curl_mime_filename(part, "file name 2"); + } + + if(res) + printf("curl_mime_xxx(1) = %s\n", curl_easy_strerror(res)); + + /* Now add the same data with another name and make it not look like + a file upload but still using the callback */ + + pooh2.readptr = testdata; +#ifndef LIB645 + datasize = (curl_off_t)strlen(testdata); +#endif + pooh2.sizeleft = datasize; + + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart(2) failed\n"); + curl_mime_free(mime); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + /* Fill in the file upload part */ + res = curl_mime_name(part, "callbackdata"); + if(!res) + res = curl_mime_data_cb(part, datasize, read_callback, + NULL, NULL, &pooh2); + + if(res) + printf("curl_mime_xxx(2) = %s\n", curl_easy_strerror(res)); + + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart(3) failed\n"); + curl_mime_free(mime); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* Fill in the filename field */ + res = curl_mime_name(part, "filename"); + if(!res) + res = curl_mime_data(part, "postit2.c", + CURL_ZERO_TERMINATED); + + if(res) + printf("curl_mime_xxx(3) = %s\n", curl_easy_strerror(res)); + + /* Fill in a submit field too */ + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart(4) failed\n"); + curl_mime_free(mime); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + res = curl_mime_name(part, "submit"); + if(!res) + res = curl_mime_data(part, "send", + CURL_ZERO_TERMINATED); + + if(res) + printf("curl_mime_xxx(4) = %s\n", curl_easy_strerror(res)); + + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart(5) failed\n"); + curl_mime_free(mime); + curl_easy_cleanup(curl); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + res = curl_mime_name(part, "somename"); + if(!res) + res = curl_mime_filename(part, "somefile.txt"); + if(!res) + res = curl_mime_data(part, "blah blah", 9); + + if(res) + printf("curl_mime_xxx(5) = %s\n", curl_easy_strerror(res)); + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* send a multi-part mimepost */ + test_setopt(curl, CURLOPT_MIMEPOST, mime); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* now cleanup the mimepost structure */ + curl_mime_free(mime); + + return res; +} + +static CURLcode cyclic_add(void) +{ + CURL *easy = curl_easy_init(); + curl_mime *mime = curl_mime_init(easy); + curl_mimepart *part = curl_mime_addpart(mime); + CURLcode a1 = curl_mime_subparts(part, mime); + + if(a1 == CURLE_BAD_FUNCTION_ARGUMENT) { + curl_mime *submime = curl_mime_init(easy); + curl_mimepart *subpart = curl_mime_addpart(submime); + + curl_mime_subparts(part, submime); + a1 = curl_mime_subparts(subpart, mime); + } + + curl_mime_free(mime); + curl_easy_cleanup(easy); + if(a1 != CURLE_BAD_FUNCTION_ARGUMENT) + /* that should have failed */ + return (CURLcode)1; + + return CURLE_OK; +} + +CURLcode test(char *URL) +{ + CURLcode res; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + res = test_once(URL, TRUE); /* old */ + if(!res) + res = test_once(URL, FALSE); /* new */ + + if(!res) + res = cyclic_add(); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib650.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib650.c new file mode 100644 index 0000000000000000000000000000000000000000..f0d459e663bfc05070c5386d5700464a29cd9da9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib650.c @@ -0,0 +1,226 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[] = + "this is what we post to the silly web server"; + +static const char testname[] = "fieldname"; + + +/* This test attempts to use all form API features that are not + * used elsewhere. + */ + +/* curl_formget callback to count characters. */ +static size_t count_chars(void *userp, const char *buf, size_t len) +{ + size_t *pcounter = (size_t *) userp; + + (void) buf; + *pcounter += len; + return len; +} + + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = TEST_ERR_MAJOR_BAD; + CURLFORMcode formrc; + struct curl_slist *headers, *headers2 = NULL; + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + struct curl_forms formarray[3]; + size_t formlength = 0; + char flbuf[32]; + long contentlength = 0; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* Check proper name and data copying, as well as headers. */ + headers = curl_slist_append(NULL, "X-customheader-1: Header 1 data"); + if(!headers) { + goto test_cleanup; + } + headers2 = curl_slist_append(headers, "X-customheader-2: Header 2 data"); + if(!headers2) { + goto test_cleanup; + } + headers = headers2; + headers2 = curl_slist_append(headers, "Content-Type: text/plain"); + if(!headers2) { + goto test_cleanup; + } + headers = headers2; + CURL_IGNORE_DEPRECATION( + formrc = curl_formadd(&formpost, &lastptr, + CURLFORM_COPYNAME, &testname, + CURLFORM_COPYCONTENTS, &testdata, + CURLFORM_CONTENTHEADER, headers, + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(1) = %d\n", (int) formrc); + goto test_cleanup; + } + + contentlength = (long)(strlen(testdata) - 1); + + CURL_IGNORE_DEPRECATION( + /* Use a form array for the non-copy test. */ + formarray[0].option = CURLFORM_PTRCONTENTS; + formarray[0].value = testdata; + formarray[1].option = CURLFORM_CONTENTSLENGTH; + formarray[1].value = (char *)(size_t)contentlength; + formarray[2].option = CURLFORM_END; + formarray[2].value = NULL; + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_PTRNAME, testname, + CURLFORM_NAMELENGTH, strlen(testname) - 1, + CURLFORM_ARRAY, formarray, + CURLFORM_FILENAME, "remotefile.txt", + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(2) = %d\n", (int) formrc); + goto test_cleanup; + } + + /* Now change in-memory data to affect CURLOPT_PTRCONTENTS value. + Copied values (first field) must not be affected. + CURLOPT_PTRNAME actually copies the name thus we do not test this here. */ + testdata[0]++; + + CURL_IGNORE_DEPRECATION( + /* Check multi-files and content type propagation. */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "multifile", + CURLFORM_FILE, libtest_arg2, /* Set in first.c. */ + CURLFORM_FILE, libtest_arg2, + CURLFORM_CONTENTTYPE, "text/whatever", + CURLFORM_FILE, libtest_arg2, + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(3) = %d\n", (int) formrc); + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( + /* Check data from file content. */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "filecontents", + CURLFORM_FILECONTENT, libtest_arg2, + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(4) = %d\n", (int) formrc); + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( + /* Measure the current form length. + * This is done before including stdin data because we want to reuse it + * and stdin cannot be rewound. + */ + curl_formget(formpost, (void *) &formlength, count_chars); + ) + + /* Include length in data for external check. */ + curl_msnprintf(flbuf, sizeof(flbuf), "%lu", (unsigned long) formlength); + CURL_IGNORE_DEPRECATION( + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "formlength", + CURLFORM_COPYCONTENTS, &flbuf, + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(5) = %d\n", (int) formrc); + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( + /* Check stdin (may be problematic on some platforms). */ + formrc = curl_formadd(&formpost, + &lastptr, + CURLFORM_COPYNAME, "standardinput", + CURLFORM_FILE, "-", + CURLFORM_END); + ) + if(formrc) { + printf("curl_formadd(6) = %d\n", (int) formrc); + goto test_cleanup; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + goto test_cleanup; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + CURL_IGNORE_DEPRECATION( + /* send a multi-part formpost */ + test_setopt(curl, CURLOPT_HTTPPOST, formpost); + ) + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + test_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + test_setopt(curl, CURLOPT_POSTREDIR, (long)CURL_REDIR_POST_301); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + + CURL_IGNORE_DEPRECATION( + /* now cleanup the formpost chain */ + curl_formfree(formpost); + ) + curl_slist_free_all(headers); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib651.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib651.c new file mode 100644 index 0000000000000000000000000000000000000000..7fb97def86501ac3f013c47a5c3a19e576a2b98f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib651.c @@ -0,0 +1,103 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testbuf[17000]; /* more than 16K */ + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + CURLFORMcode formrc; + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; + + /* create a buffer with AAAA...BBBBB...CCCC...etc */ + int i; + int size = (int)sizeof(testbuf)/1000; + + for(i = 0; i < size ; i++) + memset(&testbuf[i * 1000], 65 + i, 1000); + + testbuf[sizeof(testbuf)-1] = 0; /* null-terminate */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + CURL_IGNORE_DEPRECATION( + /* Check proper name and data copying. */ + formrc = curl_formadd(&formpost, &lastptr, + CURLFORM_COPYNAME, "hello", + CURLFORM_COPYCONTENTS, testbuf, + CURLFORM_END); + ) + if(formrc) + printf("curl_formadd(1) = %d\n", (int) formrc); + + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + CURL_IGNORE_DEPRECATION( + curl_formfree(formpost); + ) + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + /* First set the URL that is about to receive our POST. */ + test_setopt(curl, CURLOPT_URL, URL); + + CURL_IGNORE_DEPRECATION( + /* send a multi-part formpost */ + test_setopt(curl, CURLOPT_HTTPPOST, formpost); + ) + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + + CURL_IGNORE_DEPRECATION( + /* now cleanup the formpost chain */ + curl_formfree(formpost); + ) + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib652.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib652.c new file mode 100644 index 0000000000000000000000000000000000000000..591aa7269a31addb8d8383c9a91e399ef091805c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib652.c @@ -0,0 +1,133 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testbuf[17000]; /* more than 16K */ + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_OK; + curl_mime *mime = NULL; + curl_mimepart *part; + struct curl_slist *recipients = NULL; + + /* create a testbuf with AAAA...BBBBB...CCCC...etc */ + int i; + int size = (int)sizeof(testbuf) / 10; + + for(i = 0; i < size ; i++) + memset(&testbuf[i * 10], 65 + (i % 26), 10); + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + /* Build mime structure. */ + mime = curl_mime_init(curl); + if(!mime) { + fprintf(stderr, "curl_mime_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + res = curl_mime_filename(part, "myfile.jpg"); + if(res) { + fprintf(stderr, "curl_mime_filename() failed\n"); + goto test_cleanup; + } + res = curl_mime_type(part, "image/jpeg"); + if(res) { + fprintf(stderr, "curl_mime_type() failed\n"); + goto test_cleanup; + } + res = curl_mime_data(part, testbuf, sizeof(testbuf)); + if(res) { + fprintf(stderr, "curl_mime_data() failed\n"); + goto test_cleanup; + } + res = curl_mime_encoder(part, "base64"); + if(res) { + fprintf(stderr, "curl_mime_encoder() failed\n"); + goto test_cleanup; + } + + /* Prepare recipients. */ + recipients = curl_slist_append(NULL, "someone@example.com"); + if(!recipients) { + fprintf(stderr, "curl_slist_append() failed\n"); + goto test_cleanup; + } + + /* First set the URL that is about to receive our mime mail. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Set sender. */ + test_setopt(curl, CURLOPT_MAIL_FROM, "somebody@example.com"); + + /* Set recipients. */ + test_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + /* send a multi-part mail */ + test_setopt(curl, CURLOPT_MIMEPOST, mime); + + /* Shorten upload buffer. */ + test_setopt(curl, CURLOPT_UPLOAD_BUFFERSIZE, 16411L); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* now cleanup the mime structure */ + curl_mime_free(mime); + + /* cleanup the recipients. */ + curl_slist_free_all(recipients); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib653.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib653.c new file mode 100644 index 0000000000000000000000000000000000000000..a1be0df1606a1f815bbc463b5ed81808dd1f435b --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib653.c @@ -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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + + +CURLcode test(char *URL) +{ + CURL *curls = NULL; + CURLcode res = CURLE_OK; + curl_mimepart *field = NULL; + curl_mime *mime = NULL; + + global_init(CURL_GLOBAL_ALL); + easy_init(curls); + + mime = curl_mime_init(curls); + field = curl_mime_addpart(mime); + curl_mime_name(field, "name"); + curl_mime_data(field, "short value", CURL_ZERO_TERMINATED); + + easy_setopt(curls, CURLOPT_URL, URL); + easy_setopt(curls, CURLOPT_HEADER, 1L); + easy_setopt(curls, CURLOPT_VERBOSE, 1L); + easy_setopt(curls, CURLOPT_MIMEPOST, mime); + easy_setopt(curls, CURLOPT_NOPROGRESS, 1L); + + res = curl_easy_perform(curls); + if(res) + goto test_cleanup; + + /* Alter form and resubmit. */ + curl_mime_data(field, "long value for length change", CURL_ZERO_TERMINATED); + res = curl_easy_perform(curls); + +test_cleanup: + curl_mime_free(mime); + curl_easy_cleanup(curls); + curl_global_cleanup(); + return res; /* return the final return code */ +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib654.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib654.c new file mode 100644 index 0000000000000000000000000000000000000000..66ec29d17c69f779c158abc5f4432e00371acf9a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib654.c @@ -0,0 +1,166 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]= + "dummy\n"; + +struct WriteThis { + char *readptr; + curl_off_t sizeleft; + int freecount; +}; + +static void free_callback(void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *) userp; + + pooh->freecount++; +} + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + int eof = !*pooh->readptr; + + if(size*nmemb < 1) + return 0; + + eof = pooh->sizeleft <= 0; + if(!eof) + pooh->sizeleft--; + + if(!eof) { + *ptr = *pooh->readptr; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + CURL *easy2 = NULL; + curl_mime *mime = NULL; + curl_mimepart *part; + struct curl_slist *hdrs = NULL; + CURLcode res = TEST_ERR_FAILURE; + struct WriteThis pooh; + + /* + * Check proper copy/release of mime post data bound to a duplicated + * easy handle. + */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + easy = curl_easy_init(); + + /* First set the URL that is about to receive our POST. */ + test_setopt(easy, CURLOPT_URL, URL); + + /* get verbose debug output please */ + test_setopt(easy, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(easy, CURLOPT_HEADER, 1L); + + /* Prepare the callback structure. */ + pooh.readptr = testdata; + pooh.sizeleft = (curl_off_t) strlen(testdata); + pooh.freecount = 0; + + /* Build the mime tree. */ + mime = curl_mime_init(easy); + part = curl_mime_addpart(mime); + curl_mime_data(part, "hello", CURL_ZERO_TERMINATED); + curl_mime_name(part, "greeting"); + curl_mime_type(part, "application/X-Greeting"); + curl_mime_encoder(part, "base64"); + hdrs = curl_slist_append(hdrs, "X-Test-Number: 654"); + curl_mime_headers(part, hdrs, TRUE); + part = curl_mime_addpart(mime); + curl_mime_filedata(part, libtest_arg2); + part = curl_mime_addpart(mime); + curl_mime_data_cb(part, (curl_off_t) -1, read_callback, NULL, free_callback, + &pooh); + + /* Bind mime data to its easy handle. */ + test_setopt(easy, CURLOPT_MIMEPOST, mime); + + /* Duplicate the handle. */ + easy2 = curl_easy_duphandle(easy); + if(!easy2) { + fprintf(stderr, "curl_easy_duphandle() failed\n"); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + + /* Now free the mime structure: it should unbind it from the first + easy handle. */ + curl_mime_free(mime); + mime = NULL; /* Already cleaned up. */ + + /* Perform on the first handle: should not send any data. */ + res = curl_easy_perform(easy); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform(original) failed\n"); + goto test_cleanup; + } + + /* Perform on the second handle: if the bound mime structure has not been + duplicated properly, it should cause a valgrind error. */ + res = curl_easy_perform(easy2); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform(duplicated) failed\n"); + goto test_cleanup; + } + + /* Free the duplicated handle: it should call free_callback again. + If the mime copy was bad or not automatically released, valgrind + will signal it. */ + curl_easy_cleanup(easy2); + easy2 = NULL; /* Already cleaned up. */ + + if(pooh.freecount != 2) { + fprintf(stderr, "free_callback() called %d times instead of 2\n", + pooh.freecount); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + +test_cleanup: + curl_easy_cleanup(easy); + curl_easy_cleanup(easy2); + curl_mime_free(mime); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib655.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib655.c new file mode 100644 index 0000000000000000000000000000000000000000..79654cb0784206815be97d27ee32dfd8427a7769 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib655.c @@ -0,0 +1,114 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static const char *TEST_DATA_STRING = "Test data"; +static int cb_count = 0; + +static int +resolver_alloc_cb_fail(void *resolver_state, void *reserved, void *userdata) +{ + (void)resolver_state; + (void)reserved; + + cb_count++; + if(strcmp(userdata, TEST_DATA_STRING)) { + fprintf(stderr, "Invalid test data received"); + exit(1); + } + + return 1; +} + +static int +resolver_alloc_cb_pass(void *resolver_state, void *reserved, void *userdata) +{ + (void)resolver_state; + (void)reserved; + + cb_count++; + if(strcmp(userdata, TEST_DATA_STRING)) { + fprintf(stderr, "Invalid test data received"); + exit(1); + } + + return 0; +} + +CURLcode test(char *URL) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + /* First set the URL that is about to receive our request. */ + test_setopt(curl, CURLOPT_URL, URL); + + test_setopt(curl, CURLOPT_RESOLVER_START_DATA, TEST_DATA_STRING); + test_setopt(curl, CURLOPT_RESOLVER_START_FUNCTION, resolver_alloc_cb_fail); + + /* this should fail */ + res = curl_easy_perform(curl); + if(res != CURLE_COULDNT_RESOLVE_HOST) { + fprintf(stderr, "curl_easy_perform should have returned " + "CURLE_COULDNT_RESOLVE_HOST but instead returned error %d\n", res); + if(res == CURLE_OK) + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_RESOLVER_START_FUNCTION, resolver_alloc_cb_pass); + + /* this should succeed */ + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "curl_easy_perform failed.\n"); + goto test_cleanup; + } + + if(cb_count != 2) { + fprintf(stderr, "Unexpected number of callbacks: %d\n", cb_count); + res = TEST_ERR_FAILURE; + goto test_cleanup; + } + +test_cleanup: + /* always cleanup */ + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib658.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib658.c new file mode 100644 index 0000000000000000000000000000000000000000..59d947e23744f38364a9f38896583ee39821725f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib658.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +/* + * Get a single URL without select(). + */ + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURLcode res = CURLE_OK; + CURLU *urlp = NULL; + CURLUcode uc = CURLUE_OK; + + global_init(CURL_GLOBAL_ALL); + easy_init(handle); + + urlp = curl_url(); + + if(!urlp) { + fprintf(stderr, "problem init URL api."); + goto test_cleanup; + } + + uc = curl_url_set(urlp, CURLUPART_URL, URL, 0); + if(uc) { + fprintf(stderr, "problem setting CURLUPART_URL: %s.", + curl_url_strerror(uc)); + goto test_cleanup; + } + + /* demonstrate override behavior */ + easy_setopt(handle, CURLOPT_URL, "http://www.example.com"); + + easy_setopt(handle, CURLOPT_CURLU, urlp); + easy_setopt(handle, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(handle); + + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + +test_cleanup: + + curl_url_cleanup(urlp); + curl_easy_cleanup(handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib659.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib659.c new file mode 100644 index 0000000000000000000000000000000000000000..bdd879b02b7eecf9b185df423cc3d4a6fadbc1e1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib659.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +/* + * Get a single URL without select(). + */ + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURLcode res = CURLE_OK; + CURLU *urlp = NULL; + + global_init(CURL_GLOBAL_ALL); + easy_init(handle); + + urlp = curl_url(); + + if(!urlp) { + fprintf(stderr, "problem init URL api."); + goto test_cleanup; + } + + /* this doesn't set the PATH part */ + if(curl_url_set(urlp, CURLUPART_HOST, "www.example.com", 0) || + curl_url_set(urlp, CURLUPART_SCHEME, "http", 0) || + curl_url_set(urlp, CURLUPART_PORT, "80", 0)) { + fprintf(stderr, "problem setting CURLUPART"); + goto test_cleanup; + } + + easy_setopt(handle, CURLOPT_CURLU, urlp); + easy_setopt(handle, CURLOPT_VERBOSE, 1L); + easy_setopt(handle, CURLOPT_PROXY, URL); + + res = curl_easy_perform(handle); + + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + +test_cleanup: + + curl_url_cleanup(urlp); + curl_easy_cleanup(handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib661.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib661.c new file mode 100644 index 0000000000000000000000000000000000000000..10df4988854f64feafae4c6c4431af4b1d4980de --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib661.c @@ -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 + * + ***************************************************************************/ +#include "test.h" +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl = NULL; + char *newURL = NULL; + struct curl_slist *slist = NULL; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + /* test: CURLFTPMETHOD_SINGLECWD with absolute path should + skip CWD to entry path */ + newURL = aprintf("%s/folderA/661", URL); + test_setopt(curl, CURLOPT_URL, newURL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD); + res = curl_easy_perform(curl); + if(res != CURLE_REMOTE_FILE_NOT_FOUND) + goto test_cleanup; + + curl_free(newURL); + newURL = aprintf("%s/folderB/661", URL); + test_setopt(curl, CURLOPT_URL, newURL); + res = curl_easy_perform(curl); + if(res != CURLE_REMOTE_FILE_NOT_FOUND) + goto test_cleanup; + + /* test: CURLFTPMETHOD_NOCWD with absolute path should + never emit CWD (for both new and reused easy handle) */ + curl_easy_cleanup(curl); + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + curl_free(newURL); + newURL = aprintf("%s/folderA/661", URL); + test_setopt(curl, CURLOPT_URL, newURL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD); + res = curl_easy_perform(curl); + if(res != CURLE_REMOTE_FILE_NOT_FOUND) + goto test_cleanup; + + /* curve ball: CWD /folderB before reusing connection with _NOCWD */ + curl_free(newURL); + newURL = aprintf("%s/folderB/661", URL); + test_setopt(curl, CURLOPT_URL, newURL); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD); + res = curl_easy_perform(curl); + if(res != CURLE_REMOTE_FILE_NOT_FOUND) + goto test_cleanup; + + curl_free(newURL); + newURL = aprintf("%s/folderA/661", URL); + test_setopt(curl, CURLOPT_URL, newURL); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD); + res = curl_easy_perform(curl); + if(res != CURLE_REMOTE_FILE_NOT_FOUND) + goto test_cleanup; + + /* test: CURLFTPMETHOD_NOCWD with home-relative path should + not emit CWD for first FTP access after login */ + curl_easy_cleanup(curl); + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + slist = curl_slist_append(NULL, "SYST"); + if(!slist) { + fprintf(stderr, "curl_slist_append() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_NOBODY, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD); + test_setopt(curl, CURLOPT_QUOTE, slist); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* test: CURLFTPMETHOD_SINGLECWD with home-relative path should + not emit CWD for first FTP access after login */ + curl_easy_cleanup(curl); + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_NOBODY, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD); + test_setopt(curl, CURLOPT_QUOTE, slist); + res = curl_easy_perform(curl); + if(res) + goto test_cleanup; + + /* test: CURLFTPMETHOD_NOCWD with home-relative path should + not emit CWD for second FTP access when not needed + + bonus: see if path buffering survives curl_easy_reset() */ + curl_easy_reset(curl); + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_NOBODY, 1L); + test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD); + test_setopt(curl, CURLOPT_QUOTE, slist); + res = curl_easy_perform(curl); + + +test_cleanup: + + if(res) + fprintf(stderr, "test encountered error %d\n", res); + curl_slist_free_all(slist); + curl_free(newURL); + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib666.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib666.c new file mode 100644 index 0000000000000000000000000000000000000000..dd172be4ab2a95c1f6be6a7b072aa822a612b9f9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib666.c @@ -0,0 +1,122 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testbuf[17000]; /* more than 16K */ + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURLcode res = CURLE_OK; + curl_mime *mime = NULL; + curl_mimepart *part; + size_t i; + + /* Checks huge binary-encoded mime post. */ + + /* Create a testbuf with pseudo-binary data. */ + for(i = 0; i < sizeof(testbuf); i++) + if(i % 77 == 76) + testbuf[i] = '\n'; + else + testbuf[i] = (char) (0x41 + i % 26); /* A...Z */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + + /* Build mime structure. */ + mime = curl_mime_init(curl); + if(!mime) { + fprintf(stderr, "curl_mime_init() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + part = curl_mime_addpart(mime); + if(!part) { + fprintf(stderr, "curl_mime_addpart() failed\n"); + res = TEST_ERR_MAJOR_BAD; + goto test_cleanup; + } + res = curl_mime_name(part, "upfile"); + if(res) { + fprintf(stderr, "curl_mime_name() failed\n"); + goto test_cleanup; + } + res = curl_mime_filename(part, "myfile.txt"); + if(res) { + fprintf(stderr, "curl_mime_filename() failed\n"); + goto test_cleanup; + } + res = curl_mime_data(part, testbuf, sizeof(testbuf)); + if(res) { + fprintf(stderr, "curl_mime_data() failed\n"); + goto test_cleanup; + } + res = curl_mime_encoder(part, "binary"); + if(res) { + fprintf(stderr, "curl_mime_encoder() failed\n"); + goto test_cleanup; + } + + /* First set the URL that is about to receive our mime mail. */ + test_setopt(curl, CURLOPT_URL, URL); + + /* Post form */ + test_setopt(curl, CURLOPT_MIMEPOST, mime); + + /* Shorten upload buffer. */ + test_setopt(curl, CURLOPT_UPLOAD_BUFFERSIZE, 16411L); + + /* get verbose debug output please */ + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(curl, CURLOPT_HEADER, 1L); + + /* Perform the request, res will get the return code */ + res = curl_easy_perform(curl); + +test_cleanup: + + /* always cleanup */ + curl_easy_cleanup(curl); + + /* now cleanup the mime structure */ + curl_mime_free(mime); + + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib667.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib667.c new file mode 100644 index 0000000000000000000000000000000000000000..d190601464fa3187815cf93d42db7bdf859a9617 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib667.c @@ -0,0 +1,112 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]= + "dummy"; + +struct WriteThis { + char *readptr; + curl_off_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + int eof = !*pooh->readptr; + + if(size*nmemb < 1) + return 0; + + eof = pooh->sizeleft <= 0; + if(!eof) + pooh->sizeleft--; + + if(!eof) { + *ptr = *pooh->readptr; /* copy one single byte */ + pooh->readptr++; /* advance pointer */ + return 1; /* we return 1 byte at a time! */ + } + + return 0; /* no more data left to deliver */ +} + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + curl_mime *mime = NULL; + curl_mimepart *part; + CURLcode res = TEST_ERR_FAILURE; + struct WriteThis pooh; + + /* + * Check proper handling of mime encoder feature when the part read callback + * delivers data bytes one at a time. Use chunked encoding for accurate test. + */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + easy = curl_easy_init(); + + /* First set the URL that is about to receive our POST. */ + test_setopt(easy, CURLOPT_URL, URL); + + /* get verbose debug output please */ + test_setopt(easy, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(easy, CURLOPT_HEADER, 1L); + + /* Prepare the callback structure. */ + pooh.readptr = testdata; + pooh.sizeleft = (curl_off_t) strlen(testdata); + + /* Build the mime tree. */ + mime = curl_mime_init(easy); + part = curl_mime_addpart(mime); + curl_mime_name(part, "field"); + curl_mime_encoder(part, "base64"); + /* Using an undefined length forces chunked transfer. */ + curl_mime_data_cb(part, (curl_off_t) -1, read_callback, NULL, NULL, &pooh); + + /* Bind mime data to its easy handle. */ + test_setopt(easy, CURLOPT_MIMEPOST, mime); + + /* Send data. */ + res = curl_easy_perform(easy); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed\n"); + } + +test_cleanup: + curl_easy_cleanup(easy); + curl_mime_free(mime); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib668.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib668.c new file mode 100644 index 0000000000000000000000000000000000000000..141e0ea5716ef8309a99e178a08e48039fa043ee --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib668.c @@ -0,0 +1,116 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "memdebug.h" + +static char testdata[]= "dummy"; + +struct WriteThis { + char *readptr; + curl_off_t sizeleft; +}; + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct WriteThis *pooh = (struct WriteThis *)userp; + size_t len = strlen(pooh->readptr); + + (void) size; /* Always 1.*/ + + if(len > nmemb) + len = nmemb; + if(len) { + memcpy(ptr, pooh->readptr, len); + pooh->readptr += len; + } + return len; +} + +CURLcode test(char *URL) +{ + CURL *easy = NULL; + curl_mime *mime = NULL; + curl_mimepart *part; + CURLcode res = TEST_ERR_FAILURE; + struct WriteThis pooh1, pooh2; + + /* + * Check early end of part data detection. + */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + easy = curl_easy_init(); + + /* First set the URL that is about to receive our POST. */ + test_setopt(easy, CURLOPT_URL, URL); + + /* get verbose debug output please */ + test_setopt(easy, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(easy, CURLOPT_HEADER, 1L); + + /* Prepare the callback structures. */ + pooh1.readptr = testdata; + pooh1.sizeleft = (curl_off_t) strlen(testdata); + pooh2 = pooh1; + + /* Build the mime tree. */ + mime = curl_mime_init(easy); + part = curl_mime_addpart(mime); + curl_mime_name(part, "field1"); + /* Early end of data detection can be done because the data size is known. */ + curl_mime_data_cb(part, (curl_off_t) strlen(testdata), + read_callback, NULL, NULL, &pooh1); + part = curl_mime_addpart(mime); + curl_mime_name(part, "field2"); + /* Using an undefined length forces chunked transfer and disables early + end of data detection for this part. */ + curl_mime_data_cb(part, (curl_off_t) -1, read_callback, NULL, NULL, &pooh2); + part = curl_mime_addpart(mime); + curl_mime_name(part, "field3"); + /* Regular file part sources early end of data can be detected because + the file size is known. In addition, and EOF test is performed. */ + curl_mime_filedata(part, libtest_arg2); + + /* Bind mime data to its easy handle. */ + test_setopt(easy, CURLOPT_MIMEPOST, mime); + + /* Send data. */ + res = curl_easy_perform(easy); + if(res != CURLE_OK) { + fprintf(stderr, "curl_easy_perform() failed\n"); + } + +test_cleanup: + curl_easy_cleanup(easy); + curl_mime_free(mime); + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib670.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib670.c new file mode 100644 index 0000000000000000000000000000000000000000..e03e8abebf6c67f73baa9a7b3cb8acf9abb861b5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib670.c @@ -0,0 +1,262 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include + +#include "memdebug.h" + +#define PAUSE_TIME 5 + + +static const char testname[] = "field"; + +struct ReadThis { + CURL *easy; + time_t origin; + int count; +}; + + +static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp) +{ + struct ReadThis *pooh = (struct ReadThis *) userp; + time_t delta; + + if(size * nmemb < 1) + return 0; + + switch(pooh->count++) { + case 0: + *ptr = '\x41'; /* ASCII A. */ + return 1; + case 1: + pooh->origin = time(NULL); + return CURL_READFUNC_PAUSE; + case 2: + delta = time(NULL) - pooh->origin; + *ptr = delta >= PAUSE_TIME ? '\x42' : '\x41'; /* ASCII A or B. */ + return 1; + case 3: + return 0; + } + fprintf(stderr, "Read callback called after EOF\n"); + exit(1); +} + +#if !defined(LIB670) && !defined(LIB672) +static int xferinfo(void *clientp, curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + struct ReadThis *pooh = (struct ReadThis *) clientp; + + (void) dltotal; + (void) dlnow; + (void) ultotal; + (void) ulnow; + + if(pooh->origin) { + time_t delta = time(NULL) - pooh->origin; + + if(delta >= 4 * PAUSE_TIME) { + fprintf(stderr, "unpausing failed: drain problem?\n"); + return CURLE_ABORTED_BY_CALLBACK; + } + + if(delta >= PAUSE_TIME) + curl_easy_pause(pooh->easy, CURLPAUSE_CONT); + } + + return 0; +} +#endif + +CURLcode test(char *URL) +{ +#if defined(LIB670) || defined(LIB671) + curl_mime *mime = NULL; + curl_mimepart *part; +#else + CURLFORMcode formrc; + struct curl_httppost *formpost = NULL; + struct curl_httppost *lastptr = NULL; +#endif +#if defined(LIB670) || defined(LIB672) + CURLM *multi = NULL; + CURLMcode mres; + CURLMsg *msg; + int msgs_left; + int still_running = 0; +#endif + + struct ReadThis pooh; + CURLcode res = TEST_ERR_FAILURE; + + /* + * Check proper pausing/unpausing from a mime or form read callback. + */ + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + pooh.origin = (time_t) 0; + pooh.count = 0; + pooh.easy = curl_easy_init(); + + /* First set the URL that is about to receive our POST. */ + test_setopt(pooh.easy, CURLOPT_URL, URL); + + /* get verbose debug output please */ + test_setopt(pooh.easy, CURLOPT_VERBOSE, 1L); + + /* include headers in the output */ + test_setopt(pooh.easy, CURLOPT_HEADER, 1L); + +#if defined(LIB670) || defined(LIB671) + /* Build the mime tree. */ + mime = curl_mime_init(pooh.easy); + part = curl_mime_addpart(mime); + res = curl_mime_name(part, testname); + if(res != CURLE_OK) { + fprintf(stderr, + "Something went wrong when building the mime structure: %d\n", + res); + goto test_cleanup; + } + + res = curl_mime_data_cb(part, (curl_off_t) 2, read_callback, + NULL, NULL, &pooh); + + /* Bind mime data to its easy handle. */ + if(res == CURLE_OK) + test_setopt(pooh.easy, CURLOPT_MIMEPOST, mime); +#else + CURL_IGNORE_DEPRECATION( + /* Build the form. */ + formrc = curl_formadd(&formpost, &lastptr, + CURLFORM_COPYNAME, testname, + CURLFORM_STREAM, &pooh, + CURLFORM_CONTENTLEN, (curl_off_t) 2, + CURLFORM_END); + ) + if(formrc) { + fprintf(stderr, "curl_formadd() = %d\n", (int) formrc); + goto test_cleanup; + } + + /* We want to use our own read function. */ + test_setopt(pooh.easy, CURLOPT_READFUNCTION, read_callback); + + CURL_IGNORE_DEPRECATION( + /* Send a multi-part formpost. */ + test_setopt(pooh.easy, CURLOPT_HTTPPOST, formpost); + ) +#endif + +#if defined(LIB670) || defined(LIB672) + /* Use the multi interface. */ + multi = curl_multi_init(); + mres = curl_multi_add_handle(multi, pooh.easy); + while(!mres) { + struct timeval timeout; + int rc = 0; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcept; + int maxfd = -1; + + mres = curl_multi_perform(multi, &still_running); + if(!still_running || mres != CURLM_OK) + break; + + if(pooh.origin) { + time_t delta = time(NULL) - pooh.origin; + + if(delta >= 4 * PAUSE_TIME) { + fprintf(stderr, "unpausing failed: drain problem?\n"); + res = CURLE_OPERATION_TIMEDOUT; + break; + } + + if(delta >= PAUSE_TIME) + curl_easy_pause(pooh.easy, CURLPAUSE_CONT); + } + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcept); + timeout.tv_sec = 0; + timeout.tv_usec = 1000000 * PAUSE_TIME / 10; + mres = curl_multi_fdset(multi, &fdread, &fdwrite, &fdexcept, &maxfd); + if(mres) + break; +#if defined(_WIN32) + if(maxfd == -1) + Sleep(100); + else +#endif + rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcept, &timeout); + if(rc == -1) { + fprintf(stderr, "Select error\n"); + break; + } + } + + if(mres != CURLM_OK) + for(;;) { + msg = curl_multi_info_read(multi, &msgs_left); + if(!msg) + break; + if(msg->msg == CURLMSG_DONE) { + res = msg->data.result; + } + } + + curl_multi_remove_handle(multi, pooh.easy); + curl_multi_cleanup(multi); + +#else + /* Use the easy interface. */ + test_setopt(pooh.easy, CURLOPT_XFERINFODATA, &pooh); + test_setopt(pooh.easy, CURLOPT_XFERINFOFUNCTION, xferinfo); + test_setopt(pooh.easy, CURLOPT_NOPROGRESS, 0L); + res = curl_easy_perform(pooh.easy); +#endif + + +test_cleanup: + curl_easy_cleanup(pooh.easy); +#if defined(LIB670) || defined(LIB671) + curl_mime_free(mime); +#else + CURL_IGNORE_DEPRECATION( + curl_formfree(formpost); + ) +#endif + + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib674.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib674.c new file mode 100644 index 0000000000000000000000000000000000000000..39e16e0f5f3d0f65e2000c700d991842c71a89b8 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib674.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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +/* + * Get a single URL without select(). + */ + +CURLcode test(char *URL) +{ + CURL *handle = NULL; + CURL *handle2; + CURLcode res = CURLE_OK; + CURLU *urlp = NULL; + CURLUcode uc = CURLUE_OK; + + global_init(CURL_GLOBAL_ALL); + easy_init(handle); + + urlp = curl_url(); + + if(!urlp) { + fprintf(stderr, "problem init URL api."); + goto test_cleanup; + } + + uc = curl_url_set(urlp, CURLUPART_URL, URL, 0); + if(uc) { + fprintf(stderr, "problem setting CURLUPART_URL: %s.", + curl_url_strerror(uc)); + goto test_cleanup; + } + + /* demonstrate override behavior */ + + + easy_setopt(handle, CURLOPT_CURLU, urlp); + easy_setopt(handle, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(handle); + + if(res) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, res, curl_easy_strerror(res)); + goto test_cleanup; + } + + handle2 = curl_easy_duphandle(handle); + res = curl_easy_perform(handle2); + curl_easy_cleanup(handle2); + +test_cleanup: + + curl_url_cleanup(urlp); + curl_easy_cleanup(handle); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib676.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib676.c new file mode 100644 index 0000000000000000000000000000000000000000..fc292705a59f12a373ca748a882e9745d851dc59 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib676.c @@ -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 + * + ***************************************************************************/ +#include "test.h" + +#include "memdebug.h" + +CURLcode test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_USERAGENT, "the-moo agent next generation"); + test_setopt(curl, CURLOPT_COOKIEFILE, libtest_arg2); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + if(res) { + fprintf(stderr, "retrieve 1 failed\n"); + goto test_cleanup; + } + + /* now clear the cookies */ + test_setopt(curl, CURLOPT_COOKIEFILE, NULL); + + res = curl_easy_perform(curl); + if(res) + fprintf(stderr, "retrieve 2 failed\n"); + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib677.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib677.c new file mode 100644 index 0000000000000000000000000000000000000000..ebb9f40848fc2a38ab72a7a9d4e8ed6041de2096 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib677.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 + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +static const char testcmd[] = "A1 IDLE\r\n"; +static char testbuf[1024]; + +CURLcode test(char *URL) +{ + CURLM *mcurl; + CURL *curl = NULL; + int mrun; + curl_socket_t sock = CURL_SOCKET_BAD; + time_t start = time(NULL); + int state = 0; + ssize_t pos = 0; + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_DEFAULT); + multi_init(mcurl); + easy_init(curl); + + easy_setopt(curl, CURLOPT_VERBOSE, 1L); + easy_setopt(curl, CURLOPT_URL, URL); + easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L); + if(curl_multi_add_handle(mcurl, curl)) + goto test_cleanup; + + while(time(NULL) - start < 5) { + struct curl_waitfd waitfd; + + multi_perform(mcurl, &mrun); + for(;;) { + int i; + struct CURLMsg *m = curl_multi_info_read(mcurl, &i); + + if(!m) + break; + if(m->msg == CURLMSG_DONE && m->easy_handle == curl) { + curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sock); + if(sock == CURL_SOCKET_BAD) + goto test_cleanup; + printf("Connected fine, extracted socket. Moving on\n"); + } + } + + if(sock != CURL_SOCKET_BAD) { + waitfd.events = state ? CURL_WAIT_POLLIN : CURL_WAIT_POLLOUT; + waitfd.revents = 0; + curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sock); + waitfd.fd = sock; + } + curl_multi_wait(mcurl, &waitfd, sock == CURL_SOCKET_BAD ? 0 : 1, 50, + &mrun); + if((sock != CURL_SOCKET_BAD) && (waitfd.revents & waitfd.events)) { + size_t len = 0; + + if(!state) { + CURLcode ec; + ec = curl_easy_send(curl, testcmd + pos, + sizeof(testcmd) - 1 - pos, &len); + if(ec == CURLE_AGAIN) { + continue; + } + else if(ec) { + fprintf(stderr, "curl_easy_send() failed, with code %d (%s)\n", + (int)ec, curl_easy_strerror(ec)); + res = ec; + goto test_cleanup; + } + if(len > 0) + pos += len; + else + pos = 0; + if(pos == sizeof(testcmd) - 1) { + state++; + pos = 0; + } + } + else if(pos < (ssize_t)sizeof(testbuf)) { + CURLcode ec; + ec = curl_easy_recv(curl, testbuf + pos, sizeof(testbuf) - pos, &len); + if(ec == CURLE_AGAIN) { + continue; + } + else if(ec) { + fprintf(stderr, "curl_easy_recv() failed, with code %d (%s)\n", + (int)ec, curl_easy_strerror(ec)); + res = ec; + goto test_cleanup; + } + if(len > 0) + pos += len; + } + if(len <= 0) + sock = CURL_SOCKET_BAD; + } + } + + if(state) { + fwrite(testbuf, pos, 1, stdout); + putchar('\n'); + } + + curl_multi_remove_handle(mcurl, curl); +test_cleanup: + curl_easy_cleanup(curl); + curl_multi_cleanup(mcurl); + + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/lib678.c b/local-test-curl-delta-01/afc-curl/tests/libtest/lib678.c new file mode 100644 index 0000000000000000000000000000000000000000..9a8ab7670df64c27807822f89e1bef82b3e22f64 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/lib678.c @@ -0,0 +1,122 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +static int loadfile(const char *filename, void **filedata, size_t *filesize) +{ + size_t datasize = 0; + void *data = NULL; + if(filename) { + FILE *fInCert = fopen(filename, "rb"); + + 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 + datasize = (size_t)cert_tell; + if(continue_reading) + continue_reading = fseek(fInCert, 0, SEEK_SET) == 0; + if(continue_reading) + data = malloc(datasize + 1); + if((!data) || + ((int)fread(data, datasize, 1, fInCert) != 1)) + continue_reading = FALSE; + fclose(fInCert); + if(!continue_reading) { + free(data); + datasize = 0; + data = NULL; + } + } + } + *filesize = datasize; + *filedata = data; + return data ? 1 : 0; +} + +static CURLcode test_cert_blob(const char *url, const char *cafile) +{ + CURLcode code = CURLE_OUT_OF_MEMORY; + CURL *curl; + struct curl_blob blob; + size_t certsize; + void *certdata; + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + return CURLE_FAILED_INIT; + } + + if(loadfile(cafile, &certdata, &certsize)) { + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(curl, CURLOPT_HEADER, 1L); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_USERAGENT, "CURLOPT_CAINFO_BLOB"); + curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, + CURLSSLOPT_REVOKE_BEST_EFFORT); + + blob.data = certdata; + blob.len = certsize; + blob.flags = CURL_BLOB_COPY; + curl_easy_setopt(curl, CURLOPT_CAINFO_BLOB, &blob); + free(certdata); + code = curl_easy_perform(curl); + } + curl_easy_cleanup(curl); + + return code; +} + +CURLcode test(char *URL) +{ + CURLcode res = CURLE_OK; + curl_global_init(CURL_GLOBAL_DEFAULT); + if(!strcmp("check", URL)) { + CURL *e; + CURLcode w = CURLE_OK; + struct curl_blob blob = {0}; + e = curl_easy_init(); + if(e) { + w = curl_easy_setopt(e, CURLOPT_CAINFO_BLOB, &blob); + if(w) + printf("CURLOPT_CAINFO_BLOB is not supported\n"); + curl_easy_cleanup(e); + } + res = w; + } + else + res = test_cert_blob(URL, libtest_arg2); + + curl_global_cleanup(); + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/libauthretry.c b/local-test-curl-delta-01/afc-curl/tests/libtest/libauthretry.c new file mode 100644 index 0000000000000000000000000000000000000000..db648f35a16535c6bac3b72ee27e7434790de785 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/libauthretry.c @@ -0,0 +1,149 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* argv1 = URL + * argv2 = main auth type + * argv3 = second auth type + */ + +#include "test.h" +#include "memdebug.h" + +static CURLcode send_request(CURL *curl, const char *url, int seq, + long auth_scheme, const char *userpwd) +{ + CURLcode res; + size_t len = strlen(url) + 4 + 1; + char *full_url = malloc(len); + if(!full_url) { + fprintf(stderr, "Not enough memory for full url\n"); + return CURLE_OUT_OF_MEMORY; + } + + msnprintf(full_url, len, "%s%04d", url, seq); + fprintf(stderr, "Sending new request %d to %s with credential %s " + "(auth %ld)\n", seq, full_url, userpwd, auth_scheme); + test_setopt(curl, CURLOPT_URL, full_url); + test_setopt(curl, CURLOPT_VERBOSE, 1L); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_HTTPGET, 1L); + test_setopt(curl, CURLOPT_USERPWD, userpwd); + test_setopt(curl, CURLOPT_HTTPAUTH, auth_scheme); + + res = curl_easy_perform(curl); + +test_cleanup: + free(full_url); + return res; +} + +static CURLcode send_wrong_password(CURL *curl, const char *url, int seq, + long auth_scheme) +{ + return send_request(curl, url, seq, auth_scheme, "testuser:wrongpass"); +} + +static CURLcode send_right_password(CURL *curl, const char *url, int seq, + long auth_scheme) +{ + return send_request(curl, url, seq, auth_scheme, "testuser:testpass"); +} + +static long parse_auth_name(const char *arg) +{ + if(!arg) + return CURLAUTH_NONE; + if(curl_strequal(arg, "basic")) + return CURLAUTH_BASIC; + if(curl_strequal(arg, "digest")) + return CURLAUTH_DIGEST; + if(curl_strequal(arg, "ntlm")) + return CURLAUTH_NTLM; + return CURLAUTH_NONE; +} + +CURLcode test(char *url) +{ + CURLcode res; + CURL *curl = NULL; + + long main_auth_scheme = parse_auth_name(libtest_arg2); + long fallback_auth_scheme = parse_auth_name(libtest_arg3); + + if(main_auth_scheme == CURLAUTH_NONE || + fallback_auth_scheme == CURLAUTH_NONE) { + fprintf(stderr, "auth schemes not found on commandline\n"); + return TEST_ERR_MAJOR_BAD; + } + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + /* Send wrong password, then right password */ + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + res = send_wrong_password(curl, url, 100, main_auth_scheme); + if(res != CURLE_OK) + goto test_cleanup; + + res = send_right_password(curl, url, 200, fallback_auth_scheme); + if(res != CURLE_OK) + goto test_cleanup; + + curl_easy_cleanup(curl); + + /* Send wrong password twice, then right password */ + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + res = send_wrong_password(curl, url, 300, main_auth_scheme); + if(res != CURLE_OK) + goto test_cleanup; + + res = send_wrong_password(curl, url, 400, fallback_auth_scheme); + if(res != CURLE_OK) + goto test_cleanup; + + res = send_right_password(curl, url, 500, fallback_auth_scheme); + if(res != CURLE_OK) + goto test_cleanup; + +test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/libntlmconnect.c b/local-test-curl-delta-01/afc-curl/tests/libtest/libntlmconnect.c new file mode 100644 index 0000000000000000000000000000000000000000..9cbcb50bb55ff92a2b619d51d5e374670f21b37e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/libntlmconnect.c @@ -0,0 +1,241 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +#include +#include + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 +#define MAX_EASY_HANDLES 3 + +static int ntlm_counter[MAX_EASY_HANDLES]; +static CURL *ntlm_easy[MAX_EASY_HANDLES]; +static curl_socket_t ntlm_sockets[MAX_EASY_HANDLES]; +static CURLcode ntlmcb_res = CURLE_OK; + +static size_t callback(char *ptr, size_t size, size_t nmemb, void *data) +{ + ssize_t idx = ((CURL **) data) - ntlm_easy; + curl_socket_t sock; + long longdata; + CURLcode code; + const size_t failure = (size && nmemb) ? 0 : 1; + (void)ptr; + + ntlm_counter[idx] += (int)(size * nmemb); + + /* Get socket being used for this easy handle, otherwise CURL_SOCKET_BAD */ + CURL_IGNORE_DEPRECATION( + code = curl_easy_getinfo(ntlm_easy[idx], CURLINFO_LASTSOCKET, &longdata); + ) + if(CURLE_OK != code) { + fprintf(stderr, "%s:%d curl_easy_getinfo() failed, " + "with code %d (%s)\n", + __FILE__, __LINE__, (int)code, curl_easy_strerror(code)); + ntlmcb_res = TEST_ERR_MAJOR_BAD; + return failure; + } + if(longdata == -1L) + sock = CURL_SOCKET_BAD; + else + sock = (curl_socket_t)longdata; + + if(sock != CURL_SOCKET_BAD) { + /* Track relationship between this easy handle and the socket. */ + if(ntlm_sockets[idx] == CURL_SOCKET_BAD) { + /* An easy handle without previous socket, record the socket. */ + ntlm_sockets[idx] = sock; + } + else if(sock != ntlm_sockets[idx]) { + /* An easy handle with a socket different to previously + tracked one, log and fail right away. Known bug #37. */ + fprintf(stderr, "Handle %d started on socket %d and moved to %d\n", + curlx_sztosi(idx), (int)ntlm_sockets[idx], (int)sock); + ntlmcb_res = TEST_ERR_MAJOR_BAD; + return failure; + } + } + return size * nmemb; +} + +enum HandleState { + ReadyForNewHandle, + NeedSocketForNewHandle, + NoMoreHandles +}; + +CURLcode test(char *url) +{ + CURLcode res = CURLE_OK; + CURLM *multi = NULL; + int running; + int i; + int num_handles = 0; + enum HandleState state = ReadyForNewHandle; + size_t urllen = strlen(url) + 4 + 1; + char *full_url = malloc(urllen); + + start_test_timing(); + + if(!full_url) { + fprintf(stderr, "Not enough memory for full url\n"); + return TEST_ERR_MAJOR_BAD; + } + + for(i = 0; i < MAX_EASY_HANDLES; ++i) { + ntlm_easy[i] = NULL; + ntlm_sockets[i] = CURL_SOCKET_BAD; + } + + res_global_init(CURL_GLOBAL_ALL); + if(res) { + free(full_url); + return res; + } + + multi_init(multi); + + for(;;) { + struct timeval interval; + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + long timeout = -99; + int maxfd = -99; + bool found_new_socket = FALSE; + + /* Start a new handle if we aren't at the max */ + if(state == ReadyForNewHandle) { + easy_init(ntlm_easy[num_handles]); + + if(num_handles % 3 == 2) { + msnprintf(full_url, urllen, "%s0200", url); + easy_setopt(ntlm_easy[num_handles], CURLOPT_HTTPAUTH, CURLAUTH_NTLM); + } + else { + msnprintf(full_url, urllen, "%s0100", url); + easy_setopt(ntlm_easy[num_handles], CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + } + easy_setopt(ntlm_easy[num_handles], CURLOPT_FRESH_CONNECT, 1L); + easy_setopt(ntlm_easy[num_handles], CURLOPT_URL, full_url); + easy_setopt(ntlm_easy[num_handles], CURLOPT_VERBOSE, 1L); + easy_setopt(ntlm_easy[num_handles], CURLOPT_HTTPGET, 1L); + easy_setopt(ntlm_easy[num_handles], CURLOPT_USERPWD, + "testuser:testpass"); + easy_setopt(ntlm_easy[num_handles], CURLOPT_WRITEFUNCTION, callback); + easy_setopt(ntlm_easy[num_handles], CURLOPT_WRITEDATA, + ntlm_easy + num_handles); + easy_setopt(ntlm_easy[num_handles], CURLOPT_HEADER, 1L); + + multi_add_handle(multi, ntlm_easy[num_handles]); + num_handles += 1; + state = NeedSocketForNewHandle; + res = ntlmcb_res; + } + + multi_perform(multi, &running); + + fprintf(stderr, "%s:%d running %d state %d\n", + __FILE__, __LINE__, running, state); + + abort_on_test_timeout(); + + if(!running && state == NoMoreHandles) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(multi, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + if(state == NeedSocketForNewHandle) { + if(maxfd != -1 && !found_new_socket) { + fprintf(stderr, "Warning: socket did not open immediately for new " + "handle (trying again)\n"); + continue; + } + state = num_handles < MAX_EASY_HANDLES ? ReadyForNewHandle + : NoMoreHandles; + fprintf(stderr, "%s:%d new state %d\n", + __FILE__, __LINE__, state); + } + + multi_timeout(multi, &timeout); + + /* At this point, timeout is guaranteed to be greater or equal than -1. */ + + fprintf(stderr, "%s:%d num_handles %d timeout %ld running %d\n", + __FILE__, __LINE__, num_handles, timeout, running); + + if(timeout != -1L) { + int itimeout; +#if LONG_MAX > INT_MAX + itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; +#else + itimeout = (int)timeout; +#endif + interval.tv_sec = itimeout/1000; + interval.tv_usec = (itimeout%1000)*1000; + } + else { + interval.tv_sec = 0; + interval.tv_usec = 5000; + + /* if there's no timeout and we get here on the last handle, we may + already have read the last part of the stream so waiting makes no + sense */ + if(!running && num_handles == MAX_EASY_HANDLES) { + break; + } + } + + select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &interval); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PB */ + + for(i = 0; i < MAX_EASY_HANDLES; i++) { + printf("Data connection %d: %d\n", i, ntlm_counter[i]); + curl_multi_remove_handle(multi, ntlm_easy[i]); + curl_easy_cleanup(ntlm_easy[i]); + } + + curl_multi_cleanup(multi); + curl_global_cleanup(); + + free(full_url); + + return res; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/libprereq.c b/local-test-curl-delta-01/afc-curl/tests/libtest/libprereq.c new file mode 100644 index 0000000000000000000000000000000000000000..3eef5f369084f09dbfefa3d3dc421615b59e45b7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/libprereq.c @@ -0,0 +1,99 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Max Dymond, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" + +typedef struct prcs { + int prereq_retcode; + int ipv6; +} PRCS; + +static int prereq_callback(void *clientp, + char *conn_primary_ip, + char *conn_local_ip, + int conn_primary_port, + int conn_local_port) +{ + PRCS *prereq_cb = (PRCS *)clientp; + + if(prereq_cb->ipv6) { + printf("Connected to [%s]\n", conn_primary_ip); + printf("Connected from [%s]\n", conn_local_ip); + } + else { + printf("Connected to %s\n", conn_primary_ip); + printf("Connected from %s\n", conn_local_ip); + } + + printf("Remote port = %d\n", conn_primary_port); + printf("Local port = %d\n", conn_local_port); + printf("Returning = %d\n", prereq_cb->prereq_retcode); + return prereq_cb->prereq_retcode; +} + +CURLcode test(char *URL) +{ + PRCS prereq_cb; + CURLcode ret = CURLE_OK; + CURL *curl = NULL; + + prereq_cb.prereq_retcode = CURL_PREREQFUNC_OK; + prereq_cb.ipv6 = 0; + + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + + if(curl) { + if(strstr(URL, "#ipv6")) { + /* The IP addresses should be surrounded by brackets! */ + prereq_cb.ipv6 = 1; + } + if(strstr(URL, "#err")) { + /* Set the callback to exit with failure */ + prereq_cb.prereq_retcode = CURL_PREREQFUNC_ABORT; + } + + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_PREREQFUNCTION, prereq_callback); + curl_easy_setopt(curl, CURLOPT_PREREQDATA, &prereq_cb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, stderr); + + if(strstr(URL, "#redir")) { + /* Enable follow-location */ + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); + } + + ret = curl_easy_perform(curl); + if(ret) { + fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n", + __FILE__, __LINE__, ret, curl_easy_strerror(ret)); + goto test_cleanup; + } + } + +test_cleanup: + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return ret; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/mk-lib1521.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/mk-lib1521.pl new file mode 100644 index 0000000000000000000000000000000000000000..e668874654d2f9c62da0abb973d24b4ad0b378ae --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/mk-lib1521.pl @@ -0,0 +1,613 @@ +#!/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 +# +########################################################################### + +# Usage: +# perl mk-lib1521.pl < ../../include/curl/curl.h lib1521.c + +# minimum and maximum long signed values +my $minlong = "LONG_MIN"; +my $maxlong = "LONG_MAX"; +# maximum curl_off_t +my $maxofft = "CURL_OFF_T_MAX"; +my $line = ""; +my $incomment = 0; + +# Options allowed to return CURLE_BAD_FUNCTION_ARGUMENT if given a string they +# do not recognize as valid +my @bad_function_argument = ( + 'CURLOPT_DNS_LOCAL_IP4', + 'CURLOPT_DNS_LOCAL_IP6', + 'CURLOPT_DNS_SERVERS', + 'CURLOPT_PROXY_TLSAUTH_TYPE', + 'CURLOPT_SSLENGINE', + 'CURLOPT_TLSAUTH_TYPE', +); + +# Options allowed to return CURLE_UNSUPPORTED_PROTOCOL if given a string they +# do not recognize as valid +my @unsupported_protocol = ( + 'CURLOPT_PROTOCOLS_STR', + 'CURLOPT_REDIR_PROTOCOLS_STR', + ); + +# Options allowed to return CURLE_SSL_ENGINE_NOTFOUND if given a string they +# do not recognize as valid +my @ssl_engine_notfound = ( + 'CURLOPT_SSLENGINE', + ); + +# Options allowed to return CURLE_UNSUPPORTED_PROTOCOL if given a bad +# numerical input they do not recognize as valid +my @unsupported_protocol_num = ( + 'CURLOPT_HTTP_VERSION', + ); + +# Options allowed to return CURLE_NOT_BUILT_IN if given a bad +# numerical input they do not recognize as valid +my @not_built_in_num = ( + 'CURLOPT_HTTPAUTH', + 'CURLOPT_PROXYAUTH', + 'CURLOPT_SOCKS5_AUTH', + ); + + +# +# Generate a set of string checks +# + +my $allowedstringerrors = <, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "memdebug.h" +#include + +/* This source code is generated by mk-lib1521.pl ! */ + +struct testdata { + char *blaha; +}; + +#define LO $minlong +#define HI $maxlong +#define OFF_LO (curl_off_t) LO +#define OFF_HI (curl_off_t) $maxofft +#define OFF_NO (curl_off_t) 0 + +static size_t writecb(char *buffer, size_t size, size_t nitems, + void *outstream) +{ + (void)buffer; + (void)size; + (void)nitems; + (void)outstream; + return 0; +} + +static size_t readcb(char *buffer, + size_t size, + size_t nitems, + void *instream) +{ + (void)buffer; + (void)size; + (void)nitems; + (void)instream; + return 0; +} + +static void errlongzero(const char *name, CURLcode code, int lineno) +{ + printf("%s set to 0 returned %d, \\"%s\\" on line %d\\n", + name, code, curl_easy_strerror(code), lineno); +} + +static void errlong(const char *name, CURLcode code, int lineno) +{ +$allowednumerrors + printf("%s set to non-zero returned %d, \\"%s\\" on line %d\\n", + name, code, curl_easy_strerror(code), lineno); +} + +static void errstring(const char *name, CURLcode code, int lineno) +{ + /* allow this set of options to return CURLE_BAD_FUNCTION_ARGUMENT + when given a strange string input */ +$allowedstringerrors + printf("%s set to a string returned %d, \\"%s\\" on line %d\\n", + name, code, curl_easy_strerror(code), lineno); +} + +static void err(const char *name, CURLcode val, int lineno) +{ + printf("%s returned %d, \\"%s\\" on line %d\\n", + name, val, curl_easy_strerror(val), lineno); +} + +static void errnull(const char *name, CURLcode val, int lineno) +{ + printf("%s set to NULL returned %d, \\"%s\\" on line %d\\n", + name, val, curl_easy_strerror(val), lineno); +} + +static void geterr(const char *name, CURLcode val, int lineno) +{ + printf("CURLINFO_%s returned %d, \\"%s\\" on line %d\\n", + name, val, curl_easy_strerror(val), lineno); +} + +static curl_progress_callback progresscb; +static curl_write_callback headercb; +static curl_debug_callback debugcb; +static curl_trailer_callback trailercb; +static curl_ssl_ctx_callback ssl_ctx_cb; +static curl_ioctl_callback ioctlcb; +static curl_sockopt_callback sockoptcb; +static curl_opensocket_callback opensocketcb; +static curl_seek_callback seekcb; +static curl_sshkeycallback ssh_keycb; +static curl_sshhostkeycallback ssh_hostkeycb; +static curl_chunk_bgn_callback chunk_bgn_cb; +static curl_chunk_end_callback chunk_end_cb; +static curl_fnmatch_callback fnmatch_cb; +static curl_closesocket_callback closesocketcb; +static curl_xferinfo_callback xferinfocb; +static curl_hstsread_callback hstsreadcb; +static curl_hstswrite_callback hstswritecb; +static curl_resolver_start_callback resolver_start_cb; +static curl_prereq_callback prereqcb; + +/* long options that are okay to return + CURLE_BAD_FUNCTION_ARGUMENT */ +static bool bad_long(CURLcode res, int check) +{ + if(res != CURLE_BAD_FUNCTION_ARGUMENT) + return 0; /* not okay */ + + if(check < CURLOPTTYPE_OBJECTPOINT) { + /* LONG */ + return 1; + } + else if((check >= CURLOPTTYPE_OFF_T) && + (check < CURLOPTTYPE_BLOB)) { + /* OFF_T */ + return 1; + } + return 0; +} + +/* macro to check the first setopt of an option which then is allowed to get a + non-existing function return code back */ +#define present(x) ((x != CURLE_NOT_BUILT_IN) && (x != CURLE_UNKNOWN_OPTION)) + +CURLcode test(char *URL) +{ + CURL *curl = NULL; + CURL *dep = NULL; + CURLSH *share = NULL; + char errorbuffer[CURL_ERROR_SIZE]; + void *conv_from_network_cb = NULL; + void *conv_to_network_cb = NULL; + void *conv_from_utf8_cb = NULL; + void *interleavecb = NULL; + char *stringpointerextra = (char *)"moooo"; + struct curl_slist *slist = NULL; + struct curl_httppost *httppost = NULL; + curl_mime *mimepost = NULL; + FILE *stream = stderr; + struct testdata object; + char *charp; + long val; + curl_off_t oval; + double dval; + curl_socket_t sockfd; + struct curl_certinfo *certinfo; + struct curl_tlssessioninfo *tlssession; + struct curl_blob blob = { (void *)"silly", 5, 0}; + CURLcode res = CURLE_OK; + (void)URL; /* not used */ + global_init(CURL_GLOBAL_ALL); + easy_init(dep); + easy_init(curl); + share = curl_share_init(); + if(!share) { + res = CURLE_OUT_OF_MEMORY; + goto test_cleanup; + } + + CURL_IGNORE_DEPRECATION( +HEADER + ; + +while() { + s/^\s*(.*?)\s*$/$1/; # Trim. + # Remove multi-line comment trail. + if($incomment) { + if($_ !~ /.*?\*\/\s*(.*)$/) { + next; + } + $_ = $1; + $incomment = 0; + } + if($line ne "") { + # Unfold line. + $_ = "$line $1"; + $line = ""; + } + # Remove comments. + while($_ =~ /^(.*?)\/\*.*?\*\/(.*)$/) { + $_ = "$1 $2"; + } + s/^\s*(.*?)\s*$/$1/; # Trim again. + if($_ =~ /^(.*)\/\*/) { + $_ = $1; + $incomment = 1; + } + # Ignore preprocessor directives and blank lines. + if($_ =~ /^(?:#|$)/) { + next; + } + # Handle lines that may be continued as if they were folded. + if($_ !~ /[;,{}]$/) { + # Folded line. + $line = $_; + next; + } + if($_ =~ / CURL_DEPRECATED\(/) { + # Drop deprecation info. + if($_ !~ /^(.*?) CURL_DEPRECATED\(.*?"\)(.*)$/) { + # Needs unfolding. + $line = $_; + next; + } + $_ = $1 . $2; + } + if($_ =~ /^CURLOPT(?:DEPRECATED)?\(/ && $_ !~ /\),$/) { + # Multi-line CURLOPTs need unfolding. + $line = $_; + next; + } + if($_ =~ /^CURLOPT(?:DEPRECATED)?\(([^ ]*), ([^ ]*), (\d*)[,)]/) { + my ($name, $type, $val)=($1, $2, $3); + my $w=" "; + my $w2="$w$w"; + my $w3="$w$w$w"; + my $opt = $name; + $opt =~ s/^CURLOPT_//; + my $exists = "${w}{\n"; + # the first check for an option + my $fpref = "${exists}${w2}CURLcode first =\n${w3}curl_easy_setopt(curl, $name,"; + my $ifpresent = "${w2}if(present(first)) {\n"; + my $pref = "${w3}res = curl_easy_setopt(curl, $name,"; + my $i = ' ' x (length($w) + 25); + my $fcheck = <, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* Only provides the bare minimum to link with libcurl */ + +#include +#include +#include + +#include "stub_gssapi.h" + +/* !checksrc! disable SNPRINTF all */ + +#define MAX_CREDS_LENGTH 250 +#define APPROX_TOKEN_LEN 250 + +enum min_err_code { + GSS_OK = 0, + GSS_NO_MEMORY, + GSS_INVALID_ARGS, + GSS_INVALID_CREDS, + GSS_INVALID_CTX, + GSS_SERVER_ERR, + GSS_NO_MECH, + GSS_LAST +}; + +static const char *min_err_table[] = { + "stub-gss: no error", + "stub-gss: no memory", + "stub-gss: invalid arguments", + "stub-gss: invalid credentials", + "stub-gss: invalid context", + "stub-gss: server returned error", + "stub-gss: cannot find a mechanism", + NULL +}; + +struct gss_ctx_id_t_desc_struct { + enum { NONE, KRB5, NTLM1, NTLM3 } sent; + int have_krb5; + int have_ntlm; + OM_uint32 flags; + char creds[MAX_CREDS_LENGTH]; +}; + +/* simple implementation of strndup(), which isn't portable */ +static char *my_strndup(const char *ptr, size_t len) +{ + char *copy = malloc(len + 1); + if(!copy) + return NULL; + memcpy(copy, ptr, len); + copy[len] = '\0'; + return copy; +} + +OM_uint32 gss_init_sec_context(OM_uint32 *min, + gss_const_cred_id_t initiator_cred_handle, + gss_ctx_id_t *context_handle, + gss_const_name_t target_name, + const gss_OID mech_type, + OM_uint32 req_flags, + OM_uint32 time_req, + const gss_channel_bindings_t input_chan_bindings, + const gss_buffer_t input_token, + gss_OID *actual_mech_type, + gss_buffer_t output_token, + OM_uint32 *ret_flags, + OM_uint32 *time_rec) +{ + /* The token will be encoded in base64 */ + size_t length = APPROX_TOKEN_LEN * 3 / 4; + size_t used = 0; + char *token = NULL; + const char *creds = NULL; + gss_ctx_id_t ctx = NULL; + + (void)initiator_cred_handle; + (void)mech_type; + (void)time_req; + (void)input_chan_bindings; + (void)actual_mech_type; + + if(!min) + return GSS_S_FAILURE; + + *min = 0; + + if(!context_handle || !target_name || !output_token) { + *min = GSS_INVALID_ARGS; + return GSS_S_FAILURE; + } + + creds = getenv("CURL_STUB_GSS_CREDS"); + if(!creds || strlen(creds) >= MAX_CREDS_LENGTH) { + *min = GSS_INVALID_CREDS; + return GSS_S_FAILURE; + } + + ctx = *context_handle; + if(ctx && strcmp(ctx->creds, creds)) { + *min = GSS_INVALID_CREDS; + return GSS_S_FAILURE; + } + + output_token->length = 0; + output_token->value = NULL; + + if(input_token && input_token->length) { + if(!ctx) { + *min = GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + /* Server response, either D (RA==) or C (Qw==) */ + if(((char *) input_token->value)[0] == 'D') { + /* Done */ + switch(ctx->sent) { + case KRB5: + case NTLM3: + if(ret_flags) + *ret_flags = ctx->flags; + if(time_rec) + *time_rec = GSS_C_INDEFINITE; + return GSS_S_COMPLETE; + default: + *min = GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + } + + if(((char *) input_token->value)[0] != 'C') { + /* We only support Done or Continue */ + *min = GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + + /* Continue */ + switch(ctx->sent) { + case KRB5: + /* We sent KRB5 and it failed, let's try NTLM */ + if(ctx->have_ntlm) { + ctx->sent = NTLM1; + break; + } + else { + *min = GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + case NTLM1: + ctx->sent = NTLM3; + break; + default: + *min = GSS_SERVER_ERR; + return GSS_S_FAILURE; + } + } + else { + if(ctx) { + *min = GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + ctx = (gss_ctx_id_t) calloc(1, sizeof(*ctx)); + if(!ctx) { + *min = GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + if(strstr(creds, "KRB5")) + ctx->have_krb5 = 1; + + if(strstr(creds, "NTLM")) + ctx->have_ntlm = 1; + + if(ctx->have_krb5) + ctx->sent = KRB5; + else if(ctx->have_ntlm) + ctx->sent = NTLM1; + else { + free(ctx); + *min = GSS_NO_MECH; + return GSS_S_FAILURE; + } + + strcpy(ctx->creds, creds); + ctx->flags = req_flags; + } + + token = malloc(length); + if(!token) { + free(ctx); + *min = GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + /* Token format: creds:target:type:padding */ + /* Note: this is using the *real* snprintf() and not the curl provided + one */ + used = (size_t) snprintf(token, length, "%s:%s:%d:", creds, + (char *) target_name, ctx->sent); + + if(used >= length) { + free(token); + free(ctx); + *min = GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + /* Overwrite null terminator */ + memset(token + used, 'A', length - used); + + *context_handle = ctx; + + output_token->value = token; + output_token->length = length; + + return GSS_S_CONTINUE_NEEDED; +} + +OM_uint32 gss_delete_sec_context(OM_uint32 *min, + gss_ctx_id_t *context_handle, + gss_buffer_t output_token) +{ + (void)output_token; + + if(!min) + return GSS_S_FAILURE; + + if(!context_handle) { + *min = GSS_INVALID_CTX; + return GSS_S_FAILURE; + } + + free(*context_handle); + *context_handle = NULL; + *min = 0; + + return GSS_S_COMPLETE; +} + +OM_uint32 gss_release_buffer(OM_uint32 *min, + gss_buffer_t buffer) +{ + if(min) + *min = 0; + + if(buffer && buffer->length) { + free(buffer->value); + buffer->length = 0; + } + + return GSS_S_COMPLETE; +} + +OM_uint32 gss_import_name(OM_uint32 *min, + const gss_buffer_t input_name_buffer, + const gss_OID input_name_type, + gss_name_t *output_name) +{ + char *name = NULL; + (void)input_name_type; + + if(!min) + return GSS_S_FAILURE; + + if(!input_name_buffer || !output_name) { + *min = GSS_INVALID_ARGS; + return GSS_S_FAILURE; + } + + name = my_strndup(input_name_buffer->value, input_name_buffer->length); + if(!name) { + *min = GSS_NO_MEMORY; + return GSS_S_FAILURE; + } + + *output_name = (gss_name_t) name; + *min = 0; + + return GSS_S_COMPLETE; +} + +OM_uint32 gss_release_name(OM_uint32 *min, + gss_name_t *input_name) +{ + if(min) + *min = 0; + + if(input_name) + free(*input_name); + + return GSS_S_COMPLETE; +} + +OM_uint32 gss_display_status(OM_uint32 *min, + OM_uint32 status_value, + int status_type, + const gss_OID mech_type, + OM_uint32 *message_context, + gss_buffer_t status_string) +{ + const char maj_str[] = "Stub GSS error"; + (void)mech_type; + if(min) + *min = 0; + + if(message_context) + *message_context = 0; + + if(status_string) { + status_string->value = NULL; + status_string->length = 0; + + if(status_value >= GSS_LAST) + return GSS_S_FAILURE; + + switch(status_type) { + case GSS_C_GSS_CODE: + status_string->value = strdup(maj_str); + break; + case GSS_C_MECH_CODE: + status_string->value = strdup(min_err_table[status_value]); + break; + default: + return GSS_S_FAILURE; + } + + if(status_string->value) + status_string->length = strlen(status_string->value); + else + return GSS_S_FAILURE; + } + + return GSS_S_COMPLETE; +} + +/* Stubs returning error */ + +OM_uint32 gss_display_name(OM_uint32 *min, + gss_const_name_t input_name, + gss_buffer_t output_name_buffer, + gss_OID *output_name_type) +{ + (void)min; + (void)input_name; + (void)output_name_buffer; + (void)output_name_type; + return GSS_S_FAILURE; +} + +OM_uint32 gss_inquire_context(OM_uint32 *min, + gss_const_ctx_id_t context_handle, + gss_name_t *src_name, + gss_name_t *targ_name, + OM_uint32 *lifetime_rec, + gss_OID *mech_type, + OM_uint32 *ctx_flags, + int *locally_initiated, + int *open_context) +{ + (void)min; + (void)context_handle; + (void)src_name; + (void)targ_name; + (void)lifetime_rec; + (void)mech_type; + (void)ctx_flags; + (void)locally_initiated; + (void)open_context; + return GSS_S_FAILURE; +} + +OM_uint32 gss_wrap(OM_uint32 *min, + gss_const_ctx_id_t context_handle, + int conf_req_flag, + gss_qop_t qop_req, + const gss_buffer_t input_message_buffer, + int *conf_state, + gss_buffer_t output_message_buffer) +{ + (void)min; + (void)context_handle; + (void)conf_req_flag; + (void)qop_req; + (void)input_message_buffer; + (void)conf_state; + (void)output_message_buffer; + return GSS_S_FAILURE; +} + +OM_uint32 gss_unwrap(OM_uint32 *min, + gss_const_ctx_id_t context_handle, + const gss_buffer_t input_message_buffer, + gss_buffer_t output_message_buffer, + int *conf_state, + gss_qop_t *qop_state) +{ + (void)min; + (void)context_handle; + (void)input_message_buffer; + (void)output_message_buffer; + (void)conf_state; + (void)qop_state; + return GSS_S_FAILURE; +} + +OM_uint32 gss_seal(OM_uint32 *min, + gss_ctx_id_t context_handle, + int conf_req_flag, + int qop_req, + gss_buffer_t input_message_buffer, + int *conf_state, + gss_buffer_t output_message_buffer) +{ + (void)min; + (void)context_handle; + (void)conf_req_flag; + (void)qop_req; + (void)input_message_buffer; + (void)conf_state; + (void)output_message_buffer; + return GSS_S_FAILURE; +} + +OM_uint32 gss_unseal(OM_uint32 *min, + gss_ctx_id_t context_handle, + gss_buffer_t input_message_buffer, + gss_buffer_t output_message_buffer, + int *conf_state, + int *qop_state) +{ + (void)min; + (void)context_handle; + (void)input_message_buffer; + (void)output_message_buffer; + (void)conf_state; + (void)qop_state; + return GSS_S_FAILURE; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/stub_gssapi.h b/local-test-curl-delta-01/afc-curl/tests/libtest/stub_gssapi.h new file mode 100644 index 0000000000000000000000000000000000000000..d29c69e8a16bde65000c659f8d7ddaabca58a12e --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/stub_gssapi.h @@ -0,0 +1,184 @@ +#ifndef HEADER_CURL_GSSAPI_STUBS_H +#define HEADER_CURL_GSSAPI_STUBS_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 + * + ***************************************************************************/ + +/* Roughly based on Heimdal's gssapi.h */ + +#include +#include + +#define GSS_ERROR(status) (status & 0x80000000) + +#define GSS_S_COMPLETE 0 +#define GSS_S_FAILURE (0x80000000) +#define GSS_S_CONTINUE_NEEDED (1ul) + +#define GSS_C_QOP_DEFAULT 0 +#define GSS_C_NO_OID ((gss_OID) 0) +#define GSS_C_NO_NAME ((gss_name_t) 0) +#define GSS_C_NO_BUFFER ((gss_buffer_t) 0) +#define GSS_C_NO_CONTEXT ((gss_ctx_id_t) 0) +#define GSS_C_NO_CREDENTIAL ((gss_cred_id_t) 0) +#define GSS_C_NO_CHANNEL_BINDINGS ((gss_channel_bindings_t) 0) + +#define GSS_C_NULL_OID GSS_C_NO_OID + +#define GSS_C_EMPTY_BUFFER {0, NULL} + +#define GSS_C_AF_INET 2 + +#define GSS_C_GSS_CODE 1 +#define GSS_C_MECH_CODE 2 + +#define GSS_C_DELEG_FLAG 1 +#define GSS_C_MUTUAL_FLAG 2 +#define GSS_C_REPLAY_FLAG 4 +#define GSS_C_CONF_FLAG 16 +#define GSS_C_INTEG_FLAG 32 + +/* + * Expiration time of 2^32-1 seconds means infinite lifetime for a + * credential or security context + */ +#define GSS_C_INDEFINITE 0xfffffffful + +#define GSS_C_NT_HOSTBASED_SERVICE NULL + +typedef uint32_t OM_uint32; + +typedef OM_uint32 gss_qop_t; + +typedef struct gss_buffer_desc_struct { + size_t length; + void *value; +} gss_buffer_desc, *gss_buffer_t; + +struct gss_cred_id_t_desc_struct; +typedef struct gss_cred_id_t_desc_struct *gss_cred_id_t; +typedef const struct gss_cred_id_t_desc_struct *gss_const_cred_id_t; + +struct gss_ctx_id_t_desc_struct; +typedef struct gss_ctx_id_t_desc_struct *gss_ctx_id_t; +typedef const struct gss_ctx_id_t_desc_struct *gss_const_ctx_id_t; + +struct gss_name_t_desc_struct; +typedef struct gss_name_t_desc_struct *gss_name_t; +typedef const struct gss_name_t_desc_struct *gss_const_name_t; + +typedef struct gss_OID_desc_struct { + OM_uint32 length; + void *elements; +} gss_OID_desc, *gss_OID; + +typedef struct gss_channel_bindings_struct { + OM_uint32 initiator_addrtype; + gss_buffer_desc initiator_address; + OM_uint32 acceptor_addrtype; + gss_buffer_desc acceptor_address; + gss_buffer_desc application_data; +} *gss_channel_bindings_t; + +OM_uint32 gss_release_buffer(OM_uint32 * /* minor_status */, + gss_buffer_t /* buffer */); + +OM_uint32 gss_init_sec_context(OM_uint32 * /* minor_status */, + gss_const_cred_id_t /* initiator_cred_handle */, + gss_ctx_id_t * /* context_handle */, + gss_const_name_t /* target_name */, + const gss_OID /* mech_type */, + OM_uint32 /* req_flags */, + OM_uint32 /* time_req */, + const gss_channel_bindings_t /* input_chan_bindings */, + const gss_buffer_t /* input_token */, + gss_OID * /* actual_mech_type */, + gss_buffer_t /* output_token */, + OM_uint32 * /* ret_flags */, + OM_uint32 * /* time_rec */); + +OM_uint32 gss_delete_sec_context(OM_uint32 * /* minor_status */, + gss_ctx_id_t * /* context_handle */, + gss_buffer_t /* output_token */); + +OM_uint32 gss_inquire_context(OM_uint32 * /* minor_status */, + gss_const_ctx_id_t /* context_handle */, + gss_name_t * /* src_name */, + gss_name_t * /* targ_name */, + OM_uint32 * /* lifetime_rec */, + gss_OID * /* mech_type */, + OM_uint32 * /* ctx_flags */, + int * /* locally_initiated */, + int * /* open_context */); + +OM_uint32 gss_wrap(OM_uint32 * /* minor_status */, + gss_const_ctx_id_t /* context_handle */, + int /* conf_req_flag */, + gss_qop_t /* qop_req */, + const gss_buffer_t /* input_message_buffer */, + int * /* conf_state */, + gss_buffer_t /* output_message_buffer */); + +OM_uint32 gss_unwrap(OM_uint32 * /* minor_status */, + gss_const_ctx_id_t /* context_handle */, + const gss_buffer_t /* input_message_buffer */, + gss_buffer_t /* output_message_buffer */, + int * /* conf_state */, + gss_qop_t * /* qop_state */); + +OM_uint32 gss_seal(OM_uint32 * /* minor_status */, + gss_ctx_id_t /* context_handle n */, + int /* conf_req_flag */, + int /* qop_req */, + gss_buffer_t /* input_message_buffer */, + int * /* conf_state */, + gss_buffer_t /* output_message_buffer */); + +OM_uint32 gss_unseal(OM_uint32 * /* minor_status */, + gss_ctx_id_t /* context_handle */, + gss_buffer_t /* input_message_buffer */, + gss_buffer_t /* output_message_buffer */, + int * /* conf_state */, + int * /* qop_state */); + +OM_uint32 gss_import_name(OM_uint32 * /* minor_status */, + const gss_buffer_t /* input_name_buffer */, + const gss_OID /* input_name_type */, + gss_name_t * /* output_name */); + +OM_uint32 gss_release_name(OM_uint32 * /* minor_status */, + gss_name_t * /* input_name */); + +OM_uint32 gss_display_name(OM_uint32 * /* minor_status */, + gss_const_name_t /* input_name */, + gss_buffer_t /* output_name_buffer */, + gss_OID * /* output_name_type */); + +OM_uint32 gss_display_status(OM_uint32 * /* minor_status */, + OM_uint32 /* status_value */, + int /* status_type */, + const gss_OID /* mech_type */, + OM_uint32 * /* message_context */, + gss_buffer_t /* status_string */); + +#endif /* HEADER_CURL_GSSAPI_STUBS_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test.h b/local-test-curl-delta-01/afc-curl/tests/libtest/test.h new file mode 100644 index 0000000000000000000000000000000000000000..28673c6f9d27a834ddca7b58f43ee9fb8811efe9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test.h @@ -0,0 +1,522 @@ +#ifndef HEADER_CURL_TEST_H +#define HEADER_CURL_TEST_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 + * + ***************************************************************************/ + +/* Now include the curl_setup.h file from libcurl's private libdir (the source + version, but that might include "curl_config.h" from the build dir so we + need both of them in the include path), so that we get good in-depth + knowledge about the system we're building this on */ + +#define CURL_NO_OLDIES + +#include "curl_setup.h" + +#include + +#ifdef HAVE_SYS_SELECT_H +/* since so many tests use select(), we can just as well include it here */ +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif + +#include "curl_printf.h" + +#ifdef _WIN32 +#define sleep(sec) Sleep ((sec)*1000) +#endif + +#define test_setopt(A,B,C) \ + if((res = curl_easy_setopt((A), (B), (C))) != CURLE_OK) \ + goto test_cleanup + +#define test_multi_setopt(A,B,C) \ + if((res = curl_multi_setopt((A), (B), (C))) != CURLE_OK) \ + goto test_cleanup + +extern char *libtest_arg2; /* set by first.c to the argv[2] or NULL */ +extern char *libtest_arg3; /* set by first.c to the argv[3] or NULL */ + +/* argc and argv as passed in to the main() function */ +extern int test_argc; +extern char **test_argv; + +extern struct timeval tv_test_start; /* for test timing */ + +extern int select_wrapper(int nfds, fd_set *rd, fd_set *wr, fd_set *exc, + struct timeval *tv); + +extern void wait_ms(int ms); /* wait this many milliseconds */ + +#ifndef CURLTESTS_BUNDLED_TEST_H +extern CURLcode test(char *URL); /* the actual test function provided by each + individual libXXX.c file */ +#endif + +extern char *hexdump(const unsigned char *buffer, size_t len); + +extern int unitfail; + +/* +** TEST_ERR_* values must be greater than CURL_LAST CURLcode in order +** to avoid confusion with any CURLcode or CURLMcode. These TEST_ERR_* +** codes are returned to signal test specific situations and should +** not get mixed with CURLcode or CURLMcode values. +** +** For portability reasons TEST_ERR_* values should be less than 127. +*/ + +#define TEST_ERR_MAJOR_BAD (CURLcode) 126 +#define TEST_ERR_RUNS_FOREVER (CURLcode) 125 +#define TEST_ERR_EASY_INIT (CURLcode) 124 +#define TEST_ERR_MULTI (CURLcode) 123 +#define TEST_ERR_NUM_HANDLES (CURLcode) 122 +#define TEST_ERR_SELECT (CURLcode) 121 +#define TEST_ERR_SUCCESS (CURLcode) 120 +#define TEST_ERR_FAILURE (CURLcode) 119 +#define TEST_ERR_USAGE (CURLcode) 118 +#define TEST_ERR_FOPEN (CURLcode) 117 +#define TEST_ERR_FSTAT (CURLcode) 116 +#define TEST_ERR_BAD_TIMEOUT (CURLcode) 115 + +/* +** Macros for test source code readability/maintainability. +** +** All of the following macros require that an int data type 'res' variable +** exists in scope where macro is used, and that it has been initialized to +** zero before the macro is used. +** +** exe_* and chk_* macros are helper macros not intended to be used from +** outside of this header file. Arguments 'Y' and 'Z' of these represent +** source code file and line number, while Arguments 'A', 'B', etc, are +** the arguments used to actually call a libcurl function. +** +** All easy_* and multi_* macros call a libcurl function and evaluate if +** the function has succeeded or failed. When the function succeeds 'res' +** variable is not set nor cleared and program continues normal flow. On +** the other hand if function fails 'res' variable is set and a jump to +** label 'test_cleanup' is performed. +** +** Every easy_* and multi_* macros have a res_easy_* and res_multi_* macro +** counterpart that operates in the same way with the exception that no +** jump takes place in case of failure. res_easy_* and res_multi_* macros +** should be immediately followed by checking if 'res' variable has been +** set. +** +** 'res' variable when set will hold a CURLcode, CURLMcode, or any of the +** TEST_ERR_* values defined above. It is advisable to return this value +** as test result. +*/ + +/* ---------------------------------------------------------------- */ + +#define exe_easy_init(A,Y,Z) do { \ + if(((A) = curl_easy_init()) == NULL) { \ + fprintf(stderr, "%s:%d curl_easy_init() failed\n", (Y), (Z)); \ + res = TEST_ERR_EASY_INIT; \ + } \ +} while(0) + +#define res_easy_init(A) \ + exe_easy_init((A), (__FILE__), (__LINE__)) + +#define chk_easy_init(A,Y,Z) do { \ + exe_easy_init((A), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define easy_init(A) \ + chk_easy_init((A), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_init(A,Y,Z) do { \ + if(((A) = curl_multi_init()) == NULL) { \ + fprintf(stderr, "%s:%d curl_multi_init() failed\n", (Y), (Z)); \ + res = TEST_ERR_MULTI; \ + } \ +} while(0) + +#define res_multi_init(A) \ + exe_multi_init((A), (__FILE__), (__LINE__)) + +#define chk_multi_init(A,Y,Z) do { \ + exe_multi_init((A), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_init(A) \ + chk_multi_init((A), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_easy_setopt(A,B,C,Y,Z) do { \ + CURLcode ec; \ + if((ec = curl_easy_setopt((A), (B), (C))) != CURLE_OK) { \ + fprintf(stderr, "%s:%d curl_easy_setopt() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_easy_strerror(ec)); \ + res = ec; \ + } \ +} while(0) + +#define res_easy_setopt(A, B, C) \ + exe_easy_setopt((A), (B), (C), (__FILE__), (__LINE__)) + +#define chk_easy_setopt(A, B, C, Y, Z) do { \ + exe_easy_setopt((A), (B), (C), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define easy_setopt(A, B, C) \ + chk_easy_setopt((A), (B), (C), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_setopt(A, B, C, Y, Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_setopt((A), (B), (C))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_setopt() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ +} while(0) + +#define res_multi_setopt(A,B,C) \ + exe_multi_setopt((A), (B), (C), (__FILE__), (__LINE__)) + +#define chk_multi_setopt(A,B,C,Y,Z) do { \ + exe_multi_setopt((A), (B), (C), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_setopt(A,B,C) \ + chk_multi_setopt((A), (B), (C), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_add_handle(A,B,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_add_handle((A), (B))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_add_handle() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ +} while(0) + +#define res_multi_add_handle(A, B) \ + exe_multi_add_handle((A), (B), (__FILE__), (__LINE__)) + +#define chk_multi_add_handle(A, B, Y, Z) do { \ + exe_multi_add_handle((A), (B), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_add_handle(A, B) \ + chk_multi_add_handle((A), (B), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_remove_handle(A,B,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_remove_handle((A), (B))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_remove_handle() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ +} while(0) + +#define res_multi_remove_handle(A, B) \ + exe_multi_remove_handle((A), (B), (__FILE__), (__LINE__)) + +#define chk_multi_remove_handle(A, B, Y, Z) do { \ + exe_multi_remove_handle((A), (B), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + + +#define multi_remove_handle(A, B) \ + chk_multi_remove_handle((A), (B), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_perform(A,B,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_perform((A), (B))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_perform() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ + else if(*((B)) < 0) { \ + fprintf(stderr, "%s:%d curl_multi_perform() succeeded, " \ + "but returned invalid running_handles value (%d)\n", \ + (Y), (Z), (int)*((B))); \ + res = TEST_ERR_NUM_HANDLES; \ + } \ +} while(0) + +#define res_multi_perform(A, B) \ + exe_multi_perform((A), (B), (__FILE__), (__LINE__)) + +#define chk_multi_perform(A, B, Y, Z) do { \ + exe_multi_perform((A), (B), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_perform(A,B) \ + chk_multi_perform((A), (B), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_fdset(A, B, C, D, E, Y, Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_fdset((A), (B), (C), (D), (E))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_fdset() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ + else if(*((E)) < -1) { \ + fprintf(stderr, "%s:%d curl_multi_fdset() succeeded, " \ + "but returned invalid max_fd value (%d)\n", \ + (Y), (Z), (int)*((E))); \ + res = TEST_ERR_NUM_HANDLES; \ + } \ +} while(0) + +#define res_multi_fdset(A, B, C, D, E) \ + exe_multi_fdset((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +#define chk_multi_fdset(A, B, C, D, E, Y, Z) do { \ + exe_multi_fdset((A), (B), (C), (D), (E), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ + } while(0) + +#define multi_fdset(A, B, C, D, E) \ + chk_multi_fdset((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_timeout(A,B,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_timeout((A), (B))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_timeout() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_BAD_TIMEOUT; \ + } \ + else if(*((B)) < -1L) { \ + fprintf(stderr, "%s:%d curl_multi_timeout() succeeded, " \ + "but returned invalid timeout value (%ld)\n", \ + (Y), (Z), (long)*((B))); \ + res = TEST_ERR_BAD_TIMEOUT; \ + } \ +} while(0) + +#define res_multi_timeout(A, B) \ + exe_multi_timeout((A), (B), (__FILE__), (__LINE__)) + +#define chk_multi_timeout(A, B, Y, Z) do { \ + exe_multi_timeout((A), (B), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ + } while(0) + +#define multi_timeout(A, B) \ + chk_multi_timeout((A), (B), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_poll(A,B,C,D,E,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_poll((A), (B), (C), (D), (E))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_poll() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ + else if(*((E)) < 0) { \ + fprintf(stderr, "%s:%d curl_multi_poll() succeeded, " \ + "but returned invalid numfds value (%d)\n", \ + (Y), (Z), (int)*((E))); \ + res = TEST_ERR_NUM_HANDLES; \ + } \ +} while(0) + +#define res_multi_poll(A, B, C, D, E) \ + exe_multi_poll((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +#define chk_multi_poll(A, B, C, D, E, Y, Z) do { \ + exe_multi_poll((A), (B), (C), (D), (E), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_poll(A, B, C, D, E) \ + chk_multi_poll((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_multi_wakeup(A,Y,Z) do { \ + CURLMcode ec; \ + if((ec = curl_multi_wakeup((A))) != CURLM_OK) { \ + fprintf(stderr, "%s:%d curl_multi_wakeup() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_multi_strerror(ec)); \ + res = TEST_ERR_MULTI; \ + } \ +} while(0) + +#define res_multi_wakeup(A) \ + exe_multi_wakeup((A), (__FILE__), (__LINE__)) + +#define chk_multi_wakeup(A, Y, Z) do { \ + exe_multi_wakeup((A), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ +} while(0) + +#define multi_wakeup(A) \ + chk_multi_wakeup((A), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_select_test(A, B, C, D, E, Y, Z) do { \ + int ec; \ + if(select_wrapper((A), (B), (C), (D), (E)) == -1) { \ + ec = SOCKERRNO; \ + fprintf(stderr, "%s:%d select() failed, with " \ + "errno %d (%s)\n", \ + (Y), (Z), ec, strerror(ec)); \ + res = TEST_ERR_SELECT; \ + } \ + } while(0) + +#define res_select_test(A, B, C, D, E) \ + exe_select_test((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +#define chk_select_test(A, B, C, D, E, Y, Z) do { \ + exe_select_test((A), (B), (C), (D), (E), (Y), (Z)); \ + if(res) \ + goto test_cleanup; \ + } while(0) + +#define select_test(A, B, C, D, E) \ + chk_select_test((A), (B), (C), (D), (E), (__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define start_test_timing() do { \ + tv_test_start = tutil_tvnow(); \ +} while(0) + +#define exe_test_timedout(Y,Z) do { \ + long timediff = tutil_tvdiff(tutil_tvnow(), tv_test_start); \ + if(timediff > (TEST_HANG_TIMEOUT)) { \ + fprintf(stderr, "%s:%d ABORTING TEST, since it seems " \ + "that it would have run forever (%ld ms > %ld ms)\n", \ + (Y), (Z), timediff, (long) (TEST_HANG_TIMEOUT)); \ + res = TEST_ERR_RUNS_FOREVER; \ + } \ +} while(0) + +#define res_test_timedout() \ + exe_test_timedout((__FILE__), (__LINE__)) + +#define chk_test_timedout(Y, Z) do { \ + exe_test_timedout(Y, Z); \ + if(res) \ + goto test_cleanup; \ + } while(0) + +#define abort_on_test_timeout() \ + chk_test_timedout((__FILE__), (__LINE__)) + +/* ---------------------------------------------------------------- */ + +#define exe_global_init(A,Y,Z) do { \ + CURLcode ec; \ + if((ec = curl_global_init((A))) != CURLE_OK) { \ + fprintf(stderr, "%s:%d curl_global_init() failed, " \ + "with code %d (%s)\n", \ + (Y), (Z), (int)ec, curl_easy_strerror(ec)); \ + res = ec; \ + } \ +} while(0) + +#define res_global_init(A) \ + exe_global_init((A), (__FILE__), (__LINE__)) + +#define chk_global_init(A, Y, Z) do { \ + exe_global_init((A), (Y), (Z)); \ + if(res) \ + return res; \ + } while(0) + +/* global_init() is different than other macros. In case of + failure it 'return's instead of going to 'test_cleanup'. */ + +#define global_init(A) \ + chk_global_init((A), (__FILE__), (__LINE__)) + +#ifndef CURLTESTS_BUNDLED_TEST_H +#define NO_SUPPORT_BUILT_IN \ + CURLcode test(char *URL) \ + { \ + (void)URL; \ + fprintf(stderr, "Missing support\n"); \ + return (CURLcode)1; \ + } +#endif + +/* ---------------------------------------------------------------- */ + +#endif /* HEADER_CURL_TEST_H */ + +#ifdef CURLTESTS_BUNDLED_TEST_H +extern CURLcode test(char *URL); /* the actual test function provided by each + individual libXXX.c file */ + +#undef NO_SUPPORT_BUILT_IN +#define NO_SUPPORT_BUILT_IN \ + CURLcode test(char *URL) \ + { \ + (void)URL; \ + fprintf(stderr, "Missing support\n"); \ + return (CURLcode)1; \ + } +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test1013.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/test1013.pl new file mode 100644 index 0000000000000000000000000000000000000000..6d10a3223a534d5344b6ae96e9fc62829f64d728 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test1013.pl @@ -0,0 +1,74 @@ +#!/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 +# +########################################################################### +# Determine if curl-config --protocols/--features matches the +# curl --version protocols/features +if ( $#ARGV != 2 ) +{ + print "Usage: $0 curl-config-script curl-version-output-file features|protocols\n"; + exit 3; +} + +my $what=$ARGV[2]; + +# Read the output of curl --version +my $curl_protocols=""; +open(CURL, "$ARGV[1]") || die "Can't get curl $what list\n"; +while( ) +{ + $curl_protocols = $_ if ( /$what:/i ); +} +close CURL; + +$curl_protocols =~ s/\r//; +$curl_protocols =~ /\w+: (.*)$/; +@curl = split / /,$1; + +# Read the output of curl-config +my @curl_config; +open(CURLCONFIG, "sh $ARGV[0] --$what|") || die "Can't get curl-config $what list\n"; +while( ) +{ + chomp; + $_ = lc($_) if($what eq "protocols"); # accept uppercase protocols in curl-config + push @curl_config, $_; +} +close CURLCONFIG; + +# allow order mismatch to handle autotools builds with no 'sort -f' available +if($what eq "features") { + @curl = sort @curl; + @curl_config = sort @curl_config; +} + +my $curlproto = join ' ', @curl; +my $curlconfigproto = join ' ', @curl_config; + +my $different = $curlproto ne $curlconfigproto; +if ($different) { + print "Mismatch in $what lists:\n"; + print "curl: $curlproto\n"; + print "curl-config: $curlconfigproto\n"; +} +exit $different; diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test1022.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/test1022.pl new file mode 100644 index 0000000000000000000000000000000000000000..583b8f8562c033e2190d659034b103f7e3c0ca4c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test1022.pl @@ -0,0 +1,77 @@ +#!/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 +# +########################################################################### +# Determine if curl-config --version matches the curl --version +if ( $#ARGV != 2 ) +{ + print "Usage: $0 curl-config-script curl-version-output-file version|vernum\n"; + exit 3; +} + +my $what=$ARGV[2]; + +# Read the output of curl --version +open(CURL, "$ARGV[1]") || die "Can't open curl --version list in $ARGV[1]\n"; +$_ = ; +chomp; +/libcurl\/([\.\d]+((-DEV)|(-\d+))?)/; +my $version = $1; +close CURL; + +my $curlconfigversion; + +# Read the output of curl-config --version/--vernum +open(CURLCONFIG, "sh $ARGV[0] --$what|") || die "Can't get curl-config --$what list\n"; +$_ = ; +chomp; +my $filever=$_; +if ( $what eq "version" ) { + if($filever =~ /^libcurl ([\.\d]+((-DEV)|(-\d+))?)$/) { + $curlconfigversion = $1; + } + else { + $curlconfigversion = "illegal value"; + } +} +else { # "vernum" case + # Convert hex version to decimal for comparison's sake + if($filever =~ /^(..)(..)(..)$/) { + $curlconfigversion = hex($1) . "." . hex($2) . "." . hex($3); + } + else { + $curlconfigversion = "illegal value"; + } + + # Strip off the -DEV from the curl version if it's there + $version =~ s/-\w*$//; +} +close CURLCONFIG; + +my $different = $version ne $curlconfigversion; +if ($different || !$version) { + print "Mismatch in --version:\n"; + print "curl: $version\n"; + print "curl-config: $curlconfigversion\n"; + exit 1; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test307.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/test307.pl new file mode 100644 index 0000000000000000000000000000000000000000..862f0e972982ce7844f289520dccf9104e55f614 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test307.pl @@ -0,0 +1,42 @@ +#!/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 +# +########################################################################### +# Determine if the given curl executable supports the 'openssl' SSL engine +if ( $#ARGV != 0 ) +{ + print "Usage: $0 curl-executable\n"; + exit 3; +} +if (!open(CURL, "@ARGV[0] -s --engine list|")) +{ + print "Can't get SSL engine list\n"; + exit 2; +} +while( ) +{ + exit 0 if ( /openssl/ ); +} +close CURL; +print "openssl engine not supported\n"; +exit 1; diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test610.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/test610.pl new file mode 100644 index 0000000000000000000000000000000000000000..0ef9330684753e07e4708aeb59f83a6466f30229 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test610.pl @@ -0,0 +1,56 @@ +#!/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 +# +########################################################################### +# Perform simple file and directory manipulation in a portable way +if ( $#ARGV <= 0 ) +{ + print "Usage: $0 mkdir|rmdir|rm|move|gone path1 [path2] [more commands...]\n"; + exit 1; +} + +use File::Copy; +while(@ARGV) { + my $cmd = shift @ARGV; + my $arg = shift @ARGV; + if ($cmd eq "mkdir") { + mkdir $arg || die "$!"; + } + elsif ($cmd eq "rmdir") { + rmdir $arg || die "$!"; + } + elsif ($cmd eq "rm") { + unlink $arg || die "$!"; + } + elsif ($cmd eq "move") { + my $arg2 = shift @ARGV; + move($arg,$arg2) || die "$!"; + } + elsif ($cmd eq "gone") { + ! -e $arg || die "Path $arg exists"; + } else { + print "Unsupported command $cmd\n"; + exit 1; + } +} +exit 0; diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/test613.pl b/local-test-curl-delta-01/afc-curl/tests/libtest/test613.pl new file mode 100644 index 0000000000000000000000000000000000000000..dee3b175431fcca7b5805cea16f4ef90d9f7803f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/test613.pl @@ -0,0 +1,146 @@ +#!/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 +# +########################################################################### +# Prepare a directory with known files and clean up afterwards +use Time::Local; + +if ( $#ARGV < 1 ) +{ + print "Usage: $0 prepare|postprocess dir [logfile]\n"; + exit 1; +} + +# expects an error message on stdout +sub errout { + print $_[0] . "\n"; + exit 1; +} + +if ($ARGV[0] eq "prepare") +{ + my $dirname = $ARGV[1]; + mkdir $dirname || errout "$!"; + chdir $dirname; + + # Create the files in alphabetical order, to increase the chances + # of receiving a consistent set of directory contents regardless + # of whether the server alphabetizes the results or not. + mkdir "asubdir" || errout "$!"; + chmod 0777, "asubdir"; + + open(FILE, ">plainfile.txt") || errout "$!"; + binmode FILE; + print FILE "Test file to support curl test suite\n"; + close(FILE); + # The mtime is specifically chosen to be an even number so that it can be + # represented exactly on a FAT filesystem. + utime time, timegm(0,0,12,1,0,100), "plainfile.txt"; + chmod 0666, "plainfile.txt"; + + open(FILE, ">rofile.txt") || errout "$!"; + binmode FILE; + print FILE "Read-only test file to support curl test suite\n"; + close(FILE); + # The mtime is specifically chosen to be an even number so that it can be + # represented exactly on a FAT filesystem. + utime time, timegm(0,0,12,31,11,100), "rofile.txt"; + chmod 0444, "rofile.txt"; + + exit 0; +} +elsif ($ARGV[0] eq "postprocess") +{ + my $dirname = $ARGV[1]; + my $logfile = $ARGV[2]; + + # Clean up the test directory + unlink "$dirname/rofile.txt"; + unlink "$dirname/plainfile.txt"; + rmdir "$dirname/asubdir"; + + rmdir $dirname || die "$!"; + + if ($logfile && -s $logfile) { + # Process the directory file to remove all information that + # could be inconsistent from one test run to the next (e.g. + # file date) or may be unsupported on some platforms (e.g. + # Windows). Also, since 7.17.0, the sftp directory listing + # format can be dependent on the server (with a recent + # enough version of libssh2) so this script must also + # canonicalize the format. Here are examples of the general + # format supported: + # -r--r--r-- 12 ausername grp 47 Dec 31 2000 rofile.txt + # -r--r--r-- 1 1234 4321 47 Dec 31 2000 rofile.txt + # The "canonical" format is similar to the first (which is + # the one generated on a typical Linux installation): + # -r-?r-?r-? 12 U U 47 Dec 31 2000 rofile.txt + + my @canondir; + open(IN, "<$logfile") || die "$!"; + while () { + /^(.)(..).(..).(..).\s*(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+\s+\S+\s+\S+)\s+(.*)$/; + if ($1 eq "d") { + # Skip current and parent directory listing, because some SSH + # servers (eg. OpenSSH for Windows) are not listing those + if ($8 eq "." || $8 eq "..") { + next; + } + # Erase all directory metadata except for the name, as it is not + # consistent for across all test systems and filesystems + push @canondir, "d????????? N U U N ??? N NN:NN $8\n"; + } elsif ($1 eq "-") { + # Replace missing group and other permissions with user + # permissions (eg. on Windows) due to them being shown as * + my ($u, $g, $o) = ($2, $3, $4); + if($g eq "**") { + $g = $u; + } + if($o eq "**") { + $o = $u; + } + # Erase user and group names, as they are not consistent across + # all test systems + my $line = sprintf("%s%s?%s?%s?%5d U U %15d %s %s\n", $1,$u,$g,$o,$5,$6,$7,$8); + push @canondir, $line; + } else { + # Unexpected format; just pass it through and let the test fail + push @canondir, $_; + } + } + close(IN); + + @canondir = sort {substr($a,57) cmp substr($b,57)} @canondir; + my $newfile = $logfile . ".new"; + open(OUT, ">$newfile") || die "$!"; + print OUT join('', @canondir); + close(OUT); + + unlink $logfile; + rename $newfile, $logfile; + } + + exit 0; +} +print "Unsupported command $ARGV[0]\n"; +exit 1; diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.c b/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4cb5bb47b6d52528040fa97844d9949c097fce --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.c @@ -0,0 +1,144 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "test.h" +#include "testutil.h" +#include "testtrace.h" +#include "memdebug.h" + +struct libtest_trace_cfg libtest_debug_config; + +static time_t epoch_offset; /* for test time tracing */ +static int known_offset; /* for test time tracing */ + +static +void libtest_debug_dump(const char *timebuf, const char *text, FILE *stream, + const unsigned char *ptr, size_t size, int nohex) +{ + size_t i; + size_t c; + + unsigned int width = 0x10; + + if(nohex) + /* without the hex output, we can fit more on screen */ + width = 0x40; + + fprintf(stream, "%s%s, %zu bytes (0x%zx)\n", timebuf, text, + size, size); + + for(i = 0; i < size; i += width) { + + fprintf(stream, "%04zx: ", i); + + if(!nohex) { + /* hex not disabled, show it */ + for(c = 0; c < width; c++) + if(i + c < size) + fprintf(stream, "%02x ", ptr[i + c]); + else + fputs(" ", stream); + } + + for(c = 0; (c < width) && (i + c < size); c++) { + /* check for 0D0A; if found, skip past and start a new line of output */ + if(nohex && + (i + c + 1 < size) && (ptr[i + c] == 0x0D) && + (ptr[i + c + 1] == 0x0A)) { + i += (c + 2 - width); + break; + } + fprintf(stream, "%c", ((ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80)) ? + ptr[i + c] : '.'); + /* check again for 0D0A, to avoid an extra \n if it's at width */ + if(nohex && + (i + c + 2 < size) && (ptr[i + c + 1] == 0x0D) && + (ptr[i + c + 2] == 0x0A)) { + i += (c + 3 - width); + break; + } + } + fputc('\n', stream); /* newline */ + } + fflush(stream); +} + +int libtest_debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, void *userp) +{ + struct libtest_trace_cfg *trace_cfg = userp; + const char *text; + struct timeval tv; + char timebuf[20]; + char *timestr; + time_t secs; + + (void)handle; + + timebuf[0] = '\0'; + timestr = &timebuf[0]; + + if(trace_cfg->tracetime) { + struct tm *now; + tv = tutil_tvnow(); + if(!known_offset) { + epoch_offset = time(NULL) - tv.tv_sec; + known_offset = 1; + } + secs = epoch_offset + tv.tv_sec; + now = localtime(&secs); /* not thread safe but we don't care */ + msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld ", + now->tm_hour, now->tm_min, now->tm_sec, (long)tv.tv_usec); + } + + switch(type) { + case CURLINFO_TEXT: + fprintf(stderr, "%s== Info: %s", timestr, (char *)data); + return 0; + case CURLINFO_HEADER_OUT: + text = "=> Send header"; + break; + case CURLINFO_DATA_OUT: + text = "=> Send data"; + break; + case CURLINFO_SSL_DATA_OUT: + text = "=> Send SSL data"; + break; + case CURLINFO_HEADER_IN: + text = "<= Recv header"; + break; + case CURLINFO_DATA_IN: + text = "<= Recv data"; + break; + case CURLINFO_SSL_DATA_IN: + text = "<= Recv SSL data"; + break; + default: /* in case a new one is introduced to shock us */ + return 0; + } + + libtest_debug_dump(timebuf, text, stderr, (unsigned char *)data, size, + trace_cfg->nohex); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.h b/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.h new file mode 100644 index 0000000000000000000000000000000000000000..d7087c5366fa5acbbc779a26d5701c659bacae2f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/testtrace.h @@ -0,0 +1,37 @@ +#ifndef HEADER_LIBTEST_TESTTRACE_H +#define HEADER_LIBTEST_TESTTRACE_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 libtest_trace_cfg { + int tracetime; /* 0 represents FALSE, anything else TRUE */ + int nohex; /* 0 represents FALSE, anything else TRUE */ +}; + +extern struct libtest_trace_cfg libtest_debug_config; + +int libtest_debug_cb(CURL *handle, curl_infotype type, + char *data, size_t size, void *userp); + +#endif /* HEADER_LIBTEST_TESTTRACE_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.c b/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.c new file mode 100644 index 0000000000000000000000000000000000000000..49c15d5951a500886d74676855791d03282555e4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.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" +#include +#include "testutil.h" +#include "memdebug.h" + +#if defined(_WIN32) + +struct timeval tutil_tvnow(void) +{ + /* + ** GetTickCount() is available on _all_ Windows versions from W95 up + ** to nowadays. Returns milliseconds elapsed since last system boot, + ** increases monotonically and wraps once 49.7 days have elapsed. + */ + struct timeval now; + DWORD milliseconds = GetTickCount(); + now.tv_sec = (long)(milliseconds / 1000); + now.tv_usec = (long)((milliseconds % 1000) * 1000); + return now; +} + +#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC) + +struct timeval tutil_tvnow(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. + */ + struct timeval now; + struct timespec tsnow; + if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) { + now.tv_sec = tsnow.tv_sec; + now.tv_usec = (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); +#else + else { + now.tv_sec = time(NULL); + now.tv_usec = 0; + } +#endif + return now; +} + +#elif defined(HAVE_GETTIMEOFDAY) + +struct timeval tutil_tvnow(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; + (void)gettimeofday(&now, NULL); + return now; +} + +#else + +struct timeval tutil_tvnow(void) +{ + /* + ** time() returns the value of time in seconds since the Epoch. + */ + struct timeval now; + now.tv_sec = time(NULL); + now.tv_usec = 0; + return now; +} + +#endif + +/* + * Make sure that the first argument is the more recent time, as otherwise + * we'll get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds. + */ +long tutil_tvdiff(struct timeval newer, struct timeval older) +{ + return (long)(newer.tv_sec-older.tv_sec)*1000+ + (long)(newer.tv_usec-older.tv_usec)/1000; +} + +/* + * Same as tutil_tvdiff but with full usec resolution. + * + * Returns: the time difference in seconds with subsecond resolution. + */ +double tutil_tvdiff_secs(struct timeval newer, struct timeval older) +{ + if(newer.tv_sec != older.tv_sec) + return (double)(newer.tv_sec-older.tv_sec)+ + (double)(newer.tv_usec-older.tv_usec)/1000000.0; + return (double)(newer.tv_usec-older.tv_usec)/1000000.0; +} + +#ifdef _WIN32 +HMODULE win32_load_system_library(const TCHAR *filename) +{ +#ifdef CURL_WINDOWS_UWP + (void)filename; + return NULL; +#else + size_t filenamelen = _tcslen(filename); + size_t systemdirlen = GetSystemDirectory(NULL, 0); + size_t written; + TCHAR *path; + + if(!filenamelen || filenamelen > 32768 || + !systemdirlen || systemdirlen > 32768) + return NULL; + + /* systemdirlen includes null character */ + path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen)); + if(!path) + return NULL; + + /* if written >= systemdirlen then nothing was written */ + written = GetSystemDirectory(path, (unsigned int)systemdirlen); + if(!written || written >= systemdirlen) + return NULL; + + if(path[written - 1] != _T('\\')) + path[written++] = _T('\\'); + + _tcscpy(path + written, filename); + + return LoadLibrary(path); +#endif +} +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.h b/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.h new file mode 100644 index 0000000000000000000000000000000000000000..9f063795aba1251052b47a48195c438a0a0a6535 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/libtest/testutil.h @@ -0,0 +1,49 @@ +#ifndef HEADER_CURL_LIBTEST_TESTUTIL_H +#define HEADER_CURL_LIBTEST_TESTUTIL_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 timeval tutil_tvnow(void); + +/* + * Make sure that the first argument (t1) is the more recent time and t2 is + * the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds. + */ +long tutil_tvdiff(struct timeval t1, struct timeval t2); + +/* + * Same as tutil_tvdiff but with full usec resolution. + * + * Returns: the time difference in seconds with subsecond resolution. + */ +double tutil_tvdiff_secs(struct timeval t1, struct timeval t2); + +#ifdef _WIN32 +HMODULE win32_load_system_library(const TCHAR *filename); +#endif + +#endif /* HEADER_CURL_LIBTEST_TESTUTIL_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/server/.checksrc b/local-test-curl-delta-01/afc-curl/tests/server/.checksrc new file mode 100644 index 0000000000000000000000000000000000000000..8f67fd2a3eeea96b6ebf45f0c684c8d4fa727ac3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/.checksrc @@ -0,0 +1 @@ +enable STRNCPY diff --git a/local-test-curl-delta-01/afc-curl/tests/server/.gitignore b/local-test-curl-delta-01/afc-curl/tests/server/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..57c685b4e367cbd2e6dfe3b28bd11a19e719425c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/.gitignore @@ -0,0 +1,13 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +getpart +resolve +rtspd +sockfilt +sws +tftpd +socksd +disabled +mqttd diff --git a/local-test-curl-delta-01/afc-curl/tests/server/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/server/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed8c302dc6660697856575d95d9be8239cf160f5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/CMakeLists.txt @@ -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 +# +########################################################################### + +# Get 'noinst_PROGRAMS', '_SOURCES' variables +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + +set_source_files_properties("../../lib/memdebug.c" "../../lib/curl_multibyte.c" PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) + +foreach(_target IN LISTS noinst_PROGRAMS) + set(_target_name "${_target}") + add_executable(${_target_name} EXCLUDE_FROM_ALL ${${_target}_SOURCES}) + add_dependencies(testdeps ${_target_name}) + target_include_directories(${_target_name} PRIVATE + "${PROJECT_BINARY_DIR}/lib" # for "curl_config.h" + "${PROJECT_SOURCE_DIR}/lib" # for "curl_setup.h" + "${PROJECT_SOURCE_DIR}/src" # for "tool_xattr.h" in disabled_SOURCES + ) + target_link_libraries(${_target_name} ${CURL_LIBS}) + # Test servers simply are standalone programs that do not use libcurl + # library. For convenience and to ease portability of these servers, + # some source code files from the libcurl subdirectory are also used + # to build the servers. In order to achieve proper linkage of these + # files on Windows targets it is necessary to build the test servers + # with CURL_STATICLIB defined, independently of how libcurl is built. + if(WIN32) + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_STATICLIB") + endif() + # getaddrinfo/freeaddrinfo overrides break UNITY build by overriding them + # before including system headers. Server code doesn't need these overrides, + # so it's safe to disable them globally. + set_property(TARGET ${_target_name} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_NO_GETADDRINFO_OVERRIDE") + set_target_properties(${_target_name} PROPERTIES + OUTPUT_NAME "${_target}" + PROJECT_LABEL "Test server ${_target}") +endforeach() diff --git a/local-test-curl-delta-01/afc-curl/tests/server/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/server/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..1a844f121bd3d30a3b9bd0e74782799c7a31e22f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/Makefile.am @@ -0,0 +1,66 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 + +# 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 "borrowed" files + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib + +disabled_CPPFLAGS = $(AM_CPPFLAGS) \ + -I$(top_srcdir)/src + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +if DOING_NATIVE_WINDOWS +AM_CPPFLAGS += -DCURL_STATICLIB +endif +AM_CPPFLAGS += -DCURL_NO_GETADDRINFO_OVERRIDE + +# Makefile.inc provides neat definitions +include Makefile.inc + +EXTRA_DIST = base64.pl CMakeLists.txt .checksrc + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl $(srcdir)/*.[ch] + +if DEBUGBUILD +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif diff --git a/local-test-curl-delta-01/afc-curl/tests/server/Makefile.inc b/local-test-curl-delta-01/afc-curl/tests/server/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..575a4d121c7c72b363e7bdb415949bf58689cb8f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/Makefile.inc @@ -0,0 +1,112 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +noinst_PROGRAMS = getpart resolve rtspd sockfilt sws tftpd \ + socksd disabled mqttd + +CURLX_SRCS = \ + ../../lib/mprintf.c \ + ../../lib/nonblock.c \ + ../../lib/strtoofft.c \ + ../../lib/warnless.c \ + ../../lib/timediff.c \ + ../../lib/dynbuf.c \ + ../../lib/strdup.c \ + ../../lib/strcase.c \ + ../../lib/curl_multibyte.c + +CURLX_HDRS = \ + ../../lib/curlx.h \ + ../../lib/nonblock.h \ + ../../lib/strtoofft.h \ + ../../lib/warnless.h \ + ../../lib/timediff.h \ + ../../lib/curl_ctype.h \ + ../../lib/dynbuf.h \ + ../../lib/strdup.h \ + ../../lib/curl_multibyte.h + +USEFUL = \ + getpart.c \ + getpart.h \ + server_setup.h \ + ../../lib/base64.c \ + ../../lib/curl_base64.h \ + ../../lib/memdebug.c \ + ../../lib/memdebug.h + +UTIL = \ + util.c \ + util.h + +getpart_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) \ + testpart.c +getpart_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +getpart_CFLAGS = $(AM_CFLAGS) + +resolve_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + resolve.c +resolve_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +resolve_CFLAGS = $(AM_CFLAGS) + +rtspd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h \ + rtspd.c +rtspd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +rtspd_CFLAGS = $(AM_CFLAGS) + +sockfilt_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h \ + sockfilt.c \ + ../../lib/inet_pton.c +sockfilt_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +sockfilt_CFLAGS = $(AM_CFLAGS) + +socksd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h socksd.c \ + ../../lib/inet_pton.c +socksd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +socksd_CFLAGS = $(AM_CFLAGS) + +mqttd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h mqttd.c \ + ../../lib/inet_pton.c +mqttd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +mqttd_CFLAGS = $(AM_CFLAGS) + +sws_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h \ + sws.c \ + ../../lib/inet_pton.c +sws_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +sws_CFLAGS = $(AM_CFLAGS) + +tftpd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ + server_sockaddr.h \ + tftpd.c \ + tftp.h +tftpd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ +tftpd_CFLAGS = $(AM_CFLAGS) + +disabled_SOURCES = disabled.c diff --git a/local-test-curl-delta-01/afc-curl/tests/server/base64.pl b/local-test-curl-delta-01/afc-curl/tests/server/base64.pl new file mode 100644 index 0000000000000000000000000000000000000000..885e6f41995a26654d08125b5ddbefb910ad4f7d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/base64.pl @@ -0,0 +1,32 @@ +#!/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 MIME::Base64 qw(encode_base64); + +my $buf; +while(read(STDIN, $buf, 60*57)) { + my $enc = encode_base64($buf); + print "$enc"; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/disabled.c b/local-test-curl-delta-01/afc-curl/tests/server/disabled.c new file mode 100644 index 0000000000000000000000000000000000000000..057ab36fc615d0cfceefdc9271fed78077df4ebb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/disabled.c @@ -0,0 +1,130 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 purpose of this tool is to figure out which, if any, features that are + * disabled which should otherwise exist and work. These aren't visible in + * regular curl -V output. + * + * Disabled protocols are visible in curl_version_info() and are not included + * in this table. + */ + +#include "curl_setup.h" +#include "multihandle.h" /* for ENABLE_WAKEUP */ +#include "tool_xattr.h" /* for USE_XATTR */ +#include "curl_sha512_256.h" /* for CURL_HAVE_SHA512_256 */ +#include + +static const char *disabled[]={ +#ifdef CURL_DISABLE_BINDLOCAL + "bindlocal", +#endif +#ifdef CURL_DISABLE_COOKIES + "cookies", +#endif +#ifdef CURL_DISABLE_BASIC_AUTH + "basic-auth", +#endif +#ifdef CURL_DISABLE_BEARER_AUTH + "bearer-auth", +#endif +#ifdef CURL_DISABLE_DIGEST_AUTH + "digest-auth", +#endif +#ifdef CURL_DISABLE_NEGOTIATE_AUTH + "negotiate-auth", +#endif +#ifdef CURL_DISABLE_AWS + "aws", +#endif +#ifdef CURL_DISABLE_DOH + "DoH", +#endif +#ifdef CURL_DISABLE_HTTP_AUTH + "HTTP-auth", +#endif +#ifdef CURL_DISABLE_MIME + "Mime", +#endif +#ifdef CURL_DISABLE_NETRC + "netrc", +#endif +#ifdef CURL_DISABLE_PARSEDATE + "parsedate", +#endif +#ifdef CURL_DISABLE_PROXY + "proxy", +#endif +#ifdef CURL_DISABLE_SHUFFLE_DNS + "shuffle-dns", +#endif +#ifdef CURL_DISABLE_TYPECHECK + "typecheck", +#endif +#ifdef CURL_DISABLE_VERBOSE_STRINGS + "verbose-strings", +#endif +#ifndef ENABLE_WAKEUP + "wakeup", +#endif +#ifdef CURL_DISABLE_HEADERS_API + "headers-api", +#endif +#ifndef USE_XATTR + "xattr", +#endif +#ifdef CURL_DISABLE_FORM_API + "form-api", +#endif +#if (SIZEOF_TIME_T < 5) + "large-time", +#endif +#ifndef CURL_HAVE_SHA512_256 + "sha512-256", +#endif +#ifdef _WIN32 +#if defined(CURL_WINDOWS_UWP) || \ + defined(CURL_DISABLE_CA_SEARCH) || defined(CURL_CA_SEARCH_SAFE) + "win32-ca-searchpath", +#endif +#ifndef CURL_CA_SEARCH_SAFE + "win32-ca-search-safe", +#endif +#endif + NULL +}; + +int main(int argc, char **argv) +{ + int i; + + (void) argc; + (void) argv; + + for(i = 0; disabled[i]; i++) + printf("%s\n", disabled[i]); + + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/getpart.c b/local-test-curl-delta-01/afc-curl/tests/server/getpart.c new file mode 100644 index 0000000000000000000000000000000000000000..5bfaad5882b6c08a1fb891944a192d583490c392 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/getpart.c @@ -0,0 +1,488 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" + +#include "getpart.h" + +#include "curlx.h" /* from the private lib dir */ + +#include "curl_base64.h" +#include "curl_memory.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#define EAT_SPACE(p) while(*(p) && ISSPACE(*(p))) (p)++ + +#define EAT_WORD(p) while(*(p) && !ISSPACE(*(p)) && ('>' != *(p))) (p)++ + +#ifdef DEBUG_GETPART +#define show(x) printf x +#else +#define show(x) Curl_nop_stmt +#endif + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(push) +# pragma warning(disable:4232) /* MSVC extension, dllimport identity */ +#endif + +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)strdup; +curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; +#if defined(_WIN32) && defined(UNICODE) +curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; +#endif + +#if defined(_MSC_VER) && defined(_DLL) +# pragma warning(pop) +#endif + + +/* + * line_length() + * + * Counts the number of characters in a line including a new line. + * Unlike strlen() it does not stop at nul bytes. + * + */ +static size_t line_length(const char *buffer, int bytestocheck) +{ + size_t length = 1; + + while(*buffer != '\n' && --bytestocheck) { + length++; + buffer++; + } + if(*buffer != '\n') { + /* + * We didn't find a new line so the last byte must be a + * '\0' character inserted by fgets() which we should not + * count. + */ + length--; + } + + return length; +} + +/* + * readline() + * + * Reads a complete line from a file into a dynamically allocated buffer. + * + * Calling function may call this multiple times with same 'buffer' + * and 'bufsize' pointers to avoid multiple buffer allocations. Buffer + * will be reallocated and 'bufsize' increased until whole line fits in + * buffer before returning it. + * + * Calling function is responsible to free allocated buffer. + * + * This function may return: + * GPE_OUT_OF_MEMORY + * GPE_END_OF_FILE + * GPE_OK + */ + +static int readline(char **buffer, size_t *bufsize, size_t *length, + FILE *stream) +{ + size_t offset = 0; + char *newptr; + + if(!*buffer) { + *buffer = calloc(1, 128); + if(!*buffer) + return GPE_OUT_OF_MEMORY; + *bufsize = 128; + } + + for(;;) { + int bytestoread = curlx_uztosi(*bufsize - offset); + + if(!fgets(*buffer + offset, bytestoread, stream)) + return (offset != 0) ? GPE_OK : GPE_END_OF_FILE; + + *length = offset + line_length(*buffer + offset, bytestoread); + if(*(*buffer + *length - 1) == '\n') + break; + offset = *length; + if(*length < *bufsize - 1) + continue; + + newptr = realloc(*buffer, *bufsize * 2); + if(!newptr) + return GPE_OUT_OF_MEMORY; + memset(&newptr[*bufsize], 0, *bufsize); + *buffer = newptr; + *bufsize *= 2; + } + + return GPE_OK; +} + +/* + * appenddata() + * + * This appends data from a given source buffer to the end of the used part of + * a destination buffer. Arguments relative to the destination buffer are, the + * address of a pointer to the destination buffer 'dst_buf', the length of data + * in destination buffer excluding potential null string termination 'dst_len', + * the allocated size of destination buffer 'dst_alloc'. All three destination + * buffer arguments may be modified by this function. Arguments relative to the + * source buffer are, a pointer to the source buffer 'src_buf' and indication + * whether the source buffer is base64 encoded or not 'src_b64'. + * + * If the source buffer is indicated to be base64 encoded, this appends the + * decoded data, binary or whatever, to the destination. The source buffer + * may not hold binary data, only a null terminated string is valid content. + * + * Destination buffer will be enlarged and relocated as needed. + * + * Calling function is responsible to provide preallocated destination + * buffer and also to deallocate it when no longer needed. + * + * This function may return: + * GPE_OUT_OF_MEMORY + * GPE_OK + */ + +static int appenddata(char **dst_buf, /* dest buffer */ + size_t *dst_len, /* dest buffer data length */ + size_t *dst_alloc, /* dest buffer allocated size */ + char *src_buf, /* source buffer */ + size_t src_len, /* source buffer length */ + int src_b64) /* != 0 if source is base64 encoded */ +{ + size_t need_alloc = 0; + + if(!src_len) + return GPE_OK; + + need_alloc = src_len + *dst_len + 1; + + if(src_b64) { + if(src_buf[src_len - 1] == '\r') + src_len--; + + if(src_buf[src_len - 1] == '\n') + src_len--; + } + + /* enlarge destination buffer if required */ + if(need_alloc > *dst_alloc) { + size_t newsize = need_alloc * 2; + char *newptr = realloc(*dst_buf, newsize); + if(!newptr) { + return GPE_OUT_OF_MEMORY; + } + *dst_alloc = newsize; + *dst_buf = newptr; + } + + /* memcpy to support binary blobs */ + memcpy(*dst_buf + *dst_len, src_buf, src_len); + *dst_len += src_len; + *(*dst_buf + *dst_len) = '\0'; + + return GPE_OK; +} + +static int decodedata(char **buf, /* dest buffer */ + size_t *len) /* dest buffer data length */ +{ + CURLcode error = CURLE_OK; + unsigned char *buf64 = NULL; + size_t src_len = 0; + + if(!*len) + return GPE_OK; + + /* base64 decode the given buffer */ + error = Curl_base64_decode(*buf, &buf64, &src_len); + if(error) + return GPE_OUT_OF_MEMORY; + + if(!src_len) { + /* + ** currently there is no way to tell apart an OOM condition in + ** Curl_base64_decode() from zero length decoded data. For now, + ** let's just assume it is an OOM condition, currently we have + ** no input for this function that decodes to zero length data. + */ + free(buf64); + + return GPE_OUT_OF_MEMORY; + } + + /* memcpy to support binary blobs */ + memcpy(*buf, buf64, src_len); + *len = src_len; + *(*buf + src_len) = '\0'; + + free(buf64); + + return GPE_OK; +} + +/* + * getpart() + * + * This returns whole contents of specified XML-like section and subsection + * from the given file. This is mostly used to retrieve a specific part from + * a test definition file for consumption by test suite servers. + * + * Data is returned in a dynamically allocated buffer, a pointer to this data + * and the size of the data is stored at the addresses that caller specifies. + * + * If the returned data is a string the returned size will be the length of + * the string excluding null termination. Otherwise it will just be the size + * of the returned binary data. + * + * Calling function is responsible to free returned buffer. + * + * This function may return: + * GPE_NO_BUFFER_SPACE + * GPE_OUT_OF_MEMORY + * GPE_OK + */ + +int getpart(char **outbuf, size_t *outlen, + const char *main, const char *sub, FILE *stream) +{ +# define MAX_TAG_LEN 200 + char couter[MAX_TAG_LEN + 1]; /* current outermost section */ + char cmain[MAX_TAG_LEN + 1]; /* current main section */ + char csub[MAX_TAG_LEN + 1]; /* current sub section */ + char ptag[MAX_TAG_LEN + 1]; /* potential tag */ + char patt[MAX_TAG_LEN + 1]; /* potential attributes */ + char *buffer = NULL; + char *ptr; + char *end; + union { + ssize_t sig; + size_t uns; + } len; + size_t bufsize = 0; + size_t outalloc = 256; + size_t datalen; + int in_wanted_part = 0; + int base64 = 0; + int nonewline = 0; + int error; + + enum { + STATE_OUTSIDE = 0, + STATE_OUTER = 1, + STATE_INMAIN = 2, + STATE_INSUB = 3, + STATE_ILLEGAL = 4 + } state = STATE_OUTSIDE; + + *outlen = 0; + *outbuf = malloc(outalloc); + if(!*outbuf) + return GPE_OUT_OF_MEMORY; + *(*outbuf) = '\0'; + + couter[0] = cmain[0] = csub[0] = ptag[0] = patt[0] = '\0'; + + while((error = readline(&buffer, &bufsize, &datalen, stream)) == GPE_OK) { + + ptr = buffer; + EAT_SPACE(ptr); + + if('<' != *ptr) { + if(in_wanted_part) { + show(("=> %s", buffer)); + error = appenddata(outbuf, outlen, &outalloc, buffer, datalen, + base64); + if(error) + break; + } + continue; + } + + ptr++; + + if('/' == *ptr) { + /* + ** closing section tag + */ + + ptr++; + end = ptr; + EAT_WORD(end); + len.sig = end - ptr; + if(len.sig > MAX_TAG_LEN) { + error = GPE_NO_BUFFER_SPACE; + break; + } + memcpy(ptag, ptr, len.uns); + ptag[len.uns] = '\0'; + + if((STATE_INSUB == state) && !strcmp(csub, ptag)) { + /* end of current sub section */ + state = STATE_INMAIN; + csub[0] = '\0'; + if(in_wanted_part) { + /* end of wanted part */ + in_wanted_part = 0; + + /* Do we need to base64 decode the data? */ + if(base64) { + error = decodedata(outbuf, outlen); + if(error) + return error; + } + if(nonewline) + (*outlen)--; + break; + } + } + else if((STATE_INMAIN == state) && !strcmp(cmain, ptag)) { + /* end of current main section */ + state = STATE_OUTER; + cmain[0] = '\0'; + if(in_wanted_part) { + /* end of wanted part */ + in_wanted_part = 0; + + /* Do we need to base64 decode the data? */ + if(base64) { + error = decodedata(outbuf, outlen); + if(error) + return error; + } + if(nonewline) + (*outlen)--; + break; + } + } + else if((STATE_OUTER == state) && !strcmp(couter, ptag)) { + /* end of outermost file section */ + state = STATE_OUTSIDE; + couter[0] = '\0'; + if(in_wanted_part) { + /* end of wanted part */ + in_wanted_part = 0; + break; + } + } + + } + else if(!in_wanted_part) { + /* + ** opening section tag + */ + + /* get potential tag */ + end = ptr; + EAT_WORD(end); + len.sig = end - ptr; + if(len.sig > MAX_TAG_LEN) { + error = GPE_NO_BUFFER_SPACE; + break; + } + memcpy(ptag, ptr, len.uns); + ptag[len.uns] = '\0'; + + /* ignore comments, doctypes and xml declarations */ + if(('!' == ptag[0]) || ('?' == ptag[0])) { + show(("* ignoring (%s)", buffer)); + continue; + } + + /* get all potential attributes */ + ptr = end; + EAT_SPACE(ptr); + end = ptr; + while(*end && ('>' != *end)) + end++; + len.sig = end - ptr; + if(len.sig > MAX_TAG_LEN) { + error = GPE_NO_BUFFER_SPACE; + break; + } + memcpy(patt, ptr, len.uns); + patt[len.uns] = '\0'; + + if(STATE_OUTSIDE == state) { + /* outermost element () */ + strcpy(couter, ptag); + state = STATE_OUTER; + continue; + } + else if(STATE_OUTER == state) { + /* start of a main section */ + strcpy(cmain, ptag); + state = STATE_INMAIN; + continue; + } + else if(STATE_INMAIN == state) { + /* start of a sub section */ + strcpy(csub, ptag); + state = STATE_INSUB; + if(!strcmp(cmain, main) && !strcmp(csub, sub)) { + /* start of wanted part */ + in_wanted_part = 1; + if(strstr(patt, "base64=")) + /* bit rough test, but "mostly" functional, */ + /* treat wanted part data as base64 encoded */ + base64 = 1; + if(strstr(patt, "nonewline=")) { + show(("* setting nonewline\n")); + nonewline = 1; + } + } + continue; + } + + } + + if(in_wanted_part) { + show(("=> %s", buffer)); + error = appenddata(outbuf, outlen, &outalloc, buffer, datalen, base64); + if(error) + break; + } + + } /* while */ + + free(buffer); + + if(error != GPE_OK) { + if(error == GPE_END_OF_FILE) + error = GPE_OK; + else { + free(*outbuf); + *outbuf = NULL; + *outlen = 0; + } + } + + return error; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/getpart.h b/local-test-curl-delta-01/afc-curl/tests/server/getpart.h new file mode 100644 index 0000000000000000000000000000000000000000..e9323d4c9a48350a8059a8ed1027d22fc1c145bb --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/getpart.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_SERVER_GETPART_H +#define HEADER_CURL_SERVER_GETPART_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 "server_setup.h" + +#define GPE_NO_BUFFER_SPACE -2 +#define GPE_OUT_OF_MEMORY -1 +#define GPE_OK 0 +#define GPE_END_OF_FILE 1 + +int getpart(char **outbuf, size_t *outlen, + const char *main, const char *sub, FILE *stream); + +#endif /* HEADER_CURL_SERVER_GETPART_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/server/mqttd.c b/local-test-curl-delta-01/afc-curl/tests/server/mqttd.c new file mode 100644 index 0000000000000000000000000000000000000000..dc56d99a9e636310872fe54989482322ce1cc570 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/mqttd.c @@ -0,0 +1,1100 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" +#include +#include +#include "util.h" + +/* Function + * + * Accepts a TCP connection on a custom port (IPv4 or IPv6). Speaks MQTT. + * + * Read commands from FILE (set with --config). The commands control how to + * act and is reset to defaults each client TCP connect. + * + * Config file keywords: + * + * TODO + */ + +/* based on sockfilt.c */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "inet_pton.h" +#include "server_sockaddr.h" +#include "warnless.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef EAGAIN +#define EAGAIN 11 /* errno.h value */ +#undef ENOMEM +#define ENOMEM 12 /* errno.h value */ +#undef EINVAL +#define EINVAL 22 /* errno.h value */ +#endif + +#define DEFAULT_PORT 1883 /* MQTT default port */ + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/mqttd.log" +#endif + +#ifndef DEFAULT_CONFIG +#define DEFAULT_CONFIG "mqttd.config" +#endif + +#define MQTT_MSG_CONNECT 0x10 +#define MQTT_MSG_CONNACK 0x20 +#define MQTT_MSG_PUBLISH 0x30 +#define MQTT_MSG_PUBACK 0x40 +#define MQTT_MSG_SUBSCRIBE 0x82 +#define MQTT_MSG_SUBACK 0x90 +#define MQTT_MSG_DISCONNECT 0xe0 + +#define MQTT_CONNACK_LEN 4 +#define MQTT_SUBACK_LEN 5 +#define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */ + +struct configurable { + unsigned char version; /* initial version byte in the request must match + this */ + bool publish_before_suback; + bool short_publish; + bool excessive_remaining; + unsigned char error_connack; + int testnum; +}; + +#define REQUEST_DUMP "server.input" +#define CONFIG_VERSION 5 + +static struct configurable config; + +const char *serverlogfile = DEFAULT_LOGFILE; +static const char *configfile = DEFAULT_CONFIG; +static const char *logdir = "log"; +static char loglockfile[256]; + +#ifdef USE_IPV6 +static bool use_ipv6 = FALSE; +#endif +static const char *ipv_inuse = "IPv4"; +static unsigned short port = DEFAULT_PORT; + +static void resetdefaults(void) +{ + logmsg("Reset to defaults"); + config.version = CONFIG_VERSION; + config.publish_before_suback = FALSE; + config.short_publish = FALSE; + config.excessive_remaining = FALSE; + config.error_connack = 0; + config.testnum = 0; +} + +static unsigned char byteval(char *value) +{ + unsigned long num = strtoul(value, NULL, 10); + return num & 0xff; +} + +static void getconfig(void) +{ + FILE *fp = fopen(configfile, FOPEN_READTEXT); + resetdefaults(); + if(fp) { + char buffer[512]; + logmsg("parse config file"); + while(fgets(buffer, sizeof(buffer), fp)) { + char key[32]; + char value[32]; + if(2 == sscanf(buffer, "%31s %31s", key, value)) { + if(!strcmp(key, "version")) { + config.version = byteval(value); + logmsg("version [%d] set", config.version); + } + else if(!strcmp(key, "PUBLISH-before-SUBACK")) { + logmsg("PUBLISH-before-SUBACK set"); + config.publish_before_suback = TRUE; + } + else if(!strcmp(key, "short-PUBLISH")) { + logmsg("short-PUBLISH set"); + config.short_publish = TRUE; + } + else if(!strcmp(key, "error-CONNACK")) { + config.error_connack = byteval(value); + logmsg("error-CONNACK = %d", config.error_connack); + } + else if(!strcmp(key, "Testnum")) { + config.testnum = atoi(value); + logmsg("testnum = %d", config.testnum); + } + else if(!strcmp(key, "excessive-remaining")) { + logmsg("excessive-remaining set"); + config.excessive_remaining = TRUE; + } + } + } + fclose(fp); + } + else { + logmsg("No config file '%s' to read", configfile); + } +} + +static void loghex(unsigned char *buffer, ssize_t len) +{ + char data[12000]; + ssize_t i; + unsigned char *ptr = buffer; + char *optr = data; + ssize_t width = 0; + int left = sizeof(data); + + for(i = 0; i < len && (left >= 0); i++) { + msnprintf(optr, left, "%02x", ptr[i]); + width += 2; + optr += 2; + left -= 2; + } + if(width) + logmsg("'%s'", data); +} + +typedef enum { + FROM_CLIENT, + FROM_SERVER +} mqttdir; + +static void logprotocol(mqttdir dir, + const char *prefix, size_t remlen, + FILE *output, + unsigned char *buffer, ssize_t len) +{ + char data[12000] = ""; + ssize_t i; + unsigned char *ptr = buffer; + char *optr = data; + int left = sizeof(data); + + for(i = 0; i < len && (left >= 0); i++) { + msnprintf(optr, left, "%02x", ptr[i]); + optr += 2; + left -= 2; + } + fprintf(output, "%s %s %zx %s\n", + dir == FROM_CLIENT ? "client" : "server", + prefix, remlen, data); +} + + +/* return 0 on success */ +static int connack(FILE *dump, curl_socket_t fd) +{ + unsigned char packet[]={ + MQTT_MSG_CONNACK, 0x02, + 0x00, 0x00 + }; + ssize_t rc; + + packet[3] = config.error_connack; + + rc = swrite(fd, (char *)packet, sizeof(packet)); + if(rc > 0) { + logmsg("WROTE %zd bytes [CONNACK]", rc); + loghex(packet, rc); + logprotocol(FROM_SERVER, "CONNACK", 2, dump, packet, sizeof(packet)); + } + if(rc == sizeof(packet)) { + return 0; + } + return 1; +} + +/* return 0 on success */ +static int suback(FILE *dump, curl_socket_t fd, unsigned short packetid) +{ + unsigned char packet[]={ + MQTT_MSG_SUBACK, 0x03, + 0, 0, /* filled in below */ + 0x00 + }; + ssize_t rc; + packet[2] = (unsigned char)(packetid >> 8); + packet[3] = (unsigned char)(packetid & 0xff); + + rc = swrite(fd, (char *)packet, sizeof(packet)); + if(rc == sizeof(packet)) { + logmsg("WROTE %zd bytes [SUBACK]", rc); + loghex(packet, rc); + logprotocol(FROM_SERVER, "SUBACK", 3, dump, packet, rc); + return 0; + } + return 1; +} + +#ifdef QOS +/* return 0 on success */ +static int puback(FILE *dump, curl_socket_t fd, unsigned short packetid) +{ + unsigned char packet[]={ + MQTT_MSG_PUBACK, 0x00, + 0, 0 /* filled in below */ + }; + ssize_t rc; + packet[2] = (unsigned char)(packetid >> 8); + packet[3] = (unsigned char)(packetid & 0xff); + + rc = swrite(fd, (char *)packet, sizeof(packet)); + if(rc == sizeof(packet)) { + logmsg("WROTE %zd bytes [PUBACK]", rc); + loghex(packet, rc); + logprotocol(FROM_SERVER, dump, packet, rc); + return 0; + } + logmsg("Failed sending [PUBACK]"); + return 1; +} +#endif + +/* return 0 on success */ +static int disconnect(FILE *dump, curl_socket_t fd) +{ + unsigned char packet[]={ + MQTT_MSG_DISCONNECT, 0x00, + }; + ssize_t rc = swrite(fd, (char *)packet, sizeof(packet)); + if(rc == sizeof(packet)) { + logmsg("WROTE %zd bytes [DISCONNECT]", rc); + loghex(packet, rc); + logprotocol(FROM_SERVER, "DISCONNECT", 0, dump, packet, rc); + return 0; + } + logmsg("Failed sending [DISCONNECT]"); + return 1; +} + + + +/* + do + + encodedByte = X MOD 128 + + X = X DIV 128 + + // if there are more data to encode, set the top bit of this byte + + if ( X > 0 ) + + encodedByte = encodedByte OR 128 + + endif + + 'output' encodedByte + + while ( X > 0 ) + +*/ + +/* return number of bytes used */ +static size_t encode_length(size_t packetlen, + unsigned char *remlength) /* 4 bytes */ +{ + size_t bytes = 0; + unsigned char encode; + + do { + encode = packetlen % 0x80; + packetlen /= 0x80; + if(packetlen) + encode |= 0x80; + + remlength[bytes++] = encode; + + if(bytes > 3) { + logmsg("too large packet!"); + return 0; + } + } while(packetlen); + + return bytes; +} + + +static size_t decode_length(unsigned char *buf, + size_t buflen, size_t *lenbytes) +{ + size_t len = 0; + size_t mult = 1; + size_t i; + unsigned char encoded = 0x80; + + for(i = 0; (i < buflen) && (encoded & 0x80); i++) { + encoded = buf[i]; + len += (encoded & 0x7f) * mult; + mult *= 0x80; + } + + if(lenbytes) + *lenbytes = i; + + return len; +} + + +/* return 0 on success */ +static int publish(FILE *dump, + curl_socket_t fd, unsigned short packetid, + char *topic, char *payload, size_t payloadlen) +{ + size_t topiclen = strlen(topic); + unsigned char *packet; + size_t payloadindex; + size_t remaininglength = topiclen + 2 + payloadlen; + size_t packetlen; + size_t sendamount; + ssize_t rc; + unsigned char rembuffer[4]; + size_t encodedlen; + + if(config.excessive_remaining) { + /* manually set illegal remaining length */ + rembuffer[0] = 0xff; + rembuffer[1] = 0xff; + rembuffer[2] = 0xff; + rembuffer[3] = 0x80; /* maximum allowed here by spec is 0x7f */ + encodedlen = 4; + } + else + encodedlen = encode_length(remaininglength, rembuffer); + + /* one packet type byte (possibly two more for packetid) */ + packetlen = remaininglength + encodedlen + 1; + packet = malloc(packetlen); + if(!packet) + return 1; + + packet[0] = MQTT_MSG_PUBLISH; /* TODO: set QoS? */ + memcpy(&packet[1], rembuffer, encodedlen); + + (void)packetid; + /* packet_id if QoS is set */ + + packet[1 + encodedlen] = (unsigned char)(topiclen >> 8); + packet[2 + encodedlen] = (unsigned char)(topiclen & 0xff); + memcpy(&packet[3 + encodedlen], topic, topiclen); + + payloadindex = 3 + topiclen + encodedlen; + memcpy(&packet[payloadindex], payload, payloadlen); + + sendamount = packetlen; + if(config.short_publish) + sendamount -= 2; + + rc = swrite(fd, (char *)packet, sendamount); + if(rc > 0) { + logmsg("WROTE %zd bytes [PUBLISH]", rc); + loghex(packet, rc); + logprotocol(FROM_SERVER, "PUBLISH", remaininglength, dump, packet, rc); + } + free(packet); + if((size_t)rc == packetlen) + return 0; + return 1; +} + +#define MAX_TOPIC_LENGTH 65535 +#define MAX_CLIENT_ID_LENGTH 32 + +static char topic[MAX_TOPIC_LENGTH + 1]; + +static int fixedheader(curl_socket_t fd, + unsigned char *bytep, + size_t *remaining_lengthp, + size_t *remaining_length_bytesp) +{ + /* get the fixed header */ + unsigned char buffer[10]; + + /* get the first two bytes */ + ssize_t rc = sread(fd, (char *)buffer, 2); + size_t i; + if(rc < 2) { + logmsg("READ %zd bytes [SHORT!]", rc); + return 1; /* fail */ + } + logmsg("READ %zd bytes", rc); + loghex(buffer, rc); + *bytep = buffer[0]; + + /* if the length byte has the top bit set, get the next one too */ + i = 1; + while(buffer[i] & 0x80) { + i++; + rc = sread(fd, (char *)&buffer[i], 1); + if(rc != 1) { + logmsg("Remaining Length broken"); + return 1; + } + } + *remaining_lengthp = decode_length(&buffer[1], i, remaining_length_bytesp); + logmsg("Remaining Length: %zu [%zu bytes]", *remaining_lengthp, + *remaining_length_bytesp); + return 0; +} + +static curl_socket_t mqttit(curl_socket_t fd) +{ + size_t buff_size = 10*1024; + unsigned char *buffer = NULL; + ssize_t rc; + unsigned char byte; + unsigned short packet_id; + size_t payload_len; + size_t client_id_length; + size_t topic_len; + size_t remaining_length = 0; + size_t bytes = 0; /* remaining length field size in bytes */ + char client_id[MAX_CLIENT_ID_LENGTH]; + long testno; + FILE *stream = NULL; + FILE *dump; + char dumpfile[256]; + + static const char protocol[7] = { + 0x00, 0x04, /* protocol length */ + 'M','Q','T','T', /* protocol name */ + 0x04 /* protocol level */ + }; + msnprintf(dumpfile, sizeof(dumpfile), "%s/%s", logdir, REQUEST_DUMP); + dump = fopen(dumpfile, "ab"); + if(!dump) + goto end; + + getconfig(); + + testno = config.testnum; + + if(testno) + logmsg("Found test number %ld", testno); + + buffer = malloc(buff_size); + if(!buffer) { + logmsg("Out of memory, unable to allocate buffer"); + goto end; + } + + do { + unsigned char usr_flag = 0x80; + unsigned char passwd_flag = 0x40; + unsigned char conn_flags; + const size_t client_id_offset = 12; + size_t start_usr; + size_t start_passwd; + + /* get the fixed header */ + rc = fixedheader(fd, &byte, &remaining_length, &bytes); + if(rc) + break; + + if(remaining_length >= buff_size) { + buff_size = remaining_length; + buffer = realloc(buffer, buff_size); + if(!buffer) { + logmsg("Failed realloc of size %zu", buff_size); + goto end; + } + } + + if(remaining_length) { + /* reading variable header and payload into buffer */ + rc = sread(fd, (char *)buffer, remaining_length); + if(rc > 0) { + logmsg("READ %zd bytes", rc); + loghex(buffer, rc); + } + } + + if(byte == MQTT_MSG_CONNECT) { + logprotocol(FROM_CLIENT, "CONNECT", remaining_length, + dump, buffer, rc); + + if(memcmp(protocol, buffer, sizeof(protocol))) { + logmsg("Protocol preamble mismatch"); + goto end; + } + /* ignore the connect flag byte and two keepalive bytes */ + payload_len = (size_t)(buffer[10] << 8) | buffer[11]; + /* first part of the payload is the client ID */ + client_id_length = payload_len; + + /* checking if user and password flags were set */ + conn_flags = buffer[7]; + + start_usr = client_id_offset + payload_len; + if(usr_flag == (unsigned char)(conn_flags & usr_flag)) { + logmsg("User flag is present in CONN flag"); + payload_len += (size_t)(buffer[start_usr] << 8) | + buffer[start_usr + 1]; + payload_len += 2; /* MSB and LSB for user length */ + } + + start_passwd = client_id_offset + payload_len; + if(passwd_flag == (char)(conn_flags & passwd_flag)) { + logmsg("Password flag is present in CONN flags"); + payload_len += (size_t)(buffer[start_passwd] << 8) | + buffer[start_passwd + 1]; + payload_len += 2; /* MSB and LSB for password length */ + } + + /* check the length of the payload */ + if((ssize_t)payload_len != (rc - 12)) { + logmsg("Payload length mismatch, expected %zx got %zx", + rc - 12, payload_len); + goto end; + } + /* check the length of the client ID */ + else if((client_id_length + 1) > MAX_CLIENT_ID_LENGTH) { + logmsg("Too large client id"); + goto end; + } + memcpy(client_id, &buffer[12], client_id_length); + client_id[client_id_length] = 0; + + logmsg("MQTT client connect accepted: %s", client_id); + + /* The first packet sent from the Server to the Client MUST be a + CONNACK Packet */ + + if(connack(dump, fd)) { + logmsg("failed sending CONNACK"); + goto end; + } + } + else if(byte == MQTT_MSG_SUBSCRIBE) { + int error; + char *data; + size_t datalen; + logprotocol(FROM_CLIENT, "SUBSCRIBE", remaining_length, + dump, buffer, rc); + logmsg("Incoming SUBSCRIBE"); + + if(rc < 6) { + logmsg("Too small SUBSCRIBE"); + goto end; + } + + /* two bytes packet id */ + packet_id = (unsigned short)((buffer[0] << 8) | buffer[1]); + + /* two bytes topic length */ + topic_len = (size_t)(buffer[2] << 8) | buffer[3]; + if(topic_len != (remaining_length - 5)) { + logmsg("Wrong topic length, got %zu expected %zu", + topic_len, remaining_length - 5); + goto end; + } + memcpy(topic, &buffer[4], topic_len); + topic[topic_len] = 0; + + /* there's a QoS byte (two bits) after the topic */ + + logmsg("SUBSCRIBE to '%s' [%d]", topic, packet_id); + stream = test2fopen(testno, logdir); + error = getpart(&data, &datalen, "reply", "data", stream); + if(!error) { + if(!config.publish_before_suback) { + if(suback(dump, fd, packet_id)) { + logmsg("failed sending SUBACK"); + free(data); + goto end; + } + } + if(publish(dump, fd, packet_id, topic, data, datalen)) { + logmsg("PUBLISH failed"); + free(data); + goto end; + } + free(data); + if(config.publish_before_suback) { + if(suback(dump, fd, packet_id)) { + logmsg("failed sending SUBACK"); + goto end; + } + } + } + else { + char *def = (char *)"this is random payload yes yes it is"; + publish(dump, fd, packet_id, topic, def, strlen(def)); + } + disconnect(dump, fd); + } + else if((byte & 0xf0) == (MQTT_MSG_PUBLISH & 0xf0)) { + size_t topiclen; + + logmsg("Incoming PUBLISH"); + logprotocol(FROM_CLIENT, "PUBLISH", remaining_length, + dump, buffer, rc); + + topiclen = (size_t)(buffer[1 + bytes] << 8) | buffer[2 + bytes]; + logmsg("Got %zu bytes topic", topiclen); + /* TODO: verify topiclen */ + +#ifdef QOS + /* TODO: handle packetid if there is one. Send puback if QoS > 0 */ + puback(dump, fd, 0); +#endif + /* expect a disconnect here */ + /* get the request */ + rc = sread(fd, (char *)&buffer[0], 2); + + logmsg("READ %zd bytes [DISCONNECT]", rc); + loghex(buffer, rc); + logprotocol(FROM_CLIENT, "DISCONNECT", 0, dump, buffer, rc); + goto end; + } + else { + /* not supported (yet) */ + goto end; + } + } while(1); + +end: + if(buffer) + free(buffer); + if(dump) + fclose(dump); + if(stream) + fclose(stream); + return CURL_SOCKET_BAD; +} + +/* + sockfdp is a pointer to an established stream or CURL_SOCKET_BAD + + if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must + accept() +*/ +static bool incoming(curl_socket_t listenfd) +{ + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + int clients = 0; /* connected clients */ + + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + +#ifdef HAVE_GETPPID + /* As a last resort, quit if socks5 process becomes orphan. */ + if(getppid() <= 1) { + logmsg("process becomes orphan, exiting"); + return FALSE; + } +#endif + + do { + ssize_t rc; + int error = 0; + curl_socket_t sockfd = listenfd; + int maxfd = (int)sockfd; + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + + /* there's always a socket to wait for */ + FD_SET(sockfd, &fds_read); + + do { + /* select() blocking behavior call on blocking descriptors please */ + rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL); + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + } while((rc == -1) && ((error = SOCKERRNO) == EINTR)); + + if(rc < 0) { + logmsg("select() failed with error: (%d) %s", + error, strerror(error)); + return FALSE; + } + + if(FD_ISSET(sockfd, &fds_read)) { + curl_socket_t newfd = accept(sockfd, NULL, NULL); + if(CURL_SOCKET_BAD == newfd) { + error = SOCKERRNO; + logmsg("accept(%" FMT_SOCKET_T ", NULL, NULL) " + "failed with error: (%d) %s", sockfd, error, sstrerror(error)); + } + else { + logmsg("====> Client connect, fd %" FMT_SOCKET_T ". " + "Read config from %s", newfd, configfile); + set_advisor_read_lock(loglockfile); + (void)mqttit(newfd); /* until done */ + clear_advisor_read_lock(loglockfile); + + logmsg("====> Client disconnect"); + sclose(newfd); + } + } + } while(clients); + + return TRUE; +} + +static curl_socket_t sockdaemon(curl_socket_t sock, + unsigned short *listenport) +{ + /* passive daemon style */ + srvr_sockaddr_union_t listener; + int flag; + int rc; + int totdelay = 0; + int maxretr = 10; + int delay = 20; + int attempt = 0; + int error = 0; + + do { + attempt++; + flag = 1; + rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag)); + if(rc) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + if(maxretr) { + rc = wait_ms(delay); + if(rc) { + /* should not happen */ + logmsg("wait_ms() failed with error: %d", rc); + sclose(sock); + return CURL_SOCKET_BAD; + } + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + sclose(sock); + return CURL_SOCKET_BAD; + } + totdelay += delay; + delay *= 2; /* double the sleep for next attempt */ + } + } + } while(rc && maxretr--); + + if(rc) { + logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", + attempt, totdelay, error, strerror(error)); + logmsg("Continuing anyway..."); + } + + /* When the specified listener port is zero, it is actually a + request to let the system choose a non-zero available port. */ + +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + memset(&listener.sa4, 0, sizeof(listener.sa4)); + listener.sa4.sin_family = AF_INET; + listener.sa4.sin_addr.s_addr = INADDR_ANY; + listener.sa4.sin_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa4)); +#ifdef USE_IPV6 + } + else { + memset(&listener.sa6, 0, sizeof(listener.sa6)); + listener.sa6.sin6_family = AF_INET6; + listener.sa6.sin6_addr = in6addr_any; + listener.sa6.sin6_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa6)); + } +#endif /* USE_IPV6 */ + if(rc) { + error = SOCKERRNO; + logmsg("Error binding socket on port %hu: (%d) %s", + *listenport, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + if(!*listenport) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + la_size = sizeof(localaddr.sa4); +#ifdef USE_IPV6 + else + la_size = sizeof(localaddr.sa6); +#endif + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + *listenport = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + *listenport = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!*listenport) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + sclose(sock); + return CURL_SOCKET_BAD; + } + } + + /* start accepting connections */ + rc = listen(sock, 5); + if(0 != rc) { + error = SOCKERRNO; + logmsg("listen(%" FMT_SOCKET_T ", 5) failed with error: (%d) %s", + sock, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + return sock; +} + + +int main(int argc, char *argv[]) +{ + curl_socket_t sock = CURL_SOCKET_BAD; + curl_socket_t msgsock = CURL_SOCKET_BAD; + int wrotepidfile = 0; + int wroteportfile = 0; + const char *pidname = ".mqttd.pid"; + const char *portname = ".mqttd.port"; + bool juggle_again; + int error; + int arg = 1; + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("mqttd IPv4%s\n", +#ifdef USE_IPV6 + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--config", argv[arg])) { + arg++; + if(argc > arg) + configfile = argv[arg++]; + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--logdir", argv[arg])) { + arg++; + if(argc > arg) + logdir = argv[arg++]; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv6"; + use_ipv6 = TRUE; +#endif + arg++; + } + else if(!strcmp("--ipv4", argv[arg])) { + /* for completeness, we support this option as well */ +#ifdef USE_IPV6 + ipv_inuse = "IPv4"; + use_ipv6 = FALSE; +#endif + arg++; + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + if((endptr != argv[arg] + strlen(argv[arg])) || + ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) { + fprintf(stderr, "mqttd: invalid --port argument (%s)\n", + argv[arg]); + return 0; + } + port = curlx_ultous(ulnum); + arg++; + } + } + else { + puts("Usage: mqttd [option]\n" + " --config [file]\n" + " --version\n" + " --logfile [file]\n" + " --logdir [directory]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --port [port]\n"); + return 0; + } + } + + msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/mqtt-%s.lock", + logdir, SERVERLOGS_LOCKDIR, ipv_inuse); + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); + + setmode(fileno(stdin), O_BINARY); + setmode(fileno(stdout), O_BINARY); + setmode(fileno(stderr), O_BINARY); +#endif + + install_signal_handlers(FALSE); + +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + sock = socket(AF_INET, SOCK_STREAM, 0); +#ifdef USE_IPV6 + else + sock = socket(AF_INET6, SOCK_STREAM, 0); +#endif + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", error, sstrerror(error)); + goto mqttd_cleanup; + } + + { + /* passive daemon style */ + sock = sockdaemon(sock, &port); + if(CURL_SOCKET_BAD == sock) { + goto mqttd_cleanup; + } + msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ + } + + logmsg("Running %s version", ipv_inuse); + logmsg("Listening on port %hu", port); + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) { + goto mqttd_cleanup; + } + + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) { + goto mqttd_cleanup; + } + + do { + juggle_again = incoming(sock); + } while(juggle_again); + +mqttd_cleanup: + + if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) + sclose(msgsock); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + restore_signal_handlers(FALSE); + + if(got_exit_signal) { + logmsg("============> mqttd exits with signal (%d)", exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("============> mqttd quits"); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/resolve.c b/local-test-curl-delta-01/afc-curl/tests/server/resolve.c new file mode 100644 index 0000000000000000000000000000000000000000..96db23b4facd61b99010be6e32355cd383b53ba5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/resolve.c @@ -0,0 +1,155 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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_NO_GETADDRINFO_OVERRIDE +#define CURL_NO_GETADDRINFO_OVERRIDE +#endif + +#include "server_setup.h" + +/* Purpose + * + * Resolve the given name, using system name resolve functions (NOT any + * function provided by libcurl). Used to see if the name exists and thus if + * we can allow a test case to use it for testing. + * + * Like if 'localhost' actual exists etc. + * + */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef _XOPEN_SOURCE_EXTENDED +/* This define is "almost" required to build on HP-UX 11 */ +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "util.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +static bool use_ipv6 = FALSE; +static const char *ipv_inuse = "IPv4"; + +const char *serverlogfile = ""; /* for a util.c function we don't use */ + +int main(int argc, char *argv[]) +{ + int arg = 1; + const char *host = NULL; + int rc = 0; + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("resolve IPv4%s\n", +#if defined(CURLRES_IPV6) + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--ipv6", argv[arg])) { + ipv_inuse = "IPv6"; + use_ipv6 = TRUE; + arg++; + } + else if(!strcmp("--ipv4", argv[arg])) { + /* for completeness, we support this option as well */ + ipv_inuse = "IPv4"; + use_ipv6 = FALSE; + arg++; + } + else { + host = argv[arg++]; + } + } + if(!host) { + puts("Usage: resolve [option] \n" + " --version\n" + " --ipv4" +#if defined(CURLRES_IPV6) + "\n --ipv6" +#endif + ); + return 1; + } + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); +#endif + +#if defined(CURLRES_IPV6) + if(use_ipv6) { + /* Check that the system has IPv6 enabled before checking the resolver */ + curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); + if(s == CURL_SOCKET_BAD) + /* an IPv6 address was requested and we can't get/use one */ + rc = -1; + else { + sclose(s); + } + } + + if(rc == 0) { + /* getaddrinfo() resolve */ + struct addrinfo *ai; + struct addrinfo hints; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = use_ipv6 ? PF_INET6 : PF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = 0; + rc = getaddrinfo(host, "80", &hints, &ai); + if(rc == 0) + freeaddrinfo(ai); + } +#else + if(use_ipv6) { + puts("IPv6 support has been disabled in this program"); + return 1; + } + else { + /* gethostbyname() resolve */ + struct hostent *he; + + he = gethostbyname(host); + + rc = !he; + } +#endif + + if(rc) + printf("Resolving %s '%s' didn't work\n", ipv_inuse, host); + + return !!rc; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/rtspd.c b/local-test-curl-delta-01/afc-curl/tests/server/rtspd.c new file mode 100644 index 0000000000000000000000000000000000000000..9cab12c5ac37a922977f3163dfe05e5c8d5122b6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/rtspd.c @@ -0,0 +1,1408 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" + +/* + * curl's test suite Real Time Streaming Protocol (RTSP) server. + * + * This source file was started based on curl's HTTP test suite server. + */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_NETINET_TCP_H +#include /* for TCP_NODELAY */ +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "util.h" +#include "server_sockaddr.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef ERANGE +#define ERANGE 34 /* errno.h value */ +#endif + +#ifdef USE_IPV6 +static bool use_ipv6 = FALSE; +#endif +static const char *ipv_inuse = "IPv4"; +static int serverlogslocked = 0; + +#define REQBUFSIZ 150000 +#define REQBUFSIZ_TXT "149999" + +static long prevtestno = -1; /* previous test number we served */ +static long prevpartno = -1; /* previous part number we served */ +static bool prevbounce = FALSE; /* instructs the server to increase the part + number for a test in case the identical + testno+partno request shows up again */ + +#define RCMD_NORMALREQ 0 /* default request, use the tests file normally */ +#define RCMD_IDLE 1 /* told to sit idle */ +#define RCMD_STREAM 2 /* told to stream */ + +typedef enum { + RPROT_NONE = 0, + RPROT_RTSP = 1, + RPROT_HTTP = 2 +} reqprot_t; + +#define SET_RTP_PKT_CHN(p,c) ((p)[1] = (char)((c) & 0xFF)) + +#define SET_RTP_PKT_LEN(p,l) (((p)[2] = (char)(((l) >> 8) & 0xFF)), \ + ((p)[3] = (char)((l) & 0xFF))) + +struct httprequest { + char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */ + size_t checkindex; /* where to start checking of the request */ + size_t offset; /* size of the incoming request */ + long testno; /* test number found in the request */ + long partno; /* part number found in the request */ + bool open; /* keep connection open info, as found in the request */ + bool auth_req; /* authentication required, don't wait for body unless + there's an Authorization header */ + bool auth; /* Authorization header present in the incoming request */ + size_t cl; /* Content-Length of the incoming request */ + bool digest; /* Authorization digest header found */ + bool ntlm; /* Authorization NTLM header found */ + int pipe; /* if non-zero, expect this many requests to do a "piped" + request/response */ + int skip; /* if non-zero, the server is instructed to not read this + many bytes from a PUT/POST request. Ie the client sends N + bytes said in Content-Length, but the server only reads N + - skip bytes. */ + int rcmd; /* doing a special command, see defines above */ + reqprot_t protocol; /* request protocol, HTTP or RTSP */ + int prot_version; /* HTTP or RTSP version (major*10 + minor) */ + bool pipelining; /* true if request is pipelined */ + char *rtp_buffer; + size_t rtp_buffersize; +}; + +static int ProcessRequest(struct httprequest *req); +static void storerequest(char *reqbuf, size_t totalsize); + +#define DEFAULT_PORT 8999 + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/rtspd.log" +#endif + +const char *serverlogfile = DEFAULT_LOGFILE; +static const char *logdir = "log"; +static char loglockfile[256]; + +#define RTSPDVERSION "curl test suite RTSP server/0.1" + +#define REQUEST_DUMP "server.input" +#define RESPONSE_DUMP "server.response" + +/* very-big-path support */ +#define MAXDOCNAMELEN 140000 +#define MAXDOCNAMELEN_TXT "139999" + +#define REQUEST_KEYWORD_SIZE 256 +#define REQUEST_KEYWORD_SIZE_TXT "255" + +#define CMD_AUTH_REQUIRED "auth_required" + +/* 'idle' means that it will accept the request fine but never respond + any data. Just keep the connection alive. */ +#define CMD_IDLE "idle" + +/* 'stream' means to send a never-ending stream of data */ +#define CMD_STREAM "stream" + +#define END_OF_HEADERS "\r\n\r\n" + +enum { + DOCNUMBER_NOTHING = -7, + DOCNUMBER_QUIT = -6, + DOCNUMBER_BADCONNECT = -5, + DOCNUMBER_INTERNAL = -4, + DOCNUMBER_CONNECT = -3, + DOCNUMBER_WERULEZ = -2, + DOCNUMBER_404 = -1 +}; + + +/* sent as reply to a QUIT */ +static const char *docquit = +"HTTP/1.1 200 Goodbye" END_OF_HEADERS; + +/* sent as reply to a CONNECT */ +static const char *docconnect = +"HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS; + +/* sent as reply to a "bad" CONNECT */ +static const char *docbadconnect = +"HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS; + +/* send back this on HTTP 404 file not found */ +static const char *doc404_HTTP = "HTTP/1.1 404 Not Found\r\n" + "Server: " RTSPDVERSION "\r\n" + "Connection: close\r\n" + "Content-Type: text/html" + END_OF_HEADERS + "\n" + "\n" + "404 Not Found\n" + "\n" + "

Not Found

\n" + "The requested URL was not found on this server.\n" + "


" RTSPDVERSION "
\n" "\n"; + +/* send back this on RTSP 404 file not found */ +static const char *doc404_RTSP = "RTSP/1.0 404 Not Found\r\n" + "Server: " RTSPDVERSION + END_OF_HEADERS; + +/* Default size to send away fake RTP data */ +#define RTP_DATA_SIZE 12 +static const char *RTP_DATA = "$_1234\n\0Rsdf"; + +static int ProcessRequest(struct httprequest *req) +{ + char *line = &req->reqbuf[req->checkindex]; + bool chunked = FALSE; + static char request[REQUEST_KEYWORD_SIZE]; + static char doc[MAXDOCNAMELEN]; + static char prot_str[5]; + int prot_major, prot_minor; + char *end = strstr(line, END_OF_HEADERS); + + logmsg("ProcessRequest() called with testno %ld and line [%s]", + req->testno, line); + + /* try to figure out the request characteristics as soon as possible, but + only once! */ + if((req->testno == DOCNUMBER_NOTHING) && + sscanf(line, + "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s %4s/%d.%d", + request, + doc, + prot_str, + &prot_major, + &prot_minor) == 5) { + char *ptr; + char logbuf[256]; + + if(!strcmp(prot_str, "HTTP")) { + req->protocol = RPROT_HTTP; + } + else if(!strcmp(prot_str, "RTSP")) { + req->protocol = RPROT_RTSP; + } + else { + req->protocol = RPROT_NONE; + logmsg("got unknown protocol %s", prot_str); + return 1; + } + + req->prot_version = prot_major*10 + prot_minor; + + /* find the last slash */ + ptr = strrchr(doc, '/'); + + /* get the number after it */ + if(ptr) { + FILE *stream; + if((strlen(doc) + strlen(request)) < 200) + msnprintf(logbuf, sizeof(logbuf), "Got request: %s %s %s/%d.%d", + request, doc, prot_str, prot_major, prot_minor); + else + msnprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request %s/%d.%d", + prot_str, prot_major, prot_minor); + logmsg("%s", logbuf); + + if(!strncmp("/verifiedserver", ptr, 15)) { + logmsg("Are-we-friendly question received"); + req->testno = DOCNUMBER_WERULEZ; + return 1; /* done */ + } + + if(!strncmp("/quit", ptr, 5)) { + logmsg("Request-to-quit received"); + req->testno = DOCNUMBER_QUIT; + return 1; /* done */ + } + + ptr++; /* skip the slash */ + + /* skip all non-numericals following the slash */ + while(*ptr && !ISDIGIT(*ptr)) + ptr++; + + req->testno = strtol(ptr, &ptr, 10); + + if(req->testno > 10000) { + req->partno = req->testno % 10000; + req->testno /= 10000; + } + else + req->partno = 0; + + msnprintf(logbuf, sizeof(logbuf), "Requested test number %ld part %ld", + req->testno, req->partno); + logmsg("%s", logbuf); + + stream = test2fopen(req->testno, logdir); + + if(!stream) { + int error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Couldn't open test file %ld", req->testno); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + else { + char *cmd = NULL; + size_t cmdsize = 0; + int num = 0; + + int rtp_channel = 0; + int rtp_size = 0; + int rtp_size_err = 0; + int rtp_partno = -1; + char *rtp_scratch = NULL; + + /* get the custom server control "commands" */ + int error = getpart(&cmd, &cmdsize, "reply", "servercmd", stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + ptr = cmd; + + if(cmdsize) { + logmsg("Found a reply-servercmd section!"); + do { + rtp_size_err = 0; + if(!strncmp(CMD_AUTH_REQUIRED, ptr, strlen(CMD_AUTH_REQUIRED))) { + logmsg("instructed to require authorization header"); + req->auth_req = TRUE; + } + else if(!strncmp(CMD_IDLE, ptr, strlen(CMD_IDLE))) { + logmsg("instructed to idle"); + req->rcmd = RCMD_IDLE; + req->open = TRUE; + } + else if(!strncmp(CMD_STREAM, ptr, strlen(CMD_STREAM))) { + logmsg("instructed to stream"); + req->rcmd = RCMD_STREAM; + } + else if(1 == sscanf(ptr, "pipe: %d", &num)) { + logmsg("instructed to allow a pipe size of %d", num); + if(num < 0) + logmsg("negative pipe size ignored"); + else if(num > 0) + req->pipe = num-1; /* decrease by one since we don't count the + first request in this number */ + } + else if(1 == sscanf(ptr, "skip: %d", &num)) { + logmsg("instructed to skip this number of bytes %d", num); + req->skip = num; + } + else if(3 <= sscanf(ptr, + "rtp: part %d channel %d size %d size_err %d", + &rtp_partno, &rtp_channel, &rtp_size, + &rtp_size_err)) { + + if(rtp_partno == req->partno) { + int i = 0; + logmsg("RTP: part %d channel %d size %d size_err %d", + rtp_partno, rtp_channel, rtp_size, rtp_size_err); + + /* Make our scratch buffer enough to fit all the + * desired data and one for padding */ + rtp_scratch = malloc(rtp_size + 4 + RTP_DATA_SIZE); + + /* RTP is signalled with a $ */ + rtp_scratch[0] = '$'; + + /* The channel follows and is one byte */ + SET_RTP_PKT_CHN(rtp_scratch, rtp_channel); + + /* Length follows and is a two byte short in network order */ + SET_RTP_PKT_LEN(rtp_scratch, rtp_size + rtp_size_err); + + /* Fill it with junk data */ + for(i = 0; i < rtp_size; i += RTP_DATA_SIZE) { + memcpy(rtp_scratch + 4 + i, RTP_DATA, RTP_DATA_SIZE); + } + + if(!req->rtp_buffer) { + req->rtp_buffer = rtp_scratch; + req->rtp_buffersize = rtp_size + 4; + } + else { + req->rtp_buffer = realloc(req->rtp_buffer, + req->rtp_buffersize + + rtp_size + 4); + memcpy(req->rtp_buffer + req->rtp_buffersize, rtp_scratch, + rtp_size + 4); + req->rtp_buffersize += rtp_size + 4; + free(rtp_scratch); + } + logmsg("rtp_buffersize is %zu, rtp_size is %d.", + req->rtp_buffersize, rtp_size); + } + } + else { + logmsg("funny instruction found: %s", ptr); + } + + ptr = strchr(ptr, '\n'); + if(ptr) + ptr++; + else + ptr = NULL; + } while(ptr && *ptr); + logmsg("Done parsing server commands"); + } + free(cmd); + } + } + else { + if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d", + doc, &prot_major, &prot_minor) == 3) { + msnprintf(logbuf, sizeof(logbuf), + "Received a CONNECT %s HTTP/%d.%d request", + doc, prot_major, prot_minor); + logmsg("%s", logbuf); + + if(req->prot_version == 10) + req->open = FALSE; /* HTTP 1.0 closes connection by default */ + + if(!strncmp(doc, "bad", 3)) + /* if the host name starts with bad, we fake an error here */ + req->testno = DOCNUMBER_BADCONNECT; + else if(!strncmp(doc, "test", 4)) { + /* if the host name starts with test, the port number used in the + CONNECT line will be used as test number! */ + char *portp = strchr(doc, ':'); + if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1))) + req->testno = strtol(portp + 1, NULL, 10); + else + req->testno = DOCNUMBER_CONNECT; + } + else + req->testno = DOCNUMBER_CONNECT; + } + else { + logmsg("Did not find test number in PATH"); + req->testno = DOCNUMBER_404; + } + } + } + + if(!end) { + /* we don't have a complete request yet! */ + logmsg("ProcessRequest returned without a complete request"); + return 0; /* not complete yet */ + } + logmsg("ProcessRequest found a complete request"); + + if(req->pipe) + /* we do have a full set, advance the checkindex to after the end of the + headers, for the pipelining case mostly */ + req->checkindex += (end - line) + strlen(END_OF_HEADERS); + + /* **** Persistence **** + * + * If the request is an HTTP/1.0 one, we close the connection unconditionally + * when we're done. + * + * If the request is an HTTP/1.1 one, we MUST check for a "Connection:" + * header that might say "close". If it does, we close a connection when + * this request is processed. Otherwise, we keep the connection alive for X + * seconds. + */ + + do { + if(got_exit_signal) + return 1; /* done */ + + if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) { + /* If we don't ignore content-length, we read it and we read the whole + request including the body before we return. If we've been told to + ignore the content-length, we will return as soon as all headers + have been received */ + char *endptr; + char *ptr = line + 15; + unsigned long clen = 0; + while(*ptr && ISSPACE(*ptr)) + ptr++; + endptr = ptr; + errno = 0; + clen = strtoul(ptr, &endptr, 10); + if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) { + /* this assumes that a zero Content-Length is valid */ + logmsg("Found invalid Content-Length: (%s) in the request", ptr); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + req->cl = clen - req->skip; + + logmsg("Found Content-Length: %lu in the request", clen); + if(req->skip) + logmsg("... but will abort after %zu bytes", req->cl); + break; + } + else if(strncasecompare("Transfer-Encoding: chunked", line, + strlen("Transfer-Encoding: chunked"))) { + /* chunked data coming in */ + chunked = TRUE; + } + + if(chunked) { + if(strstr(req->reqbuf, "\r\n0\r\n\r\n")) + /* end of chunks reached */ + return 1; /* done */ + else + return 0; /* not done */ + } + + line = strchr(line, '\n'); + if(line) + line++; + + } while(line); + + if(!req->auth && strstr(req->reqbuf, "Authorization:")) { + req->auth = TRUE; /* Authorization: header present! */ + if(req->auth_req) + logmsg("Authorization header found, as required"); + } + + if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) { + /* If the client is passing this Digest-header, we set the part number + to 1000. Not only to spice up the complexity of this, but to make + Digest stuff to work in the test suite. */ + req->partno += 1000; + req->digest = TRUE; /* header found */ + logmsg("Received Digest request, sending back data %ld", req->partno); + } + else if(!req->ntlm && + strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) { + /* If the client is passing this type-3 NTLM header */ + req->partno += 1002; + req->ntlm = TRUE; /* NTLM found */ + logmsg("Received NTLM type-3, sending back data %ld", req->partno); + if(req->cl) { + logmsg(" Expecting %zu POSTed bytes", req->cl); + } + } + else if(!req->ntlm && + strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) { + /* If the client is passing this type-1 NTLM header */ + req->partno += 1001; + req->ntlm = TRUE; /* NTLM found */ + logmsg("Received NTLM type-1, sending back data %ld", req->partno); + } + else if((req->partno >= 1000) && + strstr(req->reqbuf, "Authorization: Basic")) { + /* If the client is passing this Basic-header and the part number is + already >=1000, we add 1 to the part number. This allows simple Basic + authentication negotiation to work in the test suite. */ + req->partno += 1; + logmsg("Received Basic request, sending back data %ld", req->partno); + } + if(strstr(req->reqbuf, "Connection: close")) + req->open = FALSE; /* close connection after this request */ + + if(!req->pipe && + req->open && + req->prot_version >= 11 && + req->reqbuf + req->offset > end + strlen(END_OF_HEADERS) && + (!strncmp(req->reqbuf, "GET", strlen("GET")) || + !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) { + /* If we have a persistent connection, HTTP version >= 1.1 + and GET/HEAD request, enable pipelining. */ + req->checkindex = (end - req->reqbuf) + strlen(END_OF_HEADERS); + req->pipelining = TRUE; + } + + while(req->pipe) { + if(got_exit_signal) + return 1; /* done */ + /* scan for more header ends within this chunk */ + line = &req->reqbuf[req->checkindex]; + end = strstr(line, END_OF_HEADERS); + if(!end) + break; + req->checkindex += (end - line) + strlen(END_OF_HEADERS); + req->pipe--; + } + + /* If authentication is required and no auth was provided, end now. This + makes the server NOT wait for PUT/POST data and you can then make the + test case send a rejection before any such data has been sent. Test case + 154 uses this.*/ + if(req->auth_req && !req->auth) + return 1; /* done */ + + if(req->cl > 0) { + if(req->cl <= req->offset - (end - req->reqbuf) - strlen(END_OF_HEADERS)) + return 1; /* done */ + else + return 0; /* not complete yet */ + } + + return 1; /* done */ +} + +/* store the entire request in a file */ +static void storerequest(char *reqbuf, size_t totalsize) +{ + int res; + int error = 0; + size_t written; + size_t writeleft; + FILE *dump; + char dumpfile[256]; + + msnprintf(dumpfile, sizeof(dumpfile), "%s/%s", logdir, REQUEST_DUMP); + + if(!reqbuf) + return; + if(totalsize == 0) + return; + + do { + dump = fopen(dumpfile, "ab"); + } while(!dump && ((error = errno) == EINTR)); + if(!dump) { + logmsg("Error opening file %s error: %d %s", + dumpfile, error, strerror(error)); + logmsg("Failed to write request input to %s", dumpfile); + return; + } + + writeleft = totalsize; + do { + written = fwrite(&reqbuf[totalsize-writeleft], + 1, writeleft, dump); + if(got_exit_signal) + goto storerequest_cleanup; + if(written > 0) + writeleft -= written; + } while((writeleft > 0) && ((error = errno) == EINTR)); + + if(writeleft == 0) + logmsg("Wrote request (%zu bytes) input to %s", totalsize, dumpfile); + else if(writeleft > 0) { + logmsg("Error writing file %s error: %d %s", + dumpfile, error, strerror(error)); + logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s", + totalsize-writeleft, totalsize, dumpfile); + } + +storerequest_cleanup: + + do { + res = fclose(dump); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error closing file %s error: %d %s", + dumpfile, error, strerror(error)); +} + +/* return 0 on success, non-zero on failure */ +static int get_request(curl_socket_t sock, struct httprequest *req) +{ + int error; + int fail = 0; + int done_processing = 0; + char *reqbuf = req->reqbuf; + ssize_t got = 0; + + char *pipereq = NULL; + size_t pipereq_length = 0; + + if(req->pipelining) { + pipereq = reqbuf + req->checkindex; + pipereq_length = req->offset - req->checkindex; + } + + /*** Init the httprequest structure properly for the upcoming request ***/ + + req->checkindex = 0; + req->offset = 0; + req->testno = DOCNUMBER_NOTHING; + req->partno = 0; + req->open = TRUE; + req->auth_req = FALSE; + req->auth = FALSE; + req->cl = 0; + req->digest = FALSE; + req->ntlm = FALSE; + req->pipe = 0; + req->skip = 0; + req->rcmd = RCMD_NORMALREQ; + req->protocol = RPROT_NONE; + req->prot_version = 0; + req->pipelining = FALSE; + req->rtp_buffer = NULL; + req->rtp_buffersize = 0; + + /*** end of httprequest init ***/ + + while(!done_processing && (req->offset < REQBUFSIZ-1)) { + if(pipereq_length && pipereq) { + memmove(reqbuf, pipereq, pipereq_length); + got = curlx_uztosz(pipereq_length); + pipereq_length = 0; + } + else { + if(req->skip) + /* we are instructed to not read the entire thing, so we make sure to + only read what we're supposed to and NOT read the enire thing the + client wants to send! */ + got = sread(sock, reqbuf + req->offset, req->cl); + else + got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset); + } + if(got_exit_signal) + return 1; + if(got == 0) { + logmsg("Connection closed by client"); + fail = 1; + } + else if(got < 0) { + error = SOCKERRNO; + logmsg("recv() returned error: (%d) %s", error, sstrerror(error)); + fail = 1; + } + if(fail) { + /* dump the request received so far to the external file */ + reqbuf[req->offset] = '\0'; + storerequest(reqbuf, req->offset); + return 1; + } + + logmsg("Read %zd bytes", got); + + req->offset += (size_t)got; + reqbuf[req->offset] = '\0'; + + done_processing = ProcessRequest(req); + if(got_exit_signal) + return 1; + if(done_processing && req->pipe) { + logmsg("Waiting for another piped request"); + done_processing = 0; + req->pipe--; + } + } + + if((req->offset == REQBUFSIZ-1) && (got > 0)) { + logmsg("Request would overflow buffer, closing connection"); + /* dump request received so far to external file anyway */ + reqbuf[REQBUFSIZ-1] = '\0'; + fail = 1; + } + else if(req->offset > REQBUFSIZ-1) { + logmsg("Request buffer overflow, closing connection"); + /* dump request received so far to external file anyway */ + reqbuf[REQBUFSIZ-1] = '\0'; + fail = 1; + } + else + reqbuf[req->offset] = '\0'; + + /* dump the request to an external file */ + storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset); + if(got_exit_signal) + return 1; + + return fail; /* return 0 on success */ +} + +/* returns -1 on failure */ +static int send_doc(curl_socket_t sock, struct httprequest *req) +{ + ssize_t written; + size_t count; + const char *buffer; + char *ptr = NULL; + char *cmd = NULL; + size_t cmdsize = 0; + FILE *dump; + bool persistent = TRUE; + bool sendfailure = FALSE; + size_t responsesize; + int error = 0; + int res; + static char weare[256]; + char responsedump[256]; + + msnprintf(responsedump, sizeof(responsedump), "%s/%s", + logdir, RESPONSE_DUMP); + + logmsg("Send response number %ld part %ld", req->testno, req->partno); + + switch(req->rcmd) { + default: + case RCMD_NORMALREQ: + break; /* continue with business as usual */ + case RCMD_STREAM: +#define STREAMTHIS "a string to stream 01234567890\n" + count = strlen(STREAMTHIS); + for(;;) { + written = swrite(sock, STREAMTHIS, count); + if(got_exit_signal) + return -1; + if(written != (ssize_t)count) { + logmsg("Stopped streaming"); + break; + } + } + return -1; + case RCMD_IDLE: + /* Do nothing. Sit idle. Pretend it rains. */ + return 0; + } + + req->open = FALSE; + + if(req->testno < 0) { + size_t msglen; + char msgbuf[64]; + + switch(req->testno) { + case DOCNUMBER_QUIT: + logmsg("Replying to QUIT"); + buffer = docquit; + break; + case DOCNUMBER_WERULEZ: + /* we got a "friends?" question, reply back that we sure are */ + logmsg("Identifying ourselves as friends"); + msnprintf(msgbuf, sizeof(msgbuf), "RTSP_SERVER WE ROOLZ: %" + CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); + msglen = strlen(msgbuf); + msnprintf(weare, sizeof(weare), + "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", + msglen, msgbuf); + buffer = weare; + break; + case DOCNUMBER_INTERNAL: + logmsg("Bailing out due to internal error"); + return -1; + case DOCNUMBER_CONNECT: + logmsg("Replying to CONNECT"); + buffer = docconnect; + break; + case DOCNUMBER_BADCONNECT: + logmsg("Replying to a bad CONNECT"); + buffer = docbadconnect; + break; + case DOCNUMBER_404: + default: + logmsg("Replying to with a 404"); + if(req->protocol == RPROT_HTTP) { + buffer = doc404_HTTP; + } + else { + buffer = doc404_RTSP; + } + break; + } + + count = strlen(buffer); + } + else { + FILE *stream = test2fopen(req->testno, logdir); + char partbuf[80]="data"; + if(0 != req->partno) + msnprintf(partbuf, sizeof(partbuf), "data%ld", req->partno); + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Couldn't open test file"); + return 0; + } + else { + error = getpart(&ptr, &count, "reply", partbuf, stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + return 0; + } + buffer = ptr; + } + + if(got_exit_signal) { + free(ptr); + return -1; + } + + /* re-open the same file again */ + stream = test2fopen(req->testno, logdir); + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Couldn't open test file"); + free(ptr); + return 0; + } + else { + /* get the custom server control "commands" */ + error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + free(ptr); + return 0; + } + } + } + + if(got_exit_signal) { + free(ptr); + free(cmd); + return -1; + } + + /* If the word 'swsclose' is present anywhere in the reply chunk, the + connection will be closed after the data has been sent to the requesting + client... */ + if(strstr(buffer, "swsclose") || !count) { + persistent = FALSE; + logmsg("connection close instruction \"swsclose\" found in response"); + } + if(strstr(buffer, "swsbounce")) { + prevbounce = TRUE; + logmsg("enable \"swsbounce\" in the next request"); + } + else + prevbounce = FALSE; + + dump = fopen(responsedump, "ab"); + if(!dump) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Error opening file: %s", responsedump); + logmsg("couldn't create logfile: %s", responsedump); + free(ptr); + free(cmd); + return -1; + } + + responsesize = count; + do { + /* Ok, we send no more than 200 bytes at a time, just to make sure that + larger chunks are split up so that the client will need to do multiple + recv() calls to get it and thus we exercise that code better */ + size_t num = count; + if(num > 200) + num = 200; + written = swrite(sock, buffer, num); + if(written < 0) { + sendfailure = TRUE; + break; + } + else { + logmsg("Sent off %zd bytes", written); + } + /* write to file as well */ + fwrite(buffer, 1, (size_t)written, dump); + if(got_exit_signal) + break; + + count -= written; + buffer += written; + } while(count > 0); + + /* Send out any RTP data */ + if(req->rtp_buffer) { + logmsg("About to write %zu RTP bytes", req->rtp_buffersize); + count = req->rtp_buffersize; + do { + size_t num = count; + if(num > 200) + num = 200; + written = swrite(sock, req->rtp_buffer + (req->rtp_buffersize - count), + num); + if(written < 0) { + sendfailure = TRUE; + break; + } + count -= written; + } while(count > 0); + + free(req->rtp_buffer); + req->rtp_buffersize = 0; + } + + do { + res = fclose(dump); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error closing file %s error: %d %s", + responsedump, error, strerror(error)); + + if(got_exit_signal) { + free(ptr); + free(cmd); + return -1; + } + + if(sendfailure) { + logmsg("Sending response failed. Only (%zu bytes) of " + "(%zu bytes) were sent", + responsesize-count, responsesize); + free(ptr); + free(cmd); + return -1; + } + + logmsg("Response sent (%zu bytes) and written to %s", + responsesize, responsedump); + free(ptr); + + if(cmdsize > 0) { + char command[32]; + int quarters; + int num; + ptr = cmd; + do { + if(2 == sscanf(ptr, "%31s %d", command, &num)) { + if(!strcmp("wait", command)) { + logmsg("Told to sleep for %d seconds", num); + quarters = num * 4; + while(quarters > 0) { + quarters--; + res = wait_ms(250); + if(got_exit_signal) + break; + if(res) { + /* should not happen */ + error = errno; + logmsg("wait_ms() failed with error: (%d) %s", + error, strerror(error)); + break; + } + } + if(!quarters) + logmsg("Continuing after sleeping %d seconds", num); + } + else + logmsg("Unknown command in reply command section"); + } + ptr = strchr(ptr, '\n'); + if(ptr) + ptr++; + else + ptr = NULL; + } while(ptr && *ptr); + } + free(cmd); + req->open = persistent; + + prevtestno = req->testno; + prevpartno = req->partno; + + return 0; +} + + +int main(int argc, char *argv[]) +{ + srvr_sockaddr_union_t me; + curl_socket_t sock = CURL_SOCKET_BAD; + curl_socket_t msgsock = CURL_SOCKET_BAD; + int wrotepidfile = 0; + int wroteportfile = 0; + int flag; + unsigned short port = DEFAULT_PORT; + const char *pidname = ".rtsp.pid"; + const char *portname = NULL; /* none by default */ + struct httprequest req; + int rc; + int error; + int arg = 1; + + memset(&req, 0, sizeof(req)); + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("rtspd IPv4%s" + "\n" + , +#ifdef USE_IPV6 + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--logdir", argv[arg])) { + arg++; + if(argc > arg) + logdir = argv[arg++]; + } + else if(!strcmp("--ipv4", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv4"; + use_ipv6 = FALSE; +#endif + arg++; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv6"; + use_ipv6 = TRUE; +#endif + arg++; + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + port = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--srcdir", argv[arg])) { + arg++; + if(argc > arg) { + path = argv[arg]; + arg++; + } + } + else { + puts("Usage: rtspd [option]\n" + " --version\n" + " --logfile [file]\n" + " --logdir [directory]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --port [port]\n" + " --srcdir [path]"); + return 0; + } + } + + msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/rtsp-%s.lock", + logdir, SERVERLOGS_LOCKDIR, ipv_inuse); + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); +#endif + + install_signal_handlers(false); + +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + sock = socket(AF_INET, SOCK_STREAM, 0); +#ifdef USE_IPV6 + else + sock = socket(AF_INET6, SOCK_STREAM, 0); +#endif + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", error, sstrerror(error)); + goto server_cleanup; + } + + flag = 1; + if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag))) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + goto server_cleanup; + } + +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + memset(&me.sa4, 0, sizeof(me.sa4)); + me.sa4.sin_family = AF_INET; + me.sa4.sin_addr.s_addr = INADDR_ANY; + me.sa4.sin_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa4)); +#ifdef USE_IPV6 + } + else { + memset(&me.sa6, 0, sizeof(me.sa6)); + me.sa6.sin6_family = AF_INET6; + me.sa6.sin6_addr = in6addr_any; + me.sa6.sin6_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa6)); + } +#endif /* USE_IPV6 */ + if(0 != rc) { + error = SOCKERRNO; + logmsg("Error binding socket on port %hu: (%d) %s", + port, error, sstrerror(error)); + goto server_cleanup; + } + + if(!port) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + la_size = sizeof(localaddr.sa4); +#ifdef USE_IPV6 + else + la_size = sizeof(localaddr.sa6); +#endif + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + goto server_cleanup; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + port = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + port = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!port) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + sclose(sock); + goto server_cleanup; + } + } + logmsg("Running %s version on port %d", ipv_inuse, (int)port); + + /* start accepting connections */ + rc = listen(sock, 5); + if(0 != rc) { + error = SOCKERRNO; + logmsg("listen() failed with error: (%d) %s", + error, sstrerror(error)); + goto server_cleanup; + } + + /* + ** As soon as this server writes its pid file the test harness will + ** attempt to connect to this server and initiate its verification. + */ + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) + goto server_cleanup; + + if(portname) { + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) + goto server_cleanup; + } + + for(;;) { + msgsock = accept(sock, NULL, NULL); + + if(got_exit_signal) + break; + if(CURL_SOCKET_BAD == msgsock) { + error = SOCKERRNO; + logmsg("MAJOR ERROR: accept() failed with error: (%d) %s", + error, sstrerror(error)); + break; + } + + /* + ** As soon as this server accepts a connection from the test harness it + ** must set the server logs advisor read lock to indicate that server + ** logs should not be read until this lock is removed by this server. + */ + + set_advisor_read_lock(loglockfile); + serverlogslocked = 1; + + logmsg("====> Client connect"); + +#ifdef TCP_NODELAY + /* + * Disable the Nagle algorithm to make it easier to send out a large + * response in many small segments to torture the clients more. + */ + flag = 1; + if(setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY, + (void *)&flag, sizeof(flag)) == -1) { + logmsg("====> TCP_NODELAY failed"); + } +#endif + + /* initialization of httprequest struct is done in get_request(), but due + to pipelining treatment the pipelining struct field must be initialized + previously to FALSE every time a new connection arrives. */ + + req.pipelining = FALSE; + + do { + if(got_exit_signal) + break; + + if(get_request(msgsock, &req)) + /* non-zero means error, break out of loop */ + break; + + if(prevbounce) { + /* bounce treatment requested */ + if((req.testno == prevtestno) && + (req.partno == prevpartno)) { + req.partno++; + logmsg("BOUNCE part number to %ld", req.partno); + } + else { + prevbounce = FALSE; + prevtestno = -1; + prevpartno = -1; + } + } + + send_doc(msgsock, &req); + if(got_exit_signal) + break; + + if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) { + logmsg("special request received, no persistency"); + break; + } + if(!req.open) { + logmsg("instructed to close connection after server-reply"); + break; + } + + if(req.open) + logmsg("=> persistent connection request ended, awaits new request"); + /* if we got a CONNECT, loop and get another request as well! */ + } while(req.open || (req.testno == DOCNUMBER_CONNECT)); + + if(got_exit_signal) + break; + + logmsg("====> Client disconnect"); + sclose(msgsock); + msgsock = CURL_SOCKET_BAD; + + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + + if(req.testno == DOCNUMBER_QUIT) + break; + } + +server_cleanup: + + if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) + sclose(msgsock); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + + if(got_exit_signal) + logmsg("signalled to die"); + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + + restore_signal_handlers(false); + + if(got_exit_signal) { + logmsg("========> %s rtspd (port: %d pid: %ld) exits with signal (%d)", + ipv_inuse, (int)port, (long)Curl_getpid(), exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("========> rtspd quits"); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/server_setup.h b/local-test-curl-delta-01/afc-curl/tests/server/server_setup.h new file mode 100644 index 0000000000000000000000000000000000000000..8bdcc913b13f2722cff8506e204882bd87525f88 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/server_setup.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_SERVER_SETUP_H +#define HEADER_CURL_SERVER_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 + * + ***************************************************************************/ + +#define CURL_NO_OLDIES + +#include "curl_setup.h" /* portability help from the lib directory */ + +#endif /* HEADER_CURL_SERVER_SETUP_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/server/server_sockaddr.h b/local-test-curl-delta-01/afc-curl/tests/server/server_sockaddr.h new file mode 100644 index 0000000000000000000000000000000000000000..fb4609976a1e2abe3456fc08ece40b445e0f2b46 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/server_sockaddr.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_SERVER_SOCKADDR_H +#define HEADER_CURL_SERVER_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 "server_setup.h" + +#ifdef HAVE_SYS_UN_H +#include /* for sockaddr_un */ +#endif + +typedef union { + struct sockaddr sa; + struct sockaddr_in sa4; +#ifdef USE_IPV6 + struct sockaddr_in6 sa6; +#endif +#ifdef USE_UNIX_SOCKETS + struct sockaddr_un sau; +#endif +} srvr_sockaddr_union_t; + +#endif /* HEADER_CURL_SERVER_SOCKADDR_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/server/sockfilt.c b/local-test-curl-delta-01/afc-curl/tests/server/sockfilt.c new file mode 100644 index 0000000000000000000000000000000000000000..480d23ccebd8bfc95a17e4c96db8939249819858 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/sockfilt.c @@ -0,0 +1,1597 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" + +/* Purpose + * + * 1. Accept a TCP connection on a custom port (IPv4 or IPv6), or connect + * to a given (localhost) port. + * + * 2. Get commands on STDIN. Pass data on to the TCP stream. + * Get data from TCP stream and pass on to STDOUT. + * + * This program is made to perform all the socket/stream/connection stuff for + * the test suite's (perl) FTP server. Previously the perl code did all of + * this by its own, but I decided to let this program do the socket layer + * because of several things: + * + * o We want the perl code to work with rather old perl installations, thus + * we cannot use recent perl modules or features. + * + * o We want IPv6 support for systems that provide it, and doing optional IPv6 + * support in perl seems if not impossible so at least awkward. + * + * o We want FTP-SSL support, which means that a connection that starts with + * plain sockets needs to be able to "go SSL" in the midst. This would also + * require some nasty perl stuff I'd rather avoid. + * + * (Source originally based on sws.c) + */ + +/* + * Signal handling notes for sockfilt + * ---------------------------------- + * + * This program is a single-threaded process. + * + * This program is intended to be highly portable and as such it must be kept + * as simple as possible, due to this the only signal handling mechanisms used + * will be those of ANSI C, and used only in the most basic form which is good + * enough for the purpose of this program. + * + * For the above reason and the specific needs of this program signals SIGHUP, + * SIGPIPE and SIGALRM will be simply ignored on systems where this can be + * done. If possible, signals SIGINT and SIGTERM will be handled by this + * program as an indication to cleanup and finish execution as soon as + * possible. This will be achieved with a single signal handler + * 'exit_signal_handler' for both signals. + * + * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal + * will just set to one the global var 'got_exit_signal' storing in global var + * 'exit_signal' the signal that triggered this change. + * + * Nothing fancy that could introduce problems is used, the program at certain + * points in its normal flow checks if var 'got_exit_signal' is set and in + * case this is true it just makes its way out of loops and functions in + * structured and well behaved manner to achieve proper program cleanup and + * termination. + * + * Even with the above mechanism implemented it is worthwhile to note that + * other signals might still be received, or that there might be systems on + * which it is not possible to trap and ignore some of the above signals. + * This implies that for increased portability and reliability the program + * must be coded as if no signal was being ignored or handled at all. Enjoy + * it! + */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "inet_pton.h" +#include "util.h" +#include "server_sockaddr.h" +#include "timediff.h" +#include "warnless.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef EAGAIN +#define EAGAIN 11 /* errno.h value */ +#undef ENOMEM +#define ENOMEM 12 /* errno.h value */ +#undef EINVAL +#define EINVAL 22 /* errno.h value */ +#endif + +#define DEFAULT_PORT 8999 + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/sockfilt.log" +#endif + +/* buffer is this excessively large only to be able to support things like + test 1003 which tests exceedingly large server response lines */ +#define BUFFER_SIZE 17010 + +const char *serverlogfile = DEFAULT_LOGFILE; + +static bool verbose = FALSE; +static bool bind_only = FALSE; +#ifdef USE_IPV6 +static bool use_ipv6 = FALSE; +#endif +static const char *ipv_inuse = "IPv4"; +static unsigned short port = DEFAULT_PORT; +static unsigned short connectport = 0; /* if non-zero, we activate this mode */ + +enum sockmode { + PASSIVE_LISTEN, /* as a server waiting for connections */ + PASSIVE_CONNECT, /* as a server, connected to a client */ + ACTIVE, /* as a client, connected to a server */ + ACTIVE_DISCONNECT /* as a client, disconnected from server */ +}; + +#if defined(_WIN32) && !defined(CURL_WINDOWS_UWP) +/* + * read-wrapper to support reading from stdin on Windows. + */ +static ssize_t read_wincon(int fd, void *buf, size_t count) +{ + HANDLE handle = NULL; + DWORD mode, rcount = 0; + BOOL success; + + if(fd == fileno(stdin)) { + handle = GetStdHandle(STD_INPUT_HANDLE); + } + else { + return read(fd, buf, count); + } + + if(GetConsoleMode(handle, &mode)) { + success = ReadConsole(handle, buf, curlx_uztoul(count), &rcount, NULL); + } + else { + success = ReadFile(handle, buf, curlx_uztoul(count), &rcount, NULL); + } + if(success) { + return rcount; + } + + errno = (int)GetLastError(); + return -1; +} +#undef read +#define read(a,b,c) read_wincon(a,b,c) + +/* + * write-wrapper to support writing to stdout and stderr on Windows. + */ +static ssize_t write_wincon(int fd, const void *buf, size_t count) +{ + HANDLE handle = NULL; + DWORD mode, wcount = 0; + BOOL success; + + if(fd == fileno(stdout)) { + handle = GetStdHandle(STD_OUTPUT_HANDLE); + } + else if(fd == fileno(stderr)) { + handle = GetStdHandle(STD_ERROR_HANDLE); + } + else { + return write(fd, buf, count); + } + + if(GetConsoleMode(handle, &mode)) { + success = WriteConsole(handle, buf, curlx_uztoul(count), &wcount, NULL); + } + else { + success = WriteFile(handle, buf, curlx_uztoul(count), &wcount, NULL); + } + if(success) { + return wcount; + } + + errno = (int)GetLastError(); + return -1; +} +#undef write +#define write(a,b,c) write_wincon(a,b,c) +#endif + +/* On Windows, we sometimes get this for a broken pipe, seemingly + * when the client just closed stdin? */ +#define CURL_WIN32_EPIPE 109 + +/* + * fullread is a wrapper around the read() function. This will repeat the call + * to read() until it actually has read the complete number of bytes indicated + * in nbytes or it fails with a condition that cannot be handled with a simple + * retry of the read call. + */ + +static ssize_t fullread(int filedes, void *buffer, size_t nbytes) +{ + int error; + ssize_t nread = 0; + + do { + ssize_t rc = read(filedes, + (unsigned char *)buffer + nread, nbytes - nread); + + if(got_exit_signal) { + logmsg("signalled to die"); + return -1; + } + + if(rc < 0) { + error = errno; + if((error == EINTR) || (error == EAGAIN)) + continue; + if(error == CURL_WIN32_EPIPE) { + logmsg("got Windows ERROR_BROKEN_PIPE on fd=%d, treating as close", + filedes); + return 0; + } + logmsg("reading from file descriptor: %d,", filedes); + logmsg("unrecoverable read() failure: (%d) %s", + error, strerror(error)); + return -1; + } + + if(rc == 0) { + logmsg("got 0 reading from stdin"); + return 0; + } + + nread += rc; + + } while((size_t)nread < nbytes); + + if(verbose) + logmsg("read %zd bytes", nread); + + return nread; +} + +/* + * fullwrite is a wrapper around the write() function. This will repeat the + * call to write() until it actually has written the complete number of bytes + * indicated in nbytes or it fails with a condition that cannot be handled + * with a simple retry of the write call. + */ + +static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes) +{ + int error; + ssize_t nwrite = 0; + + do { + ssize_t wc = write(filedes, (const unsigned char *)buffer + nwrite, + nbytes - nwrite); + + if(got_exit_signal) { + logmsg("signalled to die"); + return -1; + } + + if(wc < 0) { + error = errno; + if((error == EINTR) || (error == EAGAIN)) + continue; + logmsg("writing to file descriptor: %d,", filedes); + logmsg("unrecoverable write() failure: (%d) %s", + error, strerror(error)); + return -1; + } + + if(wc == 0) { + logmsg("put 0 writing to stdout"); + return 0; + } + + nwrite += wc; + + } while((size_t)nwrite < nbytes); + + if(verbose) + logmsg("wrote %zd bytes", nwrite); + + return nwrite; +} + +/* + * read_stdin tries to read from stdin nbytes into the given buffer. This is a + * blocking function that will only return TRUE when nbytes have actually been + * read or FALSE when an unrecoverable error has been detected. Failure of this + * function is an indication that the sockfilt process should terminate. + */ + +static bool read_stdin(void *buffer, size_t nbytes) +{ + ssize_t nread = fullread(fileno(stdin), buffer, nbytes); + if(nread != (ssize_t)nbytes) { + logmsg("exiting..."); + return FALSE; + } + return TRUE; +} + +/* + * write_stdout tries to write to stdio nbytes from the given buffer. This is a + * blocking function that will only return TRUE when nbytes have actually been + * written or FALSE when an unrecoverable error has been detected. Failure of + * this function is an indication that the sockfilt process should terminate. + */ + +static bool write_stdout(const void *buffer, size_t nbytes) +{ + ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes); + if(nwrite != (ssize_t)nbytes) { + logmsg("exiting..."); + return FALSE; + } + return TRUE; +} + +static void lograw(unsigned char *buffer, ssize_t len) +{ + char data[120]; + ssize_t i; + unsigned char *ptr = buffer; + char *optr = data; + ssize_t width = 0; + int left = sizeof(data); + + for(i = 0; i < len; i++) { + switch(ptr[i]) { + case '\n': + msnprintf(optr, left, "\\n"); + width += 2; + optr += 2; + left -= 2; + break; + case '\r': + msnprintf(optr, left, "\\r"); + width += 2; + optr += 2; + left -= 2; + break; + default: + msnprintf(optr, left, "%c", (ISGRAPH(ptr[i]) || + ptr[i] == 0x20) ? ptr[i] : '.'); + width++; + optr++; + left--; + break; + } + + if(width > 60) { + logmsg("'%s'", data); + width = 0; + optr = data; + left = sizeof(data); + } + } + if(width) + logmsg("'%s'", data); +} + +/* + * handle the DATA command + * maxlen is the available space in buffer (input) + * *buffer_len is the amount of data in the buffer (output) + */ +static bool read_data_block(unsigned char *buffer, ssize_t maxlen, + ssize_t *buffer_len) +{ + if(!read_stdin(buffer, 5)) + return FALSE; + + buffer[5] = '\0'; + + *buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16); + if(*buffer_len > maxlen) { + logmsg("ERROR: Buffer size (%zd bytes) too small for data size " + "(%zd bytes)", maxlen, *buffer_len); + return FALSE; + } + logmsg("> %zd bytes data, server => client", *buffer_len); + + if(!read_stdin(buffer, *buffer_len)) + return FALSE; + + lograw(buffer, *buffer_len); + + return TRUE; +} + + +#if defined(USE_WINSOCK) && !defined(CURL_WINDOWS_UWP) +/* + * Winsock select() does not support standard file descriptors, + * it can only check SOCKETs. The following function is an attempt + * to re-create a select() function with support for other handle types. + * + * select() function with support for Winsock2 sockets and all + * other handle types supported by WaitForMultipleObjectsEx() as + * well as disk files, anonymous and names pipes, and character input. + * + * https://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx + * https://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx + */ +struct select_ws_wait_data { + HANDLE handle; /* actual handle to wait for during select */ + HANDLE signal; /* internal event to signal handle trigger */ + HANDLE abort; /* internal event to abort waiting threads */ +}; +#ifdef _WIN32_WCE +static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter) +#else +#include +static unsigned int WINAPI select_ws_wait_thread(void *lpParameter) +#endif +{ + struct select_ws_wait_data *data; + HANDLE signal, handle, handles[2]; + INPUT_RECORD inputrecord; + LARGE_INTEGER size, pos; + DWORD type, length, ret; + + /* retrieve handles from internal structure */ + data = (struct select_ws_wait_data *) lpParameter; + if(data) { + handle = data->handle; + handles[0] = data->abort; + handles[1] = handle; + signal = data->signal; + free(data); + } + else + return (DWORD)-1; + + /* retrieve the type of file to wait on */ + type = GetFileType(handle); + switch(type) { + case FILE_TYPE_DISK: + /* The handle represents a file on disk, this means: + * - WaitForMultipleObjectsEx will always be signalled for it. + * - comparison of current position in file and total size of + * the file can be used to check if we reached the end yet. + * + * Approach: Loop till either the internal event is signalled + * or if the end of the file has already been reached. + */ + while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE) + == WAIT_TIMEOUT) { + /* get total size of file */ + length = 0; + size.QuadPart = 0; + size.LowPart = GetFileSize(handle, &length); + if((size.LowPart != INVALID_FILE_SIZE) || + (GetLastError() == NO_ERROR)) { + size.HighPart = (LONG)length; + /* get the current position within the file */ + pos.QuadPart = 0; + pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart, FILE_CURRENT); + if((pos.LowPart != INVALID_SET_FILE_POINTER) || + (GetLastError() == NO_ERROR)) { + /* compare position with size, abort if not equal */ + if(size.QuadPart == pos.QuadPart) { + /* sleep and continue waiting */ + SleepEx(0, FALSE); + continue; + } + } + } + /* there is some data available, stop waiting */ + logmsg("[select_ws_wait_thread] data available, DISK: %p", handle); + SetEvent(signal); + } + break; + + case FILE_TYPE_CHAR: + /* The handle represents a character input, this means: + * - WaitForMultipleObjectsEx will be signalled on any kind of input, + * including mouse and window size events we do not care about. + * + * Approach: Loop till either the internal event is signalled + * or we get signalled for an actual key-event. + */ + while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE) + == WAIT_OBJECT_0 + 1) { + /* check if this is an actual console handle */ + if(GetConsoleMode(handle, &ret)) { + /* retrieve an event from the console buffer */ + length = 0; + if(PeekConsoleInput(handle, &inputrecord, 1, &length)) { + /* check if the event is not an actual key-event */ + if(length == 1 && inputrecord.EventType != KEY_EVENT) { + /* purge the non-key-event and continue waiting */ + ReadConsoleInput(handle, &inputrecord, 1, &length); + continue; + } + } + } + /* there is some data available, stop waiting */ + logmsg("[select_ws_wait_thread] data available, CHAR: %p", handle); + SetEvent(signal); + } + break; + + case FILE_TYPE_PIPE: + /* The handle represents an anonymous or named pipe, this means: + * - WaitForMultipleObjectsEx will always be signalled for it. + * - peek into the pipe and retrieve the amount of data available. + * + * Approach: Loop till either the internal event is signalled + * or there is data in the pipe available for reading. + */ + while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE) + == WAIT_TIMEOUT) { + /* peek into the pipe and retrieve the amount of data available */ + length = 0; + if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) { + /* if there is no data available, sleep and continue waiting */ + if(length == 0) { + SleepEx(0, FALSE); + continue; + } + else { + logmsg("[select_ws_wait_thread] PeekNamedPipe len: %lu", length); + } + } + else { + /* if the pipe has NOT been closed, sleep and continue waiting */ + ret = GetLastError(); + if(ret != ERROR_BROKEN_PIPE) { + logmsg("[select_ws_wait_thread] PeekNamedPipe error: %lu", ret); + SleepEx(0, FALSE); + continue; + } + else { + logmsg("[select_ws_wait_thread] pipe closed, PIPE: %p", handle); + } + } + /* there is some data available, stop waiting */ + logmsg("[select_ws_wait_thread] data available, PIPE: %p", handle); + SetEvent(signal); + } + break; + + default: + /* The handle has an unknown type, try to wait on it */ + if(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE) + == WAIT_OBJECT_0 + 1) { + logmsg("[select_ws_wait_thread] data available, HANDLE: %p", handle); + SetEvent(signal); + } + break; + } + + return 0; +} +static HANDLE select_ws_wait(HANDLE handle, HANDLE signal, HANDLE abort) +{ +#ifdef _WIN32_WCE + typedef HANDLE curl_win_thread_handle_t; +#else + typedef uintptr_t curl_win_thread_handle_t; +#endif + struct select_ws_wait_data *data; + curl_win_thread_handle_t thread; + + /* allocate internal waiting data structure */ + data = malloc(sizeof(struct select_ws_wait_data)); + if(data) { + data->handle = handle; + data->signal = signal; + data->abort = abort; + + /* launch waiting thread */ +#ifdef _WIN32_WCE + thread = CreateThread(NULL, 0, &select_ws_wait_thread, data, 0, NULL); +#else + thread = _beginthreadex(NULL, 0, &select_ws_wait_thread, data, 0, NULL); +#endif + + /* free data if thread failed to launch */ + if(!thread) { + free(data); + } + return (HANDLE)thread; + } + return NULL; +} +struct select_ws_data { + int fd; /* provided file descriptor (indexed by nfd) */ + long wsastate; /* internal pre-select state (indexed by nfd) */ + curl_socket_t wsasock; /* internal socket handle (indexed by nws) */ + WSAEVENT wsaevent; /* internal select event (indexed by nws) */ + HANDLE signal; /* internal thread signal (indexed by nth) */ + HANDLE thread; /* internal thread handle (indexed by nth) */ +}; +static int select_ws(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, struct timeval *tv) +{ + DWORD timeout_ms, wait, nfd, nth, nws, i; + HANDLE abort, signal, handle, *handles; + fd_set readsock, writesock, exceptsock; + struct select_ws_data *data; + WSANETWORKEVENTS wsaevents; + curl_socket_t wsasock; + int error, ret, fd; + WSAEVENT wsaevent; + + /* check if the input value is valid */ + if(nfds < 0) { + errno = EINVAL; + return -1; + } + + /* convert struct timeval to milliseconds */ + if(tv) { + timeout_ms = (DWORD)curlx_tvtoms(tv); + } + else { + timeout_ms = INFINITE; + } + + /* check if we got descriptors, sleep in case we got none */ + if(!nfds) { + SleepEx(timeout_ms, FALSE); + return 0; + } + + /* create internal event to abort waiting threads */ + abort = CreateEvent(NULL, TRUE, FALSE, NULL); + if(!abort) { + errno = ENOMEM; + return -1; + } + + /* allocate internal array for the internal data */ + data = calloc(nfds, sizeof(struct select_ws_data)); + if(!data) { + CloseHandle(abort); + errno = ENOMEM; + return -1; + } + + /* allocate internal array for the internal event handles */ + handles = calloc(nfds + 1, sizeof(HANDLE)); + if(!handles) { + CloseHandle(abort); + free(data); + errno = ENOMEM; + return -1; + } + + /* loop over the handles in the input descriptor sets */ + nfd = 0; /* number of handled file descriptors */ + nth = 0; /* number of internal waiting threads */ + nws = 0; /* number of handled Winsock sockets */ + for(fd = 0; fd < nfds; fd++) { + wsasock = (curl_socket_t)fd; + wsaevents.lNetworkEvents = 0; + handles[nfd] = 0; + + FD_ZERO(&readsock); + FD_ZERO(&writesock); + FD_ZERO(&exceptsock); + + if(FD_ISSET(wsasock, readfds)) { + FD_SET(wsasock, &readsock); + wsaevents.lNetworkEvents |= FD_READ|FD_ACCEPT|FD_CLOSE; + } + + if(FD_ISSET(wsasock, writefds)) { + FD_SET(wsasock, &writesock); + wsaevents.lNetworkEvents |= FD_WRITE|FD_CONNECT|FD_CLOSE; + } + + if(FD_ISSET(wsasock, exceptfds)) { + FD_SET(wsasock, &exceptsock); + wsaevents.lNetworkEvents |= FD_OOB; + } + + /* only wait for events for which we actually care */ + if(wsaevents.lNetworkEvents) { + data[nfd].fd = fd; + if(fd == fileno(stdin)) { + signal = CreateEvent(NULL, TRUE, FALSE, NULL); + if(signal) { + handle = GetStdHandle(STD_INPUT_HANDLE); + handle = select_ws_wait(handle, signal, abort); + if(handle) { + handles[nfd] = signal; + data[nth].signal = signal; + data[nth].thread = handle; + nfd++; + nth++; + } + else { + CloseHandle(signal); + } + } + } + else if(fd == fileno(stdout)) { + handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE); + nfd++; + } + else if(fd == fileno(stderr)) { + handles[nfd] = GetStdHandle(STD_ERROR_HANDLE); + nfd++; + } + else { + wsaevent = WSACreateEvent(); + if(wsaevent != WSA_INVALID_EVENT) { + if(wsaevents.lNetworkEvents & FD_WRITE) { + send(wsasock, NULL, 0, 0); /* reset FD_WRITE */ + } + error = WSAEventSelect(wsasock, wsaevent, wsaevents.lNetworkEvents); + if(error != SOCKET_ERROR) { + handles[nfd] = (HANDLE)wsaevent; + data[nws].wsasock = wsasock; + data[nws].wsaevent = wsaevent; + data[nfd].wsastate = 0; + tv->tv_sec = 0; + tv->tv_usec = 0; + /* check if the socket is already ready */ + if(select(fd + 1, &readsock, &writesock, &exceptsock, tv) == 1) { + logmsg("[select_ws] socket %d is ready", fd); + WSASetEvent(wsaevent); + if(FD_ISSET(wsasock, &readsock)) + data[nfd].wsastate |= FD_READ; + if(FD_ISSET(wsasock, &writesock)) + data[nfd].wsastate |= FD_WRITE; + if(FD_ISSET(wsasock, &exceptsock)) + data[nfd].wsastate |= FD_OOB; + } + nfd++; + nws++; + } + else { + WSACloseEvent(wsaevent); + signal = CreateEvent(NULL, TRUE, FALSE, NULL); + if(signal) { + handle = (HANDLE)wsasock; + handle = select_ws_wait(handle, signal, abort); + if(handle) { + handles[nfd] = signal; + data[nth].signal = signal; + data[nth].thread = handle; + nfd++; + nth++; + } + else { + CloseHandle(signal); + } + } + } + } + } + } + } + + /* wait on the number of handles */ + wait = nfd; + + /* make sure we stop waiting on exit signal event */ + if(exit_event) { + /* we allocated handles nfds + 1 for this */ + handles[nfd] = exit_event; + wait += 1; + } + + /* wait for one of the internal handles to trigger */ + wait = WaitForMultipleObjectsEx(wait, handles, FALSE, timeout_ms, FALSE); + + /* signal the abort event handle and join the other waiting threads */ + SetEvent(abort); + for(i = 0; i < nth; i++) { + WaitForSingleObjectEx(data[i].thread, INFINITE, FALSE); + CloseHandle(data[i].thread); + } + + /* loop over the internal handles returned in the descriptors */ + ret = 0; /* number of ready file descriptors */ + for(i = 0; i < nfd; i++) { + fd = data[i].fd; + handle = handles[i]; + wsasock = (curl_socket_t)fd; + + /* check if the current internal handle was triggered */ + if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= i && + WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) { + /* first handle stdin, stdout and stderr */ + if(fd == fileno(stdin)) { + /* stdin is never ready for write or exceptional */ + FD_CLR(wsasock, writefds); + FD_CLR(wsasock, exceptfds); + } + else if(fd == fileno(stdout) || fd == fileno(stderr)) { + /* stdout and stderr are never ready for read or exceptional */ + FD_CLR(wsasock, readfds); + FD_CLR(wsasock, exceptfds); + } + else { + /* try to handle the event with the Winsock2 functions */ + wsaevents.lNetworkEvents = 0; + error = WSAEnumNetworkEvents(wsasock, handle, &wsaevents); + if(error != SOCKET_ERROR) { + /* merge result from pre-check using select */ + wsaevents.lNetworkEvents |= data[i].wsastate; + + /* remove from descriptor set if not ready for read/accept/close */ + if(!(wsaevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))) + FD_CLR(wsasock, readfds); + + /* remove from descriptor set if not ready for write/connect */ + if(!(wsaevents.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))) + FD_CLR(wsasock, writefds); + + /* remove from descriptor set if not exceptional */ + if(!(wsaevents.lNetworkEvents & FD_OOB)) + FD_CLR(wsasock, exceptfds); + } + } + + /* check if the event has not been filtered using specific tests */ + if(FD_ISSET(wsasock, readfds) || FD_ISSET(wsasock, writefds) || + FD_ISSET(wsasock, exceptfds)) { + ret++; + } + } + else { + /* remove from all descriptor sets since this handle did not trigger */ + FD_CLR(wsasock, readfds); + FD_CLR(wsasock, writefds); + FD_CLR(wsasock, exceptfds); + } + } + + for(fd = 0; fd < nfds; fd++) { + if(FD_ISSET(fd, readfds)) + logmsg("[select_ws] %d is readable", fd); + if(FD_ISSET(fd, writefds)) + logmsg("[select_ws] %d is writable", fd); + if(FD_ISSET(fd, exceptfds)) + logmsg("[select_ws] %d is exceptional", fd); + } + + for(i = 0; i < nws; i++) { + WSAEventSelect(data[i].wsasock, NULL, 0); + WSACloseEvent(data[i].wsaevent); + } + + for(i = 0; i < nth; i++) { + CloseHandle(data[i].signal); + } + CloseHandle(abort); + + free(handles); + free(data); + + return ret; +} +#define select(a,b,c,d,e) select_ws(a,b,c,d,e) +#endif /* USE_WINSOCK */ + + +/* Perform the disconnect handshake with sockfilt + * This involves waiting for the disconnect acknowledgment after the DISC + * command, while throwing away anything else that might come in before + * that. + */ +static bool disc_handshake(void) +{ + if(!write_stdout("DISC\n", 5)) + return FALSE; + + do { + unsigned char buffer[BUFFER_SIZE]; + ssize_t buffer_len; + if(!read_stdin(buffer, 5)) + return FALSE; + logmsg("Received %c%c%c%c (on stdin)", + buffer[0], buffer[1], buffer[2], buffer[3]); + + if(!memcmp("ACKD", buffer, 4)) { + /* got the ack we were waiting for */ + break; + } + else if(!memcmp("DISC", buffer, 4)) { + logmsg("Crikey! Client also wants to disconnect"); + if(!write_stdout("ACKD\n", 5)) + return FALSE; + } + else if(!memcmp("DATA", buffer, 4)) { + /* We must read more data to stay in sync */ + logmsg("Throwing away data bytes"); + if(!read_data_block(buffer, sizeof(buffer), &buffer_len)) + return FALSE; + + } + else if(!memcmp("QUIT", buffer, 4)) { + /* just die */ + logmsg("quits"); + return FALSE; + } + else { + logmsg("Error: unexpected message; aborting"); + /* + * The only other messages that could occur here are PING and PORT, + * and both of them occur at the start of a test when nothing should be + * trying to DISC. Therefore, we should not ever get here, but if we + * do, it's probably due to some kind of unclean shutdown situation so + * us shutting down is what we probably ought to be doing, anyway. + */ + return FALSE; + } + + } while(TRUE); + return TRUE; +} + +/* + sockfdp is a pointer to an established stream or CURL_SOCKET_BAD + + if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must + accept() +*/ +static bool juggle(curl_socket_t *sockfdp, + curl_socket_t listenfd, + enum sockmode *mode) +{ + struct timeval timeout; + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + curl_socket_t sockfd = CURL_SOCKET_BAD; + int maxfd = -99; + ssize_t rc; + int error = 0; + + unsigned char buffer[BUFFER_SIZE]; + char data[16]; + + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + +#ifdef HAVE_GETPPID + /* As a last resort, quit if sockfilt process becomes orphan. Just in case + parent ftpserver process has died without killing its sockfilt children */ + if(getppid() <= 1) { + logmsg("process becomes orphan, exiting"); + return FALSE; + } +#endif + + timeout.tv_sec = 120; + timeout.tv_usec = 0; + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + + FD_SET((curl_socket_t)fileno(stdin), &fds_read); + + switch(*mode) { + + case PASSIVE_LISTEN: + + /* server mode */ + sockfd = listenfd; + /* there's always a socket to wait for */ + FD_SET(sockfd, &fds_read); + maxfd = (int)sockfd; + break; + + case PASSIVE_CONNECT: + + sockfd = *sockfdp; + if(CURL_SOCKET_BAD == sockfd) { + /* eeek, we are supposedly connected and then this cannot be -1 ! */ + logmsg("socket is -1! on %s:%d", __FILE__, __LINE__); + maxfd = 0; /* stdin */ + } + else { + /* there's always a socket to wait for */ + FD_SET(sockfd, &fds_read); + maxfd = (int)sockfd; + } + break; + + case ACTIVE: + + sockfd = *sockfdp; + /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */ + if(CURL_SOCKET_BAD != sockfd) { + FD_SET(sockfd, &fds_read); + maxfd = (int)sockfd; + } + else { + logmsg("No socket to read on"); + maxfd = 0; + } + break; + + case ACTIVE_DISCONNECT: + + logmsg("disconnected, no socket to read on"); + maxfd = 0; + sockfd = CURL_SOCKET_BAD; + break; + + } /* switch(*mode) */ + + + do { + + /* select() blocking behavior call on blocking descriptors please */ + + rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout); + + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + + } while((rc == -1) && ((error = errno) == EINTR)); + + if(rc < 0) { + logmsg("select() failed with error: (%d) %s", + error, strerror(error)); + return FALSE; + } + + if(rc == 0) + /* timeout */ + return TRUE; + + + if(FD_ISSET(fileno(stdin), &fds_read)) { + ssize_t buffer_len; + /* read from stdin, commands/data to be dealt with and possibly passed on + to the socket + + protocol: + + 4 letter command + LF [mandatory] + + 4-digit hexadecimal data length + LF [if the command takes data] + data [the data being as long as set above] + + Commands: + + DATA - plain pass-through data + */ + + if(!read_stdin(buffer, 5)) + return FALSE; + + logmsg("Received %c%c%c%c (on stdin)", + buffer[0], buffer[1], buffer[2], buffer[3]); + + if(!memcmp("PING", buffer, 4)) { + /* send reply on stdout, just proving we are alive */ + if(!write_stdout("PONG\n", 5)) + return FALSE; + } + + else if(!memcmp("PORT", buffer, 4)) { + /* Question asking us what PORT number we are listening to. + Replies to PORT with "IPv[num]/[port]" */ + msnprintf((char *)buffer, sizeof(buffer), "%s/%hu\n", ipv_inuse, port); + buffer_len = (ssize_t)strlen((char *)buffer); + msnprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len); + if(!write_stdout(data, 10)) + return FALSE; + if(!write_stdout(buffer, buffer_len)) + return FALSE; + } + else if(!memcmp("QUIT", buffer, 4)) { + /* just die */ + logmsg("quits"); + return FALSE; + } + else if(!memcmp("DATA", buffer, 4)) { + /* data IN => data OUT */ + if(!read_data_block(buffer, sizeof(buffer), &buffer_len)) + return FALSE; + + if(*mode == PASSIVE_LISTEN) { + logmsg("*** We are disconnected!"); + if(!disc_handshake()) + return FALSE; + } + else { + /* send away on the socket */ + ssize_t bytes_written = swrite(sockfd, buffer, buffer_len); + if(bytes_written != buffer_len) { + logmsg("Not all data was sent. Bytes to send: %zd sent: %zd", + buffer_len, bytes_written); + } + } + } + else if(!memcmp("DISC", buffer, 4)) { + /* disconnect! */ + if(!write_stdout("ACKD\n", 5)) + return FALSE; + if(sockfd != CURL_SOCKET_BAD) { + logmsg("====> Client forcibly disconnected"); + sclose(sockfd); + *sockfdp = CURL_SOCKET_BAD; + if(*mode == PASSIVE_CONNECT) + *mode = PASSIVE_LISTEN; + else + *mode = ACTIVE_DISCONNECT; + } + else + logmsg("attempt to close already dead connection"); + return TRUE; + } + } + + + if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) { + ssize_t nread_socket; + if(*mode == PASSIVE_LISTEN) { + /* there's no stream set up yet, this is an indication that there's a + client connecting. */ + curl_socket_t newfd = accept(sockfd, NULL, NULL); + if(CURL_SOCKET_BAD == newfd) { + error = SOCKERRNO; + logmsg("accept(%" FMT_SOCKET_T ", NULL, NULL) " + "failed with error: (%d) %s", sockfd, error, sstrerror(error)); + } + else { + logmsg("====> Client connect"); + if(!write_stdout("CNCT\n", 5)) + return FALSE; + *sockfdp = newfd; /* store the new socket */ + *mode = PASSIVE_CONNECT; /* we have connected */ + } + return TRUE; + } + + /* read from socket, pass on data to stdout */ + nread_socket = sread(sockfd, buffer, sizeof(buffer)); + + if(nread_socket > 0) { + msnprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket); + if(!write_stdout(data, 10)) + return FALSE; + if(!write_stdout(buffer, nread_socket)) + return FALSE; + + logmsg("< %zd bytes data, client => server", nread_socket); + lograw(buffer, nread_socket); + } + + if(nread_socket <= 0) { + logmsg("====> Client disconnect"); + if(!disc_handshake()) + return FALSE; + sclose(sockfd); + *sockfdp = CURL_SOCKET_BAD; + if(*mode == PASSIVE_CONNECT) + *mode = PASSIVE_LISTEN; + else + *mode = ACTIVE_DISCONNECT; + return TRUE; + } + } + + return TRUE; +} + +static curl_socket_t sockdaemon(curl_socket_t sock, + unsigned short *listenport) +{ + /* passive daemon style */ + srvr_sockaddr_union_t listener; + int flag; + int rc; + int totdelay = 0; + int maxretr = 10; + int delay = 20; + int attempt = 0; + int error = 0; + + do { + attempt++; + flag = 1; + rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag)); + if(rc) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + if(maxretr) { + rc = wait_ms(delay); + if(rc) { + /* should not happen */ + error = errno; + logmsg("wait_ms() failed with error: (%d) %s", + error, strerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + sclose(sock); + return CURL_SOCKET_BAD; + } + totdelay += delay; + delay *= 2; /* double the sleep for next attempt */ + } + } + } while(rc && maxretr--); + + if(rc) { + logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", + attempt, totdelay, error, strerror(error)); + logmsg("Continuing anyway..."); + } + + /* When the specified listener port is zero, it is actually a + request to let the system choose a non-zero available port. */ + +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + memset(&listener.sa4, 0, sizeof(listener.sa4)); + listener.sa4.sin_family = AF_INET; + listener.sa4.sin_addr.s_addr = INADDR_ANY; + listener.sa4.sin_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa4)); +#ifdef USE_IPV6 + } + else { + memset(&listener.sa6, 0, sizeof(listener.sa6)); + listener.sa6.sin6_family = AF_INET6; + listener.sa6.sin6_addr = in6addr_any; + listener.sa6.sin6_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa6)); + } +#endif /* USE_IPV6 */ + if(rc) { + error = SOCKERRNO; + logmsg("Error binding socket on port %hu: (%d) %s", + *listenport, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + if(!*listenport) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + la_size = sizeof(localaddr.sa4); +#ifdef USE_IPV6 + else + la_size = sizeof(localaddr.sa6); +#endif + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + *listenport = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + *listenport = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!*listenport) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + sclose(sock); + return CURL_SOCKET_BAD; + } + } + + /* bindonly option forces no listening */ + if(bind_only) { + logmsg("instructed to bind port without listening"); + return sock; + } + + /* start accepting connections */ + rc = listen(sock, 5); + if(0 != rc) { + error = SOCKERRNO; + logmsg("listen(%" FMT_SOCKET_T ", 5) failed with error: (%d) %s", + sock, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + return sock; +} + + +int main(int argc, char *argv[]) +{ + srvr_sockaddr_union_t me; + curl_socket_t sock = CURL_SOCKET_BAD; + curl_socket_t msgsock = CURL_SOCKET_BAD; + int wrotepidfile = 0; + int wroteportfile = 0; + const char *pidname = ".sockfilt.pid"; + const char *portname = NULL; /* none by default */ + bool juggle_again; + int rc; + int error; + int arg = 1; + enum sockmode mode = PASSIVE_LISTEN; /* default */ + const char *addr = NULL; + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("sockfilt IPv4%s\n", +#ifdef USE_IPV6 + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--verbose", argv[arg])) { + verbose = TRUE; + arg++; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv6"; + use_ipv6 = TRUE; +#endif + arg++; + } + else if(!strcmp("--ipv4", argv[arg])) { + /* for completeness, we support this option as well */ +#ifdef USE_IPV6 + ipv_inuse = "IPv4"; + use_ipv6 = FALSE; +#endif + arg++; + } + else if(!strcmp("--bindonly", argv[arg])) { + bind_only = TRUE; + arg++; + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + port = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--connect", argv[arg])) { + /* Asked to actively connect to the specified local port instead of + doing a passive server-style listening. */ + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + if((endptr != argv[arg] + strlen(argv[arg])) || + (ulnum < 1025UL) || (ulnum > 65535UL)) { + fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n", + argv[arg]); + return 0; + } + connectport = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--addr", argv[arg])) { + /* Set an IP address to use with --connect; otherwise use localhost */ + arg++; + if(argc > arg) { + addr = argv[arg]; + arg++; + } + } + else { + puts("Usage: sockfilt [option]\n" + " --version\n" + " --verbose\n" + " --logfile [file]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --bindonly\n" + " --port [port]\n" + " --connect [port]\n" + " --addr [address]"); + return 0; + } + } + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); + + setmode(fileno(stdin), O_BINARY); + setmode(fileno(stdout), O_BINARY); + setmode(fileno(stderr), O_BINARY); +#endif + + install_signal_handlers(false); + +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + sock = socket(AF_INET, SOCK_STREAM, 0); +#ifdef USE_IPV6 + else + sock = socket(AF_INET6, SOCK_STREAM, 0); +#endif + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", error, sstrerror(error)); + write_stdout("FAIL\n", 5); + goto sockfilt_cleanup; + } + + if(connectport) { + /* Active mode, we should connect to the given port number */ + mode = ACTIVE; +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + memset(&me.sa4, 0, sizeof(me.sa4)); + me.sa4.sin_family = AF_INET; + me.sa4.sin_port = htons(connectport); + me.sa4.sin_addr.s_addr = INADDR_ANY; + if(!addr) + addr = "127.0.0.1"; + Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr); + + rc = connect(sock, &me.sa, sizeof(me.sa4)); +#ifdef USE_IPV6 + } + else { + memset(&me.sa6, 0, sizeof(me.sa6)); + me.sa6.sin6_family = AF_INET6; + me.sa6.sin6_port = htons(connectport); + if(!addr) + addr = "::1"; + Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr); + + rc = connect(sock, &me.sa, sizeof(me.sa6)); + } +#endif /* USE_IPV6 */ + if(rc) { + error = SOCKERRNO; + logmsg("Error connecting to port %hu: (%d) %s", + connectport, error, sstrerror(error)); + write_stdout("FAIL\n", 5); + goto sockfilt_cleanup; + } + logmsg("====> Client connect"); + msgsock = sock; /* use this as stream */ + } + else { + /* passive daemon style */ + sock = sockdaemon(sock, &port); + if(CURL_SOCKET_BAD == sock) { + write_stdout("FAIL\n", 5); + goto sockfilt_cleanup; + } + msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ + } + + logmsg("Running %s version", ipv_inuse); + + if(connectport) + logmsg("Connected to port %hu", connectport); + else if(bind_only) + logmsg("Bound without listening on port %hu", port); + else + logmsg("Listening on port %hu", port); + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) { + write_stdout("FAIL\n", 5); + goto sockfilt_cleanup; + } + if(portname) { + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) { + write_stdout("FAIL\n", 5); + goto sockfilt_cleanup; + } + } + + do { + juggle_again = juggle(&msgsock, sock, &mode); + } while(juggle_again); + +sockfilt_cleanup: + + if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) + sclose(msgsock); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + restore_signal_handlers(false); + + if(got_exit_signal) { + logmsg("============> sockfilt exits with signal (%d)", exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("============> sockfilt quits"); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/socksd.c b/local-test-curl-delta-01/afc-curl/tests/server/socksd.c new file mode 100644 index 0000000000000000000000000000000000000000..5206c6bf59d1f323489ea7e34e8cf75acf5a90c0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/socksd.c @@ -0,0 +1,1172 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" +#include + +/* Function + * + * Accepts a TCP connection on a custom port (IPv4 or IPv6). Connects to a + * given addr + port backend (that is NOT extracted form the client's + * request). The backend server default to connect to can be set with + * --backend and --backendport. + * + * Read commands from FILE (set with --config). The commands control how to + * act and is reset to defaults each client TCP connect. + * + * Config file keywords: + * + * "version [number: 5]" - requires the communication to use this version. + * "nmethods_min [number: 1]" - the minimum numberf NMETHODS the client must + * state + * "nmethods_max [number: 3]" - the minimum numberf NMETHODS the client must + * state + * "user [string]" - the user name that must match (if method is 2) + * "password [string]" - the password that must match (if method is 2) + * "backend [IPv4]" - numerical IPv4 address of backend to connect to + * "backendport [number:0]" - TCP port of backend to connect to. 0 means use + the client's specified port number. + * "method [number: 0]" - connect method to respond with: + * 0 - no auth + * 1 - GSSAPI (not supported) + * 2 - user + password + * "response [number]" - the decimal number to respond to a connect + * SOCKS5: 0 is OK, SOCKS4: 90 is ok + * + */ + +/* based on sockfilt.c */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "inet_pton.h" +#include "util.h" +#include "server_sockaddr.h" +#include "warnless.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef EAGAIN +#define EAGAIN 11 /* errno.h value */ +#undef ENOMEM +#define ENOMEM 12 /* errno.h value */ +#undef EINVAL +#define EINVAL 22 /* errno.h value */ +#endif + +#define DEFAULT_PORT 8905 + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/socksd.log" +#endif + +#ifndef DEFAULT_REQFILE +#define DEFAULT_REQFILE "log/socksd-request.log" +#endif + +#ifndef DEFAULT_CONFIG +#define DEFAULT_CONFIG "socksd.config" +#endif + +static const char *backendaddr = "127.0.0.1"; +static unsigned short backendport = 0; /* default is use client's */ + +struct configurable { + unsigned char version; /* initial version byte in the request must match + this */ + unsigned char nmethods_min; /* minimum number of nmethods to expect */ + unsigned char nmethods_max; /* maximum number of nmethods to expect */ + unsigned char responseversion; + unsigned char responsemethod; + unsigned char reqcmd; + unsigned char connectrep; + unsigned short port; /* backend port */ + char addr[32]; /* backend IPv4 numerical */ + char user[256]; + char password[256]; +}; + +#define CONFIG_VERSION 5 +#define CONFIG_NMETHODS_MIN 1 /* unauth, gssapi, auth */ +#define CONFIG_NMETHODS_MAX 3 +#define CONFIG_RESPONSEVERSION CONFIG_VERSION +#define CONFIG_RESPONSEMETHOD 0 /* no auth */ +#define CONFIG_REQCMD 1 /* CONNECT */ +#define CONFIG_PORT backendport +#define CONFIG_ADDR backendaddr +#define CONFIG_CONNECTREP 0 + +static struct configurable config; + +const char *serverlogfile = DEFAULT_LOGFILE; +static const char *reqlogfile = DEFAULT_REQFILE; +static const char *configfile = DEFAULT_CONFIG; + +static const char *socket_type = "IPv4"; +static unsigned short port = DEFAULT_PORT; + +static void resetdefaults(void) +{ + logmsg("Reset to defaults"); + config.version = CONFIG_VERSION; + config.nmethods_min = CONFIG_NMETHODS_MIN; + config.nmethods_max = CONFIG_NMETHODS_MAX; + config.responseversion = CONFIG_RESPONSEVERSION; + config.responsemethod = CONFIG_RESPONSEMETHOD; + config.reqcmd = CONFIG_REQCMD; + config.connectrep = CONFIG_CONNECTREP; + config.port = CONFIG_PORT; + strcpy(config.addr, CONFIG_ADDR); + strcpy(config.user, "user"); + strcpy(config.password, "password"); +} + +static unsigned char byteval(char *value) +{ + unsigned long num = strtoul(value, NULL, 10); + return num & 0xff; +} + +static unsigned short shortval(char *value) +{ + unsigned long num = strtoul(value, NULL, 10); + return num & 0xffff; +} + +static enum { + socket_domain_inet = AF_INET +#ifdef USE_IPV6 + , socket_domain_inet6 = AF_INET6 +#endif +#ifdef USE_UNIX_SOCKETS + , socket_domain_unix = AF_UNIX +#endif +} socket_domain = AF_INET; + +static void getconfig(void) +{ + FILE *fp = fopen(configfile, FOPEN_READTEXT); + resetdefaults(); + if(fp) { + char buffer[512]; + logmsg("parse config file"); + while(fgets(buffer, sizeof(buffer), fp)) { + char key[32]; + char value[260]; + if(2 == sscanf(buffer, "%31s %259s", key, value)) { + if(!strcmp(key, "version")) { + config.version = byteval(value); + logmsg("version [%d] set", config.version); + } + else if(!strcmp(key, "nmethods_min")) { + config.nmethods_min = byteval(value); + logmsg("nmethods_min [%d] set", config.nmethods_min); + } + else if(!strcmp(key, "nmethods_max")) { + config.nmethods_max = byteval(value); + logmsg("nmethods_max [%d] set", config.nmethods_max); + } + else if(!strcmp(key, "backend")) { + strcpy(config.addr, value); + logmsg("backend [%s] set", config.addr); + } + else if(!strcmp(key, "backendport")) { + config.port = shortval(value); + logmsg("backendport [%d] set", config.port); + } + else if(!strcmp(key, "user")) { + strcpy(config.user, value); + logmsg("user [%s] set", config.user); + } + else if(!strcmp(key, "password")) { + strcpy(config.password, value); + logmsg("password [%s] set", config.password); + } + /* Methods: + o X'00' NO AUTHENTICATION REQUIRED + o X'01' GSSAPI + o X'02' USERNAME/PASSWORD + */ + else if(!strcmp(key, "method")) { + config.responsemethod = byteval(value); + logmsg("method [%d] set", config.responsemethod); + } + else if(!strcmp(key, "response")) { + config.connectrep = byteval(value); + logmsg("response [%d] set", config.connectrep); + } + } + } + fclose(fp); + } +} + +static void loghex(unsigned char *buffer, ssize_t len) +{ + char data[1200]; + ssize_t i; + unsigned char *ptr = buffer; + char *optr = data; + ssize_t width = 0; + int left = sizeof(data); + + for(i = 0; i < len && (left >= 0); i++) { + msnprintf(optr, left, "%02x", ptr[i]); + width += 2; + optr += 2; + left -= 2; + } + if(width) + logmsg("'%s'", data); +} + +/* RFC 1928, SOCKS5 byte index */ +#define SOCKS5_VERSION 0 +#define SOCKS5_NMETHODS 1 /* number of methods that is listed */ + +/* in the request: */ +#define SOCKS5_REQCMD 1 +#define SOCKS5_RESERVED 2 +#define SOCKS5_ATYP 3 +#define SOCKS5_DSTADDR 4 + +/* connect response */ +#define SOCKS5_REP 1 +#define SOCKS5_BNDADDR 4 + +/* auth request */ +#define SOCKS5_ULEN 1 +#define SOCKS5_UNAME 2 + +#define SOCKS4_CD 1 +#define SOCKS4_DSTPORT 2 + +/* connect to a given IPv4 address, not the one asked for */ +static curl_socket_t socksconnect(unsigned short connectport, + const char *connectaddr) +{ + int rc; + srvr_sockaddr_union_t me; + curl_socket_t sock = socket(AF_INET, SOCK_STREAM, 0); + if(sock == CURL_SOCKET_BAD) + return CURL_SOCKET_BAD; + memset(&me.sa4, 0, sizeof(me.sa4)); + me.sa4.sin_family = AF_INET; + me.sa4.sin_port = htons(connectport); + me.sa4.sin_addr.s_addr = INADDR_ANY; + Curl_inet_pton(AF_INET, connectaddr, &me.sa4.sin_addr); + + rc = connect(sock, &me.sa, sizeof(me.sa4)); + + if(rc) { + int error = SOCKERRNO; + logmsg("Error connecting to %s:%hu: (%d) %s", + connectaddr, connectport, error, sstrerror(error)); + return CURL_SOCKET_BAD; + } + logmsg("Connected fine to %s:%d", connectaddr, connectport); + return sock; +} + +static curl_socket_t socks4(curl_socket_t fd, + unsigned char *buffer, + ssize_t rc) +{ + unsigned char response[256 + 16]; + curl_socket_t connfd; + unsigned char cd; + unsigned short s4port; + + if(buffer[SOCKS4_CD] != 1) { + logmsg("SOCKS4 CD is not 1: %d", buffer[SOCKS4_CD]); + return CURL_SOCKET_BAD; + } + if(rc < 9) { + logmsg("SOCKS4 connect message too short: %zd", rc); + return CURL_SOCKET_BAD; + } + if(!config.port) + s4port = (unsigned short)((buffer[SOCKS4_DSTPORT] << 8) | + (buffer[SOCKS4_DSTPORT + 1])); + else + s4port = config.port; + + connfd = socksconnect(s4port, config.addr); + if(connfd == CURL_SOCKET_BAD) { + /* failed */ + cd = 91; + } + else { + /* success */ + cd = 90; + } + response[0] = 0; /* reply version 0 */ + response[1] = cd; /* result */ + /* copy port and address from connect request */ + memcpy(&response[2], &buffer[SOCKS4_DSTPORT], 6); + rc = (send)(fd, (char *)response, 8, 0); + if(rc != 8) { + logmsg("Sending SOCKS4 response failed!"); + return CURL_SOCKET_BAD; + } + logmsg("Sent %zd bytes", rc); + loghex(response, rc); + + if(cd == 90) + /* now do the transfer */ + return connfd; + + if(connfd != CURL_SOCKET_BAD) + sclose(connfd); + + return CURL_SOCKET_BAD; +} + +static curl_socket_t sockit(curl_socket_t fd) +{ + unsigned char buffer[2*256 + 16]; + unsigned char response[2*256 + 16]; + ssize_t rc; + unsigned char len; + unsigned char type; + unsigned char rep = 0; + unsigned char *address; + unsigned short socksport; + curl_socket_t connfd = CURL_SOCKET_BAD; + unsigned short s5port; + + getconfig(); + + rc = recv(fd, (char *)buffer, sizeof(buffer), 0); + if(rc <= 0) { + logmsg("SOCKS identifier message missing, recv returned %zd", rc); + return CURL_SOCKET_BAD; + } + + logmsg("READ %zd bytes", rc); + loghex(buffer, rc); + + if(buffer[SOCKS5_VERSION] == 4) + return socks4(fd, buffer, rc); + + if(rc < 3) { + logmsg("SOCKS5 identifier message too short: %zd", rc); + return CURL_SOCKET_BAD; + } + + if(buffer[SOCKS5_VERSION] != config.version) { + logmsg("VERSION byte not %d", config.version); + return CURL_SOCKET_BAD; + } + if((buffer[SOCKS5_NMETHODS] < config.nmethods_min) || + (buffer[SOCKS5_NMETHODS] > config.nmethods_max)) { + logmsg("NMETHODS byte not within %d - %d ", + config.nmethods_min, config.nmethods_max); + return CURL_SOCKET_BAD; + } + /* after NMETHODS follows that many bytes listing the methods the client + says it supports */ + if(rc != (buffer[SOCKS5_NMETHODS] + 2)) { + logmsg("Expected %d bytes, got %zd", buffer[SOCKS5_NMETHODS] + 2, rc); + return CURL_SOCKET_BAD; + } + logmsg("Incoming request deemed fine!"); + + /* respond with two bytes: VERSION + METHOD */ + response[0] = config.responseversion; + response[1] = config.responsemethod; + rc = (send)(fd, (char *)response, 2, 0); + if(rc != 2) { + logmsg("Sending response failed!"); + return CURL_SOCKET_BAD; + } + logmsg("Sent %zd bytes", rc); + loghex(response, rc); + + /* expect the request or auth */ + rc = recv(fd, (char *)buffer, sizeof(buffer), 0); + if(rc <= 0) { + logmsg("SOCKS5 request or auth message missing, recv returned %zd", rc); + return CURL_SOCKET_BAD; + } + + logmsg("READ %zd bytes", rc); + loghex(buffer, rc); + + if(config.responsemethod == 2) { + /* RFC 1929 authentication + +----+------+----------+------+----------+ + |VER | ULEN | UNAME | PLEN | PASSWD | + +----+------+----------+------+----------+ + | 1 | 1 | 1 to 255 | 1 | 1 to 255 | + +----+------+----------+------+----------+ + */ + unsigned char ulen; + unsigned char plen; + bool login = TRUE; + if(rc < 5) { + logmsg("Too short auth input: %zd", rc); + return CURL_SOCKET_BAD; + } + if(buffer[SOCKS5_VERSION] != 1) { + logmsg("Auth VERSION byte not 1, got %d", buffer[SOCKS5_VERSION]); + return CURL_SOCKET_BAD; + } + ulen = buffer[SOCKS5_ULEN]; + if(rc < 4 + ulen) { + logmsg("Too short packet for username: %zd", rc); + return CURL_SOCKET_BAD; + } + plen = buffer[SOCKS5_ULEN + ulen + 1]; + if(rc < 3 + ulen + plen) { + logmsg("Too short packet for ulen %d plen %d: %zd", ulen, plen, rc); + return CURL_SOCKET_BAD; + } + if((ulen != strlen(config.user)) || + (plen != strlen(config.password)) || + memcmp(&buffer[SOCKS5_UNAME], config.user, ulen) || + memcmp(&buffer[SOCKS5_UNAME + ulen + 1], config.password, plen)) { + /* no match! */ + logmsg("mismatched credentials!"); + login = FALSE; + } + response[0] = 1; + response[1] = login ? 0 : 1; + rc = (send)(fd, (char *)response, 2, 0); + if(rc != 2) { + logmsg("Sending auth response failed!"); + return CURL_SOCKET_BAD; + } + logmsg("Sent %zd bytes", rc); + loghex(response, rc); + if(!login) + return CURL_SOCKET_BAD; + + /* expect the request */ + rc = recv(fd, (char *)buffer, sizeof(buffer), 0); + if(rc <= 0) { + logmsg("SOCKS5 request message missing, recv returned %zd", rc); + return CURL_SOCKET_BAD; + } + + logmsg("READ %zd bytes", rc); + loghex(buffer, rc); + } + if(rc < 6) { + logmsg("Too short for request: %zd", rc); + return CURL_SOCKET_BAD; + } + + if(buffer[SOCKS5_VERSION] != config.version) { + logmsg("Request VERSION byte not %d", config.version); + return CURL_SOCKET_BAD; + } + /* 1 == CONNECT */ + if(buffer[SOCKS5_REQCMD] != config.reqcmd) { + logmsg("Request COMMAND byte not %d", config.reqcmd); + return CURL_SOCKET_BAD; + } + /* reserved, should be zero */ + if(buffer[SOCKS5_RESERVED]) { + logmsg("Request COMMAND byte not %d", config.reqcmd); + return CURL_SOCKET_BAD; + } + /* ATYP: + o IP V4 address: X'01' + o DOMAINNAME: X'03' + o IP V6 address: X'04' + */ + type = buffer[SOCKS5_ATYP]; + address = &buffer[SOCKS5_DSTADDR]; + switch(type) { + case 1: + /* 4 bytes IPv4 address */ + len = 4; + break; + case 3: + /* The first octet of the address field contains the number of octets of + name that follow */ + len = buffer[SOCKS5_DSTADDR]; + len++; + break; + case 4: + /* 16 bytes IPv6 address */ + len = 16; + break; + default: + logmsg("Unknown ATYP %d", type); + return CURL_SOCKET_BAD; + } + if(rc < (4 + len + 2)) { + logmsg("Request too short: %zd, expected %d", rc, 4 + len + 2); + return CURL_SOCKET_BAD; + } + logmsg("Received ATYP %d", type); + + { + FILE *dump; + dump = fopen(reqlogfile, "ab"); + if(dump) { + int i; + fprintf(dump, "atyp %u =>", type); + switch(type) { + case 1: + /* 4 bytes IPv4 address */ + fprintf(dump, " %u.%u.%u.%u\n", + address[0], address[1], address[2], address[3]); + break; + case 3: + /* The first octet of the address field contains the number of octets + of name that follow */ + fprintf(dump, " %.*s\n", len-1, &address[1]); + break; + case 4: + /* 16 bytes IPv6 address */ + for(i = 0; i < 16; i++) { + fprintf(dump, " %02x", address[i]); + } + fprintf(dump, "\n"); + break; + } + fclose(dump); + } + } + + if(!config.port) { + unsigned char *portp = &buffer[SOCKS5_DSTADDR + len]; + s5port = (unsigned short)((portp[0] << 8) | (portp[1])); + } + else + s5port = config.port; + + if(!config.connectrep) + connfd = socksconnect(s5port, config.addr); + + if(connfd == CURL_SOCKET_BAD) { + /* failed */ + rep = 1; + } + else { + rep = config.connectrep; + } + + /* */ + response[SOCKS5_VERSION] = config.responseversion; + + /* + o REP Reply field: + o X'00' succeeded + o X'01' general SOCKS server failure + o X'02' connection not allowed by ruleset + o X'03' Network unreachable + o X'04' Host unreachable + o X'05' Connection refused + o X'06' TTL expired + o X'07' Command not supported + o X'08' Address type not supported + o X'09' to X'FF' unassigned + */ + response[SOCKS5_REP] = rep; + response[SOCKS5_RESERVED] = 0; /* must be zero */ + response[SOCKS5_ATYP] = type; /* address type */ + + /* mirror back the original addr + port */ + + /* address or hostname */ + memcpy(&response[SOCKS5_BNDADDR], address, len); + + /* port number */ + memcpy(&response[SOCKS5_BNDADDR + len], + &buffer[SOCKS5_DSTADDR + len], sizeof(socksport)); + + rc = (send)(fd, (char *)response, (SEND_TYPE_ARG3)(len + 6), 0); + if(rc != (len + 6)) { + logmsg("Sending connect response failed!"); + return CURL_SOCKET_BAD; + } + logmsg("Sent %zd bytes", rc); + loghex(response, rc); + + if(!rep) + return connfd; + + if(connfd != CURL_SOCKET_BAD) + sclose(connfd); + + return CURL_SOCKET_BAD; +} + +struct perclient { + size_t fromremote; + size_t fromclient; + curl_socket_t remotefd; + curl_socket_t clientfd; + bool used; +}; + +/* return non-zero when transfer is done */ +static int tunnel(struct perclient *cp, fd_set *fds) +{ + ssize_t nread; + ssize_t nwrite; + char buffer[512]; + if(FD_ISSET(cp->clientfd, fds)) { + /* read from client, send to remote */ + nread = recv(cp->clientfd, buffer, sizeof(buffer), 0); + if(nread > 0) { + nwrite = send(cp->remotefd, (char *)buffer, + (SEND_TYPE_ARG3)nread, 0); + if(nwrite != nread) + return 1; + cp->fromclient += nwrite; + } + else + return 1; + } + if(FD_ISSET(cp->remotefd, fds)) { + /* read from remote, send to client */ + nread = recv(cp->remotefd, buffer, sizeof(buffer), 0); + if(nread > 0) { + nwrite = send(cp->clientfd, (char *)buffer, + (SEND_TYPE_ARG3)nread, 0); + if(nwrite != nread) + return 1; + cp->fromremote += nwrite; + } + else + return 1; + } + return 0; +} + +/* + sockfdp is a pointer to an established stream or CURL_SOCKET_BAD + + if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must + accept() +*/ +static bool incoming(curl_socket_t listenfd) +{ + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + int clients = 0; /* connected clients */ + struct perclient c[2]; + + memset(c, 0, sizeof(c)); + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + +#ifdef HAVE_GETPPID + /* As a last resort, quit if socks5 process becomes orphan. */ + if(getppid() <= 1) { + logmsg("process becomes orphan, exiting"); + return FALSE; + } +#endif + + do { + int i; + ssize_t rc; + int error = 0; + curl_socket_t sockfd = listenfd; + int maxfd = (int)sockfd; + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + + /* there's always a socket to wait for */ + FD_SET(sockfd, &fds_read); + + for(i = 0; i < 2; i++) { + if(c[i].used) { + curl_socket_t fd = c[i].clientfd; + FD_SET(fd, &fds_read); + if((int)fd > maxfd) + maxfd = (int)fd; + fd = c[i].remotefd; + FD_SET(fd, &fds_read); + if((int)fd > maxfd) + maxfd = (int)fd; + } + } + + do { + /* select() blocking behavior call on blocking descriptors please */ + rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL); + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + return FALSE; + } + } while((rc == -1) && ((error = errno) == EINTR)); + + if(rc < 0) { + logmsg("select() failed with error: (%d) %s", + error, strerror(error)); + return FALSE; + } + + if((clients < 2) && FD_ISSET(sockfd, &fds_read)) { + curl_socket_t newfd = accept(sockfd, NULL, NULL); + if(CURL_SOCKET_BAD == newfd) { + error = SOCKERRNO; + logmsg("accept(%" FMT_SOCKET_T ", NULL, NULL) " + "failed with error: (%d) %s", + sockfd, error, sstrerror(error)); + } + else { + curl_socket_t remotefd; + logmsg("====> Client connect, fd %" FMT_SOCKET_T ". " + "Read config from %s", newfd, configfile); + remotefd = sockit(newfd); /* SOCKS until done */ + if(remotefd == CURL_SOCKET_BAD) { + logmsg("====> Client disconnect"); + sclose(newfd); + } + else { + struct perclient *cp = &c[0]; + logmsg("====> Tunnel transfer"); + + if(c[0].used) + cp = &c[1]; + cp->fromremote = 0; + cp->fromclient = 0; + cp->clientfd = newfd; + cp->remotefd = remotefd; + cp->used = TRUE; + clients++; + } + + } + } + for(i = 0; i < 2; i++) { + struct perclient *cp = &c[i]; + if(cp->used) { + if(tunnel(cp, &fds_read)) { + logmsg("SOCKS transfer completed. Bytes: < %zu > %zu", + cp->fromremote, cp->fromclient); + sclose(cp->clientfd); + sclose(cp->remotefd); + cp->used = FALSE; + clients--; + } + } + } + } while(clients); + + return TRUE; +} + +static curl_socket_t sockdaemon(curl_socket_t sock, + unsigned short *listenport +#ifdef USE_UNIX_SOCKETS + , const char *unix_socket +#endif + ) +{ + /* passive daemon style */ + srvr_sockaddr_union_t listener; + int flag; + int rc; + int totdelay = 0; + int maxretr = 10; + int delay = 20; + int attempt = 0; + int error = 0; + + do { + attempt++; + flag = 1; + rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag)); + if(rc) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + if(maxretr) { + rc = wait_ms(delay); + if(rc) { + /* should not happen */ + error = errno; + logmsg("wait_ms() failed with error: (%d) %s", + error, strerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + if(got_exit_signal) { + logmsg("signalled to die, exiting..."); + sclose(sock); + return CURL_SOCKET_BAD; + } + totdelay += delay; + delay *= 2; /* double the sleep for next attempt */ + } + } + } while(rc && maxretr--); + + if(rc) { + logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", + attempt, totdelay, error, strerror(error)); + logmsg("Continuing anyway..."); + } + + /* When the specified listener port is zero, it is actually a + request to let the system choose a non-zero available port. */ + + switch(socket_domain) { + case AF_INET: + memset(&listener.sa4, 0, sizeof(listener.sa4)); + listener.sa4.sin_family = AF_INET; + listener.sa4.sin_addr.s_addr = INADDR_ANY; + listener.sa4.sin_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa4)); + break; +#ifdef USE_IPV6 + case AF_INET6: + memset(&listener.sa6, 0, sizeof(listener.sa6)); + listener.sa6.sin6_family = AF_INET6; + listener.sa6.sin6_addr = in6addr_any; + listener.sa6.sin6_port = htons(*listenport); + rc = bind(sock, &listener.sa, sizeof(listener.sa6)); + break; +#endif /* USE_IPV6 */ +#ifdef USE_UNIX_SOCKETS + case AF_UNIX: + rc = bind_unix_socket(sock, unix_socket, &listener.sau); +#endif + } + + if(rc) { + error = SOCKERRNO; +#ifdef USE_UNIX_SOCKETS + if(socket_domain == AF_UNIX) + logmsg("Error binding socket on path %s: (%d) %s", + unix_socket, error, sstrerror(error)); + else +#endif + logmsg("Error binding socket on port %hu: (%d) %s", + *listenport, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + if(!*listenport +#ifdef USE_UNIX_SOCKETS + && !unix_socket +#endif + ) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(socket_domain == AF_INET6) + la_size = sizeof(localaddr.sa6); + else +#endif + la_size = sizeof(localaddr.sa4); + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + *listenport = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + *listenport = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!*listenport) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + sclose(sock); + return CURL_SOCKET_BAD; + } + } + + /* start accepting connections */ + rc = listen(sock, 5); + if(0 != rc) { + error = SOCKERRNO; + logmsg("listen(%" FMT_SOCKET_T ", 5) failed with error: (%d) %s", + sock, error, sstrerror(error)); + sclose(sock); + return CURL_SOCKET_BAD; + } + + return sock; +} + + +int main(int argc, char *argv[]) +{ + curl_socket_t sock = CURL_SOCKET_BAD; + curl_socket_t msgsock = CURL_SOCKET_BAD; + int wrotepidfile = 0; + int wroteportfile = 0; + const char *pidname = ".socksd.pid"; + const char *portname = NULL; /* none by default */ + bool juggle_again; + int error; + int arg = 1; + +#ifdef USE_UNIX_SOCKETS + const char *unix_socket = NULL; + bool unlink_socket = false; +#endif + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("socksd IPv4%s\n", +#ifdef USE_IPV6 + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--config", argv[arg])) { + arg++; + if(argc > arg) + configfile = argv[arg++]; + } + else if(!strcmp("--backend", argv[arg])) { + arg++; + if(argc > arg) + backendaddr = argv[arg++]; + } + else if(!strcmp("--backendport", argv[arg])) { + arg++; + if(argc > arg) + backendport = (unsigned short)atoi(argv[arg++]); + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--reqfile", argv[arg])) { + arg++; + if(argc > arg) + reqlogfile = argv[arg++]; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + socket_domain = AF_INET6; + socket_type = "IPv6"; +#endif + arg++; + } + else if(!strcmp("--ipv4", argv[arg])) { + /* for completeness, we support this option as well */ +#ifdef USE_IPV6 + socket_type = "IPv4"; +#endif + arg++; + } + else if(!strcmp("--unix-socket", argv[arg])) { + arg++; + if(argc > arg) { +#ifdef USE_UNIX_SOCKETS + struct sockaddr_un sau; + unix_socket = argv[arg]; + if(strlen(unix_socket) >= sizeof(sau.sun_path)) { + fprintf(stderr, + "socksd: socket path must be shorter than %zu chars: %s\n", + sizeof(sau.sun_path), unix_socket); + return 0; + } + socket_domain = AF_UNIX; + socket_type = "unix"; +#endif + arg++; + } + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + port = curlx_ultous(ulnum); + arg++; + } + } + else { + puts("Usage: socksd [option]\n" + " --backend [ipv4 addr]\n" + " --backendport [TCP port]\n" + " --config [file]\n" + " --version\n" + " --logfile [file]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --reqfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --unix-socket [file]\n" + " --bindonly\n" + " --port [port]\n"); + return 0; + } + } + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); + + setmode(fileno(stdin), O_BINARY); + setmode(fileno(stdout), O_BINARY); + setmode(fileno(stderr), O_BINARY); +#endif + + install_signal_handlers(false); + + sock = socket(socket_domain, SOCK_STREAM, 0); + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", + error, sstrerror(error)); + goto socks5_cleanup; + } + + { + /* passive daemon style */ + sock = sockdaemon(sock, &port +#ifdef USE_UNIX_SOCKETS + , unix_socket +#endif + ); + if(CURL_SOCKET_BAD == sock) { + goto socks5_cleanup; + } +#ifdef USE_UNIX_SOCKETS + unlink_socket = true; +#endif + msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ + } + + logmsg("Running %s version", socket_type); + +#ifdef USE_UNIX_SOCKETS + if(socket_domain == AF_UNIX) + logmsg("Listening on Unix socket %s", unix_socket); + else +#endif + logmsg("Listening on port %hu", port); + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) { + goto socks5_cleanup; + } + + if(portname) { + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) { + goto socks5_cleanup; + } + } + + do { + juggle_again = incoming(sock); + } while(juggle_again); + +socks5_cleanup: + + if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) + sclose(msgsock); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + +#ifdef USE_UNIX_SOCKETS + if(unlink_socket && socket_domain == AF_UNIX) { + error = unlink(unix_socket); + logmsg("unlink(%s) = %d (%s)", unix_socket, error, strerror(error)); + } +#endif + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + restore_signal_handlers(false); + + if(got_exit_signal) { + logmsg("============> socksd exits with signal (%d)", exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("============> socksd quits"); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/sws.c b/local-test-curl-delta-01/afc-curl/tests/server/sws.c new file mode 100644 index 0000000000000000000000000000000000000000..ef139bfc3c1f39f5c7c009b70780ddcab5dd95a5 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/sws.c @@ -0,0 +1,2506 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" + +/* sws.c: simple (silly?) web server + + This code was originally graciously donated to the project by Juergen + Wilke. Thanks a bunch! + + */ + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_NETINET_TCP_H +#include /* for TCP_NODELAY */ +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "inet_pton.h" +#include "util.h" +#include "server_sockaddr.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef EAGAIN +#define EAGAIN 11 /* errno.h value */ +#undef ERANGE +#define ERANGE 34 /* errno.h value */ +#endif + +static enum { + socket_domain_inet = AF_INET +#ifdef USE_IPV6 + , socket_domain_inet6 = AF_INET6 +#endif +#ifdef USE_UNIX_SOCKETS + , socket_domain_unix = AF_UNIX +#endif +} socket_domain = AF_INET; +static bool use_gopher = FALSE; +static int serverlogslocked = 0; +static bool is_proxy = FALSE; + +#define REQBUFSIZ (2*1024*1024) + +#define MAX_SLEEP_TIME_MS 250 + +static long prevtestno = -1; /* previous test number we served */ +static long prevpartno = -1; /* previous part number we served */ +static bool prevbounce = FALSE; /* instructs the server to increase the part + number for a test in case the identical + testno+partno request shows up again */ + +#define RCMD_NORMALREQ 0 /* default request, use the tests file normally */ +#define RCMD_IDLE 1 /* told to sit idle */ +#define RCMD_STREAM 2 /* told to stream */ + +struct httprequest { + char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */ + bool connect_request; /* if a CONNECT */ + unsigned short connect_port; /* the port number CONNECT used */ + size_t checkindex; /* where to start checking of the request */ + size_t offset; /* size of the incoming request */ + long testno; /* test number found in the request */ + long partno; /* part number found in the request */ + bool open; /* keep connection open info, as found in the request */ + bool auth_req; /* authentication required, don't wait for body unless + there's an Authorization header */ + bool auth; /* Authorization header present in the incoming request */ + size_t cl; /* Content-Length of the incoming request */ + bool digest; /* Authorization digest header found */ + bool ntlm; /* Authorization NTLM header found */ + int delay; /* if non-zero, delay this number of msec after connect */ + int writedelay; /* if non-zero, delay this number of milliseconds between + writes in the response */ + int skip; /* if non-zero, the server is instructed to not read this + many bytes from a PUT/POST request. Ie the client sends N + bytes said in Content-Length, but the server only reads N + - skip bytes. */ + int rcmd; /* doing a special command, see defines above */ + int prot_version; /* HTTP version * 10 */ + int callcount; /* times ProcessRequest() gets called */ + bool skipall; /* skip all incoming data */ + bool noexpect; /* refuse Expect: (don't read the body) */ + bool connmon; /* monitor the state of the connection, log disconnects */ + bool upgrade; /* test case allows upgrade */ + bool upgrade_request; /* upgrade request found and allowed */ + bool close; /* similar to swsclose in response: close connection after + response is sent */ + int done_processing; +}; + +#define MAX_SOCKETS 1024 + +static curl_socket_t all_sockets[MAX_SOCKETS]; +static size_t num_sockets = 0; + +static int ProcessRequest(struct httprequest *req); +static void storerequest(const char *reqbuf, size_t totalsize); + +#define DEFAULT_PORT 8999 + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/sws.log" +#endif + +const char *serverlogfile = DEFAULT_LOGFILE; +static const char *logdir = "log"; +static char loglockfile[256]; + +#define SWSVERSION "curl test suite HTTP server/0.1" + +#define REQUEST_DUMP "server.input" +#define RESPONSE_DUMP "server.response" + +/* when told to run as proxy, we store the logs in different files so that + they can co-exist with the same program running as a "server" */ +#define REQUEST_PROXY_DUMP "proxy.input" +#define RESPONSE_PROXY_DUMP "proxy.response" + +/* file in which additional instructions may be found */ +#define DEFAULT_CMDFILE "log/server.cmd" +const char *cmdfile = DEFAULT_CMDFILE; + +/* very-big-path support */ +#define MAXDOCNAMELEN 140000 +#define MAXDOCNAMELEN_TXT "139999" + +#define REQUEST_KEYWORD_SIZE 256 +#define REQUEST_KEYWORD_SIZE_TXT "255" + +#define CMD_AUTH_REQUIRED "auth_required" + +/* 'idle' means that it will accept the request fine but never respond + any data. Just keep the connection alive. */ +#define CMD_IDLE "idle" + +/* 'stream' means to send a never-ending stream of data */ +#define CMD_STREAM "stream" + +/* 'connection-monitor' will output when a server/proxy connection gets + disconnected as for some cases it is important that it gets done at the + proper point - like with NTLM */ +#define CMD_CONNECTIONMONITOR "connection-monitor" + +/* upgrade to http2/websocket/xxxx */ +#define CMD_UPGRADE "upgrade" + +/* close connection */ +#define CMD_SWSCLOSE "swsclose" + +/* deny Expect: requests */ +#define CMD_NOEXPECT "no-expect" + +#define END_OF_HEADERS "\r\n\r\n" + +enum { + DOCNUMBER_NOTHING = -4, + DOCNUMBER_QUIT = -3, + DOCNUMBER_WERULEZ = -2, + DOCNUMBER_404 = -1 +}; + +static const char *end_of_headers = END_OF_HEADERS; + +/* sent as reply to a QUIT */ +static const char *docquit = +"HTTP/1.1 200 Goodbye" END_OF_HEADERS; + +/* send back this on 404 file not found */ +static const char *doc404 = "HTTP/1.1 404 Not Found\r\n" + "Server: " SWSVERSION "\r\n" + "Connection: close\r\n" + "Content-Type: text/html" + END_OF_HEADERS + "\n" + "\n" + "404 Not Found\n" + "\n" + "

Not Found

\n" + "The requested URL was not found on this server.\n" + "


" SWSVERSION "
\n" "\n"; + +/* work around for handling trailing headers */ +static int already_recv_zeroed_chunk = FALSE; + +#ifdef TCP_NODELAY +/* returns true if the current socket is an IP one */ +static bool socket_domain_is_ip(void) +{ + switch(socket_domain) { + case AF_INET: +#ifdef USE_IPV6 + case AF_INET6: +#endif + return true; + default: + /* case AF_UNIX: */ + return false; + } +} +#endif + +/* parse the file on disk that might have a test number for us */ +static int parse_cmdfile(struct httprequest *req) +{ + FILE *f = fopen(cmdfile, FOPEN_READTEXT); + if(f) { + int testnum = DOCNUMBER_NOTHING; + char buf[256]; + while(fgets(buf, sizeof(buf), f)) { + if(1 == sscanf(buf, "Testnum %d", &testnum)) { + logmsg("[%s] cmdfile says testnum %d", cmdfile, testnum); + req->testno = testnum; + } + } + fclose(f); + } + return 0; +} + +/* based on the testno, parse the correct server commands */ +static int parse_servercmd(struct httprequest *req) +{ + FILE *stream; + int error; + + stream = test2fopen(req->testno, logdir); + req->close = FALSE; + req->connmon = FALSE; + + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg(" Couldn't open test file %ld", req->testno); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + else { + char *orgcmd = NULL; + char *cmd = NULL; + size_t cmdsize = 0; + int num = 0; + + /* get the custom server control "commands" */ + error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + + cmd = orgcmd; + while(cmd && cmdsize) { + char *check; + + if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) { + logmsg("instructed to require authorization header"); + req->auth_req = TRUE; + } + else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) { + logmsg("instructed to idle"); + req->rcmd = RCMD_IDLE; + req->open = TRUE; + } + else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) { + logmsg("instructed to stream"); + req->rcmd = RCMD_STREAM; + } + else if(!strncmp(CMD_CONNECTIONMONITOR, cmd, + strlen(CMD_CONNECTIONMONITOR))) { + logmsg("enabled connection monitoring"); + req->connmon = TRUE; + } + else if(!strncmp(CMD_UPGRADE, cmd, strlen(CMD_UPGRADE))) { + logmsg("enabled upgrade"); + req->upgrade = TRUE; + } + else if(!strncmp(CMD_SWSCLOSE, cmd, strlen(CMD_SWSCLOSE))) { + logmsg("swsclose: close this connection after response"); + req->close = TRUE; + } + else if(1 == sscanf(cmd, "skip: %d", &num)) { + logmsg("instructed to skip this number of bytes %d", num); + req->skip = num; + } + else if(!strncmp(CMD_NOEXPECT, cmd, strlen(CMD_NOEXPECT))) { + logmsg("instructed to reject Expect: 100-continue"); + req->noexpect = TRUE; + } + else if(1 == sscanf(cmd, "delay: %d", &num)) { + logmsg("instructed to delay %d msecs after connect", num); + req->delay = num; + } + else if(1 == sscanf(cmd, "writedelay: %d", &num)) { + logmsg("instructed to delay %d msecs between packets", num); + req->writedelay = num; + } + else { + logmsg("Unknown instruction found: %s", cmd); + } + /* try to deal with CRLF or just LF */ + check = strchr(cmd, '\r'); + if(!check) + check = strchr(cmd, '\n'); + + if(check) { + /* get to the letter following the newline */ + while((*check == '\r') || (*check == '\n')) + check++; + + if(!*check) + /* if we reached a zero, get out */ + break; + cmd = check; + } + else + break; + } + free(orgcmd); + } + + return 0; /* OK! */ +} + +static int ProcessRequest(struct httprequest *req) +{ + char *line = &req->reqbuf[req->checkindex]; + bool chunked = FALSE; + static char request[REQUEST_KEYWORD_SIZE]; + char logbuf[456]; + int prot_major = 0; + int prot_minor = 0; + char *end = strstr(line, end_of_headers); + + req->callcount++; + + logmsg("Process %zu bytes request%s", req->offset, + req->callcount > 1 ? " [CONTINUED]" : ""); + + /* try to figure out the request characteristics as soon as possible, but + only once! */ + + if(use_gopher && + (req->testno == DOCNUMBER_NOTHING) && + !strncmp("/verifiedserver", line, 15)) { + logmsg("Are-we-friendly question received"); + req->testno = DOCNUMBER_WERULEZ; + return 1; /* done */ + } + + else if(req->testno == DOCNUMBER_NOTHING) { + char *http; + bool fine = FALSE; + char *httppath = NULL; + size_t npath = 0; /* httppath length */ + + if(sscanf(line, + "%" REQUEST_KEYWORD_SIZE_TXT"s ", request)) { + http = strstr(line + strlen(request), "HTTP/"); + + if(http && sscanf(http, "HTTP/%d.%d", + &prot_major, + &prot_minor) == 2) { + /* between the request keyword and HTTP/ there's a path */ + httppath = line + strlen(request); + npath = http - httppath; + + /* trim leading spaces */ + while(npath && ISSPACE(*httppath)) { + httppath++; + npath--; + } + /* trim ending spaces */ + while(npath && ISSPACE(httppath[npath - 1])) { + npath--; + } + if(npath) + fine = TRUE; + } + } + + if(fine) { + char *ptr; + + req->prot_version = prot_major*10 + prot_minor; + + /* find the last slash */ + ptr = &httppath[npath]; + while(ptr >= httppath) { + if(*ptr == '/') + break; + ptr--; + } + + /* get the number after it */ + if(*ptr == '/') { + if((npath + strlen(request)) < 400) + msnprintf(logbuf, sizeof(logbuf), "Got request: %s %.*s HTTP/%d.%d", + request, (int)npath, httppath, prot_major, prot_minor); + else + msnprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request HTTP/%d.%d", + prot_major, prot_minor); + logmsg("%s", logbuf); + + if(!strncmp("/verifiedserver", ptr, 15)) { + logmsg("Are-we-friendly question received"); + req->testno = DOCNUMBER_WERULEZ; + return 1; /* done */ + } + + if(!strncmp("/quit", ptr, 5)) { + logmsg("Request-to-quit received"); + req->testno = DOCNUMBER_QUIT; + return 1; /* done */ + } + + ptr++; /* skip the slash */ + + req->testno = strtol(ptr, &ptr, 10); + + if(req->testno > 10000) { + req->partno = req->testno % 10000; + req->testno /= 10000; + } + else + req->partno = 0; + + if(req->testno) { + + msnprintf(logbuf, sizeof(logbuf), "Serve test number %ld part %ld", + req->testno, req->partno); + logmsg("%s", logbuf); + } + else { + logmsg("No test number in path"); + req->testno = DOCNUMBER_NOTHING; + } + + } + + if(req->testno == DOCNUMBER_NOTHING) { + /* didn't find any in the first scan, try alternative test case + number placements */ + static char doc[MAXDOCNAMELEN]; + if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d", + doc, &prot_major, &prot_minor) == 3) { + char *portp = NULL; + + msnprintf(logbuf, sizeof(logbuf), + "Received a CONNECT %s HTTP/%d.%d request", + doc, prot_major, prot_minor); + logmsg("%s", logbuf); + + req->connect_request = TRUE; + + if(req->prot_version == 10) + req->open = FALSE; /* HTTP 1.0 closes connection by default */ + + if(doc[0] == '[') { + char *p = &doc[1]; + unsigned long part = 0; + /* scan through the hexgroups and store the value of the last group + in the 'part' variable and use as test case number!! */ + while(*p && (ISXDIGIT(*p) || (*p == ':') || (*p == '.'))) { + char *endp; + part = strtoul(p, &endp, 16); + if(ISXDIGIT(*p)) + p = endp; + else + p++; + } + if(*p != ']') + logmsg("Invalid CONNECT IPv6 address format"); + else if(*(p + 1) != ':') + logmsg("Invalid CONNECT IPv6 port format"); + else + portp = p + 1; + + req->testno = part; + } + else + portp = strchr(doc, ':'); + + if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1))) { + unsigned long ulnum = strtoul(portp + 1, NULL, 10); + if(!ulnum || (ulnum > 65535UL)) + logmsg("Invalid CONNECT port received"); + else + req->connect_port = curlx_ultous(ulnum); + + } + logmsg("Port number: %d, test case number: %ld", + req->connect_port, req->testno); + } + } + + if(req->testno == DOCNUMBER_NOTHING) + /* might get the test number */ + parse_cmdfile(req); + + if(req->testno == DOCNUMBER_NOTHING) { + logmsg("Did not find test number in PATH"); + req->testno = DOCNUMBER_404; + } + else + parse_servercmd(req); + } + else if((req->offset >= 3)) { + unsigned char *l = (unsigned char *)line; + logmsg("** Unusual request. Starts with %02x %02x %02x (%c%c%c)", + l[0], l[1], l[2], l[0], l[1], l[2]); + } + } + + if(!end) { + /* we don't have a complete request yet! */ + logmsg("request not complete yet"); + return 0; /* not complete yet */ + } + logmsg("- request found to be complete (%ld)", req->testno); + + if(req->testno == DOCNUMBER_NOTHING) { + /* check for a Testno: header with the test case number */ + char *testno = strstr(line, "\nTestno: "); + if(testno) { + req->testno = strtol(&testno[9], NULL, 10); + logmsg("Found test number %ld in Testno: header!", req->testno); + } + else { + logmsg("No Testno: header"); + } + } + + /* find and parse for this test */ + parse_servercmd(req); + + if(use_gopher) { + /* when using gopher we cannot check the request until the entire + thing has been received */ + char *ptr; + + /* find the last slash in the line */ + ptr = strrchr(line, '/'); + + if(ptr) { + ptr++; /* skip the slash */ + + /* skip all non-numericals following the slash */ + while(*ptr && !ISDIGIT(*ptr)) + ptr++; + + req->testno = strtol(ptr, &ptr, 10); + + if(req->testno > 10000) { + req->partno = req->testno % 10000; + req->testno /= 10000; + } + else + req->partno = 0; + + msnprintf(logbuf, sizeof(logbuf), + "Requested GOPHER test number %ld part %ld", + req->testno, req->partno); + logmsg("%s", logbuf); + } + } + + /* **** Persistence **** + * + * If the request is an HTTP/1.0 one, we close the connection unconditionally + * when we're done. + * + * If the request is an HTTP/1.1 one, we MUST check for a "Connection:" + * header that might say "close". If it does, we close a connection when + * this request is processed. Otherwise, we keep the connection alive for X + * seconds. + */ + + do { + if(got_exit_signal) + return 1; /* done */ + + if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) { + /* If we don't ignore content-length, we read it and we read the whole + request including the body before we return. If we've been told to + ignore the content-length, we will return as soon as all headers + have been received */ + char *endptr; + char *ptr = line + 15; + unsigned long clen = 0; + while(*ptr && ISSPACE(*ptr)) + ptr++; + endptr = ptr; + errno = 0; + clen = strtoul(ptr, &endptr, 10); + if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) { + /* this assumes that a zero Content-Length is valid */ + logmsg("Found invalid Content-Length: (%s) in the request", ptr); + req->open = FALSE; /* closes connection */ + return 1; /* done */ + } + if(req->skipall) + req->cl = 0; + else + req->cl = clen - req->skip; + + logmsg("Found Content-Length: %lu in the request", clen); + if(req->skip) + logmsg("... but will abort after %zu bytes", req->cl); + } + else if(strncasecompare("Transfer-Encoding: chunked", line, + strlen("Transfer-Encoding: chunked"))) { + /* chunked data coming in */ + chunked = TRUE; + } + else if(req->noexpect && + strncasecompare("Expect: 100-continue", line, + strlen("Expect: 100-continue"))) { + if(req->cl) + req->cl = 0; + req->skipall = TRUE; + logmsg("Found Expect: 100-continue, ignore body"); + } + + if(chunked) { + if(strstr(req->reqbuf, "\r\n0\r\n\r\n")) { + /* end of chunks reached */ + return 1; /* done */ + } + else if(strstr(req->reqbuf, "\r\n0\r\n")) { + char *last_crlf_char = strstr(req->reqbuf, "\r\n\r\n"); + while(TRUE) { + if(!strstr(last_crlf_char + 4, "\r\n\r\n")) + break; + last_crlf_char = strstr(last_crlf_char + 4, "\r\n\r\n"); + } + if(last_crlf_char && + last_crlf_char > strstr(req->reqbuf, "\r\n0\r\n")) + return 1; + already_recv_zeroed_chunk = TRUE; + return 0; + } + else if(already_recv_zeroed_chunk && strstr(req->reqbuf, "\r\n\r\n")) + return 1; + else + return 0; /* not done */ + } + + line = strchr(line, '\n'); + if(line) + line++; + + } while(line); + + if(!req->auth && strstr(req->reqbuf, "Authorization:")) { + req->auth = TRUE; /* Authorization: header present! */ + if(req->auth_req) + logmsg("Authorization header found, as required"); + } + + if(strstr(req->reqbuf, "Authorization: Negotiate")) { + /* Negotiate iterations */ + static long prev_testno = -1; + static long prev_partno = -1; + logmsg("Negotiate: prev_testno: %ld, prev_partno: %ld", + prev_testno, prev_partno); + if(req->testno != prev_testno) { + prev_testno = req->testno; + prev_partno = req->partno; + } + prev_partno += 1; + req->partno = prev_partno; + } + else if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) { + /* If the client is passing this Digest-header, we set the part number + to 1000. Not only to spice up the complexity of this, but to make + Digest stuff to work in the test suite. */ + req->partno += 1000; + req->digest = TRUE; /* header found */ + logmsg("Received Digest request, sending back data %ld", req->partno); + } + else if(!req->ntlm && + strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) { + /* If the client is passing this type-3 NTLM header */ + req->partno += 1002; + req->ntlm = TRUE; /* NTLM found */ + logmsg("Received NTLM type-3, sending back data %ld", req->partno); + if(req->cl) { + logmsg(" Expecting %zu POSTed bytes", req->cl); + } + } + else if(!req->ntlm && + strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) { + /* If the client is passing this type-1 NTLM header */ + req->partno += 1001; + req->ntlm = TRUE; /* NTLM found */ + logmsg("Received NTLM type-1, sending back data %ld", req->partno); + } + else if((req->partno >= 1000) && + strstr(req->reqbuf, "Authorization: Basic")) { + /* If the client is passing this Basic-header and the part number is + already >=1000, we add 1 to the part number. This allows simple Basic + authentication negotiation to work in the test suite. */ + req->partno += 1; + logmsg("Received Basic request, sending back data %ld", req->partno); + } + if(strstr(req->reqbuf, "Connection: close")) + req->open = FALSE; /* close connection after this request */ + + if(req->open && + req->prot_version >= 11 && + req->reqbuf + req->offset > end + strlen(end_of_headers) && + !req->cl && + (!strncmp(req->reqbuf, "GET", strlen("GET")) || + !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) { + /* If we have a persistent connection, HTTP version >= 1.1 + and GET/HEAD request, enable pipelining. */ + req->checkindex = (end - req->reqbuf) + strlen(end_of_headers); + } + + /* If authentication is required and no auth was provided, end now. This + makes the server NOT wait for PUT/POST data and you can then make the + test case send a rejection before any such data has been sent. Test case + 154 uses this.*/ + if(req->auth_req && !req->auth) { + logmsg("Return early due to auth requested by none provided"); + return 1; /* done */ + } + + if(req->upgrade && strstr(req->reqbuf, "Upgrade:")) { + /* we allow upgrade and there was one! */ + logmsg("Found Upgrade: in request and allow it"); + req->upgrade_request = TRUE; + return 0; /* not done */ + } + + if(req->cl > 0) { + if(req->cl <= req->offset - (end - req->reqbuf) - strlen(end_of_headers)) + return 1; /* done */ + else + return 0; /* not complete yet */ + } + + return 1; /* done */ +} + +/* store the entire request in a file */ +static void storerequest(const char *reqbuf, size_t totalsize) +{ + int res; + int error = 0; + size_t written; + size_t writeleft; + FILE *dump; + char dumpfile[256]; + + msnprintf(dumpfile, sizeof(dumpfile), "%s/%s", + logdir, is_proxy ? REQUEST_PROXY_DUMP : REQUEST_DUMP); + + if(!reqbuf) + return; + if(totalsize == 0) + return; + + do { + dump = fopen(dumpfile, "ab"); + } while(!dump && ((error = errno) == EINTR)); + if(!dump) { + logmsg("[2] Error opening file %s error: %d %s", + dumpfile, error, strerror(error)); + logmsg("Failed to write request input "); + return; + } + + writeleft = totalsize; + do { + written = fwrite(&reqbuf[totalsize-writeleft], + 1, writeleft, dump); + if(got_exit_signal) + goto storerequest_cleanup; + if(written > 0) + writeleft -= written; + } while((writeleft > 0) && ((error = errno) == EINTR)); + + if(writeleft == 0) + logmsg("Wrote request (%zu bytes) input to %s", totalsize, dumpfile); + else if(writeleft > 0) { + logmsg("Error writing file %s error: %d %s", + dumpfile, error, strerror(error)); + logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s", + totalsize-writeleft, totalsize, dumpfile); + } + +storerequest_cleanup: + + do { + res = fclose(dump); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error closing file %s error: %d %s", + dumpfile, error, strerror(error)); +} + +static void init_httprequest(struct httprequest *req) +{ + req->checkindex = 0; + req->offset = 0; + req->testno = DOCNUMBER_NOTHING; + req->partno = 0; + req->connect_request = FALSE; + req->open = TRUE; + req->auth_req = FALSE; + req->auth = FALSE; + req->cl = 0; + req->digest = FALSE; + req->ntlm = FALSE; + req->skip = 0; + req->skipall = FALSE; + req->noexpect = FALSE; + req->delay = 0; + req->writedelay = 0; + req->rcmd = RCMD_NORMALREQ; + req->prot_version = 0; + req->callcount = 0; + req->connect_port = 0; + req->done_processing = 0; + req->upgrade = 0; + req->upgrade_request = 0; +} + +static int send_doc(curl_socket_t sock, struct httprequest *req); + +/* returns 1 if the connection should be serviced again immediately, 0 if there + is no data waiting, or < 0 if it should be closed */ +static int get_request(curl_socket_t sock, struct httprequest *req) +{ + int fail = 0; + char *reqbuf = req->reqbuf; + ssize_t got = 0; + int overflow = 0; + + if(req->upgrade_request) { + /* upgraded connection, work it differently until end of connection */ + logmsg("Upgraded connection, this is no longer HTTP/1"); + send_doc(sock, req); + + /* dump the request received so far to the external file */ + reqbuf[req->offset] = '\0'; + storerequest(reqbuf, req->offset); + req->offset = 0; + + /* read websocket traffic */ + if(req->open) { + logmsg("wait for websocket traffic"); + do { + got = sread(sock, reqbuf + req->offset, REQBUFSIZ - req->offset); + if(got > 0) { + req->offset += got; + logmsg("Got %zu bytes from client", got); + } + + if((got == -1) && ((EAGAIN == errno) || (EWOULDBLOCK == errno))) { + int rc; + fd_set input; + fd_set output; + struct timeval timeout = {1, 0}; /* 1000 ms */ + + logmsg("Got EAGAIN from sread"); + FD_ZERO(&input); + FD_ZERO(&output); + got = 0; + FD_SET(sock, &input); + do { + logmsg("Wait until readable"); + rc = select((int)sock + 1, &input, &output, NULL, &timeout); + } while(rc < 0 && errno == EINTR && !got_exit_signal); + logmsg("readable %d", rc); + if(rc) + got = 1; + } + } while(got > 0); + } + else { + logmsg("NO wait for websocket traffic"); + } + if(req->offset) { + logmsg("log the websocket traffic"); + /* dump the incoming websocket traffic to the external file */ + reqbuf[req->offset] = '\0'; + storerequest(reqbuf, req->offset); + req->offset = 0; + } + init_httprequest(req); + + return -1; + } + + if(req->offset >= REQBUFSIZ-1) { + /* buffer is already full; do nothing */ + overflow = 1; + } + else { + if(req->skip) + /* we are instructed to not read the entire thing, so we make sure to + only read what we're supposed to and NOT read the entire thing the + client wants to send! */ + got = sread(sock, reqbuf + req->offset, req->cl); + else + got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset); + + if(got_exit_signal) + return -1; + if(got == 0) { + logmsg("Connection closed by client"); + fail = 1; + } + else if(got < 0) { + int error = SOCKERRNO; + if(EAGAIN == error || EWOULDBLOCK == error) { + /* nothing to read at the moment */ + return 0; + } + logmsg("recv() returned error: (%d) %s", error, sstrerror(error)); + fail = 1; + } + if(fail) { + /* dump the request received so far to the external file */ + reqbuf[req->offset] = '\0'; + storerequest(reqbuf, req->offset); + return -1; + } + + logmsg("Read %zd bytes", got); + + req->offset += (size_t)got; + reqbuf[req->offset] = '\0'; + + req->done_processing = ProcessRequest(req); + if(got_exit_signal) + return -1; + } + + if(overflow || (req->offset == REQBUFSIZ-1 && got > 0)) { + logmsg("Request would overflow buffer, closing connection"); + /* dump request received so far to external file anyway */ + reqbuf[REQBUFSIZ-1] = '\0'; + fail = 1; + } + else if(req->offset > REQBUFSIZ-1) { + logmsg("Request buffer overflow, closing connection"); + /* dump request received so far to external file anyway */ + reqbuf[REQBUFSIZ-1] = '\0'; + fail = 1; + } + else + reqbuf[req->offset] = '\0'; + + /* at the end of a request dump it to an external file */ + if(fail || req->done_processing) + storerequest(reqbuf, req->offset); + if(got_exit_signal) + return -1; + + return fail ? -1 : 1; +} + +/* returns -1 on failure */ +static int send_doc(curl_socket_t sock, struct httprequest *req) +{ + ssize_t written; + size_t count; + const char *buffer; + char *ptr = NULL; + FILE *stream; + char *cmd = NULL; + size_t cmdsize = 0; + FILE *dump; + bool persistent = TRUE; + bool sendfailure = FALSE; + size_t responsesize; + int error = 0; + int res; + static char weare[256]; + char responsedump[256]; + + msnprintf(responsedump, sizeof(responsedump), "%s/%s", + logdir, is_proxy ? RESPONSE_PROXY_DUMP : RESPONSE_DUMP); + + switch(req->rcmd) { + default: + case RCMD_NORMALREQ: + break; /* continue with business as usual */ + case RCMD_STREAM: +#define STREAMTHIS "a string to stream 01234567890\n" + count = strlen(STREAMTHIS); + for(;;) { + written = swrite(sock, STREAMTHIS, count); + if(got_exit_signal) + return -1; + if(written != (ssize_t)count) { + logmsg("Stopped streaming"); + break; + } + } + return -1; + case RCMD_IDLE: + /* Do nothing. Sit idle. Pretend it rains. */ + return 0; + } + + req->open = FALSE; + + if(req->testno < 0) { + size_t msglen; + char msgbuf[64]; + + switch(req->testno) { + case DOCNUMBER_QUIT: + logmsg("Replying to QUIT"); + buffer = docquit; + break; + case DOCNUMBER_WERULEZ: + /* we got a "friends?" question, reply back that we sure are */ + logmsg("Identifying ourselves as friends"); + msnprintf(msgbuf, sizeof(msgbuf), "WE ROOLZ: %" + CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); + msglen = strlen(msgbuf); + if(use_gopher) + msnprintf(weare, sizeof(weare), "%s", msgbuf); + else + msnprintf(weare, sizeof(weare), + "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", + msglen, msgbuf); + buffer = weare; + break; + case DOCNUMBER_404: + default: + logmsg("Replying to with a 404"); + buffer = doc404; + break; + } + + count = strlen(buffer); + } + else { + char partbuf[80]; + + /* select the tag for "normal" requests and the one + for CONNECT requests (within the section) */ + const char *section = req->connect_request ? "connect" : "data"; + + if(req->partno) + msnprintf(partbuf, sizeof(partbuf), "%s%ld", section, req->partno); + else + msnprintf(partbuf, sizeof(partbuf), "%s", section); + + logmsg("Send response test%ld section <%s>", req->testno, partbuf); + + stream = test2fopen(req->testno, logdir); + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + return 0; + } + else { + error = getpart(&ptr, &count, "reply", partbuf, stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + return 0; + } + buffer = ptr; + } + + if(got_exit_signal) { + free(ptr); + return -1; + } + + /* re-open the same file again */ + stream = test2fopen(req->testno, logdir); + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + free(ptr); + return 0; + } + else { + /* get the custom server control "commands" */ + error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + free(ptr); + return 0; + } + } + } + + if(got_exit_signal) { + free(ptr); + free(cmd); + return -1; + } + + /* If the word 'swsclose' is present anywhere in the reply chunk, the + connection will be closed after the data has been sent to the requesting + client... */ + if(strstr(buffer, "swsclose") || !count || req->close) { + persistent = FALSE; + logmsg("connection close instruction \"swsclose\" found in response"); + } + if(strstr(buffer, "swsbounce")) { + prevbounce = TRUE; + logmsg("enable \"swsbounce\" in the next request"); + } + else + prevbounce = FALSE; + + dump = fopen(responsedump, "ab"); + if(!dump) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg(" [5] Error opening file: %s", responsedump); + free(ptr); + free(cmd); + return -1; + } + + responsesize = count; + do { + /* Ok, we send no more than N bytes at a time, just to make sure that + larger chunks are split up so that the client will need to do multiple + recv() calls to get it and thus we exercise that code better */ + size_t num = count; + if(num > 20) + num = 20; + +retry: + written = swrite(sock, buffer, num); + if(written < 0) { + if((EWOULDBLOCK == SOCKERRNO) || (EAGAIN == SOCKERRNO)) { + wait_ms(10); + goto retry; + } + sendfailure = TRUE; + break; + } + + /* write to file as well */ + fwrite(buffer, 1, (size_t)written, dump); + + count -= written; + buffer += written; + + if(req->writedelay) { + int msecs_left = req->writedelay; + int intervals = msecs_left / MAX_SLEEP_TIME_MS; + if(msecs_left%MAX_SLEEP_TIME_MS) + intervals++; + logmsg("Pausing %d milliseconds after writing %zd bytes", + msecs_left, written); + while((intervals > 0) && !got_exit_signal) { + int sleep_time = msecs_left > MAX_SLEEP_TIME_MS ? + MAX_SLEEP_TIME_MS : msecs_left; + intervals--; + wait_ms(sleep_time); + msecs_left -= sleep_time; + } + } + } while((count > 0) && !got_exit_signal); + + do { + res = fclose(dump); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error closing file %s error: %d %s", + responsedump, error, strerror(error)); + + if(got_exit_signal) { + free(ptr); + free(cmd); + return -1; + } + + if(sendfailure) { + logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) " + "were sent", + responsesize-count, responsesize); + prevtestno = req->testno; + prevpartno = req->partno; + free(ptr); + free(cmd); + return -1; + } + + logmsg("Response sent (%zu bytes) and written to %s", + responsesize, responsedump); + free(ptr); + + if(cmdsize > 0) { + char command[32]; + int quarters; + int num; + ptr = cmd; + do { + if(2 == sscanf(ptr, "%31s %d", command, &num)) { + if(!strcmp("wait", command)) { + logmsg("Told to sleep for %d seconds", num); + quarters = num * 4; + while((quarters > 0) && !got_exit_signal) { + quarters--; + res = wait_ms(250); + if(res) { + /* should not happen */ + error = errno; + logmsg("wait_ms() failed with error: (%d) %s", + error, strerror(error)); + break; + } + } + if(!quarters) + logmsg("Continuing after sleeping %d seconds", num); + } + else + logmsg("Unknown command in reply command section"); + } + ptr = strchr(ptr, '\n'); + if(ptr) + ptr++; + else + ptr = NULL; + } while(ptr && *ptr); + } + free(cmd); + req->open = use_gopher ? FALSE : persistent; + + prevtestno = req->testno; + prevpartno = req->partno; + + return 0; +} + +static curl_socket_t connect_to(const char *ipaddr, unsigned short port) +{ + srvr_sockaddr_union_t serveraddr; + curl_socket_t serverfd; + int error; + int rc = 0; + const char *op_br = ""; + const char *cl_br = ""; + +#ifdef USE_IPV6 + if(socket_domain == AF_INET6) { + op_br = "["; + cl_br = "]"; + } +#endif + + if(!ipaddr) + return CURL_SOCKET_BAD; + + logmsg("about to connect to %s%s%s:%hu", + op_br, ipaddr, cl_br, port); + + + serverfd = socket(socket_domain, SOCK_STREAM, 0); + if(CURL_SOCKET_BAD == serverfd) { + error = SOCKERRNO; + logmsg("Error creating socket for server connection: (%d) %s", + error, sstrerror(error)); + return CURL_SOCKET_BAD; + } + +#ifdef TCP_NODELAY + if(socket_domain_is_ip()) { + /* Disable the Nagle algorithm */ + curl_socklen_t flag = 1; + if(0 != setsockopt(serverfd, IPPROTO_TCP, TCP_NODELAY, + (void *)&flag, sizeof(flag))) + logmsg("====> TCP_NODELAY for server connection failed"); + } +#endif + + /* We want to do the connect() in a non-blocking mode, since + * Windows has an internal retry logic that may lead to long + * timeouts if the peer is not listening. */ + if(0 != curlx_nonblock(serverfd, TRUE)) { + error = SOCKERRNO; + logmsg("curlx_nonblock(TRUE) failed with error: (%d) %s", + error, sstrerror(error)); + sclose(serverfd); + return CURL_SOCKET_BAD; + } + + switch(socket_domain) { + case AF_INET: + memset(&serveraddr.sa4, 0, sizeof(serveraddr.sa4)); + serveraddr.sa4.sin_family = AF_INET; + serveraddr.sa4.sin_port = htons(port); + if(Curl_inet_pton(AF_INET, ipaddr, &serveraddr.sa4.sin_addr) < 1) { + logmsg("Error inet_pton failed AF_INET conversion of '%s'", ipaddr); + sclose(serverfd); + return CURL_SOCKET_BAD; + } + + rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa4)); + break; +#ifdef USE_IPV6 + case AF_INET6: + memset(&serveraddr.sa6, 0, sizeof(serveraddr.sa6)); + serveraddr.sa6.sin6_family = AF_INET6; + serveraddr.sa6.sin6_port = htons(port); + if(Curl_inet_pton(AF_INET6, ipaddr, &serveraddr.sa6.sin6_addr) < 1) { + logmsg("Error inet_pton failed AF_INET6 conversion of '%s'", ipaddr); + sclose(serverfd); + return CURL_SOCKET_BAD; + } + + rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa6)); + break; +#endif /* USE_IPV6 */ +#ifdef USE_UNIX_SOCKETS + case AF_UNIX: + logmsg("Proxying through Unix socket is not (yet?) supported."); + return CURL_SOCKET_BAD; +#endif /* USE_UNIX_SOCKETS */ + } + + if(got_exit_signal) { + sclose(serverfd); + return CURL_SOCKET_BAD; + } + + if(rc) { + error = SOCKERRNO; + if((error == EINPROGRESS) || (error == EWOULDBLOCK)) { + fd_set output; + struct timeval timeout = {1, 0}; /* 1000 ms */ + + FD_ZERO(&output); + FD_SET(serverfd, &output); + while(1) { + rc = select((int)serverfd + 1, NULL, &output, NULL, &timeout); + if(rc < 0 && SOCKERRNO != EINTR) + goto error; + else if(rc > 0) { + curl_socklen_t errSize = sizeof(error); + if(0 != getsockopt(serverfd, SOL_SOCKET, SO_ERROR, + (void *)&error, &errSize)) + error = SOCKERRNO; + if((0 == error) || (EISCONN == error)) + goto success; + else if((error != EINPROGRESS) && (error != EWOULDBLOCK)) + goto error; + } + else if(!rc) { + logmsg("Timeout connecting to server port %hu", port); + sclose(serverfd); + return CURL_SOCKET_BAD; + } + } + } +error: + logmsg("Error connecting to server port %hu: (%d) %s", + port, error, sstrerror(error)); + sclose(serverfd); + return CURL_SOCKET_BAD; + } +success: + logmsg("connected fine to %s%s%s:%hu, now tunnel", + op_br, ipaddr, cl_br, port); + + if(0 != curlx_nonblock(serverfd, FALSE)) { + error = SOCKERRNO; + logmsg("curlx_nonblock(FALSE) failed with error: (%d) %s", + error, sstrerror(error)); + sclose(serverfd); + return CURL_SOCKET_BAD; + } + + return serverfd; +} + +/* + * A CONNECT has been received, a CONNECT response has been sent. + * + * This function needs to connect to the server, and then pass data between + * the client and the server back and forth until the connection is closed by + * either end. + * + * When doing FTP through a CONNECT proxy, we expect that the data connection + * will be setup while the first connect is still being kept up. Therefore we + * must accept a new connection and deal with it appropriately. + */ + +#define data_or_ctrl(x) ((x)?"DATA":"CTRL") + +#define SWS_CTRL 0 +#define SWS_DATA 1 + +static void http_connect(curl_socket_t *infdp, + curl_socket_t rootfd, + const char *ipaddr, + unsigned short ipport, + int keepalive_secs) +{ + curl_socket_t serverfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD}; + curl_socket_t clientfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD}; + ssize_t toc[2] = {0, 0}; /* number of bytes to client */ + ssize_t tos[2] = {0, 0}; /* number of bytes to server */ + char readclient[2][256]; + char readserver[2][256]; + bool poll_client_rd[2] = { TRUE, TRUE }; + bool poll_server_rd[2] = { TRUE, TRUE }; + bool poll_client_wr[2] = { TRUE, TRUE }; + bool poll_server_wr[2] = { TRUE, TRUE }; + bool primary = FALSE; + bool secondary = FALSE; + int max_tunnel_idx; /* SWS_CTRL or SWS_DATA */ + int loop; + int i; + int timeout_count = 0; + + /* primary tunnel client endpoint already connected */ + clientfd[SWS_CTRL] = *infdp; + + /* Sleep here to make sure the client reads CONNECT response's + 'end of headers' separate from the server data that follows. + This is done to prevent triggering libcurl known bug #39. */ + for(loop = 2; (loop > 0) && !got_exit_signal; loop--) + wait_ms(250); + if(got_exit_signal) + goto http_connect_cleanup; + + serverfd[SWS_CTRL] = connect_to(ipaddr, ipport); + if(serverfd[SWS_CTRL] == CURL_SOCKET_BAD) + goto http_connect_cleanup; + + /* Primary tunnel socket endpoints are now connected. Tunnel data back and + forth over the primary tunnel until client or server breaks the primary + tunnel, simultaneously allowing establishment, operation and teardown of + a secondary tunnel that may be used for passive FTP data connection. */ + + max_tunnel_idx = SWS_CTRL; + primary = TRUE; + + while(!got_exit_signal) { + + fd_set input; + fd_set output; + struct timeval timeout = {1, 0}; /* 1000 ms */ + ssize_t rc; + curl_socket_t maxfd = (curl_socket_t)-1; + + FD_ZERO(&input); + FD_ZERO(&output); + + if((clientfd[SWS_DATA] == CURL_SOCKET_BAD) && + (serverfd[SWS_DATA] == CURL_SOCKET_BAD) && + poll_client_rd[SWS_CTRL] && poll_client_wr[SWS_CTRL] && + poll_server_rd[SWS_CTRL] && poll_server_wr[SWS_CTRL]) { + /* listener socket is monitored to allow client to establish + secondary tunnel only when this tunnel is not established + and primary one is fully operational */ + FD_SET(rootfd, &input); + maxfd = rootfd; + } + + /* set tunnel sockets to wait for */ + for(i = 0; i <= max_tunnel_idx; i++) { + /* client side socket monitoring */ + if(clientfd[i] != CURL_SOCKET_BAD) { + if(poll_client_rd[i]) { + /* unless told not to do so, monitor readability */ + FD_SET(clientfd[i], &input); + if(clientfd[i] > maxfd) + maxfd = clientfd[i]; + } + if(poll_client_wr[i] && toc[i]) { + /* unless told not to do so, monitor writability + if there is data ready to be sent to client */ + FD_SET(clientfd[i], &output); + if(clientfd[i] > maxfd) + maxfd = clientfd[i]; + } + } + /* server side socket monitoring */ + if(serverfd[i] != CURL_SOCKET_BAD) { + if(poll_server_rd[i]) { + /* unless told not to do so, monitor readability */ + FD_SET(serverfd[i], &input); + if(serverfd[i] > maxfd) + maxfd = serverfd[i]; + } + if(poll_server_wr[i] && tos[i]) { + /* unless told not to do so, monitor writability + if there is data ready to be sent to server */ + FD_SET(serverfd[i], &output); + if(serverfd[i] > maxfd) + maxfd = serverfd[i]; + } + } + } + if(got_exit_signal) + break; + + do { + rc = select((int)maxfd + 1, &input, &output, NULL, &timeout); + } while(rc < 0 && errno == EINTR && !got_exit_signal); + + if(got_exit_signal) + break; + + if(rc > 0) { + /* socket action */ + bool tcp_fin_wr = FALSE; + timeout_count = 0; + + /* ---------------------------------------------------------- */ + + /* passive mode FTP may establish a secondary tunnel */ + if((clientfd[SWS_DATA] == CURL_SOCKET_BAD) && + (serverfd[SWS_DATA] == CURL_SOCKET_BAD) && FD_ISSET(rootfd, &input)) { + /* a new connection on listener socket (most likely from client) */ + curl_socket_t datafd = accept(rootfd, NULL, NULL); + if(datafd != CURL_SOCKET_BAD) { + static struct httprequest *req2; + int err = 0; + if(!req2) { + req2 = malloc(sizeof(*req2)); + if(!req2) + exit(1); + } + memset(req2, 0, sizeof(*req2)); + logmsg("====> Client connect DATA"); +#ifdef TCP_NODELAY + if(socket_domain_is_ip()) { + /* Disable the Nagle algorithm */ + curl_socklen_t flag = 1; + if(0 != setsockopt(datafd, IPPROTO_TCP, TCP_NODELAY, + (void *)&flag, sizeof(flag))) + logmsg("====> TCP_NODELAY for client DATA connection failed"); + } +#endif + init_httprequest(req2); + while(!req2->done_processing) { + err = get_request(datafd, req2); + if(err < 0) { + /* this socket must be closed, done or not */ + break; + } + } + + /* skip this and close the socket if err < 0 */ + if(err >= 0) { + err = send_doc(datafd, req2); + if(!err && req2->connect_request) { + /* sleep to prevent triggering libcurl known bug #39. */ + for(loop = 2; (loop > 0) && !got_exit_signal; loop--) + wait_ms(250); + if(!got_exit_signal) { + /* connect to the server */ + serverfd[SWS_DATA] = connect_to(ipaddr, req2->connect_port); + if(serverfd[SWS_DATA] != CURL_SOCKET_BAD) { + /* secondary tunnel established, now we have two + connections */ + poll_client_rd[SWS_DATA] = TRUE; + poll_client_wr[SWS_DATA] = TRUE; + poll_server_rd[SWS_DATA] = TRUE; + poll_server_wr[SWS_DATA] = TRUE; + max_tunnel_idx = SWS_DATA; + secondary = TRUE; + toc[SWS_DATA] = 0; + tos[SWS_DATA] = 0; + clientfd[SWS_DATA] = datafd; + datafd = CURL_SOCKET_BAD; + } + } + } + } + if(datafd != CURL_SOCKET_BAD) { + /* secondary tunnel not established */ + shutdown(datafd, SHUT_RDWR); + sclose(datafd); + } + } + if(got_exit_signal) + break; + } + + /* ---------------------------------------------------------- */ + + /* react to tunnel endpoint readable/writable notifications */ + for(i = 0; i <= max_tunnel_idx; i++) { + size_t len; + if(clientfd[i] != CURL_SOCKET_BAD) { + len = sizeof(readclient[i]) - tos[i]; + if(len && FD_ISSET(clientfd[i], &input)) { + /* read from client */ + rc = sread(clientfd[i], &readclient[i][tos[i]], len); + if(rc <= 0) { + logmsg("[%s] got %zd, STOP READING client", data_or_ctrl(i), rc); + shutdown(clientfd[i], SHUT_RD); + poll_client_rd[i] = FALSE; + } + else { + logmsg("[%s] READ %zd bytes from client", data_or_ctrl(i), rc); + logmsg("[%s] READ \"%s\"", data_or_ctrl(i), + data_to_hex(&readclient[i][tos[i]], rc)); + tos[i] += rc; + } + } + } + if(serverfd[i] != CURL_SOCKET_BAD) { + len = sizeof(readserver[i])-toc[i]; + if(len && FD_ISSET(serverfd[i], &input)) { + /* read from server */ + rc = sread(serverfd[i], &readserver[i][toc[i]], len); + if(rc <= 0) { + logmsg("[%s] got %zd, STOP READING server", data_or_ctrl(i), rc); + shutdown(serverfd[i], SHUT_RD); + poll_server_rd[i] = FALSE; + } + else { + logmsg("[%s] READ %zd bytes from server", data_or_ctrl(i), rc); + logmsg("[%s] READ \"%s\"", data_or_ctrl(i), + data_to_hex(&readserver[i][toc[i]], rc)); + toc[i] += rc; + } + } + } + if(clientfd[i] != CURL_SOCKET_BAD) { + if(toc[i] && FD_ISSET(clientfd[i], &output)) { + /* write to client */ + rc = swrite(clientfd[i], readserver[i], toc[i]); + if(rc <= 0) { + logmsg("[%s] got %zd, STOP WRITING client", data_or_ctrl(i), rc); + shutdown(clientfd[i], SHUT_WR); + poll_client_wr[i] = FALSE; + tcp_fin_wr = TRUE; + } + else { + logmsg("[%s] SENT %zd bytes to client", data_or_ctrl(i), rc); + logmsg("[%s] SENT \"%s\"", data_or_ctrl(i), + data_to_hex(readserver[i], rc)); + if(toc[i] - rc) + memmove(&readserver[i][0], &readserver[i][rc], toc[i]-rc); + toc[i] -= rc; + } + } + } + if(serverfd[i] != CURL_SOCKET_BAD) { + if(tos[i] && FD_ISSET(serverfd[i], &output)) { + /* write to server */ + rc = swrite(serverfd[i], readclient[i], tos[i]); + if(rc <= 0) { + logmsg("[%s] got %zd, STOP WRITING server", data_or_ctrl(i), rc); + shutdown(serverfd[i], SHUT_WR); + poll_server_wr[i] = FALSE; + tcp_fin_wr = TRUE; + } + else { + logmsg("[%s] SENT %zd bytes to server", data_or_ctrl(i), rc); + logmsg("[%s] SENT \"%s\"", data_or_ctrl(i), + data_to_hex(readclient[i], rc)); + if(tos[i] - rc) + memmove(&readclient[i][0], &readclient[i][rc], tos[i]-rc); + tos[i] -= rc; + } + } + } + } + if(got_exit_signal) + break; + + /* ---------------------------------------------------------- */ + + /* endpoint read/write disabling, endpoint closing and tunnel teardown */ + for(i = 0; i <= max_tunnel_idx; i++) { + for(loop = 2; loop > 0; loop--) { + /* loop twice to satisfy condition interdependencies without + having to await select timeout or another socket event */ + if(clientfd[i] != CURL_SOCKET_BAD) { + if(poll_client_rd[i] && !poll_server_wr[i]) { + logmsg("[%s] DISABLED READING client", data_or_ctrl(i)); + shutdown(clientfd[i], SHUT_RD); + poll_client_rd[i] = FALSE; + } + if(poll_client_wr[i] && !poll_server_rd[i] && !toc[i]) { + logmsg("[%s] DISABLED WRITING client", data_or_ctrl(i)); + shutdown(clientfd[i], SHUT_WR); + poll_client_wr[i] = FALSE; + tcp_fin_wr = TRUE; + } + } + if(serverfd[i] != CURL_SOCKET_BAD) { + if(poll_server_rd[i] && !poll_client_wr[i]) { + logmsg("[%s] DISABLED READING server", data_or_ctrl(i)); + shutdown(serverfd[i], SHUT_RD); + poll_server_rd[i] = FALSE; + } + if(poll_server_wr[i] && !poll_client_rd[i] && !tos[i]) { + logmsg("[%s] DISABLED WRITING server", data_or_ctrl(i)); + shutdown(serverfd[i], SHUT_WR); + poll_server_wr[i] = FALSE; + tcp_fin_wr = TRUE; + } + } + } + } + + if(tcp_fin_wr) + /* allow kernel to place FIN bit packet on the wire */ + wait_ms(250); + + /* socket clearing */ + for(i = 0; i <= max_tunnel_idx; i++) { + for(loop = 2; loop > 0; loop--) { + if(clientfd[i] != CURL_SOCKET_BAD) { + if(!poll_client_wr[i] && !poll_client_rd[i]) { + logmsg("[%s] CLOSING client socket", data_or_ctrl(i)); + sclose(clientfd[i]); + clientfd[i] = CURL_SOCKET_BAD; + if(serverfd[i] == CURL_SOCKET_BAD) { + logmsg("[%s] ENDING", data_or_ctrl(i)); + if(i == SWS_DATA) + secondary = FALSE; + else + primary = FALSE; + } + } + } + if(serverfd[i] != CURL_SOCKET_BAD) { + if(!poll_server_wr[i] && !poll_server_rd[i]) { + logmsg("[%s] CLOSING server socket", data_or_ctrl(i)); + sclose(serverfd[i]); + serverfd[i] = CURL_SOCKET_BAD; + if(clientfd[i] == CURL_SOCKET_BAD) { + logmsg("[%s] ENDING", data_or_ctrl(i)); + if(i == SWS_DATA) + secondary = FALSE; + else + primary = FALSE; + } + } + } + } + } + + /* ---------------------------------------------------------- */ + + max_tunnel_idx = secondary ? SWS_DATA : SWS_CTRL; + + if(!primary) + /* exit loop upon primary tunnel teardown */ + break; + + } /* (rc > 0) */ + else { + timeout_count++; + if(timeout_count > keepalive_secs) { + logmsg("CONNECT proxy timeout after %d idle seconds!", timeout_count); + break; + } + } + } + +http_connect_cleanup: + + for(i = SWS_DATA; i >= SWS_CTRL; i--) { + if(serverfd[i] != CURL_SOCKET_BAD) { + logmsg("[%s] CLOSING server socket (cleanup)", data_or_ctrl(i)); + shutdown(serverfd[i], SHUT_RDWR); + sclose(serverfd[i]); + } + if(clientfd[i] != CURL_SOCKET_BAD) { + logmsg("[%s] CLOSING client socket (cleanup)", data_or_ctrl(i)); + shutdown(clientfd[i], SHUT_RDWR); + sclose(clientfd[i]); + } + if((serverfd[i] != CURL_SOCKET_BAD) || + (clientfd[i] != CURL_SOCKET_BAD)) { + logmsg("[%s] ABORTING", data_or_ctrl(i)); + } + } + + *infdp = CURL_SOCKET_BAD; +} + +static void http_upgrade(struct httprequest *req) +{ + (void)req; + logmsg("Upgraded to ... %u", req->upgrade_request); + /* left to implement */ +} + + +/* returns a socket handle, or 0 if there are no more waiting sockets, + or < 0 if there was an error */ +static curl_socket_t accept_connection(curl_socket_t sock) +{ + curl_socket_t msgsock = CURL_SOCKET_BAD; + int error; + int flag = 1; + + if(MAX_SOCKETS == num_sockets) { + logmsg("Too many open sockets!"); + return CURL_SOCKET_BAD; + } + + msgsock = accept(sock, NULL, NULL); + + if(got_exit_signal) { + if(CURL_SOCKET_BAD != msgsock) + sclose(msgsock); + return CURL_SOCKET_BAD; + } + + if(CURL_SOCKET_BAD == msgsock) { + error = SOCKERRNO; + if(EAGAIN == error || EWOULDBLOCK == error) { + /* nothing to accept */ + return 0; + } + logmsg("MAJOR ERROR: accept() failed with error: (%d) %s", + error, sstrerror(error)); + return CURL_SOCKET_BAD; + } + + if(0 != curlx_nonblock(msgsock, TRUE)) { + error = SOCKERRNO; + logmsg("curlx_nonblock failed with error: (%d) %s", + error, sstrerror(error)); + sclose(msgsock); + return CURL_SOCKET_BAD; + } + + if(0 != setsockopt(msgsock, SOL_SOCKET, SO_KEEPALIVE, + (void *)&flag, sizeof(flag))) { + error = SOCKERRNO; + logmsg("setsockopt(SO_KEEPALIVE) failed with error: (%d) %s", + error, sstrerror(error)); + sclose(msgsock); + return CURL_SOCKET_BAD; + } + + /* + ** As soon as this server accepts a connection from the test harness it + ** must set the server logs advisor read lock to indicate that server + ** logs should not be read until this lock is removed by this server. + */ + + if(!serverlogslocked) + set_advisor_read_lock(loglockfile); + serverlogslocked += 1; + + logmsg("====> Client connect"); + + all_sockets[num_sockets] = msgsock; + num_sockets += 1; + +#ifdef TCP_NODELAY + if(socket_domain_is_ip()) { + /* + * Disable the Nagle algorithm to make it easier to send out a large + * response in many small segments to torture the clients more. + */ + if(0 != setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY, + (void *)&flag, sizeof(flag))) + logmsg("====> TCP_NODELAY failed"); + } +#endif + + return msgsock; +} + +/* returns 1 if the connection should be serviced again immediately, 0 if there + is no data waiting, or < 0 if it should be closed */ +static int service_connection(curl_socket_t msgsock, struct httprequest *req, + curl_socket_t listensock, + const char *connecthost, + int keepalive_secs) +{ + if(got_exit_signal) + return -1; + + while(!req->done_processing) { + int rc = get_request(msgsock, req); + if(rc <= 0) { + /* Nothing further to read now, possibly because the socket was closed */ + return rc; + } + } + + if(prevbounce) { + /* bounce treatment requested */ + if((req->testno == prevtestno) && + (req->partno == prevpartno)) { + req->partno++; + logmsg("BOUNCE part number to %ld", req->partno); + } + else { + prevbounce = FALSE; + prevtestno = -1; + prevpartno = -1; + } + } + + send_doc(msgsock, req); + if(got_exit_signal) + return -1; + + if(req->testno < 0) { + logmsg("special request received, no persistency"); + return -1; + } + if(!req->open) { + logmsg("instructed to close connection after server-reply"); + return -1; + } + + if(req->connect_request) { + /* a CONNECT request, setup and talk the tunnel */ + if(!is_proxy) { + logmsg("received CONNECT but isn't running as proxy!"); + return 1; + } + else { + http_connect(&msgsock, listensock, connecthost, req->connect_port, + keepalive_secs); + return -1; + } + } + + if(req->upgrade_request) { + /* an upgrade request, switch to another protocol here */ + http_upgrade(req); + return 1; + } + + /* if we got a CONNECT, loop and get another request as well! */ + + if(req->open) { + logmsg("=> persistent connection request ended, awaits new request\n"); + return 1; + } + else { + logmsg("=> NOT a persistent connection, close close CLOSE\n"); + } + + return -1; +} + +int main(int argc, char *argv[]) +{ + srvr_sockaddr_union_t me; + curl_socket_t sock = CURL_SOCKET_BAD; + int wrotepidfile = 0; + int wroteportfile = 0; + int flag; + unsigned short port = DEFAULT_PORT; +#ifdef USE_UNIX_SOCKETS + const char *unix_socket = NULL; + bool unlink_socket = false; +#endif + const char *pidname = ".http.pid"; + const char *portname = ".http.port"; + struct httprequest *req = NULL; + int rc = 0; + int error; + int arg = 1; + const char *connecthost = "127.0.0.1"; + const char *socket_type = "IPv4"; + char port_str[11]; + const char *location_str = port_str; + int keepalive_secs = 5; + const char *protocol_type = "HTTP"; + + /* a default CONNECT port is basically pointless but still ... */ + size_t socket_idx; + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + puts("sws IPv4" +#ifdef USE_IPV6 + "/IPv6" +#endif +#ifdef USE_UNIX_SOCKETS + "/unix" +#endif + ); + return 0; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--logdir", argv[arg])) { + arg++; + if(argc > arg) + logdir = argv[arg++]; + } + else if(!strcmp("--cmdfile", argv[arg])) { + arg++; + if(argc > arg) + cmdfile = argv[arg++]; + } + else if(!strcmp("--gopher", argv[arg])) { + arg++; + use_gopher = TRUE; + protocol_type = "GOPHER"; + end_of_headers = "\r\n"; /* gopher style is much simpler */ + } + else if(!strcmp("--ipv4", argv[arg])) { + socket_type = "IPv4"; + socket_domain = AF_INET; + location_str = port_str; + arg++; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + socket_type = "IPv6"; + socket_domain = AF_INET6; + location_str = port_str; +#endif + arg++; + } + else if(!strcmp("--unix-socket", argv[arg])) { + arg++; + if(argc > arg) { +#ifdef USE_UNIX_SOCKETS + unix_socket = argv[arg]; + if(strlen(unix_socket) >= sizeof(me.sau.sun_path)) { + fprintf(stderr, + "sws: socket path must be shorter than %zu chars: %s\n", + sizeof(me.sau.sun_path), unix_socket); + return 0; + } + socket_type = "unix"; + socket_domain = AF_UNIX; + location_str = unix_socket; +#endif + arg++; + } + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + if((endptr != argv[arg] + strlen(argv[arg])) || + (ulnum && ((ulnum < 1025UL) || (ulnum > 65535UL)))) { + fprintf(stderr, "sws: invalid --port argument (%s)\n", + argv[arg]); + return 0; + } + port = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--srcdir", argv[arg])) { + arg++; + if(argc > arg) { + path = argv[arg]; + arg++; + } + } + else if(!strcmp("--keepalive", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + if((endptr != argv[arg] + strlen(argv[arg])) || + (ulnum && (ulnum > 65535UL))) { + fprintf(stderr, "sws: invalid --keepalive argument (%s), must " + "be number of seconds\n", argv[arg]); + return 0; + } + keepalive_secs = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--connect", argv[arg])) { + /* The connect host IP number that the proxy will connect to no matter + what the client asks for, but also use this as a hint that we run as + a proxy and do a few different internal choices */ + arg++; + if(argc > arg) { + connecthost = argv[arg]; + arg++; + is_proxy = TRUE; + logmsg("Run as proxy, CONNECT to host %s", connecthost); + } + } + else { + puts("Usage: sws [option]\n" + " --version\n" + " --logfile [file]\n" + " --logdir [directory]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --unix-socket [file]\n" + " --port [port]\n" + " --srcdir [path]\n" + " --connect [ip4-addr]\n" + " --gopher"); + return 0; + } + } + + msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/sws-%s%s-%s.lock", + logdir, SERVERLOGS_LOCKDIR, protocol_type, + is_proxy ? "-proxy" : "", socket_type); + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); +#endif + + install_signal_handlers(false); + + req = calloc(1, sizeof(*req)); + if(!req) + goto sws_cleanup; + + sock = socket(socket_domain, SOCK_STREAM, 0); + + all_sockets[0] = sock; + num_sockets = 1; + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", error, sstrerror(error)); + goto sws_cleanup; + } + + flag = 1; + if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag))) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + goto sws_cleanup; + } + if(0 != curlx_nonblock(sock, TRUE)) { + error = SOCKERRNO; + logmsg("curlx_nonblock failed with error: (%d) %s", + error, sstrerror(error)); + goto sws_cleanup; + } + + switch(socket_domain) { + case AF_INET: + memset(&me.sa4, 0, sizeof(me.sa4)); + me.sa4.sin_family = AF_INET; + me.sa4.sin_addr.s_addr = INADDR_ANY; + me.sa4.sin_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa4)); + break; +#ifdef USE_IPV6 + case AF_INET6: + memset(&me.sa6, 0, sizeof(me.sa6)); + me.sa6.sin6_family = AF_INET6; + me.sa6.sin6_addr = in6addr_any; + me.sa6.sin6_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa6)); + break; +#endif /* USE_IPV6 */ +#ifdef USE_UNIX_SOCKETS + case AF_UNIX: + rc = bind_unix_socket(sock, unix_socket, &me.sau); +#endif /* USE_UNIX_SOCKETS */ + } + if(0 != rc) { + error = SOCKERRNO; +#ifdef USE_UNIX_SOCKETS + if(socket_domain == AF_UNIX) + logmsg("Error binding socket on path %s: (%d) %s", + unix_socket, error, sstrerror(error)); + else +#endif + logmsg("Error binding socket on port %hu: (%d) %s", + port, error, sstrerror(error)); + goto sws_cleanup; + } + + if(!port) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(socket_domain != AF_INET6) +#endif + la_size = sizeof(localaddr.sa4); +#ifdef USE_IPV6 + else + la_size = sizeof(localaddr.sa6); +#endif + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + goto sws_cleanup; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + port = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + port = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!port) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + sclose(sock); + goto sws_cleanup; + } + } +#ifdef USE_UNIX_SOCKETS + if(socket_domain != AF_UNIX) +#endif + msnprintf(port_str, sizeof(port_str), "port %hu", port); + + logmsg("Running %s %s version on %s", + protocol_type, socket_type, location_str); + + /* start accepting connections */ + rc = listen(sock, 50); + if(0 != rc) { + error = SOCKERRNO; + logmsg("listen() failed with error: (%d) %s", error, sstrerror(error)); + goto sws_cleanup; + } + +#ifdef USE_UNIX_SOCKETS + /* listen succeeds, so let's assume a valid listening Unix socket */ + unlink_socket = true; +#endif + + /* + ** As soon as this server writes its pid file the test harness will + ** attempt to connect to this server and initiate its verification. + */ + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) + goto sws_cleanup; + + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) + goto sws_cleanup; + + /* initialization of httprequest struct is done before get_request(), but + the pipelining struct field must be initialized previously to FALSE + every time a new connection arrives. */ + + init_httprequest(req); + + for(;;) { + fd_set input; + fd_set output; + struct timeval timeout = {0, 250000L}; /* 250 ms */ + curl_socket_t maxfd = (curl_socket_t)-1; + int active; + + /* Clear out closed sockets */ + for(socket_idx = num_sockets - 1; socket_idx >= 1; --socket_idx) { + if(CURL_SOCKET_BAD == all_sockets[socket_idx]) { + char *dst = (char *) (all_sockets + socket_idx); + char *src = (char *) (all_sockets + socket_idx + 1); + char *end = (char *) (all_sockets + num_sockets); + memmove(dst, src, end - src); + num_sockets -= 1; + } + } + + if(got_exit_signal) + goto sws_cleanup; + + /* Set up for select */ + FD_ZERO(&input); + FD_ZERO(&output); + + for(socket_idx = 0; socket_idx < num_sockets; ++socket_idx) { + /* Listen on all sockets */ + FD_SET(all_sockets[socket_idx], &input); + if(all_sockets[socket_idx] > maxfd) + maxfd = all_sockets[socket_idx]; + } + + if(got_exit_signal) + goto sws_cleanup; + + do { + rc = select((int)maxfd + 1, &input, &output, NULL, &timeout); + } while(rc < 0 && errno == EINTR && !got_exit_signal); + + if(got_exit_signal) + goto sws_cleanup; + + if(rc < 0) { + error = SOCKERRNO; + logmsg("select() failed with error: (%d) %s", error, sstrerror(error)); + goto sws_cleanup; + } + + if(rc == 0) { + /* Timed out - try again */ + continue; + } + active = rc; /* a positive number */ + + /* Check if the listening socket is ready to accept */ + if(FD_ISSET(all_sockets[0], &input)) { + /* Service all queued connections */ + curl_socket_t msgsock; + do { + msgsock = accept_connection(sock); + logmsg("accept_connection %" FMT_SOCKET_T + " returned %" FMT_SOCKET_T, sock, msgsock); + if(CURL_SOCKET_BAD == msgsock) + goto sws_cleanup; + if(req->delay) + wait_ms(req->delay); + } while(msgsock > 0); + active--; + } + + /* Service all connections that are ready */ + for(socket_idx = 1; (socket_idx < num_sockets) && active; ++socket_idx) { + if(FD_ISSET(all_sockets[socket_idx], &input)) { + active--; + if(got_exit_signal) + goto sws_cleanup; + + /* Service this connection until it has nothing available */ + do { + rc = service_connection(all_sockets[socket_idx], req, sock, + connecthost, keepalive_secs); + if(got_exit_signal) + goto sws_cleanup; + + if(rc < 0) { + logmsg("====> Client disconnect %d", req->connmon); + + if(req->connmon) { + const char *keepopen = "[DISCONNECT]\n"; + storerequest(keepopen, strlen(keepopen)); + } + + if(!req->open) + /* When instructed to close connection after server-reply we + wait a very small amount of time before doing so. If this + is not done client might get an ECONNRESET before reading + a single byte of server-reply. */ + wait_ms(50); + + if(all_sockets[socket_idx] != CURL_SOCKET_BAD) { + sclose(all_sockets[socket_idx]); + all_sockets[socket_idx] = CURL_SOCKET_BAD; + } + + serverlogslocked -= 1; + if(!serverlogslocked) + clear_advisor_read_lock(loglockfile); + + if(req->testno == DOCNUMBER_QUIT) + goto sws_cleanup; + } + + /* Reset the request, unless we're still in the middle of reading */ + if(rc && !req->upgrade_request) + /* Note: resetting the HTTP request here can cause problems if: + * 1) req->skipall is TRUE, + * 2) the socket is still open, and + * 3) (stale) data is still available (or about to be available) + * on that socket + * In that case, this loop will run once more and treat that stale + * data (in service_connection()) as the first data received on + * this new HTTP request and report "** Unusual request" (skipall + * would have otherwise caused that data to be ignored). Normally, + * that socket will be closed by the client and there won't be any + * stale data to cause this, but stranger things have happened (see + * issue #11678). + */ + init_httprequest(req); + } while(rc > 0); + } + } + + if(got_exit_signal) + goto sws_cleanup; + } + +sws_cleanup: + + for(socket_idx = 1; socket_idx < num_sockets; ++socket_idx) + if((all_sockets[socket_idx] != sock) && + (all_sockets[socket_idx] != CURL_SOCKET_BAD)) + sclose(all_sockets[socket_idx]); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + +#ifdef USE_UNIX_SOCKETS + if(unlink_socket && socket_domain == AF_UNIX) { + rc = unlink(unix_socket); + logmsg("unlink(%s) = %d (%s)", unix_socket, rc, strerror(rc)); + } +#endif + + free(req); + + if(got_exit_signal) + logmsg("signalled to die"); + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + + restore_signal_handlers(false); + + if(got_exit_signal) { + logmsg("========> %s sws (%s pid: %ld) exits with signal (%d)", + socket_type, location_str, (long)Curl_getpid(), exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("========> sws quits"); + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/testpart.c b/local-test-curl-delta-01/afc-curl/tests/server/testpart.c new file mode 100644 index 0000000000000000000000000000000000000000..b102f3e375edc1f6e1a3dcc4185b56dbf5630217 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/testpart.c @@ -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 + * + ***************************************************************************/ +#include "server_setup.h" + +#include "getpart.h" + +#include "curl_printf.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +int main(int argc, char **argv) +{ + char *part; + size_t partlen; + + if(argc < 3) { + printf("./testpart main sub\n"); + } + else { + int rc = getpart(&part, &partlen, argv[1], argv[2], stdin); + size_t i; + if(rc) + return rc; + for(i = 0; i < partlen; i++) + printf("%c", part[i]); + free(part); + } + return 0; +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/tftp.h b/local-test-curl-delta-01/afc-curl/tests/server/tftp.h new file mode 100644 index 0000000000000000000000000000000000000000..a3d56b7b3c7f6dde4ecd3ad458485684b03677b6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/tftp.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_SERVER_TFTP_H +#define HEADER_CURL_SERVER_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 + * + ***************************************************************************/ +#include "server_setup.h" + +/* This file is a rewrite/clone of the arpa/tftp.h file for systems without + it. */ + +#define SEGSIZE 512 /* data segment size */ + +#if defined(__GNUC__) && ((__GNUC__ >= 3) || \ + ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7))) +# define PACKED_STRUCT __attribute__((__packed__)) +#else +# define PACKED_STRUCT /* NOTHING */ +#endif + +/* Using a packed struct as binary in a program is begging for problems, but + the tftpd server was written like this so we have this struct here to make + things build. */ + +struct tftphdr { + unsigned short th_opcode; /* packet type */ + unsigned short th_block; /* all sorts of things */ + char th_data[1]; /* data or error string */ +} PACKED_STRUCT; + +#define th_stuff th_block +#define th_code th_block +#define th_msg th_data + +#define EUNDEF 0 +#define ENOTFOUND 1 +#define EACCESS 2 +#define ENOSPACE 3 +#define EBADOP 4 +#define EBADID 5 +#define EEXISTS 6 +#define ENOUSER 7 + +#endif /* HEADER_CURL_SERVER_TFTP_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/server/tftpd.c b/local-test-curl-delta-01/afc-curl/tests/server/tftpd.c new file mode 100644 index 0000000000000000000000000000000000000000..4edc2fd6ddf4c505a4d52d882d7f3b91a372de7c --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/tftpd.c @@ -0,0 +1,1378 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * + * Trivial file transfer protocol server. + * + * This code includes many modifications by Jim Guyton + * + * This source file was started based on netkit-tftpd 0.17 + * Heavily modified for curl's test suite + */ + +/* + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (c) 1983, Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * SPDX-License-Identifier: BSD-4-Clause-UC + */ + +#include "server_setup.h" + +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#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 HAVE_SYS_FILIO_H +/* FIONREAD on Solaris 7 */ +#include +#endif + +#include + +#ifdef HAVE_PWD_H +#include +#endif + +#include + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "util.h" +#include "server_sockaddr.h" +#include "tftp.h" + +/* include memdebug.h last */ +#include "memdebug.h" + +/***************************************************************************** +* STRUCT DECLARATIONS AND DEFINES * +*****************************************************************************/ + +#ifndef PKTSIZE +#define PKTSIZE (SEGSIZE + 4) /* SEGSIZE defined in arpa/tftp.h */ +#endif + +struct testcase { + char *buffer; /* holds the file data to send to the client */ + size_t bufsize; /* size of the data in buffer */ + char *rptr; /* read pointer into the buffer */ + size_t rcount; /* amount of data left to read of the file */ + long testno; /* test case number */ + int ofile; /* file descriptor for output file when uploading to us */ + + int writedelay; /* number of seconds between each packet */ +}; + +struct formats { + const char *f_mode; + int f_convert; +}; + +struct errmsg { + int e_code; + const char *e_msg; +}; + +typedef union { + struct tftphdr hdr; + char storage[PKTSIZE]; +} tftphdr_storage_t; + +/* + * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the + * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE. + */ + +struct bf { + int counter; /* size of data in buffer, or flag */ + tftphdr_storage_t buf; /* room for data packet */ +}; + +#define BF_ALLOC -3 /* alloc'd but not yet filled */ +#define BF_FREE -2 /* free */ + +#define opcode_RRQ 1 +#define opcode_WRQ 2 +#define opcode_DATA 3 +#define opcode_ACK 4 +#define opcode_ERROR 5 + +#define TIMEOUT 5 + +#undef MIN +#define MIN(x,y) ((x)<(y)?(x):(y)) + +#ifndef DEFAULT_LOGFILE +#define DEFAULT_LOGFILE "log/tftpd.log" +#endif + +#define REQUEST_DUMP "server.input" + +#define DEFAULT_PORT 8999 /* UDP */ + +/***************************************************************************** +* GLOBAL VARIABLES * +*****************************************************************************/ + +static struct errmsg errmsgs[] = { + { EUNDEF, "Undefined error code" }, + { ENOTFOUND, "File not found" }, + { EACCESS, "Access violation" }, + { ENOSPACE, "Disk full or allocation exceeded" }, + { EBADOP, "Illegal TFTP operation" }, + { EBADID, "Unknown transfer ID" }, + { EEXISTS, "File already exists" }, + { ENOUSER, "No such user" }, + { -1, 0 } +}; + +static const struct formats formata[] = { + { "netascii", 1 }, + { "octet", 0 }, + { NULL, 0 } +}; + +static struct bf bfs[2]; + +static int nextone; /* index of next buffer to use */ +static int current; /* index of buffer in use */ + + /* control flags for crlf conversions */ +static int newline = 0; /* fillbuf: in middle of newline expansion */ +static int prevchar = -1; /* putbuf: previous char (cr check) */ + +static tftphdr_storage_t buf; +static tftphdr_storage_t ackbuf; + +static srvr_sockaddr_union_t from; +static curl_socklen_t fromlen; + +static curl_socket_t peer = CURL_SOCKET_BAD; + +static unsigned int timeout; +static unsigned int maxtimeout = 5 * TIMEOUT; + +#ifdef USE_IPV6 +static bool use_ipv6 = FALSE; +#endif +static const char *ipv_inuse = "IPv4"; + +const char *serverlogfile = DEFAULT_LOGFILE; +static const char *logdir = "log"; +static char loglockfile[256]; +static const char *pidname = ".tftpd.pid"; +static const char *portname = NULL; /* none by default */ +static int serverlogslocked = 0; +static int wrotepidfile = 0; +static int wroteportfile = 0; + +#ifdef HAVE_SIGSETJMP +static sigjmp_buf timeoutbuf; +#endif + +#if defined(HAVE_ALARM) && defined(SIGALRM) +static const unsigned int rexmtval = TIMEOUT; +#endif + +/***************************************************************************** +* FUNCTION PROTOTYPES * +*****************************************************************************/ + +static struct tftphdr *rw_init(int); + +static struct tftphdr *w_init(void); + +static struct tftphdr *r_init(void); + +static void read_ahead(struct testcase *test, int convert); + +static ssize_t write_behind(struct testcase *test, int convert); + +static int synchnet(curl_socket_t); + +static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size); + +static int validate_access(struct testcase *test, + const char *filename, unsigned short mode); + +static void sendtftp(struct testcase *test, const struct formats *pf); + +static void recvtftp(struct testcase *test, const struct formats *pf); + +static void nak(int error); + +#if defined(HAVE_ALARM) && defined(SIGALRM) + +static void mysignal(int sig, void (*handler)(int)); + +static void timer(int signum); + +static void justtimeout(int signum); + +#endif /* HAVE_ALARM && SIGALRM */ + +/***************************************************************************** +* FUNCTION IMPLEMENTATIONS * +*****************************************************************************/ + +#if defined(HAVE_ALARM) && defined(SIGALRM) + +/* + * Like signal(), but with well-defined semantics. + */ +static void mysignal(int sig, void (*handler)(int)) +{ + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handler; + sigaction(sig, &sa, NULL); +} + +#ifdef HAVE_SIGSETJMP +CURL_NORETURN +#endif +static void timer(int signum) +{ + (void)signum; + + logmsg("alarm!"); + + timeout += rexmtval; + if(timeout >= maxtimeout) { + if(wrotepidfile) { + wrotepidfile = 0; + unlink(pidname); + } + if(wroteportfile) { + wroteportfile = 0; + unlink(portname); + } + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + exit(1); + } +#ifdef HAVE_SIGSETJMP + siglongjmp(timeoutbuf, 1); +#endif +} + +static void justtimeout(int signum) +{ + (void)signum; +} + +#endif /* HAVE_ALARM && SIGALRM */ + +/* + * init for either read-ahead or write-behind. + * zero for write-behind, one for read-head. + */ +static struct tftphdr *rw_init(int x) +{ + newline = 0; /* init crlf flag */ + prevchar = -1; + bfs[0].counter = BF_ALLOC; /* pass out the first buffer */ + current = 0; + bfs[1].counter = BF_FREE; + nextone = x; /* ahead or behind? */ + return &bfs[0].buf.hdr; +} + +static struct tftphdr *w_init(void) +{ + return rw_init(0); /* write-behind */ +} + +static struct tftphdr *r_init(void) +{ + return rw_init(1); /* read-ahead */ +} + +/* Have emptied current buffer by sending to net and getting ack. + Free it and return next buffer filled with data. + */ +static int readit(struct testcase *test, struct tftphdr **dpp, + int convert /* if true, convert to ASCII */) +{ + struct bf *b; + + bfs[current].counter = BF_FREE; /* free old one */ + current = !current; /* "incr" current */ + + b = &bfs[current]; /* look at new buffer */ + if(b->counter == BF_FREE) /* if it's empty */ + read_ahead(test, convert); /* fill it */ + + *dpp = &b->buf.hdr; /* set caller's ptr */ + return b->counter; +} + +/* + * fill the input buffer, doing ASCII conversions if requested + * conversions are lf -> cr, lf and cr -> cr, nul + */ +static void read_ahead(struct testcase *test, + int convert /* if true, convert to ASCII */) +{ + int i; + char *p; + int c; + struct bf *b; + struct tftphdr *dp; + + b = &bfs[nextone]; /* look at "next" buffer */ + if(b->counter != BF_FREE) /* nop if not free */ + return; + nextone = !nextone; /* "incr" next buffer ptr */ + + dp = &b->buf.hdr; + + if(convert == 0) { + /* The former file reading code did this: + b->counter = read(fileno(file), dp->th_data, SEGSIZE); */ + size_t copy_n = MIN(SEGSIZE, test->rcount); + memcpy(dp->th_data, test->rptr, copy_n); + + /* decrease amount, advance pointer */ + test->rcount -= copy_n; + test->rptr += copy_n; + b->counter = (int)copy_n; + return; + } + + p = dp->th_data; + for(i = 0 ; i < SEGSIZE; i++) { + if(newline) { + if(prevchar == '\n') + c = '\n'; /* lf to cr,lf */ + else + c = '\0'; /* cr to cr,nul */ + newline = 0; + } + else { + if(test->rcount) { + c = test->rptr[0]; + test->rptr++; + test->rcount--; + } + else + break; + if(c == '\n' || c == '\r') { + prevchar = c; + c = '\r'; + newline = 1; + } + } + *p++ = (char)c; + } + b->counter = (int)(p - dp->th_data); +} + +/* Update count associated with the buffer, get new buffer from the queue. + Calls write_behind only if next buffer not available. + */ +static int writeit(struct testcase *test, struct tftphdr * volatile *dpp, + int ct, int convert) +{ + bfs[current].counter = ct; /* set size of data to write */ + current = !current; /* switch to other buffer */ + if(bfs[current].counter != BF_FREE) /* if not free */ + write_behind(test, convert); /* flush it */ + bfs[current].counter = BF_ALLOC; /* mark as alloc'd */ + *dpp = &bfs[current].buf.hdr; + return ct; /* this is a lie of course */ +} + +/* + * Output a buffer to a file, converting from netascii if requested. + * CR, NUL -> CR and CR, LF => LF. + * Note spec is undefined if we get CR as last byte of file or a + * CR followed by anything else. In this case we leave it alone. + */ +static ssize_t write_behind(struct testcase *test, int convert) +{ + char *writebuf; + int count; + int ct; + char *p; + int c; /* current character */ + struct bf *b; + struct tftphdr *dp; + + b = &bfs[nextone]; + if(b->counter < -1) /* anything to flush? */ + return 0; /* just nop if nothing to do */ + + if(!test->ofile) { + char outfile[256]; + msnprintf(outfile, sizeof(outfile), "%s/upload.%ld", logdir, test->testno); +#ifdef _WIN32 + test->ofile = open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777); +#else + test->ofile = open(outfile, O_CREAT|O_RDWR, 0777); +#endif + if(test->ofile == -1) { + logmsg("Couldn't create and/or open file %s for upload!", outfile); + return -1; /* failure! */ + } + } + + count = b->counter; /* remember byte count */ + b->counter = BF_FREE; /* reset flag */ + dp = &b->buf.hdr; + nextone = !nextone; /* incr for next time */ + writebuf = dp->th_data; + + if(count <= 0) + return -1; /* nak logic? */ + + if(convert == 0) + return write(test->ofile, writebuf, count); + + p = writebuf; + ct = count; + while(ct--) { /* loop over the buffer */ + c = *p++; /* pick up a character */ + if(prevchar == '\r') { /* if prev char was cr */ + if(c == '\n') /* if have cr,lf then just */ + lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */ + else + if(c == '\0') /* if have cr,nul then */ + goto skipit; /* just skip over the putc */ + /* else just fall through and allow it */ + } + /* formerly + putc(c, file); */ + if(1 != write(test->ofile, &c, 1)) + break; +skipit: + prevchar = c; + } + return count; +} + +/* When an error has occurred, it is possible that the two sides are out of + * synch. Ie: that what I think is the other side's response to packet N is + * really their response to packet N-1. + * + * So, to try to prevent that, we flush all the input queued up for us on the + * network connection on our host. + * + * We return the number of packets we flushed (mostly for reporting when trace + * is active). + */ + +static int synchnet(curl_socket_t f /* socket to flush */) +{ + +#if defined(HAVE_IOCTLSOCKET) + unsigned long i; +#else + int i; +#endif + int j = 0; + char rbuf[PKTSIZE]; + srvr_sockaddr_union_t fromaddr; + curl_socklen_t fromaddrlen; + + for(;;) { +#if defined(HAVE_IOCTLSOCKET) + (void) ioctlsocket(f, FIONREAD, &i); +#else + (void) ioctl(f, FIONREAD, &i); +#endif + if(i) { + j++; +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + fromaddrlen = sizeof(fromaddr.sa4); +#ifdef USE_IPV6 + else + fromaddrlen = sizeof(fromaddr.sa6); +#endif + (void) recvfrom(f, rbuf, sizeof(rbuf), 0, + &fromaddr.sa, &fromaddrlen); + } + else + break; + } + return j; +} + +int main(int argc, char **argv) +{ + srvr_sockaddr_union_t me; + struct tftphdr *tp; + ssize_t n = 0; + int arg = 1; + unsigned short port = DEFAULT_PORT; + curl_socket_t sock = CURL_SOCKET_BAD; + int flag; + int rc; + int error; + struct testcase test; + int result = 0; + + memset(&test, 0, sizeof(test)); + + while(argc > arg) { + if(!strcmp("--version", argv[arg])) { + printf("tftpd IPv4%s\n", +#ifdef USE_IPV6 + "/IPv6" +#else + "" +#endif + ); + return 0; + } + else if(!strcmp("--pidfile", argv[arg])) { + arg++; + if(argc > arg) + pidname = argv[arg++]; + } + else if(!strcmp("--portfile", argv[arg])) { + arg++; + if(argc > arg) + portname = argv[arg++]; + } + else if(!strcmp("--logfile", argv[arg])) { + arg++; + if(argc > arg) + serverlogfile = argv[arg++]; + } + else if(!strcmp("--logdir", argv[arg])) { + arg++; + if(argc > arg) + logdir = argv[arg++]; + } + else if(!strcmp("--ipv4", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv4"; + use_ipv6 = FALSE; +#endif + arg++; + } + else if(!strcmp("--ipv6", argv[arg])) { +#ifdef USE_IPV6 + ipv_inuse = "IPv6"; + use_ipv6 = TRUE; +#endif + arg++; + } + else if(!strcmp("--port", argv[arg])) { + arg++; + if(argc > arg) { + char *endptr; + unsigned long ulnum = strtoul(argv[arg], &endptr, 10); + port = curlx_ultous(ulnum); + arg++; + } + } + else if(!strcmp("--srcdir", argv[arg])) { + arg++; + if(argc > arg) { + path = argv[arg]; + arg++; + } + } + else { + puts("Usage: tftpd [option]\n" + " --version\n" + " --logfile [file]\n" + " --logdir [directory]\n" + " --pidfile [file]\n" + " --portfile [file]\n" + " --ipv4\n" + " --ipv6\n" + " --port [port]\n" + " --srcdir [path]"); + return 0; + } + } + + msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/tftp-%s.lock", + logdir, SERVERLOGS_LOCKDIR, ipv_inuse); + +#ifdef _WIN32 + win32_init(); + atexit(win32_cleanup); +#endif + + install_signal_handlers(true); + +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + sock = socket(AF_INET, SOCK_DGRAM, 0); +#ifdef USE_IPV6 + else + sock = socket(AF_INET6, SOCK_DGRAM, 0); +#endif + + if(CURL_SOCKET_BAD == sock) { + error = SOCKERRNO; + logmsg("Error creating socket: (%d) %s", error, sstrerror(error)); + result = 1; + goto tftpd_cleanup; + } + + flag = 1; + if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (void *)&flag, sizeof(flag))) { + error = SOCKERRNO; + logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", + error, sstrerror(error)); + result = 1; + goto tftpd_cleanup; + } + +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + memset(&me.sa4, 0, sizeof(me.sa4)); + me.sa4.sin_family = AF_INET; + me.sa4.sin_addr.s_addr = INADDR_ANY; + me.sa4.sin_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa4)); +#ifdef USE_IPV6 + } + else { + memset(&me.sa6, 0, sizeof(me.sa6)); + me.sa6.sin6_family = AF_INET6; + me.sa6.sin6_addr = in6addr_any; + me.sa6.sin6_port = htons(port); + rc = bind(sock, &me.sa, sizeof(me.sa6)); + } +#endif /* USE_IPV6 */ + if(0 != rc) { + error = SOCKERRNO; + logmsg("Error binding socket on port %hu: (%d) %s", port, error, + sstrerror(error)); + result = 1; + goto tftpd_cleanup; + } + + if(!port) { + /* The system was supposed to choose a port number, figure out which + port we actually got and update the listener port value with it. */ + curl_socklen_t la_size; + srvr_sockaddr_union_t localaddr; +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + la_size = sizeof(localaddr.sa4); +#ifdef USE_IPV6 + else + la_size = sizeof(localaddr.sa6); +#endif + memset(&localaddr.sa, 0, (size_t)la_size); + if(getsockname(sock, &localaddr.sa, &la_size) < 0) { + error = SOCKERRNO; + logmsg("getsockname() failed with error: (%d) %s", + error, sstrerror(error)); + sclose(sock); + goto tftpd_cleanup; + } + switch(localaddr.sa.sa_family) { + case AF_INET: + port = ntohs(localaddr.sa4.sin_port); + break; +#ifdef USE_IPV6 + case AF_INET6: + port = ntohs(localaddr.sa6.sin6_port); + break; +#endif + default: + break; + } + if(!port) { + /* Real failure, listener port shall not be zero beyond this point. */ + logmsg("Apparently getsockname() succeeded, with listener port zero."); + logmsg("A valid reason for this failure is a binary built without"); + logmsg("proper network library linkage. This might not be the only"); + logmsg("reason, but double check it before anything else."); + result = 2; + goto tftpd_cleanup; + } + } + + wrotepidfile = write_pidfile(pidname); + if(!wrotepidfile) { + result = 1; + goto tftpd_cleanup; + } + + if(portname) { + wroteportfile = write_portfile(portname, port); + if(!wroteportfile) { + result = 1; + goto tftpd_cleanup; + } + } + + logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port); + + for(;;) { + fromlen = sizeof(from); +#ifdef USE_IPV6 + if(!use_ipv6) +#endif + fromlen = sizeof(from.sa4); +#ifdef USE_IPV6 + else + fromlen = sizeof(from.sa6); +#endif + n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0, + &from.sa, &fromlen); + if(got_exit_signal) + break; + if(n < 0) { + logmsg("recvfrom"); + result = 3; + break; + } + + set_advisor_read_lock(loglockfile); + serverlogslocked = 1; + +#ifdef USE_IPV6 + if(!use_ipv6) { +#endif + from.sa4.sin_family = AF_INET; + peer = socket(AF_INET, SOCK_DGRAM, 0); + if(CURL_SOCKET_BAD == peer) { + logmsg("socket"); + result = 2; + break; + } + if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) { + logmsg("connect: fail"); + result = 1; + break; + } +#ifdef USE_IPV6 + } + else { + from.sa6.sin6_family = AF_INET6; + peer = socket(AF_INET6, SOCK_DGRAM, 0); + if(CURL_SOCKET_BAD == peer) { + logmsg("socket"); + result = 2; + break; + } + if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) { + logmsg("connect: fail"); + result = 1; + break; + } + } +#endif + + maxtimeout = 5*TIMEOUT; + + tp = &buf.hdr; + tp->th_opcode = ntohs(tp->th_opcode); + if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) { + memset(&test, 0, sizeof(test)); + if(do_tftp(&test, tp, n) < 0) + break; + free(test.buffer); + } + sclose(peer); + peer = CURL_SOCKET_BAD; + + if(got_exit_signal) + break; + + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + + logmsg("end of one transfer"); + + } + +tftpd_cleanup: + + if(test.ofile > 0) + close(test.ofile); + + if((peer != sock) && (peer != CURL_SOCKET_BAD)) + sclose(peer); + + if(sock != CURL_SOCKET_BAD) + sclose(sock); + + if(got_exit_signal) + logmsg("signalled to die"); + + if(wrotepidfile) + unlink(pidname); + if(wroteportfile) + unlink(portname); + + if(serverlogslocked) { + serverlogslocked = 0; + clear_advisor_read_lock(loglockfile); + } + + restore_signal_handlers(true); + + if(got_exit_signal) { + logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)", + ipv_inuse, (int)port, (long)Curl_getpid(), exit_signal); + /* + * To properly set the return status of the process we + * must raise the same signal SIGINT or SIGTERM that we + * caught and let the old handler take care of it. + */ + raise(exit_signal); + } + + logmsg("========> tftpd quits"); + return result; +} + +/* + * Handle initial connection protocol. + */ +static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size) +{ + char *cp; + int first = 1, ecode; + const struct formats *pf; + char *filename, *mode = NULL; +#ifdef USE_WINSOCK + DWORD recvtimeout, recvtimeoutbak; +#endif + const char *option = "mode"; /* mode is implicit */ + int toggle = 1; + FILE *server; + char dumpfile[256]; + + msnprintf(dumpfile, sizeof(dumpfile), "%s/%s", logdir, REQUEST_DUMP); + + /* Open request dump file. */ + server = fopen(dumpfile, "ab"); + if(!server) { + int error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Error opening file: %s", dumpfile); + return -1; + } + + /* store input protocol */ + fprintf(server, "opcode = %x\n", tp->th_opcode); + + cp = (char *)&tp->th_stuff; + filename = cp; + do { + bool endofit = true; + while(cp < &buf.storage[size]) { + if(*cp == '\0') { + endofit = false; + break; + } + cp++; + } + if(endofit) + /* no more options */ + break; + + /* before increasing pointer, make sure it is still within the legal + space */ + if((cp + 1) < &buf.storage[size]) { + ++cp; + if(first) { + /* store the mode since we need it later */ + mode = cp; + first = 0; + } + if(toggle) + /* name/value pair: */ + fprintf(server, "%s = %s\n", option, cp); + else { + /* store the name pointer */ + option = cp; + } + toggle ^= 1; + } + else + /* No more options */ + break; + } while(1); + + if(*cp) { + nak(EBADOP); + fclose(server); + return 3; + } + + /* store input protocol */ + fprintf(server, "filename = %s\n", filename); + + for(cp = mode; cp && *cp; cp++) + if(ISUPPER(*cp)) + *cp = (char)tolower((int)*cp); + + /* store input protocol */ + fclose(server); + + for(pf = formata; pf->f_mode; pf++) + if(strcmp(pf->f_mode, mode) == 0) + break; + if(!pf->f_mode) { + nak(EBADOP); + return 2; + } + ecode = validate_access(test, filename, tp->th_opcode); + if(ecode) { + nak(ecode); + return 1; + } + +#ifdef USE_WINSOCK + recvtimeout = sizeof(recvtimeoutbak); + getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, + (char *)&recvtimeoutbak, (int *)&recvtimeout); + recvtimeout = TIMEOUT*1000; + setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, + (const char *)&recvtimeout, sizeof(recvtimeout)); +#endif + + if(tp->th_opcode == opcode_WRQ) + recvtftp(test, pf); + else + sendtftp(test, pf); + +#ifdef USE_WINSOCK + recvtimeout = recvtimeoutbak; + setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, + (const char *)&recvtimeout, sizeof(recvtimeout)); +#endif + + return 0; +} + +/* Based on the testno, parse the correct server commands. */ +static int parse_servercmd(struct testcase *req) +{ + FILE *stream; + int error; + + stream = test2fopen(req->testno, logdir); + if(!stream) { + error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg(" Couldn't open test file %ld", req->testno); + return 1; /* done */ + } + else { + char *orgcmd = NULL; + char *cmd = NULL; + size_t cmdsize = 0; + int num = 0; + + /* get the custom server control "commands" */ + error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + return 1; /* done */ + } + + cmd = orgcmd; + while(cmd && cmdsize) { + char *check; + if(1 == sscanf(cmd, "writedelay: %d", &num)) { + logmsg("instructed to delay %d secs between packets", num); + req->writedelay = num; + } + else { + logmsg("Unknown instruction found: %s", cmd); + } + /* try to deal with CRLF or just LF */ + check = strchr(cmd, '\r'); + if(!check) + check = strchr(cmd, '\n'); + + if(check) { + /* get to the letter following the newline */ + while((*check == '\r') || (*check == '\n')) + check++; + + if(!*check) + /* if we reached a zero, get out */ + break; + cmd = check; + } + else + break; + } + free(orgcmd); + } + + return 0; /* OK! */ +} + + +/* + * Validate file access. + */ +static int validate_access(struct testcase *test, + const char *filename, unsigned short mode) +{ + char *ptr; + + logmsg("trying to get file: %s mode %x", filename, mode); + + if(!strncmp("verifiedserver", filename, 14)) { + char weare[128]; + size_t count = msnprintf(weare, sizeof(weare), "WE ROOLZ: %" + CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); + + logmsg("Are-we-friendly question received"); + test->buffer = strdup(weare); + test->rptr = test->buffer; /* set read pointer */ + test->bufsize = count; /* set total count */ + test->rcount = count; /* set data left to read */ + return 0; /* fine */ + } + + /* find the last slash */ + ptr = strrchr(filename, '/'); + + if(ptr) { + char partbuf[80]="data"; + long partno; + long testno; + FILE *stream; + + ptr++; /* skip the slash */ + + /* skip all non-numericals following the slash */ + while(*ptr && !ISDIGIT(*ptr)) + ptr++; + + /* get the number */ + testno = strtol(ptr, &ptr, 10); + + if(testno > 10000) { + partno = testno % 10000; + testno /= 10000; + } + else + partno = 0; + + + logmsg("requested test number %ld part %ld", testno, partno); + + test->testno = testno; + + (void)parse_servercmd(test); + + stream = test2fopen(testno, logdir); + + if(0 != partno) + msnprintf(partbuf, sizeof(partbuf), "data%ld", partno); + + if(!stream) { + int error = errno; + logmsg("fopen() failed with error: %d %s", error, strerror(error)); + logmsg("Couldn't open test file for test: %ld", testno); + return EACCESS; + } + else { + size_t count; + int error = getpart(&test->buffer, &count, "reply", partbuf, stream); + fclose(stream); + if(error) { + logmsg("getpart() failed with error: %d", error); + return EACCESS; + } + if(test->buffer) { + test->rptr = test->buffer; /* set read pointer */ + test->bufsize = count; /* set total count */ + test->rcount = count; /* set data left to read */ + } + else + return EACCESS; + } + } + else { + logmsg("no slash found in path"); + return EACCESS; /* failure */ + } + + logmsg("file opened and all is good"); + return 0; +} + +/* + * Send the requested file. + */ +static void sendtftp(struct testcase *test, const struct formats *pf) +{ + int size; + ssize_t n; + /* These are volatile to live through a siglongjmp */ + volatile unsigned short sendblock; /* block count */ + struct tftphdr * volatile sdp = r_init(); /* data buffer */ + struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */ + + sendblock = 1; +#if defined(HAVE_ALARM) && defined(SIGALRM) + mysignal(SIGALRM, timer); +#endif + do { + size = readit(test, (struct tftphdr **)&sdp, pf->f_convert); + if(size < 0) { + nak(errno + 100); + return; + } + sdp->th_opcode = htons(opcode_DATA); + sdp->th_block = htons(sendblock); + timeout = 0; +#ifdef HAVE_SIGSETJMP + (void) sigsetjmp(timeoutbuf, 1); +#endif + if(test->writedelay) { + logmsg("Pausing %d seconds before %d bytes", test->writedelay, + size); + wait_ms(1000*test->writedelay); + } + +send_data: + logmsg("write"); + if(swrite(peer, sdp, size + 4) != size + 4) { + logmsg("write: fail"); + return; + } + read_ahead(test, pf->f_convert); + for(;;) { +#ifdef HAVE_ALARM + alarm(rexmtval); /* read the ack */ +#endif + logmsg("read"); + n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage)); + logmsg("read: %zd", n); +#ifdef HAVE_ALARM + alarm(0); +#endif + if(got_exit_signal) + return; + if(n < 0) { + logmsg("read: fail"); + return; + } + sap->th_opcode = ntohs(sap->th_opcode); + sap->th_block = ntohs(sap->th_block); + + if(sap->th_opcode == opcode_ERROR) { + logmsg("got ERROR"); + return; + } + + if(sap->th_opcode == opcode_ACK) { + if(sap->th_block == sendblock) { + break; + } + /* Re-synchronize with the other side */ + (void) synchnet(peer); + if(sap->th_block == (sendblock-1)) { + goto send_data; + } + } + + } + sendblock++; + } while(size == SEGSIZE); +} + +/* + * Receive a file. + */ +static void recvtftp(struct testcase *test, const struct formats *pf) +{ + ssize_t n, size; + /* These are volatile to live through a siglongjmp */ + volatile unsigned short recvblock; /* block count */ + struct tftphdr * volatile rdp; /* data buffer */ + struct tftphdr *rap; /* ack buffer */ + + recvblock = 0; + rdp = w_init(); +#if defined(HAVE_ALARM) && defined(SIGALRM) + mysignal(SIGALRM, timer); +#endif + rap = &ackbuf.hdr; + do { + timeout = 0; + rap->th_opcode = htons(opcode_ACK); + rap->th_block = htons(recvblock); + recvblock++; +#ifdef HAVE_SIGSETJMP + (void) sigsetjmp(timeoutbuf, 1); +#endif +send_ack: + logmsg("write"); + if(swrite(peer, &ackbuf.storage[0], 4) != 4) { + logmsg("write: fail"); + goto abort; + } + write_behind(test, pf->f_convert); + for(;;) { +#ifdef HAVE_ALARM + alarm(rexmtval); +#endif + logmsg("read"); + n = sread(peer, rdp, PKTSIZE); + logmsg("read: %zd", n); +#ifdef HAVE_ALARM + alarm(0); +#endif + if(got_exit_signal) + goto abort; + if(n < 0) { /* really? */ + logmsg("read: fail"); + goto abort; + } + rdp->th_opcode = ntohs(rdp->th_opcode); + rdp->th_block = ntohs(rdp->th_block); + if(rdp->th_opcode == opcode_ERROR) + goto abort; + if(rdp->th_opcode == opcode_DATA) { + if(rdp->th_block == recvblock) { + break; /* normal */ + } + /* Re-synchronize with the other side */ + (void) synchnet(peer); + if(rdp->th_block == (recvblock-1)) + goto send_ack; /* rexmit */ + } + } + + size = writeit(test, &rdp, (int)(n - 4), pf->f_convert); + if(size != (n-4)) { /* ahem */ + if(size < 0) + nak(errno + 100); + else + nak(ENOSPACE); + goto abort; + } + } while(size == SEGSIZE); + write_behind(test, pf->f_convert); + /* close the output file as early as possible after upload completion */ + if(test->ofile > 0) { + close(test->ofile); + test->ofile = 0; + } + + rap->th_opcode = htons(opcode_ACK); /* send the "final" ack */ + rap->th_block = htons(recvblock); + (void) swrite(peer, &ackbuf.storage[0], 4); +#if defined(HAVE_ALARM) && defined(SIGALRM) + mysignal(SIGALRM, justtimeout); /* just abort read on timeout */ + alarm(rexmtval); +#endif + /* normally times out and quits */ + n = sread(peer, &buf.storage[0], sizeof(buf.storage)); +#ifdef HAVE_ALARM + alarm(0); +#endif + if(got_exit_signal) + goto abort; + if(n >= 4 && /* if read some data */ + rdp->th_opcode == opcode_DATA && /* and got a data block */ + recvblock == rdp->th_block) { /* then my last ack was lost */ + (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */ + } +abort: + /* make sure the output file is closed in case of abort */ + if(test->ofile > 0) { + close(test->ofile); + test->ofile = 0; + } + return; +} + +/* + * Send a nak packet (error message). Error code passed in is one of the + * standard TFTP codes, or a Unix errno offset by 100. + */ +static void nak(int error) +{ + struct tftphdr *tp; + int length; + struct errmsg *pe; + + tp = &buf.hdr; + tp->th_opcode = htons(opcode_ERROR); + tp->th_code = htons((unsigned short)error); + for(pe = errmsgs; pe->e_code >= 0; pe++) + if(pe->e_code == error) + break; + if(pe->e_code < 0) { + pe->e_msg = strerror(error - 100); + tp->th_code = EUNDEF; /* set 'undef' errorcode */ + } + length = (int)strlen(pe->e_msg); + + /* we use memcpy() instead of strcpy() in order to avoid buffer overflow + * report from glibc with FORTIFY_SOURCE */ + memcpy(tp->th_msg, pe->e_msg, length + 1); + length += 5; + if(swrite(peer, &buf.storage[0], length) != length) + logmsg("nak: fail\n"); +} diff --git a/local-test-curl-delta-01/afc-curl/tests/server/util.c b/local-test-curl-delta-01/afc-curl/tests/server/util.c new file mode 100644 index 0000000000000000000000000000000000000000..287ca3000ac5630fb81ef19a34f2acdd59d07527 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/util.c @@ -0,0 +1,899 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "server_setup.h" + +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef _XOPEN_SOURCE_EXTENDED +/* This define is "almost" required to build on HP-UX 11 */ +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_POLL_H +#include +#elif defined(HAVE_SYS_POLL_H) +#include +#endif + +#include "curlx.h" /* from the private lib dir */ +#include "getpart.h" +#include "util.h" +#include "timeval.h" + +#ifdef USE_WINSOCK +#undef EINTR +#define EINTR 4 /* errno.h value */ +#undef EINVAL +#define EINVAL 22 /* errno.h value */ +#endif + +static struct timeval tvnow(void); + +/* This function returns a pointer to STATIC memory. It converts the given + * binary lump to a hex formatted string usable for output in logs or + * whatever. + */ +char *data_to_hex(char *data, size_t len) +{ + static char buf[256*3]; + size_t i; + char *optr = buf; + char *iptr = data; + + if(len > 255) + len = 255; + + for(i = 0; i < len; i++) { + if((data[i] >= 0x20) && (data[i] < 0x7f)) + *optr++ = *iptr++; + else { + msnprintf(optr, 4, "%%%02x", *iptr++); + optr += 3; + } + } + *optr = 0; /* in case no sprintf was used */ + + return buf; +} + +void logmsg(const char *msg, ...) +{ + va_list ap; + char buffer[2048 + 1]; + FILE *logfp; + struct timeval tv; + time_t sec; + struct tm *now; + char timebuf[20]; + static time_t epoch_offset; + static int known_offset; + + if(!serverlogfile) { + fprintf(stderr, "Error: serverlogfile not set\n"); + return; + } + + tv = tvnow(); + if(!known_offset) { + epoch_offset = time(NULL) - tv.tv_sec; + known_offset = 1; + } + sec = epoch_offset + tv.tv_sec; + /* !checksrc! disable BANNEDFUNC 1 */ + now = localtime(&sec); /* not thread safe but we don't care */ + + msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld", + (int)now->tm_hour, (int)now->tm_min, (int)now->tm_sec, + (long)tv.tv_usec); + + va_start(ap, msg); + mvsnprintf(buffer, sizeof(buffer), msg, ap); + va_end(ap); + + do { + logfp = fopen(serverlogfile, "ab"); + } while(!logfp && (errno == EINTR)); + if(logfp) { + fprintf(logfp, "%s %s\n", timebuf, buffer); + fclose(logfp); + } + else { + int error = errno; + fprintf(stderr, "fopen() failed with error: %d %s\n", + error, strerror(error)); + fprintf(stderr, "Error opening file: %s\n", serverlogfile); + fprintf(stderr, "Msg not logged: %s %s\n", timebuf, buffer); + } +} + +#ifdef _WIN32 +/* use instead of strerror() on generic Windows */ +static const char *win32_strerror(int err, char *buf, size_t buflen) +{ + if(!FormatMessageA((FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS), NULL, (DWORD)err, + LANG_NEUTRAL, buf, (DWORD)buflen, NULL)) + msnprintf(buf, buflen, "Unknown error %d (%#x)", err, err); + return buf; +} + +/* use instead of perror() on generic Windows */ +void win32_perror(const char *msg) +{ + char buf[512]; + int err = SOCKERRNO; + win32_strerror(err, buf, sizeof(buf)); + if(msg) + fprintf(stderr, "%s: ", msg); + fprintf(stderr, "%s\n", buf); +} + +void win32_init(void) +{ +#ifdef USE_WINSOCK + WORD wVersionRequested; + WSADATA wsaData; + int err; + + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + + if(err) { + perror("Winsock init failed"); + logmsg("Error initialising Winsock -- aborting"); + exit(1); + } + + if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) || + HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) { + WSACleanup(); + perror("Winsock init failed"); + logmsg("No suitable winsock.dll found -- aborting"); + exit(1); + } +#endif /* USE_WINSOCK */ +} + +void win32_cleanup(void) +{ +#ifdef USE_WINSOCK + WSACleanup(); +#endif /* USE_WINSOCK */ + + /* flush buffers of all streams regardless of their mode */ + _flushall(); +} + +/* socket-safe strerror (works on Winsock errors, too */ +const char *sstrerror(int err) +{ + static char buf[512]; + return win32_strerror(err, buf, sizeof(buf)); +} +#endif /* _WIN32 */ + +/* set by the main code to point to where the test dir is */ +const char *path = "."; + +FILE *test2fopen(long testno, const char *logdir) +{ + FILE *stream; + char filename[256]; + /* first try the alternative, preprocessed, file */ + msnprintf(filename, sizeof(filename), ALTTEST_DATA_PATH, logdir, testno); + stream = fopen(filename, "rb"); + if(stream) + return stream; + + /* then try the source version */ + msnprintf(filename, sizeof(filename), TEST_DATA_PATH, path, testno); + stream = fopen(filename, "rb"); + + return stream; +} + +/* + * Portable function used for waiting a specific amount of ms. + * Waiting indefinitely with this function is not allowed, a + * zero or negative timeout value will return immediately. + * + * Return values: + * -1 = system call error, or invalid timeout value + * 0 = specified timeout has elapsed + */ +int wait_ms(int timeout_ms) +{ +#if !defined(MSDOS) && !defined(USE_WINSOCK) +#ifndef HAVE_POLL + struct timeval pending_tv; +#endif + struct timeval initial_tv; + int pending_ms; +#endif + int r = 0; + + if(!timeout_ms) + return 0; + if(timeout_ms < 0) { + errno = EINVAL; + return -1; + } +#if defined(MSDOS) + delay(timeout_ms); +#elif defined(USE_WINSOCK) + Sleep((DWORD)timeout_ms); +#else + pending_ms = timeout_ms; + initial_tv = tvnow(); + do { + int error; +#ifdef HAVE_POLL + r = poll(NULL, 0, pending_ms); +#else + pending_tv.tv_sec = pending_ms / 1000; + pending_tv.tv_usec = (pending_ms % 1000) * 1000; + r = select(0, NULL, NULL, NULL, &pending_tv); +#endif /* HAVE_POLL */ + if(r != -1) + break; + error = errno; + if(error && (error != EINTR)) + break; + pending_ms = timeout_ms - (int)timediff(tvnow(), initial_tv); + if(pending_ms <= 0) + break; + } while(r == -1); +#endif /* USE_WINSOCK */ + if(r) + r = -1; + return r; +} + +curl_off_t our_getpid(void) +{ + curl_off_t pid; + + pid = (curl_off_t)Curl_getpid(); +#if defined(_WIN32) + /* store pid + 65536 to avoid conflict with Cygwin/msys PIDs, see also: + * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵ + * h=b5e1003722cb14235c4f166be72c09acdffc62ea + * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵ + * h=448cf5aa4b429d5a9cebf92a0da4ab4b5b6d23fe + */ + pid += 65536; +#endif + return pid; +} + +int write_pidfile(const char *filename) +{ + FILE *pidfile; + curl_off_t pid; + + pid = our_getpid(); + pidfile = fopen(filename, "wb"); + if(!pidfile) { + logmsg("Couldn't write pid file: %s %s", filename, strerror(errno)); + return 0; /* fail */ + } + fprintf(pidfile, "%" CURL_FORMAT_CURL_OFF_T "\n", pid); + fclose(pidfile); + logmsg("Wrote pid %" CURL_FORMAT_CURL_OFF_T " to %s", pid, filename); + return 1; /* success */ +} + +/* store the used port number in a file */ +int write_portfile(const char *filename, int port) +{ + FILE *portfile = fopen(filename, "wb"); + if(!portfile) { + logmsg("Couldn't write port file: %s %s", filename, strerror(errno)); + return 0; /* fail */ + } + fprintf(portfile, "%d\n", port); + fclose(portfile); + logmsg("Wrote port %d to %s", port, filename); + return 1; /* success */ +} + +void set_advisor_read_lock(const char *filename) +{ + FILE *lockfile; + int error = 0; + int res; + + do { + lockfile = fopen(filename, "wb"); + } while(!lockfile && ((error = errno) == EINTR)); + if(!lockfile) { + logmsg("Error creating lock file %s error: %d %s", + filename, error, strerror(error)); + return; + } + + do { + res = fclose(lockfile); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error closing lock file %s error: %d %s", + filename, error, strerror(error)); +} + +void clear_advisor_read_lock(const char *filename) +{ + int error = 0; + int res; + + /* + ** Log all removal failures. Even those due to file not existing. + ** This allows to detect if unexpectedly the file has already been + ** removed by a process different than the one that should do this. + */ + + do { + res = unlink(filename); + } while(res && ((error = errno) == EINTR)); + if(res) + logmsg("Error removing lock file %s error: %d %s", + filename, error, strerror(error)); +} + + +#if defined(_WIN32) + +static struct timeval tvnow(void) +{ + /* + ** GetTickCount() is available on _all_ Windows versions from W95 up + ** to nowadays. Returns milliseconds elapsed since last system boot, + ** increases monotonically and wraps once 49.7 days have elapsed. + ** + ** GetTickCount64() is available on Windows version from Windows Vista + ** and Windows Server 2008 up to nowadays. The resolution of the + ** function is limited to the resolution of the system timer, which + ** is typically in the range of 10 milliseconds to 16 milliseconds. + */ + struct timeval now; +#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) + ULONGLONG milliseconds = GetTickCount64(); +#else + DWORD milliseconds = GetTickCount(); +#endif + now.tv_sec = (long)(milliseconds / 1000); + now.tv_usec = (long)((milliseconds % 1000) * 1000); + return now; +} + +#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC) + +static struct timeval tvnow(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. + */ + struct timeval now; + struct timespec tsnow; + if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) { + now.tv_sec = tsnow.tv_sec; + now.tv_usec = (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); +#else + else { + now.tv_sec = time(NULL); + now.tv_usec = 0; + } +#endif + return now; +} + +#elif defined(HAVE_GETTIMEOFDAY) + +static struct timeval tvnow(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; + (void)gettimeofday(&now, NULL); + return now; +} + +#else + +static struct timeval tvnow(void) +{ + /* + ** time() returns the value of time in seconds since the Epoch. + */ + struct timeval now; + now.tv_sec = time(NULL); + now.tv_usec = 0; + return now; +} + +#endif + +long timediff(struct timeval newer, struct timeval older) +{ + timediff_t diff = newer.tv_sec-older.tv_sec; + if(diff >= (LONG_MAX/1000)) + return LONG_MAX; + else if(diff <= (LONG_MIN/1000)) + return LONG_MIN; + return (long)(newer.tv_sec-older.tv_sec)*1000+ + (long)(newer.tv_usec-older.tv_usec)/1000; +} + +/* vars used to keep around previous signal handlers */ + +typedef void (*SIGHANDLER_T)(int); + +#if defined(_MSC_VER) && _MSC_VER == 1600 +/* Workaround for warning C4306: + 'type cast' : conversion from 'int' to 'void (__cdecl *)(int)' */ +#undef SIG_ERR +#define SIG_ERR ((SIGHANDLER_T)(size_t)-1) +#endif + +#ifdef SIGHUP +static SIGHANDLER_T old_sighup_handler = SIG_ERR; +#endif + +#ifdef SIGPIPE +static SIGHANDLER_T old_sigpipe_handler = SIG_ERR; +#endif + +#ifdef SIGALRM +static SIGHANDLER_T old_sigalrm_handler = SIG_ERR; +#endif + +#ifdef SIGINT +static SIGHANDLER_T old_sigint_handler = SIG_ERR; +#endif + +#ifdef SIGTERM +static SIGHANDLER_T old_sigterm_handler = SIG_ERR; +#endif + +#if defined(SIGBREAK) && defined(_WIN32) +static SIGHANDLER_T old_sigbreak_handler = SIG_ERR; +#endif + +#if defined(_WIN32) && !defined(CURL_WINDOWS_UWP) +#ifdef _WIN32_WCE +static DWORD thread_main_id = 0; +#else +static unsigned int thread_main_id = 0; +#endif +static HANDLE thread_main_window = NULL; +static HWND hidden_main_window = NULL; +#endif + +/* var which if set indicates that the program should finish execution */ +volatile int got_exit_signal = 0; + +/* if next is set indicates the first signal handled in exit_signal_handler */ +volatile int exit_signal = 0; + +#ifdef _WIN32 +/* event which if set indicates that the program should finish */ +HANDLE exit_event = NULL; +#endif + +/* signal handler that will be triggered to indicate that the program + * should finish its execution in a controlled manner as soon as possible. + * The first time this is called it will set got_exit_signal to one and + * store in exit_signal the signal that triggered its execution. + */ +static void exit_signal_handler(int signum) +{ + int old_errno = errno; + logmsg("exit_signal_handler: %d", signum); + if(got_exit_signal == 0) { + got_exit_signal = 1; + exit_signal = signum; +#ifdef _WIN32 + if(exit_event) + (void)SetEvent(exit_event); +#endif + } + (void)signal(signum, exit_signal_handler); + errno = old_errno; +} + +#ifdef _WIN32 +/* CTRL event handler for Windows Console applications to simulate + * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler. + * + * Background information from MSDN: + * SIGINT is not supported for any Win32 application. When a CTRL+C + * interrupt occurs, Win32 operating systems generate a new thread + * to specifically handle that interrupt. This can cause a single-thread + * application, such as one in UNIX, to become multithreaded and cause + * unexpected behavior. + * [...] + * The SIGILL and SIGTERM signals are not generated under Windows. + * They are included for ANSI compatibility. Therefore, you can set + * signal handlers for these signals by using signal, and you can also + * explicitly generate these signals by calling raise. Source: + * https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/signal + */ +static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType) +{ + int signum = 0; + logmsg("ctrl_event_handler: %lu", dwCtrlType); + switch(dwCtrlType) { +#ifdef SIGINT + case CTRL_C_EVENT: + signum = SIGINT; + break; +#endif +#ifdef SIGTERM + case CTRL_CLOSE_EVENT: + signum = SIGTERM; + break; +#endif +#ifdef SIGBREAK + case CTRL_BREAK_EVENT: + signum = SIGBREAK; + break; +#endif + default: + return FALSE; + } + if(signum) { + logmsg("ctrl_event_handler: %lu -> %d", dwCtrlType, signum); + raise(signum); + } + return TRUE; +} +#endif + +#if defined(_WIN32) && !defined(CURL_WINDOWS_UWP) +/* Window message handler for Windows applications to add support + * for graceful process termination via taskkill (without /f) which + * sends WM_CLOSE to all Windows of a process (even hidden ones). + * + * Therefore we create and run a hidden Window in a separate thread + * to receive and handle the WM_CLOSE message as SIGTERM signal. + */ +static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg, + WPARAM wParam, LPARAM lParam) +{ + int signum = 0; + if(hwnd == hidden_main_window) { + switch(uMsg) { +#ifdef SIGTERM + case WM_CLOSE: + signum = SIGTERM; + break; +#endif + case WM_DESTROY: + PostQuitMessage(0); + break; + } + if(signum) { + logmsg("main_window_proc: %d -> %d", uMsg, signum); + raise(signum); + } + } + return DefWindowProc(hwnd, uMsg, wParam, lParam); +} +/* Window message queue loop for hidden main window, details see above. + */ +#ifdef _WIN32_WCE +static DWORD WINAPI main_window_loop(LPVOID lpParameter) +#else +#include +static unsigned int WINAPI main_window_loop(void *lpParameter) +#endif +{ + WNDCLASS wc; + BOOL ret; + MSG msg; + + ZeroMemory(&wc, sizeof(wc)); + wc.lpfnWndProc = (WNDPROC)main_window_proc; + wc.hInstance = (HINSTANCE)lpParameter; + wc.lpszClassName = TEXT("MainWClass"); + if(!RegisterClass(&wc)) { + perror("RegisterClass failed"); + return (DWORD)-1; + } + + hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"), + TEXT("Recv WM_CLOSE msg"), + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, + (HWND)NULL, (HMENU)NULL, + wc.hInstance, (LPVOID)NULL); + if(!hidden_main_window) { + perror("CreateWindowEx failed"); + return (DWORD)-1; + } + + do { + ret = GetMessage(&msg, NULL, 0, 0); + if(ret == -1) { + perror("GetMessage failed"); + return (DWORD)-1; + } + else if(ret) { + if(msg.message == WM_APP) { + DestroyWindow(hidden_main_window); + } + else if(msg.hwnd && !TranslateMessage(&msg)) { + DispatchMessage(&msg); + } + } + } while(ret); + + hidden_main_window = NULL; + return (DWORD)msg.wParam; +} +#endif + +static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler, + bool restartable) +{ +#if defined(HAVE_SIGACTION) && defined(SA_RESTART) + struct sigaction sa, oldsa; + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handler; + sigemptyset(&sa.sa_mask); + sigaddset(&sa.sa_mask, signum); + sa.sa_flags = restartable ? SA_RESTART : 0; + + if(sigaction(signum, &sa, &oldsa)) + return SIG_ERR; + + return oldsa.sa_handler; +#else + SIGHANDLER_T oldhdlr = signal(signum, handler); + +#ifdef HAVE_SIGINTERRUPT + if(oldhdlr != SIG_ERR) + siginterrupt(signum, (int) restartable); +#else + (void) restartable; +#endif + + return oldhdlr; +#endif +} + +void install_signal_handlers(bool keep_sigalrm) +{ +#ifdef _WIN32 + /* setup Windows exit event before any signal can trigger */ + exit_event = CreateEvent(NULL, TRUE, FALSE, NULL); + if(!exit_event) + logmsg("cannot create exit event"); +#endif +#ifdef SIGHUP + /* ignore SIGHUP signal */ + old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE); + if(old_sighup_handler == SIG_ERR) + logmsg("cannot install SIGHUP handler: %s", strerror(errno)); +#endif +#ifdef SIGPIPE + /* ignore SIGPIPE signal */ + old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE); + if(old_sigpipe_handler == SIG_ERR) + logmsg("cannot install SIGPIPE handler: %s", strerror(errno)); +#endif +#ifdef SIGALRM + if(!keep_sigalrm) { + /* ignore SIGALRM signal */ + old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE); + if(old_sigalrm_handler == SIG_ERR) + logmsg("cannot install SIGALRM handler: %s", strerror(errno)); + } +#else + (void)keep_sigalrm; +#endif +#ifdef SIGINT + /* handle SIGINT signal with our exit_signal_handler */ + old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE); + if(old_sigint_handler == SIG_ERR) + logmsg("cannot install SIGINT handler: %s", strerror(errno)); +#endif +#ifdef SIGTERM + /* handle SIGTERM signal with our exit_signal_handler */ + old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE); + if(old_sigterm_handler == SIG_ERR) + logmsg("cannot install SIGTERM handler: %s", strerror(errno)); +#endif +#if defined(SIGBREAK) && defined(_WIN32) + /* handle SIGBREAK signal with our exit_signal_handler */ + old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE); + if(old_sigbreak_handler == SIG_ERR) + logmsg("cannot install SIGBREAK handler: %s", strerror(errno)); +#endif +#ifdef _WIN32 + if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE)) + logmsg("cannot install CTRL event handler"); + +#ifndef CURL_WINDOWS_UWP + { +#ifdef _WIN32_WCE + typedef HANDLE curl_win_thread_handle_t; +#else + typedef uintptr_t curl_win_thread_handle_t; +#endif + curl_win_thread_handle_t thread; +#ifdef _WIN32_WCE + thread = CreateThread(NULL, 0, &main_window_loop, + (LPVOID)GetModuleHandle(NULL), 0, &thread_main_id); +#else + thread = _beginthreadex(NULL, 0, &main_window_loop, + (void *)GetModuleHandle(NULL), 0, &thread_main_id); +#endif + thread_main_window = (HANDLE)thread; + if(!thread_main_window || !thread_main_id) + logmsg("cannot start main window loop"); + } +#endif +#endif +} + +void restore_signal_handlers(bool keep_sigalrm) +{ +#ifdef SIGHUP + if(SIG_ERR != old_sighup_handler) + (void) set_signal(SIGHUP, old_sighup_handler, FALSE); +#endif +#ifdef SIGPIPE + if(SIG_ERR != old_sigpipe_handler) + (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE); +#endif +#ifdef SIGALRM + if(!keep_sigalrm) { + if(SIG_ERR != old_sigalrm_handler) + (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE); + } +#else + (void)keep_sigalrm; +#endif +#ifdef SIGINT + if(SIG_ERR != old_sigint_handler) + (void) set_signal(SIGINT, old_sigint_handler, FALSE); +#endif +#ifdef SIGTERM + if(SIG_ERR != old_sigterm_handler) + (void) set_signal(SIGTERM, old_sigterm_handler, FALSE); +#endif +#if defined(SIGBREAK) && defined(_WIN32) + if(SIG_ERR != old_sigbreak_handler) + (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE); +#endif +#ifdef _WIN32 + (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE); +#ifndef CURL_WINDOWS_UWP + if(thread_main_window && thread_main_id) { + if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) { + if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) { + if(CloseHandle(thread_main_window)) { + thread_main_window = NULL; + thread_main_id = 0; + } + } + } + } + if(exit_event) { + if(CloseHandle(exit_event)) { + exit_event = NULL; + } + } +#endif +#endif +} + +#ifdef USE_UNIX_SOCKETS + +int bind_unix_socket(curl_socket_t sock, const char *unix_socket, + struct sockaddr_un *sau) +{ + int error; + int rc; + size_t len = strlen(unix_socket); + + memset(sau, 0, sizeof(struct sockaddr_un)); + sau->sun_family = AF_UNIX; + if(len >= sizeof(sau->sun_path) - 1) { + logmsg("Too long unix socket domain path (%zd)", len); + return -1; + } + strcpy(sau->sun_path, unix_socket); + rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un)); + if(0 != rc && SOCKERRNO == EADDRINUSE) { + struct_stat statbuf; + /* socket already exists. Perhaps it is stale? */ + curl_socket_t unixfd = socket(AF_UNIX, SOCK_STREAM, 0); + if(CURL_SOCKET_BAD == unixfd) { + logmsg("Failed to create socket at %s: (%d) %s", + unix_socket, SOCKERRNO, sstrerror(SOCKERRNO)); + return -1; + } + /* check whether the server is alive */ + rc = connect(unixfd, (struct sockaddr*)sau, sizeof(struct sockaddr_un)); + error = SOCKERRNO; + sclose(unixfd); + if(0 != rc && ECONNREFUSED != error) { + logmsg("Failed to connect to %s: (%d) %s", + unix_socket, error, sstrerror(error)); + return rc; + } + /* socket server is not alive, now check if it was actually a socket. */ +#ifdef _WIN32 + /* Windows does not have lstat function. */ + rc = curlx_win32_stat(unix_socket, &statbuf); +#else + rc = lstat(unix_socket, &statbuf); +#endif + if(0 != rc) { + logmsg("Error binding socket, failed to stat %s: (%d) %s", + unix_socket, errno, strerror(errno)); + return rc; + } +#ifdef S_IFSOCK + if((statbuf.st_mode & S_IFSOCK) != S_IFSOCK) { + logmsg("Error binding socket, failed to stat %s", unix_socket); + return -1; + } +#endif + /* dead socket, cleanup and retry bind */ + rc = unlink(unix_socket); + if(0 != rc) { + logmsg("Error binding socket, failed to unlink %s: (%d) %s", + unix_socket, errno, strerror(errno)); + return rc; + } + /* stale socket is gone, retry bind */ + rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un)); + } + return rc; +} +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/server/util.h b/local-test-curl-delta-01/afc-curl/tests/server/util.h new file mode 100644 index 0000000000000000000000000000000000000000..a91ecf47787a89274d72599bfe1f041e54616451 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/server/util.h @@ -0,0 +1,98 @@ +#ifndef HEADER_CURL_SERVER_UTIL_H +#define HEADER_CURL_SERVER_UTIL_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 "server_setup.h" + +char *data_to_hex(char *data, size_t len); +void logmsg(const char *msg, ...) CURL_PRINTF(1, 2); +long timediff(struct timeval newer, struct timeval older); + +#define TEST_DATA_PATH "%s/data/test%ld" +#define ALTTEST_DATA_PATH "%s/test%ld" +#define SERVERLOGS_LOCKDIR "lock" /* within logdir */ + +/* global variable, where to find the 'data' dir */ +extern const char *path; + +/* global variable, log file name */ +extern const char *serverlogfile; + +extern const char *cmdfile; + +#ifdef _WIN32 +#include +#include + +#define sleep(sec) Sleep ((sec)*1000) + +#undef perror +#define perror(m) win32_perror(m) +void win32_perror(const char *msg); + +void win32_init(void); +void win32_cleanup(void); +const char *sstrerror(int err); +#else /* _WIN32 */ + +#define sstrerror(e) strerror(e) +#endif /* _WIN32 */ + +/* fopens the test case file */ +FILE *test2fopen(long testno, const char *logdir); + +int wait_ms(int timeout_ms); +curl_off_t our_getpid(void); +int write_pidfile(const char *filename); +int write_portfile(const char *filename, int port); +void set_advisor_read_lock(const char *filename); +void clear_advisor_read_lock(const char *filename); + +/* global variable which if set indicates that the program should finish */ +extern volatile int got_exit_signal; + +/* global variable which if set indicates the first signal handled */ +extern volatile int exit_signal; + +#ifdef _WIN32 +/* global event which if set indicates that the program should finish */ +extern HANDLE exit_event; +#endif + +void install_signal_handlers(bool keep_sigalrm); +void restore_signal_handlers(bool keep_sigalrm); + +#ifdef USE_UNIX_SOCKETS + +#include /* for curl_socket_t */ + +#ifdef HAVE_SYS_UN_H +#include /* for sockaddr_un */ +#endif /* HAVE_SYS_UN_H */ + +int bind_unix_socket(curl_socket_t sock, const char *unix_socket, + struct sockaddr_un *sau); +#endif /* USE_UNIX_SOCKETS */ + +#endif /* HEADER_CURL_SERVER_UTIL_H */ diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/.gitignore b/local-test-curl-delta-01/afc-curl/tests/unit/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a91670e0d5a69059daa81f67b4216b29fffd0991 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/.gitignore @@ -0,0 +1,6 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +/unit[0-9][0-9][0-9][0-9] +units.c diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/CMakeLists.txt b/local-test-curl-delta-01/afc-curl/tests/unit/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c599ca33eca8c7503786563b6377bcd854b2f13 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/CMakeLists.txt @@ -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 +# +########################################################################### + +# Get 'UNITPROGS', '*_SOURCES', 'FIRSTFILES' variables +transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") +include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") + +if(CURL_TEST_BUNDLES) + add_custom_command( + OUTPUT "unit_bundle.c" + COMMAND ${PERL_EXECUTABLE} "${PROJECT_SOURCE_DIR}/tests/mk-bundle.pl" "${CMAKE_CURRENT_SOURCE_DIR}" > "unit_bundle.c" + DEPENDS + "${PROJECT_SOURCE_DIR}/tests/mk-bundle.pl" ${FIRSTFILES} + "${CMAKE_CURRENT_SOURCE_DIR}/Makefile.inc" + VERBATIM) + + set(UNITPROGS "units") + set(units_SOURCES "unit_bundle.c") +endif() + +foreach(_target IN LISTS UNITPROGS) + set(_target_name "${_target}") + add_executable(${_target_name} EXCLUDE_FROM_ALL ${${_target}_SOURCES}) + add_dependencies(testdeps ${_target_name}) + target_link_libraries(${_target_name} curltool curlu) + target_include_directories(${_target_name} PRIVATE + "${PROJECT_BINARY_DIR}/lib" # for "curl_config.h" + "${PROJECT_SOURCE_DIR}/lib" # for "curl_setup.h" + "${PROJECT_SOURCE_DIR}/src" + "${PROJECT_SOURCE_DIR}/tests/libtest" + ) + if(CURL_TEST_BUNDLES) + target_include_directories(${_target_name} PRIVATE "${PROJECT_SOURCE_DIR}/tests/unit") + endif() + set_target_properties(${_target_name} PROPERTIES + OUTPUT_NAME "${_target}" + PROJECT_LABEL "Test unit ${_target}") +endforeach() diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.am b/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..811ffac99678b982cafe7addab326abad45b0d64 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.am @@ -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 +# +########################################################################### +AUTOMAKE_OPTIONS = foreign nostdinc + +# 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 "borrowed" files + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib \ + -I$(top_srcdir)/src \ + -I$(top_srcdir)/tests/libtest \ + -I$(top_srcdir)/tests/unit + +EXTRA_DIST = CMakeLists.txt README.md + +CFLAGS += @CURL_CFLAG_EXTRAS@ + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +LDADD = $(top_builddir)/src/libcurltool.la \ + $(top_builddir)/lib/libcurlu.la \ + @LIBCURL_PC_LDFLAGS_PRIVATE@ @LIBCURL_PC_LIBS_PRIVATE@ + +AM_CPPFLAGS += -DCURL_STATICLIB -DUNITTESTS + +if BUILD_UNITTESTS +if USE_TEST_BUNDLES +unit_bundle.c: $(top_srcdir)/tests/mk-bundle.pl + @PERL@ $(top_srcdir)/tests/mk-bundle.pl $(srcdir) > unit_bundle.c + +noinst_PROGRAMS = units +nodist_units_SOURCES = unit_bundle.c +CLEANFILES = unit_bundle.c +else +# Makefile.inc provides neat definitions +include Makefile.inc +noinst_PROGRAMS = $(UNITPROGS) +endif +else +noinst_PROGRAMS = +endif + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)@PERL@ $(top_srcdir)/scripts/checksrc.pl $(srcdir)/*.[ch] diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.inc b/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.inc new file mode 100644 index 0000000000000000000000000000000000000000..d17540bceaff447fbd06f830ebab234250c8959a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/Makefile.inc @@ -0,0 +1,147 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 files are used in every single unit test program + +FIRSTFILES = \ + ../libtest/first.c \ + ../libtest/first.h + +UNITFILES = curlcheck.h $(FIRSTFILES) + +# These are all unit test programs +UNITPROGS = unit1300 unit1302 unit1303 unit1304 unit1305 unit1307 \ + unit1308 unit1309 unit1323 \ + unit1330 unit1394 unit1395 unit1396 unit1397 unit1398 \ + unit1399 \ + unit1600 unit1601 unit1602 unit1603 unit1604 unit1605 unit1606 unit1607 \ + unit1608 unit1609 unit1610 unit1611 unit1612 unit1614 unit1615 unit1616 \ + unit1620 unit1621 \ + unit1650 unit1651 unit1652 unit1653 unit1654 unit1655 unit1656 \ + unit1660 unit1661 unit1663 \ + unit2600 unit2601 unit2602 unit2603 unit2604 \ + unit3200 \ + unit3205 + +unit1300_SOURCES = unit1300.c $(UNITFILES) + +unit1302_SOURCES = unit1302.c $(UNITFILES) + +unit1303_SOURCES = unit1303.c $(UNITFILES) + +unit1304_SOURCES = unit1304.c $(UNITFILES) + +unit1305_SOURCES = unit1305.c $(UNITFILES) + +unit1307_SOURCES = unit1307.c $(UNITFILES) + +unit1308_SOURCES = unit1308.c $(UNITFILES) + +unit1309_SOURCES = unit1309.c $(UNITFILES) + +unit1323_SOURCES = unit1323.c $(UNITFILES) + +unit1330_SOURCES = unit1330.c $(UNITFILES) + +unit1394_SOURCES = unit1394.c $(UNITFILES) + +unit1395_SOURCES = unit1395.c $(UNITFILES) + +unit1396_SOURCES = unit1396.c $(UNITFILES) + +unit1397_SOURCES = unit1397.c $(UNITFILES) + +unit1398_SOURCES = unit1398.c $(UNITFILES) + +unit1399_SOURCES = unit1399.c $(UNITFILES) + +unit1600_SOURCES = unit1600.c $(UNITFILES) + +unit1601_SOURCES = unit1601.c $(UNITFILES) + +unit1602_SOURCES = unit1602.c $(UNITFILES) + +unit1603_SOURCES = unit1603.c $(UNITFILES) + +unit1604_SOURCES = unit1604.c $(UNITFILES) + +unit1605_SOURCES = unit1605.c $(UNITFILES) + +unit1606_SOURCES = unit1606.c $(UNITFILES) + +unit1607_SOURCES = unit1607.c $(UNITFILES) + +unit1608_SOURCES = unit1608.c $(UNITFILES) + +unit1609_SOURCES = unit1609.c $(UNITFILES) + +unit1610_SOURCES = unit1610.c $(UNITFILES) + +unit1611_SOURCES = unit1611.c $(UNITFILES) + +unit1612_SOURCES = unit1612.c $(UNITFILES) + +unit1614_SOURCES = unit1614.c $(UNITFILES) + +unit1615_SOURCES = unit1615.c $(UNITFILES) + +unit1616_SOURCES = unit1616.c $(UNITFILES) + +unit1620_SOURCES = unit1620.c $(UNITFILES) + +unit1621_SOURCES = unit1621.c $(UNITFILES) + +unit1650_SOURCES = unit1650.c $(UNITFILES) + +unit1651_SOURCES = unit1651.c $(UNITFILES) + +unit1652_SOURCES = unit1652.c $(UNITFILES) + +unit1653_SOURCES = unit1653.c $(UNITFILES) + +unit1654_SOURCES = unit1654.c $(UNITFILES) + +unit1655_SOURCES = unit1655.c $(UNITFILES) + +unit1656_SOURCES = unit1656.c $(UNITFILES) + +unit1660_SOURCES = unit1660.c $(UNITFILES) + +unit1661_SOURCES = unit1661.c $(UNITFILES) + +unit1663_SOURCES = unit1663.c $(UNITFILES) + +unit2600_SOURCES = unit2600.c $(UNITFILES) + +unit2601_SOURCES = unit2601.c $(UNITFILES) + +unit2602_SOURCES = unit2602.c $(UNITFILES) + +unit2603_SOURCES = unit2603.c $(UNITFILES) + +unit2604_SOURCES = unit2604.c $(UNITFILES) + +unit3200_SOURCES = unit3200.c $(UNITFILES) + +unit3205_SOURCES = unit3205.c $(UNITFILES) diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/README.md b/local-test-curl-delta-01/afc-curl/tests/unit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..38462902dbc63d679db69bfc67b2152e285b68d3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/README.md @@ -0,0 +1,73 @@ + + +# Unit tests + +The goal is to add tests for *all* functions in libcurl. If functions are too +big and complicated, we should split them into smaller and testable ones. + +## Build Unit Tests + +`./configure --enable-debug` is required for the unit tests to build. To +enable unit tests, there will be a separate static libcurl built that will be +used exclusively for linking unit test programs. Just build everything as +normal, and then you can run the unit test cases as well. + +## Run Unit Tests + +Unit tests are run as part of the regular test suite. If you have built +everything to run unit tests, to can do 'make test' at the root level. Or you +can `cd tests` and `make` and then invoke individual unit tests with +`./runtests.pl NNNN` where `NNNN` is the specific test number. + +## Debug Unit Tests + +If a specific test fails you will get told. The test case then has output left +in the %LOGDIR subdirectory, but most importantly you can re-run the test again +using gdb by doing `./runtests.pl -g NNNN`. That is, add a `-g` to make it +start up gdb and run the same case using that. + +## Write Unit Tests + +We put tests that focus on an area or a specific function into a single C +source file. The source file should be named `unitNNNN.c` where `NNNN` is a +previously unused number. + +Add your test to `tests/unit/Makefile.inc` (if it is a unit test). Add your +test data file name to `tests/data/Makefile.am` + +You also need a separate file called `tests/data/testNNNN` (using the same +number) that describes your test case. See the test1300 file for inspiration +and the `tests/FILEFORMAT.md` documentation. + +For the actual C file, here's a simple example: +~~~c + + #include "curlcheck.h" + + #include "a libcurl header.h" /* from the lib dir */ + + static CURLcode unit_setup( void ) + { + /* whatever you want done first */ + return CURLE_OK; + } + + static void unit_stop( void ) + { + /* done before shutting down and exiting */ + } + + UNITTEST_START + + /* here you start doing things and checking that the results are good */ + + fail_unless( size == 0 , "initial size should be zero" ); + fail_if( head == NULL , "head should not be initiated to NULL" ); + + /* you end the test code like this: */ + + UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/curlcheck.h b/local-test-curl-delta-01/afc-curl/tests/unit/curlcheck.h new file mode 100644 index 0000000000000000000000000000000000000000..c0faf5069b28285c1e679421ccb972a66dd95687 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/curlcheck.h @@ -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 + * + ***************************************************************************/ +#include "test.h" + +/* The fail macros mark the current test step as failed, and continue */ +#define fail_if(expr, msg) \ + do { \ + if(expr) { \ + fprintf(stderr, "%s:%d FAILED Assertion '%s' met: %s\n", \ + __FILE__, __LINE__, #expr, msg); \ + unitfail++; \ + } \ + } while(0) + +#define fail_unless(expr, msg) \ + do { \ + if(!(expr)) { \ + fprintf(stderr, "%s:%d Assertion '%s' FAILED: %s\n", \ + __FILE__, __LINE__, #expr, msg); \ + unitfail++; \ + } \ + } while(0) + +#define verify_memory(dynamic, check, len) \ + do { \ + if(dynamic && memcmp(dynamic, check, len)) { \ + fprintf(stderr, "%s:%d Memory buffer FAILED match size %d. " \ + "'%s' is not\n", __FILE__, __LINE__, len, \ + hexdump((const unsigned char *)check, len)); \ + fprintf(stderr, "%s:%d the same as '%s'\n", __FILE__, __LINE__, \ + hexdump((const unsigned char *)dynamic, len)); \ + unitfail++; \ + } \ + } while(0) + +/* fail() is for when the test case figured out by itself that a check + proved a failure */ +#define fail(msg) do { \ + fprintf(stderr, "%s:%d test FAILED: '%s'\n", \ + __FILE__, __LINE__, msg); \ + unitfail++; \ + } while(0) + + +/* The abort macros mark the current test step as failed, and exit the test */ +#define abort_if(expr, msg) \ + do { \ + if(expr) { \ + fprintf(stderr, "%s:%d ABORT assertion '%s' met: %s\n", \ + __FILE__, __LINE__, #expr, msg); \ + unitfail++; \ + goto unit_test_abort; \ + } \ + } while(0) + +#define abort_unless(expr, msg) \ + do { \ + if(!(expr)) { \ + fprintf(stderr, "%s:%d ABORT assertion '%s' failed: %s\n", \ + __FILE__, __LINE__, #expr, msg); \ + unitfail++; \ + goto unit_test_abort; \ + } \ + } while(0) + +#define abort_test(msg) \ + do { \ + fprintf(stderr, "%s:%d test ABORTED: '%s'\n", \ + __FILE__, __LINE__, msg); \ + unitfail++; \ + goto unit_test_abort; \ + } while(0) + + +#define UNITTEST_START \ + CURLcode test(char *arg) \ + { \ + (void)arg; \ + if(unit_setup()) { \ + fail("unit_setup() FAILURE"); \ + } \ + else { + +#define UNITTEST_STOP \ + goto unit_test_abort; /* avoid warning */ \ +unit_test_abort: \ + unit_stop(); \ + } \ + return (CURLcode)unitfail; \ + } diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1300.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1300.c new file mode 100644 index 0000000000000000000000000000000000000000..60a0a0e1b8cd9eebf716f0dd3a44852e50d44479 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1300.c @@ -0,0 +1,275 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "llist.h" + +static struct Curl_llist llist; + +static struct Curl_llist llist_destination; + +static void test_Curl_llist_dtor(void *key, void *value) +{ + /* used by the llist API, does nothing here */ + (void)key; + (void)value; +} + +static CURLcode unit_setup(void) +{ + Curl_llist_init(&llist, test_Curl_llist_dtor); + Curl_llist_init(&llist_destination, test_Curl_llist_dtor); + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +UNITTEST_START +{ + int unusedData_case1 = 1; + int unusedData_case2 = 2; + int unusedData_case3 = 3; + struct Curl_llist_node case1_list; + struct Curl_llist_node case2_list; + struct Curl_llist_node case3_list; + struct Curl_llist_node case4_list; + struct Curl_llist_node *head; + struct Curl_llist_node *element_next; + struct Curl_llist_node *element_prev; + struct Curl_llist_node *to_remove; + size_t llist_size = Curl_llist_count(&llist); + + /** + * testing llist_init + * case 1: + * list initiation + * @assumptions: + * 1: list size will be 0 + * 2: list head will be NULL + * 3: list tail will be NULL + * 4: list dtor will be NULL + */ + + fail_unless(Curl_llist_count(&llist) == 0, + "list initial size should be zero"); + fail_unless(Curl_llist_head(&llist) == NULL, + "list head should initiate to NULL"); + fail_unless(Curl_llist_tail(&llist) == NULL, + "list tail should initiate to NULL"); + + /** + * testing Curl_llist_insert_next + * case 1: + * list is empty + * @assumptions: + * 1: list size will be 1 + * 2: list head will hold the data "unusedData_case1" + * 3: list tail will be the same as list head + */ + + Curl_llist_insert_next(&llist, Curl_llist_head(&llist), &unusedData_case1, + &case1_list); + + fail_unless(Curl_llist_count(&llist) == 1, + "List size should be 1 after adding a new element"); + /* test that the list head data holds my unusedData */ + fail_unless(Curl_node_elem(Curl_llist_head(&llist)) == &unusedData_case1, + "head ptr should be first entry"); + /* same goes for the list tail */ + fail_unless(Curl_llist_tail(&llist) == Curl_llist_head(&llist), + "tail and head should be the same"); + + /** + * testing Curl_llist_insert_next + * case 2: + * list has 1 element, adding one element after the head + * @assumptions: + * 1: the element next to head should be our newly created element + * 2: the list tail should be our newly created element + */ + + Curl_llist_insert_next(&llist, Curl_llist_head(&llist), + &unusedData_case3, &case3_list); + fail_unless(Curl_node_elem(Curl_node_next(Curl_llist_head(&llist))) == + &unusedData_case3, + "the node next to head is not getting set correctly"); + fail_unless(Curl_node_elem(Curl_llist_tail(&llist)) == &unusedData_case3, + "the list tail is not getting set correctly"); + + /** + * testing Curl_llist_insert_next + * case 3: + * list has >1 element, adding one element after "NULL" + * @assumptions: + * 1: the element next to head should be our newly created element + * 2: the list tail should different from newly created element + */ + + Curl_llist_insert_next(&llist, Curl_llist_head(&llist), + &unusedData_case2, &case2_list); + fail_unless(Curl_node_elem(Curl_node_next(Curl_llist_head(&llist))) == + &unusedData_case2, + "the node next to head is not getting set correctly"); + /* better safe than sorry, check that the tail isn't corrupted */ + fail_unless(Curl_node_elem(Curl_llist_tail(&llist)) != &unusedData_case2, + "the list tail is not getting set correctly"); + + /* unit tests for Curl_node_remove */ + + /** + * case 1: + * list has >1 element, removing head + * @assumptions: + * 1: list size will be decremented by one + * 2: head will be the head->next + * 3: "new" head's previous will be NULL + */ + + head = Curl_llist_head(&llist); + abort_unless(head, "llist.head is NULL"); + element_next = Curl_node_next(head); + llist_size = Curl_llist_count(&llist); + + Curl_node_remove(Curl_llist_head(&llist)); + + fail_unless(Curl_llist_count(&llist) == (llist_size-1), + "llist size not decremented as expected"); + fail_unless(Curl_llist_head(&llist) == element_next, + "llist new head not modified properly"); + abort_unless(Curl_llist_head(&llist), "llist.head is NULL"); + fail_unless(Curl_node_prev(Curl_llist_head(&llist)) == NULL, + "new head previous not set to null"); + + /** + * case 2: + * removing non head element, with list having >=2 elements + * @setup: + * 1: insert another element to the list to make element >=2 + * @assumptions: + * 1: list size will be decremented by one ; tested + * 2: element->previous->next will be element->next + * 3: element->next->previous will be element->previous + */ + Curl_llist_insert_next(&llist, Curl_llist_head(&llist), &unusedData_case3, + &case4_list); + llist_size = Curl_llist_count(&llist); + fail_unless(llist_size == 3, "should be 3 list members"); + + to_remove = Curl_node_next(Curl_llist_head(&llist)); + abort_unless(to_remove, "to_remove is NULL"); + element_next = Curl_node_next(to_remove); + element_prev = Curl_node_prev(to_remove); + Curl_node_uremove(to_remove, NULL); + fail_unless(Curl_node_next(element_prev) == element_next, + "element previous->next is not being adjusted"); + abort_unless(element_next, "element_next is NULL"); + fail_unless(Curl_node_prev(element_next) == element_prev, + "element next->previous is not being adjusted"); + + /** + * case 3: + * removing the tail with list having >=1 element + * @assumptions + * 1: list size will be decremented by one ;tested + * 2: element->previous->next will be element->next ;tested + * 3: element->next->previous will be element->previous ;tested + * 4: list->tail will be tail->previous + */ + + to_remove = Curl_llist_tail(&llist); + element_prev = Curl_node_prev(to_remove); + Curl_node_remove(to_remove); + fail_unless(Curl_llist_tail(&llist) == element_prev, + "llist tail is not being adjusted when removing tail"); + + /** + * case 4: + * removing head with list having 1 element + * @assumptions: + * 1: list size will be decremented by one ;tested + * 2: list head will be null + * 3: list tail will be null + */ + + to_remove = Curl_llist_head(&llist); + Curl_node_remove(to_remove); + fail_unless(Curl_llist_head(&llist) == NULL, + "llist head is not NULL while the llist is empty"); + fail_unless(Curl_llist_tail(&llist) == NULL, + "llist tail is not NULL while the llist is empty"); + + /** + * testing Curl_llist_append + * case 1: + * list is empty + * @assumptions: + * 1: the element next to head should be our newly created element + * 2: the list tail should different from newly created element + */ + Curl_llist_append(&llist, &unusedData_case1, &case1_list); + fail_unless(Curl_llist_count(&llist) == 1, + "List size should be 1 after appending a new element"); + /* test that the list head data holds my unusedData */ + fail_unless(Curl_node_elem(Curl_llist_head(&llist)) == &unusedData_case1, + "head ptr should be first entry"); + /* same goes for the list tail */ + fail_unless(Curl_llist_tail(&llist) == Curl_llist_head(&llist), + "tail and head should be the same"); + + /** + * testing Curl_llist_append + * case 2: + * list is not empty + * @assumptions: + * 1: the list head-next should be the newly created element + * 2: the list tail should be the newly created element + */ + Curl_llist_append(&llist, &unusedData_case2, &case2_list); + fail_unless(Curl_node_elem(Curl_node_next(Curl_llist_head(&llist))) == + &unusedData_case2, + "the node next to head is not getting set correctly"); + fail_unless(Curl_node_elem(Curl_llist_tail(&llist)) == &unusedData_case2, + "the list tail is not getting set correctly"); + + /** + * testing Curl_llist_append + * case 3: + * list is has 2 members + * @assumptions: + * 1: the list head-next should remain the same + * 2: the list tail should be the newly created element + */ + Curl_llist_append(&llist, &unusedData_case3, &case3_list); + fail_unless(Curl_node_elem(Curl_node_next(Curl_llist_head(&llist))) == + &unusedData_case2, + "the node next to head did not stay the same"); + fail_unless(Curl_node_elem(Curl_llist_tail(&llist)) == &unusedData_case3, + "the list tail is not getting set correctly"); + + Curl_llist_destroy(&llist, NULL); + Curl_llist_destroy(&llist_destination, NULL); +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1302.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1302.c new file mode 100644 index 0000000000000000000000000000000000000000..83c58177dba2aad547b3270d03d27891f5ac0663 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1302.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#include "urldata.h" +#include "url.h" /* for Curl_safefree */ +#include "curl_base64.h" +#include "memdebug.h" /* LAST include file */ + +static struct Curl_easy *testdata; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + testdata = curl_easy_init(); + if(!testdata) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(testdata); + curl_global_cleanup(); +} + +UNITTEST_START + +char *output; +unsigned char *decoded; +size_t size = 0; +unsigned char anychar = 'x'; +CURLcode rc; + +rc = Curl_base64_encode("i", 1, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 4, "size should be 4"); +verify_memory(output, "aQ==", 4); +Curl_safefree(output); + +rc = Curl_base64_encode("ii", 2, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 4, "size should be 4"); +verify_memory(output, "aWk=", 4); +Curl_safefree(output); + +rc = Curl_base64_encode("iii", 3, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 4, "size should be 4"); +verify_memory(output, "aWlp", 4); +Curl_safefree(output); + +rc = Curl_base64_encode("iiii", 4, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 8, "size should be 8"); +verify_memory(output, "aWlpaQ==", 8); +Curl_safefree(output); + +rc = Curl_base64_encode("\xff\x01\xfe\x02", 4, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 8, "size should be 8"); +verify_memory(output, "/wH+Ag==", 8); +Curl_safefree(output); + +rc = Curl_base64url_encode("\xff\x01\xfe\x02", 4, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 6, "size should be 6"); +verify_memory(output, "_wH-Ag", 6); +Curl_safefree(output); + +rc = Curl_base64url_encode("iiii", 4, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 6, "size should be 6"); +verify_memory(output, "aWlpaQ", 6); +Curl_safefree(output); + +/* 0 length makes it do strlen() */ +rc = Curl_base64_encode("iiii", 0, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 8, "size should be 8"); +verify_memory(output, "aWlpaQ==", 8); +Curl_safefree(output); + +rc = Curl_base64_encode("", 0, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 0, "size should be 0"); +fail_unless(output && !output[0], "output should be a zero-length string"); +Curl_safefree(output); + +rc = Curl_base64url_encode("", 0, &output, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 0, "size should be 0"); +fail_unless(output && !output[0], "output should be a zero-length string"); +Curl_safefree(output); + +rc = Curl_base64_decode("aWlpaQ==", &decoded, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 4, "size should be 4"); +verify_memory(decoded, "iiii", 4); +Curl_safefree(decoded); + +rc = Curl_base64_decode("aWlp", &decoded, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 3, "size should be 3"); +verify_memory(decoded, "iii", 3); +Curl_safefree(decoded); + +rc = Curl_base64_decode("aWk=", &decoded, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 2, "size should be 2"); +verify_memory(decoded, "ii", 2); +Curl_safefree(decoded); + +rc = Curl_base64_decode("aQ==", &decoded, &size); +fail_unless(rc == CURLE_OK, "return code should be CURLE_OK"); +fail_unless(size == 1, "size should be 1"); +verify_memory(decoded, "i", 2); +Curl_safefree(decoded); + +/* This is illegal input as the data is too short */ +size = 1; /* not zero */ +decoded = &anychar; /* not NULL */ +rc = Curl_base64_decode("aQ", &decoded, &size); +fail_unless(rc == CURLE_BAD_CONTENT_ENCODING, + "return code should be CURLE_BAD_CONTENT_ENCODING"); +fail_unless(size == 0, "size should be 0"); +fail_if(decoded, "returned pointer should be NULL"); + +/* This is illegal input as it contains three padding characters */ +size = 1; /* not zero */ +decoded = &anychar; /* not NULL */ +rc = Curl_base64_decode("a===", &decoded, &size); +fail_unless(rc == CURLE_BAD_CONTENT_ENCODING, + "return code should be CURLE_BAD_CONTENT_ENCODING"); +fail_unless(size == 0, "size should be 0"); +fail_if(decoded, "returned pointer should be NULL"); + +/* This is illegal input as it contains a padding character mid input */ +size = 1; /* not zero */ +decoded = &anychar; /* not NULL */ +rc = Curl_base64_decode("a=Q=", &decoded, &size); +fail_unless(rc == CURLE_BAD_CONTENT_ENCODING, + "return code should be CURLE_BAD_CONTENT_ENCODING"); +fail_unless(size == 0, "size should be 0"); +fail_if(decoded, "returned pointer should be NULL"); + +/* This is also illegal input as it contains a padding character mid input */ +size = 1; /* not zero */ +decoded = &anychar; /* not NULL */ +rc = Curl_base64_decode("aWlpa=Q=", &decoded, &size); +fail_unless(rc == CURLE_BAD_CONTENT_ENCODING, + "return code should be CURLE_BAD_CONTENT_ENCODING"); +fail_unless(size == 0, "size should be 0"); +fail_if(decoded, "returned pointer should be NULL"); + +/* This is garbage input as it contains an illegal base64 character */ +size = 1; /* not zero */ +decoded = &anychar; /* not NULL */ +rc = Curl_base64_decode("a\x1f==", &decoded, &size); +fail_unless(rc == CURLE_BAD_CONTENT_ENCODING, + "return code should be CURLE_BAD_CONTENT_ENCODING"); +fail_unless(size == 0, "size should be 0"); +fail_if(decoded, "returned pointer should be NULL"); + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1303.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1303.c new file mode 100644 index 0000000000000000000000000000000000000000..93262706b3a5ddabbe9b008ba68422e44ae8e58d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1303.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 "curlcheck.h" + +#include "urldata.h" +#include "connect.h" +#include "memdebug.h" /* LAST include file */ + +static struct Curl_easy *testdata; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + testdata = curl_easy_init(); + if(!testdata) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(testdata); + curl_global_cleanup(); +} + +/* BASE is just a define to make us fool around with decently large number so + that we aren't zero-based */ +#define BASE 1000000 + +/* macro to set the pretended current time */ +#define NOW(x,y) now.tv_sec = x; now.tv_usec = y +/* macro to set the millisecond based timeouts to use */ +#define TIMEOUTS(x,y) testdata->set.timeout = x; \ + testdata->set.connecttimeout = y + +/* + * To test: + * + * 00/10/01/11 timeouts set + * 0/1 during connect + * T various values on the timeouts + * N various values of now + */ + +struct timetest { + int now_s; + int now_us; + unsigned int timeout_ms; + unsigned int connecttimeout_ms; + bool connecting; + timediff_t result; + const char *comment; +}; + +UNITTEST_START +{ + struct curltime now; + unsigned int i; + + const struct timetest run[] = { + /* both timeouts set, not connecting */ + {BASE + 4, 0, 10000, 8000, FALSE, 6000, "6 seconds should be left"}, + {BASE + 4, 990000, 10000, 8000, FALSE, 5010, "5010 ms should be left"}, + {BASE + 10, 0, 10000, 8000, FALSE, -1, "timeout is -1, expired"}, + {BASE + 12, 0, 10000, 8000, FALSE, -2000, "-2000, overdue 2 seconds"}, + + /* both timeouts set, connecting */ + {BASE + 4, 0, 10000, 8000, TRUE, 4000, "4 seconds should be left"}, + {BASE + 4, 990000, 10000, 8000, TRUE, 3010, "3010 ms should be left"}, + {BASE + 8, 0, 10000, 8000, TRUE, -1, "timeout is -1, expired"}, + {BASE + 10, 0, 10000, 8000, TRUE, -2000, "-2000, overdue 2 seconds"}, + + /* no connect timeout set, not connecting */ + {BASE + 4, 0, 10000, 0, FALSE, 6000, "6 seconds should be left"}, + {BASE + 4, 990000, 10000, 0, FALSE, 5010, "5010 ms should be left"}, + {BASE + 10, 0, 10000, 0, FALSE, -1, "timeout is -1, expired"}, + {BASE + 12, 0, 10000, 0, FALSE, -2000, "-2000, overdue 2 seconds"}, + + /* no connect timeout set, connecting */ + {BASE + 4, 0, 10000, 0, TRUE, 6000, "6 seconds should be left"}, + {BASE + 4, 990000, 10000, 0, TRUE, 5010, "5010 ms should be left"}, + {BASE + 10, 0, 10000, 0, TRUE, -1, "timeout is -1, expired"}, + {BASE + 12, 0, 10000, 0, TRUE, -2000, "-2000, overdue 2 seconds"}, + + /* only connect timeout set, not connecting */ + {BASE + 4, 0, 0, 10000, FALSE, 0, "no timeout active"}, + {BASE + 4, 990000, 0, 10000, FALSE, 0, "no timeout active"}, + {BASE + 10, 0, 0, 10000, FALSE, 0, "no timeout active"}, + {BASE + 12, 0, 0, 10000, FALSE, 0, "no timeout active"}, + + /* only connect timeout set, connecting */ + {BASE + 4, 0, 0, 10000, TRUE, 6000, "6 seconds should be left"}, + {BASE + 4, 990000, 0, 10000, TRUE, 5010, "5010 ms should be left"}, + {BASE + 10, 0, 0, 10000, TRUE, -1, "timeout is -1, expired"}, + {BASE + 12, 0, 0, 10000, TRUE, -2000, "-2000, overdue 2 seconds"}, + + /* no timeout set, not connecting */ + {BASE + 4, 0, 0, 0, FALSE, 0, "no timeout active"}, + {BASE + 4, 990000, 0, 0, FALSE, 0, "no timeout active"}, + {BASE + 10, 0, 0, 0, FALSE, 0, "no timeout active"}, + {BASE + 12, 0, 0, 0, FALSE, 0, "no timeout active"}, + + /* no timeout set, connecting */ + {BASE + 4, 0, 0, 0, TRUE, 296000, "no timeout active"}, + {BASE + 4, 990000, 0, 0, TRUE, 295010, "no timeout active"}, + {BASE + 10, 0, 0, 0, TRUE, 290000, "no timeout active"}, + {BASE + 12, 0, 0, 0, TRUE, 288000, "no timeout active"}, + + /* both timeouts set, connecting, connect timeout the longer one */ + {BASE + 4, 0, 10000, 12000, TRUE, 6000, "6 seconds should be left"}, + + }; + + /* this is the pretended start time of the transfer */ + testdata->progress.t_startsingle.tv_sec = BASE; + testdata->progress.t_startsingle.tv_usec = 0; + testdata->progress.t_startop.tv_sec = BASE; + testdata->progress.t_startop.tv_usec = 0; + + for(i = 0; i < sizeof(run)/sizeof(run[0]); i++) { + timediff_t timeout; + NOW(run[i].now_s, run[i].now_us); + TIMEOUTS(run[i].timeout_ms, run[i].connecttimeout_ms); + timeout = Curl_timeleft(testdata, &now, run[i].connecting); + if(timeout != run[i].result) + fail(run[i].comment); + } +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1304.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1304.c new file mode 100644 index 0000000000000000000000000000000000000000..817887b94c87485a8bced0b051a8164fd81ccb0f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1304.c @@ -0,0 +1,195 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" +#include "netrc.h" +#include "memdebug.h" /* LAST include file */ + +#ifndef CURL_DISABLE_NETRC + +static char *s_login; +static char *s_password; + +static CURLcode unit_setup(void) +{ + s_password = NULL; + s_login = NULL; + return CURLE_OK; +} + +static void unit_stop(void) +{ + Curl_safefree(s_password); + Curl_safefree(s_login); +} + +UNITTEST_START +{ + int result; + struct store_netrc store; + + /* + * Test a non existent host in our netrc file. + */ + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "test.example.com", &s_login, &s_password, arg); + fail_unless(result == 1, "Host not found should return 1"); + abort_unless(s_password == NULL, "password did not return NULL!"); + abort_unless(s_login == NULL, "user did not return NULL!"); + Curl_netrc_cleanup(&store); + + /* + * Test a non existent login in our netrc file. + */ + s_login = (char *)"me"; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password == NULL, "password is not NULL!"); + Curl_netrc_cleanup(&store); + + /* + * Test a non existent login and host in our netrc file. + */ + s_login = (char *)"me"; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "test.example.com", &s_login, &s_password, arg); + fail_unless(result == 1, "Host not found should return 1"); + abort_unless(s_password == NULL, "password is not NULL!"); + Curl_netrc_cleanup(&store); + + /* + * Test a non existent login (substring of an existing one) in our + * netrc file. + */ + s_login = (char *)"admi"; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password == NULL, "password is not NULL!"); + Curl_netrc_cleanup(&store); + + /* + * Test a non existent login (superstring of an existing one) + * in our netrc file. + */ + s_login = (char *)"adminn"; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password == NULL, "password is not NULL!"); + Curl_netrc_cleanup(&store); + + /* + * Test for the first existing host in our netrc file + * with s_login[0] = 0. + */ + s_login = NULL; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password != NULL, "returned NULL!"); + fail_unless(strncmp(s_password, "passwd", 6) == 0, + "password should be 'passwd'"); + abort_unless(s_login != NULL, "returned NULL!"); + fail_unless(strncmp(s_login, "admin", 5) == 0, "login should be 'admin'"); + Curl_netrc_cleanup(&store); + + /* + * Test for the first existing host in our netrc file + * with s_login[0] != 0. + */ + free(s_password); + free(s_login); + s_password = NULL; + s_login = NULL; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password != NULL, "returned NULL!"); + fail_unless(strncmp(s_password, "passwd", 6) == 0, + "password should be 'passwd'"); + abort_unless(s_login != NULL, "returned NULL!"); + fail_unless(strncmp(s_login, "admin", 5) == 0, "login should be 'admin'"); + Curl_netrc_cleanup(&store); + + /* + * Test for the second existing host in our netrc file + * with s_login[0] = 0. + */ + free(s_password); + s_password = NULL; + free(s_login); + s_login = NULL; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "curl.example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password != NULL, "returned NULL!"); + fail_unless(strncmp(s_password, "none", 4) == 0, + "password should be 'none'"); + abort_unless(s_login != NULL, "returned NULL!"); + fail_unless(strncmp(s_login, "none", 4) == 0, "login should be 'none'"); + Curl_netrc_cleanup(&store); + + /* + * Test for the second existing host in our netrc file + * with s_login[0] != 0. + */ + free(s_password); + free(s_login); + s_password = NULL; + s_login = NULL; + Curl_netrc_init(&store); + result = Curl_parsenetrc(&store, + "curl.example.com", &s_login, &s_password, arg); + fail_unless(result == 0, "Host should have been found"); + abort_unless(s_password != NULL, "returned NULL!"); + fail_unless(strncmp(s_password, "none", 4) == 0, + "password should be 'none'"); + abort_unless(s_login != NULL, "returned NULL!"); + fail_unless(strncmp(s_login, "none", 4) == 0, "login should be 'none'"); + Curl_netrc_cleanup(&store); + +} +UNITTEST_STOP + +#else +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} +static void unit_stop(void) +{ +} +UNITTEST_START +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1305.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1305.c new file mode 100644 index 0000000000000000000000000000000000000000..03011a577a9acfaeaffcc7724918ed98bf75d13a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1305.c @@ -0,0 +1,131 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif + +#include "curlx.h" + +#include "hash.h" +#include "hostip.h" + +#include "memdebug.h" /* LAST include file */ + +static struct Curl_easy *testdata; +static struct Curl_hash hp; +static char *data_key; +static struct Curl_dns_entry *data_node; + +static CURLcode unit_setup(void) +{ + testdata = curl_easy_init(); + if(!testdata) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + + Curl_init_dnscache(&hp, 7); + return CURLE_OK; +} + +static void unit_stop(void) +{ + if(data_node) { + Curl_freeaddrinfo(data_node->addr); + free(data_node); + } + free(data_key); + Curl_hash_destroy(&hp); + + curl_easy_cleanup(testdata); + curl_global_cleanup(); +} + +static struct Curl_addrinfo *fake_ai(void) +{ + static struct Curl_addrinfo *ai; + static const char dummy[]="dummy"; + size_t namelen = sizeof(dummy); /* including the null-terminator */ + + ai = calloc(1, sizeof(struct Curl_addrinfo) + sizeof(struct sockaddr_in) + + namelen); + if(!ai) + return NULL; + + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + ai->ai_canonname = (void *)((char *)ai->ai_addr + + sizeof(struct sockaddr_in)); + memcpy(ai->ai_canonname, dummy, namelen); + + ai->ai_family = AF_INET; + ai->ai_addrlen = sizeof(struct sockaddr_in); + + return ai; +} + +static CURLcode create_node(void) +{ + data_key = aprintf("%s:%d", "dummy", 0); + if(!data_key) + return CURLE_OUT_OF_MEMORY; + + data_node = calloc(1, sizeof(struct Curl_dns_entry)); + if(!data_node) + return CURLE_OUT_OF_MEMORY; + + data_node->addr = fake_ai(); + if(!data_node->addr) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + + +UNITTEST_START + + struct Curl_dns_entry *nodep; + size_t key_len; + + /* Test 1305 exits without adding anything to the hash */ + if(strcmp(arg, "1305") != 0) { + CURLcode rc = create_node(); + abort_unless(rc == CURLE_OK, "data node creation failed"); + key_len = strlen(data_key); + + data_node->refcount = 1; /* hash will hold the reference */ + nodep = Curl_hash_add(&hp, data_key, key_len + 1, data_node); + abort_unless(nodep, "insertion into hash failed"); + /* Freeing will now be done by Curl_hash_destroy */ + data_node = NULL; + } + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1307.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1307.c new file mode 100644 index 0000000000000000000000000000000000000000..08faa339033142384ee95480a9ed206ea4be2668 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1307.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 "curlcheck.h" + +#include "curl_fnmatch.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +#ifndef CURL_DISABLE_FTP + +/* + CURL_FNMATCH_MATCH 0 + CURL_FNMATCH_NOMATCH 1 + CURL_FNMATCH_FAIL 2 + */ + +#define MATCH CURL_FNMATCH_MATCH +#define NOMATCH CURL_FNMATCH_NOMATCH + +#define LINUX_DIFFER 0x80 +#define LINUX_SHIFT 8 +#define LINUX_MATCH ((CURL_FNMATCH_MATCH << LINUX_SHIFT) | LINUX_DIFFER) +#define LINUX_NOMATCH ((CURL_FNMATCH_NOMATCH << LINUX_SHIFT) | LINUX_DIFFER) +#define LINUX_FAIL ((CURL_FNMATCH_FAIL << LINUX_SHIFT) | LINUX_DIFFER) + +#define MAC_DIFFER 0x40 +#define MAC_SHIFT 16 +#define MAC_MATCH ((CURL_FNMATCH_MATCH << MAC_SHIFT) | MAC_DIFFER) +#define MAC_NOMATCH ((CURL_FNMATCH_NOMATCH << MAC_SHIFT) | MAC_DIFFER) +#define MAC_FAIL ((CURL_FNMATCH_FAIL << MAC_SHIFT) | MAC_DIFFER) + +struct testcase { + const char *pattern; + const char *string; + int result; +}; + +static const struct testcase tests[] = { + /* brackets syntax */ + {"*[*[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\001\177[[[[[[[[[[[[[[[[[[[[[", + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[", + NOMATCH|MAC_FAIL}, + + { "\\[", "[", MATCH }, + { "[", "[", NOMATCH|LINUX_MATCH|MAC_FAIL}, + { "[]", "[]", NOMATCH|LINUX_MATCH|MAC_FAIL}, + { "[][]", "[", MATCH }, + { "[][]", "]", MATCH }, + { "[[]", "[", MATCH }, + { "[[[]", "[", MATCH }, + { "[[[[]", "[", MATCH }, + { "[[[[]", "[", MATCH }, + + { "[][[]", "]", MATCH }, + { "[][[[]", "[", MATCH }, + { "[[]", "]", NOMATCH }, + + { "[a@]", "a", MATCH }, + + { "[a-z]", "a", MATCH }, + { "[a-z]", "A", NOMATCH }, + { "?[a-z]", "?Z", NOMATCH }, + { "[A-Z]", "C", MATCH }, + { "[A-Z]", "c", NOMATCH }, + { "[0-9]", "7", MATCH }, + { "[7-8]", "7", MATCH }, + { "[7-]", "7", MATCH }, + { "[7-]", "-", MATCH }, + { "[7-]", "[", NOMATCH }, + { "[a-bA-F]", "F", MATCH }, + { "[a-bA-B9]", "9", MATCH }, + { "[a-bA-B98]", "8", MATCH }, + { "[a-bA-B98]", "C", NOMATCH }, + { "[a-bA-Z9]", "F", MATCH }, + { "[a-bA-Z9]ero*", "Zero chance.", MATCH }, + { "S[a-][x]opho*", "Saxophone", MATCH }, + { "S[a-][x]opho*", "SaXophone", NOMATCH }, + { "S[a-][x]*.txt", "S-x.txt", MATCH }, + { "[\\a-\\b]", "a", MATCH }, + { "[\\a-\\b]", "b", MATCH }, + { "[?*[][?*[][?*[]", "?*[", MATCH }, + { "[][?*-]", "]", MATCH }, + { "[][?*-]", "[", MATCH }, + { "[][?*-]", "?", MATCH }, + { "[][?*-]", "*", MATCH }, + { "[][?*-]", "-", MATCH }, + { "[]?*-]", "-", MATCH }, + { "[\xFF]", "\xFF", MATCH|LINUX_FAIL|MAC_FAIL}, + { "?/b/c", "a/b/c", MATCH }, + { "^_{}~", "^_{}~", MATCH }, + { "!#%+,-./01234567889", "!#%+,-./01234567889", MATCH }, + { "PQRSTUVWXYZ]abcdefg", "PQRSTUVWXYZ]abcdefg", MATCH }, + { ":;=@ABCDEFGHIJKLMNO", ":;=@ABCDEFGHIJKLMNO", MATCH }, + + /* negate */ + { "[!a]", "b", MATCH }, + { "[!a]", "a", NOMATCH }, + { "[^a]", "b", MATCH }, + { "[^a]", "a", NOMATCH }, + { "[^a-z0-9A-Z]", "a", NOMATCH }, + { "[^a-z0-9A-Z]", "-", MATCH }, + { "curl[!a-z]lib", "curl lib", MATCH }, + { "curl[! ]lib", "curl lib", NOMATCH }, + { "[! ][ ]", " ", NOMATCH }, + { "[! ][ ]", "a ", MATCH }, + { "*[^a].t?t", "a.txt", NOMATCH }, + { "*[^a].t?t", "ba.txt", NOMATCH }, + { "*[^a].t?t", "ab.txt", MATCH }, + { "*[^a]", "", NOMATCH }, + { "[!\xFF]", "", NOMATCH|LINUX_FAIL}, + { "[!\xFF]", "\xFF", NOMATCH|LINUX_FAIL|MAC_FAIL}, + { "[!\xFF]", "a", MATCH|LINUX_FAIL|MAC_FAIL}, + { "[!?*[]", "?", NOMATCH }, + { "[!!]", "!", NOMATCH }, + { "[!!]", "x", MATCH }, + + { "[[:alpha:]]", "a", MATCH }, + { "[[:alpha:]]", "9", NOMATCH }, + { "[[:alnum:]]", "a", MATCH }, + { "[[:alnum:]]", "[", NOMATCH }, + { "[[:alnum:]]", "]", NOMATCH }, + { "[[:alnum:]]", "9", MATCH }, + { "[[:digit:]]", "9", MATCH }, + { "[[:xdigit:]]", "9", MATCH }, + { "[[:xdigit:]]", "F", MATCH }, + { "[[:xdigit:]]", "G", NOMATCH }, + { "[[:upper:]]", "U", MATCH }, + { "[[:upper:]]", "u", NOMATCH }, + { "[[:lower:]]", "l", MATCH }, + { "[[:lower:]]", "L", NOMATCH }, + { "[[:print:]]", "L", MATCH }, + { "[[:print:]]", "\10", NOMATCH }, + { "[[:print:]]", "\10", NOMATCH }, + { "[[:space:]]", " ", MATCH }, + { "[[:space:]]", "x", NOMATCH }, + { "[[:graph:]]", " ", NOMATCH }, + { "[[:graph:]]", "x", MATCH }, + { "[[:blank:]]", "\t", MATCH }, + { "[[:blank:]]", " ", MATCH }, + { "[[:blank:]]", "\r", NOMATCH }, + { "[^[:blank:]]", "\t", NOMATCH }, + { "[^[:print:]]", "\10", MATCH }, + { "[[:lower:]][[:lower:]]", "ll", MATCH }, + { "[[:foo:]]", "bar", NOMATCH|MAC_FAIL}, + { "[[:foo:]]", "f]", MATCH|LINUX_NOMATCH|MAC_FAIL}, + + { "Curl[[:blank:]];-)", "Curl ;-)", MATCH }, + { "*[[:blank:]]*", " ", MATCH }, + { "*[[:blank:]]*", "", NOMATCH }, + { "*[[:blank:]]*", "hi, im_Pavel", MATCH }, + + /* common using */ + { "filename.dat", "filename.dat", MATCH }, + { "*curl*", "lets use curl!!", MATCH }, + { "filename.txt", "filename.dat", NOMATCH }, + { "*.txt", "text.txt", MATCH }, + { "*.txt", "a.txt", MATCH }, + { "*.txt", ".txt", MATCH }, + { "*.txt", "txt", NOMATCH }, + { "??.txt", "99.txt", MATCH }, + { "??.txt", "a99.txt", NOMATCH }, + { "?.???", "a.txt", MATCH }, + { "*.???", "somefile.dat", MATCH }, + { "*.???", "photo.jpeg", NOMATCH }, + { ".*", ".htaccess", MATCH }, + { ".*", ".", MATCH }, + { ".*", "..", MATCH }, + + /* many stars => one star */ + { "**.txt", "text.txt", MATCH }, + { "***.txt", "t.txt", MATCH }, + { "****.txt", ".txt", MATCH }, + + /* empty string or pattern */ + { "", "", MATCH }, + { "", "hello", NOMATCH }, + { "file", "", NOMATCH }, + { "?", "", NOMATCH }, + { "*", "", MATCH }, + { "x", "", NOMATCH }, + + /* backslash */ + { "\\", "\\", MATCH|LINUX_NOMATCH}, + { "\\\\", "\\", MATCH }, + { "\\\\", "\\\\", NOMATCH }, + { "\\?", "?", MATCH }, + { "\\*", "*", MATCH }, + { "?.txt", "?.txt", MATCH }, + { "*.txt", "*.txt", MATCH }, + { "\\?.txt", "?.txt", MATCH }, + { "\\*.txt", "*.txt", MATCH }, + { "\\?.txt", "x.txt", NOMATCH }, + { "\\*.txt", "x.txt", NOMATCH }, + { "\\*\\\\.txt", "*\\.txt", MATCH }, + { "*\\**\\?*\\\\*", "cc*cc?cccc", NOMATCH }, + { "*\\?*\\**", "cc?cc", NOMATCH }, + { "\\\"\\$\\&\\'\\(\\)", "\"$&'()", MATCH }, + { "\\*\\?\\[\\\\\\`\\|", "*?[\\`|", MATCH }, + { "[\\a\\b]c", "ac", MATCH }, + { "[\\a\\b]c", "bc", MATCH }, + { "[\\a\\b]d", "bc", NOMATCH }, + { "[a-bA-B\\?]", "?", MATCH }, + { "cu[a-ab-b\\r]l", "curl", MATCH }, + { "[\\a-z]", "c", MATCH }, + + { "?*?*?.*?*", "abc.c", MATCH }, + { "?*?*?.*?*", "abcc", NOMATCH }, + { "?*?*?.*?*", "abc.", NOMATCH }, + { "?*?*?.*?*", "abc.c++", MATCH }, + { "?*?*?.*?*", "abcdef.c++", MATCH }, + { "?*?*?.?", "abcdef.c", MATCH }, + { "?*?*?.?", "abcdef.cd", NOMATCH }, + + { "Lindmätarv", "Lindmätarv", MATCH }, + + { "", "", MATCH}, + {"**]*[*[\x13]**[*\x13)]*]*[**[*\x13~r-]*]**[.*]*[\xe3\xe3\xe3\xe3\xe3\xe3" + "\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3\xe3" + "\xe3\xe3\xe3\xe3\xe3*[\x13]**[*\x13)]*]*[*[\x13]*[~r]*]*\xba\x13\xa6~b-]*", + "a", NOMATCH|LINUX_FAIL} +}; + +static const char *ret2name(int i) +{ + switch(i) { + case 0: + return "MATCH"; + case 1: + return "NOMATCH"; + case 2: + return "FAIL"; + default: + return "unknown"; + } + /* not reached */ +} + +enum system { + SYSTEM_CUSTOM, + SYSTEM_LINUX, + SYSTEM_MACOS +}; + +UNITTEST_START +{ + int testnum = sizeof(tests) / sizeof(struct testcase); + int i; + enum system machine; + +#ifdef HAVE_FNMATCH +#ifdef __APPLE__ + machine = SYSTEM_MACOS; +#else + machine = SYSTEM_LINUX; +#endif + printf("Tested with system fnmatch(), %s-style\n", + machine == SYSTEM_LINUX ? "linux" : "mac"); +#else + printf("Tested with custom fnmatch()\n"); + machine = SYSTEM_CUSTOM; +#endif + + for(i = 0; i < testnum; i++) { + int result = tests[i].result; + int rc = Curl_fnmatch(NULL, tests[i].pattern, tests[i].string); + if(result & (LINUX_DIFFER|MAC_DIFFER)) { + if((result & LINUX_DIFFER) && (machine == SYSTEM_LINUX)) + result >>= LINUX_SHIFT; + else if((result & MAC_DIFFER) && (machine == SYSTEM_MACOS)) + result >>= MAC_SHIFT; + result &= 0x03; /* filter off all high bits */ + } + if(rc != result) { + printf("Curl_fnmatch(\"%s\", \"%s\") should return %s (returns %s)" + " [%d]\n", + tests[i].pattern, tests[i].string, ret2name(result), + ret2name(rc), i); + fail("pattern mismatch"); + } + } +} +UNITTEST_STOP + +#else + +UNITTEST_START +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1308.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1308.c new file mode 100644 index 0000000000000000000000000000000000000000..4d29fb887bc78a43a69a88a28fc98400229ae2cc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1308.c @@ -0,0 +1,109 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +static size_t print_httppost_callback(void *arg, const char *buf, size_t len) +{ + fwrite(buf, len, 1, stdout); + (*(size_t *) arg) += len; + return len; +} + +UNITTEST_START + CURLFORMcode rc; + int res; + struct curl_httppost *post = NULL; + struct curl_httppost *last = NULL; + size_t total_size = 0; + char buffer[] = "test buffer"; + + CURL_IGNORE_DEPRECATION( + rc = curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", + CURLFORM_COPYCONTENTS, "content", CURLFORM_END); + ) + fail_unless(rc == 0, "curl_formadd returned error"); + + /* after the first curl_formadd when there's a single entry, both pointers + should point to the same struct */ + fail_unless(post == last, "post and last weren't the same"); + + CURL_IGNORE_DEPRECATION( + rc = curl_formadd(&post, &last, CURLFORM_COPYNAME, "htmlcode", + CURLFORM_COPYCONTENTS, "", + CURLFORM_CONTENTTYPE, "text/html", CURLFORM_END); + ) + fail_unless(rc == 0, "curl_formadd returned error"); + + CURL_IGNORE_DEPRECATION( + rc = curl_formadd(&post, &last, CURLFORM_COPYNAME, "name_for_ptrcontent", + CURLFORM_PTRCONTENTS, buffer, CURLFORM_END); + ) + fail_unless(rc == 0, "curl_formadd returned error"); + + CURL_IGNORE_DEPRECATION( + res = curl_formget(post, &total_size, print_httppost_callback); + ) + fail_unless(res == 0, "curl_formget returned error"); + + fail_unless(total_size == 518, "curl_formget got wrong size back"); + + CURL_IGNORE_DEPRECATION( + curl_formfree(post); + ) + + /* start a new formpost with a file upload and formget */ + post = last = NULL; + + CURL_IGNORE_DEPRECATION( + rc = curl_formadd(&post, &last, + CURLFORM_PTRNAME, "name of file field", + CURLFORM_FILE, arg, + CURLFORM_FILENAME, "custom named file", + CURLFORM_END); + ) + fail_unless(rc == 0, "curl_formadd returned error"); + + CURL_IGNORE_DEPRECATION( + res = curl_formget(post, &total_size, print_httppost_callback); + ) + fail_unless(res == 0, "curl_formget returned error"); + fail_unless(total_size == 899, "curl_formget got wrong size back"); + + CURL_IGNORE_DEPRECATION( + curl_formfree(post); + ) + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1309.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1309.c new file mode 100644 index 0000000000000000000000000000000000000000..2bd2f9b46546ef470c9327963f1d40b0c3107895 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1309.c @@ -0,0 +1,144 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "splay.h" +#include "warnless.h" + + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +static void splayprint(struct Curl_tree *t, int d, char output) +{ + struct Curl_tree *node; + int i; + int count; + if(!t) + return; + + splayprint(t->larger, d + 1, output); + for(i = 0; i < d; i++) + if(output) + printf(" "); + + if(output) { + printf("%ld.%ld[%d]", (long)t->key.tv_sec, + (long)t->key.tv_usec, i); + } + + for(count = 0, node = t->samen; node != t; node = node->samen, count++) + ; + + if(output) { + if(count) + printf(" [%d more]\n", count); + else + printf("\n"); + } + + splayprint(t->smaller, d + 1, output); +} + +UNITTEST_START + +/* number of nodes to add to the splay tree */ +#define NUM_NODES 50 + + struct Curl_tree *root, *removed; + struct Curl_tree nodes[NUM_NODES*3]; + size_t storage[NUM_NODES*3]; + int rc; + int i, j; + struct curltime tv_now = {0, 0}; + root = NULL; /* the empty tree */ + + /* add nodes */ + for(i = 0; i < NUM_NODES; i++) { + struct curltime key; + + key.tv_sec = 0; + key.tv_usec = (541*i)%1023; + storage[i] = key.tv_usec; + Curl_splayset(&nodes[i], &storage[i]); + root = Curl_splayinsert(key, root, &nodes[i]); + } + + puts("Result:"); + splayprint(root, 0, 1); + + for(i = 0; i < NUM_NODES; i++) { + int rem = (i + 7)%NUM_NODES; + printf("Tree look:\n"); + splayprint(root, 0, 1); + printf("remove pointer %d, payload %zu\n", rem, + *(size_t *)Curl_splayget(&nodes[rem])); + rc = Curl_splayremove(root, &nodes[rem], &root); + if(rc) { + /* failed! */ + printf("remove %d failed!\n", rem); + fail("remove"); + } + } + + fail_unless(root == NULL, "tree not empty after removing all nodes"); + + /* rebuild tree */ + for(i = 0; i < NUM_NODES; i++) { + struct curltime key; + + key.tv_sec = 0; + key.tv_usec = (541*i)%1023; + + /* add some nodes with the same key */ + for(j = 0; j <= i % 3; j++) { + storage[i * 3 + j] = key.tv_usec*10 + j; + Curl_splayset(&nodes[i * 3 + j], &storage[i * 3 + j]); + root = Curl_splayinsert(key, root, &nodes[i * 3 + j]); + } + } + + removed = NULL; + for(i = 0; i <= 1100; i += 100) { + printf("Removing nodes not larger than %d\n", i); + tv_now.tv_usec = i; + root = Curl_splaygetbest(tv_now, root, &removed); + while(removed) { + printf("removed payload %zu[%zu]\n", + *(size_t *)Curl_splayget(removed) / 10, + *(size_t *)Curl_splayget(removed) % 10); + root = Curl_splaygetbest(tv_now, root, &removed); + } + } + + fail_unless(root == NULL, "tree not empty when it should be"); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1323.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1323.c new file mode 100644 index 0000000000000000000000000000000000000000..bdd02b5de5d01e2a1987a03595ab4bd643973c47 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1323.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 "curlcheck.h" + +#include "timeval.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +struct a { + struct curltime first; + struct curltime second; + time_t result; +}; + +UNITTEST_START +{ + struct a tests[] = { + { {36762, 8345 }, {36761, 995926 }, 13 }, + { {36761, 995926 }, {36762, 8345 }, -13 }, + { {36761, 995926 }, {0, 0}, 36761995 }, + { {0, 0}, {36761, 995926 }, -36761995 }, + }; + size_t i; + + for(i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { + timediff_t result = Curl_timediff(tests[i].first, tests[i].second); + if(result != tests[i].result) { + printf("%ld.%06u to %ld.%06u got %d, but expected %ld\n", + (long)tests[i].first.tv_sec, + tests[i].first.tv_usec, + (long)tests[i].second.tv_sec, + tests[i].second.tv_usec, + (int)result, + (long)tests[i].result); + fail("unexpected result!"); + } + } +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1330.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1330.c new file mode 100644 index 0000000000000000000000000000000000000000..2e27e8093fa3fa0176df5a7571b2f5506da2707f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1330.c @@ -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 "curlcheck.h" + +#include "memdebug.h" + + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +UNITTEST_START + +char *ptr = malloc(1330); +Curl_safefree(ptr); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1394.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1394.c new file mode 100644 index 0000000000000000000000000000000000000000..ef398ab22f2219aca53189d0d2d2c796ca0227e6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1394.c @@ -0,0 +1,133 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "tool_getparam.h" + +#include +#include +#include + +#include "memdebug.h" /* LAST include file */ + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +UNITTEST_START + + const char *values[] = { + /* -E parameter */ /* exp. cert name */ /* exp. passphrase */ + "foo:bar:baz", "foo", "bar:baz", + "foo\\:bar:baz", "foo:bar", "baz", + "foo\\\\:bar:baz", "foo\\", "bar:baz", + "foo:bar\\:baz", "foo", "bar\\:baz", + "foo:bar\\\\:baz", "foo", "bar\\\\:baz", + "foo\\bar\\baz", "foo\\bar\\baz", NULL, + "foo\\\\bar\\\\baz", "foo\\bar\\baz", NULL, + "foo\\", "foo\\", NULL, + "foo\\\\", "foo\\", NULL, + "foo:bar\\", "foo", "bar\\", + "foo:bar\\\\", "foo", "bar\\\\", + "foo:bar:", "foo", "bar:", + "foo\\::bar\\:", "foo:", "bar\\:", + "pkcs11:foobar", "pkcs11:foobar", NULL, + "PKCS11:foobar", "PKCS11:foobar", NULL, + "PkCs11:foobar", "PkCs11:foobar", NULL, +#ifdef _WIN32 + "c:\\foo:bar:baz", "c:\\foo", "bar:baz", + "c:\\foo\\:bar:baz", "c:\\foo:bar", "baz", + "c:\\foo\\\\:bar:baz", "c:\\foo\\", "bar:baz", + "c:\\foo:bar\\:baz", "c:\\foo", "bar\\:baz", + "c:\\foo:bar\\\\:baz", "c:\\foo", "bar\\\\:baz", + "c:\\foo\\bar\\baz", "c:\\foo\\bar\\baz", NULL, + "c:\\foo\\\\bar\\\\baz", "c:\\foo\\bar\\baz", NULL, + "c:\\foo\\", "c:\\foo\\", NULL, + "c:\\foo\\\\", "c:\\foo\\", NULL, + "c:\\foo:bar\\", "c:\\foo", "bar\\", + "c:\\foo:bar\\\\", "c:\\foo", "bar\\\\", + "c:\\foo:bar:", "c:\\foo", "bar:", + "c:\\foo\\::bar\\:", "c:\\foo:", "bar\\:", +#endif + NULL, NULL, NULL, + }; + const char **p; + char *certname, *passphrase; + for(p = values; *p; p += 3) { + parse_cert_parameter(p[0], &certname, &passphrase); + if(p[1]) { + if(certname) { + if(strcmp(p[1], certname)) { + printf("expected certname '%s' but got '%s' " + "for -E param '%s'\n", p[1], certname, p[0]); + fail("assertion failure"); + } + } + else { + printf("expected certname '%s' but got NULL " + "for -E param '%s'\n", p[1], p[0]); + fail("assertion failure"); + } + } + else { + if(certname) { + printf("expected certname NULL but got '%s' " + "for -E param '%s'\n", certname, p[0]); + fail("assertion failure"); + } + } + if(p[2]) { + if(passphrase) { + if(strcmp(p[2], passphrase)) { + printf("expected passphrase '%s' but got '%s'" + "for -E param '%s'\n", p[2], passphrase, p[0]); + fail("assertion failure"); + } + } + else { + printf("expected passphrase '%s' but got NULL " + "for -E param '%s'\n", p[2], p[0]); + fail("assertion failure"); + } + } + else { + if(passphrase) { + printf("expected passphrase NULL but got '%s' " + "for -E param '%s'\n", passphrase, p[0]); + fail("assertion failure"); + } + } + if(certname) + free(certname); + if(passphrase) + free(passphrase); + } + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1395.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1395.c new file mode 100644 index 0000000000000000000000000000000000000000..017b45a0e40abc1e1c4a2b99a8d912519610e5fe --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1395.c @@ -0,0 +1,107 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +/* copied from urlapi.c */ +extern int dedotdotify(const char *input, size_t clen, char **out); + +#include "memdebug.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +struct dotdot { + const char *input; + const char *output; +}; + +UNITTEST_START + + unsigned int i; + int fails = 0; + const struct dotdot pairs[] = { + { "/a/b/c/./../../g", "/a/g" }, + { "mid/content=5/../6", "mid/6" }, + { "/hello/../moo", "/moo" }, + { "/1/../1", "/1" }, + { "/1/./1", "/1/1" }, + { "/1/..", "/" }, + { "/1/.", "/1/" }, + { "/1/./..", "/" }, + { "/1/./../2", "/2" }, + { "/hello/1/./../2", "/hello/2" }, + { "test/this", NULL }, + { "test/this/../now", "test/now" }, + { "/1../moo../foo", "/1../moo../foo"}, + { "/../../moo", "/moo"}, + { "/../../moo?", "/moo?"}, + { "/123?", NULL}, + { "/../moo/..?", "/" }, + { "/", NULL }, + { "", NULL }, + { "/.../", "/.../" }, + { "./moo", "moo" }, + { "../moo", "moo" }, + { "/.", "/" }, + { "/..", "/" }, + { "/moo/..", "/" }, + { "/..", "/" }, + { "/.", "/" }, + }; + + for(i = 0; i < sizeof(pairs)/sizeof(pairs[0]); i++) { + char *out; + int err = dedotdotify(pairs[i].input, strlen(pairs[i].input), &out); + abort_unless(err == 0, "returned error"); + abort_if(err && out, "returned error with output"); + + if(out && pairs[i].output && strcmp(out, pairs[i].output)) { + fprintf(stderr, "Test %u: '%s' gave '%s' instead of '%s'\n", + i, pairs[i].input, out, pairs[i].output); + fail("Test case output mismatched"); + fails++; + } + else if((!out && pairs[i].output) || + (out && !pairs[i].output)) { + fprintf(stderr, "Test %u: '%s' gave '%s' instead of '%s'\n", + i, pairs[i].input, out ? out : "(null)", + pairs[i].output ? pairs[i].output : "(null)"); + fail("Test case output mismatched"); + fails++; + } + else + fprintf(stderr, "Test %u: OK\n", i); + free(out); + } + + fail_if(fails, "output mismatched"); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1396.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1396.c new file mode 100644 index 0000000000000000000000000000000000000000..43f9c8667268e655fb076492d9ecf647353b43ad --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1396.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +static CURL *hnd; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + return res; +} + +static void unit_stop(void) +{ + if(hnd) + curl_easy_cleanup(hnd); + curl_global_cleanup(); +} + +struct test { + const char *in; + int inlen; + const char *out; + int outlen; +}; + +UNITTEST_START +{ + /* unescape, this => that */ + const struct test list1[]={ + {"%61", 3, "a", 1}, + {"%61a", 4, "aa", 2}, + {"%61b", 4, "ab", 2}, + {"%6 1", 4, "%6 1", 4}, + {"%61", 1, "%", 1}, + {"%61", 2, "%6", 2}, + {"%6%a", 4, "%6%a", 4}, + {"%6a", 0, "j", 1}, + {"%FF", 0, "\xff", 1}, + {"%FF%00%ff", 9, "\xff\x00\xff", 3}, + {"%-2", 0, "%-2", 3}, + {"%FG", 0, "%FG", 3}, + {NULL, 0, NULL, 0} /* end of list marker */ + }; + /* escape, this => that */ + const struct test list2[]={ + {"a", 1, "a", 1}, + {"/", 1, "%2F", 3}, + {"a=b", 3, "a%3Db", 5}, + {"a=b", 0, "a%3Db", 5}, + {"a=b", 1, "a", 1}, + {"a=b", 2, "a%3D", 4}, + {"1/./0", 5, "1%2F.%2F0", 9}, + {"-._~!#%&", 0, "-._~%21%23%25%26", 16}, + {"a", 2, "a%00", 4}, + {"a\xff\x01g", 4, "a%FF%01g", 8}, + {NULL, 0, NULL, 0} /* end of list marker */ + }; + int i; + + hnd = curl_easy_init(); + abort_unless(hnd != NULL, "returned NULL!"); + for(i = 0; list1[i].in; i++) { + int outlen; + char *out = curl_easy_unescape(hnd, + list1[i].in, list1[i].inlen, + &outlen); + + abort_unless(out != NULL, "returned NULL!"); + fail_unless(outlen == list1[i].outlen, "wrong output length returned"); + fail_unless(!memcmp(out, list1[i].out, list1[i].outlen), + "bad output data returned"); + + printf("curl_easy_unescape test %d DONE\n", i); + + curl_free(out); + } + + for(i = 0; list2[i].in; i++) { + int outlen; + char *out = curl_easy_escape(hnd, list2[i].in, list2[i].inlen); + abort_unless(out != NULL, "returned NULL!"); + + outlen = (int)strlen(out); + fail_unless(outlen == list2[i].outlen, "wrong output length returned"); + fail_unless(!memcmp(out, list2[i].out, list2[i].outlen), + "bad output data returned"); + + printf("curl_easy_escape test %d DONE (%s)\n", i, out); + + curl_free(out); + } +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1397.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1397.c new file mode 100644 index 0000000000000000000000000000000000000000..bf65d9231a4d2e18e681c11ed7cbeb640b4c909f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1397.c @@ -0,0 +1,124 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +/* only these backends define the tested functions */ +#if defined(USE_OPENSSL) || defined(USE_SCHANNEL) +#include "vtls/hostcheck.h" +struct testcase { + const char *host; + const char *pattern; + bool match; +}; + +static struct testcase tests[] = { + {"", "", FALSE}, + {"a", "", FALSE}, + {"", "b", FALSE}, + {"a", "b", FALSE}, + {"aa", "bb", FALSE}, + {"\xff", "\xff", TRUE}, + {"aa.aa.aa", "aa.aa.bb", FALSE}, + {"aa.aa.aa", "aa.aa.aa", TRUE}, + {"aa.aa.aa", "*.aa.bb", FALSE}, + {"aa.aa.aa", "*.aa.aa", TRUE}, + {"192.168.0.1", "192.168.0.1", TRUE}, + {"192.168.0.1", "*.168.0.1", FALSE}, + {"192.168.0.1", "*.0.1", FALSE}, + {"h.ello", "*.ello", FALSE}, + {"h.ello.", "*.ello", FALSE}, + {"h.ello", "*.ello.", FALSE}, + {"h.e.llo", "*.e.llo", TRUE}, + {"h.e.llo", " *.e.llo", FALSE}, + {" h.e.llo", "*.e.llo", TRUE}, + {"h.e.llo.", "*.e.llo", TRUE}, + {"*.e.llo.", "*.e.llo", TRUE}, + {"************.e.llo.", "*.e.llo", TRUE}, + {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + ".e.llo.", "*.e.llo", TRUE}, + {"\xfe\xfe.e.llo.", "*.e.llo", TRUE}, + {"h.e.llo.", "*.e.llo.", TRUE}, + {"h.e.llo", "*.e.llo.", TRUE}, + {".h.e.llo", "*.e.llo.", FALSE}, + {"h.e.llo", "*.*.llo.", FALSE}, + {"h.e.llo", "h.*.llo", FALSE}, + {"h.e.llo", "h.e.*", FALSE}, + {"hello", "*.ello", FALSE}, + {"hello", "**llo", FALSE}, + {"bar.foo.example.com", "*.example.com", FALSE}, + {"foo.example.com", "*.example.com", TRUE}, + {"baz.example.net", "b*z.example.net", FALSE}, + {"foobaz.example.net", "*baz.example.net", FALSE}, + {"xn--l8j.example.local", "x*.example.local", FALSE}, + {"xn--l8j.example.net", "*.example.net", TRUE}, + {"xn--l8j.example.net", "*j.example.net", FALSE}, + {"xn--l8j.example.net", "xn--l8j.example.net", TRUE}, + {"xn--l8j.example.net", "xn--l8j.*.net", FALSE}, + {"xl8j.example.net", "*.example.net", TRUE}, + {"fe80::3285:a9ff:fe46:b619", "*::3285:a9ff:fe46:b619", FALSE}, + {"fe80::3285:a9ff:fe46:b619", "fe80::3285:a9ff:fe46:b619", TRUE}, + {NULL, NULL, FALSE} +}; + +UNITTEST_START +{ + int i; + for(i = 0; tests[i].host; i++) { + if(tests[i].match != Curl_cert_hostcheck(tests[i].pattern, + strlen(tests[i].pattern), + tests[i].host, + strlen(tests[i].host))) { + fprintf(stderr, + "HOST: %s\n" + "PTRN: %s\n" + "did %sMATCH\n", + tests[i].host, + tests[i].pattern, + tests[i].match ? "NOT ": ""); + unitfail++; + } + } +} + +UNITTEST_STOP +#else + +UNITTEST_START + +UNITTEST_STOP +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1398.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1398.c new file mode 100644 index 0000000000000000000000000000000000000000..3e70309b4bbf7d5b93973d16f7de6092fd32e0a3 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1398.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat" +#endif + +static CURLcode unit_setup(void) {return CURLE_OK;} +static void unit_stop(void) {} + +UNITTEST_START + +int rc; +char buf[3] = {'b', 'u', 'g'}; +const char *str = "bug"; +int width = 3; +char output[130]; + +/*#define curl_msnprintf snprintf */ + +/* without a trailing zero */ +rc = curl_msnprintf(output, 4, "%.*s", width, buf); +fail_unless(rc == 3, "return code should be 3"); +fail_unless(!strcmp(output, "bug"), "wrong output"); + +/* with a trailing zero */ +rc = curl_msnprintf(output, 4, "%.*s", width, str); +fail_unless(rc == 3, "return code should be 3"); +fail_unless(!strcmp(output, "bug"), "wrong output"); + +width = 2; +/* one byte less */ +rc = curl_msnprintf(output, 4, "%.*s", width, buf); +fail_unless(rc == 2, "return code should be 2"); +fail_unless(!strcmp(output, "bu"), "wrong output"); + +/* string with larger precision */ +rc = curl_msnprintf(output, 8, "%.8s", str); +fail_unless(rc == 3, "return code should be 3"); +fail_unless(!strcmp(output, "bug"), "wrong output"); + +/* longer string with precision */ +rc = curl_msnprintf(output, 8, "%.3s", "0123456789"); +fail_unless(rc == 3, "return code should be 3"); +fail_unless(!strcmp(output, "012"), "wrong output"); + +/* negative width */ +rc = curl_msnprintf(output, 8, "%-8s", str); +fail_unless(rc == 7, "return code should be 7"); +fail_unless(!strcmp(output, "bug "), "wrong output"); + +/* larger width that string length */ +rc = curl_msnprintf(output, 8, "%8s", str); +fail_unless(rc == 7, "return code should be 7"); +fail_unless(!strcmp(output, " bu"), "wrong output"); + +/* output a number in a limited output */ +rc = curl_msnprintf(output, 4, "%d", 10240); +fail_unless(rc == 3, "return code should be 3"); +fail_unless(!strcmp(output, "102"), "wrong output"); + +/* padded strings */ +rc = curl_msnprintf(output, 16, "%8s%8s", str, str); +fail_unless(rc == 15, "return code should be 15"); +fail_unless(!strcmp(output, " bug bu"), "wrong output"); + +/* padded numbers */ +rc = curl_msnprintf(output, 16, "%8d%8d", 1234, 5678); +fail_unless(rc == 15, "return code should be 15"); +fail_unless(!strcmp(output, " 1234 567"), "wrong output"); + +/* double precision */ +rc = curl_msnprintf(output, 24, "%2$.*1$.99d", 3, 5678); +fail_unless(rc == 0, "return code should be 0"); + +/* 129 input % flags */ +rc = curl_msnprintf(output, 130, + "%s%s%s%s%s%s%s%s%s%s" /* 10 */ + "%s%s%s%s%s%s%s%s%s%s" /* 20 */ + "%s%s%s%s%s%s%s%s%s%s" /* 30 */ + "%s%s%s%s%s%s%s%s%s%s" /* 40 */ + "%s%s%s%s%s%s%s%s%s%s" /* 50 */ + "%s%s%s%s%s%s%s%s%s%s" /* 60 */ + "%s%s%s%s%s%s%s%s%s%s" /* 70 */ + "%s%s%s%s%s%s%s%s%s%s" /* 80 */ + "%s%s%s%s%s%s%s%s%s%s" /* 90 */ + "%s%s%s%s%s%s%s%s%s%s" /* 100 */ + "%s%s%s%s%s%s%s%s%s%s" /* 110 */ + "%s%s%s%s%s%s%s%s%s%s" /* 120 */ + "%s%s%s%s%s%s%s%s%s", /* 129 */ + + "a", "", "", "", "", "", "", "", "", "", /* 10 */ + "b", "", "", "", "", "", "", "", "", "", /* 20 */ + "c", "", "", "", "", "", "", "", "", "", /* 30 */ + "d", "", "", "", "", "", "", "", "", "", /* 40 */ + "e", "", "", "", "", "", "", "", "", "", /* 50 */ + "f", "", "", "", "", "", "", "", "", "", /* 60 */ + "g", "", "", "", "", "", "", "", "", "", /* 70 */ + "h", "", "", "", "", "", "", "", "", "", /* 80 */ + "i", "", "", "", "", "", "", "", "", "", /* 90 */ + "j", "", "", "", "", "", "", "", "", "", /* 100 */ + "k", "", "", "", "", "", "", "", "", "", /* 110 */ + "l", "", "", "", "", "", "", "", "", "", /* 120 */ + "m", "", "", "", "", "", "", "", "" /* 129 */ + ); +fail_unless(rc == 0, "return code should be 0"); + +/* 128 input % flags */ +rc = curl_msnprintf(output, 130, + "%s%s%s%s%s%s%s%s%s%s" /* 10 */ + "%s%s%s%s%s%s%s%s%s%s" /* 20 */ + "%s%s%s%s%s%s%s%s%s%s" /* 30 */ + "%s%s%s%s%s%s%s%s%s%s" /* 40 */ + "%s%s%s%s%s%s%s%s%s%s" /* 50 */ + "%s%s%s%s%s%s%s%s%s%s" /* 60 */ + "%s%s%s%s%s%s%s%s%s%s" /* 70 */ + "%s%s%s%s%s%s%s%s%s%s" /* 80 */ + "%s%s%s%s%s%s%s%s%s%s" /* 90 */ + "%s%s%s%s%s%s%s%s%s%s" /* 100 */ + "%s%s%s%s%s%s%s%s%s%s" /* 110 */ + "%s%s%s%s%s%s%s%s%s%s" /* 120 */ + "%s%s%s%s%s%s%s%s", /* 128 */ + + "a", "", "", "", "", "", "", "", "", "", /* 10 */ + "b", "", "", "", "", "", "", "", "", "", /* 20 */ + "c", "", "", "", "", "", "", "", "", "", /* 30 */ + "d", "", "", "", "", "", "", "", "", "", /* 40 */ + "e", "", "", "", "", "", "", "", "", "", /* 50 */ + "f", "", "", "", "", "", "", "", "", "", /* 60 */ + "g", "", "", "", "", "", "", "", "", "", /* 70 */ + "h", "", "", "", "", "", "", "", "", "", /* 80 */ + "i", "", "", "", "", "", "", "", "", "", /* 90 */ + "j", "", "", "", "", "", "", "", "", "", /* 100 */ + "k", "", "", "", "", "", "", "", "", "", /* 110 */ + "l", "", "", "", "", "", "", "", "", "", /* 120 */ + "m", "", "", "", "", "", "", "" /* 128 */ + ); +fail_unless(rc == 13, "return code should be 13"); + +/* 129 output segments */ +rc = curl_msnprintf(output, 130, + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 20 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 40 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 60 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 80 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 100 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 120 */ + "%%%%%%%%%%%%%%%%%%" /* 129 */ + ); +fail_unless(rc == 0, "return code should be 0"); + +/* 128 output segments */ +rc = curl_msnprintf(output, 129, + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 20 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 40 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 60 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 80 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 100 */ + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" /* 120 */ + "%%%%%%%%%%%%%%%%" /* 128 */ + ); +fail_unless(rc == 128, "return code should be 128"); + +UNITTEST_STOP + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1399.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1399.c new file mode 100644 index 0000000000000000000000000000000000000000..6e886d45e5254e03dc2448f36b819e81b30a632d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1399.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "progress.h" + +static int usec_magnitude = 1000000; + +static bool unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +/* + * Invoke Curl_pgrsTime for TIMER_STARTSINGLE to trigger the behavior that + * manages is_t_startransfer_set, but fake the t_startsingle time for purposes + * of the test. + */ +static void fake_t_startsingle_time(struct Curl_easy *data, + struct curltime fake_now, + int seconds_offset) +{ + Curl_pgrsTime(data, TIMER_STARTSINGLE); + data->progress.t_startsingle.tv_sec = fake_now.tv_sec + seconds_offset; + data->progress.t_startsingle.tv_usec = fake_now.tv_usec; +} + +static bool usec_matches_seconds(timediff_t time_usec, int expected_seconds) +{ + int time_sec = (int)(time_usec / usec_magnitude); + bool same = (time_sec == expected_seconds); + fprintf(stderr, "is %d us same as %d seconds? %s\n", + (int)time_usec, expected_seconds, + same ? "Yes" : "No"); + return same; +} + +static void expect_timer_seconds(struct Curl_easy *data, int seconds) +{ + char msg[64]; + msnprintf(msg, sizeof(msg), "about %d seconds should have passed", seconds); + fail_unless(usec_matches_seconds(data->progress.t_nslookup, seconds), msg); + fail_unless(usec_matches_seconds(data->progress.t_connect, seconds), msg); + fail_unless(usec_matches_seconds(data->progress.t_appconnect, seconds), msg); + fail_unless(usec_matches_seconds(data->progress.t_pretransfer, seconds), + msg); + fail_unless(usec_matches_seconds(data->progress.t_starttransfer, seconds), + msg); +} + +/* Scenario: simulate a redirect. When a redirect occurs, t_nslookup, + * t_connect, t_appconnect, t_pretransfer, and t_starttransfer are additive. + * E.g., if t_starttransfer took 2 seconds initially and took another 1 + * second for the redirect request, then the resulting t_starttransfer should + * be 3 seconds. */ +UNITTEST_START + struct Curl_easy data; + struct curltime now = Curl_now(); + + data.progress.t_nslookup = 0; + data.progress.t_connect = 0; + data.progress.t_appconnect = 0; + data.progress.t_pretransfer = 0; + data.progress.t_starttransfer = 0; + data.progress.t_redirect = 0; + data.progress.start.tv_sec = now.tv_sec - 2; + data.progress.start.tv_usec = now.tv_usec; + fake_t_startsingle_time(&data, now, -2); + + Curl_pgrsTime(&data, TIMER_NAMELOOKUP); + Curl_pgrsTime(&data, TIMER_CONNECT); + Curl_pgrsTime(&data, TIMER_APPCONNECT); + Curl_pgrsTime(&data, TIMER_PRETRANSFER); + Curl_pgrsTime(&data, TIMER_STARTTRANSFER); + + expect_timer_seconds(&data, 2); + + /* now simulate the redirect */ + data.progress.t_redirect = data.progress.t_starttransfer + 1; + fake_t_startsingle_time(&data, now, -1); + + Curl_pgrsTime(&data, TIMER_NAMELOOKUP); + Curl_pgrsTime(&data, TIMER_CONNECT); + Curl_pgrsTime(&data, TIMER_APPCONNECT); + Curl_pgrsTime(&data, TIMER_PRETRANSFER); + /* ensure t_starttransfer is only set on the first invocation by attempting + * to set it twice */ + Curl_pgrsTime(&data, TIMER_STARTTRANSFER); + Curl_pgrsTime(&data, TIMER_STARTTRANSFER); + + expect_timer_seconds(&data, 3); +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1600.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1600.c new file mode 100644 index 0000000000000000000000000000000000000000..ee36c5e65cec81abd6a53588617a403dfcfecfd7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1600.c @@ -0,0 +1,75 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "curl_ntlm_core.h" + +static CURL *easy; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(easy); + curl_global_cleanup(); +} + +UNITTEST_START + +#if defined(USE_NTLM) && (!defined(USE_WINDOWS_SSPI) || \ + defined(USE_WIN32_CRYPTO)) + unsigned char output[21]; + unsigned char *testp = output; + Curl_ntlm_core_mk_nt_hash("1", output); + + verify_memory(testp, + "\x69\x94\x3c\x5e\x63\xb4\xd2\xc1\x04\xdb" + "\xbc\xc1\x51\x38\xb7\x2b\x00\x00\x00\x00\x00", 21); + + Curl_ntlm_core_mk_nt_hash("hello-you-fool", output); + + verify_memory(testp, + "\x39\xaf\x87\xa6\x75\x0a\x7a\x00\xba\xa0" + "\xd3\x4f\x04\x9e\xc1\xd0\x00\x00\x00\x00\x00", 21); + +/* !checksrc! disable LONGLINE 2 */ + Curl_ntlm_core_mk_nt_hash("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", output); + + verify_memory(testp, + "\x36\x9d\xae\x06\x84\x7e\xe1\xc1\x4a\x94\x39\xea\x6f\x44\x8c\x65\x00\x00\x00\x00\x00", 21); +#endif + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1601.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1601.c new file mode 100644 index 0000000000000000000000000000000000000000..4623bb7769bd8d1176e7c9f1e304aaf557dda3c9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1601.c @@ -0,0 +1,60 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "curl_md5.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +UNITTEST_START + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + + const char string1[] = "1"; + const char string2[] = "hello-you-fool"; + unsigned char output[MD5_DIGEST_LEN]; + unsigned char *testp = output; + + Curl_md5it(output, (const unsigned char *) string1, strlen(string1)); + + verify_memory(testp, "\xc4\xca\x42\x38\xa0\xb9\x23\x82\x0d\xcc\x50\x9a\x6f" + "\x75\x84\x9b", MD5_DIGEST_LEN); + + Curl_md5it(output, (const unsigned char *) string2, strlen(string2)); + + verify_memory(testp, "\x88\x67\x0b\x6d\x5d\x74\x2f\xad\xa5\xcd\xf9\xb6\x82" + "\x87\x5f\x22", MD5_DIGEST_LEN); +#endif + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1602.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1602.c new file mode 100644 index 0000000000000000000000000000000000000000..4c7b794ab8389f0ede7975285ff0e0cc9b445c9d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1602.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 "curlcheck.h" + +#include "curlx.h" + +#include "hash.h" + +#include "memdebug.h" /* LAST include file */ + +static struct Curl_hash hash_static; + +static void mydtor(void *p) +{ + int *ptr = (int *)p; + free(ptr); +} + +static CURLcode unit_setup(void) +{ + Curl_hash_init(&hash_static, 7, Curl_hash_str, + Curl_str_key_compare, mydtor); + return CURLE_OK; +} + +static void unit_stop(void) +{ + Curl_hash_destroy(&hash_static); +} + +UNITTEST_START + int *value; + int *value2; + int *nodep; + size_t klen = sizeof(int); + + int key = 20; + int key2 = 25; + + + value = malloc(sizeof(int)); + abort_unless(value != NULL, "Out of memory"); + *value = 199; + nodep = Curl_hash_add(&hash_static, &key, klen, value); + if(!nodep) + free(value); + abort_unless(nodep, "insertion into hash failed"); + Curl_hash_clean(&hash_static); + + /* Attempt to add another key/value pair */ + value2 = malloc(sizeof(int)); + abort_unless(value2 != NULL, "Out of memory"); + *value2 = 204; + nodep = Curl_hash_add(&hash_static, &key2, klen, value2); + if(!nodep) + free(value2); + abort_unless(nodep, "insertion into hash failed"); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1603.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1603.c new file mode 100644 index 0000000000000000000000000000000000000000..46492424c565a694bf61dfec8786b24a8e8d82f7 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1603.c @@ -0,0 +1,178 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "curlx.h" + +#include "hash.h" + +#include "memdebug.h" /* LAST include file */ + +static struct Curl_hash hash_static; +static const size_t slots = 3; + +static void mydtor(void *p) +{ + /* Data are statically allocated */ + (void)p; /* unused */ +} + +static size_t elem_dtor_calls; + +static void my_elem_dtor(void *key, size_t key_len, void *p) +{ + (void)p; /* unused */ + (void)key; /* unused */ + (void)key_len; /* unused */ + ++elem_dtor_calls; +} + +static CURLcode unit_setup(void) +{ + Curl_hash_init(&hash_static, slots, Curl_hash_str, + Curl_str_key_compare, mydtor); + return CURLE_OK; +} + +static void unit_stop(void) +{ + Curl_hash_destroy(&hash_static); +} + +UNITTEST_START + char key1[] = "key1"; + char key2[] = "key2b"; + char key3[] = "key3"; + char key4[] = "key4"; + char notakey[] = "notakey"; + char *nodep; + int rc; + + /* Ensure the key hashes are as expected in order to test both hash + collisions and a full table. Unfortunately, the hashes can vary + between architectures. */ + if(Curl_hash_str(key1, strlen(key1), slots) != 1 || + Curl_hash_str(key2, strlen(key2), slots) != 0 || + Curl_hash_str(key3, strlen(key3), slots) != 2 || + Curl_hash_str(key4, strlen(key4), slots) != 1) + fprintf(stderr, "Warning: hashes are not computed as expected on this " + "architecture; test coverage will be less comprehensive\n"); + + nodep = Curl_hash_add(&hash_static, &key1, strlen(key1), &key1); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(nodep == key1, "hash retrieval failed"); + + nodep = Curl_hash_add(&hash_static, &key2, strlen(key2), &key2); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key2, strlen(key2)); + fail_unless(nodep == key2, "hash retrieval failed"); + + nodep = Curl_hash_add(&hash_static, &key3, strlen(key3), &key3); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key3, strlen(key3)); + fail_unless(nodep == key3, "hash retrieval failed"); + + /* The fourth element exceeds the number of slots & collides */ + nodep = Curl_hash_add(&hash_static, &key4, strlen(key4), &key4); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(nodep == key4, "hash retrieval failed"); + + /* Make sure all elements are still accessible */ + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(nodep == key1, "hash retrieval failed"); + nodep = Curl_hash_pick(&hash_static, &key2, strlen(key2)); + fail_unless(nodep == key2, "hash retrieval failed"); + nodep = Curl_hash_pick(&hash_static, &key3, strlen(key3)); + fail_unless(nodep == key3, "hash retrieval failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(nodep == key4, "hash retrieval failed"); + + /* Delete the second of two entries in a bucket */ + rc = Curl_hash_delete(&hash_static, &key4, strlen(key4)); + fail_unless(rc == 0, "hash delete failed"); + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(nodep == key1, "hash retrieval failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(!nodep, "hash retrieval should have failed"); + + /* Insert that deleted node again */ + nodep = Curl_hash_add(&hash_static, &key4, strlen(key4), &key4); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(nodep == key4, "hash retrieval failed"); + + /* Delete the first of two entries in a bucket */ + rc = Curl_hash_delete(&hash_static, &key1, strlen(key1)); + fail_unless(rc == 0, "hash delete failed"); + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(!nodep, "hash retrieval should have failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(nodep == key4, "hash retrieval failed"); + + /* Delete the remaining one of two entries in a bucket */ + rc = Curl_hash_delete(&hash_static, &key4, strlen(key4)); + fail_unless(rc == 0, "hash delete failed"); + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(!nodep, "hash retrieval should have failed"); + nodep = Curl_hash_pick(&hash_static, &key4, strlen(key4)); + fail_unless(!nodep, "hash retrieval should have failed"); + + /* Delete an already deleted node */ + rc = Curl_hash_delete(&hash_static, &key4, strlen(key4)); + fail_unless(rc, "hash delete should have failed"); + + /* Replace an existing node */ + nodep = Curl_hash_add(&hash_static, &key1, strlen(key1), ¬akey); + fail_unless(nodep, "insertion into hash failed"); + nodep = Curl_hash_pick(&hash_static, &key1, strlen(key1)); + fail_unless(nodep == notakey, "hash retrieval failed"); + + /* Make sure all remaining elements are still accessible */ + nodep = Curl_hash_pick(&hash_static, &key2, strlen(key2)); + fail_unless(nodep == key2, "hash retrieval failed"); + nodep = Curl_hash_pick(&hash_static, &key3, strlen(key3)); + fail_unless(nodep == key3, "hash retrieval failed"); + + /* Add element with own destructor */ + nodep = Curl_hash_add2(&hash_static, &key1, strlen(key1), &key1, + my_elem_dtor); + fail_unless(nodep, "add2 insertion into hash failed"); + fail_unless(elem_dtor_calls == 0, "element destructor count should be 0"); + /* Add it again, should invoke destructor on first */ + nodep = Curl_hash_add2(&hash_static, &key1, strlen(key1), &key1, + my_elem_dtor); + fail_unless(nodep, "add2 again, insertion into hash failed"); + fail_unless(elem_dtor_calls == 1, "element destructor count should be 1"); + /* remove, should invoke destructor */ + rc = Curl_hash_delete(&hash_static, &key1, strlen(key1)); + fail_unless(rc == 0, "hash delete failed"); + fail_unless(elem_dtor_calls == 2, "element destructor count should be 1"); + + + /* Clean up */ + Curl_hash_clean(&hash_static); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1604.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1604.c new file mode 100644 index 0000000000000000000000000000000000000000..690779202377cd64f5177d4ffa2fc3c9915b5689 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1604.c @@ -0,0 +1,268 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "tool_cfgable.h" +#include "tool_doswin.h" + +#include +#include +#include + +#include "memdebug.h" /* LAST include file */ + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +#if defined(_WIN32) || defined(MSDOS) + +static char *getflagstr(int flags) +{ + char *buf = malloc(256); + if(buf) { + msnprintf(buf, 256, "%s,%s", + ((flags & SANITIZE_ALLOW_PATH) ? + "SANITIZE_ALLOW_PATH" : ""), + ((flags & SANITIZE_ALLOW_RESERVED) ? + "SANITIZE_ALLOW_RESERVED" : "")); + } + return buf; +} + +static char *getcurlcodestr(int cc) +{ + char *buf = malloc(256); + if(buf) { + msnprintf(buf, 256, "%s (%d)", + (cc == SANITIZE_ERR_OK ? "SANITIZE_ERR_OK" : + cc == SANITIZE_ERR_BAD_ARGUMENT ? "SANITIZE_ERR_BAD_ARGUMENT" : + cc == SANITIZE_ERR_INVALID_PATH ? "SANITIZE_ERR_INVALID_PATH" : + cc == SANITIZE_ERR_OUT_OF_MEMORY ? "SANITIZE_ERR_OUT_OF_MEMORY": + "unexpected error code - add name"), + cc); + } + return buf; +} + +struct data { + const char *input; + int flags; + const char *expected_output; + SANITIZEcode expected_result; +}; + +UNITTEST_START +{ /* START sanitize_file_name */ + struct data data[] = { + { "", 0, + "", SANITIZE_ERR_OK + }, + { "normal filename", 0, + "normal filename", SANITIZE_ERR_OK + }, + { "control\tchar", 0, + "control_char", SANITIZE_ERR_OK + }, + { "banned*char", 0, + "banned_char", SANITIZE_ERR_OK + }, + { "f:foo", 0, + "f_foo", SANITIZE_ERR_OK + }, + { "f:foo", SANITIZE_ALLOW_PATH, + "f:foo", SANITIZE_ERR_OK + }, + { "f:\\foo", 0, + "f__foo", SANITIZE_ERR_OK + }, + { "f:\\foo", SANITIZE_ALLOW_PATH, + "f:\\foo", SANITIZE_ERR_OK + }, + { "f:/foo", 0, + "f__foo", SANITIZE_ERR_OK + }, + { "f:/foo", SANITIZE_ALLOW_PATH, + "f:/foo", SANITIZE_ERR_OK + }, +#ifndef MSDOS + { "\\\\?\\C:\\foo", SANITIZE_ALLOW_PATH, + "\\\\?\\C:\\foo", SANITIZE_ERR_OK + }, + { "\\\\?\\C:\\foo", 0, + "____C__foo", SANITIZE_ERR_OK + }, +#endif + { "foo:bar", 0, + "foo_bar", SANITIZE_ERR_OK + }, + { "foo|<>/bar\\\":?*baz", 0, + "foo____bar_____baz", SANITIZE_ERR_OK + }, + { "f:foo::$DATA", 0, + "f_foo__$DATA", SANITIZE_ERR_OK + }, + { "con . air", 0, + "con _ air", SANITIZE_ERR_OK + }, + { "con.air", 0, + "con_air", SANITIZE_ERR_OK + }, + { "con:/x", 0, + "con__x", SANITIZE_ERR_OK + }, + { "file . . . . .. .", 0, + "file", SANITIZE_ERR_OK + }, + { "foo . . ? . . ", 0, + "foo . . _", SANITIZE_ERR_OK + }, + { "com1", 0, + "_com1", SANITIZE_ERR_OK + }, + { "com1", SANITIZE_ALLOW_RESERVED, + "com1", SANITIZE_ERR_OK + }, + { "f:\\com1", 0, + "f__com1", SANITIZE_ERR_OK + }, + { "f:\\com1", SANITIZE_ALLOW_PATH, + "f:\\_com1", SANITIZE_ERR_OK + }, + { "f:\\com1", SANITIZE_ALLOW_RESERVED, + "f__com1", SANITIZE_ERR_OK + }, + { "f:\\com1", SANITIZE_ALLOW_RESERVED | SANITIZE_ALLOW_PATH, + "f:\\com1", SANITIZE_ERR_OK + }, + { "com1:\\com1", SANITIZE_ALLOW_PATH, + "_com1:\\_com1", SANITIZE_ERR_OK + }, + { "com1:\\com1", SANITIZE_ALLOW_RESERVED | SANITIZE_ALLOW_PATH, + "com1:\\com1", SANITIZE_ERR_OK + }, + { "com1:\\com1", SANITIZE_ALLOW_RESERVED, + "com1__com1", SANITIZE_ERR_OK + }, +#ifndef MSDOS + { "\\com1", SANITIZE_ALLOW_PATH, + "\\_com1", SANITIZE_ERR_OK + }, + { "\\\\com1", SANITIZE_ALLOW_PATH, + "\\\\com1", SANITIZE_ERR_OK + }, + { "\\\\?\\C:\\com1", SANITIZE_ALLOW_PATH, + "\\\\?\\C:\\com1", SANITIZE_ERR_OK + }, +#endif + { "CoM1", 0, + "_CoM1", SANITIZE_ERR_OK + }, + { "CoM1", SANITIZE_ALLOW_RESERVED, + "CoM1", SANITIZE_ERR_OK + }, + { "COM56", 0, + "COM56", SANITIZE_ERR_OK + }, + /* At the moment we expect a maximum path length of 259. I assume MS-DOS + has variable max path lengths depending on compiler that are shorter + so currently these "good" truncate tests will not run on MS-DOS */ + { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD" + "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + 0, + NULL, SANITIZE_ERR_INVALID_PATH + }, + { NULL, 0, + NULL, SANITIZE_ERR_BAD_ARGUMENT + }, + }; + + size_t i; + + for(i = 0; i < sizeof(data) / sizeof(data[0]); ++i) { + char *output = NULL; + char *flagstr = NULL; + char *received_ccstr = NULL; + char *expected_ccstr = NULL; + SANITIZEcode res; + + res = sanitize_file_name(&output, data[i].input, data[i].flags); + + if(res == data[i].expected_result && + ((!output && !data[i].expected_output) || + (output && data[i].expected_output && + !strcmp(output, data[i].expected_output)))) { /* OK */ + free(output); + continue; + } + + flagstr = getflagstr(data[i].flags); + abort_unless(flagstr, "out of memory"); + received_ccstr = getcurlcodestr(res); + abort_unless(received_ccstr, "out of memory"); + expected_ccstr = getcurlcodestr(data[i].expected_result); + abort_unless(expected_ccstr, "out of memory"); + + unitfail++; + fprintf(stderr, "\n" + "%s:%d sanitize_file_name failed.\n" + "input: %s\n" + "flags: %s\n" + "output: %s\n" + "result: %s\n" + "expected output: %s\n" + "expected result: %s\n", + __FILE__, __LINE__, + data[i].input, + flagstr, + (output ? output : "(null)"), + received_ccstr, + (data[i].expected_output ? data[i].expected_output : "(null)"), + expected_ccstr); + + free(output); + free(flagstr); + free(received_ccstr); + free(expected_ccstr); + } +} /* END sanitize_file_name */ + +#else +UNITTEST_START +{ + fprintf(stderr, "Skipped test not for this platform\n"); +} +#endif /* _WIN32 || MSDOS */ + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1605.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1605.c new file mode 100644 index 0000000000000000000000000000000000000000..d0006d2b5f00f9d980cb8068f0ff09febcd807fd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1605.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#include "llist.h" + +static CURL *easy; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(easy); + curl_global_cleanup(); +} + +UNITTEST_START + int len; + char *esc; + + esc = curl_easy_escape(easy, "", -1); + fail_unless(esc == NULL, "negative string length can't work"); + + esc = curl_easy_unescape(easy, "%41%41%41%41", -1, &len); + fail_unless(esc == NULL, "negative string length can't work"); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1606.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1606.c new file mode 100644 index 0000000000000000000000000000000000000000..b7f557d6898f577905c5c466c2bee2106a19eb7f --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1606.c @@ -0,0 +1,93 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "speedcheck.h" +#include "urldata.h" + +static struct Curl_easy *easy; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(easy); + curl_global_cleanup(); +} + +static int runawhile(long time_limit, + long speed_limit, + curl_off_t speed, + int dec) +{ + int counter = 1; + struct curltime now = {1, 0}; + CURLcode result; + int finaltime; + + curl_easy_setopt(easy, CURLOPT_LOW_SPEED_LIMIT, speed_limit); + curl_easy_setopt(easy, CURLOPT_LOW_SPEED_TIME, time_limit); + Curl_speedinit(easy); + + do { + /* fake the current transfer speed */ + easy->progress.current_speed = speed; + result = Curl_speedcheck(easy, now); + if(result) + break; + /* step the time */ + now.tv_sec = ++counter; + speed -= dec; + } while(counter < 100); + + finaltime = (int)(now.tv_sec - 1); + + return finaltime; +} + +UNITTEST_START + fail_unless(runawhile(41, 41, 40, 0) == 41, + "wrong low speed timeout"); + fail_unless(runawhile(21, 21, 20, 0) == 21, + "wrong low speed timeout"); + fail_unless(runawhile(60, 60, 40, 0) == 60, + "wrong log speed timeout"); + fail_unless(runawhile(50, 50, 40, 0) == 50, + "wrong log speed timeout"); + fail_unless(runawhile(40, 40, 40, 0) == 99, + "should not time out"); + fail_unless(runawhile(10, 50, 100, 2) == 36, + "bad timeout"); +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1607.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1607.c new file mode 100644 index 0000000000000000000000000000000000000000..ecc1fc931e5fa4e34632c5bbcfe8ee602cf999ac --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1607.c @@ -0,0 +1,235 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "connect.h" +#include "share.h" + +#include "memdebug.h" /* LAST include file */ + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + return res; +} + +struct testcase { + /* host:port:address[,address]... */ + const char *optval; + + /* lowercase host and port to retrieve the addresses from hostcache */ + const char *host; + int port; + + /* whether we expect a permanent or non-permanent cache entry */ + bool permanent; + + /* 0 to 9 addresses expected from hostcache */ + const char *address[10]; +}; + + +/* In builds without IPv6 support CURLOPT_RESOLVE should skip over those + addresses, so we have to do that as well. */ +static const char skip = 0; +#ifdef USE_IPV6 +#define IPV6ONLY(x) x +#else +#define IPV6ONLY(x) &skip +#endif + +/* CURLOPT_RESOLVE address parsing tests */ +static const struct testcase tests[] = { + /* spaces aren't allowed, for now */ + { "test.com:80:127.0.0.1, 127.0.0.2", + "test.com", 80, TRUE, { NULL, } + }, + { "TEST.com:80:,,127.0.0.1,,,127.0.0.2,,,,::1,,,", + "test.com", 80, TRUE, { "127.0.0.1", "127.0.0.2", IPV6ONLY("::1"), } + }, + { "test.com:80:::1,127.0.0.1", + "test.com", 80, TRUE, { IPV6ONLY("::1"), "127.0.0.1", } + }, + { "test.com:80:[::1],127.0.0.1", + "test.com", 80, TRUE, { IPV6ONLY("::1"), "127.0.0.1", } + }, + { "test.com:80:::1", + "test.com", 80, TRUE, { IPV6ONLY("::1"), } + }, + { "test.com:80:[::1]", + "test.com", 80, TRUE, { IPV6ONLY("::1"), } + }, + { "test.com:80:127.0.0.1", + "test.com", 80, TRUE, { "127.0.0.1", } + }, + { "test.com:80:,127.0.0.1", + "test.com", 80, TRUE, { "127.0.0.1", } + }, + { "test.com:80:127.0.0.1,", + "test.com", 80, TRUE, { "127.0.0.1", } + }, + { "test.com:0:127.0.0.1", + "test.com", 0, TRUE, { "127.0.0.1", } + }, + { "+test.com:80:127.0.0.1,", + "test.com", 80, FALSE, { "127.0.0.1", } + }, +}; + +UNITTEST_START +{ + int i; + int testnum = sizeof(tests) / sizeof(struct testcase); + struct Curl_multi *multi = NULL; + struct Curl_easy *easy = NULL; + struct curl_slist *list = NULL; + + for(i = 0; i < testnum; ++i) { + int j; + int addressnum = sizeof(tests[i].address) / sizeof(*tests[i].address); + struct Curl_addrinfo *addr; + struct Curl_dns_entry *dns; + void *entry_id; + bool problem = false; + easy = curl_easy_init(); + if(!easy) + goto error; + + /* create a multi handle and add the easy handle to it so that the + hostcache is setup */ + multi = curl_multi_init(); + curl_multi_add_handle(multi, easy); + + list = curl_slist_append(NULL, tests[i].optval); + if(!list) + goto error; + curl_easy_setopt(easy, CURLOPT_RESOLVE, list); + + Curl_loadhostpairs(easy); + + entry_id = (void *)aprintf("%s:%d", tests[i].host, tests[i].port); + if(!entry_id) + goto error; + dns = Curl_hash_pick(easy->dns.hostcache, entry_id, strlen(entry_id) + 1); + free(entry_id); + entry_id = NULL; + + addr = dns ? dns->addr : NULL; + + for(j = 0; j < addressnum; ++j) { + int port = 0; + char ipaddress[MAX_IPADR_LEN] = {0}; + + if(!addr && !tests[i].address[j]) + break; + + if(tests[i].address[j] == &skip) + continue; + + if(addr && !Curl_addr2string(addr->ai_addr, addr->ai_addrlen, + ipaddress, &port)) { + fprintf(stderr, "%s:%d tests[%d] failed. getaddressinfo failed.\n", + __FILE__, __LINE__, i); + problem = true; + break; + } + + if(addr && !tests[i].address[j]) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "is %s but tests[%d].address[%d] is NULL.\n", + __FILE__, __LINE__, i, ipaddress, i, j); + problem = true; + break; + } + + if(!addr && tests[i].address[j]) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "is NULL but tests[%d].address[%d] is %s.\n", + __FILE__, __LINE__, i, i, j, tests[i].address[j]); + problem = true; + break; + } + + if(!curl_strequal(ipaddress, tests[i].address[j])) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "%s is not equal to tests[%d].address[%d] %s.\n", + __FILE__, __LINE__, i, ipaddress, i, j, tests[i].address[j]); + problem = true; + break; + } + + if(port != tests[i].port) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved port " + "for tests[%d].address[%d] is %d but tests[%d].port is %d.\n", + __FILE__, __LINE__, i, i, j, port, i, tests[i].port); + problem = true; + break; + } + + if(dns->timestamp && tests[i].permanent) { + fprintf(stderr, "%s:%d tests[%d] failed. the timestamp is not zero " + "but tests[%d].permanent is TRUE\n", + __FILE__, __LINE__, i, i); + problem = true; + break; + } + + if(dns->timestamp == 0 && !tests[i].permanent) { + fprintf(stderr, "%s:%d tests[%d] failed. the timestamp is zero " + "but tests[%d].permanent is FALSE\n", + __FILE__, __LINE__, i, i); + problem = true; + break; + } + + addr = addr->ai_next; + } + + curl_easy_cleanup(easy); + easy = NULL; + curl_multi_cleanup(multi); + multi = NULL; + curl_slist_free_all(list); + list = NULL; + + if(problem) { + unitfail++; + continue; + } + } +error: + curl_easy_cleanup(easy); + curl_multi_cleanup(multi); + curl_slist_free_all(list); +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1608.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1608.c new file mode 100644 index 0000000000000000000000000000000000000000..f734b77885c250005c188fd88322ac300c952dcc --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1608.c @@ -0,0 +1,89 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "hostip.h" + +#ifndef CURL_DISABLE_SHUFFLE_DNS + +CURLcode Curl_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr); + +#define NUM_ADDRS 8 +static struct Curl_addrinfo addrs[NUM_ADDRS]; + +static CURLcode unit_setup(void) +{ + int i; + for(i = 0; i < NUM_ADDRS - 1; i++) { + addrs[i].ai_next = &addrs[i + 1]; + } + + return CURLE_OK; +} + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +UNITTEST_START + + int i; + CURLcode code; + struct Curl_addrinfo *addrhead = addrs; + + struct Curl_easy *easy = curl_easy_init(); + abort_unless(easy, "out of memory"); + + code = curl_easy_setopt(easy, CURLOPT_DNS_SHUFFLE_ADDRESSES, 1L); + abort_unless(code == CURLE_OK, "curl_easy_setopt failed"); + + /* Shuffle repeatedly and make sure that the list changes */ + for(i = 0; i < 10; i++) { + if(CURLE_OK != Curl_shuffle_addr(easy, &addrhead)) + break; + if(addrhead != addrs) + break; + } + + curl_easy_cleanup(easy); + curl_global_cleanup(); + + abort_unless(addrhead != addrs, "addresses are not being reordered"); + +UNITTEST_STOP + +#else +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} +static void unit_stop(void) +{ +} +UNITTEST_START +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1609.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1609.c new file mode 100644 index 0000000000000000000000000000000000000000..c902243f5953087c42aea9efebf8bfe42c5901d0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1609.c @@ -0,0 +1,219 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "connect.h" +#include "share.h" + +#include "memdebug.h" /* LAST include file */ + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + + return res; +} + +struct testcase { + /* host:port:address[,address]... */ + const char *optval; + + /* lowercase host and port to retrieve the addresses from hostcache */ + const char *host; + int port; + + /* 0 to 9 addresses expected from hostcache */ + const char *address[10]; +}; + + +/* CURLOPT_RESOLVE address parsing test - to test the following defect fix: + + 1) if there is already existing host:port pair in the DNS cache and + we call CURLOPT_RESOLVE, it should also replace addresses. + for example, if there is "test.com:80" with address "1.1.1.1" + and we called CURLOPT_RESOLVE with address "2.2.2.2", then DNS entry needs to + reflect that. + + 2) when cached address is already there and close to expire, then by the + time request is made, it can get expired. This happens because, when + we set address using CURLOPT_RESOLVE, + it usually marks as permanent (by setting timestamp to zero). However, + if address already exists +in the cache, then it does not mark it, but just leaves it as it is. + So we fixing this by timestamp to zero if address already exists too. + +Test: + + - insert new entry + - verify that timestamp is not zero + - call set options with CURLOPT_RESOLVE + - then, call Curl_loadhostpairs + + expected result: cached address has zero timestamp. + + - call set options with CURLOPT_RESOLVE with same host:port pair, + different address. + - then, call Curl_loadhostpairs + + expected result: cached address has zero timestamp and new address +*/ + +static const struct testcase tests[] = { + /* spaces aren't allowed, for now */ + { "test.com:80:127.0.0.1", + "test.com", 80, { "127.0.0.1", } + }, + { "test.com:80:127.0.0.2", + "test.com", 80, { "127.0.0.2", } + }, +}; + +UNITTEST_START +{ + int i; + int testnum = sizeof(tests) / sizeof(struct testcase); + struct Curl_multi *multi = NULL; + struct Curl_easy *easy = NULL; + struct curl_slist *list = NULL; + +/* important: we setup cache outside of the loop + and also clean cache after the loop. In contrast,for example, + test 1607 sets up and cleans cache on each iteration. */ + + for(i = 0; i < testnum; ++i) { + int j; + int addressnum = sizeof (tests[i].address) / sizeof (*tests[i].address); + struct Curl_addrinfo *addr; + struct Curl_dns_entry *dns; + void *entry_id; + bool problem = false; + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + /* create a multi handle and add the easy handle to it so that the + hostcache is setup */ + multi = curl_multi_init(); + if(!multi) + goto error; + curl_multi_add_handle(multi, easy); + + list = curl_slist_append(NULL, tests[i].optval); + if(!list) + goto error; + + curl_easy_setopt(easy, CURLOPT_RESOLVE, list); + + if(Curl_loadhostpairs(easy)) + goto error; + + entry_id = (void *)aprintf("%s:%d", tests[i].host, tests[i].port); + if(!entry_id) + goto error; + + dns = Curl_hash_pick(easy->dns.hostcache, entry_id, strlen(entry_id) + 1); + free(entry_id); + entry_id = NULL; + + addr = dns ? dns->addr : NULL; + + for(j = 0; j < addressnum; ++j) { + int port = 0; + char ipaddress[MAX_IPADR_LEN] = {0}; + + if(!addr && !tests[i].address[j]) + break; + + if(addr && !Curl_addr2string(addr->ai_addr, addr->ai_addrlen, + ipaddress, &port)) { + fprintf(stderr, "%s:%d tests[%d] failed. Curl_addr2string failed.\n", + __FILE__, __LINE__, i); + problem = true; + break; + } + + if(addr && !tests[i].address[j]) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "is %s but tests[%d].address[%d] is NULL.\n", + __FILE__, __LINE__, i, ipaddress, i, j); + problem = true; + break; + } + + if(!addr && tests[i].address[j]) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "is NULL but tests[%d].address[%d] is %s.\n", + __FILE__, __LINE__, i, i, j, tests[i].address[j]); + problem = true; + break; + } + + if(!curl_strequal(ipaddress, tests[i].address[j])) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " + "%s is not equal to tests[%d].address[%d] %s.\n", + __FILE__, __LINE__, i, ipaddress, i, j, tests[i].address[j]); + problem = true; + break; + } + + if(port != tests[i].port) { + fprintf(stderr, "%s:%d tests[%d] failed. the retrieved port " + "for tests[%d].address[%d] is %d but tests[%d].port is %d.\n", + __FILE__, __LINE__, i, i, j, port, i, tests[i].port); + problem = true; + break; + } + + addr = addr->ai_next; + } + + curl_easy_cleanup(easy); + easy = NULL; + curl_multi_cleanup(multi); + multi = NULL; + curl_slist_free_all(list); + list = NULL; + + if(problem) { + unitfail++; + continue; + } + } + goto unit_test_abort; +error: + curl_easy_cleanup(easy); + curl_multi_cleanup(multi); + curl_slist_free_all(list); +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1610.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1610.c new file mode 100644 index 0000000000000000000000000000000000000000..b9d6117a74b6224307e235a85a9353c3d4039f24 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1610.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "curl_sha256.h" + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + global_init(CURL_GLOBAL_ALL); + return res; +} + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +UNITTEST_START + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) \ + || defined(USE_LIBSSH2) + + const char string1[] = "1"; + const char string2[] = "hello-you-fool"; + unsigned char output[CURL_SHA256_DIGEST_LENGTH]; + unsigned char *testp = output; + + Curl_sha256it(output, (const unsigned char *) string1, strlen(string1)); + + verify_memory(testp, + "\x6b\x86\xb2\x73\xff\x34\xfc\xe1\x9d\x6b\x80\x4e\xff\x5a\x3f" + "\x57\x47\xad\xa4\xea\xa2\x2f\x1d\x49\xc0\x1e\x52\xdd\xb7\x87" + "\x5b\x4b", CURL_SHA256_DIGEST_LENGTH); + + Curl_sha256it(output, (const unsigned char *) string2, strlen(string2)); + + verify_memory(testp, + "\xcb\xb1\x6a\x8a\xb9\xcb\xb9\x35\xa8\xcb\xa0\x2e\x28\xc0\x26" + "\x30\xd1\x19\x9c\x1f\x02\x17\xf4\x7c\x96\x20\xf3\xef\xe8\x27" + "\x15\xae", CURL_SHA256_DIGEST_LENGTH); +#endif + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1611.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1611.c new file mode 100644 index 0000000000000000000000000000000000000000..0062ac6c373c7fd501c805f7f0635d081e249fa4 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1611.c @@ -0,0 +1,60 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "curl_md4.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +UNITTEST_START + +#ifdef USE_CURL_NTLM_CORE + const char string1[] = "1"; + const char string2[] = "hello-you-fool"; + unsigned char output[MD4_DIGEST_LENGTH]; + unsigned char *testp = output; + + Curl_md4it(output, (const unsigned char *) string1, strlen(string1)); + + verify_memory(testp, + "\x8b\xe1\xec\x69\x7b\x14\xad\x3a\x53\xb3\x71\x43\x61\x20\x64" + "\x1d", MD4_DIGEST_LENGTH); + + Curl_md4it(output, (const unsigned char *) string2, strlen(string2)); + + verify_memory(testp, + "\xa7\x16\x1c\xad\x7e\xbe\xdb\xbc\xf8\xc7\x23\x10\x2d\x2c\xe2" + "\x0b", MD4_DIGEST_LENGTH); +#endif + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1612.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1612.c new file mode 100644 index 0000000000000000000000000000000000000000..76483d92a391bef6639b35bcd95b6170dc401bd6 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1612.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#include "curl_hmac.h" +#include "curl_md5.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +UNITTEST_START + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + + const char password[] = "Pa55worD"; + const char string1[] = "1"; + const char string2[] = "hello-you-fool"; + unsigned char output[HMAC_MD5_LENGTH]; + unsigned char *testp = output; + + Curl_hmacit(&Curl_HMAC_MD5, + (const unsigned char *) password, strlen(password), + (const unsigned char *) string1, strlen(string1), + output); + + verify_memory(testp, + "\xd1\x29\x75\x43\x58\xdc\xab\x78\xdf\xcd\x7f\x2b\x29\x31\x13" + "\x37", HMAC_MD5_LENGTH); + + Curl_hmacit(&Curl_HMAC_MD5, + (const unsigned char *) password, strlen(password), + (const unsigned char *) string2, strlen(string2), + output); + + verify_memory(testp, + "\x75\xf1\xa7\xb9\xf5\x40\xe5\xa4\x98\x83\x9f\x64\x5a\x27\x6d" + "\xd0", HMAC_MD5_LENGTH); +#endif + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1614.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1614.c new file mode 100644 index 0000000000000000000000000000000000000000..3258fd225ef66ab8118929b8bc21b28fb8e21807 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1614.c @@ -0,0 +1,166 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "noproxy.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +struct check { + const char *a; + const char *n; + unsigned int bits; + bool match; +}; + +struct noproxy { + const char *a; + const char *n; + bool match; +}; + +UNITTEST_START +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_PROXY) +{ + int i; + int err = 0; + struct check list4[]= { + { "192.160.0.1", "192.160.0.1", 33, FALSE}, + { "192.160.0.1", "192.160.0.1", 32, TRUE}, + { "192.160.0.1", "192.160.0.1", 0, TRUE}, + { "192.160.0.1", "192.160.0.1", 24, TRUE}, + { "192.160.0.1", "192.160.0.1", 26, TRUE}, + { "192.160.0.1", "192.160.0.1", 20, TRUE}, + { "192.160.0.1", "192.160.0.1", 18, TRUE}, + { "192.160.0.1", "192.160.0.1", 12, TRUE}, + { "192.160.0.1", "192.160.0.1", 8, TRUE}, + { "192.160.0.1", "10.0.0.1", 8, FALSE}, + { "192.160.0.1", "10.0.0.1", 32, FALSE}, + { "192.160.0.1", "10.0.0.1", 0, FALSE}, + { NULL, NULL, 0, FALSE} /* end marker */ + }; +#ifdef USE_IPV6 + struct check list6[]= { + { "::1", "::1", 0, TRUE}, + { "::1", "::1", 128, TRUE}, + { "::1", "0:0::1", 128, TRUE}, + { "::1", "0:0::1", 129, FALSE}, + { "fe80::ab47:4396:55c9:8474", "fe80::ab47:4396:55c9:8474", 64, TRUE}, + { NULL, NULL, 0, FALSE} /* end marker */ + }; +#endif + struct noproxy list[]= { + { "www.example.com", "localhost .example.com .example.de", FALSE}, + { "www.example.com", "localhost,.example.com,.example.de", TRUE}, + { "www.example.com.", "localhost,.example.com,.example.de", TRUE}, + { "example.com", "localhost,.example.com,.example.de", TRUE}, + { "example.com.", "localhost,.example.com,.example.de", TRUE}, + { "www.example.com", "localhost,.example.com.,.example.de", TRUE}, + { "www.example.com", "localhost,www.example.com.,.example.de", TRUE}, + { "example.com", "localhost,example.com,.example.de", TRUE}, + { "example.com.", "localhost,example.com,.example.de", TRUE}, + { "nexample.com", "localhost,example.com,.example.de", FALSE}, + { "www.example.com", "localhost,example.com,.example.de", TRUE}, + { "127.0.0.1", "127.0.0.1,localhost", TRUE}, + { "127.0.0.1", "127.0.0.1,localhost,", TRUE}, + { "127.0.0.1", "127.0.0.1/8,localhost,", TRUE}, + { "127.0.0.1", "127.0.0.1/28,localhost,", TRUE}, + { "127.0.0.1", "127.0.0.1/31,localhost,", TRUE}, + { "127.0.0.1", "localhost,127.0.0.1", TRUE}, + { "127.0.0.1", "localhost,127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1." + "127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127." + "0.0.1.127.0.0.1.127.0.0." /* 128 bytes "address" */, FALSE}, + { "127.0.0.1", "localhost,127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1." + "127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127.0.0.1.127." + "0.0.1.127.0.0.1.127.0.0" /* 127 bytes "address" */, FALSE}, + { "localhost", "localhost,127.0.0.1", TRUE}, + { "localhost", "127.0.0.1,localhost", TRUE}, + { "foobar", "barfoo", FALSE}, + { "foobar", "foobar", TRUE}, + { "192.168.0.1", "foobar", FALSE}, + { "192.168.0.1", "192.168.0.0/16", TRUE}, + { "192.168.0.1", "192.168.0.0/24", TRUE}, + { "192.168.0.1", "192.168.0.0/32", FALSE}, + { "192.168.0.1", "192.168.0.0", FALSE}, + { "192.168.1.1", "192.168.0.0/24", FALSE}, + { "192.168.1.1", "192.168.0.0/33", FALSE}, + { "192.168.1.1", "foo, bar, 192.168.0.0/24", FALSE}, + { "192.168.1.1", "foo, bar, 192.168.0.0/16", TRUE}, +#ifdef USE_IPV6 + { "[::1]", "foo, bar, 192.168.0.0/16", FALSE}, + { "[::1]", "foo, bar, ::1/64", TRUE}, + { "[::1]", "::1/64", TRUE}, + { "[::1]", "::1/96", TRUE}, + { "[::1]", "::1/129", FALSE}, + { "bar", "foo, bar, ::1/64", TRUE}, + { "BAr", "foo, bar, ::1/64", TRUE}, + { "BAr", "foo,,,,, bar, ::1/64", TRUE}, +#endif + { "www.example.com", "foo, .example.com", TRUE}, + { "www.example.com", "www2.example.com, .example.net", FALSE}, + { "example.com", ".example.com, .example.net", TRUE}, + { "nonexample.com", ".example.com, .example.net", FALSE}, + { NULL, NULL, FALSE} + }; + for(i = 0; list4[i].a; i++) { + bool match = Curl_cidr4_match(list4[i].a, list4[i].n, list4[i].bits); + if(match != list4[i].match) { + fprintf(stderr, "%s in %s/%u should %smatch\n", + list4[i].a, list4[i].n, list4[i].bits, + list4[i].match ? "": "not "); + err++; + } + } +#ifdef USE_IPV6 + for(i = 0; list6[i].a; i++) { + bool match = Curl_cidr6_match(list6[i].a, list6[i].n, list6[i].bits); + if(match != list6[i].match) { + fprintf(stderr, "%s in %s/%u should %smatch\n", + list6[i].a, list6[i].n, list6[i].bits, + list6[i].match ? "": "not "); + err++; + } + } +#endif + for(i = 0; list[i].a; i++) { + bool match = Curl_check_noproxy(list[i].a, list[i].n); + if(match != list[i].match) { + fprintf(stderr, "%s in %s should %smatch\n", + list[i].a, list[i].n, + list[i].match ? "": "not "); + err++; + } + } + fail_if(err, "errors"); +} +#endif +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1615.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1615.c new file mode 100644 index 0000000000000000000000000000000000000000..72b751c3bd39be745d86c56990b5e445f3d1cc73 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1615.c @@ -0,0 +1,159 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * 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 "curlcheck.h" + +#include "curl_sha512_256.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +UNITTEST_START + +#ifdef CURL_HAVE_SHA512_256 + + static const char test_str1[] = "1"; + static const unsigned char precomp_hash1[CURL_SHA512_256_DIGEST_LENGTH] = { + 0x18, 0xd2, 0x75, 0x66, 0xbd, 0x1a, 0xc6, 0x6b, 0x23, 0x32, 0xd8, + 0xc5, 0x4a, 0xd4, 0x3f, 0x7b, 0xb2, 0x20, 0x79, 0xc9, 0x06, 0xd0, + 0x5f, 0x49, 0x1f, 0x3f, 0x07, 0xa2, 0x8d, 0x5c, 0x69, 0x90 + }; + static const char test_str2[] = "hello-you-fool"; + static const unsigned char precomp_hash2[CURL_SHA512_256_DIGEST_LENGTH] = { + 0xaf, 0x6f, 0xb4, 0xb0, 0x13, 0x9b, 0xee, 0x13, 0xd1, 0x95, 0x3c, + 0xb8, 0xc7, 0xcd, 0x5b, 0x19, 0xf9, 0xcd, 0xcd, 0x21, 0xef, 0xdf, + 0xa7, 0x42, 0x5c, 0x07, 0x13, 0xea, 0xcc, 0x1a, 0x39, 0x76 + }; + static const char test_str3[] = "abc"; + static const unsigned char precomp_hash3[CURL_SHA512_256_DIGEST_LENGTH] = { + 0x53, 0x04, 0x8E, 0x26, 0x81, 0x94, 0x1E, 0xF9, 0x9B, 0x2E, 0x29, + 0xB7, 0x6B, 0x4C, 0x7D, 0xAB, 0xE4, 0xC2, 0xD0, 0xC6, 0x34, 0xFC, + 0x6D, 0x46, 0xE0, 0xE2, 0xF1, 0x31, 0x07, 0xE7, 0xAF, 0x23 + }; + static const char test_str4[] = ""; /* empty, zero size input */ + static const unsigned char precomp_hash4[CURL_SHA512_256_DIGEST_LENGTH] = { + 0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28, 0xab, 0x87, 0xc3, + 0x62, 0x2c, 0x51, 0x14, 0x06, 0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, + 0x73, 0x74, 0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a + }; + static const char test_str5[] = + "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ + "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"; + static const unsigned char precomp_hash5[CURL_SHA512_256_DIGEST_LENGTH] = { + 0xad, 0xe9, 0x5d, 0x55, 0x3b, 0x9e, 0x45, 0x69, 0xdb, 0x53, 0xa4, + 0x04, 0x92, 0xe7, 0x87, 0x94, 0xff, 0xc9, 0x98, 0x5f, 0x93, 0x03, + 0x86, 0x45, 0xe1, 0x97, 0x17, 0x72, 0x7c, 0xbc, 0x31, 0x15 + }; + static const char test_str6[] = + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/long/long/long/long/long/long/long" \ + "/long/long/long/long/path?with%20some=parameters"; + static const unsigned char precomp_hash6[CURL_SHA512_256_DIGEST_LENGTH] = { + 0xbc, 0xab, 0xc6, 0x2c, 0x0a, 0x22, 0xd5, 0xcb, 0xac, 0xac, 0xe9, + 0x25, 0xcf, 0xce, 0xaa, 0xaf, 0x0e, 0xa1, 0xed, 0x42, 0x46, 0x8a, + 0xe2, 0x01, 0xee, 0x2f, 0xdb, 0x39, 0x75, 0x47, 0x73, 0xf1 + }; + static const char test_str7[] = "Simple string."; + static const unsigned char precomp_hash7[CURL_SHA512_256_DIGEST_LENGTH] = { + 0xde, 0xcb, 0x3c, 0x81, 0x65, 0x4b, 0xa0, 0xf5, 0xf0, 0x45, 0x6b, + 0x7e, 0x61, 0xf5, 0x0d, 0xf5, 0x38, 0xa4, 0xfc, 0xb1, 0x8a, 0x95, + 0xff, 0x59, 0xbc, 0x04, 0x82, 0xcf, 0x23, 0xb2, 0x32, 0x56 + }; + static const unsigned char test_seq8[]= { + 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, + 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, + 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, + 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, + 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, + 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, + 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, + 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, + 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, + 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, + 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, + 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, + 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, + 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, + 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; /* 255..1 sequence */ + static const unsigned char precomp_hash8[CURL_SHA512_256_DIGEST_LENGTH] = { + 0x22, 0x31, 0xf2, 0xa1, 0xb4, 0x89, 0xb2, 0x44, 0xf7, 0x66, 0xa0, + 0xb8, 0x31, 0xed, 0xb7, 0x73, 0x8a, 0x34, 0xdc, 0x11, 0xc8, 0x2c, + 0xf2, 0xb5, 0x88, 0x60, 0x39, 0x6b, 0x5c, 0x06, 0x70, 0x37 + }; + + unsigned char output_buf[CURL_SHA512_256_DIGEST_LENGTH]; + unsigned char *computed_hash; /* Just to mute compiler warning */ + + /* Mute compiler warnings in 'verify_memory' macros below */ + computed_hash = output_buf; + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str1, + (sizeof(test_str1) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash1, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str2, + (sizeof(test_str2) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash2, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str3, + (sizeof(test_str3) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash3, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str4, + (sizeof(test_str4) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash4, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str5, + (sizeof(test_str5) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash5, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str6, + (sizeof(test_str6) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash6, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, (const unsigned char *) test_str7, + (sizeof(test_str7) / sizeof(char)) - 1); + verify_memory(computed_hash, precomp_hash7, CURL_SHA512_256_DIGEST_LENGTH); + + Curl_sha512_256it(output_buf, test_seq8, + sizeof(test_seq8) / sizeof(unsigned char)); + verify_memory(computed_hash, precomp_hash8, CURL_SHA512_256_DIGEST_LENGTH); + +#endif /* CURL_HAVE_SHA512_256 */ + + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1616.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1616.c new file mode 100644 index 0000000000000000000000000000000000000000..6bccdb9cae86ce1785c009acd76b512f1ae602d0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1616.c @@ -0,0 +1,86 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "curlx.h" + +#include "hash.h" + +#include "memdebug.h" /* LAST include file */ + +static struct Curl_hash hash_static; + +static void mydtor(void *elem) +{ + int *ptr = (int *)elem; + free(ptr); +} + +static CURLcode unit_setup(void) +{ + Curl_hash_offt_init(&hash_static, 15, mydtor); + return CURLE_OK; +} + +static void unit_stop(void) +{ + Curl_hash_destroy(&hash_static); +} + +UNITTEST_START + int *value, *v; + int *value2; + int *nodep; + + curl_off_t key = 20; + curl_off_t key2 = 25; + + + value = malloc(sizeof(int)); + abort_unless(value != NULL, "Out of memory"); + *value = 199; + nodep = Curl_hash_offt_set(&hash_static, key, value); + if(!nodep) + free(value); + abort_unless(nodep, "insertion into hash failed"); + v = Curl_hash_offt_get(&hash_static, key); + abort_unless(v == value, "lookup present entry failed"); + v = Curl_hash_offt_get(&hash_static, key2); + abort_unless(!v, "lookup missing entry failed"); + Curl_hash_clean(&hash_static); + + /* Attempt to add another key/value pair */ + value2 = malloc(sizeof(int)); + abort_unless(value2 != NULL, "Out of memory"); + *value2 = 204; + nodep = Curl_hash_offt_set(&hash_static, key2, value2); + if(!nodep) + free(value2); + abort_unless(nodep, "insertion into hash failed"); + v = Curl_hash_offt_get(&hash_static, key2); + abort_unless(v == value2, "lookup present entry failed"); + v = Curl_hash_offt_get(&hash_static, key); + abort_unless(!v, "lookup missing entry failed"); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1620.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1620.c new file mode 100644 index 0000000000000000000000000000000000000000..5830d78364c2988c1a9f5bdb5c02c7c33a098879 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1620.c @@ -0,0 +1,131 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "url.h" + +#include "memdebug.h" /* LAST include file */ + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + global_init(CURL_GLOBAL_ALL); + return res; +} + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +static void test_parse( + const char *input, + const char *exp_username, + const char *exp_password, + const char *exp_options) +{ + char *userstr = NULL; + char *passwdstr = NULL; + char *options = NULL; + CURLcode rc = Curl_parse_login_details(input, strlen(input), + &userstr, &passwdstr, &options); + fail_unless(rc == CURLE_OK, "Curl_parse_login_details() failed"); + + fail_unless(!!exp_username == !!userstr, "username expectation failed"); + fail_unless(!!exp_password == !!passwdstr, "password expectation failed"); + fail_unless(!!exp_options == !!options, "options expectation failed"); + + if(!unitfail) { + fail_unless(!exp_username || strcmp(userstr, exp_username) == 0, + "userstr should be equal to exp_username"); + fail_unless(!exp_password || strcmp(passwdstr, exp_password) == 0, + "passwdstr should be equal to exp_password"); + fail_unless(!exp_options || strcmp(options, exp_options) == 0, + "options should be equal to exp_options"); + } + + free(userstr); + free(passwdstr); + free(options); +} + +UNITTEST_START +{ + CURLcode rc; + struct Curl_easy *empty; + enum dupstring i; + + bool async = FALSE; + bool protocol_connect = FALSE; + + rc = Curl_open(&empty); + if(rc) + goto unit_test_abort; + fail_unless(rc == CURLE_OK, "Curl_open() failed"); + + rc = Curl_connect(empty, &async, &protocol_connect); + fail_unless(rc == CURLE_URL_MALFORMAT, + "Curl_connect() failed to return CURLE_URL_MALFORMAT"); + + fail_unless(empty->magic == CURLEASY_MAGIC_NUMBER, + "empty->magic should be equal to CURLEASY_MAGIC_NUMBER"); + + /* double invoke to ensure no dependency on internal state */ + rc = Curl_connect(empty, &async, &protocol_connect); + fail_unless(rc == CURLE_URL_MALFORMAT, + "Curl_connect() failed to return CURLE_URL_MALFORMAT"); + + rc = Curl_init_userdefined(empty); + fail_unless(rc == CURLE_OK, "Curl_userdefined() failed"); + + rc = Curl_init_do(empty, empty->conn); + fail_unless(rc == CURLE_OK, "Curl_init_do() failed"); + + test_parse("hostname", "hostname", NULL, NULL); + test_parse("user:password", "user", "password", NULL); + test_parse("user:password;options", "user", "password", "options"); + test_parse("user:password;options;more", "user", "password", "options;more"); + test_parse("", "", NULL, NULL); + test_parse(":", "", "", NULL); + test_parse(":;", "", "", NULL); + test_parse(":password", "", "password", NULL); + test_parse(":password;", "", "password", NULL); + test_parse(";options", "", NULL, "options"); + test_parse("user;options", "user", NULL, "options"); + test_parse("user:;options", "user", "", "options"); + test_parse("user;options:password", "user", "password", "options"); + test_parse("user;options:", "user", "", "options"); + + Curl_freeset(empty); + for(i = (enum dupstring)0; i < STRING_LAST; i++) { + fail_unless(empty->set.str[i] == NULL, + "Curl_free() did not set to NULL"); + } + + rc = Curl_close(&empty); + fail_unless(rc == CURLE_OK, "Curl_close() failed"); + +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1621.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1621.c new file mode 100644 index 0000000000000000000000000000000000000000..c384e044d7456e0f1a8188869467806816e9689a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1621.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 "curlcheck.h" + +#include "urldata.h" +#include "url.h" + +#include "memdebug.h" /* LAST include file */ + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +#if defined(__MINGW32__) || \ + (!defined(HAVE_FSETXATTR) && \ + (!defined(__FreeBSD_version) || (__FreeBSD_version < 500000))) +UNITTEST_START +UNITTEST_STOP +#else + +char *stripcredentials(const char *url); + +struct checkthis { + const char *input; + const char *output; +}; + +static const struct checkthis tests[] = { + { "ninja://foo@example.com", "ninja://foo@example.com" }, + { "https://foo@example.com", "https://example.com/" }, + { "https://localhost:45", "https://localhost:45/" }, + { "https://foo@localhost:45", "https://localhost:45/" }, + { "http://daniel:password@localhost", "http://localhost/" }, + { "http://daniel@localhost", "http://localhost/" }, + { "http://localhost/", "http://localhost/" }, + { NULL, NULL } /* end marker */ +}; + +UNITTEST_START +{ + int i; + + for(i = 0; tests[i].input; i++) { + const char *url = tests[i].input; + char *stripped = stripcredentials(url); + printf("Test %u got input \"%s\", output: \"%s\"\n", + i, tests[i].input, stripped); + + fail_if(stripped && strcmp(tests[i].output, stripped), + tests[i].output); + curl_free(stripped); + } +} +UNITTEST_STOP +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1650.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1650.c new file mode 100644 index 0000000000000000000000000000000000000000..6d6261e1cc72baa6d2897bf5f2f1592c145d546d --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1650.c @@ -0,0 +1,297 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "doh.h" +#include "dynbuf.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +#ifndef CURL_DISABLE_DOH +#define DNS_PREAMBLE "\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" +#define LABEL_TEST "\x04\x74\x65\x73\x74" +#define LABEL_HOST "\x04\x68\x6f\x73\x74" +#define LABEL_NAME "\x04\x6e\x61\x6d\x65" +#define DNSA_TYPE "\x01" +#define DNSAAAA_TYPE "\x1c" +#define DNSA_EPILOGUE "\x00\x00" DNSA_TYPE "\x00\x01" +#define DNSAAAA_EPILOGUE "\x00\x00" DNSAAAA_TYPE "\x00\x01" + +#define DNS_Q1 DNS_PREAMBLE LABEL_TEST LABEL_HOST LABEL_NAME DNSA_EPILOGUE +#define DNS_Q2 DNS_PREAMBLE LABEL_TEST LABEL_HOST LABEL_NAME DNSAAAA_EPILOGUE + +struct dohrequest { + /* input */ + const char *name; + DNStype type; + + /* output */ + const char *packet; + size_t size; + DOHcode rc; +}; + + +static const struct dohrequest req[] = { + {"test.host.name", DNS_TYPE_A, DNS_Q1, sizeof(DNS_Q1)-1, DOH_OK }, + {"test.host.name", DNS_TYPE_AAAA, DNS_Q2, sizeof(DNS_Q2)-1, DOH_OK }, + {"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + ".host.name", + DNS_TYPE_AAAA, NULL, 0, DOH_DNS_BAD_LABEL } +}; + +struct dohresp { + /* input */ + const char *packet; + size_t size; + DNStype type; + + /* output */ + DOHcode rc; + const char *out; +}; + +#define DNS_FOO_EXAMPLE_COM \ + "\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x03\x66\x6f\x6f" \ + "\x07\x65\x78\x61\x6d\x70\x6c\x65\x03\x63\x6f\x6d\x00\x00\x01\x00" \ + "\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\x37\x00\x04\x7f\x00\x00" \ + "\x01" + +static const char full49[] = DNS_FOO_EXAMPLE_COM; + +static const struct dohresp resp[] = { + {"\x00\x00", 2, DNS_TYPE_A, DOH_TOO_SMALL_BUFFER, NULL }, + {"\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01", 12, + DNS_TYPE_A, DOH_DNS_BAD_ID, NULL }, + {"\x00\x00\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01", 12, + DNS_TYPE_A, DOH_DNS_BAD_RCODE, NULL }, + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x03\x66\x6f\x6f", 16, + DNS_TYPE_A, DOH_DNS_OUT_OF_RANGE, NULL }, + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x03\x66\x6f\x6f\x00", 17, + DNS_TYPE_A, DOH_DNS_OUT_OF_RANGE, NULL }, + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x03\x66\x6f\x6f\x00" + "\x00\x01\x00\x01", 21, + DNS_TYPE_A, DOH_DNS_OUT_OF_RANGE, NULL }, + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x03\x66\x6f\x6f\x00" + "\x00\x01\x00\x01" + "\x04", 18, + DNS_TYPE_A, DOH_DNS_OUT_OF_RANGE, NULL }, + + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x04\x63\x75\x72" + "\x6c\x04\x63\x75\x72\x6c\x00\x00\x05\x00\x01\xc0\x0c\x00\x05\x00" + "\x01\x00\x00\x00\x37\x00\x11\x08\x61\x6e\x79\x77\x68\x65\x72\x65" + "\x06\x72\x65\x61\x6c\x6c\x79\x00", 56, + DNS_TYPE_A, DOH_OK, "anywhere.really "}, + + {DNS_FOO_EXAMPLE_COM, 49, DNS_TYPE_A, DOH_OK, "127.0.0.1 "}, + + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x04\x61\x61\x61" + "\x61\x07\x65\x78\x61\x6d\x70\x6c\x65\x03\x63\x6f\x6d\x00\x00\x1c" + "\x00\x01\xc0\x0c\x00\x1c\x00\x01\x00\x00\x00\x37\x00\x10\x20\x20" + "\x20\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20\x20", 62, + DNS_TYPE_AAAA, DOH_OK, + "2020:2020:0000:0000:0000:0000:0000:2020 " }, + + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x00\x04\x63\x75\x72" + "\x6c\x04\x63\x75\x72\x6c\x00\x00\x05\x00\x01\xc0\x0c\x00\x05\x00" + "\x01\x00\x00\x00\x37\x00" + "\x07\x03\x61\x6e\x79\xc0\x27\x00", 46, + DNS_TYPE_A, DOH_DNS_LABEL_LOOP, NULL}, + + /* packet with NSCOUNT == 1 */ + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x01\x00\x00\x04\x61\x61\x61" + "\x61\x07\x65\x78\x61\x6d\x70\x6c\x65\x03\x63\x6f\x6d\x00\x00\x1c" + "\x00\x01\xc0\x0c\x00\x1c\x00\x01\x00\x00\x00\x37\x00\x10\x20\x20" + "\x20\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20\x20" + LABEL_TEST LABEL_HOST LABEL_NAME DNSAAAA_EPILOGUE "\x00\x00\x00\x01" + "\00\x04\x01\x01\x01\x01", /* RDDATA */ + + 62 + 30, + DNS_TYPE_AAAA, DOH_OK, + "2020:2020:0000:0000:0000:0000:0000:2020 " }, + + /* packet with ARCOUNT == 1 */ + {"\x00\x00\x01\x00\x00\x01\x00\x01\x00\x00\x00\x01\x04\x61\x61\x61" + "\x61\x07\x65\x78\x61\x6d\x70\x6c\x65\x03\x63\x6f\x6d\x00\x00\x1c" + "\x00\x01\xc0\x0c\x00\x1c\x00\x01\x00\x00\x00\x37\x00\x10\x20\x20" + "\x20\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20\x20" + LABEL_TEST LABEL_HOST LABEL_NAME DNSAAAA_EPILOGUE "\x00\x00\x00\x01" + "\00\x04\x01\x01\x01\x01", /* RDDATA */ + + 62 + 30, + DNS_TYPE_AAAA, DOH_OK, + "2020:2020:0000:0000:0000:0000:0000:2020 " }, + +}; + +UNITTEST_START +{ + size_t size = 0; + unsigned char buffer[256]; + size_t i; + unsigned char *p; + + for(i = 0; i < sizeof(req) / sizeof(req[0]); i++) { + DOHcode rc = doh_req_encode(req[i].name, req[i].type, + buffer, sizeof(buffer), &size); + if(rc != req[i].rc) { + fprintf(stderr, "req %zu: Expected return code %d got %d\n", i, + req[i].rc, rc); + abort_if(rc != req[i].rc, "return code"); + } + if(size != req[i].size) { + fprintf(stderr, "req %zu: Expected size %zu got %zu\n", i, + req[i].size, size); + fprintf(stderr, "DNS encode made: %s\n", hexdump(buffer, size)); + abort_if(size != req[i].size, "size"); + } + if(req[i].packet && memcmp(req[i].packet, buffer, size)) { + fprintf(stderr, "DNS encode made: %s\n", hexdump(buffer, size)); + fprintf(stderr, "... instead of: %s\n", + hexdump((unsigned char *)req[i].packet, size)); + abort_if(req[i].packet && memcmp(req[i].packet, buffer, size), + "contents"); + } + } + + for(i = 0; i < sizeof(resp) / sizeof(resp[0]); i++) { + struct dohentry d; + DOHcode rc; + char *ptr; + size_t len; + int u; + de_init(&d); + rc = doh_resp_decode((const unsigned char *)resp[i].packet, resp[i].size, + resp[i].type, &d); + if(rc != resp[i].rc) { + fprintf(stderr, "resp %zu: Expected return code %d got %d\n", i, + resp[i].rc, rc); + abort_if(rc != resp[i].rc, "return code"); + } + len = sizeof(buffer); + ptr = (char *)buffer; + for(u = 0; u < d.numaddr; u++) { + size_t o; + struct dohaddr *a; + a = &d.addr[u]; + if(resp[i].type == DNS_TYPE_A) { + p = &a->ip.v4[0]; + msnprintf(ptr, len, "%u.%u.%u.%u ", p[0], p[1], p[2], p[3]); + o = strlen(ptr); + len -= o; + ptr += o; + } + else { + int j; + for(j = 0; j < 16; j += 2) { + size_t l; + msnprintf(ptr, len, "%s%02x%02x", j?":":"", a->ip.v6[j], + a->ip.v6[j + 1]); + l = strlen(ptr); + len -= l; + ptr += l; + } + msnprintf(ptr, len, " "); + len--; + ptr++; + } + } + for(u = 0; u < d.numcname; u++) { + size_t o; + msnprintf(ptr, len, "%s ", Curl_dyn_ptr(&d.cname[u])); + o = strlen(ptr); + len -= o; + ptr += o; + } + de_cleanup(&d); + if(resp[i].out && strcmp((char *)buffer, resp[i].out)) { + fprintf(stderr, "resp %zu: Expected %s got %s\n", i, + resp[i].out, buffer); + abort_if(resp[i].out && strcmp((char *)buffer, resp[i].out), "content"); + } + } + + /* pass all sizes into the decoder until full */ + for(i = 0; i < sizeof(full49)-1; i++) { + struct dohentry d; + DOHcode rc; + memset(&d, 0, sizeof(d)); + rc = doh_resp_decode((const unsigned char *)full49, i, DNS_TYPE_A, &d); + if(!rc) { + /* none of them should work */ + fprintf(stderr, "%zu: %d\n", i, rc); + abort_if(!rc, "error rc"); + } + } + + /* and try all pieces from the other end of the packet */ + for(i = 1; i < sizeof(full49); i++) { + struct dohentry d; + DOHcode rc; + memset(&d, 0, sizeof(d)); + rc = doh_resp_decode((const unsigned char *)&full49[i], sizeof(full49)-i-1, + DNS_TYPE_A, &d); + if(!rc) { + /* none of them should work */ + fprintf(stderr, "2 %zu: %d\n", i, rc); + abort_if(!rc, "error rc"); + } + } + + { + DOHcode rc; + struct dohentry d; + struct dohaddr *a; + memset(&d, 0, sizeof(d)); + rc = doh_resp_decode((const unsigned char *)full49, sizeof(full49)-1, + DNS_TYPE_A, &d); + fail_if(d.numaddr != 1, "missing address"); + a = &d.addr[0]; + p = &a->ip.v4[0]; + msnprintf((char *)buffer, sizeof(buffer), + "%u.%u.%u.%u", p[0], p[1], p[2], p[3]); + if(rc || strcmp((char *)buffer, "127.0.0.1")) { + fprintf(stderr, "bad address decoded: %s, rc == %d\n", buffer, rc); + abort_if(rc || strcmp((char *)buffer, "127.0.0.1"), "bad address"); + } + fail_if(d.numcname, "bad cname counter"); + } +} +UNITTEST_STOP + +#else /* CURL_DISABLE_DOH */ +UNITTEST_START +/* nothing to do, just succeed */ +UNITTEST_STOP + + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1651.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1651.c new file mode 100644 index 0000000000000000000000000000000000000000..63f3393947a7d1354e23c5aa489b0fab3108d11a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1651.c @@ -0,0 +1,392 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "vtls/x509asn1.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) + +/* cert captured from gdb when connecting to curl.se on October 26 + 2018 */ +static unsigned char cert[] = { + 0x30, 0x82, 0x0F, 0x5B, 0x30, 0x82, 0x0E, 0x43, 0xA0, 0x03, 0x02, 0x01, 0x02, + 0x02, 0x0C, 0x08, 0x77, 0x99, 0x2C, 0x6B, 0x67, 0xE1, 0x18, 0xD6, 0x66, 0x66, + 0x9E, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, + 0x0B, 0x05, 0x00, 0x30, 0x57, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, + 0x06, 0x13, 0x02, 0x42, 0x45, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, + 0x0A, 0x13, 0x10, 0x47, 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x53, 0x69, 0x67, 0x6E, + 0x20, 0x6E, 0x76, 0x2D, 0x73, 0x61, 0x31, 0x2D, 0x30, 0x2B, 0x06, 0x03, 0x55, + 0x04, 0x03, 0x13, 0x24, 0x47, 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x53, 0x69, 0x67, + 0x6E, 0x20, 0x43, 0x6C, 0x6F, 0x75, 0x64, 0x53, 0x53, 0x4C, 0x20, 0x43, 0x41, + 0x20, 0x2D, 0x20, 0x53, 0x48, 0x41, 0x32, 0x35, 0x36, 0x20, 0x2D, 0x20, 0x47, + 0x33, 0x30, 0x1E, 0x17, 0x0D, 0x31, 0x38, 0x31, 0x30, 0x32, 0x32, 0x31, 0x37, + 0x31, 0x38, 0x32, 0x31, 0x5A, 0x17, 0x0D, 0x31, 0x39, 0x30, 0x33, 0x32, 0x31, + 0x31, 0x33, 0x34, 0x33, 0x34, 0x34, 0x5A, 0x30, 0x77, 0x31, 0x0B, 0x30, 0x09, + 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, + 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x43, 0x61, 0x6C, 0x69, 0x66, 0x6F, + 0x72, 0x6E, 0x69, 0x61, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x07, + 0x0C, 0x0D, 0x53, 0x61, 0x6E, 0x20, 0x46, 0x72, 0x61, 0x6E, 0x63, 0x69, 0x73, + 0x63, 0x6F, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x0C, 0x0C, + 0x46, 0x61, 0x73, 0x74, 0x6C, 0x79, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, + 0x24, 0x30, 0x22, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x1B, 0x6A, 0x32, 0x2E, + 0x73, 0x68, 0x61, 0x72, 0x65, 0x64, 0x2E, 0x67, 0x6C, 0x6F, 0x62, 0x61, 0x6C, + 0x2E, 0x66, 0x61, 0x73, 0x74, 0x6C, 0x79, 0x2E, 0x6E, 0x65, 0x74, 0x30, 0x82, + 0x01, 0x22, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, + 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0F, 0x00, 0x30, 0x82, 0x01, 0x0A, + 0x02, 0x82, 0x01, 0x01, 0x00, 0xC2, 0x72, 0xA2, 0x4A, 0xEF, 0x26, 0x42, 0xD7, + 0x85, 0x74, 0xC9, 0xB4, 0x9F, 0xE3, 0x31, 0xD1, 0x40, 0x77, 0xC9, 0x4B, 0x4D, + 0xFE, 0xC8, 0x75, 0xF3, 0x32, 0x76, 0xAD, 0xF9, 0x08, 0x22, 0x9E, 0xFA, 0x2F, + 0xFE, 0xEC, 0x6C, 0xC4, 0xF5, 0x1F, 0x70, 0xC9, 0x8F, 0x07, 0x48, 0x31, 0xAD, + 0x75, 0x18, 0xFC, 0x06, 0x5A, 0x4F, 0xDD, 0xFD, 0x05, 0x39, 0x6F, 0x22, 0xF9, + 0xAD, 0x62, 0x1A, 0x9E, 0xA6, 0x16, 0x48, 0x75, 0x8F, 0xB8, 0x07, 0x18, 0x25, + 0x1A, 0x87, 0x30, 0xB0, 0x3C, 0x6F, 0xE0, 0x9D, 0x90, 0x63, 0x2A, 0x16, 0x1F, + 0x0D, 0x10, 0xFC, 0x06, 0x7E, 0xEA, 0x51, 0xE2, 0xB0, 0x6D, 0x42, 0x4C, 0x2C, + 0x59, 0xF4, 0x6B, 0x99, 0x3E, 0x82, 0x1D, 0x08, 0x04, 0x2F, 0xA0, 0x63, 0x3C, + 0xAA, 0x0E, 0xE1, 0x5D, 0x67, 0x2D, 0xB3, 0xF4, 0x15, 0xD6, 0x16, 0x4E, 0xAA, + 0x91, 0x45, 0x6B, 0xC5, 0xA6, 0xED, 0x83, 0xAF, 0xF1, 0xD7, 0x42, 0x5E, 0x9B, + 0xC8, 0x39, 0x0C, 0x06, 0x76, 0x7A, 0xB8, 0x3E, 0x16, 0x70, 0xF5, 0xEB, 0x8B, + 0x33, 0x5A, 0xA9, 0x03, 0xED, 0x79, 0x0E, 0xAD, 0xBB, 0xC4, 0xF8, 0xDA, 0x93, + 0x53, 0x2A, 0xC4, 0xC9, 0x1A, 0xD1, 0xC3, 0x44, 0xD7, 0xC6, 0xD0, 0xC6, 0xAC, + 0x13, 0xE3, 0xB5, 0x73, 0x3A, 0xDF, 0x54, 0x15, 0xFB, 0xB4, 0x6B, 0x36, 0x39, + 0x18, 0xB5, 0x61, 0x12, 0xF0, 0x37, 0xAB, 0x81, 0x5F, 0x0C, 0xE7, 0xDF, 0xC1, + 0xC5, 0x5E, 0x99, 0x67, 0x85, 0xFF, 0xAD, 0xD6, 0x82, 0x09, 0x1F, 0x27, 0xE5, + 0x32, 0x52, 0x18, 0xEC, 0x35, 0x2F, 0x6C, 0xC9, 0xE6, 0x87, 0xCE, 0x30, 0xF6, + 0xDA, 0x04, 0x3F, 0xA5, 0x8A, 0x0C, 0xAE, 0x5B, 0xB0, 0xEC, 0x29, 0x9B, 0xEE, + 0x8F, 0x52, 0x1E, 0xE2, 0x56, 0x19, 0x45, 0x80, 0x3C, 0x02, 0x57, 0x5C, 0x52, + 0xD9, 0x02, 0x03, 0x01, 0x00, 0x01, 0xA3, 0x82, 0x0C, 0x05, 0x30, 0x82, 0x0C, + 0x01, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, + 0x03, 0x02, 0x05, 0xA0, 0x30, 0x81, 0x8A, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, + 0x05, 0x07, 0x01, 0x01, 0x04, 0x7E, 0x30, 0x7C, 0x30, 0x42, 0x06, 0x08, 0x2B, + 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x36, 0x68, 0x74, 0x74, 0x70, + 0x3A, 0x2F, 0x2F, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x2E, 0x67, 0x6C, 0x6F, + 0x62, 0x61, 0x6C, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x63, + 0x61, 0x63, 0x65, 0x72, 0x74, 0x2F, 0x63, 0x6C, 0x6F, 0x75, 0x64, 0x73, 0x73, + 0x6C, 0x73, 0x68, 0x61, 0x32, 0x67, 0x33, 0x2E, 0x63, 0x72, 0x74, 0x30, 0x36, + 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x2A, 0x68, + 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x6F, 0x63, 0x73, 0x70, 0x32, 0x2E, 0x67, + 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, + 0x2F, 0x63, 0x6C, 0x6F, 0x75, 0x64, 0x73, 0x73, 0x6C, 0x73, 0x68, 0x61, 0x32, + 0x67, 0x33, 0x30, 0x56, 0x06, 0x03, 0x55, 0x1D, 0x20, 0x04, 0x4F, 0x30, 0x4D, + 0x30, 0x41, 0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xA0, 0x32, 0x01, 0x14, + 0x30, 0x34, 0x30, 0x32, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, + 0x01, 0x16, 0x26, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A, 0x2F, 0x2F, 0x77, 0x77, + 0x77, 0x2E, 0x67, 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x73, 0x69, 0x67, 0x6E, 0x2E, + 0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x65, 0x70, 0x6F, 0x73, 0x69, 0x74, 0x6F, 0x72, + 0x79, 0x2F, 0x30, 0x08, 0x06, 0x06, 0x67, 0x81, 0x0C, 0x01, 0x02, 0x02, 0x30, + 0x09, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x82, 0x09, + 0x96, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x82, 0x09, 0x8D, 0x30, 0x82, 0x09, + 0x89, 0x82, 0x1B, 0x6A, 0x32, 0x2E, 0x73, 0x68, 0x61, 0x72, 0x65, 0x64, 0x2E, + 0x67, 0x6C, 0x6F, 0x62, 0x61, 0x6C, 0x2E, 0x66, 0x61, 0x73, 0x74, 0x6C, 0x79, + 0x2E, 0x6E, 0x65, 0x74, 0x82, 0x0D, 0x2A, 0x2E, 0x61, 0x32, 0x70, 0x72, 0x65, + 0x73, 0x73, 0x65, 0x2E, 0x66, 0x72, 0x82, 0x19, 0x2A, 0x2E, 0x61, 0x64, 0x76, + 0x65, 0x6E, 0x74, 0x69, 0x73, 0x74, 0x62, 0x6F, 0x6F, 0x6B, 0x63, 0x65, 0x6E, + 0x74, 0x65, 0x72, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x2A, 0x2E, 0x61, 0x70, + 0x69, 0x2E, 0x6C, 0x6F, 0x6C, 0x65, 0x73, 0x70, 0x6F, 0x72, 0x74, 0x73, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x0C, 0x2A, 0x2E, 0x62, 0x61, 0x61, 0x74, 0x63, 0x68, + 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x17, 0x2A, 0x2E, 0x62, 0x69, 0x6F, 0x74, 0x65, + 0x63, 0x68, 0x77, 0x65, 0x65, 0x6B, 0x62, 0x6F, 0x73, 0x74, 0x6F, 0x6E, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x10, 0x2A, 0x2E, 0x62, 0x6F, 0x78, 0x6F, 0x66, 0x73, + 0x74, 0x79, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0C, 0x2A, 0x2E, 0x63, + 0x61, 0x73, 0x70, 0x65, 0x72, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x11, 0x2A, 0x2E, + 0x63, 0x68, 0x61, 0x6B, 0x72, 0x61, 0x6C, 0x69, 0x6E, 0x75, 0x78, 0x2E, 0x6F, + 0x72, 0x67, 0x82, 0x18, 0x2A, 0x2E, 0x63, 0x6F, 0x6E, 0x76, 0x65, 0x72, 0x74, + 0x2E, 0x64, 0x73, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x7A, 0x6F, 0x6E, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x15, 0x2A, 0x2E, 0x64, 0x65, 0x76, 0x73, 0x70, 0x61, 0x63, + 0x65, 0x73, 0x68, 0x69, 0x70, 0x2E, 0x63, 0x6F, 0x6D, 0x2E, 0x61, 0x75, 0x82, + 0x1B, 0x2A, 0x2E, 0x64, 0x65, 0x76, 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x68, + 0x69, 0x70, 0x69, 0x6E, 0x76, 0x65, 0x73, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2E, + 0x61, 0x75, 0x82, 0x0A, 0x2A, 0x2E, 0x65, 0x63, 0x68, 0x6C, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x0F, 0x2A, 0x2E, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x74, 0x61, 0x63, + 0x6B, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x16, 0x2A, 0x2E, 0x66, 0x69, 0x6C, 0x65, + 0x73, 0x74, 0x61, 0x63, 0x6B, 0x2E, 0x6F, 0x6E, 0x65, 0x6D, 0x6F, 0x62, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x0D, 0x2A, 0x2E, 0x66, 0x69, 0x73, 0x2D, 0x73, 0x6B, + 0x69, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0C, 0x2A, 0x2E, 0x66, 0x69, 0x73, 0x73, + 0x6B, 0x69, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x2A, 0x2E, 0x66, 0x70, 0x2E, + 0x62, 0x72, 0x61, 0x6E, 0x64, 0x66, 0x6F, 0x6C, 0x64, 0x65, 0x72, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0F, 0x2A, 0x2E, 0x66, 0x73, 0x2E, 0x65, 0x6E, 0x70, 0x6C, + 0x75, 0x67, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0E, 0x2A, 0x2E, 0x66, 0x73, 0x2E, + 0x65, 0x6E, 0x70, 0x6C, 0x75, 0x67, 0x2E, 0x69, 0x6E, 0x82, 0x10, 0x2A, 0x2E, + 0x66, 0x73, 0x2E, 0x68, 0x65, 0x72, 0x6F, 0x69, 0x6E, 0x65, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x18, 0x2A, 0x2E, 0x66, 0x73, 0x2E, 0x6C, 0x65, 0x61, 0x72, 0x6E, + 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x18, 0x2A, 0x2E, 0x66, 0x73, 0x2E, 0x6C, 0x6F, 0x63, 0x61, 0x6C, + 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x12, 0x2A, 0x2E, 0x66, 0x73, 0x2E, 0x6D, 0x69, 0x6E, 0x64, 0x66, + 0x6C, 0x61, 0x73, 0x68, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x16, 0x2A, 0x2E, 0x66, + 0x73, 0x2E, 0x6F, 0x70, 0x73, 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, + 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x10, 0x2A, 0x2E, 0x66, 0x73, 0x2E, + 0x70, 0x69, 0x78, 0x76, 0x61, 0x6E, 0x61, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x15, + 0x2A, 0x2E, 0x66, 0x73, 0x2E, 0x71, 0x61, 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, + 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x17, 0x2A, 0x2E, 0x66, + 0x73, 0x2E, 0x74, 0x65, 0x73, 0x74, 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, + 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x09, 0x2A, 0x2E, 0x68, 0x61, + 0x78, 0x78, 0x2E, 0x73, 0x65, 0x82, 0x0D, 0x2A, 0x2E, 0x68, 0x6F, 0x6D, 0x65, + 0x61, 0x77, 0x61, 0x79, 0x2E, 0x6C, 0x6B, 0x82, 0x0F, 0x2A, 0x2E, 0x69, 0x64, + 0x61, 0x74, 0x61, 0x6C, 0x69, 0x6E, 0x6B, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x16, + 0x2A, 0x2E, 0x69, 0x64, 0x61, 0x74, 0x61, 0x6C, 0x69, 0x6E, 0x6B, 0x6D, 0x61, + 0x65, 0x73, 0x74, 0x72, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x11, 0x2A, 0x2E, + 0x69, 0x6D, 0x67, 0x2D, 0x74, 0x61, 0x62, 0x6F, 0x6F, 0x6C, 0x61, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0F, 0x2A, 0x2E, 0x6A, 0x75, 0x6C, 0x69, 0x61, 0x6C, 0x61, + 0x6E, 0x67, 0x2E, 0x6F, 0x72, 0x67, 0x82, 0x10, 0x2A, 0x2E, 0x6B, 0x69, 0x6E, + 0x64, 0x73, 0x6E, 0x61, 0x63, 0x6B, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x10, + 0x2A, 0x2E, 0x6B, 0x73, 0x73, 0x76, 0x61, 0x6E, 0x69, 0x6C, 0x6C, 0x61, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x0E, 0x2A, 0x2E, 0x6B, 0x73, 0x74, 0x63, 0x6F, 0x72, + 0x72, 0x61, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x10, 0x2A, 0x2E, 0x6B, 0x73, 0x74, + 0x76, 0x61, 0x6E, 0x69, 0x6C, 0x6C, 0x61, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0C, + 0x2A, 0x2E, 0x6E, 0x65, 0x77, 0x73, 0x31, 0x32, 0x2E, 0x63, 0x6F, 0x6D, 0x82, + 0x1B, 0x2A, 0x2E, 0x70, 0x61, 0x72, 0x74, 0x69, 0x64, 0x65, 0x6E, 0x74, 0x69, + 0x66, 0x69, 0x65, 0x72, 0x2E, 0x73, 0x77, 0x69, 0x73, 0x63, 0x6F, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x13, 0x2A, 0x2E, 0x73, 0x68, 0x6F, 0x70, 0x72, 0x61, 0x63, + 0x68, 0x65, 0x6C, 0x7A, 0x6F, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0A, 0x2A, + 0x2E, 0x74, 0x61, 0x73, 0x74, 0x79, 0x2E, 0x63, 0x6F, 0x82, 0x0C, 0x2A, 0x2E, + 0x74, 0x65, 0x64, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x15, 0x2A, + 0x2E, 0x75, 0x70, 0x6C, 0x6F, 0x61, 0x64, 0x73, 0x2E, 0x66, 0x6F, 0x6C, 0x69, + 0x6F, 0x68, 0x64, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x2A, 0x2E, 0x76, 0x6F, + 0x75, 0x63, 0x68, 0x65, 0x72, 0x63, 0x6F, 0x64, 0x65, 0x73, 0x2E, 0x63, 0x6F, + 0x2E, 0x75, 0x6B, 0x82, 0x0D, 0x2A, 0x2E, 0x77, 0x65, 0x61, 0x74, 0x68, 0x65, + 0x72, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0D, 0x61, 0x2E, 0x69, 0x63, 0x61, 0x6E, + 0x76, 0x61, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0B, 0x61, 0x32, 0x70, 0x72, + 0x65, 0x73, 0x73, 0x65, 0x2E, 0x66, 0x72, 0x82, 0x17, 0x61, 0x64, 0x76, 0x65, + 0x6E, 0x74, 0x69, 0x73, 0x74, 0x62, 0x6F, 0x6F, 0x6B, 0x63, 0x65, 0x6E, 0x74, + 0x65, 0x72, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x11, 0x61, 0x70, 0x69, 0x2D, 0x6D, + 0x65, 0x72, 0x72, 0x79, 0x6A, 0x61, 0x6E, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, + 0x12, 0x61, 0x70, 0x69, 0x73, 0x2E, 0x69, 0x64, 0x61, 0x74, 0x61, 0x6C, 0x69, + 0x76, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0F, 0x61, 0x70, 0x70, 0x2D, 0x61, + 0x70, 0x69, 0x2E, 0x74, 0x65, 0x64, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x12, 0x61, + 0x70, 0x70, 0x2E, 0x62, 0x69, 0x72, 0x63, 0x68, 0x62, 0x6F, 0x78, 0x2E, 0x63, + 0x6F, 0x2E, 0x75, 0x6B, 0x82, 0x0F, 0x61, 0x70, 0x70, 0x2E, 0x62, 0x69, 0x72, + 0x63, 0x68, 0x62, 0x6F, 0x78, 0x2E, 0x65, 0x73, 0x82, 0x1A, 0x61, 0x70, 0x70, + 0x2E, 0x73, 0x74, 0x61, 0x67, 0x69, 0x6E, 0x67, 0x2E, 0x62, 0x69, 0x72, 0x63, + 0x68, 0x62, 0x6F, 0x78, 0x2E, 0x63, 0x6F, 0x2E, 0x75, 0x6B, 0x82, 0x17, 0x61, + 0x70, 0x70, 0x2E, 0x73, 0x74, 0x61, 0x67, 0x69, 0x6E, 0x67, 0x2E, 0x62, 0x69, + 0x72, 0x63, 0x68, 0x62, 0x6F, 0x78, 0x2E, 0x65, 0x73, 0x82, 0x0A, 0x62, 0x61, + 0x61, 0x74, 0x63, 0x68, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x13, 0x62, 0x65, 0x72, + 0x6E, 0x61, 0x72, 0x64, 0x63, 0x6F, 0x6E, 0x74, 0x72, 0x6F, 0x6C, 0x73, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x15, 0x62, 0x69, 0x6F, 0x74, 0x65, 0x63, 0x68, 0x77, + 0x65, 0x65, 0x6B, 0x62, 0x6F, 0x73, 0x74, 0x6F, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x0E, 0x62, 0x6F, 0x78, 0x6F, 0x66, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x0A, 0x63, 0x61, 0x73, 0x70, 0x65, 0x72, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0D, 0x63, 0x64, 0x6E, 0x2E, 0x69, 0x72, 0x73, 0x64, 0x6E, + 0x2E, 0x6E, 0x65, 0x74, 0x82, 0x0F, 0x63, 0x68, 0x61, 0x6B, 0x72, 0x61, 0x6C, + 0x69, 0x6E, 0x75, 0x78, 0x2E, 0x6F, 0x72, 0x67, 0x82, 0x13, 0x64, 0x65, 0x76, + 0x73, 0x70, 0x61, 0x63, 0x65, 0x73, 0x68, 0x69, 0x70, 0x2E, 0x63, 0x6F, 0x6D, + 0x2E, 0x61, 0x75, 0x82, 0x0B, 0x64, 0x69, 0x67, 0x69, 0x64, 0x61, 0x79, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x22, 0x64, 0x69, 0x67, 0x69, 0x74, 0x61, 0x6C, 0x4C, + 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x2E, 0x62, 0x65, 0x72, 0x6E, 0x61, 0x72, + 0x64, 0x63, 0x6F, 0x6E, 0x74, 0x72, 0x6F, 0x6C, 0x73, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x14, 0x64, 0x72, 0x77, 0x70, 0x2E, 0x73, 0x74, 0x61, 0x67, 0x69, 0x6E, + 0x67, 0x2E, 0x6D, 0x6F, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x08, 0x65, 0x63, + 0x68, 0x6C, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x66, 0x69, 0x6C, 0x65, 0x73, + 0x74, 0x61, 0x63, 0x6B, 0x2E, 0x6F, 0x6E, 0x65, 0x6D, 0x6F, 0x62, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0D, 0x66, 0x73, 0x2E, 0x65, 0x6E, 0x70, 0x6C, 0x75, 0x67, + 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x16, 0x66, 0x73, 0x2E, 0x6C, 0x65, 0x61, 0x72, + 0x6E, 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x16, 0x66, 0x73, 0x2E, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x7A, + 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x14, 0x66, 0x73, 0x2E, 0x6F, 0x70, 0x73, 0x7A, 0x69, 0x6C, 0x6C, 0x69, + 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x13, 0x66, 0x73, + 0x2E, 0x71, 0x61, 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, + 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x15, 0x66, 0x73, 0x2E, 0x74, 0x65, 0x73, 0x74, + 0x7A, 0x69, 0x6C, 0x6C, 0x69, 0x6F, 0x6E, 0x63, 0x64, 0x6E, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x0B, 0x68, 0x6F, 0x6D, 0x65, 0x61, 0x77, 0x61, 0x79, 0x2E, 0x6C, + 0x6B, 0x82, 0x12, 0x69, 0x6D, 0x67, 0x2E, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, + 0x72, 0x6D, 0x61, 0x69, 0x6C, 0x2E, 0x69, 0x6F, 0x82, 0x0E, 0x6B, 0x69, 0x6E, + 0x64, 0x73, 0x6E, 0x61, 0x63, 0x6B, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0E, + 0x6B, 0x73, 0x73, 0x76, 0x61, 0x6E, 0x69, 0x6C, 0x6C, 0x61, 0x2E, 0x63, 0x6F, + 0x6D, 0x82, 0x0C, 0x6B, 0x73, 0x74, 0x63, 0x6F, 0x72, 0x72, 0x61, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0D, 0x6D, 0x65, 0x6E, 0x75, 0x2E, 0x74, 0x72, 0x65, 0x65, + 0x7A, 0x2E, 0x69, 0x6F, 0x82, 0x17, 0x6D, 0x6F, 0x62, 0x69, 0x6C, 0x65, 0x61, + 0x70, 0x69, 0x2E, 0x69, 0x64, 0x61, 0x74, 0x61, 0x6C, 0x69, 0x6E, 0x6B, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x0A, 0x6E, 0x65, 0x77, 0x73, 0x31, 0x32, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0B, 0x6F, 0x6D, 0x6E, 0x69, 0x67, 0x6F, 0x6E, 0x2E, 0x63, + 0x6F, 0x6D, 0x82, 0x0E, 0x6F, 0x72, 0x65, 0x69, 0x6C, 0x6C, 0x79, 0x2E, 0x72, + 0x65, 0x76, 0x69, 0x65, 0x77, 0x82, 0x11, 0x70, 0x6F, 0x70, 0x79, 0x6F, 0x75, + 0x72, 0x62, 0x75, 0x62, 0x62, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x18, + 0x70, 0x72, 0x6F, 0x64, 0x2E, 0x62, 0x65, 0x72, 0x6E, 0x61, 0x72, 0x64, 0x63, + 0x6F, 0x6E, 0x74, 0x72, 0x6F, 0x6C, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x18, + 0x72, 0x65, 0x6C, 0x65, 0x61, 0x73, 0x65, 0x2D, 0x70, 0x72, 0x69, 0x6D, 0x65, + 0x2E, 0x73, 0x70, 0x6F, 0x6B, 0x65, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x19, + 0x72, 0x65, 0x70, 0x6F, 0x73, 0x69, 0x74, 0x6F, 0x72, 0x69, 0x65, 0x73, 0x2E, + 0x73, 0x65, 0x6E, 0x73, 0x75, 0x61, 0x70, 0x70, 0x2E, 0x6F, 0x72, 0x67, 0x82, + 0x0C, 0x72, 0x6C, 0x2E, 0x74, 0x61, 0x6C, 0x69, 0x73, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x11, 0x73, 0x68, 0x6F, 0x70, 0x72, 0x61, 0x63, 0x68, 0x65, 0x6C, 0x7A, + 0x6F, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0F, 0x73, 0x74, 0x61, 0x67, 0x69, + 0x6E, 0x67, 0x2E, 0x6D, 0x6F, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x73, + 0x74, 0x61, 0x74, 0x69, 0x63, 0x2E, 0x70, 0x6C, 0x75, 0x6D, 0x63, 0x61, 0x63, + 0x68, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x14, 0x73, 0x74, 0x61, 0x79, 0x69, + 0x6E, 0x67, 0x61, 0x6C, 0x69, 0x76, 0x65, 0x2E, 0x6D, 0x73, 0x66, 0x2E, 0x6F, + 0x72, 0x67, 0x82, 0x08, 0x74, 0x61, 0x73, 0x74, 0x79, 0x2E, 0x63, 0x6F, 0x82, + 0x0C, 0x74, 0x6F, 0x70, 0x73, 0x70, 0x65, 0x65, 0x64, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x13, 0x75, 0x70, 0x6C, 0x6F, 0x61, 0x64, 0x73, 0x2E, 0x66, 0x6F, 0x6C, + 0x69, 0x6F, 0x68, 0x64, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x1A, 0x75, 0x73, 0x2D, + 0x65, 0x75, 0x2E, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x74, 0x61, 0x63, 0x6B, 0x63, + 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x12, 0x76, + 0x6F, 0x75, 0x63, 0x68, 0x65, 0x72, 0x63, 0x6F, 0x64, 0x65, 0x73, 0x2E, 0x63, + 0x6F, 0x2E, 0x75, 0x6B, 0x82, 0x0B, 0x77, 0x65, 0x61, 0x74, 0x68, 0x65, 0x72, + 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x13, 0x77, 0x6F, 0x6D, 0x65, 0x6E, 0x73, 0x68, + 0x65, 0x61, 0x6C, 0x74, 0x68, 0x2D, 0x6A, 0x70, 0x2E, 0x63, 0x6F, 0x6D, 0x82, + 0x19, 0x77, 0x6F, 0x72, 0x6B, 0x65, 0x72, 0x62, 0x65, 0x65, 0x2E, 0x73, 0x74, + 0x61, 0x67, 0x69, 0x6E, 0x67, 0x2E, 0x6D, 0x6F, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x0A, 0x77, 0x77, 0x77, 0x2E, 0x61, 0x67, 0x66, 0x2E, 0x64, 0x6B, 0x82, + 0x14, 0x77, 0x77, 0x77, 0x2E, 0x61, 0x76, 0x65, 0x6E, 0x69, 0x72, 0x2D, 0x73, + 0x75, 0x69, 0x73, 0x73, 0x65, 0x2E, 0x63, 0x68, 0x82, 0x11, 0x77, 0x77, 0x77, + 0x2E, 0x63, 0x61, 0x6E, 0x73, 0x74, 0x61, 0x72, 0x2E, 0x63, 0x6F, 0x2E, 0x6E, + 0x7A, 0x82, 0x15, 0x77, 0x77, 0x77, 0x2E, 0x63, 0x61, 0x6E, 0x73, 0x74, 0x61, + 0x72, 0x62, 0x6C, 0x75, 0x65, 0x2E, 0x63, 0x6F, 0x2E, 0x6E, 0x7A, 0x82, 0x16, + 0x77, 0x77, 0x77, 0x2E, 0x63, 0x61, 0x6E, 0x73, 0x74, 0x61, 0x72, 0x62, 0x6C, + 0x75, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x2E, 0x61, 0x75, 0x82, 0x1D, 0x77, 0x77, + 0x77, 0x2E, 0x63, 0x68, 0x61, 0x6D, 0x70, 0x69, 0x6F, 0x6E, 0x73, 0x68, 0x6F, + 0x63, 0x6B, 0x65, 0x79, 0x6C, 0x65, 0x61, 0x67, 0x75, 0x65, 0x2E, 0x6E, 0x65, + 0x74, 0x82, 0x0F, 0x77, 0x77, 0x77, 0x2E, 0x65, 0x78, 0x74, 0x65, 0x72, 0x72, + 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0C, 0x77, 0x77, 0x77, 0x2E, 0x65, 0x7A, + 0x75, 0x70, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0B, 0x77, 0x77, 0x77, 0x2E, 0x65, + 0x7A, 0x75, 0x70, 0x2E, 0x64, 0x65, 0x82, 0x0B, 0x77, 0x77, 0x77, 0x2E, 0x65, + 0x7A, 0x75, 0x70, 0x2E, 0x65, 0x75, 0x82, 0x0B, 0x77, 0x77, 0x77, 0x2E, 0x65, + 0x7A, 0x75, 0x70, 0x2E, 0x6E, 0x6C, 0x82, 0x11, 0x77, 0x77, 0x77, 0x2E, 0x66, + 0x72, 0x61, 0x6E, 0x6B, 0x62, 0x6F, 0x64, 0x79, 0x2E, 0x63, 0x6F, 0x6D, 0x82, + 0x0D, 0x77, 0x77, 0x77, 0x2E, 0x67, 0x6C, 0x6F, 0x73, 0x73, 0x79, 0x2E, 0x63, + 0x6F, 0x82, 0x0F, 0x77, 0x77, 0x77, 0x2E, 0x67, 0x6F, 0x6C, 0x64, 0x63, 0x75, + 0x70, 0x2E, 0x6F, 0x72, 0x67, 0x82, 0x0F, 0x77, 0x77, 0x77, 0x2E, 0x69, 0x63, + 0x61, 0x6E, 0x76, 0x61, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0D, 0x77, 0x77, + 0x77, 0x2E, 0x6D, 0x6F, 0x6E, 0x69, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x16, + 0x77, 0x77, 0x77, 0x2E, 0x6F, 0x64, 0x65, 0x6E, 0x73, 0x65, 0x2D, 0x6D, 0x61, + 0x72, 0x63, 0x69, 0x70, 0x61, 0x6E, 0x2E, 0x64, 0x6B, 0x82, 0x15, 0x77, 0x77, + 0x77, 0x2E, 0x6F, 0x6E, 0x65, 0x63, 0x6C, 0x69, 0x63, 0x6B, 0x64, 0x72, 0x69, + 0x76, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x12, 0x77, 0x77, 0x77, 0x2E, 0x6F, + 0x72, 0x65, 0x69, 0x6C, 0x6C, 0x79, 0x2E, 0x72, 0x65, 0x76, 0x69, 0x65, 0x77, + 0x82, 0x15, 0x77, 0x77, 0x77, 0x2E, 0x70, 0x6F, 0x70, 0x79, 0x6F, 0x75, 0x72, + 0x62, 0x75, 0x62, 0x62, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x82, 0x0E, 0x77, + 0x77, 0x77, 0x2E, 0x72, 0x61, 0x77, 0x6E, 0x65, 0x74, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x0E, 0x77, 0x77, 0x77, 0x2E, 0x73, 0x70, 0x6F, 0x6B, 0x65, 0x6F, 0x2E, + 0x63, 0x6F, 0x6D, 0x82, 0x10, 0x77, 0x77, 0x77, 0x2E, 0x74, 0x65, 0x61, 0x72, + 0x73, 0x68, 0x65, 0x65, 0x74, 0x2E, 0x63, 0x6F, 0x82, 0x10, 0x77, 0x77, 0x77, + 0x2E, 0x74, 0x6F, 0x70, 0x73, 0x70, 0x65, 0x65, 0x64, 0x2E, 0x63, 0x6F, 0x6D, + 0x82, 0x16, 0x77, 0x77, 0x77, 0x2E, 0x77, 0x68, 0x69, 0x74, 0x65, 0x6B, 0x65, + 0x79, 0x76, 0x69, 0x6C, 0x6C, 0x61, 0x73, 0x2E, 0x63, 0x6F, 0x6D, 0x30, 0x1D, + 0x06, 0x03, 0x55, 0x1D, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2B, 0x06, + 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, + 0x07, 0x03, 0x02, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x1D, 0x0E, 0x04, 0x16, 0x04, + 0x14, 0xA8, 0x29, 0xFD, 0xA9, 0xA5, 0x1A, 0x1C, 0x37, 0x0B, 0x20, 0x3B, 0x98, + 0xB7, 0x25, 0x39, 0xCC, 0xE5, 0x2F, 0xF4, 0x94, 0x30, 0x1F, 0x06, 0x03, 0x55, + 0x1D, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xA9, 0x2B, 0x87, 0xE1, 0xCE, + 0x24, 0x47, 0x3B, 0x1B, 0xBF, 0xCF, 0x85, 0x37, 0x02, 0x55, 0x9D, 0x0D, 0x94, + 0x58, 0xE6, 0x30, 0x82, 0x01, 0x04, 0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, + 0xD6, 0x79, 0x02, 0x04, 0x02, 0x04, 0x81, 0xF5, 0x04, 0x81, 0xF2, 0x00, 0xF0, + 0x00, 0x77, 0x00, 0xA4, 0xB9, 0x09, 0x90, 0xB4, 0x18, 0x58, 0x14, 0x87, 0xBB, + 0x13, 0xA2, 0xCC, 0x67, 0x70, 0x0A, 0x3C, 0x35, 0x98, 0x04, 0xF9, 0x1B, 0xDF, + 0xB8, 0xE3, 0x77, 0xCD, 0x0E, 0xC8, 0x0D, 0xDC, 0x10, 0x00, 0x00, 0x01, 0x66, + 0x9C, 0xC8, 0xE7, 0x38, 0x00, 0x00, 0x04, 0x03, 0x00, 0x48, 0x30, 0x46, 0x02, + 0x21, 0x00, 0xD9, 0x58, 0x6E, 0xFC, 0x4C, 0x3C, 0xAF, 0xF9, 0x5B, 0x7F, 0xDA, + 0x54, 0x95, 0xAF, 0xCF, 0xB3, 0x57, 0xB9, 0x56, 0x2C, 0xE8, 0xE0, 0xB1, 0x20, + 0x9B, 0xCB, 0x75, 0xAC, 0x4E, 0x54, 0xE9, 0x9D, 0x02, 0x21, 0x00, 0xE8, 0xF0, + 0xC0, 0x49, 0x23, 0x8E, 0x3D, 0x9B, 0xA5, 0x87, 0xA3, 0xBE, 0x6C, 0x21, 0x62, + 0xBB, 0xD2, 0x44, 0x5C, 0xE4, 0x7A, 0xCC, 0x46, 0x26, 0x04, 0x19, 0xA4, 0x2D, + 0x9B, 0x1C, 0x5D, 0x3A, 0x00, 0x75, 0x00, 0x6F, 0x53, 0x76, 0xAC, 0x31, 0xF0, + 0x31, 0x19, 0xD8, 0x99, 0x00, 0xA4, 0x51, 0x15, 0xFF, 0x77, 0x15, 0x1C, 0x11, + 0xD9, 0x02, 0xC1, 0x00, 0x29, 0x06, 0x8D, 0xB2, 0x08, 0x9A, 0x37, 0xD9, 0x13, + 0x00, 0x00, 0x01, 0x66, 0x9C, 0xC8, 0xE6, 0x20, 0x00, 0x00, 0x04, 0x03, 0x00, + 0x46, 0x30, 0x44, 0x02, 0x20, 0x14, 0xC8, 0x9F, 0xAC, 0x27, 0x48, 0xBE, 0x4D, + 0x0E, 0xC3, 0x26, 0x2E, 0x34, 0xCA, 0x38, 0xBA, 0x11, 0x3A, 0x68, 0x71, 0x88, + 0xEB, 0x24, 0x26, 0x59, 0x3E, 0xAC, 0xA8, 0x63, 0xCC, 0x8A, 0x0A, 0x02, 0x20, + 0x0F, 0x22, 0xBF, 0x0D, 0x1F, 0x8A, 0x8D, 0x1D, 0x91, 0x33, 0x3A, 0x40, 0xE4, + 0x23, 0x78, 0xFA, 0x22, 0xF5, 0x9B, 0xCB, 0x04, 0x4F, 0x53, 0x2D, 0x20, 0x75, + 0x2F, 0x76, 0x8A, 0xB1, 0xCD, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, + 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, + 0x03, 0x41, 0x0F, 0xF3, 0xA6, 0x62, 0xA2, 0xE5, 0xB4, 0x8D, 0xA8, 0x08, 0x71, + 0x7B, 0xB3, 0xE3, 0x51, 0x61, 0x0D, 0xC0, 0x67, 0x6C, 0x3C, 0x9C, 0x00, 0x0B, + 0x63, 0x77, 0xB6, 0xB6, 0x11, 0x67, 0x77, 0xA5, 0xE1, 0x49, 0xE0, 0x7F, 0xB7, + 0x1D, 0x61, 0xFB, 0x83, 0x9C, 0x83, 0x42, 0xE9, 0x31, 0xCA, 0x51, 0xE3, 0xC1, + 0xBD, 0x9B, 0x2F, 0xB5, 0x35, 0x05, 0x72, 0x7F, 0x40, 0xA6, 0x7C, 0xC9, 0xF1, + 0x59, 0xA7, 0x15, 0xB8, 0x12, 0xDA, 0xF8, 0xCE, 0x83, 0x61, 0xFC, 0x47, 0x96, + 0x9E, 0x74, 0xFE, 0xCD, 0xE4, 0x61, 0x92, 0xF2, 0x2E, 0x0C, 0x08, 0x4B, 0x60, + 0x2D, 0xF6, 0x50, 0x07, 0x83, 0xCA, 0xAF, 0xB9, 0x41, 0x33, 0x4A, 0x3E, 0x84, + 0xC7, 0x73, 0xC6, 0x1F, 0xFF, 0x7A, 0xDF, 0xAE, 0x47, 0x25, 0x32, 0xEB, 0xC0, + 0x43, 0x0C, 0xA6, 0x23, 0x13, 0x46, 0xC3, 0xFA, 0x44, 0xEA, 0x20, 0xEA, 0xCB, + 0x18, 0x17, 0x00, 0xB6, 0xE7, 0x6D, 0x8A, 0x14, 0x8C, 0x6A, 0xCA, 0x88, 0x4C, + 0xDA, 0xA8, 0xB9, 0x08, 0xAF, 0x39, 0xEE, 0xCF, 0xD7, 0xF7, 0x32, 0xC0, 0xF4, + 0xCF, 0x4E, 0x22, 0x38, 0xF7, 0xAF, 0xAE, 0x7D, 0x58, 0x5F, 0xA5, 0x2D, 0x4D, + 0xBB, 0x86, 0x10, 0xB3, 0x93, 0x62, 0x64, 0x27, 0xBF, 0xB1, 0xBB, 0x8F, 0x9F, + 0xFC, 0x07, 0x3C, 0x4B, 0x16, 0x7A, 0x84, 0x5E, 0xAF, 0xAD, 0x57, 0x9C, 0xFF, + 0x7A, 0xA7, 0xE0, 0x90, 0x89, 0x1C, 0xE8, 0xE5, 0x11, 0xF7, 0xB6, 0xDC, 0xCD, + 0x5E, 0xF7, 0x30, 0xA2, 0x2E, 0x67, 0x6D, 0x4A, 0x70, 0x26, 0xEA, 0xCD, 0x27, + 0x70, 0x77, 0x54, 0x57, 0x09, 0x03, 0x56, 0x4A, 0x33, 0x60, 0x00, 0x27, 0xFE, + 0xA7, 0xD7, 0xA9, 0xC4, 0xEC, 0x17, 0x17, 0x8D, 0x87, 0x70, 0x6B, 0x48, 0x88, + 0x61, 0x54, 0x4A, 0x2B, 0xB7, 0x6A, 0x12, 0x08, 0xFB, +}; + +UNITTEST_START +{ + CURLcode result; + const char *beg = (const char *)&cert[0]; + const char *end = (const char *)&cert[sizeof(cert)]; + struct Curl_easy *data; + int i; + int byte; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + data = curl_easy_init(); + if(data) { + result = Curl_extract_certinfo(data, 0, beg, end); + + fail_unless(result == CURLE_OK, "Curl_extract_certinfo returned error"); + + /* a poor man's fuzzing of some initial data to make sure nothing bad + happens */ + for(byte = 1 ; byte < 255; byte += 17) { + for(i = 0; i < 45; i++) { + unsigned char backup = cert[i]; + cert[i] = (unsigned char) (byte & 0xff); + (void) Curl_extract_certinfo(data, 0, beg, end); + cert[i] = backup; + } + } + + curl_easy_cleanup(data); + } + curl_global_cleanup(); +} +UNITTEST_STOP + +#else + +UNITTEST_START +{ + puts("not tested since Curl_extract_certinfo() is not built-in"); +} +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1652.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1652.c new file mode 100644 index 0000000000000000000000000000000000000000..8607ecc7e270c2eff78e37e1d78170d4916d1db0 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1652.c @@ -0,0 +1,153 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "sendf.h" + +/* + * This test hardcodes the knowledge of the buffer size which is internal to + * Curl_infof(). If that buffer is changed in size, this tests needs to be + * updated to still be valid. + */ + +static struct Curl_easy *testdata; + +static char input[4096]; +static char output[4096]; + +int debugf_cb(CURL *handle, curl_infotype type, char *buf, size_t size, + void *userptr); + +/* + * This debugf callback is simply dumping the string into the static buffer + * for the unit test to inspect. Since we know that we're only dealing with + * text we can afford the luxury of skipping the type check here. + */ +int +debugf_cb(CURL *handle, curl_infotype type, char *buf, size_t size, + void *userptr) +{ + (void)handle; + (void)type; + (void)userptr; + + memset(output, '\0', sizeof(output)); + memcpy(output, buf, size); + return 0; +} + +static CURLcode +unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + testdata = curl_easy_init(); + if(!testdata) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + curl_easy_setopt(testdata, CURLOPT_DEBUGFUNCTION, debugf_cb); + curl_easy_setopt(testdata, CURLOPT_VERBOSE, 1L); + return res; +} + +static void +unit_stop(void) +{ + curl_easy_cleanup(testdata); + curl_global_cleanup(); +} + +static int verify(const char *info, const char *two) +{ + /* the 'info' one has a newline appended */ + char *nl = strchr(info, '\n'); + if(!nl) + return 1; /* nope */ + return strncmp(info, two, nl - info); +} + +UNITTEST_START + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat" +#pragma GCC diagnostic ignored "-Wformat-zero-length" +#if __GNUC__ >= 7 +#pragma GCC diagnostic ignored "-Wformat-overflow" +#endif +#endif + +/* Injecting a simple short string via a format */ +msnprintf(input, sizeof(input), "Simple Test"); +Curl_infof(testdata, "%s", input); +fail_unless(verify(output, input) == 0, "Simple string test"); + +/* Injecting a few different variables with a format */ +Curl_infof(testdata, "%s %u testing %lu", input, 42, 43L); +fail_unless(verify(output, "Simple Test 42 testing 43\n") == 0, + "Format string"); + +/* Variations of empty strings */ +Curl_infof(testdata, ""); +fail_unless(strlen(output) == 1, "Empty string"); +Curl_infof(testdata, "%s", (char *)NULL); +fail_unless(verify(output, "(nil)") == 0, "Passing NULL as string"); + +/* A string just long enough to not be truncated */ +memset(input, '\0', sizeof(input)); +memset(input, 'A', 2047); +Curl_infof(testdata, "%s", input); +fail_unless(strlen(output) == 2048, "No truncation of infof input"); +fail_unless(verify(output, input) == 0, "No truncation of infof input"); +fail_unless(output[sizeof(output) - 1] == '\0', + "No truncation of infof input"); + +/* Just over the limit without newline for truncation via '...' */ +memset(input + 2047, 'A', 4); +Curl_infof(testdata, "%s", input); +fail_unless(strlen(output) == 2051, "Truncation of infof input 1"); +fail_unless(output[sizeof(output) - 1] == '\0', "Truncation of infof input 1"); + +/* Just over the limit with newline for truncation via '...' */ +memset(input + 2047, 'A', 4); +memset(input + 2047 + 4, '\n', 1); +Curl_infof(testdata, "%s", input); +fail_unless(strlen(output) == 2051, "Truncation of infof input 2"); +fail_unless(output[sizeof(output) - 1] == '\0', "Truncation of infof input 2"); + +/* Way over the limit for truncation via '...' */ +memset(input, '\0', sizeof(input)); +memset(input, 'A', sizeof(input) - 1); +Curl_infof(testdata, "%s", input); +fail_unless(strlen(output) == 2051, "Truncation of infof input 3"); +fail_unless(output[sizeof(output) - 1] == '\0', "Truncation of infof input 3"); + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1653.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1653.c new file mode 100644 index 0000000000000000000000000000000000000000..d543fb0276398f063b79d970a5db8c812b7c3275 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1653.c @@ -0,0 +1,232 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "curl/urlapi.h" +#include "urlapi-int.h" + + +static CURLU *u; + +static CURLcode +unit_setup(void) +{ + return CURLE_OK; +} + +static void +unit_stop(void) +{ + curl_global_cleanup(); +} + +#define free_and_clear(x) free(x); x = NULL + +static CURLUcode parse_port(CURLU *url, + char *h, bool has_scheme) +{ + struct dynbuf host; + CURLUcode ret; + Curl_dyn_init(&host, 10000); + if(Curl_dyn_add(&host, h)) + return CURLUE_OUT_OF_MEMORY; + ret = Curl_parse_port(url, &host, has_scheme); + Curl_dyn_free(&host); + return ret; +} + +UNITTEST_START +{ + CURLUcode ret; + char *ipv6port = NULL; + char *portnum; + + /* Valid IPv6 */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15]"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + ret = curl_url_get(u, CURLUPART_PORT, &portnum, CURLU_NO_DEFAULT_PORT); + fail_unless(ret != CURLUE_OK, "curl_url_get portnum returned something"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Invalid IPv6 */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15|"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret != CURLUE_OK, "parse_port true on error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff;fea7:da15]:808"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); + fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); + fail_unless(portnum && !strcmp(portnum, "808"), "Check portnumber"); + + curl_free(portnum); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Valid IPv6 with zone index and port number */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15%25eth3]:80"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); + fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); + fail_unless(portnum && !strcmp(portnum, "80"), "Check portnumber"); + curl_free(portnum); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Valid IPv6 with zone index without port number */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15%25eth3]"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Valid IPv6 with port number */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15]:81"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); + fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); + fail_unless(portnum && !strcmp(portnum, "81"), "Check portnumber"); + curl_free(portnum); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Valid IPv6 with syntax error in the port number */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15];81"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret != CURLUE_OK, "parse_port true on error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15]80"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret != CURLUE_OK, "parse_port true on error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Valid IPv6 with no port after the colon, should use default if a scheme + was used in the URL */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15]:"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, TRUE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Incorrect zone index syntax, but the port extractor doesn't care */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15!25eth3]:180"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); + fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); + fail_unless(portnum && !strcmp(portnum, "180"), "Check portnumber"); + curl_free(portnum); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* Non percent-encoded zone index */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("[fe80::250:56ff:fea7:da15%eth3]:80"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_OK, "parse_port returned error"); + free_and_clear(ipv6port); + curl_url_cleanup(u); + + /* No scheme and no digits following the colon - not accepted. Because that + makes (a*50):// that looks like a scheme be an acceptable input. */ + u = curl_url(); + if(!u) + goto fail; + ipv6port = strdup("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaa:"); + if(!ipv6port) + goto fail; + ret = parse_port(u, ipv6port, FALSE); + fail_unless(ret == CURLUE_BAD_PORT_NUMBER, "parse_port did wrong"); +fail: + free(ipv6port); + curl_url_cleanup(u); + +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1654.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1654.c new file mode 100644 index 0000000000000000000000000000000000000000..2f5d1bcc86ebb3ffb4e80aab400dad6fb16d0308 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1654.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 "curlcheck.h" + +#include "urldata.h" +#include "altsvc.h" + +static CURLcode +unit_setup(void) +{ + return CURLE_OK; +} + +static void +unit_stop(void) +{ + curl_global_cleanup(); +} + +UNITTEST_START +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +{ + char outname[256]; + CURL *curl; + CURLcode result; + struct altsvcinfo *asi = Curl_altsvc_init(); + abort_if(!asi, "Curl_altsvc_i"); + result = Curl_altsvc_load(asi, arg); + if(result) { + fail_if(result, "Curl_altsvc_load"); + goto fail; + } + curl_global_init(CURL_GLOBAL_ALL); + curl = curl_easy_init(); + if(!curl) { + fail_if(!curl, "curl_easy_init"); + goto fail; + } + fail_unless(Curl_llist_count(&asi->list) == 4, "wrong number of entries"); + msnprintf(outname, sizeof(outname), "%s-out", arg); + + result = Curl_altsvc_parse(curl, asi, "h2=\"example.com:8080\"\r\n", + ALPN_h1, "example.org", 8080); + fail_if(result, "Curl_altsvc_parse() failed!"); + fail_unless(Curl_llist_count(&asi->list) == 5, "wrong number of entries"); + + result = Curl_altsvc_parse(curl, asi, "h3=\":8080\"\r\n", + ALPN_h1, "2.example.org", 8080); + fail_if(result, "Curl_altsvc_parse(2) failed!"); + fail_unless(Curl_llist_count(&asi->list) == 6, "wrong number of entries"); + + result = Curl_altsvc_parse(curl, asi, + "h2=\"example.com:8080\", h3=\"yesyes.com\"\r\n", + ALPN_h1, "3.example.org", 8080); + fail_if(result, "Curl_altsvc_parse(3) failed!"); + /* that one should make two entries */ + fail_unless(Curl_llist_count(&asi->list) == 8, "wrong number of entries"); + + result = Curl_altsvc_parse(curl, asi, + "h2=\"example.com:443\"; ma = 120;\r\n", + ALPN_h2, "example.org", 80); + fail_if(result, "Curl_altsvc_parse(4) failed!"); + fail_unless(Curl_llist_count(&asi->list) == 9, "wrong number of entries"); + + /* quoted 'ma' value */ + result = Curl_altsvc_parse(curl, asi, + "h2=\"example.net:443\"; ma=\"180\";\r\n", + ALPN_h2, "example.net", 80); + fail_if(result, "Curl_altsvc_parse(4) failed!"); + fail_unless(Curl_llist_count(&asi->list) == 10, "wrong number of entries"); + + result = + Curl_altsvc_parse(curl, asi, + "h2=\":443\", h3=\":443\"; ma = 120; persist = 1\r\n", + ALPN_h1, "curl.se", 80); + fail_if(result, "Curl_altsvc_parse(5) failed!"); + fail_unless(Curl_llist_count(&asi->list) == 12, "wrong number of entries"); + + /* clear that one again and decrease the counter */ + result = Curl_altsvc_parse(curl, asi, "clear;\r\n", + ALPN_h1, "curl.se", 80); + fail_if(result, "Curl_altsvc_parse(6) failed!"); + fail_unless(Curl_llist_count(&asi->list) == 10, "wrong number of entries"); + + Curl_altsvc_save(curl, asi, outname); + + curl_easy_cleanup(curl); +fail: + Curl_altsvc_cleanup(&asi); +} +#endif +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1655.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1655.c new file mode 100644 index 0000000000000000000000000000000000000000..6c9298de3065cfa51e37e79a766e84f16e11a001 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1655.c @@ -0,0 +1,190 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "doh.h" /* from the lib dir */ + +static CURLcode unit_setup(void) +{ + /* whatever you want done first */ + return CURLE_OK; +} + +static void unit_stop(void) +{ + /* done before shutting down and exiting */ +} + +#ifndef CURL_DISABLE_DOH + +UNITTEST_START + +/* + * Prove detection of write overflow using a short buffer and a name + * of maximal valid length. + * + * Prove detection of other invalid input. + */ +do { + static const char max[] = + /* ..|....1.........2.........3.........4.........5.........6... */ + /* 3456789012345678901234567890123456789012345678901234567890123 */ + "this.is.a.maximum-length.hostname." /* 34: 34 */ + "with-no-label-of-greater-length-than-the-sixty-three-characters." + /* 64: 98 */ + "specified.in.the.RFCs." /* 22: 120 */ + "and.with.a.QNAME.encoding.whose.length.is.exactly." /* 50: 170 */ + "the.maximum.length.allowed." /* 27: 197 */ + "that.is.two-hundred.and.fifty-six." /* 34: 231 */ + "including.the.last.null." /* 24: 255 */ + ""; + static const char toolong[] = + /* ..|....1.........2.........3.........4.........5.........6... */ + /* 3456789012345678901234567890123456789012345678901234567890123 */ + "here.is.a.hostname.which.is.just.barely.too.long." /* 49: 49 */ + "to.be.encoded.as.a.QNAME.of.the.maximum.allowed.length." + /* 55: 104 */ + "which.is.256.including.a.final.zero-length.label." /* 49: 153 */ + "representing.the.root.node.so.that.a.name.with." /* 47: 200 */ + "a.trailing.dot.may.have.up.to." /* 30: 230 */ + "255.characters.never.more." /* 26: 256 */ + ""; + static const char emptylabel[] = + "this.is.an.otherwise-valid.hostname." + ".with.an.empty.label."; + static const char outsizelabel[] = + "this.is.an.otherwise-valid.hostname." + "with-a-label-of-greater-length-than-the-sixty-three-characters-" + "specified.in.the.RFCs."; + int i; + + struct test { + const char *name; + const DOHcode expected_result; + }; + + /* plays the role of struct dnsprobe in urldata.h */ + struct demo { + unsigned char dohbuffer[255 + 16]; /* deliberately short buffer */ + unsigned char canary1; + unsigned char canary2; + unsigned char canary3; + }; + + const struct test playlist[4] = { + { toolong, DOH_DNS_NAME_TOO_LONG }, /* expect early failure */ + { emptylabel, DOH_DNS_BAD_LABEL }, /* also */ + { outsizelabel, DOH_DNS_BAD_LABEL }, /* also */ + { max, DOH_OK } /* expect buffer overwrite */ + }; + + for(i = 0; i < (int)(sizeof(playlist)/sizeof(*playlist)); i++) { + const char *name = playlist[i].name; + size_t olen = 100000; + struct demo victim; + DOHcode d; + + victim.canary1 = 87; /* magic numbers, arbitrarily picked */ + victim.canary2 = 35; + victim.canary3 = 41; + d = doh_req_encode(name, DNS_TYPE_A, victim.dohbuffer, + sizeof(struct demo), /* allow room for overflow */ + &olen); + + fail_unless(d == playlist[i].expected_result, + "result returned was not as expected"); + if(d == playlist[i].expected_result) { + if(name == max) { + fail_if(victim.canary1 == 87, + "demo one-byte buffer overwrite did not happen"); + } + else { + fail_unless(victim.canary1 == 87, + "one-byte buffer overwrite has happened"); + } + fail_unless(victim.canary2 == 35, + "two-byte buffer overwrite has happened"); + fail_unless(victim.canary3 == 41, + "three-byte buffer overwrite has happened"); + } + else { + if(d == DOH_OK) { + fail_unless(olen <= sizeof(victim.dohbuffer), "wrote outside bounds"); + fail_unless(olen > strlen(name), "unrealistic low size"); + } + } + } +} while(0); + +/* run normal cases and try to trigger buffer length related errors */ +do { + DNStype dnstype = DNS_TYPE_A; + unsigned char buffer[128]; + const size_t buflen = sizeof(buffer); + const size_t magic1 = 9765; + size_t olen1 = magic1; + const char *sunshine1 = "a.com"; + const char *dotshine1 = "a.com."; + const char *sunshine2 = "aa.com"; + size_t olen2; + DOHcode ret2; + size_t olen; + + DOHcode ret = doh_req_encode(sunshine1, dnstype, buffer, buflen, &olen1); + fail_unless(ret == DOH_OK, "sunshine case 1 should pass fine"); + fail_if(olen1 == magic1, "olen has not been assigned properly"); + fail_unless(olen1 > strlen(sunshine1), "bad out length"); + + /* with a trailing dot, the response should have the same length */ + olen2 = magic1; + ret2 = doh_req_encode(dotshine1, dnstype, buffer, buflen, &olen2); + fail_unless(ret2 == DOH_OK, "dotshine case should pass fine"); + fail_if(olen2 == magic1, "olen has not been assigned properly"); + fail_unless(olen1 == olen2, "olen should not grow for a trailing dot"); + + /* add one letter, the response should be one longer */ + olen2 = magic1; + ret2 = doh_req_encode(sunshine2, dnstype, buffer, buflen, &olen2); + fail_unless(ret2 == DOH_OK, "sunshine case 2 should pass fine"); + fail_if(olen2 == magic1, "olen has not been assigned properly"); + fail_unless(olen1 + 1 == olen2, "olen should grow with the hostname"); + + /* pass a short buffer, should fail */ + ret = doh_req_encode(sunshine1, dnstype, buffer, olen1 - 1, &olen); + fail_if(ret == DOH_OK, "short buffer should have been noticed"); + + /* pass a minimum buffer, should succeed */ + ret = doh_req_encode(sunshine1, dnstype, buffer, olen1, &olen); + fail_unless(ret == DOH_OK, "minimal length buffer should be long enough"); + fail_unless(olen == olen1, "bad buffer length"); +} while(0); +UNITTEST_STOP + +#else /* CURL_DISABLE_DOH */ + +UNITTEST_START +/* nothing to do, just succeed */ +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1656.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1656.c new file mode 100644 index 0000000000000000000000000000000000000000..644e72fc7d65770b449744400aeaa1c233c2d549 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1656.c @@ -0,0 +1,133 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "vtls/x509asn1.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ + +} + +#if defined(USE_GNUTLS) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP) || \ + defined(USE_MBEDTLS) + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +struct test_spec { + const char *input; + const char *exp_output; + CURLcode exp_result; +}; + +static struct test_spec test_specs[] = { + { "190321134340", "1903-21-13 43:40:00", CURLE_OK }, + { "", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "WTF", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "0WTF", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "19032113434", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "19032113434WTF", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "190321134340.", NULL, CURLE_BAD_FUNCTION_ARGUMENT }, + { "190321134340.1", "1903-21-13 43:40:00.1", CURLE_OK }, + { "19032113434017.0", "1903-21-13 43:40:17", CURLE_OK }, + { "19032113434017.01", "1903-21-13 43:40:17.01", CURLE_OK }, + { "19032113434003.001", "1903-21-13 43:40:03.001", CURLE_OK }, + { "19032113434003.090", "1903-21-13 43:40:03.09", CURLE_OK }, + { "190321134340Z", "1903-21-13 43:40:00 GMT", CURLE_OK }, + { "19032113434017.0Z", "1903-21-13 43:40:17 GMT", CURLE_OK }, + { "19032113434017.01Z", "1903-21-13 43:40:17.01 GMT", CURLE_OK }, + { "19032113434003.001Z", "1903-21-13 43:40:03.001 GMT", CURLE_OK }, + { "19032113434003.090Z", "1903-21-13 43:40:03.09 GMT", CURLE_OK }, + { "190321134340CET", "1903-21-13 43:40:00 CET", CURLE_OK }, + { "19032113434017.0CET", "1903-21-13 43:40:17 CET", CURLE_OK }, + { "19032113434017.01CET", "1903-21-13 43:40:17.01 CET", CURLE_OK }, + { "190321134340+02:30", "1903-21-13 43:40:00 UTC+02:30", CURLE_OK }, + { "19032113434017.0+02:30", "1903-21-13 43:40:17 UTC+02:30", CURLE_OK }, + { "19032113434017.01+02:30", "1903-21-13 43:40:17.01 UTC+02:30", CURLE_OK }, + { "190321134340-3", "1903-21-13 43:40:00 UTC-3", CURLE_OK }, + { "19032113434017.0-04", "1903-21-13 43:40:17 UTC-04", CURLE_OK }, + { "19032113434017.01-01:10", "1903-21-13 43:40:17.01 UTC-01:10", CURLE_OK }, +}; + +static bool do_test(struct test_spec *spec, size_t i, struct dynbuf *dbuf) +{ + CURLcode result; + const char *in = spec->input; + + Curl_dyn_reset(dbuf); + result = Curl_x509_GTime2str(dbuf, in, in + strlen(in)); + if(result != spec->exp_result) { + fprintf(stderr, "test %zu: expect result %d, got %d\n", + i, spec->exp_result, result); + return FALSE; + } + else if(!result && strcmp(spec->exp_output, Curl_dyn_ptr(dbuf))) { + fprintf(stderr, "test %zu: input '%s', expected output '%s', got '%s'\n", + i, in, spec->exp_output, Curl_dyn_ptr(dbuf)); + return FALSE; + } + + return TRUE; +} + +UNITTEST_START +{ + size_t i; + struct dynbuf dbuf; + bool all_ok = TRUE; + + Curl_dyn_init(&dbuf, 32*1024); + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + for(i = 0; i < ARRAYSIZE(test_specs); ++i) { + if(!do_test(&test_specs[i], i, &dbuf)) + all_ok = FALSE; + } + fail_unless(all_ok, "some tests of Curl_x509_GTime2str() fails"); + + Curl_dyn_free(&dbuf); + curl_global_cleanup(); +} +UNITTEST_STOP + +#else + +UNITTEST_START +{ + puts("not tested since Curl_x509_GTime2str() is not built-in"); +} +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1660.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1660.c new file mode 100644 index 0000000000000000000000000000000000000000..46ab93ed8f87493d4671fc0b422e173949591f72 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1660.c @@ -0,0 +1,180 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "hsts.h" + +static CURLcode +unit_setup(void) +{ + return CURLE_OK; +} + +static void +unit_stop(void) +{ + curl_global_cleanup(); +} + +#if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_HSTS) +UNITTEST_START +{ + puts("nothing to do when HTTP or HSTS are disabled"); +} +UNITTEST_STOP +#else + +struct testit { + const char *host; + const char *chost; /* if non-NULL, use to lookup with */ + const char *hdr; /* if NULL, just do the lookup */ + const CURLcode result; /* parse result */ +}; + +static const struct testit headers[] = { + /* two entries read from disk cache, verify first */ + { "-", "readfrom.example", NULL, CURLE_OK}, + { "-", "old.example", NULL, CURLE_OK}, + /* delete the remaining one read from disk */ + { "readfrom.example", NULL, "max-age=\"0\"", CURLE_OK}, + + { "example.com", NULL, "max-age=\"31536000\"\r\n", CURLE_OK }, + { "example.com", NULL, "max-age=\"21536000\"\r\n", CURLE_OK }, + { "example.com", NULL, "max-age=\"21536000\"; \r\n", CURLE_OK }, + { "example.com", NULL, "max-age=\"21536000\"; includeSubDomains\r\n", + CURLE_OK }, + { "example.org", NULL, "max-age=\"31536000\"\r\n", CURLE_OK }, + { "this.example", NULL, "max=\"31536\";", CURLE_BAD_FUNCTION_ARGUMENT }, + { "this.example", NULL, "max-age=\"31536", CURLE_BAD_FUNCTION_ARGUMENT }, + { "this.example", NULL, "max-age=31536\"", CURLE_OK }, + /* max-age=0 removes the entry */ + { "this.example", NULL, "max-age=0", CURLE_OK }, + { "another.example", NULL, "includeSubDomains; ", + CURLE_BAD_FUNCTION_ARGUMENT }, + + /* Two max-age is illegal */ + { "example.com", NULL, + "max-age=\"21536000\"; includeSubDomains; max-age=\"3\";", + CURLE_BAD_FUNCTION_ARGUMENT }, + /* Two includeSubDomains is illegal */ + { "2.example.com", NULL, + "max-age=\"21536000\"; includeSubDomains; includeSubDomains;", + CURLE_BAD_FUNCTION_ARGUMENT }, + /* use a unknown directive "include" that should be ignored */ + { "3.example.com", NULL, "max-age=\"21536000\"; include; includeSubDomains;", + CURLE_OK }, + /* remove the "3.example.com" one, should still match the example.com */ + { "3.example.com", NULL, "max-age=\"0\"; includeSubDomains;", + CURLE_OK }, + { "-", "foo.example.com", NULL, CURLE_OK}, + { "-", "foo.xample.com", NULL, CURLE_OK}, + + /* should not match */ + { "example.net", "forexample.net", "max-age=\"31536000\"\r\n", CURLE_OK }, + + /* should not match either, since forexample.net is not in the example.net + domain */ + { "example.net", "forexample.net", + "max-age=\"31536000\"; includeSubDomains\r\n", CURLE_OK }, + /* remove example.net again */ + { "example.net", NULL, "max-age=\"0\"; includeSubDomains\r\n", CURLE_OK }, + + /* make this live for 7 seconds */ + { "expire.example", NULL, "max-age=\"7\"\r\n", CURLE_OK }, + { NULL, NULL, NULL, CURLE_OK } +}; + +static void showsts(struct stsentry *e, const char *chost) +{ + if(!e) + printf("'%s' is not HSTS\n", chost); + else { + printf("%s [%s]: %" CURL_FORMAT_CURL_OFF_T "%s\n", + chost, e->host, e->expires, + e->includeSubDomains ? " includeSubDomains" : ""); + } +} + +UNITTEST_START +{ + CURLcode result; + struct stsentry *e; + struct hsts *h = Curl_hsts_init(); + int i; + const char *chost; + CURL *easy; + char savename[256]; + + abort_unless(h, "Curl_hsts_init()"); + + curl_global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + Curl_hsts_cleanup(&h); + curl_global_cleanup(); + abort_unless(easy, "curl_easy_init()"); + } + + Curl_hsts_loadfile(easy, h, arg); + + for(i = 0; headers[i].host ; i++) { + if(headers[i].hdr) { + result = Curl_hsts_parse(h, headers[i].host, headers[i].hdr); + + if(result != headers[i].result) { + fprintf(stderr, "Curl_hsts_parse(%s) failed: %d\n", + headers[i].hdr, result); + unitfail++; + continue; + } + else if(result) { + printf("Input %u: error %d\n", i, (int) result); + continue; + } + } + + chost = headers[i].chost ? headers[i].chost : headers[i].host; + e = Curl_hsts(h, chost, TRUE); + showsts(e, chost); + } + + printf("Number of entries: %zu\n", Curl_llist_count(&h->list)); + + /* verify that it is exists for 7 seconds */ + chost = "expire.example"; + for(i = 100; i < 110; i++) { + e = Curl_hsts(h, chost, TRUE); + showsts(e, chost); + deltatime++; /* another second passed */ + } + + msnprintf(savename, sizeof(savename), "%s.save", arg); + (void)Curl_hsts_save(easy, h, savename); + Curl_hsts_cleanup(&h); + curl_easy_cleanup(easy); + curl_global_cleanup(); +} +UNITTEST_STOP +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1661.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1661.c new file mode 100644 index 0000000000000000000000000000000000000000..836e52f1a4f586cedf5cf88610fd99ca9b06525a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1661.c @@ -0,0 +1,116 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" +#include "bufref.h" +#include "memdebug.h" + +static struct bufref bufref; + +static int freecount = 0; + +static void test_free(void *p) +{ + fail_unless(p, "pointer to free may not be NULL"); + freecount++; + free(p); +} + +static CURLcode unit_setup(void) +{ + Curl_bufref_init(&bufref); + return CURLE_OK; +} + +static void unit_stop(void) +{ + Curl_bufref_free(&bufref); +} + +UNITTEST_START +{ + char *buffer = NULL; + CURLcode result = CURLE_OK; + + /** + * testing Curl_bufref_init. + * @assumptions: + * 1: data size will be 0 + * 2: reference will be NULL + * 3: destructor will be NULL + */ + + fail_unless(!bufref.ptr, "Initial reference must be NULL"); + fail_unless(!bufref.len, "Initial length must be NULL"); + fail_unless(!bufref.dtor, "Destructor must be NULL"); + + /** + * testing Curl_bufref_set + */ + + buffer = malloc(13); + abort_unless(buffer, "Out of memory"); + Curl_bufref_set(&bufref, buffer, 13, test_free); + + fail_unless((char *) bufref.ptr == buffer, "Referenced data badly set"); + fail_unless(bufref.len == 13, "Data size badly set"); + fail_unless(bufref.dtor == test_free, "Destructor badly set"); + + /** + * testing Curl_bufref_ptr + */ + + fail_unless((char *) Curl_bufref_ptr(&bufref) == buffer, + "Wrong pointer value returned"); + + /** + * testing Curl_bufref_len + */ + + fail_unless(Curl_bufref_len(&bufref) == 13, "Wrong data size returned"); + + /** + * testing Curl_bufref_memdup + */ + + result = Curl_bufref_memdup(&bufref, "1661", 3); + abort_unless(result == CURLE_OK, curl_easy_strerror(result)); + fail_unless(freecount == 1, "Destructor not called"); + fail_unless((char *) bufref.ptr != buffer, "Returned pointer not set"); + buffer = (char *) Curl_bufref_ptr(&bufref); + fail_unless(buffer, "Allocated pointer is NULL"); + fail_unless(bufref.len == 3, "Wrong data size stored"); + fail_unless(!buffer[3], "Duplicated data should have been truncated"); + fail_unless(!strcmp(buffer, "166"), "Bad duplicated data"); + + /** + * testing Curl_bufref_free + */ + + Curl_bufref_free(&bufref); + fail_unless(freecount == 1, "Wrong destructor called"); + fail_unless(!bufref.ptr, "Initial reference must be NULL"); + fail_unless(!bufref.len, "Initial length must be NULL"); + fail_unless(!bufref.dtor, "Destructor must be NULL"); +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit1663.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit1663.c new file mode 100644 index 0000000000000000000000000000000000000000..6967c0231f06e986d79f31146dec7cd1529900e9 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit1663.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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif + +#include + +#include "cf-socket.h" + +#include "memdebug.h" /* LAST include file */ + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + global_init(CURL_GLOBAL_ALL); + return res; +} + +static void unit_stop(void) +{ + curl_global_cleanup(); +} + +static void test_parse( + const char *input_data, + const char *exp_dev, + const char *exp_iface, + const char *exp_host, + CURLcode exp_rc) +{ + char *dev = NULL; + char *iface = NULL; + char *host = NULL; + CURLcode rc = Curl_parse_interface(input_data, &dev, &iface, &host); + fail_unless(rc == exp_rc, "Curl_parse_interface() failed"); + + fail_unless(!!exp_dev == !!dev, "dev expectation failed."); + fail_unless(!!exp_iface == !!iface, "iface expectation failed"); + fail_unless(!!exp_host == !!host, "host expectation failed"); + + if(!unitfail) { + fail_unless(!exp_dev || strcmp(dev, exp_dev) == 0, + "dev should be equal to exp_dev"); + fail_unless(!exp_iface || strcmp(iface, exp_iface) == 0, + "iface should be equal to exp_iface"); + fail_unless(!exp_host || strcmp(host, exp_host) == 0, + "host should be equal to exp_host"); + } + + free(dev); + free(iface); + free(host); +} + +UNITTEST_START +{ + test_parse("dev", "dev", NULL, NULL, CURLE_OK); + test_parse("if!eth0", NULL, "eth0", NULL, CURLE_OK); + test_parse("host!myname", NULL, NULL, "myname", CURLE_OK); + test_parse("ifhost!eth0!myname", NULL, "eth0", "myname", CURLE_OK); + test_parse("", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); + test_parse("!", "!", NULL, NULL, CURLE_OK); + test_parse("if!", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); + test_parse("if!eth0!blubb", NULL, "eth0!blubb", NULL, CURLE_OK); + test_parse("host!", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); + test_parse("ifhost!", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); + test_parse("ifhost!eth0", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); + test_parse("ifhost!eth0!", NULL, NULL, NULL, CURLE_BAD_FUNCTION_ARGUMENT); +} +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit2600.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit2600.c new file mode 100644 index 0000000000000000000000000000000000000000..352cdefbf2e97146290d50563ed69c4f56408ae1 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit2600.c @@ -0,0 +1,404 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.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 "connect.h" +#include "cfilters.h" +#include "multiif.h" +#include "select.h" +#include "curl_trc.h" +#include "memdebug.h" + +static CURL *easy; + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + + global_init(CURL_GLOBAL_ALL); + easy = curl_easy_init(); + if(!easy) { + curl_global_cleanup(); + return CURLE_OUT_OF_MEMORY; + } + curl_global_trace("all"); + curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L); + return res; +} + +static void unit_stop(void) +{ + curl_easy_cleanup(easy); + curl_global_cleanup(); +} + +struct test_case { + int id; + const char *url; + const char *resolve_info; + unsigned char ip_version; + timediff_t connect_timeout_ms; + timediff_t he_timeout_ms; + timediff_t cf4_fail_delay_ms; + timediff_t cf6_fail_delay_ms; + + int exp_cf4_creations; + int exp_cf6_creations; + timediff_t min_duration_ms; + timediff_t max_duration_ms; + CURLcode exp_result; + const char *pref_family; +}; + +struct ai_family_stats { + const char *family; + int creations; + timediff_t first_created; + timediff_t last_created; +}; + +struct test_result { + CURLcode result; + struct curltime started; + struct curltime ended; + struct ai_family_stats cf4; + struct ai_family_stats cf6; +}; + +static struct test_case *current_tc; +static struct test_result *current_tr; + +struct cf_test_ctx { + int ai_family; + int transport; + char id[16]; + struct curltime started; + timediff_t fail_delay_ms; + struct ai_family_stats *stats; +}; + +static void cf_test_destroy(struct Curl_cfilter *cf, struct Curl_easy *data) +{ + struct cf_test_ctx *ctx = cf->ctx; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + infof(data, "%04dms: cf[%s] destroyed", + (int)Curl_timediff(Curl_now(), current_tr->started), ctx->id); +#else + (void)data; +#endif + free(ctx); + cf->ctx = NULL; +} + +static CURLcode cf_test_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_test_ctx *ctx = cf->ctx; + timediff_t duration_ms; + + (void)data; + (void)blocking; + *done = FALSE; + duration_ms = Curl_timediff(Curl_now(), ctx->started); + if(duration_ms >= ctx->fail_delay_ms) { + infof(data, "%04dms: cf[%s] fail delay reached", + (int)duration_ms, ctx->id); + return CURLE_COULDNT_CONNECT; + } + if(duration_ms) { + infof(data, "%04dms: cf[%s] continuing", (int)duration_ms, ctx->id); + Curl_wait_ms(10); + } + Curl_expire(data, ctx->fail_delay_ms - duration_ms, EXPIRE_RUN_NOW); + return CURLE_OK; +} + +static void cf_test_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + /* just for testing, give one socket with events back */ + (void)cf; + Curl_pollset_set(data, ps, 1, TRUE, TRUE); +} + +static struct Curl_cftype cft_test = { + "TEST", + CF_TYPE_IP_CONNECT, + CURL_LOG_LVL_NONE, + cf_test_destroy, + cf_test_connect, + Curl_cf_def_close, + Curl_cf_def_shutdown, + Curl_cf_def_get_host, + cf_test_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_test_create(struct Curl_cfilter **pcf, + struct Curl_easy *data, + struct connectdata *conn, + const struct Curl_addrinfo *ai, + int transport) +{ + struct cf_test_ctx *ctx = NULL; + struct Curl_cfilter *cf = NULL; + timediff_t created_at; + CURLcode result; + + (void)data; + (void)conn; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->ai_family = ai->ai_family; + ctx->transport = transport; + ctx->started = Curl_now(); +#ifdef USE_IPV6 + if(ctx->ai_family == AF_INET6) { + ctx->stats = ¤t_tr->cf6; + ctx->fail_delay_ms = current_tc->cf6_fail_delay_ms; + curl_msprintf(ctx->id, "v6-%d", ctx->stats->creations); + ctx->stats->creations++; + } + else +#endif + { + ctx->stats = ¤t_tr->cf4; + ctx->fail_delay_ms = current_tc->cf4_fail_delay_ms; + curl_msprintf(ctx->id, "v4-%d", ctx->stats->creations); + ctx->stats->creations++; + } + + created_at = Curl_timediff(ctx->started, current_tr->started); + if(ctx->stats->creations == 1) + ctx->stats->first_created = created_at; + ctx->stats->last_created = created_at; + infof(data, "%04dms: cf[%s] created", (int)created_at, ctx->id); + + result = Curl_cf_create(&cf, &cft_test, ctx); + if(result) + goto out; + + Curl_expire(data, ctx->fail_delay_ms, EXPIRE_RUN_NOW); + +out: + *pcf = (!result) ? cf : NULL; + if(result) { + free(cf); + free(ctx); + } + return result; +} + +static void check_result(struct test_case *tc, + struct test_result *tr) +{ + char msg[256]; + timediff_t duration_ms; + + duration_ms = Curl_timediff(tr->ended, tr->started); + fprintf(stderr, "%d: test case took %dms\n", tc->id, (int)duration_ms); + + if(tr->result != tc->exp_result + && CURLE_OPERATION_TIMEDOUT != tr->result) { + /* on CI we encounter the TIMEOUT result, since images get less CPU + * and events are not as sharply timed. */ + curl_msprintf(msg, "%d: expected result %d but got %d", + tc->id, tc->exp_result, tr->result); + fail(msg); + } + if(tr->cf4.creations != tc->exp_cf4_creations) { + curl_msprintf(msg, "%d: expected %d ipv4 creations, but got %d", + tc->id, tc->exp_cf4_creations, tr->cf4.creations); + fail(msg); + } + if(tr->cf6.creations != tc->exp_cf6_creations) { + curl_msprintf(msg, "%d: expected %d ipv6 creations, but got %d", + tc->id, tc->exp_cf6_creations, tr->cf6.creations); + fail(msg); + } + + duration_ms = Curl_timediff(tr->ended, tr->started); + if(duration_ms < tc->min_duration_ms) { + curl_msprintf(msg, "%d: expected min duration of %dms, but took %dms", + tc->id, (int)tc->min_duration_ms, (int)duration_ms); + fail(msg); + } + if(duration_ms > tc->max_duration_ms) { + curl_msprintf(msg, "%d: expected max duration of %dms, but took %dms", + tc->id, (int)tc->max_duration_ms, (int)duration_ms); + fail(msg); + } + if(tr->cf6.creations && tr->cf4.creations && tc->pref_family) { + /* did ipv4 and ipv6 both, expect the preferred family to start right arway + * with the other being delayed by the happy_eyeball_timeout */ + struct ai_family_stats *stats1 = !strcmp(tc->pref_family, "v6") ? + &tr->cf6 : &tr->cf4; + struct ai_family_stats *stats2 = !strcmp(tc->pref_family, "v6") ? + &tr->cf4 : &tr->cf6; + + if(stats1->first_created > 100) { + curl_msprintf(msg, "%d: expected ip%s to start right away, instead " + "first attempt made after %dms", + tc->id, stats1->family, (int)stats1->first_created); + fail(msg); + } + if(stats2->first_created < tc->he_timeout_ms) { + curl_msprintf(msg, "%d: expected ip%s to start delayed after %dms, " + "instead first attempt made after %dms", + tc->id, stats2->family, (int)tc->he_timeout_ms, + (int)stats2->first_created); + fail(msg); + } + } +} + +static void test_connect(struct test_case *tc) +{ + struct test_result tr; + struct curl_slist *list = NULL; + + Curl_debug_set_transport_provider(TRNSPRT_TCP, cf_test_create); + current_tc = tc; + current_tr = &tr; + + list = curl_slist_append(NULL, tc->resolve_info); + fail_unless(list, "error allocating resolve list entry"); + curl_easy_setopt(easy, CURLOPT_RESOLVE, list); + curl_easy_setopt(easy, CURLOPT_IPRESOLVE, (long)tc->ip_version); + curl_easy_setopt(easy, CURLOPT_CONNECTTIMEOUT_MS, + (long)tc->connect_timeout_ms); + curl_easy_setopt(easy, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, + (long)tc->he_timeout_ms); + + curl_easy_setopt(easy, CURLOPT_URL, tc->url); + memset(&tr, 0, sizeof(tr)); + tr.cf6.family = "v6"; + tr.cf4.family = "v4"; + + tr.started = Curl_now(); + tr.result = curl_easy_perform(easy); + tr.ended = Curl_now(); + + curl_easy_setopt(easy, CURLOPT_RESOLVE, NULL); + curl_slist_free_all(list); + list = NULL; + current_tc = NULL; + current_tr = NULL; + + check_result(tc, &tr); +} + +/* + * How these test cases work: + * - replace the creation of the TCP socket filter with our test filter + * - test filter does nothing and reports failure after configured delay + * - we feed addresses into the resolve cache to simulate different cases + * - we monitor how many instances of ipv4/v6 attempts are made and when + * - for mixed families, we expect HAPPY_EYEBALLS_TIMEOUT to trigger + * + * Max Duration checks needs to be conservative since CI jobs are not + * as sharp. + */ +#define TURL "http://test.com:123" + +#define R_FAIL CURLE_COULDNT_CONNECT +/* timeout values accounting for low cpu resources in CI */ +#define TC_TMOT 90000 /* 90 sec max test duration */ +#define CNCT_TMOT 60000 /* 60sec connect timeout */ + +static struct test_case TEST_CASES[] = { + /* TIMEOUT_MS, FAIL_MS CREATED DURATION Result, HE_PREF */ + /* CNCT HE v4 v6 v4 v6 MIN MAX */ + { 1, TURL, "test.com:123:192.0.2.1", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 1, 0, 200, TC_TMOT, R_FAIL, NULL }, + /* 1 ipv4, fails after ~200ms, reports COULDNT_CONNECT */ + { 2, TURL, "test.com:123:192.0.2.1,192.0.2.2", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 2, 0, 400, TC_TMOT, R_FAIL, NULL }, + /* 2 ipv4, fails after ~400ms, reports COULDNT_CONNECT */ +#ifdef USE_IPV6 + { 3, TURL, "test.com:123:::1", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 0, 1, 200, TC_TMOT, R_FAIL, NULL }, + /* 1 ipv6, fails after ~200ms, reports COULDNT_CONNECT */ + { 4, TURL, "test.com:123:::1,::2", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 0, 2, 400, TC_TMOT, R_FAIL, NULL }, + /* 2 ipv6, fails after ~400ms, reports COULDNT_CONNECT */ + + { 5, TURL, "test.com:123:192.0.2.1,::1", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 1, 1, 350, TC_TMOT, R_FAIL, "v6" }, + /* mixed ip4+6, v6 always first, v4 kicks in on HE, fails after ~350ms */ + { 6, TURL, "test.com:123:::1,192.0.2.1", CURL_IPRESOLVE_WHATEVER, + CNCT_TMOT, 150, 200, 200, 1, 1, 350, TC_TMOT, R_FAIL, "v6" }, + /* mixed ip6+4, v6 starts, v4 never starts due to high HE, TIMEOUT */ + { 7, TURL, "test.com:123:192.0.2.1,::1", CURL_IPRESOLVE_V4, + CNCT_TMOT, 150, 500, 500, 1, 0, 400, TC_TMOT, R_FAIL, NULL }, + /* mixed ip4+6, but only use v4, check it uses full connect timeout, + although another address of the 'wrong' family is available */ + { 8, TURL, "test.com:123:::1,192.0.2.1", CURL_IPRESOLVE_V6, + CNCT_TMOT, 150, 500, 500, 0, 1, 400, TC_TMOT, R_FAIL, NULL }, + /* mixed ip4+6, but only use v6, check it uses full connect timeout, + although another address of the 'wrong' family is available */ +#endif +}; + +UNITTEST_START + + size_t i; + + for(i = 0; i < sizeof(TEST_CASES)/sizeof(TEST_CASES[0]); ++i) { + test_connect(&TEST_CASES[i]); + } + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit2601.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit2601.c new file mode 100644 index 0000000000000000000000000000000000000000..1744d9d315676fa780490e7e25606ec662c28c62 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit2601.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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#include "urldata.h" +#include "bufq.h" +#include "curl_trc.h" + +static CURLcode unit_setup(void) +{ + CURLcode res = CURLE_OK; + return res; +} + +static void unit_stop(void) +{ +} + +static const char *tail_err(struct bufq *q) +{ + struct buf_chunk *chunk; + + if(!q->tail) { + return q->head ? "tail is NULL, but head is not" : NULL; + } + + chunk = q->head; + while(chunk) { + if(chunk == q->tail) { + if(chunk->next) { + return "tail points to queue, but not at the end"; + } + return NULL; + } + chunk = chunk->next; + } + return "tail not part of queue"; +} + +static void dump_bufq(struct bufq *q, const char *msg) +{ + struct buf_chunk *chunk; + const char *terr; + size_t n; + + fprintf(stderr, "bufq[chunk_size=%zu, max_chunks=%zu] %s\n", + q->chunk_size, q->max_chunks, msg); + fprintf(stderr, "- queue[\n"); + chunk = q->head; + while(chunk) { + fprintf(stderr, " chunk[len=%zu, roff=%zu, woff=%zu]\n", + chunk->dlen, chunk->r_offset, chunk->w_offset); + chunk = chunk->next; + } + fprintf(stderr, " ]\n"); + terr = tail_err(q); + fprintf(stderr, "- tail: %s\n", terr ? terr : "ok"); + n = 0; + chunk = q->spare; + while(chunk) { + ++n; + chunk = chunk->next; + } + fprintf(stderr, "- chunks: %zu\n", q->chunk_count); + fprintf(stderr, "- spares: %zu\n", n); +} + +static unsigned char test_data[32*1024]; + +static void check_bufq(size_t pool_spares, + size_t chunk_size, size_t max_chunks, + size_t wsize, size_t rsize, int opts) +{ + struct bufq q; + struct bufc_pool pool; + size_t max_len = chunk_size * max_chunks; + CURLcode result; + ssize_t n, i; + size_t nwritten, nread; + + if(pool_spares > 0) { + Curl_bufcp_init(&pool, chunk_size, pool_spares); + Curl_bufq_initp(&q, &pool, max_chunks, opts); + } + else { + Curl_bufq_init2(&q, chunk_size, max_chunks, opts); + } + + fail_unless(q.chunk_size == chunk_size, "chunk_size init wrong"); + fail_unless(q.max_chunks == max_chunks, "max_chunks init wrong"); + fail_unless(q.head == NULL, "init: head not NULL"); + fail_unless(q.tail == NULL, "init: tail not NULL"); + fail_unless(q.spare == NULL, "init: spare not NULL"); + fail_unless(Curl_bufq_len(&q) == 0, "init: bufq length != 0"); + + n = Curl_bufq_write(&q, test_data, wsize, &result); + fail_unless(n >= 0, "write: negative size returned"); + fail_unless((size_t)n <= wsize, "write: wrong size returned"); + fail_unless(result == CURLE_OK, "write: wrong result returned"); + + /* write empty bufq full */ + nwritten = 0; + Curl_bufq_reset(&q); + while(!Curl_bufq_is_full(&q)) { + n = Curl_bufq_write(&q, test_data, wsize, &result); + if(n >= 0) { + nwritten += (size_t)n; + } + else if(result != CURLE_AGAIN) { + fail_unless(result == CURLE_AGAIN, "write-loop: unexpected result"); + break; + } + } + if(nwritten != max_len) { + fprintf(stderr, "%zu bytes written, but max_len=%zu\n", + nwritten, max_len); + dump_bufq(&q, "after writing full"); + fail_if(TRUE, "write: bufq full but nwritten wrong"); + } + + /* read full bufq empty */ + nread = 0; + while(!Curl_bufq_is_empty(&q)) { + n = Curl_bufq_read(&q, test_data, rsize, &result); + if(n >= 0) { + nread += (size_t)n; + } + else if(result != CURLE_AGAIN) { + fail_unless(result == CURLE_AGAIN, "read-loop: unexpected result"); + break; + } + } + if(nread != max_len) { + fprintf(stderr, "%zu bytes read, but max_len=%zu\n", + nwritten, max_len); + dump_bufq(&q, "after reading empty"); + fail_if(TRUE, "read: bufq empty but nread wrong"); + } + if(q.tail) { + dump_bufq(&q, "after reading empty"); + fail_if(TRUE, "read empty, but tail is not NULL"); + } + + for(i = 0; i < 1000; ++i) { + n = Curl_bufq_write(&q, test_data, wsize, &result); + if(n < 0 && result != CURLE_AGAIN) { + fail_unless(result == CURLE_AGAIN, "rw-loop: unexpected write result"); + break; + } + n = Curl_bufq_read(&q, test_data, rsize, &result); + if(n < 0 && result != CURLE_AGAIN) { + fail_unless(result == CURLE_AGAIN, "rw-loop: unexpected read result"); + break; + } + } + + /* Test SOFT_LIMIT option */ + Curl_bufq_free(&q); + Curl_bufq_init2(&q, chunk_size, max_chunks, (opts|BUFQ_OPT_SOFT_LIMIT)); + nwritten = 0; + while(!Curl_bufq_is_full(&q)) { + n = Curl_bufq_write(&q, test_data, wsize, &result); + if(n < 0 || (size_t)n != wsize) { + fail_unless(n > 0 && (size_t)n == wsize, "write should be complete"); + break; + } + nwritten += (size_t)n; + } + if(nwritten < max_len) { + fprintf(stderr, "%zu bytes written, but max_len=%zu\n", + nwritten, max_len); + dump_bufq(&q, "after writing full"); + fail_if(TRUE, "write: bufq full but nwritten wrong"); + } + /* do one more write on a full bufq, should work */ + n = Curl_bufq_write(&q, test_data, wsize, &result); + fail_unless(n > 0 && (size_t)n == wsize, "write should be complete"); + nwritten += (size_t)n; + /* see that we get all out again */ + nread = 0; + while(!Curl_bufq_is_empty(&q)) { + n = Curl_bufq_read(&q, test_data, rsize, &result); + if(n <= 0) { + fail_unless(n > 0, "read-loop: unexpected fail"); + break; + } + nread += (size_t)n; + } + fail_unless(nread == nwritten, "did not get the same out as put in"); + + /* CHECK bufq_unwrite: write a string repeatedly into the second chunk. + * bufq_unwrite() 1 byte. Read strings again and check for content. + * We had a bug that unwrite used the head chunk instead of tail, which + * did corrupt the read values. */ + if(TRUE) { + const unsigned char buf[] = "0123456789--"; + size_t roffset; + Curl_bufq_reset(&q); + while(Curl_bufq_len(&q) < chunk_size) { + n = Curl_bufq_write(&q, buf, sizeof(buf), &result); + fail_unless(n > 0 && (size_t)n == sizeof(buf), "write incomplete"); + if(result) + break; + } + result = Curl_bufq_unwrite(&q, 1); + roffset = 0; + while(!Curl_bufq_is_empty(&q)) { + unsigned char rbuf[sizeof(buf)]; + n = Curl_bufq_read(&q, rbuf, sizeof(rbuf), &result); + fail_unless(n > 0, "read should work"); + if(result) + break; + if(n != sizeof(rbuf)) { + fail_unless(Curl_bufq_is_empty(&q), "should be last read"); + } + if(memcmp(buf, rbuf, n)) { + fprintf(stderr, "at offset %zu expected '%.*s', got '%.*s'\n", + roffset, (int)n, buf, (int)n, rbuf); + fail("read buf content wrong"); + } + roffset += n; + } + Curl_bufq_reset(&q); + } + + dump_bufq(&q, "at end of test"); + Curl_bufq_free(&q); + if(pool_spares > 0) + Curl_bufcp_free(&pool); +} + +UNITTEST_START + struct bufq q; + ssize_t n; + CURLcode result; + unsigned char buf[16*1024]; + + Curl_bufq_init(&q, 8*1024, 12); + n = Curl_bufq_read(&q, buf, 128, &result); + fail_unless(n < 0 && result == CURLE_AGAIN, "read empty fail"); + Curl_bufq_free(&q); + + check_bufq(0, 1024, 4, 128, 128, BUFQ_OPT_NONE); + check_bufq(0, 1024, 4, 129, 127, BUFQ_OPT_NONE); + check_bufq(0, 1024, 4, 2000, 16000, BUFQ_OPT_NONE); + check_bufq(0, 1024, 4, 16000, 3000, BUFQ_OPT_NONE); + + check_bufq(0, 8000, 10, 1234, 1234, BUFQ_OPT_NONE); + check_bufq(0, 8000, 10, 8*1024, 4*1024, BUFQ_OPT_NONE); + + check_bufq(0, 1024, 4, 128, 128, BUFQ_OPT_NO_SPARES); + check_bufq(0, 1024, 4, 129, 127, BUFQ_OPT_NO_SPARES); + check_bufq(0, 1024, 4, 2000, 16000, BUFQ_OPT_NO_SPARES); + check_bufq(0, 1024, 4, 16000, 3000, BUFQ_OPT_NO_SPARES); + + check_bufq(8, 1024, 4, 128, 128, BUFQ_OPT_NONE); + check_bufq(8, 8000, 10, 1234, 1234, BUFQ_OPT_NONE); + check_bufq(8, 1024, 4, 129, 127, BUFQ_OPT_NO_SPARES); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit2602.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit2602.c new file mode 100644 index 0000000000000000000000000000000000000000..41476c60f0586578a48453e0c213df7b2e3f965a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit2602.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" + +#include "urldata.h" +#include "dynbuf.h" +#include "dynhds.h" +#include "curl_trc.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + + +UNITTEST_START + + struct dynhds hds; + struct dynbuf dbuf; + CURLcode result; + size_t i; + + /* add 1 more header than allowed */ + Curl_dynhds_init(&hds, 2, 128); + fail_if(Curl_dynhds_count(&hds), "should be empty"); + fail_if(Curl_dynhds_add(&hds, "test1", 5, "123", 3), "add failed"); + fail_if(Curl_dynhds_add(&hds, "test2", 5, "456", 3), "add failed"); + /* remove and add without exceeding limits */ + for(i = 0; i < 100; ++i) { + if(Curl_dynhds_remove(&hds, "test2", 5) != 1) { + fail_if(TRUE, "should"); + break; + } + if(Curl_dynhds_add(&hds, "test2", 5, "456", 3)) { + fail_if(TRUE, "add failed"); + break; + } + } + fail_unless(Curl_dynhds_count(&hds) == 2, "should hold 2"); + /* set, replacing previous entry without exceeding limits */ + for(i = 0; i < 100; ++i) { + if(Curl_dynhds_set(&hds, "test2", 5, "456", 3)) { + fail_if(TRUE, "add failed"); + break; + } + } + fail_unless(Curl_dynhds_count(&hds) == 2, "should hold 2"); + /* exceed limit on # of entries */ + result = Curl_dynhds_add(&hds, "test3", 5, "789", 3); + fail_unless(result, "add should have failed"); + + fail_unless(Curl_dynhds_count_name(&hds, "test", 4) == 0, "false positive"); + fail_unless(Curl_dynhds_count_name(&hds, "test1", 4) == 0, "false positive"); + fail_if(Curl_dynhds_get(&hds, "test1", 4), "false positive"); + fail_unless(Curl_dynhds_get(&hds, "test1", 5), "false negative"); + fail_unless(Curl_dynhds_count_name(&hds, "test1", 5) == 1, "should"); + fail_unless(Curl_dynhds_ccount_name(&hds, "test2") == 1, "should"); + fail_unless(Curl_dynhds_cget(&hds, "test2"), "should"); + fail_unless(Curl_dynhds_ccount_name(&hds, "TEST2") == 1, "should"); + fail_unless(Curl_dynhds_ccontains(&hds, "TesT2"), "should"); + fail_unless(Curl_dynhds_contains(&hds, "TeSt2", 5), "should"); + Curl_dynhds_free(&hds); + + /* add header exceeding max overall length */ + Curl_dynhds_init(&hds, 128, 10); + fail_if(Curl_dynhds_add(&hds, "test1", 5, "123", 3), "add failed"); + fail_unless(Curl_dynhds_add(&hds, "test2", 5, "456", 3), "should fail"); + fail_if(Curl_dynhds_add(&hds, "t", 1, "1", 1), "add failed"); + Curl_dynhds_reset(&hds); + Curl_dynhds_free(&hds); + + Curl_dynhds_init(&hds, 128, 4*1024); + fail_if(Curl_dynhds_add(&hds, "test1", 5, "123", 3), "add failed"); + fail_if(Curl_dynhds_add(&hds, "test1", 5, "123", 3), "add failed"); + fail_if(Curl_dynhds_cadd(&hds, "blablabla", "thingies"), "add failed"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, "blablabla: thingies"), "add failed"); + fail_unless(Curl_dynhds_ccount_name(&hds, "blablabla") == 2, "should"); + fail_unless(Curl_dynhds_cremove(&hds, "blablabla") == 2, "should"); + fail_if(Curl_dynhds_ccontains(&hds, "blablabla"), "should not"); + + result = Curl_dynhds_h1_cadd_line(&hds, "blablabla thingies"); + fail_unless(result, "add should have failed"); + if(!result) { + fail_unless(Curl_dynhds_ccount_name(&hds, "bLABlaBlA") == 0, "should"); + fail_if(Curl_dynhds_cadd(&hds, "Bla-Bla", "thingies"), "add failed"); + + Curl_dyn_init(&dbuf, 32*1024); + fail_if(Curl_dynhds_h1_dprint(&hds, &dbuf), "h1 print failed"); + if(Curl_dyn_ptr(&dbuf)) { + fail_if(strcmp(Curl_dyn_ptr(&dbuf), + "test1: 123\r\ntest1: 123\r\nBla-Bla: thingies\r\n"), + "h1 format differs"); + } + Curl_dyn_free(&dbuf); + } + + Curl_dynhds_free(&hds); + Curl_dynhds_init(&hds, 128, 4*1024); + /* continuation without previous header fails */ + result = Curl_dynhds_h1_cadd_line(&hds, " indented value"); + fail_unless(result, "add should have failed"); + + /* continuation with previous header must succeed */ + fail_if(Curl_dynhds_h1_cadd_line(&hds, "ti1: val1"), "add"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, " val2"), "add indent"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, "ti2: val1"), "add"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, "\tval2"), "add indent"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, "ti3: val1"), "add"); + fail_if(Curl_dynhds_h1_cadd_line(&hds, " val2"), "add indent"); + + Curl_dyn_init(&dbuf, 32*1024); + fail_if(Curl_dynhds_h1_dprint(&hds, &dbuf), "h1 print failed"); + if(Curl_dyn_ptr(&dbuf)) { + fprintf(stderr, "indent concat: %s\n", Curl_dyn_ptr(&dbuf)); + fail_if(strcmp(Curl_dyn_ptr(&dbuf), + "ti1: val1 val2\r\nti2: val1 val2\r\nti3: val1 val2\r\n"), + "wrong format"); + } + Curl_dyn_free(&dbuf); + + Curl_dynhds_free(&hds); + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit2603.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit2603.c new file mode 100644 index 0000000000000000000000000000000000000000..2775a4565a97b86aa2fd11b3497b737ead3b2ddd --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit2603.c @@ -0,0 +1,194 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the 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 "curlcheck.h" + +#include "urldata.h" +#include "http.h" +#include "http1.h" +#include "curl_trc.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +#ifndef CURL_DISABLE_HTTP +struct tcase { + const char **input; + const char *default_scheme; + const char *method; + const char *scheme; + const char *authority; + const char *path; + size_t header_count; + size_t input_remain; +}; + +static void check_eq(const char *s, const char *exp_s, const char *name) +{ + if(s && exp_s) { + if(strcmp(s, exp_s)) { + fprintf(stderr, "expected %s: '%s' but got '%s'\n", name, exp_s, s); + fail("unexpected req component"); + } + } + else if(!s && exp_s) { + fprintf(stderr, "expected %s: '%s' but got NULL\n", name, exp_s); + fail("unexpected req component"); + } + else if(s && !exp_s) { + fprintf(stderr, "expected %s: NULL but got '%s'\n", name, s); + fail("unexpected req component"); + } +} + +static void parse_success(struct tcase *t) +{ + struct h1_req_parser p; + const char *buf; + size_t buflen, i, in_len, in_consumed; + CURLcode err; + ssize_t nread; + + Curl_h1_req_parse_init(&p, 1024); + in_len = in_consumed = 0; + for(i = 0; t->input[i]; ++i) { + buf = t->input[i]; + buflen = strlen(buf); + in_len += buflen; + nread = Curl_h1_req_parse_read(&p, buf, buflen, t->default_scheme, + 0, &err); + if(nread < 0) { + fprintf(stderr, "got err %d parsing: '%s'\n", err, buf); + fail("error consuming"); + } + in_consumed += (size_t)nread; + if((size_t)nread != buflen) { + if(!p.done) { + fprintf(stderr, "only %zd/%zu consumed for: '%s'\n", + nread, buflen, buf); + fail("not all consumed"); + } + } + } + + fail_if(!p.done, "end not detected"); + fail_if(!p.req, "not request created"); + if(t->input_remain != (in_len - in_consumed)) { + fprintf(stderr, "expected %zu input bytes to remain, but got %zu\n", + t->input_remain, in_len - in_consumed); + fail("unexpected input consumption"); + } + if(p.req) { + check_eq(p.req->method, t->method, "method"); + check_eq(p.req->scheme, t->scheme, "scheme"); + check_eq(p.req->authority, t->authority, "authority"); + check_eq(p.req->path, t->path, "path"); + if(Curl_dynhds_count(&p.req->headers) != t->header_count) { + fprintf(stderr, "expected %zu headers but got %zu\n", t->header_count, + Curl_dynhds_count(&p.req->headers)); + fail("unexpected req header count"); + } + } + + Curl_h1_req_parse_free(&p); +} + +static const char *T1_INPUT[] = { + "GET /path HTTP/1.1\r\nHost: test.curl.se\r\n\r\n", + NULL, +}; +static struct tcase TEST1a = { + T1_INPUT, NULL, "GET", NULL, NULL, "/path", 1, 0 +}; +static struct tcase TEST1b = { + T1_INPUT, "https", "GET", "https", NULL, "/path", 1, 0 +}; + +static const char *T2_INPUT[] = { + "GET /path HTT", + "P/1.1\r\nHost: te", + "st.curl.se\r\n\r", + "\n12345678", + NULL, +}; +static struct tcase TEST2 = { + T2_INPUT, NULL, "GET", NULL, NULL, "/path", 1, 8 +}; + +static const char *T3_INPUT[] = { + "GET ftp://ftp.curl.se/xxx?a=2 HTTP/1.1\r\nContent-Length: 0\r", + "\nUser-Agent: xxx\r\n\r\n", + NULL, +}; +static struct tcase TEST3a = { + T3_INPUT, NULL, "GET", "ftp", "ftp.curl.se", "/xxx?a=2", 2, 0 +}; + +static const char *T4_INPUT[] = { + "CONNECT ftp.curl.se:123 HTTP/1.1\r\nContent-Length: 0\r\n", + "User-Agent: xxx\r\n", + "nothing: \r\n\r\n\n\n", + NULL, +}; +static struct tcase TEST4a = { + T4_INPUT, NULL, "CONNECT", NULL, "ftp.curl.se:123", NULL, 3, 2 +}; + +static const char *T5_INPUT[] = { + "OPTIONS * HTTP/1.1\r\nContent-Length: 0\r\nBlabla: xxx.yyy\r", + "\n\tzzzzzz\r\n\r\n", + "123", + NULL, +}; +static struct tcase TEST5a = { + T5_INPUT, NULL, "OPTIONS", NULL, NULL, "*", 2, 3 +}; + +static const char *T6_INPUT[] = { + "PUT /path HTTP/1.1\nHost: test.curl.se\n\n123", + NULL, +}; +static struct tcase TEST6a = { + T6_INPUT, NULL, "PUT", NULL, NULL, "/path", 1, 3 +}; +#endif + +UNITTEST_START + +#ifndef CURL_DISABLE_HTTP + parse_success(&TEST1a); + parse_success(&TEST1b); + parse_success(&TEST2); + parse_success(&TEST3a); + parse_success(&TEST4a); + parse_success(&TEST5a); + parse_success(&TEST6a); +#endif + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit2604.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit2604.c new file mode 100644 index 0000000000000000000000000000000000000000..fc7017e4a89a3713bc46b0047a92ac11105d8506 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit2604.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 "curlcheck.h" +#include "vssh/curl_path.h" +#include "memdebug.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + + +struct set { + const char *cp; + const char *expect; /* the returned content */ + const char *next; /* what cp points to after the call */ + const char *home; + CURLcode result; +}; + +UNITTEST_START +#ifdef USE_SSH +{ +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Woverlength-strings" +#endif + +/* 60 a's */ +#define SA60 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +/* 540 a's */ +#define SA540 SA60 SA60 SA60 SA60 SA60 SA60 SA60 SA60 SA60 + int i; + size_t too_long = 90720; + struct set list[] = { + { "-too-long-", "", "", "", CURLE_TOO_LARGE}, + { SA540 " c", SA540, "c", "/", CURLE_OK}, + { "\" " SA540 "\" c", " " SA540, "c", "/", CURLE_OK}, + { "a a", "a", "a", "/home/", CURLE_OK}, + { "b a", "b", "a", "/", CURLE_OK}, + { "a", "a", "", "/home/", CURLE_OK}, + { "b", "b", "", "/", CURLE_OK}, + { "\"foo bar\"\tb", "foo bar", "b", "/", CURLE_OK}, + { "/~/hej", "/home/user/hej", "", "/home/user", CURLE_OK}, + { "\"foo bar", "", "", "/", CURLE_QUOTE_ERROR}, + { "\"foo\\\"bar\" a", "foo\"bar", "a", "/", CURLE_OK}, + { "\"foo\\\'bar\" b", "foo\'bar", "b", "/", CURLE_OK}, + { "\"foo\\\\bar\" c", "foo\\bar", "c", "/", CURLE_OK}, + { "\"foo\\pbar\" c", "foo\\bar", "", "/", CURLE_QUOTE_ERROR}, + { "\"\" c", "", "", "", CURLE_QUOTE_ERROR}, + { "foo\"", "foo\"", "", "/", CURLE_OK}, + { "foo \"", "foo", "\"", "/", CURLE_OK}, + { NULL, NULL, NULL, NULL, CURLE_OK } + }; + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic warning "-Woverlength-strings" +#endif + + list[0].cp = calloc(1, too_long + 1); + fail_unless(list[0].cp, "could not alloc too long value"); + memset((void *)list[0].cp, 'a', too_long); + + for(i = 0; list[i].home; i++) { + char *path; + const char *cp = list[i].cp; + CURLcode result = Curl_get_pathname(&cp, &path, list[i].home); + printf("%u - Curl_get_pathname(\"%s\", ... \"%s\") == %u\n", i, + list[i].cp, list[i].home, list[i].result); + if(result != list[i].result) { + printf("... returned %d\n", result); + unitfail++; + } + if(!result) { + if(cp && strcmp(cp, list[i].next)) { + printf("... cp points to '%s', not '%s' as expected \n", + cp, list[i].next); + unitfail++; + } + if(path && strcmp(path, list[i].expect)) { + printf("... gave '%s', not '%s' as expected \n", + path, list[i].expect); + unitfail++; + } + curl_free(path); + + } + } + + free((void *)list[0].cp); +} +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif + +UNITTEST_STOP diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit3200.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit3200.c new file mode 100644 index 0000000000000000000000000000000000000000..92e179fc79ccfdfe803deb10c618d23b25f74158 --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit3200.c @@ -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 + * + ***************************************************************************/ +#include "curlcheck.h" +#include "curl_get_line.h" +#include "memdebug.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC) + +/* The test XML does not supply a way to write files without newlines + * so we write our own + */ + +#define C64 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +#define C256 C64 C64 C64 C64 +#define C1024 C256 C256 C256 C256 +#define C4096 C1024 C1024 C1024 C1024 + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static CURLcode unit_stop(void) +{ + return CURLE_OK; +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Woverlength-strings" +#endif + +#define NUMTESTS 6 +static const char *filecontents[] = { + /* Both should be read */ + "LINE1\n" + "LINE2 NEWLINE\n", + + /* Both should be read */ + "LINE1\n" + "LINE2 NONEWLINE", + + /* Only first should be read */ + "LINE1\n" + C4096, + + /* First line should be read */ + "LINE1\n" + C4096 "SOME EXTRA TEXT", + + /* Only first should be read */ + "LINE1\n" + C4096 "SOME EXTRA TEXT\n" + "LINE3\n", + + "LINE1\x1aTEST" +}; + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic warning "-Woverlength-strings" +#endif + + +UNITTEST_START + size_t i; + int rc = 0; + for(i = 0; i < NUMTESTS; i++) { + FILE *fp; + struct dynbuf buf; + size_t len = 4096; + char *line; + Curl_dyn_init(&buf, len); + + fp = fopen(arg, "wb"); + abort_unless(fp != NULL, "Cannot open testfile"); + fwrite(filecontents[i], 1, strlen(filecontents[i]), fp); + fclose(fp); + + fp = fopen(arg, "rb"); + abort_unless(fp != NULL, "Cannot open testfile"); + + fprintf(stderr, "Test %zd...", i); + switch(i) { + case 0: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\n", line), + "First line failed (1)"); + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE2 NEWLINE\n", line), + "Second line failed (1)"); + rc = Curl_get_line(&buf, fp); + abort_unless(!Curl_dyn_len(&buf), "Missed EOF (1)"); + break; + case 1: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\n", line), + "First line failed (2)"); + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE2 NONEWLINE\n", line), + "Second line failed (2)"); + rc = Curl_get_line(&buf, fp); + abort_unless(!Curl_dyn_len(&buf), "Missed EOF (2)"); + break; + case 2: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\n", line), + "First line failed (3)"); + rc = Curl_get_line(&buf, fp); + fail_unless(!Curl_dyn_len(&buf), + "Did not detect max read on EOF (3)"); + break; + case 3: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\n", line), + "First line failed (4)"); + rc = Curl_get_line(&buf, fp); + fail_unless(!Curl_dyn_len(&buf), + "Did not ignore partial on EOF (4)"); + break; + case 4: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\n", line), + "First line failed (5)"); + rc = Curl_get_line(&buf, fp); + fail_unless(!Curl_dyn_len(&buf), + "Did not bail out on too long line"); + break; + case 5: + rc = Curl_get_line(&buf, fp); + line = Curl_dyn_ptr(&buf); + fail_unless(line && !strcmp("LINE1\x1aTEST\n", line), + "Missed/Misinterpreted ^Z (6)"); + rc = Curl_get_line(&buf, fp); + abort_unless(!Curl_dyn_len(&buf), "Missed EOF (6)"); + break; + default: + abort_unless(1, "Unknown case"); + break; + } + Curl_dyn_free(&buf); + fclose(fp); + fprintf(stderr, "OK\n"); + } + return (CURLcode)rc; +UNITTEST_STOP + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#else +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} +static void unit_stop(void) +{ +} +UNITTEST_START +UNITTEST_STOP + +#endif diff --git a/local-test-curl-delta-01/afc-curl/tests/unit/unit3205.c b/local-test-curl-delta-01/afc-curl/tests/unit/unit3205.c new file mode 100644 index 0000000000000000000000000000000000000000..4a2423e6bf54ff8d4a9d4c1d84b231c987729e1a --- /dev/null +++ b/local-test-curl-delta-01/afc-curl/tests/unit/unit3205.c @@ -0,0 +1,797 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "curlcheck.h" + +#include "vtls/cipher_suite.h" + +static CURLcode unit_setup(void) +{ + return CURLE_OK; +} + +static void unit_stop(void) +{ +} + +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) + +struct test_cs_entry { + uint16_t id; + const char *rfc; + const char *openssl; +}; +static const struct test_cs_entry test_cs_list[] = { +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_RUSTLS) + { 0x1301, "TLS_AES_128_GCM_SHA256", + NULL }, + { 0x1302, "TLS_AES_256_GCM_SHA384", + NULL }, + { 0x1303, "TLS_CHACHA20_POLY1305_SHA256", + NULL }, + { 0x1304, "TLS_AES_128_CCM_SHA256", + NULL }, + { 0x1305, "TLS_AES_128_CCM_8_SHA256", + NULL }, +#endif + { 0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", + "ECDHE-ECDSA-AES128-GCM-SHA256" }, + { 0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", + "ECDHE-ECDSA-AES256-GCM-SHA384" }, + { 0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", + "ECDHE-RSA-AES128-GCM-SHA256" }, + { 0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", + "ECDHE-RSA-AES256-GCM-SHA384" }, + { 0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "ECDHE-RSA-CHACHA20-POLY1305" }, + { 0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", + "ECDHE-ECDSA-CHACHA20-POLY1305" }, +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_BEARSSL) + { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA", + "AES128-SHA" }, + { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA", + "AES256-SHA" }, + { 0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256", + "AES128-SHA256" }, + { 0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256", + "AES256-SHA256" }, + { 0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256", + "AES128-GCM-SHA256" }, + { 0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384", + "AES256-GCM-SHA384" }, + { 0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", + "ECDH-ECDSA-AES128-SHA" }, + { 0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", + "ECDH-ECDSA-AES256-SHA" }, + { 0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", + "ECDHE-ECDSA-AES128-SHA" }, + { 0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", + "ECDHE-ECDSA-AES256-SHA" }, + { 0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", + "ECDH-RSA-AES128-SHA" }, + { 0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", + "ECDH-RSA-AES256-SHA" }, + { 0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", + "ECDHE-RSA-AES128-SHA" }, + { 0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", + "ECDHE-RSA-AES256-SHA" }, + { 0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", + "ECDHE-ECDSA-AES128-SHA256" }, + { 0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", + "ECDHE-ECDSA-AES256-SHA384" }, + { 0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", + "ECDH-ECDSA-AES128-SHA256" }, + { 0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", + "ECDH-ECDSA-AES256-SHA384" }, + { 0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", + "ECDHE-RSA-AES128-SHA256" }, + { 0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", + "ECDHE-RSA-AES256-SHA384" }, + { 0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", + "ECDH-RSA-AES128-SHA256" }, + { 0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "ECDH-RSA-AES256-SHA384" }, + { 0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", + "ECDH-ECDSA-AES128-GCM-SHA256" }, + { 0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", + "ECDH-ECDSA-AES256-GCM-SHA384" }, + { 0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "ECDH-RSA-AES128-GCM-SHA256" }, + { 0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "ECDH-RSA-AES256-GCM-SHA384" }, +#endif +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) + { 0x0001, "TLS_RSA_WITH_NULL_MD5", + "NULL-MD5" }, + { 0x0002, "TLS_RSA_WITH_NULL_SHA", + "NULL-SHA" }, + { 0x002C, "TLS_PSK_WITH_NULL_SHA", + "PSK-NULL-SHA" }, + { 0x002D, "TLS_DHE_PSK_WITH_NULL_SHA", + "DHE-PSK-NULL-SHA" }, + { 0x002E, "TLS_RSA_PSK_WITH_NULL_SHA", + "RSA-PSK-NULL-SHA" }, + { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", + "DHE-RSA-AES128-SHA" }, + { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", + "DHE-RSA-AES256-SHA" }, + { 0x003B, "TLS_RSA_WITH_NULL_SHA256", + "NULL-SHA256" }, + { 0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", + "DHE-RSA-AES128-SHA256" }, + { 0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", + "DHE-RSA-AES256-SHA256" }, + { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA", + "PSK-AES128-CBC-SHA" }, + { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA", + "PSK-AES256-CBC-SHA" }, + { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA", + "DHE-PSK-AES128-CBC-SHA" }, + { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA", + "DHE-PSK-AES256-CBC-SHA" }, + { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA", + "RSA-PSK-AES128-CBC-SHA" }, + { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA", + "RSA-PSK-AES256-CBC-SHA" }, + { 0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", + "DHE-RSA-AES128-GCM-SHA256" }, + { 0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", + "DHE-RSA-AES256-GCM-SHA384" }, + { 0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256", + "PSK-AES128-GCM-SHA256" }, + { 0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384", + "PSK-AES256-GCM-SHA384" }, + { 0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256", + "DHE-PSK-AES128-GCM-SHA256" }, + { 0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384", + "DHE-PSK-AES256-GCM-SHA384" }, + { 0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256", + "RSA-PSK-AES128-GCM-SHA256" }, + { 0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384", + "RSA-PSK-AES256-GCM-SHA384" }, + { 0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256", + "PSK-AES128-CBC-SHA256" }, + { 0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384", + "PSK-AES256-CBC-SHA384" }, + { 0x00B0, "TLS_PSK_WITH_NULL_SHA256", + "PSK-NULL-SHA256" }, + { 0x00B1, "TLS_PSK_WITH_NULL_SHA384", + "PSK-NULL-SHA384" }, + { 0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256", + "DHE-PSK-AES128-CBC-SHA256" }, + { 0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384", + "DHE-PSK-AES256-CBC-SHA384" }, + { 0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256", + "DHE-PSK-NULL-SHA256" }, + { 0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384", + "DHE-PSK-NULL-SHA384" }, + { 0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256", + "RSA-PSK-AES128-CBC-SHA256" }, + { 0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384", + "RSA-PSK-AES256-CBC-SHA384" }, + { 0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256", + "RSA-PSK-NULL-SHA256" }, + { 0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384", + "RSA-PSK-NULL-SHA384" }, + { 0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA", + "ECDH-ECDSA-NULL-SHA" }, + { 0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA", + "ECDHE-ECDSA-NULL-SHA" }, + { 0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA", + "ECDH-RSA-NULL-SHA" }, + { 0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA", + "ECDHE-RSA-NULL-SHA" }, + { 0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", + "ECDHE-PSK-AES128-CBC-SHA" }, + { 0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", + "ECDHE-PSK-AES256-CBC-SHA" }, + { 0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256", + "PSK-CHACHA20-POLY1305" }, +#endif +#if defined(USE_SECTRANSP) || defined(USE_BEARSSL) + { 0x000A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", + "DES-CBC3-SHA" }, + { 0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", + "ECDH-ECDSA-DES-CBC3-SHA" }, + { 0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", + "ECDHE-ECDSA-DES-CBC3-SHA" }, + { 0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", + "ECDH-RSA-DES-CBC3-SHA" }, + { 0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", + "ECDHE-RSA-DES-CBC3-SHA" }, +#endif +#if defined(USE_MBEDTLS) || defined(USE_BEARSSL) + { 0xC09C, "TLS_RSA_WITH_AES_128_CCM", + "AES128-CCM" }, + { 0xC09D, "TLS_RSA_WITH_AES_256_CCM", + "AES256-CCM" }, + { 0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8", + "AES128-CCM8" }, + { 0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8", + "AES256-CCM8" }, + { 0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM", + "ECDHE-ECDSA-AES128-CCM" }, + { 0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM", + "ECDHE-ECDSA-AES256-CCM" }, + { 0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8", + "ECDHE-ECDSA-AES128-CCM8" }, + { 0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8", + "ECDHE-ECDSA-AES256-CCM8" }, +#endif +#if defined(USE_SECTRANSP) + { 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", + "EXP-RC4-MD5" }, + { 0x0004, "TLS_RSA_WITH_RC4_128_MD5", + "RC4-MD5" }, + { 0x0005, "TLS_RSA_WITH_RC4_128_SHA", + "RC4-SHA" }, + { 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", + "EXP-RC2-CBC-MD5" }, + { 0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA", + "IDEA-CBC-SHA" }, + { 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", + "EXP-DES-CBC-SHA" }, + { 0x0009, "TLS_RSA_WITH_DES_CBC_SHA", + "DES-CBC-SHA" }, + { 0x000B, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", + "EXP-DH-DSS-DES-CBC-SHA" }, + { 0x000C, "TLS_DH_DSS_WITH_DES_CBC_SHA", + "DH-DSS-DES-CBC-SHA" }, + { 0x000D, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", + "DH-DSS-DES-CBC3-SHA" }, + { 0x000E, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", + "EXP-DH-RSA-DES-CBC-SHA" }, + { 0x000F, "TLS_DH_RSA_WITH_DES_CBC_SHA", + "DH-RSA-DES-CBC-SHA" }, + { 0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", + "DH-RSA-DES-CBC3-SHA" }, + { 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", + "EXP-DHE-DSS-DES-CBC-SHA" }, + { 0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA", + "DHE-DSS-DES-CBC-SHA" }, + { 0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", + "DHE-DSS-DES-CBC3-SHA" }, + { 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", + "EXP-DHE-RSA-DES-CBC-SHA" }, + { 0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA", + "DHE-RSA-DES-CBC-SHA" }, + { 0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", + "DHE-RSA-DES-CBC3-SHA" }, + { 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", + "EXP-ADH-RC4-MD5" }, + { 0x0018, "TLS_DH_anon_WITH_RC4_128_MD5", + "ADH-RC4-MD5" }, + { 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", + "EXP-ADH-DES-CBC-SHA" }, + { 0x001A, "TLS_DH_anon_WITH_DES_CBC_SHA", + "ADH-DES-CBC-SHA" }, + { 0x001B, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", + "ADH-DES-CBC3-SHA" }, + { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA", + "DH-DSS-AES128-SHA" }, + { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA", + "DH-RSA-AES128-SHA" }, + { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", + "DHE-DSS-AES128-SHA" }, + { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA", + "ADH-AES128-SHA" }, + { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA", + "DH-DSS-AES256-SHA" }, + { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA", + "DH-RSA-AES256-SHA" }, + { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", + "DHE-DSS-AES256-SHA" }, + { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA", + "ADH-AES256-SHA" }, + { 0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256", + "DH-DSS-AES128-SHA256" }, + { 0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256", + "DH-RSA-AES128-SHA256" }, + { 0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", + "DHE-DSS-AES128-SHA256" }, + { 0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256", + "DH-DSS-AES256-SHA256" }, + { 0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256", + "DH-RSA-AES256-SHA256" }, + { 0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", + "DHE-DSS-AES256-SHA256" }, + { 0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256", + "ADH-AES128-SHA256" }, + { 0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256", + "ADH-AES256-SHA256" }, + { 0x008A, "TLS_PSK_WITH_RC4_128_SHA", + "PSK-RC4-SHA" }, + { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA", + "PSK-3DES-EDE-CBC-SHA" }, + { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA", + "DHE-PSK-RC4-SHA" }, + { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA", + "DHE-PSK-3DES-EDE-CBC-SHA" }, + { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA", + "RSA-PSK-RC4-SHA" }, + { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA", + "RSA-PSK-3DES-EDE-CBC-SHA" }, + { 0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256", + "DH-RSA-AES128-GCM-SHA256" }, + { 0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384", + "DH-RSA-AES256-GCM-SHA384" }, + { 0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", + "DHE-DSS-AES128-GCM-SHA256" }, + { 0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", + "DHE-DSS-AES256-GCM-SHA384" }, + { 0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256", + "DH-DSS-AES128-GCM-SHA256" }, + { 0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384", + "DH-DSS-AES256-GCM-SHA384" }, + { 0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256", + "ADH-AES128-GCM-SHA256" }, + { 0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384", + "ADH-AES256-GCM-SHA384" }, + { 0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", + "ECDH-ECDSA-RC4-SHA" }, + { 0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", + "ECDHE-ECDSA-RC4-SHA" }, + { 0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA", + "ECDH-RSA-RC4-SHA" }, + { 0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA", + "ECDHE-RSA-RC4-SHA" }, + { 0xC015, "TLS_ECDH_anon_WITH_NULL_SHA", + "AECDH-NULL-SHA" }, + { 0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA", + "AECDH-RC4-SHA" }, + { 0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", + "AECDH-DES-CBC3-SHA" }, + { 0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", + "AECDH-AES128-SHA" }, + { 0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", + "AECDH-AES256-SHA" }, + /* Backward compatible aliases (EDH vs DHE) */ + { 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", + "EXP-EDH-DSS-DES-CBC-SHA" }, + { 0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA", + "EDH-DSS-DES-CBC-SHA" }, + { 0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", + "EDH-DSS-DES-CBC3-SHA" }, + { 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", + "EXP-EDH-RSA-DES-CBC-SHA" }, + { 0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA", + "EDH-RSA-DES-CBC-SHA" }, + { 0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", + "EDH-RSA-DES-CBC3-SHA" }, +#endif +#if defined(USE_MBEDTLS) + /* entries marked ns are non-"standard", they are not in OpenSSL */ + { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA", + "CAMELLIA128-SHA" }, + { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA", + "DHE-RSA-CAMELLIA128-SHA" }, + { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA", + "CAMELLIA256-SHA" }, + { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA", + "DHE-RSA-CAMELLIA256-SHA" }, + { 0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "CAMELLIA128-SHA256" }, + { 0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "DHE-RSA-CAMELLIA128-SHA256" }, + { 0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256", + "CAMELLIA256-SHA256" }, + { 0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256", + "DHE-RSA-CAMELLIA256-SHA256" }, + { 0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", + "ECDHE-PSK-AES128-CBC-SHA256" }, + { 0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", + "ECDHE-PSK-AES256-CBC-SHA384" }, + { 0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA", + "ECDHE-PSK-NULL-SHA" }, + { 0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256", + "ECDHE-PSK-NULL-SHA256" }, + { 0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384", + "ECDHE-PSK-NULL-SHA384" }, + { 0xC03C, "TLS_RSA_WITH_ARIA_128_CBC_SHA256", + "ARIA128-SHA256" /* ns */ }, + { 0xC03D, "TLS_RSA_WITH_ARIA_256_CBC_SHA384", + "ARIA256-SHA384" /* ns */ }, + { 0xC044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256", + "DHE-RSA-ARIA128-SHA256" /* ns */ }, + { 0xC045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384", + "DHE-RSA-ARIA256-SHA384" /* ns */ }, + { 0xC048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256", + "ECDHE-ECDSA-ARIA128-SHA256" /* ns */ }, + { 0xC049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384", + "ECDHE-ECDSA-ARIA256-SHA384" /* ns */ }, + { 0xC04A, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256", + "ECDH-ECDSA-ARIA128-SHA256" /* ns */ }, + { 0xC04B, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384", + "ECDH-ECDSA-ARIA256-SHA384" /* ns */ }, + { 0xC04C, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256", + "ECDHE-ARIA128-SHA256" /* ns */ }, + { 0xC04D, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384", + "ECDHE-ARIA256-SHA384" /* ns */ }, + { 0xC04E, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256", + "ECDH-ARIA128-SHA256" /* ns */ }, + { 0xC04F, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384", + "ECDH-ARIA256-SHA384" /* ns */ }, + { 0xC050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256", + "ARIA128-GCM-SHA256" }, + { 0xC051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384", + "ARIA256-GCM-SHA384" }, + { 0xC052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256", + "DHE-RSA-ARIA128-GCM-SHA256" }, + { 0xC053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384", + "DHE-RSA-ARIA256-GCM-SHA384" }, + { 0xC05C, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256", + "ECDHE-ECDSA-ARIA128-GCM-SHA256" }, + { 0xC05D, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384", + "ECDHE-ECDSA-ARIA256-GCM-SHA384" }, + { 0xC05E, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256", + "ECDH-ECDSA-ARIA128-GCM-SHA256" /* ns */ }, + { 0xC05F, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384", + "ECDH-ECDSA-ARIA256-GCM-SHA384" /* ns */ }, + { 0xC060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256", + "ECDHE-ARIA128-GCM-SHA256" }, + { 0xC061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384", + "ECDHE-ARIA256-GCM-SHA384" }, + { 0xC062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256", + "ECDH-ARIA128-GCM-SHA256" /* ns */ }, + { 0xC063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384", + "ECDH-ARIA256-GCM-SHA384" /* ns */ }, + { 0xC064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256", + "PSK-ARIA128-SHA256" /* ns */ }, + { 0xC065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384", + "PSK-ARIA256-SHA384" /* ns */ }, + { 0xC066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256", + "DHE-PSK-ARIA128-SHA256" /* ns */ }, + { 0xC067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384", + "DHE-PSK-ARIA256-SHA384" /* ns */ }, + { 0xC068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256", + "RSA-PSK-ARIA128-SHA256" /* ns */ }, + { 0xC069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384", + "RSA-PSK-ARIA256-SHA384" /* ns */ }, + { 0xC06A, "TLS_PSK_WITH_ARIA_128_GCM_SHA256", + "PSK-ARIA128-GCM-SHA256" }, + { 0xC06B, "TLS_PSK_WITH_ARIA_256_GCM_SHA384", + "PSK-ARIA256-GCM-SHA384" }, + { 0xC06C, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256", + "DHE-PSK-ARIA128-GCM-SHA256" }, + { 0xC06D, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384", + "DHE-PSK-ARIA256-GCM-SHA384" }, + { 0xC06E, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256", + "RSA-PSK-ARIA128-GCM-SHA256" }, + { 0xC06F, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384", + "RSA-PSK-ARIA256-GCM-SHA384" }, + { 0xC070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256", + "ECDHE-PSK-ARIA128-SHA256" /* ns */ }, + { 0xC071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384", + "ECDHE-PSK-ARIA256-SHA384" /* ns */ }, + { 0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", + "ECDHE-ECDSA-CAMELLIA128-SHA256" }, + { 0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", + "ECDHE-ECDSA-CAMELLIA256-SHA384" }, + { 0xC074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256", + "ECDH-ECDSA-CAMELLIA128-SHA256" /* ns */ }, + { 0xC075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", + "ECDH-ECDSA-CAMELLIA256-SHA384" /* ns */ }, + { 0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "ECDHE-RSA-CAMELLIA128-SHA256" }, + { 0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384", + "ECDHE-RSA-CAMELLIA256-SHA384" }, + { 0xC078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256", + "ECDH-CAMELLIA128-SHA256" /* ns */ }, + { 0xC079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384", + "ECDH-CAMELLIA256-SHA384" /* ns */ }, + { 0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "DHE-RSA-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "DHE-RSA-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256", + "ECDHE-ECDSA-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384", + "ECDHE-ECDSA-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256", + "ECDH-ECDSA-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384", + "ECDH-ECDSA-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "ECDHE-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "ECDHE-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC08C, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256", + "ECDH-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC08D, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384", + "ECDH-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC08E, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256", + "PSK-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC08F, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384", + "PSK-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256", + "DHE-PSK-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384", + "DHE-PSK-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256", + "RSA-PSK-CAMELLIA128-GCM-SHA256" /* ns */ }, + { 0xC093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384", + "RSA-PSK-CAMELLIA256-GCM-SHA384" /* ns */ }, + { 0xC094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "PSK-CAMELLIA128-SHA256" }, + { 0xC095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "PSK-CAMELLIA256-SHA384" }, + { 0xC096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "DHE-PSK-CAMELLIA128-SHA256" }, + { 0xC097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "DHE-PSK-CAMELLIA256-SHA384" }, + { 0xC098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "RSA-PSK-CAMELLIA128-SHA256" }, + { 0xC099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "RSA-PSK-CAMELLIA256-SHA384" }, + { 0xC09A, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256", + "ECDHE-PSK-CAMELLIA128-SHA256" }, + { 0xC09B, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", + "ECDHE-PSK-CAMELLIA256-SHA384" }, + { 0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM", + "DHE-RSA-AES128-CCM" }, + { 0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM", + "DHE-RSA-AES256-CCM" }, + { 0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8", + "DHE-RSA-AES128-CCM8" }, + { 0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8", + "DHE-RSA-AES256-CCM8" }, + { 0xC0A4, "TLS_PSK_WITH_AES_128_CCM", + "PSK-AES128-CCM" }, + { 0xC0A5, "TLS_PSK_WITH_AES_256_CCM", + "PSK-AES256-CCM" }, + { 0xC0A6, "TLS_DHE_PSK_WITH_AES_128_CCM", + "DHE-PSK-AES128-CCM" }, + { 0xC0A7, "TLS_DHE_PSK_WITH_AES_256_CCM", + "DHE-PSK-AES256-CCM" }, + { 0xC0A8, "TLS_PSK_WITH_AES_128_CCM_8", + "PSK-AES128-CCM8" }, + { 0xC0A9, "TLS_PSK_WITH_AES_256_CCM_8", + "PSK-AES256-CCM8" }, + { 0xC0AA, "TLS_PSK_DHE_WITH_AES_128_CCM_8", + "DHE-PSK-AES128-CCM8" }, + { 0xC0AB, "TLS_PSK_DHE_WITH_AES_256_CCM_8", + "DHE-PSK-AES256-CCM8" }, + { 0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", + "DHE-RSA-CHACHA20-POLY1305" }, + { 0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", + "ECDHE-PSK-CHACHA20-POLY1305" }, + { 0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256", + "DHE-PSK-CHACHA20-POLY1305" }, + { 0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256", + "RSA-PSK-CHACHA20-POLY1305" }, +#endif +}; +#define TEST_CS_LIST_LEN (sizeof(test_cs_list) / sizeof(test_cs_list[0])) + +static const char *cs_test_string = + "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:" + "TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:" + "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:" + "ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:" + "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:" + "ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:" + "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:" + "DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:" + "AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:" + "DES-CBC3-SHA:" + ":: GIBBERISH ::" +; + +struct test_str_entry { + uint16_t id; + const char *str; +}; +static const struct test_str_entry test_str_list[] = { +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_RUSTLS) + { 0x1301, "TLS_AES_128_GCM_SHA256"}, + { 0x1302, "TLS_AES_256_GCM_SHA384"}, + { 0x1303, "TLS_CHACHA20_POLY1305_SHA256"}, +#else + { 0x0000, "TLS_AES_128_GCM_SHA256"}, + { 0x0000, "TLS_AES_256_GCM_SHA384"}, + { 0x0000, "TLS_CHACHA20_POLY1305_SHA256"}, +#endif + { 0xC02B, "ECDHE-ECDSA-AES128-GCM-SHA256"}, + { 0xC02F, "ECDHE-RSA-AES128-GCM-SHA256"}, + { 0xC02C, "ECDHE-ECDSA-AES256-GCM-SHA384"}, + { 0xC030, "ECDHE-RSA-AES256-GCM-SHA384"}, + { 0xCCA9, "ECDHE-ECDSA-CHACHA20-POLY1305"}, + { 0xCCA8, "ECDHE-RSA-CHACHA20-POLY1305"}, +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) + { 0x009E, "DHE-RSA-AES128-GCM-SHA256"}, + { 0x009F, "DHE-RSA-AES256-GCM-SHA384"}, +#else + { 0x0000, "DHE-RSA-AES128-GCM-SHA256"}, + { 0x0000, "DHE-RSA-AES256-GCM-SHA384"}, +#endif +#if defined(USE_MBEDTLS) + { 0xCCAA, "DHE-RSA-CHACHA20-POLY1305"}, +#else + { 0x0000, "DHE-RSA-CHACHA20-POLY1305"}, +#endif +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_BEARSSL) + { 0xC023, "ECDHE-ECDSA-AES128-SHA256" }, + { 0xC027, "ECDHE-RSA-AES128-SHA256" }, + { 0xC009, "ECDHE-ECDSA-AES128-SHA" }, + { 0xC013, "ECDHE-RSA-AES128-SHA" }, + { 0xC024, "ECDHE-ECDSA-AES256-SHA384" }, + { 0xC028, "ECDHE-RSA-AES256-SHA384" }, + { 0xC00A, "ECDHE-ECDSA-AES256-SHA" }, + { 0xC014, "ECDHE-RSA-AES256-SHA" }, +#else + { 0x0000, "ECDHE-ECDSA-AES128-SHA256" }, + { 0x0000, "ECDHE-RSA-AES128-SHA256" }, + { 0x0000, "ECDHE-ECDSA-AES128-SHA" }, + { 0x0000, "ECDHE-RSA-AES128-SHA" }, + { 0x0000, "ECDHE-ECDSA-AES256-SHA384" }, + { 0x0000, "ECDHE-RSA-AES256-SHA384" }, + { 0x0000, "ECDHE-ECDSA-AES256-SHA" }, + { 0x0000, "ECDHE-RSA-AES256-SHA" }, +#endif +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) + { 0x0067, "DHE-RSA-AES128-SHA256" }, + { 0x006B, "DHE-RSA-AES256-SHA256" }, +#else + { 0x0000, "DHE-RSA-AES128-SHA256" }, + { 0x0000, "DHE-RSA-AES256-SHA256" }, +#endif +#if defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || defined(USE_BEARSSL) + { 0x009C, "AES128-GCM-SHA256" }, + { 0x009D, "AES256-GCM-SHA384" }, + { 0x003C, "AES128-SHA256" }, + { 0x003D, "AES256-SHA256" }, + { 0x002F, "AES128-SHA" }, + { 0x0035, "AES256-SHA" }, +#else + { 0x0000, "AES128-GCM-SHA256" }, + { 0x0000, "AES256-GCM-SHA384" }, + { 0x0000, "AES128-SHA256" }, + { 0x0000, "AES256-SHA256" }, + { 0x0000, "AES128-SHA" }, + { 0x0000, "AES256-SHA" }, +#endif +#if defined(USE_SECTRANSP) || defined(USE_BEARSSL) + { 0x000A, "DES-CBC3-SHA" }, +#else + { 0x0000, "DES-CBC3-SHA" }, +#endif + { 0x0000, "GIBBERISH" }, + { 0x0000, "" }, +}; +#define TEST_STR_LIST_LEN (sizeof(test_str_list) / sizeof(test_str_list[0])) + +UNITTEST_START +{ + for(size_t i = 0; i < TEST_CS_LIST_LEN; i++) { + const struct test_cs_entry *test = &test_cs_list[i]; + const char *expect; + char buf[64] = ""; + char alt[64] = ""; + uint16_t id; + + /* test Curl_cipher_suite_lookup_id() for rfc name */ + if(test->rfc) { + id = Curl_cipher_suite_lookup_id(test->rfc, strlen(test->rfc)); + if(id != test->id) { + fprintf(stderr, "Curl_cipher_suite_lookup_id FAILED for \"%s\", " + "result = 0x%04x, expected = 0x%04x\n", + test->rfc, id, test->id); + unitfail++; + } + } + + /* test Curl_cipher_suite_lookup_id() for OpenSSL name */ + if(test->openssl) { + id = Curl_cipher_suite_lookup_id(test->openssl, strlen(test->openssl)); + if(id != test->id) { + fprintf(stderr, "Curl_cipher_suite_lookup_id FAILED for \"%s\", " + "result = 0x%04x, expected = 0x%04x\n", + test->openssl, id, test->id); + unitfail++; + } + } + + /* test Curl_cipher_suite_get_str() prefer rfc name */ + buf[0] = '\0'; + expect = test->rfc ? test->rfc : test->openssl; + + Curl_cipher_suite_get_str(test->id, buf, sizeof(buf), true); + + if(strcmp(buf, expect) != 0) { + fprintf(stderr, "Curl_cipher_suite_get_str FAILED for 0x%04x, " + "result = \"%s\", expected = \"%s\"\n", + test->id, buf, expect); + unitfail++; + } + + /* test Curl_cipher_suite_get_str() prefer OpenSSL name */ + buf[0] = '\0'; + expect = test->openssl ? test->openssl : test->rfc; + + Curl_cipher_suite_get_str(test->id, buf, sizeof(buf), false); + + /* suites matched by EDH alias will return the DHE name */ + if(test->id >= 0x0011 && test->id < 0x0017) { + if(memcmp(expect, "EDH-", 4) == 0) + expect = (char *) memcpy(strcpy(alt, expect), "DHE-", 4); + if(memcmp(expect + 4, "EDH-", 4) == 0) + expect = (char *) memcpy(strcpy(alt, expect) + 4, "DHE-", 4) - 4; + } + + if(strcmp(buf, expect) != 0) { + fprintf(stderr, "Curl_cipher_suite_get_str FAILED for 0x%04x, " + "result = \"%s\", expected = \"%s\"\n", + test->id, buf, expect); + unitfail++; + } + } + + /* test Curl_cipher_suite_walk_str() */ + { + const char *ptr, *end = cs_test_string; + int i = 0; + uint16_t id; + size_t len; + + for(ptr = cs_test_string; ptr[0] != '\0'; ptr = end) { + const struct test_str_entry *test = &test_str_list[i]; + abort_if(i == TEST_STR_LIST_LEN, "should have been done"); + + id = Curl_cipher_suite_walk_str(&ptr, &end); + len = end - ptr; + + if(id != test->id) { + fprintf(stderr, "Curl_cipher_suite_walk_str FAILED for \"%s\" " + "unexpected cipher, " + "result = 0x%04x, expected = 0x%04x\n", + test->str, id, test->id); + unitfail++; + } + if(len > 64 || strncmp(ptr, test->str, len) != 0) { + fprintf(stderr, "Curl_cipher_suite_walk_str ABORT for \"%s\" " + "unexpected pointers\n", + test->str); + unitfail++; + goto unit_test_abort; + } + i++; + } + } +} +UNITTEST_STOP + +#else /* defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) */ + +UNITTEST_START +UNITTEST_STOP + +#endif /* defined(USE_SECTRANSP) || defined(USE_MBEDTLS) || \ + defined(USE_BEARSSL) || defined(USE_RUSTLS) */