diff --git a/local-test-curl-full-01/afc-curl/include/Makefile.am b/local-test-curl-full-01/afc-curl/include/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..d65bfeaa0fbd647165663234ea1bc96e47c4cb82 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/include/Makefile.am @@ -0,0 +1,28 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +SUBDIRS = curl + +EXTRA_DIST = README.md + +AUTOMAKE_OPTIONS = foreign no-dependencies diff --git a/local-test-curl-full-01/afc-curl/include/README.md b/local-test-curl-full-01/afc-curl/include/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b155d8c13b931f11ad0e4dfb9e2e11f9465122ac --- /dev/null +++ b/local-test-curl-full-01/afc-curl/include/README.md @@ -0,0 +1,20 @@ + + +# include + +Public include files for libcurl, external users. + +They are all placed in the curl subdirectory here for better fit in any kind of +environment. You must include files from here using... + + #include + +... style and point the compiler's include path to the directory holding the +curl subdirectory. It makes it more likely to survive future modifications. + +The public curl include files can be shared freely between different platforms +and different architectures. diff --git a/local-test-curl-full-01/afc-curl/lib/.gitignore b/local-test-curl-full-01/afc-curl/lib/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..813b99411e9eef7cd7d03169303d59a08c95bd19 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/.gitignore @@ -0,0 +1,15 @@ +# Copyright (C) Daniel Stenberg, , et al. +# +# SPDX-License-Identifier: curl + +*.a +*.imp +*.nlm +*.orig +*.rej +*.res +TAGS +curl_config.h +curl_config.h.in +libcurl.vers +stamp-h1 diff --git a/local-test-curl-full-01/afc-curl/lib/Makefile.am b/local-test-curl-full-01/afc-curl/lib/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..3a40280b94cf731fa60c56bfefbd9318c0281ab6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/Makefile.am @@ -0,0 +1,171 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +AUTOMAKE_OPTIONS = foreign nostdinc + +CMAKE_DIST = CMakeLists.txt curl_config.h.cmake + +CHECKSRC_DIST = .checksrc vauth/.checksrc vquic/.checksrc vssh/.checksrc \ + vtls/.checksrc + +EXTRA_DIST = Makefile.mk config-win32.h config-win32ce.h config-plan9.h \ + config-riscos.h config-mac.h curl_config.h.in config-dos.h libcurl.rc \ + config-amigaos.h config-win32ce.h config-os400.h setup-os400.h \ + $(CMAKE_DIST) setup-win32.h Makefile.soname optiontable.pl libcurl.def \ + $(CHECKSRC_DIST) + +lib_LTLIBRARIES = libcurl.la + +if BUILD_UNITTESTS +noinst_LTLIBRARIES = libcurlu.la +else +noinst_LTLIBRARIES = +endif + +# This might hold -Werror +CFLAGS += @CURL_CFLAG_EXTRAS@ + +# Specify our include paths here, and do it relative to $(top_srcdir) and +# $(top_builddir), to ensure that these paths which belong to the library +# being currently built and tested are searched before the library which +# might possibly already be installed in the system. +# +# $(top_srcdir)/include is for libcurl's external include files +# $(top_builddir)/lib is for libcurl's generated lib/curl_config.h file +# $(top_srcdir)/lib for libcurl's lib/curl_setup.h and other "private" files + +AM_CPPFLAGS = -I$(top_srcdir)/include \ + -I$(top_builddir)/lib \ + -I$(top_srcdir)/lib + +# Prevent LIBS from being used for all link targets +LIBS = $(BLANK_AT_MAKETIME) + +include Makefile.soname + +AM_CPPFLAGS += -DBUILDING_LIBCURL +AM_LDFLAGS = +AM_CFLAGS = + +# Makefile.inc provides the CSOURCES and HHEADERS defines +include Makefile.inc + +if USE_UNITY +# Keep these separate to avoid duplicate definitions when linking libtests +# in static mode. +curl_EXCLUDE = curl_threads.c timediff.c warnless.c +if DEBUGBUILD +# We must compile these sources separately to avoid memdebug.h redefinitions +# applying to them. +curl_EXCLUDE += memdebug.c curl_multibyte.c +endif +libcurl_unity.c: $(top_srcdir)/scripts/mk-unity.pl $(CSOURCES) + @PERL@ $(top_srcdir)/scripts/mk-unity.pl $(srcdir) $(CSOURCES) --exclude $(curl_EXCLUDE) > libcurl_unity.c + +nodist_libcurl_la_SOURCES = libcurl_unity.c +libcurl_la_SOURCES = $(curl_EXCLUDE) +nodist_libcurlu_la_SOURCES = libcurl_unity.c +libcurlu_la_SOURCES = $(curl_EXCLUDE) +CLEANFILES = libcurl_unity.c +else +libcurl_la_SOURCES = $(CSOURCES) $(HHEADERS) +libcurlu_la_SOURCES = $(CSOURCES) $(HHEADERS) +endif + +libcurl_la_CPPFLAGS_EXTRA = +libcurl_la_LDFLAGS_EXTRA = +libcurl_la_CFLAGS_EXTRA = + +if CURL_LT_SHLIB_USE_VERSION_INFO +libcurl_la_LDFLAGS_EXTRA += $(VERSIONINFO) +endif + +if CURL_LT_SHLIB_USE_NO_UNDEFINED +libcurl_la_LDFLAGS_EXTRA += -no-undefined +endif + +if CURL_LT_SHLIB_USE_MIMPURE_TEXT +libcurl_la_LDFLAGS_EXTRA += -mimpure-text +endif + +if CURL_LT_SHLIB_USE_VERSIONED_SYMBOLS +libcurl_la_LDFLAGS_EXTRA += -Wl,--version-script=libcurl.vers +else +# if symbol-hiding is enabled, hide them! +if DOING_CURL_SYMBOL_HIDING +libcurl_la_LDFLAGS_EXTRA += -export-symbols-regex '^curl_.*' +endif +endif + +if USE_CPPFLAG_CURL_STATICLIB +libcurl_la_CPPFLAGS_EXTRA += -DCURL_STATICLIB +else +if HAVE_WINDRES +libcurl_la_SOURCES += $(LIB_RCFILES) +$(LIB_RCFILES): $(top_srcdir)/include/curl/curlver.h +endif +endif + +if DOING_CURL_SYMBOL_HIDING +libcurl_la_CPPFLAGS_EXTRA += -DCURL_HIDDEN_SYMBOLS +libcurl_la_CFLAGS_EXTRA += $(CFLAG_CURL_SYMBOL_HIDING) +endif + +libcurl_la_CPPFLAGS = $(AM_CPPFLAGS) $(libcurl_la_CPPFLAGS_EXTRA) +libcurl_la_LDFLAGS = $(AM_LDFLAGS) $(libcurl_la_LDFLAGS_EXTRA) $(CURL_LDFLAGS_LIB) $(LIBCURL_PC_LIBS_PRIVATE) +libcurl_la_CFLAGS = $(AM_CFLAGS) $(libcurl_la_CFLAGS_EXTRA) + +libcurlu_la_CPPFLAGS = $(AM_CPPFLAGS) -DCURL_STATICLIB -DUNITTESTS +libcurlu_la_LDFLAGS = $(AM_LDFLAGS) -static $(LIBCURL_PC_LIBS_PRIVATE) +libcurlu_la_CFLAGS = $(AM_CFLAGS) + +CHECKSRC = $(CS_$(V)) +CS_0 = @echo " RUN " $@; +CS_1 = +CS_ = $(CS_0) + +checksrc: + $(CHECKSRC)(@PERL@ $(top_srcdir)/scripts/checksrc.pl -D$(srcdir) \ + -W$(srcdir)/curl_config.h $(srcdir)/*.[ch] $(srcdir)/vauth/*.[ch] \ + $(srcdir)/vtls/*.[ch] $(srcdir)/vquic/*.[ch] $(srcdir)/vssh/*.[ch]) + +if DEBUGBUILD +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif + +# disable the tests that are mostly causing false positives +TIDYFLAGS=-checks=-clang-analyzer-security.insecureAPI.strcpy,-clang-analyzer-optin.performance.Padding,-clang-analyzer-valist.Uninitialized,-clang-analyzer-core.NonNullParamChecker,-clang-analyzer-core.NullDereference -quiet + +TIDY:=clang-tidy + +tidy: + $(TIDY) $(CSOURCES) $(TIDYFLAGS) -- $(AM_CPPFLAGS) $(CPPFLAGS) -DHAVE_CONFIG_H + +optiontable: + perl optiontable.pl < $(top_srcdir)/include/curl/curl.h > easyoptions.c + +if HAVE_WINDRES +.rc.lo: + $(LIBTOOL) --tag=RC --mode=compile $(RC) -I$(top_srcdir)/include $(RCFLAGS) -i $< -o $@ +endif diff --git a/local-test-curl-full-01/afc-curl/lib/Makefile.mk b/local-test-curl-full-01/afc-curl/lib/Makefile.mk new file mode 100644 index 0000000000000000000000000000000000000000..e130b758e57a0d2519ff1075ff3d89e045f95da6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/Makefile.mk @@ -0,0 +1,340 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +# Makefile to build curl parts with GCC-like toolchains and optional features. +# +# Usage: make -f Makefile.mk CFG=-feat1[-feat2][-feat3][...] +# Example: make -f Makefile.mk CFG=-zlib-ssl-libssh2-ipv6 +# +# Look for ' ?=' to find accepted customization variables. + +# This script is reused by 'src' and 'docs/examples' Makefile.mk scripts. + +ifndef PROOT + PROOT := .. + LOCAL := 1 +endif + +### Common + +CFLAGS ?= +CPPFLAGS ?= +LDFLAGS ?= +LIBS ?= + +CROSSPREFIX ?= + +ifeq ($(CC),cc) + CC := gcc +endif +CC := $(CROSSPREFIX)$(CC) +AR := $(CROSSPREFIX)$(AR) + +TRIPLET ?= $(shell $(CC) -dumpmachine) + +BIN_EXT := + +ifneq ($(findstring msdos,$(TRIPLET)),) + # Cross-tools: https://github.com/andrewwutw/build-djgpp + MSDOS := 1 + BIN_EXT := .exe +else ifneq ($(findstring amigaos,$(TRIPLET)),) + # Cross-tools: https://github.com/bebbo/amiga-gcc + AMIGA := 1 +endif + +CPPFLAGS += -I. -I$(PROOT)/include + +### Deprecated settings. For compatibility. + +ifdef WATT_ROOT + WATT_PATH := $(realpath $(WATT_ROOT)) +endif + +### Optional features + +ifneq ($(findstring -debug,$(CFG)),) + CFLAGS += -g + CPPFLAGS += -DDEBUGBUILD +else + CPPFLAGS += -DNDEBUG +endif +ifneq ($(findstring -trackmem,$(CFG)),) + CPPFLAGS += -DCURLDEBUG +endif +ifneq ($(findstring -map,$(CFG)),) + MAP := 1 +endif + +# CPPFLAGS below are only necessary when building libcurl via 'lib' (see +# comments below about exceptions). Always include them anyway to match +# behavior of other build systems. + +ifneq ($(findstring -sync,$(CFG)),) + CPPFLAGS += -DUSE_SYNC_DNS +else ifneq ($(findstring -ares,$(CFG)),) + LIBCARES_PATH ?= $(PROOT)/../c-ares + CPPFLAGS += -DUSE_ARES + CPPFLAGS += -isystem "$(LIBCARES_PATH)/include" + LDFLAGS += -L"$(LIBCARES_PATH)/lib" + LIBS += -lcares +endif + +ifneq ($(findstring -rtmp,$(CFG)),) + LIBRTMP_PATH ?= $(PROOT)/../librtmp + CPPFLAGS += -DUSE_LIBRTMP + CPPFLAGS += -isystem "$(LIBRTMP_PATH)" + LDFLAGS += -L"$(LIBRTMP_PATH)/librtmp" + LIBS += -lrtmp + ZLIB := 1 +endif + +ifneq ($(findstring -ssh2,$(CFG)),) + LIBSSH2_PATH ?= $(PROOT)/../libssh2 + CPPFLAGS += -DUSE_LIBSSH2 + CPPFLAGS += -isystem "$(LIBSSH2_PATH)/include" + LDFLAGS += -L"$(LIBSSH2_PATH)/lib" + LIBS += -lssh2 +else ifneq ($(findstring -libssh,$(CFG)),) + LIBSSH_PATH ?= $(PROOT)/../libssh + CPPFLAGS += -DUSE_LIBSSH + CPPFLAGS += -isystem "$(LIBSSH_PATH)/include" + LDFLAGS += -L"$(LIBSSH_PATH)/lib" + LIBS += -lssh +else ifneq ($(findstring -wolfssh,$(CFG)),) + WOLFSSH_PATH ?= $(PROOT)/../wolfssh + CPPFLAGS += -DUSE_WOLFSSH + CPPFLAGS += -isystem "$(WOLFSSH_PATH)/include" + LDFLAGS += -L"$(WOLFSSH_PATH)/lib" + LIBS += -lwolfssh +endif + +ifneq ($(findstring -ssl,$(CFG)),) + OPENSSL_PATH ?= $(PROOT)/../openssl + CPPFLAGS += -DUSE_OPENSSL + CPPFLAGS += -DCURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG + OPENSSL_INCLUDE ?= $(OPENSSL_PATH)/include + OPENSSL_LIBPATH ?= $(OPENSSL_PATH)/lib + CPPFLAGS += -isystem "$(OPENSSL_INCLUDE)" + LDFLAGS += -L"$(OPENSSL_LIBPATH)" + OPENSSL_LIBS ?= -lssl -lcrypto + LIBS += $(OPENSSL_LIBS) + + ifneq ($(findstring -srp,$(CFG)),) + ifneq ($(wildcard $(OPENSSL_INCLUDE)/openssl/srp.h),) + # OpenSSL 1.0.1 and later. + CPPFLAGS += -DHAVE_OPENSSL_SRP -DUSE_TLS_SRP + endif + endif + SSLLIBS += 1 +endif +ifneq ($(findstring -wolfssl,$(CFG)),) + WOLFSSL_PATH ?= $(PROOT)/../wolfssl + CPPFLAGS += -DUSE_WOLFSSL + CPPFLAGS += -DSIZEOF_LONG_LONG=8 + CPPFLAGS += -isystem "$(WOLFSSL_PATH)/include" + LDFLAGS += -L"$(WOLFSSL_PATH)/lib" + LIBS += -lwolfssl + SSLLIBS += 1 +endif +ifneq ($(findstring -mbedtls,$(CFG)),) + MBEDTLS_PATH ?= $(PROOT)/../mbedtls + CPPFLAGS += -DUSE_MBEDTLS + CPPFLAGS += -isystem "$(MBEDTLS_PATH)/include" + LDFLAGS += -L"$(MBEDTLS_PATH)/lib" + LIBS += -lmbedtls -lmbedx509 -lmbedcrypto + SSLLIBS += 1 +endif +ifneq ($(findstring -bearssl,$(CFG)),) + BEARSSL_PATH ?= $(PROOT)/../bearssl + CPPFLAGS += -DUSE_BEARSSL + CPPFLAGS += -isystem "$(BEARSSL_PATH)/inc" + LDFLAGS += -L"$(BEARSSL_PATH)/build" + LIBS += -lbearssl + SSLLIBS += 1 +endif + +ifneq ($(findstring -nghttp2,$(CFG)),) + NGHTTP2_PATH ?= $(PROOT)/../nghttp2 + CPPFLAGS += -DUSE_NGHTTP2 + CPPFLAGS += -isystem "$(NGHTTP2_PATH)/include" + LDFLAGS += -L"$(NGHTTP2_PATH)/lib" + LIBS += -lnghttp2 +endif + +ifeq ($(findstring -nghttp3,$(CFG))$(findstring -ngtcp2,$(CFG)),-nghttp3-ngtcp2) + NGHTTP3_PATH ?= $(PROOT)/../nghttp3 + CPPFLAGS += -DUSE_NGHTTP3 + CPPFLAGS += -isystem "$(NGHTTP3_PATH)/include" + LDFLAGS += -L"$(NGHTTP3_PATH)/lib" + LIBS += -lnghttp3 + + NGTCP2_PATH ?= $(PROOT)/../ngtcp2 + CPPFLAGS += -DUSE_NGTCP2 + CPPFLAGS += -isystem "$(NGTCP2_PATH)/include" + LDFLAGS += -L"$(NGTCP2_PATH)/lib" + + NGTCP2_LIBS ?= + ifeq ($(NGTCP2_LIBS),) + ifneq ($(findstring -ssl,$(CFG)),) + ifneq ($(wildcard $(OPENSSL_INCLUDE)/openssl/aead.h),) + NGTCP2_LIBS := -lngtcp2_crypto_boringssl + else # including libressl + NGTCP2_LIBS := -lngtcp2_crypto_quictls + endif + else ifneq ($(findstring -wolfssl,$(CFG)),) + NGTCP2_LIBS := -lngtcp2_crypto_wolfssl + endif + endif + + LIBS += -lngtcp2 $(NGTCP2_LIBS) +endif + +ifneq ($(findstring -zlib,$(CFG))$(ZLIB),) + ZLIB_PATH ?= $(PROOT)/../zlib + # These CPPFLAGS are also required when compiling the curl tool via 'src'. + CPPFLAGS += -DHAVE_LIBZ + CPPFLAGS += -isystem "$(ZLIB_PATH)/include" + LDFLAGS += -L"$(ZLIB_PATH)/lib" + ZLIB_LIBS ?= -lz + LIBS += $(ZLIB_LIBS) + ZLIB := 1 +endif +ifneq ($(findstring -zstd,$(CFG)),) + ZSTD_PATH ?= $(PROOT)/../zstd + CPPFLAGS += -DHAVE_ZSTD + CPPFLAGS += -isystem "$(ZSTD_PATH)/include" + LDFLAGS += -L"$(ZSTD_PATH)/lib" + ZSTD_LIBS ?= -lzstd + LIBS += $(ZSTD_LIBS) +endif +ifneq ($(findstring -brotli,$(CFG)),) + BROTLI_PATH ?= $(PROOT)/../brotli + CPPFLAGS += -DHAVE_BROTLI + CPPFLAGS += -isystem "$(BROTLI_PATH)/include" + LDFLAGS += -L"$(BROTLI_PATH)/lib" + BROTLI_LIBS ?= -lbrotlidec -lbrotlicommon + LIBS += $(BROTLI_LIBS) +endif +ifneq ($(findstring -gsasl,$(CFG)),) + LIBGSASL_PATH ?= $(PROOT)/../gsasl + CPPFLAGS += -DUSE_GSASL + CPPFLAGS += -isystem "$(LIBGSASL_PATH)/include" + LDFLAGS += -L"$(LIBGSASL_PATH)/lib" + LIBS += -lgsasl +endif + +ifneq ($(findstring -idn2,$(CFG)),) + LIBIDN2_PATH ?= $(PROOT)/../libidn2 + CPPFLAGS += -DHAVE_LIBIDN2 -DHAVE_IDN2_H + CPPFLAGS += -isystem "$(LIBIDN2_PATH)/include" + LDFLAGS += -L"$(LIBIDN2_PATH)/lib" + LIBS += -lidn2 + +ifneq ($(findstring -psl,$(CFG)),) + LIBPSL_PATH ?= $(PROOT)/../libpsl + CPPFLAGS += -DUSE_LIBPSL + CPPFLAGS += -isystem "$(LIBPSL_PATH)/include" + LDFLAGS += -L"$(LIBPSL_PATH)/lib" + LIBS += -lpsl +endif +endif + +ifneq ($(findstring -ipv6,$(CFG)),) + CPPFLAGS += -DUSE_IPV6 +endif + +ifneq ($(findstring -watt,$(CFG))$(MSDOS),) + WATT_PATH ?= $(PROOT)/../watt + CPPFLAGS += -isystem "$(WATT_PATH)/inc" + LDFLAGS += -L"$(WATT_PATH)/lib" + LIBS += -lwatt +endif + +ifneq ($(findstring 11,$(subst $(subst ,, ),,$(SSLLIBS))),) + CPPFLAGS += -DCURL_WITH_MULTI_SSL +endif + +### Common rules + +OBJ_DIR := $(TRIPLET) + +ifneq ($(findstring /sh,$(SHELL)),) +DEL = rm -f $1 +COPY = -cp -afv $1 $2 +MKDIR = mkdir -p $1 +RMDIR = rm -fr $1 +else +DEL = -del 2>NUL /q /f $(subst /,\,$1) +COPY = -copy 2>NUL /y $(subst /,\,$1) $(subst /,\,$2) +MKDIR = -md 2>NUL $(subst /,\,$1) +RMDIR = -rd 2>NUL /q /s $(subst /,\,$1) +endif + +all: $(TARGETS) + +$(OBJ_DIR): + -$(call MKDIR, $(OBJ_DIR)) + +$(OBJ_DIR)/%.o: %.c + $(CC) -W -Wall $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +clean: + @$(call DEL, $(TOCLEAN)) + @$(RMDIR) $(OBJ_DIR) + +distclean vclean: clean + @$(call DEL, $(TARGETS) $(TOVCLEAN)) + +### Local + +ifdef LOCAL + +CPPFLAGS += -DBUILDING_LIBCURL + +### Sources and targets + +# Provides CSOURCES, HHEADERS +include Makefile.inc + +vpath %.c vauth vquic vssh vtls + +libcurl_a_LIBRARY := libcurl.a + +TARGETS := $(libcurl_a_LIBRARY) + +libcurl_a_OBJECTS := $(patsubst %.c,$(OBJ_DIR)/%.o,$(notdir $(strip $(CSOURCES)))) +libcurl_a_DEPENDENCIES := $(strip $(CSOURCES) $(HHEADERS)) + +TOCLEAN := +TOVCLEAN := + +### Rules + +$(libcurl_a_LIBRARY): $(libcurl_a_OBJECTS) $(libcurl_a_DEPENDENCIES) + @$(call DEL, $@) + $(AR) rcs $@ $(libcurl_a_OBJECTS) + +all: $(OBJ_DIR) $(TARGETS) +endif diff --git a/local-test-curl-full-01/afc-curl/lib/altsvc.h b/local-test-curl-full-01/afc-curl/lib/altsvc.h new file mode 100644 index 0000000000000000000000000000000000000000..48999efb3177638c6617edf341f390783a0f87d6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/altsvc.h @@ -0,0 +1,81 @@ +#ifndef HEADER_CURL_ALTSVC_H +#define HEADER_CURL_ALTSVC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC) +#include +#include "llist.h" + +enum alpnid { + ALPN_none = 0, + ALPN_h1 = CURLALTSVC_H1, + ALPN_h2 = CURLALTSVC_H2, + ALPN_h3 = CURLALTSVC_H3 +}; + +struct althost { + char *host; + unsigned short port; + enum alpnid alpnid; +}; + +struct altsvc { + struct althost src; + struct althost dst; + time_t expires; + bool persist; + unsigned int prio; + struct Curl_llist_node node; +}; + +struct altsvcinfo { + char *filename; + struct Curl_llist list; /* list of entries */ + long flags; /* the publicly set bitmask */ +}; + +const char *Curl_alpnid2str(enum alpnid id); +struct altsvcinfo *Curl_altsvc_init(void); +CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_save(struct Curl_easy *data, + struct altsvcinfo *asi, const char *file); +CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl); +void Curl_altsvc_cleanup(struct altsvcinfo **altsvc); +CURLcode Curl_altsvc_parse(struct Curl_easy *data, + struct altsvcinfo *altsvc, const char *value, + enum alpnid srcalpn, const char *srchost, + unsigned short srcport); +bool Curl_altsvc_lookup(struct altsvcinfo *asi, + enum alpnid srcalpnid, const char *srchost, + int srcport, + struct altsvc **dstentry, + const int versions); /* CURLALTSVC_H* bits */ +#else +/* disabled */ +#define Curl_altsvc_save(a,b,c) +#define Curl_altsvc_cleanup(x) +#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */ +#endif /* HEADER_CURL_ALTSVC_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/asyn.h b/local-test-curl-full-01/afc-curl/lib/asyn.h new file mode 100644 index 0000000000000000000000000000000000000000..0ff2048845551e24caad9a6894c20e31d4fb5a2c --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/asyn.h @@ -0,0 +1,184 @@ +#ifndef HEADER_CURL_ASYN_H +#define HEADER_CURL_ASYN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "curl_addrinfo.h" + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; +struct Curl_dns_entry; + +/* + * This header defines all functions in the internal asynch resolver interface. + * All asynch resolvers need to provide these functions. + * asyn-ares.c and asyn-thread.c are the current implementations of asynch + * resolver backends. + */ + +/* + * Curl_resolver_global_init() + * + * Called from curl_global_init() to initialize global resolver environment. + * Returning anything else than CURLE_OK fails curl_global_init(). + */ +int Curl_resolver_global_init(void); + +/* + * Curl_resolver_global_cleanup() + * Called from curl_global_cleanup() to destroy global resolver environment. + */ +void Curl_resolver_global_cleanup(void); + +/* + * Curl_resolver_init() + * Called from curl_easy_init() -> Curl_open() to initialize resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Should fill the passed pointer by the initialized handler. + * Returning anything else than CURLE_OK fails curl_easy_init() with the + * correspondent code. + */ +CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver); + +/* + * Curl_resolver_cleanup() + * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver + * URL-state specific environment ('resolver' member of the UrlState + * structure). Should destroy the handler and free all resources connected to + * it. + */ +void Curl_resolver_cleanup(void *resolver); + +/* + * Curl_resolver_duphandle() + * Called from curl_easy_duphandle() to duplicate resolver URL-state specific + * environment ('resolver' member of the UrlState structure). Should + * duplicate the 'from' handle and pass the resulting handle to the 'to' + * pointer. Returning anything else than CURLE_OK causes failed + * curl_easy_duphandle() call. + */ +CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, + void *from); + +/* + * Curl_resolver_cancel(). + * + * It is called from inside other functions to cancel currently performing + * resolver request. Should also free any temporary resources allocated to + * perform a request. This never waits for resolver threads to complete. + * + * It is safe to call this when conn is in any state. + */ +void Curl_resolver_cancel(struct Curl_easy *data); + +/* + * Curl_resolver_kill(). + * + * This acts like Curl_resolver_cancel() except it will block until any threads + * associated with the resolver are complete. This never blocks for resolvers + * that do not use threads. This is intended to be the "last chance" function + * that cleans up an in-progress resolver completely (before its owner is about + * to die). + * + * It is safe to call this when conn is in any state. + */ +void Curl_resolver_kill(struct Curl_easy *data); + +/* Curl_resolver_getsock() + * + * This function is called from the multi_getsock() function. 'sock' is a + * pointer to an array to hold the file descriptors, with 'numsock' being the + * size of that array (in number of entries). This function is supposed to + * return bitmask indicating what file descriptors (referring to array indexes + * in the 'sock' array) to wait for, read/write. + */ +int Curl_resolver_getsock(struct Curl_easy *data, curl_socket_t *sock); + +/* + * Curl_resolver_is_resolved() + * + * Called repeatedly to check if a previous name resolve request has + * completed. It should also make sure to time-out if the operation seems to + * take too long. + * + * Returns normal CURLcode errors. + */ +CURLcode Curl_resolver_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dns); + +/* + * Curl_resolver_wait_resolv() + * + * Waits for a resolve to finish. This function should be avoided since using + * this risk getting the multi interface to "hang". + * + * If 'entry' is non-NULL, make it point to the resolved dns entry + * + * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, + * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. + */ +CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data, + struct Curl_dns_entry **dnsentry); + +/* + * Curl_resolver_getaddrinfo() - when using this resolver + * + * Returns name information about the given hostname and port number. If + * successful, the 'hostent' is returned and the fourth argument will point to + * memory we need to free after use. That memory *MUST* be freed with + * Curl_freeaddrinfo(), nothing else. + * + * Each resolver backend must of course make sure to return data in the + * correct format to comply with this. + */ +struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + +#ifndef CURLRES_ASYNCH +/* convert these functions if an asynch resolver is not used */ +#define Curl_resolver_cancel(x) Curl_nop_stmt +#define Curl_resolver_kill(x) Curl_nop_stmt +#define Curl_resolver_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST +#define Curl_resolver_wait_resolv(x,y) CURLE_COULDNT_RESOLVE_HOST +#define Curl_resolver_duphandle(x,y,z) CURLE_OK +#define Curl_resolver_init(x,y) CURLE_OK +#define Curl_resolver_global_init() CURLE_OK +#define Curl_resolver_global_cleanup() Curl_nop_stmt +#define Curl_resolver_cleanup(x) Curl_nop_stmt +#endif + +#ifdef CURLRES_ASYNCH +#define Curl_resolver_asynch() 1 +#else +#define Curl_resolver_asynch() 0 +#endif + + +/********** end of generic resolver interface functions *****************/ +#endif /* HEADER_CURL_ASYN_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cf-h1-proxy.h b/local-test-curl-full-01/afc-curl/lib/cf-h1-proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..ac5bed0b2bc7ad4bce92730148afcdd0b362b584 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cf-h1-proxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_H1_PROXY_H +#define HEADER_CURL_H1_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) + +CURLcode Curl_cf_h1_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_h1_proxy; + + +#endif /* !CURL_DISABLE_PROXY && !CURL_DISABLE_HTTP */ + +#endif /* HEADER_CURL_H1_PROXY_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cf-h2-proxy.h b/local-test-curl-full-01/afc-curl/lib/cf-h2-proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..c01bf62133b6a7c7191d590af508a7abf09d12af --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cf-h2-proxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_H2_PROXY_H +#define HEADER_CURL_H2_PROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) + +CURLcode Curl_cf_h2_proxy_insert_after(struct Curl_cfilter *cf, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_h2_proxy; + + +#endif /* defined(USE_NGHTTP2) && !defined(CURL_DISABLE_PROXY) */ + +#endif /* HEADER_CURL_H2_PROXY_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cf-haproxy.c b/local-test-curl-full-01/afc-curl/lib/cf-haproxy.c new file mode 100644 index 0000000000000000000000000000000000000000..ae2402f224117452f8906dcfa8e17d7728d8b2dd --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cf-haproxy.c @@ -0,0 +1,253 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_PROXY) + +#include +#include "urldata.h" +#include "cfilters.h" +#include "cf-haproxy.h" +#include "curl_trc.h" +#include "multiif.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +typedef enum { + HAPROXY_INIT, /* init/default/no tunnel state */ + HAPROXY_SEND, /* data_out being sent */ + HAPROXY_DONE /* all work done */ +} haproxy_state; + +struct cf_haproxy_ctx { + int state; + struct dynbuf data_out; +}; + +static void cf_haproxy_ctx_reset(struct cf_haproxy_ctx *ctx) +{ + DEBUGASSERT(ctx); + ctx->state = HAPROXY_INIT; + Curl_dyn_reset(&ctx->data_out); +} + +static void cf_haproxy_ctx_free(struct cf_haproxy_ctx *ctx) +{ + if(ctx) { + Curl_dyn_free(&ctx->data_out); + free(ctx); + } +} + +static CURLcode cf_haproxy_date_out_set(struct Curl_cfilter*cf, + struct Curl_easy *data) +{ + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + const char *client_ip; + struct ip_quadruple ipquad; + int is_ipv6; + + DEBUGASSERT(ctx); + DEBUGASSERT(ctx->state == HAPROXY_INIT); +#ifdef USE_UNIX_SOCKETS + if(cf->conn->unix_domain_socket) + /* the buffer is large enough to hold this! */ + result = Curl_dyn_addn(&ctx->data_out, STRCONST("PROXY UNKNOWN\r\n")); + else { +#endif /* USE_UNIX_SOCKETS */ + result = Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad); + if(result) + return result; + + /* Emit the correct prefix for IPv6 */ + if(data->set.str[STRING_HAPROXY_CLIENT_IP]) + client_ip = data->set.str[STRING_HAPROXY_CLIENT_IP]; + else + client_ip = ipquad.local_ip; + + result = Curl_dyn_addf(&ctx->data_out, "PROXY %s %s %s %i %i\r\n", + is_ipv6 ? "TCP6" : "TCP4", + client_ip, ipquad.remote_ip, + ipquad.local_port, ipquad.remote_port); + +#ifdef USE_UNIX_SOCKETS + } +#endif /* USE_UNIX_SOCKETS */ + return result; +} + +static CURLcode cf_haproxy_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done) +{ + struct cf_haproxy_ctx *ctx = cf->ctx; + CURLcode result; + size_t len; + + DEBUGASSERT(ctx); + if(cf->connected) { + *done = TRUE; + return CURLE_OK; + } + + result = cf->next->cft->do_connect(cf->next, data, blocking, done); + if(result || !*done) + return result; + + switch(ctx->state) { + case HAPROXY_INIT: + result = cf_haproxy_date_out_set(cf, data); + if(result) + goto out; + ctx->state = HAPROXY_SEND; + FALLTHROUGH(); + case HAPROXY_SEND: + len = Curl_dyn_len(&ctx->data_out); + if(len > 0) { + ssize_t nwritten; + nwritten = Curl_conn_cf_send(cf->next, data, + Curl_dyn_ptr(&ctx->data_out), len, FALSE, + &result); + if(nwritten < 0) { + if(result != CURLE_AGAIN) + goto out; + result = CURLE_OK; + nwritten = 0; + } + Curl_dyn_tail(&ctx->data_out, len - (size_t)nwritten); + if(Curl_dyn_len(&ctx->data_out) > 0) { + result = CURLE_OK; + goto out; + } + } + ctx->state = HAPROXY_DONE; + FALLTHROUGH(); + default: + Curl_dyn_free(&ctx->data_out); + break; + } + +out: + *done = (!result) && (ctx->state == HAPROXY_DONE); + cf->connected = *done; + return result; +} + +static void cf_haproxy_destroy(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + (void)data; + CURL_TRC_CF(data, cf, "destroy"); + cf_haproxy_ctx_free(cf->ctx); +} + +static void cf_haproxy_close(struct Curl_cfilter *cf, + struct Curl_easy *data) +{ + CURL_TRC_CF(data, cf, "close"); + cf->connected = FALSE; + cf_haproxy_ctx_reset(cf->ctx); + if(cf->next) + cf->next->cft->do_close(cf->next, data); +} + +static void cf_haproxy_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps) +{ + if(cf->next->connected && !cf->connected) { + /* If we are not connected, but the filter "below" is + * and not waiting on something, we are sending. */ + Curl_pollset_set_out_only(data, ps, Curl_conn_cf_get_socket(cf, data)); + } +} + +struct Curl_cftype Curl_cft_haproxy = { + "HAPROXY", + CF_TYPE_PROXY, + 0, + cf_haproxy_destroy, + cf_haproxy_connect, + cf_haproxy_close, + Curl_cf_def_shutdown, + Curl_cf_def_get_host, + cf_haproxy_adjust_pollset, + Curl_cf_def_data_pending, + Curl_cf_def_send, + Curl_cf_def_recv, + Curl_cf_def_cntrl, + Curl_cf_def_conn_is_alive, + Curl_cf_def_conn_keep_alive, + Curl_cf_def_query, +}; + +static CURLcode cf_haproxy_create(struct Curl_cfilter **pcf, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf = NULL; + struct cf_haproxy_ctx *ctx; + CURLcode result; + + (void)data; + ctx = calloc(1, sizeof(*ctx)); + if(!ctx) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + ctx->state = HAPROXY_INIT; + Curl_dyn_init(&ctx->data_out, DYN_HAXPROXY); + + result = Curl_cf_create(&cf, &Curl_cft_haproxy, ctx); + if(result) + goto out; + ctx = NULL; + +out: + cf_haproxy_ctx_free(ctx); + *pcf = result ? NULL : cf; + return result; +} + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data) +{ + struct Curl_cfilter *cf; + CURLcode result; + + result = cf_haproxy_create(&cf, data); + if(result) + goto out; + Curl_conn_cf_insert_after(cf_at, cf); + +out: + return result; +} + +#endif /* !CURL_DISABLE_PROXY */ diff --git a/local-test-curl-full-01/afc-curl/lib/cf-haproxy.h b/local-test-curl-full-01/afc-curl/lib/cf-haproxy.h new file mode 100644 index 0000000000000000000000000000000000000000..d02c323e7b7082604a8e87997babaa6f8c97db4b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cf-haproxy.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_CF_HAPROXY_H +#define HEADER_CURL_CF_HAPROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "urldata.h" + +#if !defined(CURL_DISABLE_PROXY) + +CURLcode Curl_cf_haproxy_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data); + +extern struct Curl_cftype Curl_cft_haproxy; + +#endif /* !CURL_DISABLE_PROXY */ + +#endif /* HEADER_CURL_CF_HAPROXY_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cf-https-connect.h b/local-test-curl-full-01/afc-curl/lib/cf-https-connect.h new file mode 100644 index 0000000000000000000000000000000000000000..6a39527317c1a29f0297955030e13ff920329b41 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cf-https-connect.h @@ -0,0 +1,58 @@ +#ifndef HEADER_CURL_CF_HTTP_H +#define HEADER_CURL_CF_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) + +struct Curl_cfilter; +struct Curl_easy; +struct connectdata; +struct Curl_cftype; +struct Curl_dns_entry; + +extern struct Curl_cftype Curl_cft_http_connect; + +CURLcode Curl_cf_http_connect_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21); + +CURLcode +Curl_cf_http_connect_insert_after(struct Curl_cfilter *cf_at, + struct Curl_easy *data, + const struct Curl_dns_entry *remotehost, + bool try_h3, bool try_h21); + + +CURLcode Curl_cf_https_setup(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + const struct Curl_dns_entry *remotehost); + + +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(USE_HYPER) */ +#endif /* HEADER_CURL_CF_HTTP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cfilters.h b/local-test-curl-full-01/afc-curl/lib/cfilters.h new file mode 100644 index 0000000000000000000000000000000000000000..af696f52a579b6e2050167f380bdaaddfef68382 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cfilters.h @@ -0,0 +1,696 @@ +#ifndef HEADER_CURL_CFILTERS_H +#define HEADER_CURL_CFILTERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "timediff.h" + +struct Curl_cfilter; +struct Curl_easy; +struct Curl_dns_entry; +struct connectdata; +struct ip_quadruple; + +/* Callback to destroy resources held by this filter instance. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef void Curl_cft_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Callback to close the connection immediately. */ +typedef void Curl_cft_close(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Callback to close the connection filter gracefully, non-blocking. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef CURLcode Curl_cft_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *done); + +typedef CURLcode Curl_cft_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done); + +/* Return the hostname and port the connection goes to. + * This may change with the connection state of filters when tunneling + * is involved. + * @param cf the filter to ask + * @param data the easy handle currently active + * @param phost on return, points to the relevant, real hostname. + * this is owned by the connection. + * @param pdisplay_host on return, points to the printable hostname. + * this is owned by the connection. + * @param pport on return, contains the port number + */ +typedef void Curl_cft_get_host(struct Curl_cfilter *cf, + struct Curl_easy *data, + const char **phost, + const char **pdisplay_host, + int *pport); + +struct easy_pollset; + +/* Passing in an easy_pollset for monitoring of sockets, let + * filters add or remove sockets actions (CURL_POLL_OUT, CURL_POLL_IN). + * This may add a socket or, in case no actions remain, remove + * a socket from the set. + * + * Filter implementations need to call filters "below" *after* they have + * made their adjustments. This allows lower filters to override "upper" + * actions. If a "lower" filter is unable to write, it needs to be able + * to disallow POLL_OUT. + * + * A filter without own restrictions/preferences should not modify + * the pollset. Filters, whose filter "below" is not connected, should + * also do no adjustments. + * + * Examples: a TLS handshake, while ongoing, might remove POLL_IN when it + * needs to write, or vice versa. An HTTP/2 filter might remove POLL_OUT when + * a stream window is exhausted and a WINDOW_UPDATE needs to be received first + * and add instead POLL_IN. + * + * @param cf the filter to ask + * @param data the easy handle the pollset is about + * @param ps the pollset (inout) for the easy handle + */ +typedef void Curl_cft_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +typedef bool Curl_cft_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); + +typedef ssize_t Curl_cft_send(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + const void *buf, /* data to write */ + size_t len, /* amount to write */ + bool eos, /* last chunk */ + CURLcode *err); /* error to return */ + +typedef ssize_t Curl_cft_recv(struct Curl_cfilter *cf, + struct Curl_easy *data, /* transfer */ + char *buf, /* store data here */ + size_t len, /* amount to read */ + CURLcode *err); /* error to return */ + +typedef bool Curl_cft_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); + +typedef CURLcode Curl_cft_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/** + * Events/controls for connection filters, their arguments and + * return code handling. Filter callbacks are invoked "top down". + * Return code handling: + * "first fail" meaning that the first filter returning != CURLE_OK, will + * abort further event distribution and determine the result. + * "ignored" meaning return values are ignored and the event is distributed + * to all filters in the chain. Overall result is always CURLE_OK. + */ +/* data event arg1 arg2 return */ +#define CF_CTRL_DATA_ATTACH 1 /* 0 NULL ignored */ +#define CF_CTRL_DATA_DETACH 2 /* 0 NULL ignored */ +#define CF_CTRL_DATA_SETUP 4 /* 0 NULL first fail */ +#define CF_CTRL_DATA_IDLE 5 /* 0 NULL first fail */ +#define CF_CTRL_DATA_PAUSE 6 /* on/off NULL first fail */ +#define CF_CTRL_DATA_DONE 7 /* premature NULL ignored */ +#define CF_CTRL_DATA_DONE_SEND 8 /* 0 NULL ignored */ +/* update conn info at connection and data */ +#define CF_CTRL_CONN_INFO_UPDATE (256+0) /* 0 NULL ignored */ +#define CF_CTRL_FORGET_SOCKET (256+1) /* 0 NULL ignored */ +#define CF_CTRL_FLUSH (256+2) /* 0 NULL first fail */ + +/** + * Handle event/control for the filter. + * Implementations MUST NOT chain calls to cf->next. + */ +typedef CURLcode Curl_cft_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); + + +/** + * Queries to ask via a `Curl_cft_query *query` method on a cfilter chain. + * - MAX_CONCURRENT: the maximum number of parallel transfers the filter + * chain expects to handle at the same time. + * default: 1 if no filter overrides. + * - CONNECT_REPLY_MS: milliseconds until the first indication of a server + * response was received on a connect. For TCP, this + * reflects the time until the socket connected. On UDP + * this gives the time the first bytes from the server + * were received. + * -1 if not determined yet. + * - CF_QUERY_SOCKET: the socket used by the filter chain + * - CF_QUERY_NEED_FLUSH: TRUE iff any of the filters have unsent data + * - CF_QUERY_IP_INFO: res1 says if connection used IPv6, res2 is the + * ip quadruple + */ +/* query res1 res2 */ +#define CF_QUERY_MAX_CONCURRENT 1 /* number - */ +#define CF_QUERY_CONNECT_REPLY_MS 2 /* number - */ +#define CF_QUERY_SOCKET 3 /* - curl_socket_t */ +#define CF_QUERY_TIMER_CONNECT 4 /* - struct curltime */ +#define CF_QUERY_TIMER_APPCONNECT 5 /* - struct curltime */ +#define CF_QUERY_STREAM_ERROR 6 /* error code - */ +#define CF_QUERY_NEED_FLUSH 7 /* TRUE/FALSE - */ +#define CF_QUERY_IP_INFO 8 /* TRUE/FALSE struct ip_quadruple */ + +/** + * Query the cfilter for properties. Filters ignorant of a query will + * pass it "down" the filter chain. + */ +typedef CURLcode Curl_cft_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); + +/** + * Type flags for connection filters. A filter can have none, one or + * many of those. Use to evaluate state/capabilities of a filter chain. + * + * CF_TYPE_IP_CONNECT: provides an IP connection or sth equivalent, like + * a CONNECT tunnel, a UNIX domain socket, a QUIC + * connection, etc. + * CF_TYPE_SSL: provide SSL/TLS + * CF_TYPE_MULTIPLEX: provides multiplexing of easy handles + * CF_TYPE_PROXY provides proxying + */ +#define CF_TYPE_IP_CONNECT (1 << 0) +#define CF_TYPE_SSL (1 << 1) +#define CF_TYPE_MULTIPLEX (1 << 2) +#define CF_TYPE_PROXY (1 << 3) + +/* A connection filter type, e.g. specific implementation. */ +struct Curl_cftype { + const char *name; /* name of the filter type */ + int flags; /* flags of filter type */ + int log_level; /* log level for such filters */ + Curl_cft_destroy_this *destroy; /* destroy resources of this cf */ + Curl_cft_connect *do_connect; /* establish connection */ + Curl_cft_close *do_close; /* close conn */ + Curl_cft_shutdown *do_shutdown; /* shutdown conn */ + Curl_cft_get_host *get_host; /* host filter talks to */ + Curl_cft_adjust_pollset *adjust_pollset; /* adjust transfer poll set */ + Curl_cft_data_pending *has_data_pending;/* conn has data pending */ + Curl_cft_send *do_send; /* send data */ + Curl_cft_recv *do_recv; /* receive data */ + Curl_cft_cntrl *cntrl; /* events/control */ + Curl_cft_conn_is_alive *is_alive; /* FALSE if conn is dead, Jim! */ + Curl_cft_conn_keep_alive *keep_alive; /* try to keep it alive */ + Curl_cft_query *query; /* query filter chain */ +}; + +/* A connection filter instance, e.g. registered at a connection */ +struct Curl_cfilter { + const struct Curl_cftype *cft; /* the type providing implementation */ + struct Curl_cfilter *next; /* next filter in chain */ + void *ctx; /* filter type specific settings */ + struct connectdata *conn; /* the connection this filter belongs to */ + int sockindex; /* the index the filter is installed at */ + BIT(connected); /* != 0 iff this filter is connected */ + BIT(shutdown); /* != 0 iff this filter has shut down */ +}; + +/* Default implementations for the type functions, implementing nop. */ +void Curl_cf_def_destroy_this(struct Curl_cfilter *cf, + struct Curl_easy *data); + +/* Default implementations for the type functions, implementing pass-through + * the filter chain. */ +void Curl_cf_def_get_host(struct Curl_cfilter *cf, struct Curl_easy *data, + const char **phost, const char **pdisplay_host, + int *pport); +void Curl_cf_def_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); +bool Curl_cf_def_data_pending(struct Curl_cfilter *cf, + const struct Curl_easy *data); +ssize_t Curl_cf_def_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, bool eos, + CURLcode *err); +ssize_t Curl_cf_def_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err); +CURLcode Curl_cf_def_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + int event, int arg1, void *arg2); +bool Curl_cf_def_conn_is_alive(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool *input_pending); +CURLcode Curl_cf_def_conn_keep_alive(struct Curl_cfilter *cf, + struct Curl_easy *data); +CURLcode Curl_cf_def_query(struct Curl_cfilter *cf, + struct Curl_easy *data, + int query, int *pres1, void *pres2); +CURLcode Curl_cf_def_shutdown(struct Curl_cfilter *cf, + struct Curl_easy *data, bool *done); + +/** + * Create a new filter instance, unattached to the filter chain. + * Use Curl_conn_cf_add() to add it to the chain. + * @param pcf on success holds the created instance + * @param cft the filter type + * @param ctx the type specific context to use + */ +CURLcode Curl_cf_create(struct Curl_cfilter **pcf, + const struct Curl_cftype *cft, + void *ctx); + +/** + * Add a filter instance to the `sockindex` filter chain at connection + * `conn`. The filter must not already be attached. It is inserted at + * the start of the chain (top). + */ +void Curl_conn_cf_add(struct Curl_easy *data, + struct connectdata *conn, + int sockindex, + struct Curl_cfilter *cf); + +/** + * Insert a filter (chain) after `cf_at`. + * `cf_new` must not already be attached. + */ +void Curl_conn_cf_insert_after(struct Curl_cfilter *cf_at, + struct Curl_cfilter *cf_new); + +/** + * Discard, e.g. remove and destroy `discard` iff + * it still is in the filter chain below `cf`. If `discard` + * is no longer found beneath `cf` return FALSE. + * if `destroy_always` is TRUE, will call `discard`s destroy + * function and free it even if not found in the subchain. + */ +bool Curl_conn_cf_discard_sub(struct Curl_cfilter *cf, + struct Curl_cfilter *discard, + struct Curl_easy *data, + bool destroy_always); + +/** + * Discard all cfilters starting with `*pcf` and clearing it afterwards. + */ +void Curl_conn_cf_discard_chain(struct Curl_cfilter **pcf, + struct Curl_easy *data); + +/** + * Remove and destroy all filters at chain `sockindex` on connection `conn`. + */ +void Curl_conn_cf_discard_all(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + + +CURLcode Curl_conn_cf_connect(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool blocking, bool *done); +void Curl_conn_cf_close(struct Curl_cfilter *cf, struct Curl_easy *data); +ssize_t Curl_conn_cf_send(struct Curl_cfilter *cf, struct Curl_easy *data, + const void *buf, size_t len, bool eos, + CURLcode *err); +ssize_t Curl_conn_cf_recv(struct Curl_cfilter *cf, struct Curl_easy *data, + char *buf, size_t len, CURLcode *err); +CURLcode Curl_conn_cf_cntrl(struct Curl_cfilter *cf, + struct Curl_easy *data, + bool ignore_result, + int event, int arg1, void *arg2); + +/** + * Determine if the connection filter chain is using SSL to the remote host + * (or will be once connected). + */ +bool Curl_conn_cf_is_ssl(struct Curl_cfilter *cf); + +/** + * Get the socket used by the filter chain starting at `cf`. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_cf_get_socket(struct Curl_cfilter *cf, + struct Curl_easy *data); + +CURLcode Curl_conn_cf_get_ip_info(struct Curl_cfilter *cf, + struct Curl_easy *data, + int *is_ipv6, struct ip_quadruple *ipquad); + +bool Curl_conn_cf_needs_flush(struct Curl_cfilter *cf, + struct Curl_easy *data); + +#define CURL_CF_SSL_DEFAULT -1 +#define CURL_CF_SSL_DISABLE 0 +#define CURL_CF_SSL_ENABLE 1 + +/** + * Bring the filter chain at `sockindex` for connection `data->conn` into + * connected state. Which will set `*done` to TRUE. + * This can be called on an already connected chain with no side effects. + * When not `blocking`, calls may return without error and `*done != TRUE`, + * while the individual filters negotiated the connection. + */ +CURLcode Curl_conn_connect(struct Curl_easy *data, int sockindex, + bool blocking, bool *done); + +/** + * Check if the filter chain at `sockindex` for connection `conn` is + * completely connected. + */ +bool Curl_conn_is_connected(struct connectdata *conn, int sockindex); + +/** + * Determine if we have reached the remote host on IP level, e.g. + * have a TCP connection. This turns TRUE before a possible SSL + * handshake has been started/done. + */ +bool Curl_conn_is_ip_connected(struct Curl_easy *data, int sockindex); + +/** + * Determine if the connection is using SSL to the remote host + * (or will be once connected). This will return FALSE, if SSL + * is only used in proxying and not for the tunnel itself. + */ +bool Curl_conn_is_ssl(struct connectdata *conn, int sockindex); + +/** + * Connection provides multiplexing of easy handles at `socketindex`. + */ +bool Curl_conn_is_multiplex(struct connectdata *conn, int sockindex); + +/** + * Close the filter chain at `sockindex` for connection `data->conn`. + * Filters remain in place and may be connected again afterwards. + */ +void Curl_conn_close(struct Curl_easy *data, int sockindex); + +/** + * Shutdown the connection at `sockindex` non-blocking, using timeout + * from `data->set.shutdowntimeout`, default DEFAULT_SHUTDOWN_TIMEOUT_MS. + * Will return CURLE_OK and *done == FALSE if not finished. + */ +CURLcode Curl_conn_shutdown(struct Curl_easy *data, int sockindex, bool *done); + +/** + * Return if data is pending in some connection filter at chain + * `sockindex` for connection `data->conn`. + */ +bool Curl_conn_data_pending(struct Curl_easy *data, + int sockindex); + +/** + * Return TRUE if any of the connection filters at chain `sockindex` + * have data still to send. + */ +bool Curl_conn_needs_flush(struct Curl_easy *data, int sockindex); + +/** + * Flush any pending data on the connection filters at chain `sockindex`. + */ +CURLcode Curl_conn_flush(struct Curl_easy *data, int sockindex); + +/** + * Return the socket used on data's connection for the index. + * Returns CURL_SOCKET_BAD if not available. + */ +curl_socket_t Curl_conn_get_socket(struct Curl_easy *data, int sockindex); + +/** + * Tell filters to forget about the socket at sockindex. + */ +void Curl_conn_forget_socket(struct Curl_easy *data, int sockindex); + +/** + * Adjust the pollset for the filter chain startgin at `cf`. + */ +void Curl_conn_cf_adjust_pollset(struct Curl_cfilter *cf, + struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Adjust pollset from filters installed at transfer's connection. + */ +void Curl_conn_adjust_pollset(struct Curl_easy *data, + struct easy_pollset *ps); + +/** + * Curl_poll() the filter chain at `cf` with timeout `timeout_ms`. + * Returns 0 on timeout, negative on error or number of sockets + * with requested poll events. + */ +int Curl_conn_cf_poll(struct Curl_cfilter *cf, + struct Curl_easy *data, + timediff_t timeout_ms); + +/** + * Receive data through the filter chain at `sockindex` for connection + * `data->conn`. Copy at most `len` bytes into `buf`. Return the + * actual number of bytes copied or a negative value on error. + * The error code is placed into `*code`. + */ +ssize_t Curl_cf_recv(struct Curl_easy *data, int sockindex, char *buf, + size_t len, CURLcode *code); + +/** + * Send `len` bytes of data from `buf` through the filter chain `sockindex` + * at connection `data->conn`. Return the actual number of bytes written + * or a negative value on error. + * The error code is placed into `*code`. + */ +ssize_t Curl_cf_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t len, bool eos, CURLcode *code); + +/** + * The easy handle `data` is being attached to `conn`. This does + * not mean that data will actually do a transfer. Attachment is + * also used for temporary actions on the connection. + */ +void Curl_conn_ev_data_attach(struct connectdata *conn, + struct Curl_easy *data); + +/** + * The easy handle `data` is being detached (no longer served) + * by connection `conn`. All filters are informed to release any resources + * related to `data`. + * Note: there may be several `data` attached to a connection at the same + * time. + */ +void Curl_conn_ev_data_detach(struct connectdata *conn, + struct Curl_easy *data); + +/** + * Notify connection filters that they need to setup data for + * a transfer. + */ +CURLcode Curl_conn_ev_data_setup(struct Curl_easy *data); + +/** + * Notify connection filters that now would be a good time to + * perform any idle, e.g. time related, actions. + */ +CURLcode Curl_conn_ev_data_idle(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is done with sending data (e.g. has uploaded everything). + */ +void Curl_conn_ev_data_done_send(struct Curl_easy *data); + +/** + * Notify connection filters that the transfer represented by `data` + * is finished - eventually premature, e.g. before being complete. + */ +void Curl_conn_ev_data_done(struct Curl_easy *data, bool premature); + +/** + * Notify connection filters that the transfer of data is paused/unpaused. + */ +CURLcode Curl_conn_ev_data_pause(struct Curl_easy *data, bool do_pause); + +/** + * Check if FIRSTSOCKET's cfilter chain deems connection alive. + */ +bool Curl_conn_is_alive(struct Curl_easy *data, struct connectdata *conn, + bool *input_pending); + +/** + * Try to upkeep the connection filters at sockindex. + */ +CURLcode Curl_conn_keep_alive(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +#ifdef UNITTESTS +void Curl_cf_def_close(struct Curl_cfilter *cf, struct Curl_easy *data); +#endif +void Curl_conn_get_host(struct Curl_easy *data, int sockindex, + const char **phost, const char **pdisplay_host, + int *pport); + +/** + * Get the maximum number of parallel transfers the connection + * expects to be able to handle at `sockindex`. + */ +size_t Curl_conn_get_max_concurrent(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +/** + * Get the underlying error code for a transfer stream or 0 if not known. + */ +int Curl_conn_get_stream_error(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +/** + * Get the index of the given socket in the connection's sockets. + * Useful in calling `Curl_conn_send()/Curl_conn_recv()` with the + * correct socket index. + */ +int Curl_conn_sockindex(struct Curl_easy *data, curl_socket_t sockfd); + +/* + * Receive data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Will return CURLE_AGAIN iff blocked on receiving. + */ +CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex, + char *buf, size_t buffersize, + ssize_t *pnread); + +/* + * Send data on the connection, using FIRSTSOCKET/SECONDARYSOCKET. + * Will return CURLE_AGAIN iff blocked on sending. + */ +CURLcode Curl_conn_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t blen, bool eos, + size_t *pnwritten); + + +void Curl_pollset_reset(struct Curl_easy *data, + struct easy_pollset *ps); + +/* Change the poll flags (CURL_POLL_IN/CURL_POLL_OUT) to the poll set for + * socket `sock`. If the socket is not already part of the poll set, it + * will be added. + * If the socket is present and all poll flags are cleared, it will be removed. + */ +void Curl_pollset_change(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + int add_flags, int remove_flags); + +void Curl_pollset_set(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool do_in, bool do_out); + +#define Curl_pollset_add_in(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), CURL_POLL_IN, 0) +#define Curl_pollset_add_out(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), CURL_POLL_OUT, 0) +#define Curl_pollset_add_inout(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_IN|CURL_POLL_OUT, 0) +#define Curl_pollset_set_in_only(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_IN, CURL_POLL_OUT) +#define Curl_pollset_set_out_only(data, ps, sock) \ + Curl_pollset_change((data), (ps), (sock), \ + CURL_POLL_OUT, CURL_POLL_IN) + +void Curl_pollset_add_socks(struct Curl_easy *data, + struct easy_pollset *ps, + int (*get_socks_cb)(struct Curl_easy *data, + curl_socket_t *socks)); + +/** + * Check if the pollset, as is, wants to read and/or write regarding + * the given socket. + */ +void Curl_pollset_check(struct Curl_easy *data, + struct easy_pollset *ps, curl_socket_t sock, + bool *pwant_read, bool *pwant_write); + +/** + * Types and macros used to keep the current easy handle in filter calls, + * allowing for nested invocations. See #10336. + * + * `cf_call_data` is intended to be a member of the cfilter's `ctx` type. + * A filter defines the macro `CF_CTX_CALL_DATA` to give access to that. + * + * With all values 0, the default, this indicates that there is no cfilter + * call with `data` ongoing. + * Macro `CF_DATA_SAVE` preserves the current `cf_call_data` in a local + * variable and sets the `data` given, incrementing the `depth` counter. + * + * Macro `CF_DATA_RESTORE` restores the old values from the local variable, + * while checking that `depth` values are as expected (debug build), catching + * cases where a "lower" RESTORE was not called. + * + * Finally, macro `CF_DATA_CURRENT` gives the easy handle of the current + * invocation. + */ +struct cf_call_data { + struct Curl_easy *data; +#ifdef DEBUGBUILD + int depth; +#endif +}; + +/** + * define to access the `struct cf_call_data for a cfilter. Normally + * a member in the cfilter's `ctx`. + * + * #define CF_CTX_CALL_DATA(cf) -> struct cf_call_data instance +*/ + +#ifdef DEBUGBUILD + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + DEBUGASSERT((save).data == NULL || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf).depth++; \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)data; \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + DEBUGASSERT(CF_CTX_CALL_DATA(cf).depth == (save).depth + 1); \ + DEBUGASSERT((save).data == NULL || (save).depth > 0); \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#else /* DEBUGBUILD */ + +#define CF_DATA_SAVE(save, cf, data) \ + do { \ + (save) = CF_CTX_CALL_DATA(cf); \ + CF_CTX_CALL_DATA(cf).data = (struct Curl_easy *)data; \ + } while(0) + +#define CF_DATA_RESTORE(cf, save) \ + do { \ + CF_CTX_CALL_DATA(cf) = (save); \ + } while(0) + +#endif /* !DEBUGBUILD */ + +#define CF_DATA_CURRENT(cf) \ + ((cf)? (CF_CTX_CALL_DATA(cf).data) : NULL) + +#endif /* HEADER_CURL_CFILTERS_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/config-os400.h b/local-test-curl-full-01/afc-curl/lib/config-os400.h new file mode 100644 index 0000000000000000000000000000000000000000..88259d95f4be056bdfd6743b954fd4b5be9a3854 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/config-os400.h @@ -0,0 +1,328 @@ +#ifndef HEADER_CURL_CONFIG_OS400_H +#define HEADER_CURL_CONFIG_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for OS/400 */ +/* ================================================================ */ + +#pragma enum(int) + +#undef PACKAGE + +/* Version number of this archive. */ +#undef VERSION + +/* Define cpu-machine-OS */ +#ifndef CURL_OS +#define CURL_OS "OS/400" +#endif + +/* OS400 supports a 3-argument ASCII version of gethostbyaddr_r(), but its + * prototype is incompatible with the "standard" one (1st argument is not + * const). However, getaddrinfo() is supported (ASCII version defined as + * a local wrapper in setup-os400.h) in a threadsafe way: we can then + * configure getaddrinfo() as such and get rid of gethostbyname_r() without + * loss of threadsafeness. */ +#undef HAVE_GETHOSTBYNAME_R +#undef HAVE_GETHOSTBYNAME_R_3 +#undef HAVE_GETHOSTBYNAME_R_5 +#undef HAVE_GETHOSTBYNAME_R_6 +#define HAVE_GETADDRINFO +#define HAVE_GETADDRINFO_THREADSAFE + +/* Define if you need the _REENTRANT define for some functions */ +#undef NEED_REENTRANT + +/* Define if you want to enable IPv6 support */ +#define USE_IPV6 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* Define this to 'int' if ssize_t is not an available typedefed type */ +#undef ssize_t + +/* Define to 1 if you have the alarm function. */ +#define HAVE_ALARM 1 + +/* Define if you have the header file. */ +#define HAVE_ARPA_INET_H + +/* Define if you have the `closesocket' function. */ +#undef HAVE_CLOSESOCKET + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H + +/* Define if you have the `geteuid' function. */ +#define HAVE_GETEUID + +/* Define if you have the `gethostname' function. */ +#define HAVE_GETHOSTNAME + +/* Define if you have the `getpass_r' function. */ +#undef HAVE_GETPASS_R + +/* Define to 1 if you have the getpeername function. */ +#define HAVE_GETPEERNAME 1 + +/* Define if you have the `getpwuid' function. */ +#define HAVE_GETPWUID + +/* Define to 1 if you have the getsockname function. */ +#define HAVE_GETSOCKNAME 1 + +/* Define if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY + +/* Define if you have the `timeval' struct. */ +#define HAVE_STRUCT_TIMEVAL + +/* Define if you have the header file. */ +#undef HAVE_IO_H + +/* Define if you have GSS API. */ +#define HAVE_GSSAPI + +/* Define if you have the GNU gssapi libraries */ +#undef HAVE_GSSGNU + +/* Define if you need the malloc.h header file even with stdlib.h */ +/* #define NEED_MALLOC_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_NETDB_H + +/* Define if you have the header file. */ +#define HAVE_NETINET_IN_H + +/* Define if you have the header file. */ +#define HAVE_NET_IF_H + +/* Define if you have the header file. */ +#define HAVE_PWD_H + +/* Define if you have the `select' function. */ +#define HAVE_SELECT + +/* Define if you have the `sigaction' function. */ +#define HAVE_SIGACTION + +/* Define if you have the `signal' function. */ +#undef HAVE_SIGNAL + +/* Define if you have the `socket' function. */ +#define HAVE_SOCKET + + +/* The following define is needed on OS400 to enable strcmpi(), stricmp() and + strdup(). */ +#define __cplusplus__strings__ + +/* Define if you have the `strcasecmp' function. */ +#undef HAVE_STRCASECMP + +/* Define if you have the `strcmpi' function. */ +#define HAVE_STRCMPI + +/* Define if you have the `stricmp' function. */ +#define HAVE_STRICMP + +/* Define if you have the `strdup' function. */ +#define HAVE_STRDUP + +/* Define if you have the header file. */ +#define HAVE_STRINGS_H + +/* Define if you have the header file. */ +#undef HAVE_STROPTS_H + +/* Define if you have the `strtok_r' function. */ +#define HAVE_STRTOK_R + +/* Define if you have the `strtoll' function. */ +#undef HAVE_STRTOLL /* Allows ASCII compile on V5R1. */ + +/* Define if you have the header file. */ +#define HAVE_SYS_PARAM_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_SOCKET_H + +/* Define if you have the header file. */ +#undef HAVE_SYS_SOCKIO_H + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TIME_H + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H + +/* Define if you have the header file. */ +#define HAVE_SYS_UN_H + +/* Define if you have the header file. */ +#define HAVE_SYS_IOCTL_H + +/* Define if you have the header file. */ +#undef HAVE_TERMIOS_H + +/* Define if you have the header file. */ +#undef HAVE_TERMIO_H + +/* Define if you have the header file. */ +#define HAVE_UNISTD_H + +/* Name of package */ +#undef PACKAGE + +/* The size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define if the compiler supports the 'long long' data type. */ +#define HAVE_LONGLONG + +/* The size of a `long long', as computed by sizeof. */ +#define SIZEOF_LONG_LONG 8 + +/* The size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 4 + +/* The size of `size_t', as computed by sizeof. */ +#define SIZEOF_SIZE_T 4 + +/* The size of `curl_off_t', as computed by sizeof. */ +#define SIZEOF_CURL_OFF_T 8 + +/* Define this if you have struct sockaddr_storage */ +#define HAVE_STRUCT_SOCKADDR_STORAGE + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS + +/* Define to enable HTTP3 support (experimental, requires NGTCP2, quiche or + MSH3) */ +#undef USE_HTTP3 + +/* Version number of package */ +#undef VERSION + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#define _LARGE_FILES + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* type to use in place of in_addr_t if not defined */ +#define in_addr_t unsigned long + +/* Define to `unsigned' if does not define. */ +#undef size_t + +/* Define if you have a working ioctl FIONBIO function. */ +#define HAVE_IOCTL_FIONBIO + +/* Define if you have a working ioctl SIOCGIFADDR function. */ +#define HAVE_IOCTL_SIOCGIFADDR + +/* To disable LDAP */ +#undef CURL_DISABLE_LDAP + +/* Definition to make a library symbol externally visible. */ +#define CURL_EXTERN_SYMBOL + +/* Define if you have the ldap_url_parse procedure. */ +/* #define HAVE_LDAP_URL_PARSE */ /* Disabled because of an IBM bug. */ + +/* Define if you have the recv function. */ +#define HAVE_RECV + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 int + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 int + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Define to use the OS/400 crypto library. */ +#define USE_OS400CRYPTO + +/* Define to use Unix sockets. */ +#define USE_UNIX_SOCKETS + +/* Use the system keyring as the default CA bundle. */ +#define CURL_CA_BUNDLE "/QIBM/UserData/ICSS/Cert/Server/DEFAULT.KDB" + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* The following must be defined BEFORE system header files inclusion. */ + +#define __ptr128 /* No teraspace. */ +#define qadrt_use_fputc_inline /* Generate fputc() wrapper inline. */ +#define qadrt_use_fread_inline /* Generate fread() wrapper inline. */ +#define qadrt_use_fwrite_inline /* Generate fwrite() wrapper inline. */ + +#endif /* HEADER_CURL_CONFIG_OS400_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/config-plan9.h b/local-test-curl-full-01/afc-curl/lib/config-plan9.h new file mode 100644 index 0000000000000000000000000000000000000000..699291a1eddb935e8f85f9c820e72232e8fc8c80 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/config-plan9.h @@ -0,0 +1,146 @@ +#ifndef HEADER_CURL_CONFIG_PLAN9_H +#define HEADER_CURL_CONFIG_PLAN9_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define BUILDING_LIBCURL 1 +#define CURL_CA_BUNDLE "/sys/lib/tls/ca.pem" +#define CURL_CA_PATH "/sys/lib/tls" +#define CURL_STATICLIB 1 +#define USE_IPV6 1 +#define CURL_DISABLE_LDAP 1 + +#define NEED_REENTRANT 1 +#ifndef CURL_OS +#define CURL_OS "plan9" +#endif +#define PACKAGE "curl" +#define PACKAGE_NAME "curl" +#define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/" +#define PACKAGE_STRING "curl -" +#define PACKAGE_TARNAME "curl" +#define PACKAGE_VERSION "-" +#define VERSION "0.0.0" /* TODO */ + +#define STDC_HEADERS 1 + +#ifdef _BITS64 +#error not implement +#else +#define SIZEOF_INT 4 +#define SIZEOF_LONG 4 +#define SIZEOF_OFF_T 8 +#define SIZEOF_CURL_OFF_T 4 /* curl_off_t = timediff_t = int */ +#define SIZEOF_SIZE_T 4 +#define SIZEOF_TIME_T 4 +#endif + +#define HAVE_RECV 1 +#define RECV_TYPE_ARG1 int +#define RECV_TYPE_ARG2 void * +#define RECV_TYPE_ARG3 int +#define RECV_TYPE_ARG4 int +#define RECV_TYPE_RETV int + +#define HAVE_SELECT 1 + +#define HAVE_SEND 1 +#define SEND_TYPE_ARG1 int +#define SEND_TYPE_ARG2 void * +#define SEND_QUAL_ARG2 +#define SEND_TYPE_ARG3 int +#define SEND_TYPE_ARG4 int +#define SEND_TYPE_RETV int + +#define HAVE_ALARM 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_BASENAME 1 +#define HAVE_BOOL_T 1 +#define HAVE_FCNTL 1 +#define HAVE_FCNTL_H 1 +#define HAVE_FREEADDRINFO 1 +#define HAVE_FTRUNCATE 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETEUID 1 +#define HAVE_GETHOSTNAME 1 +#define HAVE_GETPPID 1 +#define HAVE_GETPWUID 1 +#define HAVE_GETTIMEOFDAY 1 +#define HAVE_GMTIME_R 1 +#define HAVE_INET_NTOP 1 +#define HAVE_INET_PTON 1 +#define HAVE_LIBGEN_H 1 +#define HAVE_LIBZ 1 +#define HAVE_LOCALE_H 1 +#define HAVE_LONGLONG 1 +#define HAVE_NETDB_H 1 +#define HAVE_NETINET_IN_H 1 +#define HAVE_NETINET_TCP_H 1 +#define HAVE_PWD_H 1 +#define HAVE_SYS_SELECT_H 1 + +#define USE_OPENSSL 1 + +#define HAVE_PIPE 1 +#define HAVE_POLL 1 +#define HAVE_POLL_H 1 +#define HAVE_PTHREAD_H 1 +#define HAVE_SETLOCALE 1 + +#define HAVE_SIGACTION 1 +#define HAVE_SIGNAL 1 +#define HAVE_SIGSETJMP 1 +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 +#define HAVE_SOCKET 1 +#define HAVE_SSL_GET_SHUTDOWN 1 +#define HAVE_STDBOOL_H 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRDUP 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRUCT_TIMEVAL 1 +#define HAVE_SYS_IOCTL_H 1 +#define HAVE_SYS_PARAM_H 1 +#define HAVE_SYS_RESOURCE_H 1 +#define HAVE_SYS_SOCKET_H 1 +#define HAVE_SYS_STAT_H 1 +#define HAVE_SYS_TIME_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_SYS_UN_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_UTIME 1 +#define HAVE_UTIME_H 1 + +#define HAVE_POSIX_STRERROR_R 1 +#define HAVE_STRERROR_R 1 +#define USE_MANUAL 1 + +#define __attribute__(x) + +#ifndef __cplusplus +#undef inline +#endif + +#endif /* HEADER_CURL_CONFIG_PLAN9_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/config-win32.h b/local-test-curl-full-01/afc-curl/lib/config-win32.h new file mode 100644 index 0000000000000000000000000000000000000000..2daed912d0e9bd9ed4437c20df8a0deee5a5bc65 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/config-win32.h @@ -0,0 +1,511 @@ +#ifndef HEADER_CURL_CONFIG_WIN32_H +#define HEADER_CURL_CONFIG_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for Windows */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +/* #define HAVE_ARPA_INET_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the header file. */ +#define HAVE_IO_H 1 + +/* Define if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define if you need header even with header file. */ +#define NEED_MALLOC_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_NETDB_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_NETINET_IN_H 1 */ + +/* Define to 1 if you have the header file. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_STDBOOL_H 1 +#endif + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_SYS_PARAM_H 1 +#endif + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SELECT_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKET_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKIO_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_SYS_TIME_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define if you have the header file. */ +#define HAVE_SYS_UTIME_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_TERMIO_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_TERMIOS_H 1 */ + +/* Define if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_UNISTD_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#if defined(__MINGW32__) +#define HAVE_LIBGEN_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to 1 if bool is an available type. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_BOOL_T 1 +#endif + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you have the ftruncate function. */ +#if defined(__MINGW32__) +#define HAVE_FTRUNCATE 1 +#endif + +/* Define to 1 if you have the `getpeername' function. */ +#define HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the getsockname function. */ +#define HAVE_GETSOCKNAME 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the gettimeofday function. */ +#if defined(__MINGW32__) +#define HAVE_GETTIMEOFDAY 1 +#endif + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the select function. */ +#define HAVE_SELECT 1 + +/* Define if you have the setlocale function. */ +#define HAVE_SETLOCALE 1 + +/* Define if you have the setmode function. */ +#define HAVE_SETMODE 1 + +/* Define if you have the _setmode function. */ +#define HAVE__SETMODE 1 + +/* Define if you have the socket function. */ +#define HAVE_SOCKET 1 + +/* Define if you have the strcasecmp function. */ +#if defined(__MINGW32__) +#define HAVE_STRCASECMP 1 +#endif + +/* Define if you have the strdup function. */ +#define HAVE_STRDUP 1 + +/* Define if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define if you have the strtoll function. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) || defined(__MINGW32__) +#define HAVE_STRTOLL 1 +#endif + +/* Define if you have the utime function. */ +#define HAVE_UTIME 1 + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Define to 1 if you have the snprintf function. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1900)) || defined(__MINGW32__) +#define HAVE_SNPRINTF 1 +#endif + +#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 /* Vista */ +/* Define to 1 if you have a IPv6 capable working inet_ntop function. */ +#define HAVE_INET_NTOP 1 +/* Define to 1 if you have a IPv6 capable working inet_pton function. */ +#define HAVE_INET_PTON 1 +#endif + +/* Define to 1 if you have the `basename' function. */ +#if defined(__MINGW32__) +#define HAVE_BASENAME 1 +#endif + +/* Define to 1 if you have the strtok_r function. */ +#if defined(__MINGW32__) +#define HAVE_STRTOK_R 1 +#endif + +/* Define to 1 if you have the signal function. */ +#define HAVE_SIGNAL 1 + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define if in_addr_t is not an available 'typedefed' type. */ +#define in_addr_t unsigned long + +/* Define if ssize_t is not an available 'typedefed' type. */ +#ifndef _SSIZE_T_DEFINED +# if defined(__MINGW32__) +# elif defined(_WIN64) +# define _SSIZE_T_DEFINED +# define ssize_t __int64 +# else +# define _SSIZE_T_DEFINED +# define ssize_t int +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* Define to the size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define to the size of `long long', as computed by sizeof. */ +/* #define SIZEOF_LONG_LONG 8 */ + +/* Define to the size of `long', as computed by sizeof. */ +#define SIZEOF_LONG 4 + +/* Define to the size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* Define to the size of `curl_off_t', as computed by sizeof. */ +#define SIZEOF_CURL_OFF_T 8 + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to nothing if compiler does not support 'const' qualifier. */ +/* #define const */ + +/* Define to nothing if compiler does not support 'volatile' qualifier. */ +/* #define volatile */ + +/* Windows should not have HAVE_GMTIME_R defined */ +/* #undef HAVE_GMTIME_R */ + +/* Define if the compiler supports the 'long long' data type. */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1310)) || defined(__MINGW32__) +#define HAVE_LONGLONG 1 +#endif + +/* Define to avoid VS2005 complaining about portable C functions. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define _CRT_SECURE_NO_DEPRECATE 1 +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* mingw-w64 and visual studio >= 2005 (MSVCR80) + all default to 64-bit time_t unless _USE_32BIT_TIME_T is defined */ +#if (defined(_MSC_VER) && (_MSC_VER >= 1400)) || defined(__MINGW32__) +# ifndef _USE_32BIT_TIME_T +# define SIZEOF_TIME_T 8 +# else +# define SIZEOF_TIME_T 4 +# endif +#endif + +/* Define some minimum and default build targets for Visual Studio */ +#if defined(_MSC_VER) + /* Officially, Microsoft's Windows SDK versions 6.X does not support Windows + 2000 as a supported build target. VS2008 default installations provides + an embedded Windows SDK v6.0A along with the claim that Windows 2000 is a + valid build target for VS2008. Popular belief is that binaries built with + VS2008 using Windows SDK versions v6.X and Windows 2000 as a build target + are functional. */ +# define VS2008_MIN_TARGET 0x0500 + + /* The minimum build target for VS2012 is Vista unless Update 1 is installed + and the v110_xp toolset is chosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_MIN_TARGET 0x0501 +# else +# define VS2012_MIN_TARGET 0x0600 +# endif + + /* VS2008 default build target is Windows Vista. We override default target + to be Windows XP. */ +# define VS2008_DEF_TARGET 0x0501 + + /* VS2012 default build target is Windows Vista unless Update 1 is installed + and the v110_xp toolset is chosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_DEF_TARGET 0x0501 +# else +# define VS2012_DEF_TARGET 0x0600 +# endif +#endif + +/* VS2008 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_MSC_VER <= 1600) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2008_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2008_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET) +# error VS2008 does not support Windows build targets prior to Windows 2000 +# endif +#endif + +/* VS2012 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1700) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2012_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2012_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2012_MIN_TARGET) || (WINVER < VS2012_MIN_TARGET) +# if defined(_USING_V110_SDK71_) +# error VS2012 does not support Windows build targets prior to Windows XP +# else +# error VS2012 does not support Windows build targets prior to Windows \ +Vista +# endif +# endif +#endif + +/* Windows XP is required for freeaddrinfo, getaddrinfo */ +#define HAVE_FREEADDRINFO 1 +#define HAVE_GETADDRINFO 1 +#define HAVE_GETADDRINFO_THREADSAFE 1 + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define if you have struct sockaddr_storage. */ +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 + +/* Define if you have struct timeval. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member. */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +/* ---------------------------------------------------------------- */ +/* LARGE FILE SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define USE_WIN32_LARGE_FILES +# else +# define USE_WIN32_SMALL_FILES +# endif +#endif + +#if defined(__MINGW32__) && !defined(USE_WIN32_LARGE_FILES) +# define USE_WIN32_LARGE_FILES +#endif + +#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES) +# define USE_WIN32_SMALL_FILES +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#if defined(USE_WIN32_LARGE_FILES) && defined(__MINGW32__) +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +#endif + +/* Define to the size of `off_t', as computed by sizeof. */ +#if defined(__MINGW32__) && \ + defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64) +# define SIZEOF_OFF_T 8 +#else +# define SIZEOF_OFF_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* DNS RESOLVER SPECIALTY */ +/* ---------------------------------------------------------------- */ + +/* + * Undefine both USE_ARES and USE_THREADS_WIN32 for synchronous DNS. + */ + +/* Define to enable c-ares asynchronous DNS lookups. */ +/* #define USE_ARES 1 */ + +/* Default define to enable threaded asynchronous DNS lookups. */ +#if !defined(USE_SYNC_DNS) && !defined(USE_ARES) && \ + !defined(USE_THREADS_WIN32) +# define USE_THREADS_WIN32 1 +#endif + +#if defined(USE_ARES) && defined(USE_THREADS_WIN32) +# error "Only one DNS lookup specialty may be defined at most" +#endif + +/* ---------------------------------------------------------------- */ +/* LDAP SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(CURL_HAS_NOVELL_LDAPSDK) +#undef USE_WIN32_LDAP +#define HAVE_LDAP_SSL_H 1 +#define HAVE_LDAP_URL_PARSE 1 +#elif defined(CURL_HAS_OPENLDAP_LDAPSDK) +#undef USE_WIN32_LDAP +#define HAVE_LDAP_URL_PARSE 1 +#else +#undef HAVE_LDAP_URL_PARSE +#define HAVE_LDAP_SSL 1 +#define USE_WIN32_LDAP 1 +#endif + +/* Define to use the Windows crypto library. */ +#if !defined(CURL_WINDOWS_UWP) +#define USE_WIN32_CRYPTO +#endif + +/* Define to use Unix sockets. */ +#define USE_UNIX_SOCKETS + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* Define cpu-machine-OS */ +#ifndef CURL_OS +#if defined(_M_IX86) || defined(__i386__) /* x86 (MSVC or gcc) */ +#define CURL_OS "i386-pc-win32" +#elif defined(_M_X64) || defined(__x86_64__) /* x86_64 (MSVC >=2005 or gcc) */ +#define CURL_OS "x86_64-pc-win32" +#elif defined(_M_IA64) || defined(__ia64__) /* Itanium */ +#define CURL_OS "ia64-pc-win32" +#elif defined(_M_ARM_NT) || defined(__arm__) /* ARMv7-Thumb2 (Windows RT) */ +#define CURL_OS "thumbv7a-pc-win32" +#elif defined(_M_ARM64) || defined(__aarch64__) /* ARM64 (Windows 10) */ +#define CURL_OS "aarch64-pc-win32" +#else +#define CURL_OS "unknown-pc-win32" +#endif +#endif + +/* Name of package */ +#define PACKAGE "curl" + +/* If you want to build curl with the built-in manual */ +#define USE_MANUAL 1 + +#endif /* HEADER_CURL_CONFIG_WIN32_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/content_encoding.h b/local-test-curl-full-01/afc-curl/lib/content_encoding.h new file mode 100644 index 0000000000000000000000000000000000000000..1addf230bbf5e5912e061d35940fa9406ce5c39a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/content_encoding.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_CONTENT_ENCODING_H +#define HEADER_CURL_CONTENT_ENCODING_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +struct Curl_cwriter; + +void Curl_all_content_encodings(char *buf, size_t blen); + +CURLcode Curl_build_unencoding_stack(struct Curl_easy *data, + const char *enclist, int is_transfer); +#endif /* HEADER_CURL_CONTENT_ENCODING_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_addrinfo.c b/local-test-curl-full-01/afc-curl/lib/curl_addrinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..a08caf3328c6bd752a712091561c876fcf7b2229 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_addrinfo.c @@ -0,0 +1,586 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETINET_IN6_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef HAVE_SYS_UN_H +# include +#endif + +#ifdef __VMS +# include +# include +#endif + +#include + +#include "curl_addrinfo.h" +#include "inet_pton.h" +#include "warnless.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + * Curl_freeaddrinfo() + * + * This is used to free a linked list of Curl_addrinfo structs along + * with all its associated allocated storage. This function should be + * called once for each successful call to Curl_getaddrinfo_ex() or to + * any function call which actually allocates a Curl_addrinfo struct. + */ + +#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \ + defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__) + /* workaround icc 9.1 optimizer issue */ +# define vqualifier volatile +#else +# define vqualifier +#endif + +void +Curl_freeaddrinfo(struct Curl_addrinfo *cahead) +{ + struct Curl_addrinfo *vqualifier canext; + struct Curl_addrinfo *ca; + + for(ca = cahead; ca; ca = canext) { + canext = ca->ai_next; + free(ca); + } +} + + +#ifdef HAVE_GETADDRINFO +/* + * Curl_getaddrinfo_ex() + * + * This is a wrapper function around system's getaddrinfo(), with + * the only difference that instead of returning a linked list of + * addrinfo structs this one returns a linked list of Curl_addrinfo + * ones. The memory allocated by this function *MUST* be free'd with + * Curl_freeaddrinfo(). For each successful call to this function + * there must be an associated call later to Curl_freeaddrinfo(). + * + * There should be no single call to system's getaddrinfo() in the + * whole library, any such call should be 'routed' through this one. + */ + +int +Curl_getaddrinfo_ex(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct Curl_addrinfo **result) +{ + const struct addrinfo *ai; + struct addrinfo *aihead; + struct Curl_addrinfo *cafirst = NULL; + struct Curl_addrinfo *calast = NULL; + struct Curl_addrinfo *ca; + size_t ss_size; + int error; + + *result = NULL; /* assume failure */ + + error = getaddrinfo(nodename, servname, hints, &aihead); + if(error) + return error; + + /* traverse the addrinfo list */ + + for(ai = aihead; ai != NULL; ai = ai->ai_next) { + size_t namelen = ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0; + /* ignore elements with unsupported address family, */ + /* settle family-specific sockaddr structure size. */ + if(ai->ai_family == AF_INET) + ss_size = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(ai->ai_family == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); +#endif + else + continue; + + /* ignore elements without required address info */ + if(!ai->ai_addr || !(ai->ai_addrlen > 0)) + continue; + + /* ignore elements with bogus address size */ + if((size_t)ai->ai_addrlen < ss_size) + continue; + + ca = malloc(sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ca) { + error = EAI_MEMORY; + break; + } + + /* copy each structure member individually, member ordering, */ + /* size, or padding might be different for each platform. */ + + ca->ai_flags = ai->ai_flags; + ca->ai_family = ai->ai_family; + ca->ai_socktype = ai->ai_socktype; + ca->ai_protocol = ai->ai_protocol; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = NULL; + ca->ai_canonname = NULL; + ca->ai_next = NULL; + + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, ai->ai_addr, ss_size); + + if(namelen) { + ca->ai_canonname = (void *)((char *)ca->ai_addr + ss_size); + memcpy(ca->ai_canonname, ai->ai_canonname, namelen); + } + + /* if the return list is empty, this becomes the first element */ + if(!cafirst) + cafirst = ca; + + /* add this element last in the return list */ + if(calast) + calast->ai_next = ca; + calast = ca; + + } + + /* destroy the addrinfo list */ + if(aihead) + freeaddrinfo(aihead); + + /* if we failed, also destroy the Curl_addrinfo list */ + if(error) { + Curl_freeaddrinfo(cafirst); + cafirst = NULL; + } + else if(!cafirst) { +#ifdef EAI_NONAME + /* rfc3493 conformant */ + error = EAI_NONAME; +#else + /* rfc3493 obsoleted */ + error = EAI_NODATA; +#endif +#ifdef USE_WINSOCK + SET_SOCKERRNO(error); +#endif + } + + *result = cafirst; + + /* This is not a CURLcode */ + return error; +} +#endif /* HAVE_GETADDRINFO */ + + +/* + * Curl_he2ai() + * + * This function returns a pointer to the first element of a newly allocated + * Curl_addrinfo struct linked list filled with the data of a given hostent. + * Curl_addrinfo is meant to work like the addrinfo struct does for a IPv6 + * stack, but usable also for IPv4, all hosts and environments. + * + * The memory allocated by this function *MUST* be free'd later on calling + * Curl_freeaddrinfo(). For each successful call to this function there + * must be an associated call later to Curl_freeaddrinfo(). + * + * Curl_addrinfo defined in "lib/curl_addrinfo.h" + * + * struct Curl_addrinfo { + * int ai_flags; + * int ai_family; + * int ai_socktype; + * int ai_protocol; + * curl_socklen_t ai_addrlen; * Follow rfc3493 struct addrinfo * + * char *ai_canonname; + * struct sockaddr *ai_addr; + * struct Curl_addrinfo *ai_next; + * }; + * + * hostent defined in + * + * struct hostent { + * char *h_name; + * char **h_aliases; + * int h_addrtype; + * int h_length; + * char **h_addr_list; + * }; + * + * for backward compatibility: + * + * #define h_addr h_addr_list[0] + */ + +#if !(defined(HAVE_GETADDRINFO) && defined(HAVE_GETADDRINFO_THREADSAFE)) +struct Curl_addrinfo * +Curl_he2ai(const struct hostent *he, int port) +{ + struct Curl_addrinfo *ai; + struct Curl_addrinfo *prevai = NULL; + struct Curl_addrinfo *firstai = NULL; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + CURLcode result = CURLE_OK; + int i; + char *curr; + + if(!he) + /* no input == no output! */ + return NULL; + + DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL)); + + for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) { + size_t ss_size; + size_t namelen = strlen(he->h_name) + 1; /* include null-terminator */ +#ifdef USE_IPV6 + if(he->h_addrtype == AF_INET6) + ss_size = sizeof(struct sockaddr_in6); + else +#endif + ss_size = sizeof(struct sockaddr_in); + + /* allocate memory to hold the struct, the address and the name */ + ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + namelen); + if(!ai) { + result = CURLE_OUT_OF_MEMORY; + break; + } + /* put the address after the struct */ + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + /* then put the name after the address */ + ai->ai_canonname = (char *)ai->ai_addr + ss_size; + memcpy(ai->ai_canonname, he->h_name, namelen); + + if(!firstai) + /* store the pointer we want to return from this function */ + firstai = ai; + + if(prevai) + /* make the previous entry point to this */ + prevai->ai_next = ai; + + ai->ai_family = he->h_addrtype; + + /* we return all names as STREAM, so when using this address for TFTP + the type must be ignored and conn->socktype be used instead! */ + ai->ai_socktype = SOCK_STREAM; + + ai->ai_addrlen = (curl_socklen_t)ss_size; + + /* leave the rest of the struct filled with zero */ + + switch(ai->ai_family) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr->sin_addr, curr, sizeof(struct in_addr)); +#ifdef __MINGW32__ + addr->sin_family = (short)(he->h_addrtype); +#else + addr->sin_family = (CURL_SA_FAMILY_T)(he->h_addrtype); +#endif + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr6->sin6_addr, curr, sizeof(struct in6_addr)); +#ifdef __MINGW32__ + addr6->sin6_family = (short)(he->h_addrtype); +#else + addr6->sin6_family = (CURL_SA_FAMILY_T)(he->h_addrtype); +#endif + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + prevai = ai; + } + + if(result) { + Curl_freeaddrinfo(firstai); + firstai = NULL; + } + + return firstai; +} +#endif + +/* + * Curl_ip2addr() + * + * This function takes an Internet address, in binary form, as input parameter + * along with its address family and the string version of the address, and it + * returns a Curl_addrinfo chain filled in correctly with information for the + * given address/host + */ + +struct Curl_addrinfo * +Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port) +{ + struct Curl_addrinfo *ai; + size_t addrsize; + size_t namelen; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + + DEBUGASSERT(inaddr && hostname); + + namelen = strlen(hostname) + 1; + + if(af == AF_INET) + addrsize = sizeof(struct sockaddr_in); +#ifdef USE_IPV6 + else if(af == AF_INET6) + addrsize = sizeof(struct sockaddr_in6); +#endif + else + return NULL; + + /* allocate memory to hold the struct, the address and the name */ + ai = calloc(1, sizeof(struct Curl_addrinfo) + addrsize + namelen); + if(!ai) + return NULL; + /* put the address after the struct */ + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + /* then put the name after the address */ + ai->ai_canonname = (char *)ai->ai_addr + addrsize; + memcpy(ai->ai_canonname, hostname, namelen); + ai->ai_family = af; + ai->ai_socktype = SOCK_STREAM; + ai->ai_addrlen = (curl_socklen_t)addrsize; + /* leave the rest of the struct filled with zero */ + + switch(af) { + case AF_INET: + addr = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr->sin_addr, inaddr, sizeof(struct in_addr)); +#ifdef __MINGW32__ + addr->sin_family = (short)af; +#else + addr->sin_family = (CURL_SA_FAMILY_T)af; +#endif + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ai->ai_addr; /* storage area for this info */ + + memcpy(&addr6->sin6_addr, inaddr, sizeof(struct in6_addr)); +#ifdef __MINGW32__ + addr6->sin6_family = (short)af; +#else + addr6->sin6_family = (CURL_SA_FAMILY_T)af; +#endif + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + + return ai; +} + +/* + * Given an IPv4 or IPv6 dotted string address, this converts it to a proper + * allocated Curl_addrinfo struct and returns it. + */ +struct Curl_addrinfo *Curl_str2addr(char *address, int port) +{ + struct in_addr in; + if(Curl_inet_pton(AF_INET, address, &in) > 0) + /* This is a dotted IP address 123.123.123.123-style */ + return Curl_ip2addr(AF_INET, &in, address, port); +#ifdef USE_IPV6 + { + struct in6_addr in6; + if(Curl_inet_pton(AF_INET6, address, &in6) > 0) + /* This is a dotted IPv6 address ::1-style */ + return Curl_ip2addr(AF_INET6, &in6, address, port); + } +#endif + return NULL; /* bad input format */ +} + +#ifdef USE_UNIX_SOCKETS +/** + * Given a path to a Unix domain socket, return a newly allocated Curl_addrinfo + * struct initialized with this path. + * Set '*longpath' to TRUE if the error is a too long path. + */ +struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath, + bool abstract) +{ + struct Curl_addrinfo *ai; + struct sockaddr_un *sa_un; + size_t path_len; + + *longpath = FALSE; + + ai = calloc(1, sizeof(struct Curl_addrinfo) + sizeof(struct sockaddr_un)); + if(!ai) + return NULL; + ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo)); + + sa_un = (void *) ai->ai_addr; + sa_un->sun_family = AF_UNIX; + + /* sun_path must be able to store the NUL-terminated path */ + path_len = strlen(path) + 1; + if(path_len > sizeof(sa_un->sun_path)) { + free(ai); + *longpath = TRUE; + return NULL; + } + + ai->ai_family = AF_UNIX; + ai->ai_socktype = SOCK_STREAM; /* assume reliable transport for HTTP */ + ai->ai_addrlen = (curl_socklen_t) + ((offsetof(struct sockaddr_un, sun_path) + path_len) & 0x7FFFFFFF); + + /* Abstract Unix domain socket have NULL prefix instead of suffix */ + if(abstract) + memcpy(sa_un->sun_path + 1, path, path_len - 1); + else + memcpy(sa_un->sun_path, path, path_len); /* copy NUL byte */ + + return ai; +} +#endif + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \ + defined(HAVE_FREEADDRINFO) +/* + * curl_dbg_freeaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I did not want to include in memdebug.c + */ + +void +curl_dbg_freeaddrinfo(struct addrinfo *freethis, + int line, const char *source) +{ + curl_dbg_log("ADDR %s:%d freeaddrinfo(%p)\n", + source, line, (void *)freethis); +#ifdef USE_LWIPSOCK + lwip_freeaddrinfo(freethis); +#else + (freeaddrinfo)(freethis); +#endif +} +#endif /* defined(CURLDEBUG) && defined(HAVE_FREEADDRINFO) */ + + +#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) +/* + * curl_dbg_getaddrinfo() + * + * This is strictly for memory tracing and are using the same style as the + * family otherwise present in memdebug.c. I put these ones here since they + * require a bunch of structs I did not want to include in memdebug.c + */ + +int +curl_dbg_getaddrinfo(const char *hostname, + const char *service, + const struct addrinfo *hints, + struct addrinfo **result, + int line, const char *source) +{ +#ifdef USE_LWIPSOCK + int res = lwip_getaddrinfo(hostname, service, hints, result); +#else + int res = (getaddrinfo)(hostname, service, hints, result); +#endif + if(0 == res) + /* success */ + curl_dbg_log("ADDR %s:%d getaddrinfo() = %p\n", + source, line, (void *)*result); + else + curl_dbg_log("ADDR %s:%d getaddrinfo() failed\n", + source, line); + return res; +} +#endif /* defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) */ + +#if defined(HAVE_GETADDRINFO) && defined(USE_RESOLVE_ON_IPS) +/* + * Work-arounds the sin6_port is always zero bug on iOS 9.3.2 and macOS + * 10.11.5. + */ +void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port) +{ + struct Curl_addrinfo *ca; + struct sockaddr_in *addr; +#ifdef USE_IPV6 + struct sockaddr_in6 *addr6; +#endif + for(ca = addrinfo; ca != NULL; ca = ca->ai_next) { + switch(ca->ai_family) { + case AF_INET: + addr = (void *)ca->ai_addr; /* storage area for this info */ + addr->sin_port = htons((unsigned short)port); + break; + +#ifdef USE_IPV6 + case AF_INET6: + addr6 = (void *)ca->ai_addr; /* storage area for this info */ + addr6->sin6_port = htons((unsigned short)port); + break; +#endif + } + } +} +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/curl_base64.h b/local-test-curl-full-01/afc-curl/lib/curl_base64.h new file mode 100644 index 0000000000000000000000000000000000000000..7f7cd1d98a8474a4764c699becf4d6f651b14909 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_base64.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_BASE64_H +#define HEADER_CURL_BASE64_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef BUILDING_LIBCURL +/* this renames functions so that the tool code can use the same code + without getting symbol collisions */ +#define Curl_base64_encode(a,b,c,d) curlx_base64_encode(a,b,c,d) +#define Curl_base64url_encode(a,b,c,d) curlx_base64url_encode(a,b,c,d) +#define Curl_base64_decode(a,b,c) curlx_base64_decode(a,b,c) +#endif + +CURLcode Curl_base64_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode Curl_base64url_encode(const char *inputbuff, size_t insize, + char **outptr, size_t *outlen); +CURLcode Curl_base64_decode(const char *src, + unsigned char **outptr, size_t *outlen); +#endif /* HEADER_CURL_BASE64_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_ctype.h b/local-test-curl-full-01/afc-curl/lib/curl_ctype.h new file mode 100644 index 0000000000000000000000000000000000000000..7f0d0cc2916d08e63a9373708fdacc1c4ed7f490 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_ctype.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_CTYPE_H +#define HEADER_CURL_CTYPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define ISLOWHEXALHA(x) (((x) >= 'a') && ((x) <= 'f')) +#define ISUPHEXALHA(x) (((x) >= 'A') && ((x) <= 'F')) + +#define ISLOWCNTRL(x) ((unsigned char)(x) <= 0x1f) +#define IS7F(x) ((x) == 0x7f) + +#define ISLOWPRINT(x) (((x) >= 9) && ((x) <= 0x0d)) + +#define ISPRINT(x) (ISLOWPRINT(x) || (((x) >= ' ') && ((x) <= 0x7e))) +#define ISGRAPH(x) (ISLOWPRINT(x) || (((x) > ' ') && ((x) <= 0x7e))) +#define ISCNTRL(x) (ISLOWCNTRL(x) || IS7F(x)) +#define ISALPHA(x) (ISLOWER(x) || ISUPPER(x)) +#define ISXDIGIT(x) (ISDIGIT(x) || ISLOWHEXALHA(x) || ISUPHEXALHA(x)) +#define ISALNUM(x) (ISDIGIT(x) || ISLOWER(x) || ISUPPER(x)) +#define ISUPPER(x) (((x) >= 'A') && ((x) <= 'Z')) +#define ISLOWER(x) (((x) >= 'a') && ((x) <= 'z')) +#define ISDIGIT(x) (((x) >= '0') && ((x) <= '9')) +#define ISBLANK(x) (((x) == ' ') || ((x) == '\t')) +#define ISSPACE(x) (ISBLANK(x) || (((x) >= 0xa) && ((x) <= 0x0d))) +#define ISURLPUNTCS(x) (((x) == '-') || ((x) == '.') || ((x) == '_') || \ + ((x) == '~')) +#define ISUNRESERVED(x) (ISALNUM(x) || ISURLPUNTCS(x)) + + +#endif /* HEADER_CURL_CTYPE_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_des.c b/local-test-curl-full-01/afc-curl/lib/curl_des.c new file mode 100644 index 0000000000000000000000000000000000000000..15836f58b97ca23a5a07becc3a3bccbdcbef57fd --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_des.c @@ -0,0 +1,69 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(USE_CURL_NTLM_CORE) && \ + (defined(USE_GNUTLS) || \ + defined(USE_SECTRANSP) || \ + defined(USE_OS400CRYPTO) || \ + defined(USE_WIN32_CRYPTO)) + +#include "curl_des.h" + +/* + * Curl_des_set_odd_parity() + * + * This is used to apply odd parity to the given byte array. It is typically + * used by when a cryptography engine does not have its own version. + * + * The function is a port of the Java based oddParity() function over at: + * + * https://davenport.sourceforge.net/ntlm.html + * + * Parameters: + * + * bytes [in/out] - The data whose parity bits are to be adjusted for + * odd parity. + * len [out] - The length of the data. + */ +void Curl_des_set_odd_parity(unsigned char *bytes, size_t len) +{ + size_t i; + + for(i = 0; i < len; i++) { + unsigned char b = bytes[i]; + + bool needs_parity = (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ + (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ + (b >> 1)) & 0x01) == 0; + + if(needs_parity) + bytes[i] |= 0x01; + else + bytes[i] &= 0xfe; + } +} + +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/curl_fnmatch.h b/local-test-curl-full-01/afc-curl/lib/curl_fnmatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b8c2a4353c6230bb8a821c86ef37cc3eb5787e73 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_fnmatch.h @@ -0,0 +1,46 @@ +#ifndef HEADER_CURL_FNMATCH_H +#define HEADER_CURL_FNMATCH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define CURL_FNMATCH_MATCH 0 +#define CURL_FNMATCH_NOMATCH 1 +#define CURL_FNMATCH_FAIL 2 + +/* default pattern matching function + * ================================= + * Implemented with recursive backtracking, if you want to use Curl_fnmatch, + * please note that there is not implemented UTF/Unicode support. + * + * Implemented features: + * '?' notation, does not match UTF characters + * '*' can also work with UTF string + * [a-zA-Z0-9] enumeration support + * + * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space + * and upper (use as "[[:alnum:]]") + */ +int Curl_fnmatch(void *ptr, const char *pattern, const char *string); + +#endif /* HEADER_CURL_FNMATCH_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_get_line.c b/local-test-curl-full-01/afc-curl/lib/curl_get_line.c new file mode 100644 index 0000000000000000000000000000000000000000..100207331d81520d6172140254b958be21617821 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_get_line.c @@ -0,0 +1,77 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) || !defined(CURL_DISABLE_NETRC) + +#include "curl_get_line.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Curl_get_line() makes sure to only return complete whole lines that end + * newlines. + */ +int Curl_get_line(struct dynbuf *buf, FILE *input) +{ + CURLcode result; + char buffer[128]; + Curl_dyn_reset(buf); + while(1) { + char *b = fgets(buffer, sizeof(buffer), input); + + if(b) { + size_t rlen = strlen(b); + + if(!rlen) + break; + + result = Curl_dyn_addn(buf, b, rlen); + if(result) + /* too long line or out of memory */ + return 0; /* error */ + + else if(b[rlen-1] == '\n') + /* end of the line */ + return 1; /* all good */ + + else if(feof(input)) { + /* append a newline */ + result = Curl_dyn_addn(buf, "\n", 1); + if(result) + /* too long line or out of memory */ + return 0; /* error */ + return 1; /* all good */ + } + } + else + break; + } + return 0; +} + +#endif /* if not disabled */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_gethostname.c b/local-test-curl-full-01/afc-curl/lib/curl_gethostname.c new file mode 100644 index 0000000000000000000000000000000000000000..617a8ad52f6320f06a2e8880569cacb7745b9bbf --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_gethostname.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 "curl_setup.h" + +#include "curl_gethostname.h" + +/* + * Curl_gethostname() is a wrapper around gethostname() which allows + * overriding the hostname that the function would normally return. + * This capability is used by the test suite to verify exact matching + * of NTLM authentication, which exercises libcurl's MD4 and DES code + * as well as by the SMTP module when a hostname is not provided. + * + * For libcurl debug enabled builds hostname overriding takes place + * when environment variable CURL_GETHOSTNAME is set, using the value + * held by the variable to override returned hostname. + * + * Note: The function always returns the un-qualified hostname rather + * than being provider dependent. + */ + +int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen) +{ +#ifndef HAVE_GETHOSTNAME + + /* Allow compilation and return failure when unavailable */ + (void) name; + (void) namelen; + return -1; + +#else + int err; + char *dot; + +#ifdef DEBUGBUILD + + /* Override hostname when environment variable CURL_GETHOSTNAME is set */ + const char *force_hostname = getenv("CURL_GETHOSTNAME"); + if(force_hostname) { + if(strlen(force_hostname) < (size_t)namelen) + strcpy(name, force_hostname); + else + return 1; /* can't do it */ + err = 0; + } + else { + name[0] = '\0'; + err = gethostname(name, namelen); + } + +#else /* DEBUGBUILD */ + + name[0] = '\0'; + err = gethostname(name, namelen); + +#endif + + name[namelen - 1] = '\0'; + + if(err) + return err; + + /* Truncate domain, leave only machine name */ + dot = strchr(name, '.'); + if(dot) + *dot = '\0'; + + return 0; +#endif + +} diff --git a/local-test-curl-full-01/afc-curl/lib/curl_gssapi.c b/local-test-curl-full-01/afc-curl/lib/curl_gssapi.c new file mode 100644 index 0000000000000000000000000000000000000000..b7e774cea018ab507d98dcd372c6a83362a0d9a0 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_gssapi.c @@ -0,0 +1,152 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_GSSAPI + +#include "curl_gssapi.h" +#include "sendf.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(__GNUC__) +#define CURL_ALIGN8 __attribute__((aligned(8))) +#else +#define CURL_ALIGN8 +#endif + +gss_OID_desc Curl_spnego_mech_oid CURL_ALIGN8 = { + 6, (char *)"\x2b\x06\x01\x05\x05\x02" +}; +gss_OID_desc Curl_krb5_mech_oid CURL_ALIGN8 = { + 9, (char *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" +}; + +OM_uint32 Curl_gss_init_sec_context( + struct Curl_easy *data, + OM_uint32 *minor_status, + gss_ctx_id_t *context, + gss_name_t target_name, + gss_OID mech_type, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_buffer_t output_token, + const bool mutual_auth, + OM_uint32 *ret_flags) +{ + OM_uint32 req_flags = GSS_C_REPLAY_FLAG; + + if(mutual_auth) + req_flags |= GSS_C_MUTUAL_FLAG; + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) { +#ifdef GSS_C_DELEG_POLICY_FLAG + req_flags |= GSS_C_DELEG_POLICY_FLAG; +#else + infof(data, "WARNING: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not " + "compiled in"); +#endif + } + + if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) + req_flags |= GSS_C_DELEG_FLAG; + + return gss_init_sec_context(minor_status, + GSS_C_NO_CREDENTIAL, /* cred_handle */ + context, + target_name, + mech_type, + req_flags, + 0, /* time_req */ + input_chan_bindings, + input_token, + NULL, /* actual_mech_type */ + output_token, + ret_flags, + NULL /* time_rec */); +} + +#define GSS_LOG_BUFFER_LEN 1024 +static size_t display_gss_error(OM_uint32 status, int type, + char *buf, size_t len) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string = GSS_C_EMPTY_BUFFER; + + do { + maj_stat = gss_display_status(&min_stat, + status, + type, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(maj_stat == GSS_S_COMPLETE && status_string.length > 0) { + if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { + len += msnprintf(buf + len, GSS_LOG_BUFFER_LEN - len, + "%.*s. ", (int)status_string.length, + (char *)status_string.value); + } + } + gss_release_buffer(&min_stat, &status_string); + } while(!GSS_ERROR(maj_stat) && msg_ctx); + + return len; +} + +/* + * Curl_gss_log_error() + * + * This is used to log a GSS-API error status. + * + * Parameters: + * + * data [in] - The session handle. + * prefix [in] - The prefix of the log message. + * major [in] - The major status code. + * minor [in] - The minor status code. + */ +void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, + OM_uint32 major, OM_uint32 minor) +{ + char buf[GSS_LOG_BUFFER_LEN]; + size_t len = 0; + + if(major != GSS_S_FAILURE) + len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); + + display_gss_error(minor, GSS_C_MECH_CODE, buf, len); + + infof(data, "%s%s", prefix, buf); +#ifdef CURL_DISABLE_VERBOSE_STRINGS + (void)data; + (void)prefix; +#endif +} + +#endif /* HAVE_GSSAPI */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_krb5.h b/local-test-curl-full-01/afc-curl/lib/curl_krb5.h new file mode 100644 index 0000000000000000000000000000000000000000..ccf6b96a875edd87cee71dfba0bb0a70313a109c --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_krb5.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_KRB5_H +#define HEADER_CURL_KRB5_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +struct Curl_sec_client_mech { + const char *name; + size_t size; + int (*init)(void *); + int (*auth)(void *, struct Curl_easy *data, struct connectdata *); + void (*end)(void *); + int (*check_prot)(void *, int); + int (*encode)(void *, const void *, int, int, void **); + int (*decode)(void *, void *, int, int, struct connectdata *); +}; + +#define AUTH_OK 0 +#define AUTH_CONTINUE 1 +#define AUTH_ERROR 2 + +#ifdef HAVE_GSSAPI +int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn, char *, + enum protection_level); +void Curl_sec_end(struct connectdata *); +CURLcode Curl_sec_login(struct Curl_easy *, struct connectdata *); +int Curl_sec_request_prot(struct connectdata *conn, const char *level); +#else +#define Curl_sec_end(x) +#endif + +#endif /* HEADER_CURL_KRB5_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_ldap.h b/local-test-curl-full-01/afc-curl/lib/curl_ldap.h new file mode 100644 index 0000000000000000000000000000000000000000..8a1d807ed92b0c8fcfd6db62e9c5380a4c7ba13b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_ldap.h @@ -0,0 +1,36 @@ +#ifndef HEADER_CURL_LDAP_H +#define HEADER_CURL_LDAP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#ifndef CURL_DISABLE_LDAP +extern const struct Curl_handler Curl_handler_ldap; + +#if !defined(CURL_DISABLE_LDAPS) && \ + ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ + (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) +extern const struct Curl_handler Curl_handler_ldaps; +#endif + +#endif +#endif /* HEADER_CURL_LDAP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_md5.h b/local-test-curl-full-01/afc-curl/lib/curl_md5.h new file mode 100644 index 0000000000000000000000000000000000000000..ec27503b144440f05cd24a5eed06f022b55f2f02 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_md5.h @@ -0,0 +1,67 @@ +#ifndef HEADER_CURL_MD5_H +#define HEADER_CURL_MD5_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + +#include "curl_hmac.h" + +#define MD5_DIGEST_LEN 16 + +typedef CURLcode (*Curl_MD5_init_func)(void *context); +typedef void (*Curl_MD5_update_func)(void *context, + const unsigned char *data, + unsigned int len); +typedef void (*Curl_MD5_final_func)(unsigned char *result, void *context); + +struct MD5_params { + Curl_MD5_init_func md5_init_func; /* Initialize context procedure */ + Curl_MD5_update_func md5_update_func; /* Update context with data */ + Curl_MD5_final_func md5_final_func; /* Get final result procedure */ + unsigned int md5_ctxtsize; /* Context structure size */ + unsigned int md5_resultlen; /* Result length (bytes) */ +}; + +struct MD5_context { + const struct MD5_params *md5_hash; /* Hash function definition */ + void *md5_hashctx; /* Hash function context */ +}; + +extern const struct MD5_params Curl_DIGEST_MD5; +extern const struct HMAC_params Curl_HMAC_MD5; + +CURLcode Curl_md5it(unsigned char *output, const unsigned char *input, + const size_t len); + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params); +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *data, + unsigned int len); +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result); + +#endif + +#endif /* HEADER_CURL_MD5_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_memrchr.c b/local-test-curl-full-01/afc-curl/lib/curl_memrchr.c new file mode 100644 index 0000000000000000000000000000000000000000..c6d55f10423bc4a146f2912bae1a216a5609d340 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_memrchr.c @@ -0,0 +1,68 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "curl_memrchr.h" +#include "curl_memory.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#ifndef HAVE_MEMRCHR +#if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)) || \ + defined(USE_OPENSSL) || \ + defined(USE_SCHANNEL) + +/* + * Curl_memrchr() + * + * Our memrchr() function clone for systems which lack this function. The + * memrchr() function is like the memchr() function, except that it searches + * backwards from the end of the n bytes pointed to by s instead of forward + * from the beginning. + */ + +void * +Curl_memrchr(const void *s, int c, size_t n) +{ + if(n > 0) { + const unsigned char *p = s; + const unsigned char *q = s; + + p += n - 1; + + while(p >= q) { + if(*p == (unsigned char)c) + return (void *)p; + p--; + } + } + return NULL; +} + +#endif +#endif /* HAVE_MEMRCHR */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_multibyte.c b/local-test-curl-full-01/afc-curl/lib/curl_multibyte.c new file mode 100644 index 0000000000000000000000000000000000000000..86ac74ff4b065927bead5cfe1435659dd76ac553 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_multibyte.c @@ -0,0 +1,162 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * This file is 'mem-include-scan' clean, which means memdebug.h and + * curl_memory.h are purposely not included in this file. See test 1132. + * + * The functions in this file are curlx functions which are not tracked by the + * curl memory tracker memdebug. + */ + +#include "curl_setup.h" + +#if defined(_WIN32) + +#include "curl_multibyte.h" + +/* + * MultiByte conversions using Windows kernel32 library. + */ + +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8) +{ + wchar_t *str_w = NULL; + + if(str_utf8) { + int str_w_len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, + str_utf8, -1, NULL, 0); + if(str_w_len > 0) { + str_w = malloc(str_w_len * sizeof(wchar_t)); + if(str_w) { + if(MultiByteToWideChar(CP_UTF8, 0, str_utf8, -1, str_w, + str_w_len) == 0) { + free(str_w); + return NULL; + } + } + } + } + + return str_w; +} + +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w) +{ + char *str_utf8 = NULL; + + if(str_w) { + int bytes = WideCharToMultiByte(CP_UTF8, 0, str_w, -1, + NULL, 0, NULL, NULL); + if(bytes > 0) { + str_utf8 = malloc(bytes); + if(str_utf8) { + if(WideCharToMultiByte(CP_UTF8, 0, str_w, -1, str_utf8, bytes, + NULL, NULL) == 0) { + free(str_utf8); + return NULL; + } + } + } + } + + return str_utf8; +} + +#endif /* _WIN32 */ + +#if defined(USE_WIN32_LARGE_FILES) || defined(USE_WIN32_SMALL_FILES) + +int curlx_win32_open(const char *filename, int oflag, ...) +{ + int pmode = 0; + +#ifdef _UNICODE + int result = -1; + wchar_t *filename_w = curlx_convert_UTF8_to_wchar(filename); +#endif + + va_list param; + va_start(param, oflag); + if(oflag & O_CREAT) + pmode = va_arg(param, int); + va_end(param); + +#ifdef _UNICODE + if(filename_w) { + result = _wopen(filename_w, oflag, pmode); + curlx_unicodefree(filename_w); + } + else + errno = EINVAL; + return result; +#else + return (_open)(filename, oflag, pmode); +#endif +} + +FILE *curlx_win32_fopen(const char *filename, const char *mode) +{ +#ifdef _UNICODE + FILE *result = NULL; + wchar_t *filename_w = curlx_convert_UTF8_to_wchar(filename); + wchar_t *mode_w = curlx_convert_UTF8_to_wchar(mode); + if(filename_w && mode_w) + result = _wfopen(filename_w, mode_w); + else + errno = EINVAL; + curlx_unicodefree(filename_w); + curlx_unicodefree(mode_w); + return result; +#else + return (fopen)(filename, mode); +#endif +} + +int curlx_win32_stat(const char *path, struct_stat *buffer) +{ +#ifdef _UNICODE + int result = -1; + wchar_t *path_w = curlx_convert_UTF8_to_wchar(path); + if(path_w) { +#if defined(USE_WIN32_SMALL_FILES) + result = _wstat(path_w, buffer); +#else + result = _wstati64(path_w, buffer); +#endif + curlx_unicodefree(path_w); + } + else + errno = EINVAL; + return result; +#else +#if defined(USE_WIN32_SMALL_FILES) + return _stat(path, buffer); +#else + return _stati64(path, buffer); +#endif +#endif +} + +#endif /* USE_WIN32_LARGE_FILES || USE_WIN32_SMALL_FILES */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_multibyte.h b/local-test-curl-full-01/afc-curl/lib/curl_multibyte.h new file mode 100644 index 0000000000000000000000000000000000000000..dec384e2fe23b72968de4089ddc94c1fdebe03ec --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_multibyte.h @@ -0,0 +1,92 @@ +#ifndef HEADER_CURL_MULTIBYTE_H +#define HEADER_CURL_MULTIBYTE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(_WIN32) + + /* + * MultiByte conversions using Windows kernel32 library. + */ + +wchar_t *curlx_convert_UTF8_to_wchar(const char *str_utf8); +char *curlx_convert_wchar_to_UTF8(const wchar_t *str_w); +#endif /* _WIN32 */ + +/* + * Macros curlx_convert_UTF8_to_tchar(), curlx_convert_tchar_to_UTF8() + * and curlx_unicodefree() main purpose is to minimize the number of + * preprocessor conditional directives needed by code using these + * to differentiate Unicode from non-Unicode builds. + * + * In the case of a non-Unicode build the tchar strings are char strings that + * are duplicated via strdup and remain in whatever the passed in encoding is, + * which is assumed to be UTF-8 but may be other encoding. Therefore the + * significance of the conversion functions is primarily for Unicode builds. + * + * Allocated memory should be free'd with curlx_unicodefree(). + * + * Note: Because these are curlx functions their memory usage is not tracked + * by the curl memory tracker memdebug. you will notice that curlx + * function-like macros call free and strdup in parentheses, eg (strdup)(ptr), + * and that is to ensure that the curl memdebug override macros do not replace + * them. + */ + +#if defined(UNICODE) && defined(_WIN32) + +#define curlx_convert_UTF8_to_tchar(ptr) curlx_convert_UTF8_to_wchar((ptr)) +#define curlx_convert_tchar_to_UTF8(ptr) curlx_convert_wchar_to_UTF8((ptr)) + +typedef union { + unsigned short *tchar_ptr; + const unsigned short *const_tchar_ptr; + unsigned short *tbyte_ptr; + const unsigned short *const_tbyte_ptr; +} xcharp_u; + +#else + +#define curlx_convert_UTF8_to_tchar(ptr) (strdup)(ptr) +#define curlx_convert_tchar_to_UTF8(ptr) (strdup)(ptr) + +typedef union { + char *tchar_ptr; + const char *const_tchar_ptr; + unsigned char *tbyte_ptr; + const unsigned char *const_tbyte_ptr; +} xcharp_u; + +#endif /* UNICODE && _WIN32 */ + +#define curlx_unicodefree(ptr) \ + do { \ + if(ptr) { \ + (free)(ptr); \ + (ptr) = NULL; \ + } \ + } while(0) + +#endif /* HEADER_CURL_MULTIBYTE_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_rtmp.c b/local-test-curl-full-01/afc-curl/lib/curl_rtmp.c new file mode 100644 index 0000000000000000000000000000000000000000..59fcc4e1ffc61875c1fb852450257d62ff7baa83 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_rtmp.c @@ -0,0 +1,363 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Howard Chu, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_LIBRTMP + +#include "curl_rtmp.h" +#include "urldata.h" +#include "nonblock.h" /* for curlx_nonblock */ +#include "progress.h" /* for Curl_pgrsSetUploadSize */ +#include "transfer.h" +#include "warnless.h" +#include +#include + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(_WIN32) && !defined(USE_LWIPSOCK) +#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e) +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#elif defined(LWIP_SO_SNDRCVTIMEO_NONSTANDARD) +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#else +#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0} +#endif + +#define DEF_BUFTIME (2*60*60*1000) /* 2 hours */ + +static CURLcode rtmp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode rtmp_do(struct Curl_easy *data, bool *done); +static CURLcode rtmp_done(struct Curl_easy *data, CURLcode, bool premature); +static CURLcode rtmp_connect(struct Curl_easy *data, bool *done); +static CURLcode rtmp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead); + +static Curl_recv rtmp_recv; +static Curl_send rtmp_send; + +/* + * RTMP protocol handler.h, based on https://rtmpdump.mplayerhq.hu + */ + +const struct Curl_handler Curl_handler_rtmp = { + "rtmp", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMP, /* defport */ + CURLPROTO_RTMP, /* protocol */ + CURLPROTO_RTMP, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpt = { + "rtmpt", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPT, /* defport */ + CURLPROTO_RTMPT, /* protocol */ + CURLPROTO_RTMPT, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpe = { + "rtmpe", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMP, /* defport */ + CURLPROTO_RTMPE, /* protocol */ + CURLPROTO_RTMPE, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpte = { + "rtmpte", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPT, /* defport */ + CURLPROTO_RTMPTE, /* protocol */ + CURLPROTO_RTMPTE, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmps = { + "rtmps", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPS, /* defport */ + CURLPROTO_RTMPS, /* protocol */ + CURLPROTO_RTMP, /* family */ + PROTOPT_NONE /* flags */ +}; + +const struct Curl_handler Curl_handler_rtmpts = { + "rtmpts", /* scheme */ + rtmp_setup_connection, /* setup_connection */ + rtmp_do, /* do_it */ + rtmp_done, /* done */ + ZERO_NULL, /* do_more */ + rtmp_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + rtmp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_RTMPS, /* defport */ + CURLPROTO_RTMPTS, /* protocol */ + CURLPROTO_RTMPT, /* family */ + PROTOPT_NONE /* flags */ +}; + +static CURLcode rtmp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + RTMP *r = RTMP_Alloc(); + if(!r) + return CURLE_OUT_OF_MEMORY; + + RTMP_Init(r); + RTMP_SetBufferMS(r, DEF_BUFTIME); + if(!RTMP_SetupURL(r, data->state.url)) { + RTMP_Free(r); + return CURLE_URL_MALFORMAT; + } + conn->proto.rtmp = r; + return CURLE_OK; +} + +static CURLcode rtmp_connect(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + SET_RCVTIMEO(tv, 10); + + r->m_sb.sb_socket = (int)conn->sock[FIRSTSOCKET]; + + /* We have to know if it is a write before we send the + * connect request packet + */ + if(data->state.upload) + r->Link.protocol |= RTMP_FEATURE_WRITE; + + /* For plain streams, use the buffer toggle trick to keep data flowing */ + if(!(r->Link.lFlags & RTMP_LF_LIVE) && + !(r->Link.protocol & RTMP_FEATURE_HTTP)) + r->Link.lFlags |= RTMP_LF_BUFX; + + (void)curlx_nonblock(r->m_sb.sb_socket, FALSE); + setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, + (char *)&tv, sizeof(tv)); + + if(!RTMP_Connect1(r, NULL)) + return CURLE_FAILED_INIT; + + /* Clients must send a periodic BytesReceived report to the server */ + r->m_bSendCounter = TRUE; + + *done = TRUE; + conn->recv[FIRSTSOCKET] = rtmp_recv; + conn->send[FIRSTSOCKET] = rtmp_send; + return CURLE_OK; +} + +static CURLcode rtmp_do(struct Curl_easy *data, bool *done) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + + if(!RTMP_ConnectStream(r, 0)) + return CURLE_FAILED_INIT; + + if(data->state.upload) { + Curl_pgrsSetUploadSize(data, data->state.infilesize); + Curl_xfer_setup1(data, CURL_XFER_SEND, -1, FALSE); + } + else + Curl_xfer_setup1(data, CURL_XFER_RECV, -1, FALSE); + *done = TRUE; + return CURLE_OK; +} + +static CURLcode rtmp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + (void)data; /* unused */ + (void)status; /* unused */ + (void)premature; /* unused */ + + return CURLE_OK; +} + +static CURLcode rtmp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + RTMP *r = conn->proto.rtmp; + (void)data; + (void)dead_connection; + if(r) { + conn->proto.rtmp = NULL; + RTMP_Close(r); + RTMP_Free(r); + } + return CURLE_OK; +} + +static ssize_t rtmp_recv(struct Curl_easy *data, int sockindex, char *buf, + size_t len, CURLcode *err) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + ssize_t nread; + + (void)sockindex; /* unused */ + + nread = RTMP_Read(r, buf, curlx_uztosi(len)); + if(nread < 0) { + if(r->m_read.status == RTMP_READ_COMPLETE || + r->m_read.status == RTMP_READ_EOF) { + data->req.size = data->req.bytecount; + nread = 0; + } + else + *err = CURLE_RECV_ERROR; + } + return nread; +} + +static ssize_t rtmp_send(struct Curl_easy *data, int sockindex, + const void *buf, size_t len, bool eos, CURLcode *err) +{ + struct connectdata *conn = data->conn; + RTMP *r = conn->proto.rtmp; + ssize_t num; + + (void)sockindex; /* unused */ + (void)eos; /* unused */ + + num = RTMP_Write(r, (char *)buf, curlx_uztosi(len)); + if(num < 0) + *err = CURLE_SEND_ERROR; + + return num; +} + +void Curl_rtmp_version(char *version, size_t len) +{ + char suff[2]; + if(RTMP_LIB_VERSION & 0xff) { + suff[0] = (RTMP_LIB_VERSION & 0xff) + 'a' - 1; + suff[1] = '\0'; + } + else + suff[0] = '\0'; + + msnprintf(version, len, "librtmp/%d.%d%s", + RTMP_LIB_VERSION >> 16, (RTMP_LIB_VERSION >> 8) & 0xff, + suff); +} + +#endif /* USE_LIBRTMP */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_sasl.c b/local-test-curl-full-01/afc-curl/lib/curl_sasl.c new file mode 100644 index 0000000000000000000000000000000000000000..24f8c8c53c19d9309e5874c3c43b0b9e90496dca --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_sasl.c @@ -0,0 +1,760 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + * RFC2195 CRAM-MD5 authentication + * RFC2617 Basic and Digest Access Authentication + * RFC2831 DIGEST-MD5 authentication + * RFC4422 Simple Authentication and Security Layer (SASL) + * RFC4616 PLAIN authentication + * RFC5802 SCRAM-SHA-1 authentication + * RFC7677 SCRAM-SHA-256 authentication + * RFC6749 OAuth 2.0 Authorization Framework + * RFC7628 A Set of SASL Mechanisms for OAuth + * Draft LOGIN SASL Mechanism + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_POP3) || \ + (!defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)) + +#include +#include "urldata.h" + +#include "curl_base64.h" +#include "curl_md5.h" +#include "vauth/vauth.h" +#include "cfilters.h" +#include "vtls/vtls.h" +#include "curl_hmac.h" +#include "curl_sasl.h" +#include "warnless.h" +#include "strtok.h" +#include "sendf.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Supported mechanisms */ +static const struct { + const char *name; /* Name */ + size_t len; /* Name length */ + unsigned short bit; /* Flag bit */ +} mechtable[] = { + { "LOGIN", 5, SASL_MECH_LOGIN }, + { "PLAIN", 5, SASL_MECH_PLAIN }, + { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, + { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, + { "GSSAPI", 6, SASL_MECH_GSSAPI }, + { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, + { "NTLM", 4, SASL_MECH_NTLM }, + { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, + { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, + { "SCRAM-SHA-1", 11, SASL_MECH_SCRAM_SHA_1 }, + { "SCRAM-SHA-256",13, SASL_MECH_SCRAM_SHA_256 }, + { ZERO_NULL, 0, 0 } +}; + +/* + * Curl_sasl_cleanup() + * + * This is used to cleanup any libraries or curl modules used by the sasl + * functions. + * + * Parameters: + * + * conn [in] - The connection data. + * authused [in] - The authentication mechanism used. + */ +void Curl_sasl_cleanup(struct connectdata *conn, unsigned short authused) +{ + (void)conn; + (void)authused; + +#if defined(USE_KERBEROS5) + /* Cleanup the gssapi structure */ + if(authused == SASL_MECH_GSSAPI) { + Curl_auth_cleanup_gssapi(&conn->krb5); + } +#endif + +#if defined(USE_GSASL) + /* Cleanup the GSASL structure */ + if(authused & (SASL_MECH_SCRAM_SHA_1 | SASL_MECH_SCRAM_SHA_256)) { + Curl_auth_gsasl_cleanup(&conn->gsasl); + } +#endif + +#if defined(USE_NTLM) + /* Cleanup the NTLM structure */ + if(authused == SASL_MECH_NTLM) { + Curl_auth_cleanup_ntlm(&conn->ntlm); + } +#endif +} + +/* + * Curl_sasl_decode_mech() + * + * Convert a SASL mechanism name into a token. + * + * Parameters: + * + * ptr [in] - The mechanism string. + * maxlen [in] - Maximum mechanism string length. + * len [out] - If not NULL, effective name length. + * + * Returns the SASL mechanism token or 0 if no match. + */ +unsigned short Curl_sasl_decode_mech(const char *ptr, size_t maxlen, + size_t *len) +{ + unsigned int i; + char c; + + for(i = 0; mechtable[i].name; i++) { + if(maxlen >= mechtable[i].len && + !memcmp(ptr, mechtable[i].name, mechtable[i].len)) { + if(len) + *len = mechtable[i].len; + + if(maxlen == mechtable[i].len) + return mechtable[i].bit; + + c = ptr[mechtable[i].len]; + if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') + return mechtable[i].bit; + } + } + + return 0; +} + +/* + * Curl_sasl_parse_url_auth_option() + * + * Parse the URL login options. + */ +CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, + const char *value, size_t len) +{ + CURLcode result = CURLE_OK; + size_t mechlen; + + if(!len) + return CURLE_URL_MALFORMAT; + + if(sasl->resetprefs) { + sasl->resetprefs = FALSE; + sasl->prefmech = SASL_AUTH_NONE; + } + + if(!strncmp(value, "*", len)) + sasl->prefmech = SASL_AUTH_DEFAULT; + else { + unsigned short mechbit = Curl_sasl_decode_mech(value, len, &mechlen); + if(mechbit && mechlen == len) + sasl->prefmech |= mechbit; + else + result = CURLE_URL_MALFORMAT; + } + + return result; +} + +/* + * Curl_sasl_init() + * + * Initializes the SASL structure. + */ +void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, + const struct SASLproto *params) +{ + unsigned long auth = data->set.httpauth; + + sasl->params = params; /* Set protocol dependent parameters */ + sasl->state = SASL_STOP; /* Not yet running */ + sasl->curmech = NULL; /* No mechanism yet. */ + sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ + sasl->prefmech = params->defmechs; /* Default preferred mechanisms */ + sasl->authused = SASL_AUTH_NONE; /* The authentication mechanism used */ + sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ + sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ + sasl->force_ir = FALSE; /* Respect external option */ + + if(auth != CURLAUTH_BASIC) { + unsigned short mechs = SASL_AUTH_NONE; + + /* If some usable http authentication options have been set, determine + new defaults from them. */ + if(auth & CURLAUTH_BASIC) + mechs |= SASL_MECH_PLAIN | SASL_MECH_LOGIN; + if(auth & CURLAUTH_DIGEST) + mechs |= SASL_MECH_DIGEST_MD5; + if(auth & CURLAUTH_NTLM) + mechs |= SASL_MECH_NTLM; + if(auth & CURLAUTH_BEARER) + mechs |= SASL_MECH_OAUTHBEARER | SASL_MECH_XOAUTH2; + if(auth & CURLAUTH_GSSAPI) + mechs |= SASL_MECH_GSSAPI; + + if(mechs != SASL_AUTH_NONE) + sasl->prefmech = mechs; + } +} + +/* + * sasl_state() + * + * This is the ONLY way to change SASL state! + */ +static void sasl_state(struct SASL *sasl, struct Curl_easy *data, + saslstate newstate) +{ +#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) + /* for debug purposes */ + static const char * const names[]={ + "STOP", + "PLAIN", + "LOGIN", + "LOGIN_PASSWD", + "EXTERNAL", + "CRAMMD5", + "DIGESTMD5", + "DIGESTMD5_RESP", + "NTLM", + "NTLM_TYPE2MSG", + "GSSAPI", + "GSSAPI_TOKEN", + "GSSAPI_NO_DATA", + "OAUTH2", + "OAUTH2_RESP", + "GSASL", + "CANCEL", + "FINAL", + /* LAST */ + }; + + if(sasl->state != newstate) + infof(data, "SASL %p state change from %s to %s", + (void *)sasl, names[sasl->state], names[newstate]); +#else + (void) data; +#endif + + sasl->state = newstate; +} + +#if defined(USE_NTLM) || defined(USE_GSASL) || defined(USE_KERBEROS5) || \ + !defined(CURL_DISABLE_DIGEST_AUTH) +/* Get the SASL server message and convert it to binary. */ +static CURLcode get_server_message(struct SASL *sasl, struct Curl_easy *data, + struct bufref *out) +{ + CURLcode result = CURLE_OK; + + result = sasl->params->getmessage(data, out); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) { + unsigned char *msg; + size_t msglen; + const char *serverdata = (const char *) Curl_bufref_ptr(out); + + if(!*serverdata || *serverdata == '=') + Curl_bufref_set(out, NULL, 0, NULL); + else { + result = Curl_base64_decode(serverdata, &msg, &msglen); + if(!result) + Curl_bufref_set(out, msg, msglen, curl_free); + } + } + return result; +} +#endif + +/* Encode the outgoing SASL message. */ +static CURLcode build_message(struct SASL *sasl, struct bufref *msg) +{ + CURLcode result = CURLE_OK; + + if(sasl->params->flags & SASL_FLAG_BASE64) { + if(!Curl_bufref_ptr(msg)) /* Empty message. */ + Curl_bufref_set(msg, "", 0, NULL); + else if(!Curl_bufref_len(msg)) /* Explicit empty response. */ + Curl_bufref_set(msg, "=", 1, NULL); + else { + char *base64; + size_t base64len; + + result = Curl_base64_encode((const char *) Curl_bufref_ptr(msg), + Curl_bufref_len(msg), &base64, &base64len); + if(!result) + Curl_bufref_set(msg, base64, base64len, curl_free); + } + } + + return result; +} + +/* + * Curl_sasl_can_authenticate() + * + * Check if we have enough auth data and capabilities to authenticate. + */ +bool Curl_sasl_can_authenticate(struct SASL *sasl, struct Curl_easy *data) +{ + /* Have credentials been provided? */ + if(data->state.aptr.user) + return TRUE; + + /* EXTERNAL can authenticate without a username and/or password */ + if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) + return TRUE; + + return FALSE; +} + +/* + * Curl_sasl_start() + * + * Calculate the required login details for SASL authentication. + */ +CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, + bool force_ir, saslprogress *progress) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + unsigned short enabledmechs; + const char *mech = NULL; + struct bufref resp; + saslstate state1 = SASL_STOP; + saslstate state2 = SASL_FINAL; + const char *hostname, *disp_hostname; + int port; +#if defined(USE_KERBEROS5) || defined(USE_NTLM) + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif + const char *oauth_bearer = data->set.str[STRING_BEARER]; + struct bufref nullmsg; + + Curl_conn_get_host(data, FIRSTSOCKET, &hostname, &disp_hostname, &port); + Curl_bufref_init(&nullmsg); + Curl_bufref_init(&resp); + sasl->force_ir = force_ir; /* Latch for future use */ + sasl->authused = 0; /* No mechanism used yet */ + enabledmechs = sasl->authmechs & sasl->prefmech; + *progress = SASL_IDLE; + + /* Calculate the supported authentication mechanism, by decreasing order of + security, as well as the initial response where appropriate */ + if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) { + mech = SASL_MECH_STRING_EXTERNAL; + state1 = SASL_EXTERNAL; + sasl->authused = SASL_MECH_EXTERNAL; + + if(force_ir || data->set.sasl_ir) + Curl_auth_create_external_message(conn->user, &resp); + } + else if(data->state.aptr.user) { +#if defined(USE_KERBEROS5) + if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() && + Curl_auth_user_contains_domain(conn->user)) { + sasl->mutual_auth = FALSE; + mech = SASL_MECH_STRING_GSSAPI; + state1 = SASL_GSSAPI; + state2 = SASL_GSSAPI_TOKEN; + sasl->authused = SASL_MECH_GSSAPI; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_gssapi_user_message(data, conn->user, + conn->passwd, + service, + conn->host.name, + sasl->mutual_auth, + NULL, &conn->krb5, + &resp); + } + else +#endif +#ifdef USE_GSASL + if((enabledmechs & SASL_MECH_SCRAM_SHA_256) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_256, + &conn->gsasl)) { + mech = SASL_MECH_STRING_SCRAM_SHA_256; + sasl->authused = SASL_MECH_SCRAM_SHA_256; + state1 = SASL_GSASL; + state2 = SASL_GSASL; + + result = Curl_auth_gsasl_start(data, conn->user, + conn->passwd, &conn->gsasl); + if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) + result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); + } + else if((enabledmechs & SASL_MECH_SCRAM_SHA_1) && + Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_1, + &conn->gsasl)) { + mech = SASL_MECH_STRING_SCRAM_SHA_1; + sasl->authused = SASL_MECH_SCRAM_SHA_1; + state1 = SASL_GSASL; + state2 = SASL_GSASL; + + result = Curl_auth_gsasl_start(data, conn->user, + conn->passwd, &conn->gsasl); + if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) + result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); + } + else +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + if((enabledmechs & SASL_MECH_DIGEST_MD5) && + Curl_auth_is_digest_supported()) { + mech = SASL_MECH_STRING_DIGEST_MD5; + state1 = SASL_DIGESTMD5; + sasl->authused = SASL_MECH_DIGEST_MD5; + } + else if(enabledmechs & SASL_MECH_CRAM_MD5) { + mech = SASL_MECH_STRING_CRAM_MD5; + state1 = SASL_CRAMMD5; + sasl->authused = SASL_MECH_CRAM_MD5; + } + else +#endif +#ifdef USE_NTLM + if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) { + mech = SASL_MECH_STRING_NTLM; + state1 = SASL_NTLM; + state2 = SASL_NTLM_TYPE2MSG; + sasl->authused = SASL_MECH_NTLM; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_ntlm_type1_message(data, + conn->user, conn->passwd, + service, + hostname, + &conn->ntlm, &resp); + } + else +#endif + if((enabledmechs & SASL_MECH_OAUTHBEARER) && oauth_bearer) { + mech = SASL_MECH_STRING_OAUTHBEARER; + state1 = SASL_OAUTH2; + state2 = SASL_OAUTH2_RESP; + sasl->authused = SASL_MECH_OAUTHBEARER; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_oauth_bearer_message(conn->user, + hostname, + port, + oauth_bearer, + &resp); + } + else if((enabledmechs & SASL_MECH_XOAUTH2) && oauth_bearer) { + mech = SASL_MECH_STRING_XOAUTH2; + state1 = SASL_OAUTH2; + sasl->authused = SASL_MECH_XOAUTH2; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_xoauth_bearer_message(conn->user, + oauth_bearer, + &resp); + } + else if(enabledmechs & SASL_MECH_PLAIN) { + mech = SASL_MECH_STRING_PLAIN; + state1 = SASL_PLAIN; + sasl->authused = SASL_MECH_PLAIN; + + if(force_ir || data->set.sasl_ir) + result = Curl_auth_create_plain_message(conn->sasl_authzid, + conn->user, conn->passwd, + &resp); + } + else if(enabledmechs & SASL_MECH_LOGIN) { + mech = SASL_MECH_STRING_LOGIN; + state1 = SASL_LOGIN; + state2 = SASL_LOGIN_PASSWD; + sasl->authused = SASL_MECH_LOGIN; + + if(force_ir || data->set.sasl_ir) + Curl_auth_create_login_message(conn->user, &resp); + } + } + + if(!result && mech) { + sasl->curmech = mech; + if(Curl_bufref_ptr(&resp)) + result = build_message(sasl, &resp); + + if(sasl->params->maxirlen && + strlen(mech) + Curl_bufref_len(&resp) > sasl->params->maxirlen) + Curl_bufref_free(&resp); + + if(!result) + result = sasl->params->sendauth(data, mech, &resp); + + if(!result) { + *progress = SASL_INPROGRESS; + sasl_state(sasl, data, Curl_bufref_ptr(&resp) ? state2 : state1); + } + } + + Curl_bufref_free(&resp); + return result; +} + +/* + * Curl_sasl_continue() + * + * Continue the authentication. + */ +CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, + int code, saslprogress *progress) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + saslstate newstate = SASL_FINAL; + struct bufref resp; + const char *hostname, *disp_hostname; + int port; +#if defined(USE_KERBEROS5) || defined(USE_NTLM) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + sasl->params->service; +#endif + const char *oauth_bearer = data->set.str[STRING_BEARER]; + struct bufref serverdata; + + Curl_conn_get_host(data, FIRSTSOCKET, &hostname, &disp_hostname, &port); + Curl_bufref_init(&serverdata); + Curl_bufref_init(&resp); + *progress = SASL_INPROGRESS; + + if(sasl->state == SASL_FINAL) { + if(code != sasl->params->finalcode) + result = CURLE_LOGIN_DENIED; + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + + if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && + code != sasl->params->contcode) { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + switch(sasl->state) { + case SASL_STOP: + *progress = SASL_DONE; + return result; + case SASL_PLAIN: + result = Curl_auth_create_plain_message(conn->sasl_authzid, + conn->user, conn->passwd, &resp); + break; + case SASL_LOGIN: + Curl_auth_create_login_message(conn->user, &resp); + newstate = SASL_LOGIN_PASSWD; + break; + case SASL_LOGIN_PASSWD: + Curl_auth_create_login_message(conn->passwd, &resp); + break; + case SASL_EXTERNAL: + Curl_auth_create_external_message(conn->user, &resp); + break; +#ifdef USE_GSASL + case SASL_GSASL: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_gsasl_token(data, &serverdata, &conn->gsasl, &resp); + if(!result && Curl_bufref_len(&resp) > 0) + newstate = SASL_GSASL; + break; +#endif +#ifndef CURL_DISABLE_DIGEST_AUTH + case SASL_CRAMMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_cram_md5_message(&serverdata, conn->user, + conn->passwd, &resp); + break; + case SASL_DIGESTMD5: + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_digest_md5_message(data, &serverdata, + conn->user, conn->passwd, + service, &resp); + if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) + newstate = SASL_DIGESTMD5_RESP; + break; + case SASL_DIGESTMD5_RESP: + /* Keep response NULL to output an empty line. */ + break; +#endif + +#ifdef USE_NTLM + case SASL_NTLM: + /* Create the type-1 message */ + result = Curl_auth_create_ntlm_type1_message(data, + conn->user, conn->passwd, + service, hostname, + &conn->ntlm, &resp); + newstate = SASL_NTLM_TYPE2MSG; + break; + case SASL_NTLM_TYPE2MSG: + /* Decode the type-2 message */ + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_decode_ntlm_type2_message(data, &serverdata, + &conn->ntlm); + if(!result) + result = Curl_auth_create_ntlm_type3_message(data, conn->user, + conn->passwd, &conn->ntlm, + &resp); + break; +#endif + +#if defined(USE_KERBEROS5) + case SASL_GSSAPI: + result = Curl_auth_create_gssapi_user_message(data, conn->user, + conn->passwd, + service, + conn->host.name, + sasl->mutual_auth, NULL, + &conn->krb5, + &resp); + newstate = SASL_GSSAPI_TOKEN; + break; + case SASL_GSSAPI_TOKEN: + result = get_server_message(sasl, data, &serverdata); + if(!result) { + if(sasl->mutual_auth) { + /* Decode the user token challenge and create the optional response + message */ + result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, + NULL, NULL, + sasl->mutual_auth, + &serverdata, + &conn->krb5, + &resp); + newstate = SASL_GSSAPI_NO_DATA; + } + else + /* Decode the security challenge and create the response message */ + result = Curl_auth_create_gssapi_security_message(data, + conn->sasl_authzid, + &serverdata, + &conn->krb5, + &resp); + } + break; + case SASL_GSSAPI_NO_DATA: + /* Decode the security challenge and create the response message */ + result = get_server_message(sasl, data, &serverdata); + if(!result) + result = Curl_auth_create_gssapi_security_message(data, + conn->sasl_authzid, + &serverdata, + &conn->krb5, + &resp); + break; +#endif + + case SASL_OAUTH2: + /* Create the authorization message */ + if(sasl->authused == SASL_MECH_OAUTHBEARER) { + result = Curl_auth_create_oauth_bearer_message(conn->user, + hostname, + port, + oauth_bearer, + &resp); + + /* Failures maybe sent by the server as continuations for OAUTHBEARER */ + newstate = SASL_OAUTH2_RESP; + } + else + result = Curl_auth_create_xoauth_bearer_message(conn->user, + oauth_bearer, + &resp); + break; + + case SASL_OAUTH2_RESP: + /* The continuation is optional so check the response code */ + if(code == sasl->params->finalcode) { + /* Final response was received so we are done */ + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return result; + } + else if(code == sasl->params->contcode) { + /* Acknowledge the continuation by sending a 0x01 response. */ + Curl_bufref_set(&resp, "\x01", 1, NULL); + break; + } + else { + *progress = SASL_DONE; + sasl_state(sasl, data, SASL_STOP); + return CURLE_LOGIN_DENIED; + } + + case SASL_CANCEL: + /* Remove the offending mechanism from the supported list */ + sasl->authmechs ^= sasl->authused; + + /* Start an alternative SASL authentication */ + return Curl_sasl_start(sasl, data, sasl->force_ir, progress); + default: + failf(data, "Unsupported SASL authentication mechanism"); + result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ + break; + } + + Curl_bufref_free(&serverdata); + + switch(result) { + case CURLE_BAD_CONTENT_ENCODING: + /* Cancel dialog */ + result = sasl->params->cancelauth(data, sasl->curmech); + newstate = SASL_CANCEL; + break; + case CURLE_OK: + result = build_message(sasl, &resp); + if(!result) + result = sasl->params->contauth(data, sasl->curmech, &resp); + break; + default: + newstate = SASL_STOP; /* Stop on error */ + *progress = SASL_DONE; + break; + } + + Curl_bufref_free(&resp); + + sasl_state(sasl, data, newstate); + + return result; +} +#endif /* protocols are enabled that use SASL */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_sspi.h b/local-test-curl-full-01/afc-curl/lib/curl_sspi.h new file mode 100644 index 0000000000000000000000000000000000000000..535a1ff650a53186df6e63340e675a18f0688044 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_sspi.h @@ -0,0 +1,123 @@ +#ifndef HEADER_CURL_SSPI_H +#define HEADER_CURL_SSPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_WINDOWS_SSPI + +#include + +/* + * When including the following three headers, it is mandatory to define either + * SECURITY_WIN32 or SECURITY_KERNEL, indicating who is compiling the code. + */ + +#undef SECURITY_WIN32 +#undef SECURITY_KERNEL +#define SECURITY_WIN32 1 +#include +#include +#include + +CURLcode Curl_sspi_global_init(void); +void Curl_sspi_global_cleanup(void); + +/* This is used to populate the domain in a SSPI identity structure */ +CURLcode Curl_override_sspi_http_realm(const char *chlg, + SEC_WINNT_AUTH_IDENTITY *identity); + +/* This is used to generate an SSPI identity structure */ +CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp, + SEC_WINNT_AUTH_IDENTITY *identity); + +/* This is used to free an SSPI identity structure */ +void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity); + +/* Forward-declaration of global variables defined in curl_sspi.c */ +extern HMODULE Curl_hSecDll; +extern PSecurityFunctionTable Curl_pSecFn; + +/* Provide some definitions missing in old headers */ +#define SP_NAME_DIGEST "WDigest" +#define SP_NAME_NTLM "NTLM" +#define SP_NAME_NEGOTIATE "Negotiate" +#define SP_NAME_KERBEROS "Kerberos" + +#ifndef ISC_REQ_USE_HTTP_STYLE +#define ISC_REQ_USE_HTTP_STYLE 0x01000000 +#endif + +#ifndef SEC_E_INVALID_PARAMETER +# define SEC_E_INVALID_PARAMETER ((HRESULT)0x8009035DL) +#endif +#ifndef SEC_E_DELEGATION_POLICY +# define SEC_E_DELEGATION_POLICY ((HRESULT)0x8009035EL) +#endif +#ifndef SEC_E_POLICY_NLTM_ONLY +# define SEC_E_POLICY_NLTM_ONLY ((HRESULT)0x8009035FL) +#endif + +#ifndef SEC_I_SIGNATURE_NEEDED +# define SEC_I_SIGNATURE_NEEDED ((HRESULT)0x0009035CL) +#endif + +#ifndef CRYPT_E_REVOKED +# define CRYPT_E_REVOKED ((HRESULT)0x80092010L) +#endif + +#ifndef CRYPT_E_NO_REVOCATION_DLL +# define CRYPT_E_NO_REVOCATION_DLL ((HRESULT)0x80092011L) +#endif + +#ifndef CRYPT_E_NO_REVOCATION_CHECK +# define CRYPT_E_NO_REVOCATION_CHECK ((HRESULT)0x80092012L) +#endif + +#ifndef CRYPT_E_REVOCATION_OFFLINE +# define CRYPT_E_REVOCATION_OFFLINE ((HRESULT)0x80092013L) +#endif + +#ifndef CRYPT_E_NOT_IN_REVOCATION_DATABASE +# define CRYPT_E_NOT_IN_REVOCATION_DATABASE ((HRESULT)0x80092014L) +#endif + +#ifdef UNICODE +# define SECFLAG_WINNT_AUTH_IDENTITY \ + (unsigned long)SEC_WINNT_AUTH_IDENTITY_UNICODE +#else +# define SECFLAG_WINNT_AUTH_IDENTITY \ + (unsigned long)SEC_WINNT_AUTH_IDENTITY_ANSI +#endif + +/* + * Definitions required from ntsecapi.h are directly provided below this point + * to avoid including ntsecapi.h due to a conflict with OpenSSL's safestack.h + */ +#define KERB_WRAP_NO_ENCRYPT 0x80000001 + +#endif /* USE_WINDOWS_SSPI */ + +#endif /* HEADER_CURL_SSPI_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_threads.c b/local-test-curl-full-01/afc-curl/lib/curl_threads.c new file mode 100644 index 0000000000000000000000000000000000000000..fbbbf9b2d3214980deccff8e92eee8d2b171ec37 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_threads.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 + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#if defined(USE_THREADS_POSIX) +# ifdef HAVE_PTHREAD_H +# include +# endif +#elif defined(USE_THREADS_WIN32) +# include +#endif + +#include "curl_threads.h" +#ifdef BUILDING_LIBCURL +#include "curl_memory.h" +#endif +/* The last #include file should be: */ +#include "memdebug.h" + +#if defined(USE_THREADS_POSIX) + +struct Curl_actual_call { + unsigned int (*func)(void *); + void *arg; +}; + +static void *curl_thread_create_thunk(void *arg) +{ + struct Curl_actual_call *ac = arg; + unsigned int (*func)(void *) = ac->func; + void *real_arg = ac->arg; + + free(ac); + + (*func)(real_arg); + + return 0; +} + +curl_thread_t Curl_thread_create(unsigned int (*func) (void *), void *arg) +{ + curl_thread_t t = malloc(sizeof(pthread_t)); + struct Curl_actual_call *ac = malloc(sizeof(struct Curl_actual_call)); + if(!(ac && t)) + goto err; + + ac->func = func; + ac->arg = arg; + + if(pthread_create(t, NULL, curl_thread_create_thunk, ac) != 0) + goto err; + + return t; + +err: + free(t); + free(ac); + return curl_thread_t_null; +} + +void Curl_thread_destroy(curl_thread_t hnd) +{ + if(hnd != curl_thread_t_null) { + pthread_detach(*hnd); + free(hnd); + } +} + +int Curl_thread_join(curl_thread_t *hnd) +{ + int ret = (pthread_join(**hnd, NULL) == 0); + + free(*hnd); + *hnd = curl_thread_t_null; + + return ret; +} + +#elif defined(USE_THREADS_WIN32) + +curl_thread_t Curl_thread_create( +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) + DWORD +#else + unsigned int +#endif + (CURL_STDCALL *func) (void *), + void *arg) +{ +#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 + curl_thread_t t; + curl_win_thread_handle_t thread_handle; +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) + thread_handle = CreateThread(NULL, 0, func, arg, 0, NULL); +#else + thread_handle = _beginthreadex(NULL, 0, func, arg, 0, NULL); +#endif + t = (curl_thread_t)thread_handle; + if((t == 0) || (t == LongToHandle(-1L))) { +#ifdef _WIN32_WCE + DWORD gle = GetLastError(); + errno = ((gle == ERROR_ACCESS_DENIED || + gle == ERROR_NOT_ENOUGH_MEMORY) ? + EACCES : EINVAL); +#endif + return curl_thread_t_null; + } + return t; +} + +void Curl_thread_destroy(curl_thread_t hnd) +{ + if(hnd != curl_thread_t_null) + CloseHandle(hnd); +} + +int Curl_thread_join(curl_thread_t *hnd) +{ +#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ + (_WIN32_WINNT < _WIN32_WINNT_VISTA) + int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0); +#else + int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0); +#endif + + Curl_thread_destroy(*hnd); + + *hnd = curl_thread_t_null; + + return ret; +} + +#endif /* USE_THREADS_* */ diff --git a/local-test-curl-full-01/afc-curl/lib/curl_threads.h b/local-test-curl-full-01/afc-curl/lib/curl_threads.h new file mode 100644 index 0000000000000000000000000000000000000000..c9f18a4e09e12ac534b5917299e98c27848def1e --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curl_threads.h @@ -0,0 +1,70 @@ +#ifndef HEADER_CURL_THREADS_H +#define HEADER_CURL_THREADS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_THREADS_POSIX) +# define CURL_STDCALL +# define curl_mutex_t pthread_mutex_t +# define curl_thread_t pthread_t * +# define curl_thread_t_null (pthread_t *)0 +# define Curl_mutex_init(m) pthread_mutex_init(m, NULL) +# define Curl_mutex_acquire(m) pthread_mutex_lock(m) +# define Curl_mutex_release(m) pthread_mutex_unlock(m) +# define Curl_mutex_destroy(m) pthread_mutex_destroy(m) +#elif defined(USE_THREADS_WIN32) +# define CURL_STDCALL __stdcall +# define curl_mutex_t CRITICAL_SECTION +# define curl_thread_t HANDLE +# define curl_thread_t_null (HANDLE)0 +# if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ + (_WIN32_WINNT < _WIN32_WINNT_VISTA) +# define Curl_mutex_init(m) InitializeCriticalSection(m) +# else +# define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) +# endif +# define Curl_mutex_acquire(m) EnterCriticalSection(m) +# define Curl_mutex_release(m) LeaveCriticalSection(m) +# define Curl_mutex_destroy(m) DeleteCriticalSection(m) +#endif + +#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) + +curl_thread_t Curl_thread_create( +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) + DWORD +#else + unsigned int +#endif + (CURL_STDCALL *func) (void *), + void *arg); + +void Curl_thread_destroy(curl_thread_t hnd); + +int Curl_thread_join(curl_thread_t *hnd); + +#endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ + +#endif /* HEADER_CURL_THREADS_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/curlx.h b/local-test-curl-full-01/afc-curl/lib/curlx.h new file mode 100644 index 0000000000000000000000000000000000000000..f0e4e6470b188fec8838e506dea285cfdf107717 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/curlx.h @@ -0,0 +1,69 @@ +#ifndef HEADER_CURL_CURLX_H +#define HEADER_CURL_CURLX_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Defines protos and includes all header files that provide the curlx_* + * functions. The curlx_* functions are not part of the libcurl API, but are + * stand-alone functions whose sources can be built and linked by apps if need + * be. + */ + +/* map standard printf functions to curl implementations */ +#include "curl_printf.h" + +#include "strcase.h" +/* "strcase.h" provides the strcasecompare protos */ + +#include "strtoofft.h" +/* "strtoofft.h" provides this function: curlx_strtoofft(), returns a + curl_off_t number from a given string. +*/ + +#include "nonblock.h" +/* "nonblock.h" provides curlx_nonblock() */ + +#include "warnless.h" +/* "warnless.h" provides functions: + + curlx_ultous() + curlx_ultouc() + curlx_uztosi() +*/ + +#include "curl_multibyte.h" +/* "curl_multibyte.h" provides these functions and macros: + + curlx_convert_UTF8_to_wchar() + curlx_convert_wchar_to_UTF8() + curlx_convert_UTF8_to_tchar() + curlx_convert_tchar_to_UTF8() + curlx_unicodefree() +*/ + +#include "version_win32.h" +/* "version_win32.h" provides curlx_verify_windows_version() */ + +#endif /* HEADER_CURL_CURLX_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/cw-out.c b/local-test-curl-full-01/afc-curl/lib/cw-out.c new file mode 100644 index 0000000000000000000000000000000000000000..4d3df0a650a0b7106cd84feb714cfa9a2bdedda7 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/cw-out.c @@ -0,0 +1,473 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "urldata.h" +#include "cfilters.h" +#include "headers.h" +#include "multiif.h" +#include "sendf.h" +#include "cw-out.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +/** + * OVERALL DESIGN of this client writer + * + * The 'cw-out' writer is supposed to be the last writer in a transfer's + * stack. It is always added when that stack is initialized. Its purpose + * is to pass BODY and HEADER bytes to the client-installed callback + * functions. + * + * These callback may return `CURL_WRITEFUNC_PAUSE` to indicate that the + * data had not been written and the whole transfer should stop receiving + * new data. Or at least, stop calling the functions. When the transfer + * is "unpaused" by the client, the previous data shall be passed as + * if nothing happened. + * + * The `cw-out` writer therefore manages buffers for bytes that could + * not be written. Data that was already in flight from the server also + * needs buffering on paused transfer when it arrives. + * + * In addition, the writer allows buffering of "small" body writes, + * so client functions are called less often. That is only enabled on a + * number of conditions. + * + * HEADER and BODY data may arrive in any order. For paused transfers, + * a list of `struct cw_out_buf` is kept for `cw_out_type` types. The + * list may be: [BODY]->[HEADER]->[BODY]->[HEADER].... + * When unpausing, this list is "played back" to the client callbacks. + * + * The amount of bytes being buffered is limited by `DYN_PAUSE_BUFFER` + * and when that is exceeded `CURLE_TOO_LARGE` is returned as error. + */ +typedef enum { + CW_OUT_NONE, + CW_OUT_BODY, + CW_OUT_HDS +} cw_out_type; + +struct cw_out_buf { + struct cw_out_buf *next; + struct dynbuf b; + cw_out_type type; +}; + +static struct cw_out_buf *cw_out_buf_create(cw_out_type otype) +{ + struct cw_out_buf *cwbuf = calloc(1, sizeof(*cwbuf)); + if(cwbuf) { + cwbuf->type = otype; + Curl_dyn_init(&cwbuf->b, DYN_PAUSE_BUFFER); + } + return cwbuf; +} + +static void cw_out_buf_free(struct cw_out_buf *cwbuf) +{ + if(cwbuf) { + Curl_dyn_free(&cwbuf->b); + free(cwbuf); + } +} + +struct cw_out_ctx { + struct Curl_cwriter super; + struct cw_out_buf *buf; + BIT(paused); + BIT(errored); +}; + +static CURLcode cw_out_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); +static void cw_out_close(struct Curl_easy *data, struct Curl_cwriter *writer); +static CURLcode cw_out_init(struct Curl_easy *data, + struct Curl_cwriter *writer); + +struct Curl_cwtype Curl_cwt_out = { + "cw-out", + NULL, + cw_out_init, + cw_out_write, + cw_out_close, + sizeof(struct cw_out_ctx) +}; + +static CURLcode cw_out_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + (void)data; + ctx->buf = NULL; + return CURLE_OK; +} + +static void cw_out_bufs_free(struct cw_out_ctx *ctx) +{ + while(ctx->buf) { + struct cw_out_buf *next = ctx->buf->next; + cw_out_buf_free(ctx->buf); + ctx->buf = next; + } +} + +static size_t cw_out_bufs_len(struct cw_out_ctx *ctx) +{ + struct cw_out_buf *cwbuf = ctx->buf; + size_t len = 0; + while(cwbuf) { + len += Curl_dyn_len(&cwbuf->b); + cwbuf = cwbuf->next; + } + return len; +} + +static void cw_out_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct cw_out_ctx *ctx = writer->ctx; + + (void)data; + cw_out_bufs_free(ctx); +} + +/** + * Return the current curl_write_callback and user_data for the buf type + */ +static void cw_get_writefunc(struct Curl_easy *data, cw_out_type otype, + curl_write_callback *pwcb, void **pwcb_data, + size_t *pmax_write, size_t *pmin_write) +{ + switch(otype) { + case CW_OUT_BODY: + *pwcb = data->set.fwrite_func; + *pwcb_data = data->set.out; + *pmax_write = CURL_MAX_WRITE_SIZE; + /* if we ever want buffering of BODY output, we can set `min_write` + * the preferred size. The default should always be to pass data + * to the client as it comes without delay */ + *pmin_write = 0; + break; + case CW_OUT_HDS: + *pwcb = data->set.fwrite_header ? data->set.fwrite_header : + (data->set.writeheader ? data->set.fwrite_func : NULL); + *pwcb_data = data->set.writeheader; + *pmax_write = 0; /* do not chunk-write headers, write them as they are */ + *pmin_write = 0; + break; + default: + *pwcb = NULL; + *pwcb_data = NULL; + *pmax_write = CURL_MAX_WRITE_SIZE; + *pmin_write = 0; + } +} + +static CURLcode cw_out_ptr_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen, + size_t *pconsumed) +{ + curl_write_callback wcb; + void *wcb_data; + size_t max_write, min_write; + size_t wlen, nwritten; + + /* If we errored once, we do not invoke the client callback again */ + if(ctx->errored) + return CURLE_WRITE_ERROR; + + /* write callbacks may get NULLed by the client between calls. */ + cw_get_writefunc(data, otype, &wcb, &wcb_data, &max_write, &min_write); + if(!wcb) { + *pconsumed = blen; + return CURLE_OK; + } + + *pconsumed = 0; + while(blen && !ctx->paused) { + if(!flush_all && blen < min_write) + break; + wlen = max_write ? CURLMIN(blen, max_write) : blen; + Curl_set_in_callback(data, TRUE); + nwritten = wcb((char *)buf, 1, wlen, wcb_data); + Curl_set_in_callback(data, FALSE); + CURL_TRC_WRITE(data, "cw_out, wrote %zu %s bytes -> %zu", + wlen, (otype == CW_OUT_BODY) ? "body" : "header", + nwritten); + if(CURL_WRITEFUNC_PAUSE == nwritten) { + if(data->conn && data->conn->handler->flags & PROTOPT_NONETWORK) { + /* Protocols that work without network cannot be paused. This is + actually only FILE:// just now, and it cannot pause since the + transfer is not done using the "normal" procedure. */ + failf(data, "Write callback asked for PAUSE when not supported"); + return CURLE_WRITE_ERROR; + } + /* mark the connection as RECV paused */ + data->req.keepon |= KEEP_RECV_PAUSE; + ctx->paused = TRUE; + CURL_TRC_WRITE(data, "cw_out, PAUSE requested by client"); + break; + } + else if(CURL_WRITEFUNC_ERROR == nwritten) { + failf(data, "client returned ERROR on write of %zu bytes", wlen); + return CURLE_WRITE_ERROR; + } + else if(nwritten != wlen) { + failf(data, "Failure writing output to destination, " + "passed %zu returned %zd", wlen, nwritten); + return CURLE_WRITE_ERROR; + } + *pconsumed += nwritten; + blen -= nwritten; + buf += nwritten; + } + return CURLE_OK; +} + +static CURLcode cw_out_buf_flush(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf *cwbuf, + bool flush_all) +{ + CURLcode result = CURLE_OK; + + if(Curl_dyn_len(&cwbuf->b)) { + size_t consumed; + + result = cw_out_ptr_flush(ctx, data, cwbuf->type, flush_all, + Curl_dyn_ptr(&cwbuf->b), + Curl_dyn_len(&cwbuf->b), + &consumed); + if(result) + return result; + + if(consumed) { + if(consumed == Curl_dyn_len(&cwbuf->b)) { + Curl_dyn_free(&cwbuf->b); + } + else { + DEBUGASSERT(consumed < Curl_dyn_len(&cwbuf->b)); + result = Curl_dyn_tail(&cwbuf->b, Curl_dyn_len(&cwbuf->b) - consumed); + if(result) + return result; + } + } + } + return result; +} + +static CURLcode cw_out_flush_chain(struct cw_out_ctx *ctx, + struct Curl_easy *data, + struct cw_out_buf **pcwbuf, + bool flush_all) +{ + struct cw_out_buf *cwbuf = *pcwbuf; + CURLcode result; + + if(!cwbuf) + return CURLE_OK; + if(ctx->paused) + return CURLE_OK; + + /* write the end of the chain until it blocks or gets empty */ + while(cwbuf->next) { + struct cw_out_buf **plast = &cwbuf->next; + while((*plast)->next) + plast = &(*plast)->next; + result = cw_out_flush_chain(ctx, data, plast, flush_all); + if(result) + return result; + if(*plast) { + /* could not write last, paused again? */ + DEBUGASSERT(ctx->paused); + return CURLE_OK; + } + } + + result = cw_out_buf_flush(ctx, data, cwbuf, flush_all); + if(result) + return result; + if(!Curl_dyn_len(&cwbuf->b)) { + cw_out_buf_free(cwbuf); + *pcwbuf = NULL; + } + return CURLE_OK; +} + +static CURLcode cw_out_append(struct cw_out_ctx *ctx, + cw_out_type otype, + const char *buf, size_t blen) +{ + if(cw_out_bufs_len(ctx) + blen > DYN_PAUSE_BUFFER) + return CURLE_TOO_LARGE; + + /* if we do not have a buffer, or it is of another type, make a new one. + * And for CW_OUT_HDS always make a new one, so we "replay" headers + * exactly as they came in */ + if(!ctx->buf || (ctx->buf->type != otype) || (otype == CW_OUT_HDS)) { + struct cw_out_buf *cwbuf = cw_out_buf_create(otype); + if(!cwbuf) + return CURLE_OUT_OF_MEMORY; + cwbuf->next = ctx->buf; + ctx->buf = cwbuf; + } + DEBUGASSERT(ctx->buf && (ctx->buf->type == otype)); + return Curl_dyn_addn(&ctx->buf->b, buf, blen); +} + +static CURLcode cw_out_do_write(struct cw_out_ctx *ctx, + struct Curl_easy *data, + cw_out_type otype, + bool flush_all, + const char *buf, size_t blen) +{ + CURLcode result = CURLE_OK; + + /* if we have buffered data and it is a different type than what + * we are writing now, try to flush all */ + if(ctx->buf && ctx->buf->type != otype) { + result = cw_out_flush_chain(ctx, data, &ctx->buf, TRUE); + if(result) + goto out; + } + + if(ctx->buf) { + /* still have buffered data, append and flush */ + result = cw_out_append(ctx, otype, buf, blen); + if(result) + return result; + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) + goto out; + } + else { + /* nothing buffered, try direct write */ + size_t consumed; + result = cw_out_ptr_flush(ctx, data, otype, flush_all, + buf, blen, &consumed); + if(result) + return result; + if(consumed < blen) { + /* did not write all, append the rest */ + result = cw_out_append(ctx, otype, buf + consumed, blen - consumed); + if(result) + goto out; + } + } + +out: + if(result) { + /* We do not want to invoked client callbacks a second time after + * encountering an error. See issue #13337 */ + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + } + return result; +} + +static CURLcode cw_out_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t blen) +{ + struct cw_out_ctx *ctx = writer->ctx; + CURLcode result; + bool flush_all = !!(type & CLIENTWRITE_EOS); + + if((type & CLIENTWRITE_BODY) || + ((type & CLIENTWRITE_HEADER) && data->set.include_header)) { + result = cw_out_do_write(ctx, data, CW_OUT_BODY, flush_all, buf, blen); + if(result) + return result; + } + + if(type & (CLIENTWRITE_HEADER|CLIENTWRITE_INFO)) { + result = cw_out_do_write(ctx, data, CW_OUT_HDS, flush_all, buf, blen); + if(result) + return result; + } + + return CURLE_OK; +} + +bool Curl_cw_out_is_paused(struct Curl_easy *data) +{ + struct Curl_cwriter *cw_out; + struct cw_out_ctx *ctx; + + cw_out = Curl_cwriter_get_by_type(data, &Curl_cwt_out); + if(!cw_out) + return FALSE; + + ctx = (struct cw_out_ctx *)cw_out; + CURL_TRC_WRITE(data, "cw-out is%spaused", ctx->paused ? "" : " not"); + return ctx->paused; +} + +static CURLcode cw_out_flush(struct Curl_easy *data, + bool unpause, bool flush_all) +{ + struct Curl_cwriter *cw_out; + CURLcode result = CURLE_OK; + + cw_out = Curl_cwriter_get_by_type(data, &Curl_cwt_out); + if(cw_out) { + struct cw_out_ctx *ctx = (struct cw_out_ctx *)cw_out; + if(ctx->errored) + return CURLE_WRITE_ERROR; + if(unpause && ctx->paused) + ctx->paused = FALSE; + if(ctx->paused) + return CURLE_OK; /* not doing it */ + + result = cw_out_flush_chain(ctx, data, &ctx->buf, flush_all); + if(result) { + ctx->errored = TRUE; + cw_out_bufs_free(ctx); + return result; + } + } + return result; +} + +CURLcode Curl_cw_out_unpause(struct Curl_easy *data) +{ + CURL_TRC_WRITE(data, "cw-out unpause"); + return cw_out_flush(data, TRUE, FALSE); +} + +CURLcode Curl_cw_out_done(struct Curl_easy *data) +{ + CURL_TRC_WRITE(data, "cw-out done"); + return cw_out_flush(data, FALSE, TRUE); +} diff --git a/local-test-curl-full-01/afc-curl/lib/dict.h b/local-test-curl-full-01/afc-curl/lib/dict.h new file mode 100644 index 0000000000000000000000000000000000000000..ba9a92719ba87a99904bed485a5c14e8c81468c1 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/dict.h @@ -0,0 +1,31 @@ +#ifndef HEADER_CURL_DICT_H +#define HEADER_CURL_DICT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_DICT +extern const struct Curl_handler Curl_handler_dict; +#endif + +#endif /* HEADER_CURL_DICT_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/dllmain.c b/local-test-curl-full-01/afc-curl/lib/dllmain.c new file mode 100644 index 0000000000000000000000000000000000000000..41e97b37eb5e26e70c870517ea91df9aa6cf0c22 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/dllmain.c @@ -0,0 +1,81 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_OPENSSL +#include +#endif + +/* The fourth-to-last include */ +#ifdef __CYGWIN__ +#define WIN32_LEAN_AND_MEAN +#include +#ifdef _WIN32 +#undef _WIN32 +#endif +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* DllMain() must only be defined for Windows and Cygwin DLL builds. */ +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(CURL_STATICLIB) + +#if defined(USE_OPENSSL) && \ + !defined(OPENSSL_IS_AWSLC) && \ + !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(LIBRESSL_VERSION_NUMBER) && \ + (OPENSSL_VERSION_NUMBER >= 0x10100000L) +#define PREVENT_OPENSSL_MEMLEAK +#endif + +#ifdef PREVENT_OPENSSL_MEMLEAK +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved); +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +{ + (void)hinstDLL; + (void)lpvReserved; + + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + break; + case DLL_PROCESS_DETACH: + break; + case DLL_THREAD_ATTACH: + break; + case DLL_THREAD_DETACH: + /* Call OPENSSL_thread_stop to prevent a memory leak in case OpenSSL is + linked statically. + https://github.com/curl/curl/issues/12327#issuecomment-1826405944 */ + OPENSSL_thread_stop(); + break; + } + return TRUE; +} +#endif /* OpenSSL */ + +#endif /* DLL build */ diff --git a/local-test-curl-full-01/afc-curl/lib/doh.h b/local-test-curl-full-01/afc-curl/lib/doh.h new file mode 100644 index 0000000000000000000000000000000000000000..aae32a65409fe4d32c2fc42054061d84b6bfe649 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/doh.h @@ -0,0 +1,189 @@ +#ifndef HEADER_CURL_DOH_H +#define HEADER_CURL_DOH_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "urldata.h" +#include "curl_addrinfo.h" +#ifdef USE_HTTPSRR +# include +#endif + +#ifndef CURL_DISABLE_DOH + +typedef enum { + DOH_OK, + DOH_DNS_BAD_LABEL, /* 1 */ + DOH_DNS_OUT_OF_RANGE, /* 2 */ + DOH_DNS_LABEL_LOOP, /* 3 */ + DOH_TOO_SMALL_BUFFER, /* 4 */ + DOH_OUT_OF_MEM, /* 5 */ + DOH_DNS_RDATA_LEN, /* 6 */ + DOH_DNS_MALFORMAT, /* 7 */ + DOH_DNS_BAD_RCODE, /* 8 - no such name */ + DOH_DNS_UNEXPECTED_TYPE, /* 9 */ + DOH_DNS_UNEXPECTED_CLASS, /* 10 */ + DOH_NO_CONTENT, /* 11 */ + DOH_DNS_BAD_ID, /* 12 */ + DOH_DNS_NAME_TOO_LONG /* 13 */ +} DOHcode; + +typedef enum { + DNS_TYPE_A = 1, + DNS_TYPE_NS = 2, + DNS_TYPE_CNAME = 5, + DNS_TYPE_AAAA = 28, + DNS_TYPE_DNAME = 39, /* RFC6672 */ + DNS_TYPE_HTTPS = 65 +} DNStype; + +/* one of these for each DoH request */ +struct doh_probe { + curl_off_t easy_mid; /* multi id of easy handle doing the lookup */ + DNStype dnstype; + unsigned char req_body[512]; + size_t req_body_len; + struct dynbuf resp_body; +}; + +enum doh_slot_num { + /* Explicit values for first two symbols so as to match hard-coded + * constants in existing code + */ + DOH_SLOT_IPV4 = 0, /* make 'V4' stand out for readability */ + DOH_SLOT_IPV6 = 1, /* 'V6' likewise */ + + /* Space here for (possibly build-specific) additional slot definitions */ +#ifdef USE_HTTPSRR + DOH_SLOT_HTTPS_RR = 2, /* for HTTPS RR */ +#endif + + /* for example */ + /* #ifdef WANT_DOH_FOOBAR_TXT */ + /* DOH_PROBE_SLOT_FOOBAR_TXT, */ + /* #endif */ + + /* AFTER all slot definitions, establish how many we have */ + DOH_SLOT_COUNT +}; + +struct doh_probes { + struct curl_slist *req_hds; + struct doh_probe probe[DOH_SLOT_COUNT]; + unsigned int pending; /* still outstanding probes */ + int port; + const char *host; +}; + +/* + * Curl_doh() resolve a name using DoH (DNS-over-HTTPS). It resolves a name + * and returns a 'Curl_addrinfo *' with the address information. + */ + +struct Curl_addrinfo *Curl_doh(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + +CURLcode Curl_doh_is_resolved(struct Curl_easy *data, + struct Curl_dns_entry **dns); + +#define DOH_MAX_ADDR 24 +#define DOH_MAX_CNAME 4 +#define DOH_MAX_HTTPS 4 + +struct dohaddr { + int type; + union { + unsigned char v4[4]; /* network byte order */ + unsigned char v6[16]; + } ip; +}; + +#ifdef USE_HTTPSRR + +/* + * These are the code points for DNS wire format SvcParams as + * per draft-ietf-dnsop-svcb-https + * Not all are supported now, and even those that are may need + * more work in future to fully support the spec. + */ +#define HTTPS_RR_CODE_ALPN 0x01 +#define HTTPS_RR_CODE_NO_DEF_ALPN 0x02 +#define HTTPS_RR_CODE_PORT 0x03 +#define HTTPS_RR_CODE_IPV4 0x04 +#define HTTPS_RR_CODE_ECH 0x05 +#define HTTPS_RR_CODE_IPV6 0x06 + +/* + * These may need escaping when found within an ALPN string + * value. + */ +#define COMMA_CHAR ',' +#define BACKSLASH_CHAR '\\' + +struct dohhttps_rr { + uint16_t len; /* raw encoded length */ + unsigned char *val; /* raw encoded octets */ +}; +#endif + +struct dohentry { + struct dynbuf cname[DOH_MAX_CNAME]; + struct dohaddr addr[DOH_MAX_ADDR]; + int numaddr; + unsigned int ttl; + int numcname; +#ifdef USE_HTTPSRR + struct dohhttps_rr https_rrs[DOH_MAX_HTTPS]; + int numhttps_rrs; +#endif +}; + +void Curl_doh_close(struct Curl_easy *data); +void Curl_doh_cleanup(struct Curl_easy *data); + +#ifdef UNITTESTS +UNITTEST DOHcode doh_req_encode(const char *host, + DNStype dnstype, + unsigned char *dnsp, /* buffer */ + size_t len, /* buffer size */ + size_t *olen); /* output length */ +UNITTEST DOHcode doh_resp_decode(const unsigned char *doh, + size_t dohlen, + DNStype dnstype, + struct dohentry *d); + +UNITTEST void de_init(struct dohentry *d); +UNITTEST void de_cleanup(struct dohentry *d); +#endif + +extern struct curl_trc_feat Curl_doh_trc; + +#else /* if DoH is disabled */ +#define Curl_doh(a,b,c,d) NULL +#define Curl_doh_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST +#endif + +#endif /* HEADER_CURL_DOH_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/easygetopt.c b/local-test-curl-full-01/afc-curl/lib/easygetopt.c new file mode 100644 index 0000000000000000000000000000000000000000..86833bf6b9e3e479b813da869923717693fb5ffb --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/easygetopt.c @@ -0,0 +1,98 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ | | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * ___|___/|_| ______| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "strcase.h" +#include "easyoptions.h" + +#ifndef CURL_DISABLE_GETOPTIONS + +/* Lookups easy options at runtime */ +static struct curl_easyoption *lookup(const char *name, CURLoption id) +{ + DEBUGASSERT(name || id); + DEBUGASSERT(!Curl_easyopts_check()); + if(name || id) { + struct curl_easyoption *o = &Curl_easyopts[0]; + do { + if(name) { + if(strcasecompare(o->name, name)) + return o; + } + else { + if((o->id == id) && !(o->flags & CURLOT_FLAG_ALIAS)) + /* do not match alias options */ + return o; + } + o++; + } while(o->name); + } + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + /* when name is used, the id argument is ignored */ + return lookup(name, CURLOPT_LASTENTRY); +} + +const struct curl_easyoption *curl_easy_option_by_id(CURLoption id) +{ + return lookup(NULL, id); +} + +/* Iterates over available options */ +const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev) +{ + if(prev && prev->name) { + prev++; + if(prev->name) + return prev; + } + else if(!prev) + return &Curl_easyopts[0]; + return NULL; +} + +#else +const struct curl_easyoption *curl_easy_option_by_name(const char *name) +{ + (void)name; + return NULL; +} + +const struct curl_easyoption *curl_easy_option_by_id (CURLoption id) +{ + (void)id; + return NULL; +} + +const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev) +{ + (void)prev; + return NULL; +} +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/escape.h b/local-test-curl-full-01/afc-curl/lib/escape.h new file mode 100644 index 0000000000000000000000000000000000000000..690e4178795a93940138bf02d09ba71de05ff049 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/escape.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_ESCAPE_H +#define HEADER_CURL_ESCAPE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* Escape and unescape URL encoding in strings. The functions return a new + * allocated string or NULL if an error occurred. */ + +#include "curl_ctype.h" + +enum urlreject { + REJECT_NADA = 2, + REJECT_CTRL, + REJECT_ZERO +}; + +CURLcode Curl_urldecode(const char *string, size_t length, + char **ostring, size_t *olen, + enum urlreject ctrl); + +void Curl_hexencode(const unsigned char *src, size_t len, /* input length */ + unsigned char *out, size_t olen); /* output buffer size */ + +#endif /* HEADER_CURL_ESCAPE_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/file.c b/local-test-curl-full-01/afc-curl/lib/file.c new file mode 100644 index 0000000000000000000000000000000000000000..7440b3c66d47c0b0ffcc21fa3e8387f344e6bf4b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/file.c @@ -0,0 +1,659 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_FILE + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +#ifdef HAVE_DIRENT_H +#include +#endif + +#include "strtoofft.h" +#include "urldata.h" +#include +#include "progress.h" +#include "sendf.h" +#include "escape.h" +#include "file.h" +#include "speedcheck.h" +#include "getinfo.h" +#include "multiif.h" +#include "transfer.h" +#include "url.h" +#include "parsedate.h" /* for the week day and month names */ +#include "warnless.h" +#include "curl_range.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(_WIN32) || defined(MSDOS) || defined(__EMX__) +#define DOS_FILESYSTEM 1 +#elif defined(__amigaos4__) +#define AMIGA_FILESYSTEM 1 +#endif + +#ifdef OPEN_NEEDS_ARG3 +# define open_readonly(p,f) open((p),(f),(0)) +#else +# define open_readonly(p,f) open((p),(f)) +#endif + +/* + * Forward declarations. + */ + +static CURLcode file_do(struct Curl_easy *data, bool *done); +static CURLcode file_done(struct Curl_easy *data, + CURLcode status, bool premature); +static CURLcode file_connect(struct Curl_easy *data, bool *done); +static CURLcode file_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); +static CURLcode file_setup_connection(struct Curl_easy *data, + struct connectdata *conn); + +/* + * FILE scheme handler. + */ + +const struct Curl_handler Curl_handler_file = { + "file", /* scheme */ + file_setup_connection, /* setup_connection */ + file_do, /* do_it */ + file_done, /* done */ + ZERO_NULL, /* do_more */ + file_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + file_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + 0, /* defport */ + CURLPROTO_FILE, /* protocol */ + CURLPROTO_FILE, /* family */ + PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */ +}; + + +static CURLcode file_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + (void)conn; + /* allocate the FILE specific struct */ + data->req.p.file = calloc(1, sizeof(struct FILEPROTO)); + if(!data->req.p.file) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +/* + * file_connect() gets called from Curl_protocol_connect() to allow us to + * do protocol-specific actions at connect-time. We emulate a + * connect-then-transfer protocol and "connect" to the file here + */ +static CURLcode file_connect(struct Curl_easy *data, bool *done) +{ + char *real_path; + struct FILEPROTO *file = data->req.p.file; + int fd; +#ifdef DOS_FILESYSTEM + size_t i; + char *actual_path; +#endif + size_t real_path_len; + CURLcode result; + + if(file->path) { + /* already connected. + * the handler->connect_it() is normally only called once, but + * FILE does a special check on setting up the connection which + * calls this explicitly. */ + *done = TRUE; + return CURLE_OK; + } + + result = Curl_urldecode(data->state.up.path, 0, &real_path, + &real_path_len, REJECT_ZERO); + if(result) + return result; + +#ifdef DOS_FILESYSTEM + /* If the first character is a slash, and there is + something that looks like a drive at the beginning of + the path, skip the slash. If we remove the initial + slash in all cases, paths without drive letters end up + relative to the current directory which is not how + browsers work. + + Some browsers accept | instead of : as the drive letter + separator, so we do too. + + On other platforms, we need the slash to indicate an + absolute pathname. On Windows, absolute paths start + with a drive letter. + */ + actual_path = real_path; + if((actual_path[0] == '/') && + actual_path[1] && + (actual_path[2] == ':' || actual_path[2] == '|')) { + actual_path[2] = ':'; + actual_path++; + real_path_len--; + } + + /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */ + for(i = 0; i < real_path_len; ++i) + if(actual_path[i] == '/') + actual_path[i] = '\\'; + else if(!actual_path[i]) { /* binary zero */ + Curl_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + + fd = open_readonly(actual_path, O_RDONLY|O_BINARY); + file->path = actual_path; +#else + if(memchr(real_path, 0, real_path_len)) { + /* binary zeroes indicate foul play */ + Curl_safefree(real_path); + return CURLE_URL_MALFORMAT; + } + + #ifdef AMIGA_FILESYSTEM + /* + * A leading slash in an AmigaDOS path denotes the parent + * directory, and hence we block this as it is relative. + * Absolute paths start with 'volumename:', so we check for + * this first. Failing that, we treat the path as a real Unix + * path, but only if the application was compiled with -lunix. + */ + fd = -1; + file->path = real_path; + + if(real_path[0] == '/') { + extern int __unix_path_semantics; + if(strchr(real_path + 1, ':')) { + /* Amiga absolute path */ + fd = open_readonly(real_path + 1, O_RDONLY); + file->path++; + } + else if(__unix_path_semantics) { + /* -lunix fallback */ + fd = open_readonly(real_path, O_RDONLY); + } + } + #else + fd = open_readonly(real_path, O_RDONLY); + file->path = real_path; + #endif +#endif + Curl_safefree(file->freepath); + file->freepath = real_path; /* free this when done */ + + file->fd = fd; + if(!data->state.upload && (fd == -1)) { + failf(data, "Couldn't open file %s", data->state.up.path); + file_done(data, CURLE_FILE_COULDNT_READ_FILE, FALSE); + return CURLE_FILE_COULDNT_READ_FILE; + } + *done = TRUE; + + return CURLE_OK; +} + +static CURLcode file_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct FILEPROTO *file = data->req.p.file; + (void)status; /* not used */ + (void)premature; /* not used */ + + if(file) { + Curl_safefree(file->freepath); + file->path = NULL; + if(file->fd != -1) + close(file->fd); + file->fd = -1; + } + + return CURLE_OK; +} + +static CURLcode file_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + (void)dead_connection; /* not used */ + (void)conn; + return file_done(data, CURLE_OK, FALSE); +} + +#ifdef DOS_FILESYSTEM +#define DIRSEP '\\' +#else +#define DIRSEP '/' +#endif + +static CURLcode file_upload(struct Curl_easy *data) +{ + struct FILEPROTO *file = data->req.p.file; + const char *dir = strchr(file->path, DIRSEP); + int fd; + int mode; + CURLcode result = CURLE_OK; + char *xfer_ulbuf; + size_t xfer_ulblen; + curl_off_t bytecount = 0; + struct_stat file_stat; + const char *sendbuf; + bool eos = FALSE; + + /* + * Since FILE: does not do the full init, we need to provide some extra + * assignments here. + */ + + if(!dir) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + + if(!dir[1]) + return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ + +#ifdef O_BINARY +#define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY +#else +#define MODE_DEFAULT O_WRONLY|O_CREAT +#endif + + if(data->state.resume_from) + mode = MODE_DEFAULT|O_APPEND; + else + mode = MODE_DEFAULT|O_TRUNC; + + fd = open(file->path, mode, data->set.new_file_perms); + if(fd < 0) { + failf(data, "cannot open %s for writing", file->path); + return CURLE_WRITE_ERROR; + } + + if(-1 != data->state.infilesize) + /* known size of data to "upload" */ + Curl_pgrsSetUploadSize(data, data->state.infilesize); + + /* treat the negative resume offset value as the case of "-" */ + if(data->state.resume_from < 0) { + if(fstat(fd, &file_stat)) { + close(fd); + failf(data, "cannot get the size of %s", file->path); + return CURLE_WRITE_ERROR; + } + data->state.resume_from = (curl_off_t)file_stat.st_size; + } + + result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen); + if(result) + goto out; + + while(!result && !eos) { + size_t nread; + ssize_t nwrite; + size_t readcount; + + result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &readcount, &eos); + if(result) + break; + + if(!readcount) + break; + + nread = readcount; + + /* skip bytes before resume point */ + if(data->state.resume_from) { + if((curl_off_t)nread <= data->state.resume_from) { + data->state.resume_from -= nread; + nread = 0; + sendbuf = xfer_ulbuf; + } + else { + sendbuf = xfer_ulbuf + data->state.resume_from; + nread -= (size_t)data->state.resume_from; + data->state.resume_from = 0; + } + } + else + sendbuf = xfer_ulbuf; + + /* write the data to the target */ + nwrite = write(fd, sendbuf, nread); + if((size_t)nwrite != nread) { + result = CURLE_SEND_ERROR; + break; + } + + bytecount += nread; + + Curl_pgrsSetUploadCounter(data, bytecount); + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + } + if(!result && Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + +out: + close(fd); + Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf); + + return result; +} + +/* + * file_do() is the protocol-specific function for the do-phase, separated + * from the connect-phase above. Other protocols merely setup the transfer in + * the do-phase, to have it done in the main transfer loop but since some + * platforms we support do not allow select()ing etc on file handles (as + * opposed to sockets) we instead perform the whole do-operation in this + * function. + */ +static CURLcode file_do(struct Curl_easy *data, bool *done) +{ + /* This implementation ignores the hostname in conformance with + RFC 1738. Only local files (reachable via the standard file system) + are supported. This means that files on remotely mounted directories + (via NFS, Samba, NT sharing) can be accessed through a file:// URL + */ + CURLcode result = CURLE_OK; + struct_stat statbuf; /* struct_stat instead of struct stat just to allow the + Windows version to have a different struct without + having to redefine the simple word 'stat' */ + curl_off_t expected_size = -1; + bool size_known; + bool fstated = FALSE; + int fd; + struct FILEPROTO *file; + char *xfer_buf; + size_t xfer_blen; + + *done = TRUE; /* unconditionally */ + + if(data->state.upload) + return file_upload(data); + + file = data->req.p.file; + + /* get the fd from the connection phase */ + fd = file->fd; + + /* VMS: This only works reliable for STREAMLF files */ + if(-1 != fstat(fd, &statbuf)) { + if(!S_ISDIR(statbuf.st_mode)) + expected_size = statbuf.st_size; + /* and store the modification time */ + data->info.filetime = statbuf.st_mtime; + fstated = TRUE; + } + + if(fstated && !data->state.range && data->set.timecondition && + !Curl_meets_timecondition(data, data->info.filetime)) + return CURLE_OK; + + if(fstated) { + time_t filetime; + struct tm buffer; + const struct tm *tm = &buffer; + char header[80]; + int headerlen; + static const char accept_ranges[]= { "Accept-ranges: bytes\r\n" }; + static const char no_body[]= { "File-body: suppressed.The body of " + "this file has been supressed. If you would like to include " + "the contents of this file use the -i option.\r\n" }; + static const char body_msg[]= { "File-body: included.\r\n"}; + if(expected_size >= 0) { + headerlen = + msnprintf(header, sizeof(header), "Content-Length: %" FMT_OFF_T "\r\n", + expected_size); + result = Curl_client_write(data, CLIENTWRITE_HEADER, + header, headerlen); + if(result) + return result; + + result = Curl_client_write(data, CLIENTWRITE_HEADER, + accept_ranges, sizeof(accept_ranges) - 1); + if(result != CURLE_OK) + return result; + } + + filetime = (time_t)statbuf.st_mtime; + result = Curl_gmtime(filetime, &buffer); + if(result) + return result; + + if(data->req.no_body) { + headerlen = + msnprintf(header, sizeof(no_body), "%s (%ld bytes) \r\n", + no_body, expected_size); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + } + else { + result = Curl_client_write(data, CLIENTWRITE_HEADER, + body_msg, sizeof(body_msg) - 1); + } + if(result) + return result; + /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ + headerlen = + msnprintf(header, sizeof(header), + "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", + Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6], + tm->tm_mday, + Curl_month[tm->tm_mon], + tm->tm_year + 1900, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen); + if(!result) + /* end of headers */ + result = Curl_client_write(data, CLIENTWRITE_HEADER, "\r\n", 2); + if(result) + return result; + /* set the file size to make it available post transfer */ + Curl_pgrsSetDownloadSize(data, expected_size); + if(data->req.no_body) + return CURLE_OK; + } + + /* Check whether file range has been specified */ + result = Curl_range(data); + if(result) + return result; + + /* Adjust the start offset in case we want to get the N last bytes + * of the stream if the filesize could be determined */ + if(data->state.resume_from < 0) { + if(!fstated) { + failf(data, "cannot get the size of file."); + return CURLE_READ_ERROR; + } + data->state.resume_from += (curl_off_t)statbuf.st_size; + } + + if(data->state.resume_from > 0) { + /* We check explicitly if we have a start offset, because + * expected_size may be -1 if we do not know how large the file is, + * in which case we should not adjust it. */ + if(data->state.resume_from <= expected_size) + expected_size -= data->state.resume_from; + else { + failf(data, "failed to resume file:// transfer"); + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + /* A high water mark has been specified so we obey... */ + if(data->req.maxdownload > 0) + expected_size = data->req.maxdownload; + + if(!fstated || (expected_size <= 0)) + size_known = FALSE; + else + size_known = TRUE; + + /* The following is a shortcut implementation of file reading + this is both more efficient than the former call to download() and + it avoids problems with select() and recv() on file descriptors + in Winsock */ + if(size_known) + Curl_pgrsSetDownloadSize(data, expected_size); + + if(data->state.resume_from) { + if(!S_ISDIR(statbuf.st_mode)) { + if(data->state.resume_from != + lseek(fd, data->state.resume_from, SEEK_SET)) + return CURLE_BAD_DOWNLOAD_RESUME; + } + else { + return CURLE_BAD_DOWNLOAD_RESUME; + } + } + + result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen); + if(result) + goto out; + + if(!S_ISDIR(statbuf.st_mode)) { + while(!result) { + ssize_t nread; + /* Do not fill a whole buffer if we want less than all data */ + size_t bytestoread; + + if(size_known) { + bytestoread = (expected_size < (curl_off_t)(xfer_blen-1)) ? + curlx_sotouz(expected_size) : (xfer_blen-1); + } + else + bytestoread = xfer_blen-1; + + nread = read(fd, xfer_buf, bytestoread); + + if(nread > 0) + xfer_buf[nread] = 0; + + if(nread <= 0 || (size_known && (expected_size == 0))) + break; + + if(size_known) + expected_size -= nread; + + result = Curl_client_write(data, CLIENTWRITE_BODY, xfer_buf, nread); + if(result) + goto out; + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + if(result) + goto out; + } + } + else { +#ifdef HAVE_OPENDIR + DIR *dir = opendir(file->path); + struct dirent *entry; + + if(!dir) { + result = CURLE_READ_ERROR; + goto out; + } + else { + while((entry = readdir(dir))) { + if(entry->d_name[0] != '.') { + result = Curl_client_write(data, CLIENTWRITE_BODY, + entry->d_name, strlen(entry->d_name)); + if(result) + break; + result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1); + if(result) + break; + } + } + closedir(dir); + } +#else + failf(data, "Directory listing not yet implemented on this platform."); + result = CURLE_READ_ERROR; +#endif + } + + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + +out: + Curl_multi_xfer_buf_release(data, xfer_buf); + return result; +} + +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/fileinfo.c b/local-test-curl-full-01/afc-curl/lib/fileinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..2be3b3239b80e1f3a63437f9a7dda5b634972f9a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/fileinfo.c @@ -0,0 +1,46 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_FTP +#include "strdup.h" +#include "fileinfo.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +struct fileinfo *Curl_fileinfo_alloc(void) +{ + return calloc(1, sizeof(struct fileinfo)); +} + +void Curl_fileinfo_cleanup(struct fileinfo *finfo) +{ + if(!finfo) + return; + + Curl_dyn_free(&finfo->buf); + free(finfo); +} +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/fopen.c b/local-test-curl-full-01/afc-curl/lib/fopen.c new file mode 100644 index 0000000000000000000000000000000000000000..7373e08831dd5ce6bd08a8cafdea06c4edd61a43 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/fopen.c @@ -0,0 +1,158 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_ALTSVC) || \ + !defined(CURL_DISABLE_HSTS) + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include "urldata.h" +#include "rand.h" +#include "fopen.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* + The dirslash() function breaks a null-terminated pathname string into + directory and filename components then returns the directory component up + to, *AND INCLUDING*, a final '/'. If there is no directory in the path, + this instead returns a "" string. + + This function returns a pointer to malloc'ed memory. + + The input path to this function is expected to have a filename part. +*/ + +#ifdef _WIN32 +#define PATHSEP "\\" +#define IS_SEP(x) (((x) == '/') || ((x) == '\\')) +#elif defined(MSDOS) || defined(__EMX__) || defined(OS2) +#define PATHSEP "\\" +#define IS_SEP(x) ((x) == '\\') +#else +#define PATHSEP "/" +#define IS_SEP(x) ((x) == '/') +#endif + +static char *dirslash(const char *path) +{ + size_t n; + struct dynbuf out; + DEBUGASSERT(path); + Curl_dyn_init(&out, CURL_MAX_INPUT_LENGTH); + n = strlen(path); + if(n) { + /* find the rightmost path separator, if any */ + while(n && !IS_SEP(path[n-1])) + --n; + /* skip over all the path separators, if any */ + while(n && IS_SEP(path[n-1])) + --n; + } + if(Curl_dyn_addn(&out, path, n)) + return NULL; + /* if there was a directory, append a single trailing slash */ + if(n && Curl_dyn_addn(&out, PATHSEP, 1)) + return NULL; + return Curl_dyn_ptr(&out); +} + +/* + * Curl_fopen() opens a file for writing with a temp name, to be renamed + * to the final name when completed. If there is an existing file using this + * name at the time of the open, this function will clone the mode from that + * file. if 'tempname' is non-NULL, it needs a rename after the file is + * written. + */ +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname) +{ + CURLcode result = CURLE_WRITE_ERROR; + unsigned char randbuf[41]; + char *tempstore = NULL; + struct_stat sb; + int fd = -1; + char *dir = NULL; + *tempname = NULL; + + *fh = fopen(filename, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + if(fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) { + return CURLE_OK; + } + fclose(*fh); + *fh = NULL; + + result = Curl_rand_alnum(data, randbuf, sizeof(randbuf)); + if(result) + goto fail; + + dir = dirslash(filename); + if(dir) { + /* The temp filename should not end up too long for the target file + system */ + tempstore = aprintf("%s%s.tmp", dir, randbuf); + free(dir); + } + + if(!tempstore) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = CURLE_WRITE_ERROR; +#if (defined(ANDROID) || defined(__ANDROID__)) && \ + (defined(__i386__) || defined(__arm__)) + fd = open(tempstore, O_WRONLY | O_CREAT | O_EXCL, (mode_t)(0600|sb.st_mode)); +#else + fd = open(tempstore, O_WRONLY | O_CREAT | O_EXCL, 0600|sb.st_mode); +#endif + if(fd == -1) + goto fail; + + *fh = fdopen(fd, FOPEN_WRITETEXT); + if(!*fh) + goto fail; + + *tempname = tempstore; + return CURLE_OK; + +fail: + if(fd != -1) { + close(fd); + unlink(tempstore); + } + + free(tempstore); + return result; +} + +#endif /* ! disabled */ diff --git a/local-test-curl-full-01/afc-curl/lib/fopen.h b/local-test-curl-full-01/afc-curl/lib/fopen.h new file mode 100644 index 0000000000000000000000000000000000000000..e3a919d073678a8a5f652f1a2409f75af34a8a28 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/fopen.h @@ -0,0 +1,30 @@ +#ifndef HEADER_CURL_FOPEN_H +#define HEADER_CURL_FOPEN_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +CURLcode Curl_fopen(struct Curl_easy *data, const char *filename, + FILE **fh, char **tempname); + +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/ftp.h b/local-test-curl-full-01/afc-curl/lib/ftp.h new file mode 100644 index 0000000000000000000000000000000000000000..3d0af015878679956731446306757cb01cfe55de --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/ftp.h @@ -0,0 +1,167 @@ +#ifndef HEADER_CURL_FTP_H +#define HEADER_CURL_FTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "pingpong.h" + +#ifndef CURL_DISABLE_FTP +extern const struct Curl_handler Curl_handler_ftp; + +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_ftps; +#endif + +CURLcode Curl_GetFTPResponse(struct Curl_easy *data, ssize_t *nread, + int *ftpcode); +#endif /* CURL_DISABLE_FTP */ + +/**************************************************************************** + * FTP unique setup + ***************************************************************************/ +enum { + FTP_STOP, /* do nothing state, stops the state machine */ + FTP_WAIT220, /* waiting for the initial 220 response immediately after + a connect */ + FTP_AUTH, + FTP_USER, + FTP_PASS, + FTP_ACCT, + FTP_PBSZ, + FTP_PROT, + FTP_CCC, + FTP_PWD, + FTP_SYST, + FTP_NAMEFMT, + FTP_QUOTE, /* waiting for a response to a command sent in a quote list */ + FTP_RETR_PREQUOTE, + FTP_STOR_PREQUOTE, + FTP_POSTQUOTE, + FTP_CWD, /* change dir */ + FTP_MKD, /* if the dir did not exist */ + FTP_MDTM, /* to figure out the datestamp */ + FTP_TYPE, /* to set type when doing a head-like request */ + FTP_LIST_TYPE, /* set type when about to do a dir list */ + FTP_RETR_TYPE, /* set type when about to RETR a file */ + FTP_STOR_TYPE, /* set type when about to STOR a file */ + FTP_SIZE, /* get the remote file's size for head-like request */ + FTP_RETR_SIZE, /* get the remote file's size for RETR */ + FTP_STOR_SIZE, /* get the size for STOR */ + FTP_REST, /* when used to check if the server supports it in head-like */ + FTP_RETR_REST, /* when asking for "resume" in for RETR */ + FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */ + FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */ + FTP_PASV, /* generic state for PASV and EPSV, check count1 */ + FTP_LIST, /* generic state for LIST, NLST or a custom list command */ + FTP_RETR, + FTP_STOR, /* generic state for STOR and APPE */ + FTP_QUIT, + FTP_LAST /* never used */ +}; +typedef unsigned char ftpstate; /* use the enum values */ + +struct ftp_parselist_data; /* defined later in ftplistparser.c */ + +struct ftp_wc { + struct ftp_parselist_data *parser; + + struct { + curl_write_callback write_function; + FILE *file_descriptor; + } backup; +}; + +typedef enum { + FTPFILE_MULTICWD = 1, /* as defined by RFC1738 */ + FTPFILE_NOCWD = 2, /* use SIZE / RETR / STOR on the full path */ + FTPFILE_SINGLECWD = 3 /* make one CWD, then SIZE / RETR / STOR on the + file */ +} curl_ftpfile; + +/* This FTP struct is used in the Curl_easy. All FTP data that is + connection-oriented must be in FTP_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct FTP { + char *path; /* points to the urlpieces struct field */ + char *pathalloc; /* if non-NULL a pointer to an allocated path */ + + /* transfer a file/body or not, done as a typedefed enum just to make + debuggers display the full symbol and not just the numerical value */ + curl_pp_transfer transfer; + curl_off_t downloadsize; +}; + + +/* ftp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct ftp_conn { + struct pingpong pp; + char *account; + char *alternative_to_user; + char *entrypath; /* the PWD reply when we logged on */ + char *file; /* url-decoded filename (or path) */ + char **dirs; /* realloc()ed array for path components */ + char *newhost; + char *prevpath; /* url-decoded conn->path from the previous transfer */ + char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a + and others (A/I or zero) */ + curl_off_t retr_size_saved; /* Size of retrieved file saved */ + char *server_os; /* The target server operating system. */ + curl_off_t known_filesize; /* file size is different from -1, if wildcard + LIST parsing was done and wc_statemach set + it */ + int dirdepth; /* number of entries used in the 'dirs' array */ + int cwdcount; /* number of CWD commands issued */ + int count1; /* general purpose counter for the state machine */ + int count2; /* general purpose counter for the state machine */ + int count3; /* general purpose counter for the state machine */ + /* newhost is the (allocated) IP addr or hostname to connect the data + connection to */ + unsigned short newport; + ftpstate state; /* always use ftp.c:state() to change state! */ + ftpstate state_saved; /* transfer type saved to be reloaded after data + connection is established */ + unsigned char use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or + IMAP or POP3 or others! (type: curl_usessl)*/ + unsigned char ccc; /* ccc level for this connection */ + BIT(ftp_trying_alternative); + BIT(dont_check); /* Set to TRUE to prevent the final (post-transfer) + file size and 226/250 status check. It should still + read the line, just ignore the result. */ + BIT(ctl_valid); /* Tells Curl_ftp_quit() whether or not to do anything. If + the connection has timed out or been closed, this + should be FALSE when it gets to Curl_ftp_quit() */ + BIT(cwddone); /* if it has been determined that the proper CWD combo + already has been done */ + BIT(cwdfail); /* set TRUE if a CWD command fails, as then we must prevent + caching the current directory */ + BIT(wait_data_conn); /* this is set TRUE if data connection is waited */ +}; + +#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */ + +#endif /* HEADER_CURL_FTP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/getenv.c b/local-test-curl-full-01/afc-curl/lib/getenv.c new file mode 100644 index 0000000000000000000000000000000000000000..63eaeda0f26ea9b3f276a4bca170298d4eacbdd6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/getenv.c @@ -0,0 +1,80 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include +#include "curl_memory.h" + +#include "memdebug.h" + +static char *GetEnv(const char *variable) +{ +#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_UWP) || \ + defined(__ORBIS__) || defined(__PROSPERO__) /* PlayStation 4 and 5 */ + (void)variable; + return NULL; +#elif defined(_WIN32) + /* This uses Windows API instead of C runtime getenv() to get the environment + variable since some changes are not always visible to the latter. #4774 */ + char *buf = NULL; + char *tmp; + DWORD bufsize; + DWORD rc = 1; + const DWORD max = 32768; /* max env var size from MSCRT source */ + + for(;;) { + tmp = realloc(buf, rc); + if(!tmp) { + free(buf); + return NULL; + } + + buf = tmp; + bufsize = rc; + + /* it is possible for rc to be 0 if the variable was found but empty. + Since getenv does not make that distinction we ignore it as well. */ + rc = GetEnvironmentVariableA(variable, buf, bufsize); + if(!rc || rc == bufsize || rc > max) { + free(buf); + return NULL; + } + + /* if rc < bufsize then rc is bytes written not including null */ + if(rc < bufsize) + return buf; + + /* else rc is bytes needed, try again */ + } +#else + char *env = getenv(variable); + return (env && env[0]) ? strdup(env) : NULL; +#endif +} + +char *curl_getenv(const char *v) +{ + return GetEnv(v); +} diff --git a/local-test-curl-full-01/afc-curl/lib/getinfo.h b/local-test-curl-full-01/afc-curl/lib/getinfo.h new file mode 100644 index 0000000000000000000000000000000000000000..56bb440b43b2febfe89e1fbf1fb79efa9addb83b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/getinfo.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_GETINFO_H +#define HEADER_CURL_GETINFO_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...); +CURLcode Curl_initinfo(struct Curl_easy *data); + +#endif /* HEADER_CURL_GETINFO_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/gopher.h b/local-test-curl-full-01/afc-curl/lib/gopher.h new file mode 100644 index 0000000000000000000000000000000000000000..9e3365b71c25781c0839842d79b24c78e97cfe9e --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/gopher.h @@ -0,0 +1,34 @@ +#ifndef HEADER_CURL_GOPHER_H +#define HEADER_CURL_GOPHER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_GOPHER +extern const struct Curl_handler Curl_handler_gopher; +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_gophers; +#endif +#endif + +#endif /* HEADER_CURL_GOPHER_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/hostip.c b/local-test-curl-full-01/afc-curl/lib/hostip.c new file mode 100644 index 0000000000000000000000000000000000000000..1a9432d52afa89cb17bddb96ce8f4a680e2d093f --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/hostip.c @@ -0,0 +1,1488 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN6_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef __VMS +#include +#include +#endif + +#include +#include + +#include "urldata.h" +#include "sendf.h" +#include "hostip.h" +#include "hash.h" +#include "rand.h" +#include "share.h" +#include "url.h" +#include "inet_ntop.h" +#include "inet_pton.h" +#include "multiif.h" +#include "doh.h" +#include "warnless.h" +#include "strcase.h" +#include "easy_lock.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(CURLRES_SYNCH) && \ + defined(HAVE_ALARM) && \ + defined(SIGALRM) && \ + defined(HAVE_SIGSETJMP) && \ + defined(GLOBAL_INIT_IS_THREADSAFE) +/* alarm-based timeouts can only be used with all the dependencies satisfied */ +#define USE_ALARM_TIMEOUT +#endif + +#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */ + +#define MAX_DNS_CACHE_SIZE 29999 + +/* + * hostip.c explained + * ================== + * + * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c + * source file are these: + * + * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use + * that. The host may not be able to resolve IPv6, but we do not really have to + * take that into account. Hosts that are not IPv6-enabled have CURLRES_IPV4 + * defined. + * + * CURLRES_ARES - is defined if libcurl is built to use c-ares for + * asynchronous name resolves. This can be Windows or *nix. + * + * CURLRES_THREADED - is defined if libcurl is built to run under (native) + * Windows, and then the name resolve will be done in a new thread, and the + * supported API will be the same as for ares-builds. + * + * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If + * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is + * defined. + * + * The host*.c sources files are split up like this: + * + * hostip.c - method-independent resolver functions and utility functions + * hostasyn.c - functions for asynchronous name resolves + * hostsyn.c - functions for synchronous name resolves + * hostip4.c - IPv4 specific functions + * hostip6.c - IPv6 specific functions + * + * The two asynchronous name resolver backends are implemented in: + * asyn-ares.c - functions for ares-using name resolves + * asyn-thread.c - functions for threaded name resolves + + * The hostip.h is the united header file for all this. It defines the + * CURLRES_* defines based on the config*.h and curl_setup.h defines. + */ + +static void hostcache_unlink_entry(void *entry); + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void show_resolve_info(struct Curl_easy *data, + struct Curl_dns_entry *dns); +#else +#define show_resolve_info(x,y) Curl_nop_stmt +#endif + +/* + * Curl_printable_address() stores a printable version of the 1st address + * given in the 'ai' argument. The result will be stored in the buf that is + * bufsize bytes big. + * + * If the conversion fails, the target buffer is empty. + */ +void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf, + size_t bufsize) +{ + DEBUGASSERT(bufsize); + buf[0] = 0; + + switch(ai->ai_family) { + case AF_INET: { + const struct sockaddr_in *sa4 = (const void *)ai->ai_addr; + const struct in_addr *ipaddr4 = &sa4->sin_addr; + (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize); + break; + } +#ifdef USE_IPV6 + case AF_INET6: { + const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr; + const struct in6_addr *ipaddr6 = &sa6->sin6_addr; + (void)Curl_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize); + break; + } +#endif + default: + break; + } +} + +/* + * Create a hostcache id string for the provided host + port, to be used by + * the DNS caching. Without alloc. Return length of the id string. + */ +static size_t +create_hostcache_id(const char *name, + size_t nlen, /* 0 or actual name length */ + int port, char *ptr, size_t buflen) +{ + size_t len = nlen ? nlen : strlen(name); + DEBUGASSERT(buflen >= MAX_HOSTCACHE_LEN); + if(len > (buflen - 7)) + len = buflen - 7; + /* store and lower case the name */ + Curl_strntolower(ptr, name, len); + return msnprintf(&ptr[len], 7, ":%u", port) + len; +} + +struct hostcache_prune_data { + time_t now; + time_t oldest; /* oldest time in cache not pruned. */ + int max_age_sec; +}; + +/* + * This function is set as a callback to be called for every entry in the DNS + * cache when we want to prune old unused entries. + * + * Returning non-zero means remove the entry, return 0 to keep it in the + * cache. + */ +static int +hostcache_entry_is_stale(void *datap, void *hc) +{ + struct hostcache_prune_data *prune = + (struct hostcache_prune_data *) datap; + struct Curl_dns_entry *dns = (struct Curl_dns_entry *) hc; + + if(dns->timestamp) { + /* age in seconds */ + time_t age = prune->now - dns->timestamp; + if(age >= prune->max_age_sec) + return TRUE; + if(age > prune->oldest) + prune->oldest = age; + } + return FALSE; +} + +/* + * Prune the DNS cache. This assumes that a lock has already been taken. + * Returns the 'age' of the oldest still kept entry. + */ +static time_t +hostcache_prune(struct Curl_hash *hostcache, int cache_timeout, + time_t now) +{ + struct hostcache_prune_data user; + + user.max_age_sec = cache_timeout; + user.now = now; + user.oldest = 0; + + Curl_hash_clean_with_criterium(hostcache, + (void *) &user, + hostcache_entry_is_stale); + + return user.oldest; +} + +/* + * Library-wide function for pruning the DNS cache. This function takes and + * returns the appropriate locks. + */ +void Curl_hostcache_prune(struct Curl_easy *data) +{ + time_t now; + /* the timeout may be set -1 (forever) */ + int timeout = data->set.dns_cache_timeout; + + if(!data->dns.hostcache) + /* NULL hostcache means we cannot do it */ + return; + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + now = time(NULL); + + do { + /* Remove outdated and unused entries from the hostcache */ + time_t oldest = hostcache_prune(data->dns.hostcache, timeout, now); + + if(oldest < INT_MAX) + timeout = (int)oldest; /* we know it fits */ + else + timeout = INT_MAX - 1; + + /* if the cache size is still too big, use the oldest age as new + prune limit */ + } while(timeout && + (Curl_hash_count(data->dns.hostcache) > MAX_DNS_CACHE_SIZE)); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + +#ifdef USE_ALARM_TIMEOUT +/* Beware this is a global and unique instance. This is used to store the + return address that we can jump back to from inside a signal handler. This + is not thread-safe stuff. */ +static sigjmp_buf curl_jmpenv; +static curl_simple_lock curl_jmpenv_lock; +#endif + +/* lookup address, returns entry if found and not stale */ +static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data, + const char *hostname, + int port) +{ + struct Curl_dns_entry *dns = NULL; + char entry_id[MAX_HOSTCACHE_LEN]; + + /* Create an entry id, based upon the hostname and port */ + size_t entry_len = create_hostcache_id(hostname, 0, port, + entry_id, sizeof(entry_id)); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + + /* No entry found in cache, check if we might have a wildcard entry */ + if(!dns && data->state.wildcard_resolve) { + entry_len = create_hostcache_id("*", 1, port, entry_id, sizeof(entry_id)); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + } + + if(dns && (data->set.dns_cache_timeout != -1)) { + /* See whether the returned entry is stale. Done before we release lock */ + struct hostcache_prune_data user; + + user.now = time(NULL); + user.max_age_sec = data->set.dns_cache_timeout; + user.oldest = 0; + + if(hostcache_entry_is_stale(&user, dns)) { + infof(data, "Hostname in DNS cache was stale, zapped"); + dns = NULL; /* the memory deallocation is being handled by the hash */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + } + + /* See if the returned entry matches the required resolve mode */ + if(dns && data->conn->ip_version != CURL_IPRESOLVE_WHATEVER) { + int pf = PF_INET; + bool found = FALSE; + struct Curl_addrinfo *addr = dns->addr; + +#ifdef PF_INET6 + if(data->conn->ip_version == CURL_IPRESOLVE_V6) + pf = PF_INET6; +#endif + + while(addr) { + if(addr->ai_family == pf) { + found = TRUE; + break; + } + addr = addr->ai_next; + } + + if(!found) { + infof(data, "Hostname in DNS cache does not have needed family, zapped"); + dns = NULL; /* the memory deallocation is being handled by the hash */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + } + return dns; +} + +/* + * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Curl_resolv() checks initially and multi_runsingle() checks each time + * it discovers the handle in the state WAITRESOLVE whether the hostname + * has already been resolved and the address has already been stored in + * the DNS cache. This short circuits waiting for a lot of pending + * lookups for the same hostname requested by different handles. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "released" with Curl_resolv_unlink() after + * use, or we will leak memory! + */ +struct Curl_dns_entry * +Curl_fetch_addr(struct Curl_easy *data, + const char *hostname, + int port) +{ + struct Curl_dns_entry *dns = NULL; + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + dns = fetch_addr(data, hostname, port); + + if(dns) + dns->refcount++; /* we use it! */ + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + return dns; +} + +#ifndef CURL_DISABLE_SHUFFLE_DNS +/* + * Return # of addresses in a Curl_addrinfo struct + */ +static int num_addresses(const struct Curl_addrinfo *addr) +{ + int i = 0; + while(addr) { + addr = addr->ai_next; + i++; + } + return i; +} + +UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr); +/* + * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo' + * struct by re-linking its linked list. + * + * The addr argument should be the address of a pointer to the head node of a + * `Curl_addrinfo` list and it will be modified to point to the new head after + * shuffling. + * + * Not declared static only to make it easy to use in a unit test! + * + * @unittest: 1608 + */ +UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data, + struct Curl_addrinfo **addr) +{ + CURLcode result = CURLE_OK; + const int num_addrs = num_addresses(*addr); + + if(num_addrs > 1) { + struct Curl_addrinfo **nodes; + infof(data, "Shuffling %i addresses", num_addrs); + + nodes = malloc(num_addrs*sizeof(*nodes)); + if(nodes) { + int i; + unsigned int *rnd; + const size_t rnd_size = num_addrs * sizeof(*rnd); + + /* build a plain array of Curl_addrinfo pointers */ + nodes[0] = *addr; + for(i = 1; i < num_addrs; i++) { + nodes[i] = nodes[i-1]->ai_next; + } + + rnd = malloc(rnd_size); + if(rnd) { + /* Fisher-Yates shuffle */ + if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) { + struct Curl_addrinfo *swap_tmp; + for(i = num_addrs - 1; i > 0; i--) { + swap_tmp = nodes[rnd[i] % (unsigned int)(i + 1)]; + nodes[rnd[i] % (unsigned int)(i + 1)] = nodes[i]; + nodes[i] = swap_tmp; + } + + /* relink list in the new order */ + for(i = 1; i < num_addrs; i++) { + nodes[i-1]->ai_next = nodes[i]; + } + + nodes[num_addrs-1]->ai_next = NULL; + *addr = nodes[0]; + } + free(rnd); + } + else + result = CURLE_OUT_OF_MEMORY; + free(nodes); + } + else + result = CURLE_OUT_OF_MEMORY; + } + return result; +} +#endif + +/* + * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. + * + * When calling Curl_resolv() has resulted in a response with a returned + * address, we call this function to store the information in the dns + * cache etc + * + * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. + */ +struct Curl_dns_entry * +Curl_cache_addr(struct Curl_easy *data, + struct Curl_addrinfo *addr, + const char *hostname, + size_t hostlen, /* length or zero */ + int port, + bool permanent) +{ + char entry_id[MAX_HOSTCACHE_LEN]; + size_t entry_len; + struct Curl_dns_entry *dns; + struct Curl_dns_entry *dns2; + +#ifndef CURL_DISABLE_SHUFFLE_DNS + /* shuffle addresses if requested */ + if(data->set.dns_shuffle_addresses) { + CURLcode result = Curl_shuffle_addr(data, &addr); + if(result) + return NULL; + } +#endif + if(!hostlen) + hostlen = strlen(hostname); + + /* Create a new cache entry */ + dns = calloc(1, sizeof(struct Curl_dns_entry) + hostlen); + if(!dns) { + return NULL; + } + + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(hostname, hostlen, port, + entry_id, sizeof(entry_id)); + + dns->refcount = 1; /* the cache has the first reference */ + dns->addr = addr; /* this is the address(es) */ + if(permanent) + dns->timestamp = 0; /* an entry that never goes stale */ + else { + dns->timestamp = time(NULL); + if(dns->timestamp == 0) + dns->timestamp = 1; + } + dns->hostport = port; + if(hostlen) + memcpy(dns->hostname, hostname, hostlen); + + /* Store the resolved data in our DNS cache. */ + dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1, + (void *)dns); + if(!dns2) { + free(dns); + return NULL; + } + + dns = dns2; + dns->refcount++; /* mark entry as in-use */ + return dns; +} + +#ifdef USE_IPV6 +/* return a static IPv6 ::1 for the name */ +static struct Curl_addrinfo *get_localhost6(int port, const char *name) +{ + struct Curl_addrinfo *ca; + const size_t ss_size = sizeof(struct sockaddr_in6); + const size_t hostlen = strlen(name); + struct sockaddr_in6 sa6; + unsigned char ipv6[16]; + unsigned short port16 = (unsigned short)(port & 0xffff); + ca = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + + sa6.sin6_family = AF_INET6; + sa6.sin6_port = htons(port16); + sa6.sin6_flowinfo = 0; + sa6.sin6_scope_id = 0; + + (void)Curl_inet_pton(AF_INET6, "::1", ipv6); + memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6)); + + ca->ai_flags = 0; + ca->ai_family = AF_INET6; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_next = NULL; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa6, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + strcpy(ca->ai_canonname, name); + return ca; +} +#else +#define get_localhost6(x,y) NULL +#endif + +/* return a static IPv4 127.0.0.1 for the given name */ +static struct Curl_addrinfo *get_localhost(int port, const char *name) +{ + struct Curl_addrinfo *ca; + struct Curl_addrinfo *ca6; + const size_t ss_size = sizeof(struct sockaddr_in); + const size_t hostlen = strlen(name); + struct sockaddr_in sa; + unsigned int ipv4; + unsigned short port16 = (unsigned short)(port & 0xffff); + + /* memset to clear the sa.sin_zero field */ + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_port = htons(port16); + if(Curl_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1) + return NULL; + memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4)); + + ca = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1); + if(!ca) + return NULL; + ca->ai_flags = 0; + ca->ai_family = AF_INET; + ca->ai_socktype = SOCK_STREAM; + ca->ai_protocol = IPPROTO_TCP; + ca->ai_addrlen = (curl_socklen_t)ss_size; + ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo)); + memcpy(ca->ai_addr, &sa, ss_size); + ca->ai_canonname = (char *)ca->ai_addr + ss_size; + strcpy(ca->ai_canonname, name); + + ca6 = get_localhost6(port, name); + if(!ca6) + return ca; + ca6->ai_next = ca; + return ca6; +} + +#ifdef USE_IPV6 +/* + * Curl_ipv6works() returns TRUE if IPv6 seems to work. + */ +bool Curl_ipv6works(struct Curl_easy *data) +{ + if(data) { + /* the nature of most system is that IPv6 status does not come and go + during a program's lifetime so we only probe the first time and then we + have the info kept for fast reuse */ + DEBUGASSERT(data); + DEBUGASSERT(data->multi); + if(data->multi->ipv6_up == IPV6_UNKNOWN) { + bool works = Curl_ipv6works(NULL); + data->multi->ipv6_up = works ? IPV6_WORKS : IPV6_DEAD; + } + return data->multi->ipv6_up == IPV6_WORKS; + } + else { + int ipv6_works = -1; + /* probe to see if we have a working IPv6 stack */ + curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); + if(s == CURL_SOCKET_BAD) + /* an IPv6 address was requested but we cannot get/use one */ + ipv6_works = 0; + else { + ipv6_works = 1; + sclose(s); + } + return (ipv6_works > 0); + } +} +#endif /* USE_IPV6 */ + +/* + * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4 + * (or IPv6 if supported) address. + */ +bool Curl_host_is_ipnum(const char *hostname) +{ + struct in_addr in; +#ifdef USE_IPV6 + struct in6_addr in6; +#endif + if(Curl_inet_pton(AF_INET, hostname, &in) > 0 +#ifdef USE_IPV6 + || Curl_inet_pton(AF_INET6, hostname, &in6) > 0 +#endif + ) + return TRUE; + return FALSE; +} + + +/* return TRUE if 'part' is a case insensitive tail of 'full' */ +static bool tailmatch(const char *full, const char *part) +{ + size_t plen = strlen(part); + size_t flen = strlen(full); + if(plen > flen) + return FALSE; + return strncasecompare(part, &full[flen - plen], plen); +} + +/* + * Curl_resolv() is the main name resolve function within libcurl. It resolves + * a name and returns a pointer to the entry in the 'entry' argument (if one + * is provided). This function might return immediately if we are using asynch + * resolves. See the return codes. + * + * The cache entry we return will get its 'inuse' counter increased when this + * function is used. You MUST call Curl_resolv_unlink() later (when you are + * done using this struct) to decrease the reference counter again. + * + * Return codes: + * + * CURLRESOLV_ERROR (-1) = error, no pointer + * CURLRESOLV_RESOLVED (0) = OK, pointer provided + * CURLRESOLV_PENDING (1) = waiting for response, no pointer + */ + +enum resolve_t Curl_resolv(struct Curl_easy *data, + const char *hostname, + int port, + bool allowDOH, + struct Curl_dns_entry **entry) +{ + struct Curl_dns_entry *dns = NULL; + CURLcode result; + enum resolve_t rc = CURLRESOLV_ERROR; /* default to failure */ + struct connectdata *conn = data->conn; + /* We should intentionally error and not resolve .onion TLDs */ + size_t hostname_len = strlen(hostname); + if(hostname_len >= 7 && + (curl_strequal(&hostname[hostname_len - 6], ".onion") || + curl_strequal(&hostname[hostname_len - 7], ".onion."))) { + failf(data, "Not resolving .onion address (RFC 7686)"); + return CURLRESOLV_ERROR; + } + *entry = NULL; +#ifndef CURL_DISABLE_DOH + conn->bits.doh = FALSE; /* default is not */ +#else + (void)allowDOH; +#endif + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + dns = fetch_addr(data, hostname, port); + + if(dns) { + infof(data, "Hostname %s was found in DNS cache", hostname); + dns->refcount++; /* we use it! */ + rc = CURLRESOLV_RESOLVED; + } + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + /* The entry was not in the cache. Resolve it to IP address */ + + struct Curl_addrinfo *addr = NULL; + int respwait = 0; +#if !defined(CURL_DISABLE_DOH) || !defined(USE_RESOLVE_ON_IPS) + struct in_addr in; +#endif +#ifndef CURL_DISABLE_DOH +#ifndef USE_RESOLVE_ON_IPS + const +#endif + bool ipnum = FALSE; +#endif + + /* notify the resolver start callback */ + if(data->set.resolver_start) { + int st; + Curl_set_in_callback(data, TRUE); + st = data->set.resolver_start( +#ifdef USE_CURL_ASYNC + data->state.async.resolver, +#else + NULL, +#endif + NULL, + data->set.resolver_start_client); + Curl_set_in_callback(data, FALSE); + if(st) + return CURLRESOLV_ERROR; + } + +#ifndef USE_RESOLVE_ON_IPS + /* First check if this is an IPv4 address string */ + if(Curl_inet_pton(AF_INET, hostname, &in) > 0) { + /* This is a dotted IP address 123.123.123.123-style */ + addr = Curl_ip2addr(AF_INET, &in, hostname, port); + if(!addr) + return CURLRESOLV_ERROR; + } +#ifdef USE_IPV6 + else { + struct in6_addr in6; + /* check if this is an IPv6 address string */ + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) { + /* This is an IPv6 address literal */ + addr = Curl_ip2addr(AF_INET6, &in6, hostname, port); + if(!addr) + return CURLRESOLV_ERROR; + } + } +#endif /* USE_IPV6 */ + +#else /* if USE_RESOLVE_ON_IPS */ +#ifndef CURL_DISABLE_DOH + /* First check if this is an IPv4 address string */ + if(Curl_inet_pton(AF_INET, hostname, &in) > 0) + /* This is a dotted IP address 123.123.123.123-style */ + ipnum = TRUE; +#ifdef USE_IPV6 + else { + struct in6_addr in6; + /* check if this is an IPv6 address string */ + if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0) + /* This is an IPv6 address literal */ + ipnum = TRUE; + } +#endif /* USE_IPV6 */ +#endif /* CURL_DISABLE_DOH */ + +#endif /* !USE_RESOLVE_ON_IPS */ + + if(!addr) { + if(conn->ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data)) + return CURLRESOLV_ERROR; + + if(strcasecompare(hostname, "localhost") || + strcasecompare(hostname, "localhost.") || + tailmatch(hostname, ".localhost") || + tailmatch(hostname, ".localhost.")) + addr = get_localhost(port, hostname); +#ifndef CURL_DISABLE_DOH + else if(allowDOH && data->set.doh && !ipnum) + addr = Curl_doh(data, hostname, port, &respwait); +#endif + else { + /* Check what IP specifics the app has requested and if we can provide + * it. If not, bail out. */ + if(!Curl_ipvalid(data, conn)) + return CURLRESOLV_ERROR; + /* If Curl_getaddrinfo() returns NULL, 'respwait' might be set to a + non-zero value indicating that we need to wait for the response to + the resolve call */ + addr = Curl_getaddrinfo(data, hostname, port, &respwait); + } + } + if(!addr) { + if(respwait) { + /* the response to our resolve call will come asynchronously at + a later time, good or bad */ + /* First, check that we have not received the info by now */ + result = Curl_resolv_check(data, &dns); + if(result) /* error detected */ + return CURLRESOLV_ERROR; + if(dns) + rc = CURLRESOLV_RESOLVED; /* pointer provided */ + else + rc = CURLRESOLV_PENDING; /* no info yet */ + } + } + else { + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* we got a response, store it in the cache */ + dns = Curl_cache_addr(data, addr, hostname, 0, port, FALSE); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) + /* returned failure, bail out nicely */ + Curl_freeaddrinfo(addr); + else { + rc = CURLRESOLV_RESOLVED; + show_resolve_info(data, dns); + } + } + } + + *entry = dns; + + return rc; +} + +#ifdef USE_ALARM_TIMEOUT +/* + * This signal handler jumps back into the main libcurl code and continues + * execution. This effectively causes the remainder of the application to run + * within a signal handler which is nonportable and could lead to problems. + */ +CURL_NORETURN static +void alarmfunc(int sig) +{ + (void)sig; + siglongjmp(curl_jmpenv, 1); +} +#endif /* USE_ALARM_TIMEOUT */ + +/* + * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a + * timeout. This function might return immediately if we are using asynch + * resolves. See the return codes. + * + * The cache entry we return will get its 'inuse' counter increased when this + * function is used. You MUST call Curl_resolv_unlink() later (when you are + * done using this struct) to decrease the reference counter again. + * + * If built with a synchronous resolver and use of signals is not + * disabled by the application, then a nonzero timeout will cause a + * timeout after the specified number of milliseconds. Otherwise, timeout + * is ignored. + * + * Return codes: + * + * CURLRESOLV_TIMEDOUT(-2) = warning, time too short or previous alarm expired + * CURLRESOLV_ERROR (-1) = error, no pointer + * CURLRESOLV_RESOLVED (0) = OK, pointer provided + * CURLRESOLV_PENDING (1) = waiting for response, no pointer + */ + +enum resolve_t Curl_resolv_timeout(struct Curl_easy *data, + const char *hostname, + int port, + struct Curl_dns_entry **entry, + timediff_t timeoutms) +{ +#ifdef USE_ALARM_TIMEOUT +#ifdef HAVE_SIGACTION + struct sigaction keep_sigact; /* store the old struct here */ + volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */ + struct sigaction sigact; +#else +#ifdef HAVE_SIGNAL + void (*keep_sigact)(int); /* store the old handler here */ +#endif /* HAVE_SIGNAL */ +#endif /* HAVE_SIGACTION */ + volatile long timeout; + volatile unsigned int prev_alarm = 0; +#endif /* USE_ALARM_TIMEOUT */ + enum resolve_t rc; + + *entry = NULL; + + if(timeoutms < 0) + /* got an already expired timeout */ + return CURLRESOLV_TIMEDOUT; + +#ifdef USE_ALARM_TIMEOUT + if(data->set.no_signal) + /* Ignore the timeout when signals are disabled */ + timeout = 0; + else + timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms; + + if(!timeout) + /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */ + return Curl_resolv(data, hostname, port, TRUE, entry); + + if(timeout < 1000) { + /* The alarm() function only provides integer second resolution, so if + we want to wait less than one second we must bail out already now. */ + failf(data, + "remaining timeout of %ld too small to resolve via SIGALRM method", + timeout); + return CURLRESOLV_TIMEDOUT; + } + /* This allows us to time-out from the name resolver, as the timeout + will generate a signal and we will siglongjmp() from that here. + This technique has problems (see alarmfunc). + This should be the last thing we do before calling Curl_resolv(), + as otherwise we would have to worry about variables that get modified + before we invoke Curl_resolv() (and thus use "volatile"). */ + curl_simple_lock_lock(&curl_jmpenv_lock); + + if(sigsetjmp(curl_jmpenv, 1)) { + /* this is coming from a siglongjmp() after an alarm signal */ + failf(data, "name lookup timed out"); + rc = CURLRESOLV_ERROR; + goto clean_up; + } + else { + /************************************************************* + * Set signal handler to catch SIGALRM + * Store the old value to be able to set it back later! + *************************************************************/ +#ifdef HAVE_SIGACTION + sigaction(SIGALRM, NULL, &sigact); + keep_sigact = sigact; + keep_copysig = TRUE; /* yes, we have a copy */ + sigact.sa_handler = alarmfunc; +#ifdef SA_RESTART + /* HP-UX does not have SA_RESTART but defaults to that behavior! */ + sigact.sa_flags &= ~SA_RESTART; +#endif + /* now set the new struct */ + sigaction(SIGALRM, &sigact, NULL); +#else /* HAVE_SIGACTION */ + /* no sigaction(), revert to the much lamer signal() */ +#ifdef HAVE_SIGNAL + keep_sigact = signal(SIGALRM, alarmfunc); +#endif +#endif /* HAVE_SIGACTION */ + + /* alarm() makes a signal get sent when the timeout fires off, and that + will abort system calls */ + prev_alarm = alarm(curlx_sltoui(timeout/1000L)); + } + +#else +#ifndef CURLRES_ASYNCH + if(timeoutms) + infof(data, "timeout on name lookup is not supported"); +#else + (void)timeoutms; /* timeoutms not used with an async resolver */ +#endif +#endif /* USE_ALARM_TIMEOUT */ + + /* Perform the actual name resolution. This might be interrupted by an + * alarm if it takes too long. + */ + rc = Curl_resolv(data, hostname, port, TRUE, entry); + +#ifdef USE_ALARM_TIMEOUT +clean_up: + + if(!prev_alarm) + /* deactivate a possibly active alarm before uninstalling the handler */ + alarm(0); + +#ifdef HAVE_SIGACTION + if(keep_copysig) { + /* we got a struct as it looked before, now put that one back nice + and clean */ + sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */ + } +#else +#ifdef HAVE_SIGNAL + /* restore the previous SIGALRM handler */ + signal(SIGALRM, keep_sigact); +#endif +#endif /* HAVE_SIGACTION */ + + curl_simple_lock_unlock(&curl_jmpenv_lock); + + /* switch back the alarm() to either zero or to what it was before minus + the time we spent until now! */ + if(prev_alarm) { + /* there was an alarm() set before us, now put it back */ + timediff_t elapsed_secs = Curl_timediff(Curl_now(), + data->conn->created) / 1000; + + /* the alarm period is counted in even number of seconds */ + unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs); + + if(!alarm_set || + ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) { + /* if the alarm time-left reached zero or turned "negative" (counted + with unsigned values), we should fire off a SIGALRM here, but we + will not, and zero would be to switch it off so we never set it to + less than 1! */ + alarm(1); + rc = CURLRESOLV_TIMEDOUT; + failf(data, "Previous alarm fired off"); + } + else + alarm((unsigned int)alarm_set); + } +#endif /* USE_ALARM_TIMEOUT */ + + return rc; +} + +/* + * Curl_resolv_unlink() releases a reference to the given cached DNS entry. + * When the reference count reaches 0, the entry is destroyed. It is important + * that only one unlink is made for each Curl_resolv() call. + * + * May be called with 'data' == NULL for global cache. + */ +void Curl_resolv_unlink(struct Curl_easy *data, struct Curl_dns_entry **pdns) +{ + struct Curl_dns_entry *dns = *pdns; + *pdns = NULL; + if(data && data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + hostcache_unlink_entry(dns); + + if(data && data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + +/* + * File-internal: release cache dns entry reference, free if inuse drops to 0 + */ +static void hostcache_unlink_entry(void *entry) +{ + struct Curl_dns_entry *dns = (struct Curl_dns_entry *) entry; + DEBUGASSERT(dns && (dns->refcount > 0)); + + dns->refcount--; + if(dns->refcount == 0) { + Curl_freeaddrinfo(dns->addr); +#ifdef USE_HTTPSRR + if(dns->hinfo) { + if(dns->hinfo->target) + free(dns->hinfo->target); + if(dns->hinfo->alpns) + free(dns->hinfo->alpns); + if(dns->hinfo->ipv4hints) + free(dns->hinfo->ipv4hints); + if(dns->hinfo->echconfiglist) + free(dns->hinfo->echconfiglist); + if(dns->hinfo->ipv6hints) + free(dns->hinfo->ipv6hints); + if(dns->hinfo->val) + free(dns->hinfo->val); + free(dns->hinfo); + } +#endif + free(dns); + } +} + +/* + * Curl_init_dnscache() inits a new DNS cache. + */ +void Curl_init_dnscache(struct Curl_hash *hash, size_t size) +{ + Curl_hash_init(hash, size, Curl_hash_str, Curl_str_key_compare, + hostcache_unlink_entry); +} + +/* + * Curl_hostcache_clean() + * + * This _can_ be called with 'data' == NULL but then of course no locking + * can be done! + */ + +void Curl_hostcache_clean(struct Curl_easy *data, + struct Curl_hash *hash) +{ + if(data && data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + Curl_hash_clean(hash); + + if(data && data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); +} + + +CURLcode Curl_loadhostpairs(struct Curl_easy *data) +{ + struct curl_slist *hostp; + char *host_end; + + /* Default is no wildcard found */ + data->state.wildcard_resolve = FALSE; + + for(hostp = data->state.resolve; hostp; hostp = hostp->next) { + char entry_id[MAX_HOSTCACHE_LEN]; + if(!hostp->data) + continue; + if(hostp->data[0] == '-') { + unsigned long num = 0; + size_t entry_len; + size_t hlen = 0; + host_end = strchr(&hostp->data[1], ':'); + + if(host_end) { + hlen = host_end - &hostp->data[1]; + num = strtoul(++host_end, NULL, 10); + if(!hlen || (num > 0xffff)) + host_end = NULL; + } + if(!host_end) { + infof(data, "Bad syntax CURLOPT_RESOLVE removal entry '%s'", + hostp->data); + continue; + } + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(&hostp->data[1], hlen, (int)num, + entry_id, sizeof(entry_id)); + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* delete entry, ignore if it did not exist */ + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + } + else { + struct Curl_dns_entry *dns; + struct Curl_addrinfo *head = NULL, *tail = NULL; + size_t entry_len; + char address[64]; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + char *addresses = NULL; +#endif + char *addr_begin; + char *addr_end; + char *port_ptr; + int port = 0; + char *end_ptr; + bool permanent = TRUE; + unsigned long tmp_port; + bool error = TRUE; + char *host_begin = hostp->data; + size_t hlen = 0; + + if(host_begin[0] == '+') { + host_begin++; + permanent = FALSE; + } + host_end = strchr(host_begin, ':'); + if(!host_end) + goto err; + hlen = host_end - host_begin; + + port_ptr = host_end + 1; + tmp_port = strtoul(port_ptr, &end_ptr, 10); + if(tmp_port > USHRT_MAX || end_ptr == port_ptr || *end_ptr != ':') + goto err; + + port = (int)tmp_port; +#if !defined(CURL_DISABLE_VERBOSE_STRINGS) + addresses = end_ptr + 1; +#endif + + while(*end_ptr) { + size_t alen; + struct Curl_addrinfo *ai; + + addr_begin = end_ptr + 1; + addr_end = strchr(addr_begin, ','); + if(!addr_end) + addr_end = addr_begin + strlen(addr_begin); + end_ptr = addr_end; + + /* allow IP(v6) address within [brackets] */ + if(*addr_begin == '[') { + if(addr_end == addr_begin || *(addr_end - 1) != ']') + goto err; + ++addr_begin; + --addr_end; + } + + alen = addr_end - addr_begin; + if(!alen) + continue; + + if(alen >= sizeof(address)) + goto err; + + memcpy(address, addr_begin, alen); + address[alen] = '\0'; + +#ifndef USE_IPV6 + if(strchr(address, ':')) { + infof(data, "Ignoring resolve address '%s', missing IPv6 support.", + address); + continue; + } +#endif + + ai = Curl_str2addr(address, port); + if(!ai) { + infof(data, "Resolve address '%s' found illegal", address); + goto err; + } + + if(tail) { + tail->ai_next = ai; + tail = tail->ai_next; + } + else { + head = tail = ai; + } + } + + if(!head) + goto err; + + error = FALSE; +err: + if(error) { + failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'", + hostp->data); + Curl_freeaddrinfo(head); + return CURLE_SETOPT_OPTION_SYNTAX; + } + + /* Create an entry id, based upon the hostname and port */ + entry_len = create_hostcache_id(host_begin, hlen, port, + entry_id, sizeof(entry_id)); + + if(data->share) + Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); + + /* See if it is already in our dns cache */ + dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1); + + if(dns) { + infof(data, "RESOLVE %.*s:%d - old addresses discarded", + (int)hlen, host_begin, port); + /* delete old entry, there are two reasons for this + 1. old entry may have different addresses. + 2. even if entry with correct addresses is already in the cache, + but if it is close to expire, then by the time next http + request is made, it can get expired and pruned because old + entry is not necessarily marked as permanent. + 3. when adding a non-permanent entry, we want it to remove and + replace an existing permanent entry. + 4. when adding a non-permanent entry, we want it to get a "fresh" + timeout that starts _now_. */ + + Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1); + } + + /* put this new host in the cache */ + dns = Curl_cache_addr(data, head, host_begin, hlen, port, permanent); + if(dns) { + /* release the returned reference; the cache itself will keep the + * entry alive: */ + dns->refcount--; + } + + if(data->share) + Curl_share_unlock(data, CURL_LOCK_DATA_DNS); + + if(!dns) { + Curl_freeaddrinfo(head); + return CURLE_OUT_OF_MEMORY; + } +#ifndef CURL_DISABLE_VERBOSE_STRINGS + infof(data, "Added %.*s:%d:%s to DNS cache%s", + (int)hlen, host_begin, port, addresses, + permanent ? "" : " (non-permanent)"); +#endif + + /* Wildcard hostname */ + if((hlen == 1) && (host_begin[0] == '*')) { + infof(data, "RESOLVE *:%d using wildcard", port); + data->state.wildcard_resolve = TRUE; + } + } + } + data->state.resolve = NULL; /* dealt with now */ + + return CURLE_OK; +} + +#ifndef CURL_DISABLE_VERBOSE_STRINGS +static void show_resolve_info(struct Curl_easy *data, + struct Curl_dns_entry *dns) +{ + struct Curl_addrinfo *a; + CURLcode result = CURLE_OK; +#ifdef CURLRES_IPV6 + struct dynbuf out[2]; +#else + struct dynbuf out[1]; +#endif + DEBUGASSERT(data); + DEBUGASSERT(dns); + + if(!data->set.verbose || + /* ignore no name or numerical IP addresses */ + !dns->hostname[0] || Curl_host_is_ipnum(dns->hostname)) + return; + + a = dns->addr; + + infof(data, "Host %s:%d was resolved.", + (dns->hostname[0] ? dns->hostname : "(none)"), dns->hostport); + + Curl_dyn_init(&out[0], 1024); +#ifdef CURLRES_IPV6 + Curl_dyn_init(&out[1], 1024); +#endif + + while(a) { + if( +#ifdef CURLRES_IPV6 + a->ai_family == PF_INET6 || +#endif + a->ai_family == PF_INET) { + char buf[MAX_IPADR_LEN]; + struct dynbuf *d = &out[(a->ai_family != PF_INET)]; + Curl_printable_address(a, buf, sizeof(buf)); + if(Curl_dyn_len(d)) + result = Curl_dyn_addn(d, ", ", 2); + if(!result) + result = Curl_dyn_add(d, buf); + if(result) { + infof(data, "too many IP, cannot show"); + goto fail; + } + } + a = a->ai_next; + } + +#ifdef CURLRES_IPV6 + infof(data, "IPv6: %s", + (Curl_dyn_len(&out[1]) ? Curl_dyn_ptr(&out[1]) : "(none)")); +#endif + infof(data, "IPv4: %s", + (Curl_dyn_len(&out[0]) ? Curl_dyn_ptr(&out[0]) : "(none)")); + +fail: + Curl_dyn_free(&out[0]); +#ifdef CURLRES_IPV6 + Curl_dyn_free(&out[1]); +#endif +} +#endif + +CURLcode Curl_resolv_check(struct Curl_easy *data, + struct Curl_dns_entry **dns) +{ + CURLcode result; +#if defined(CURL_DISABLE_DOH) && !defined(CURLRES_ASYNCH) + (void)data; + (void)dns; +#endif +#ifndef CURL_DISABLE_DOH + if(data->conn->bits.doh) { + result = Curl_doh_is_resolved(data, dns); + } + else +#endif + result = Curl_resolver_is_resolved(data, dns); + if(*dns) + show_resolve_info(data, *dns); + return result; +} + +int Curl_resolv_getsock(struct Curl_easy *data, + curl_socket_t *socks) +{ +#ifdef CURLRES_ASYNCH +#ifndef CURL_DISABLE_DOH + if(data->conn->bits.doh) + /* nothing to wait for during DoH resolve, those handles have their own + sockets */ + return GETSOCK_BLANK; +#endif + return Curl_resolver_getsock(data, socks); +#else + (void)data; + (void)socks; + return GETSOCK_BLANK; +#endif +} + +/* Call this function after Curl_connect() has returned async=TRUE and + then a successful name resolve has been received. + + Note: this function disconnects and frees the conn data in case of + resolve failure */ +CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_done) +{ + CURLcode result; + struct connectdata *conn = data->conn; + +#ifdef USE_CURL_ASYNC + if(data->state.async.dns) { + conn->dns_entry = data->state.async.dns; + data->state.async.dns = NULL; + } +#endif + + result = Curl_setup_conn(data, protocol_done); + + if(result) { + Curl_detach_connection(data); + Curl_cpool_disconnect(data, conn, TRUE); + } + return result; +} + +/* + * Curl_resolver_error() calls failf() with the appropriate message after a + * resolve error + */ + +#ifdef USE_CURL_ASYNC +CURLcode Curl_resolver_error(struct Curl_easy *data) +{ + const char *host_or_proxy; + CURLcode result; + +#ifndef CURL_DISABLE_PROXY + struct connectdata *conn = data->conn; + if(conn->bits.httpproxy) { + host_or_proxy = "proxy"; + result = CURLE_COULDNT_RESOLVE_PROXY; + } + else +#endif + { + host_or_proxy = "host"; + result = CURLE_COULDNT_RESOLVE_HOST; + } + + failf(data, "Could not resolve %s: %s", host_or_proxy, + data->state.async.hostname); + + return result; +} +#endif /* USE_CURL_ASYNC */ diff --git a/local-test-curl-full-01/afc-curl/lib/hostip.h b/local-test-curl-full-01/afc-curl/lib/hostip.h new file mode 100644 index 0000000000000000000000000000000000000000..b1c5ecb2e1b72e287de3a546af6ea435b54c3abe --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/hostip.h @@ -0,0 +1,267 @@ +#ifndef HEADER_CURL_HOSTIP_H +#define HEADER_CURL_HOSTIP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include "hash.h" +#include "curl_addrinfo.h" +#include "timeval.h" /* for timediff_t */ +#include "asyn.h" + +#include + +#ifdef USE_HTTPSRR +# include +#endif + +/* Allocate enough memory to hold the full name information structs and + * everything. OSF1 is known to require at least 8872 bytes. The buffer + * required for storing all possible aliases and IP numbers is according to + * Stevens' Unix Network Programming 2nd edition, p. 304: 8192 bytes! + */ +#define CURL_HOSTENT_SIZE 9000 + +#define CURL_TIMEOUT_RESOLVE 300 /* when using asynch methods, we allow this + many seconds for a name resolve */ + +#define CURL_ASYNC_SUCCESS CURLE_OK + +struct addrinfo; +struct hostent; +struct Curl_easy; +struct connectdata; + +/* + * Curl_global_host_cache_init() initializes and sets up a global DNS cache. + * Global DNS cache is general badness. Do not use. This will be removed in + * a future version. Use the share interface instead! + * + * Returns a struct Curl_hash pointer on success, NULL on failure. + */ +struct Curl_hash *Curl_global_host_cache_init(void); + +#ifdef USE_HTTPSRR + +#define CURL_MAXLEN_host_name 253 + +struct Curl_https_rrinfo { + size_t len; /* raw encoded length */ + unsigned char *val; /* raw encoded octets */ + /* + * fields from HTTPS RR, with the mandatory fields + * first (priority, target), then the others in the + * order of the keytag numbers defined at + * https://datatracker.ietf.org/doc/html/rfc9460#section-14.3.2 + */ + uint16_t priority; + char *target; + char *alpns; /* keytag = 1 */ + bool no_def_alpn; /* keytag = 2 */ + /* + * we do not support ports (keytag = 3) as we do not support + * port-switching yet + */ + unsigned char *ipv4hints; /* keytag = 4 */ + size_t ipv4hints_len; + unsigned char *echconfiglist; /* keytag = 5 */ + size_t echconfiglist_len; + unsigned char *ipv6hints; /* keytag = 6 */ + size_t ipv6hints_len; +}; +#endif + +struct Curl_dns_entry { + struct Curl_addrinfo *addr; +#ifdef USE_HTTPSRR + struct Curl_https_rrinfo *hinfo; +#endif + /* timestamp == 0 -- permanent CURLOPT_RESOLVE entry (does not time out) */ + time_t timestamp; + /* reference counter, entry is freed on reaching 0 */ + size_t refcount; + /* hostname port number that resolved to addr. */ + int hostport; + /* hostname that resolved to addr. may be NULL (Unix domain sockets). */ + char hostname[1]; +}; + +bool Curl_host_is_ipnum(const char *hostname); + +/* + * Curl_resolv() returns an entry with the info for the specified host + * and port. + * + * The returned data *MUST* be "released" with Curl_resolv_unlink() after + * use, or we will leak memory! + */ +/* return codes */ +enum resolve_t { + CURLRESOLV_TIMEDOUT = -2, + CURLRESOLV_ERROR = -1, + CURLRESOLV_RESOLVED = 0, + CURLRESOLV_PENDING = 1 +}; +enum resolve_t Curl_resolv(struct Curl_easy *data, + const char *hostname, + int port, + bool allowDOH, + struct Curl_dns_entry **dnsentry); +enum resolve_t Curl_resolv_timeout(struct Curl_easy *data, + const char *hostname, int port, + struct Curl_dns_entry **dnsentry, + timediff_t timeoutms); + +#ifdef USE_IPV6 +/* + * Curl_ipv6works() returns TRUE if IPv6 seems to work. + */ +bool Curl_ipv6works(struct Curl_easy *data); +#else +#define Curl_ipv6works(x) FALSE +#endif + +/* + * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've + * been set and returns TRUE if they are OK. + */ +bool Curl_ipvalid(struct Curl_easy *data, struct connectdata *conn); + + +/* + * Curl_getaddrinfo() is the generic low-level name resolve API within this + * source file. There are several versions of this function - for different + * name resolve layers (selected at build-time). They all take this same set + * of arguments + */ +struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data, + const char *hostname, + int port, + int *waitp); + + +/* unlink a dns entry, potentially shared with a cache */ +void Curl_resolv_unlink(struct Curl_easy *data, + struct Curl_dns_entry **pdns); + +/* init a new dns cache */ +void Curl_init_dnscache(struct Curl_hash *hash, size_t hashsize); + +/* prune old entries from the DNS cache */ +void Curl_hostcache_prune(struct Curl_easy *data); + +/* IPv4 threadsafe resolve function used for synch and asynch builds */ +struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port); + +CURLcode Curl_once_resolved(struct Curl_easy *data, bool *protocol_connect); + +/* + * Curl_addrinfo_callback() is used when we build with any asynch specialty. + * Handles end of async request processing. Inserts ai into hostcache when + * status is CURL_ASYNC_SUCCESS. Twiddles fields in conn to indicate async + * request completed whether successful or failed. + */ +CURLcode Curl_addrinfo_callback(struct Curl_easy *data, + int status, + struct Curl_addrinfo *ai); + +/* + * Curl_printable_address() returns a printable version of the 1st address + * given in the 'ip' argument. The result will be stored in the buf that is + * bufsize bytes big. + */ +void Curl_printable_address(const struct Curl_addrinfo *ip, + char *buf, size_t bufsize); + +/* + * Curl_fetch_addr() fetches a 'Curl_dns_entry' already in the DNS cache. + * + * Returns the Curl_dns_entry entry pointer or NULL if not in the cache. + * + * The returned data *MUST* be "released" with Curl_resolv_unlink() after + * use, or we will leak memory! + */ +struct Curl_dns_entry * +Curl_fetch_addr(struct Curl_easy *data, + const char *hostname, + int port); + +/* + * Curl_cache_addr() stores a 'Curl_addrinfo' struct in the DNS cache. + * @param permanent iff TRUE, entry will never become stale + * Returns the Curl_dns_entry entry pointer or NULL if the storage failed. + */ +struct Curl_dns_entry * +Curl_cache_addr(struct Curl_easy *data, struct Curl_addrinfo *addr, + const char *hostname, size_t hostlen, int port, + bool permanent); + +#ifndef INADDR_NONE +#define CURL_INADDR_NONE (in_addr_t) ~0 +#else +#define CURL_INADDR_NONE INADDR_NONE +#endif + +/* + * Function provided by the resolver backend to set DNS servers to use. + */ +CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers); + +/* + * Function provided by the resolver backend to set + * outgoing interface to use for DNS requests + */ +CURLcode Curl_set_dns_interface(struct Curl_easy *data, + const char *interf); + +/* + * Function provided by the resolver backend to set + * local IPv4 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, + const char *local_ip4); + +/* + * Function provided by the resolver backend to set + * local IPv6 address to use as source address for DNS requests + */ +CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, + const char *local_ip6); + +/* + * Clean off entries from the cache + */ +void Curl_hostcache_clean(struct Curl_easy *data, struct Curl_hash *hash); + +/* + * Populate the cache with specified entries from CURLOPT_RESOLVE. + */ +CURLcode Curl_loadhostpairs(struct Curl_easy *data); +CURLcode Curl_resolv_check(struct Curl_easy *data, + struct Curl_dns_entry **dns); +int Curl_resolv_getsock(struct Curl_easy *data, + curl_socket_t *socks); + +CURLcode Curl_resolver_error(struct Curl_easy *data); +#endif /* HEADER_CURL_HOSTIP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/hsts.h b/local-test-curl-full-01/afc-curl/lib/hsts.h new file mode 100644 index 0000000000000000000000000000000000000000..1c544f97bd8a081a974a53e934730af9c5a781e7 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/hsts.h @@ -0,0 +1,69 @@ +#ifndef HEADER_CURL_HSTS_H +#define HEADER_CURL_HSTS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) +#include +#include "llist.h" + +#if defined(DEBUGBUILD) || defined(UNITTESTS) +extern time_t deltatime; +#endif + +struct stsentry { + struct Curl_llist_node node; + const char *host; + bool includeSubDomains; + curl_off_t expires; /* the timestamp of this entry's expiry */ +}; + +/* The HSTS cache. Needs to be able to tailmatch hostnames. */ +struct hsts { + struct Curl_llist list; + char *filename; + unsigned int flags; +}; + +struct hsts *Curl_hsts_init(void); +void Curl_hsts_cleanup(struct hsts **hp); +CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, + const char *sts); +struct stsentry *Curl_hsts(struct hsts *h, const char *hostname, + bool subdomain); +CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, + const char *file); +CURLcode Curl_hsts_loadfile(struct Curl_easy *data, + struct hsts *h, const char *file); +CURLcode Curl_hsts_loadcb(struct Curl_easy *data, + struct hsts *h); +void Curl_hsts_loadfiles(struct Curl_easy *data); +#else +#define Curl_hsts_cleanup(x) +#define Curl_hsts_loadcb(x,y) CURLE_OK +#define Curl_hsts_save(x,y,z) +#define Curl_hsts_loadfiles(x) +#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */ +#endif /* HEADER_CURL_HSTS_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/http.h b/local-test-curl-full-01/afc-curl/lib/http.h new file mode 100644 index 0000000000000000000000000000000000000000..7056e8a8ed10bc538663ebf84c3fef23212e5a1f --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http.h @@ -0,0 +1,293 @@ +#ifndef HEADER_CURL_HTTP_H +#define HEADER_CURL_HTTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MSH3) && !defined(_WIN32) +#include +#endif + +#include "bufq.h" +#include "dynhds.h" +#include "ws.h" + +typedef enum { + HTTPREQ_GET, + HTTPREQ_POST, + HTTPREQ_POST_FORM, /* we make a difference internally */ + HTTPREQ_POST_MIME, /* we make a difference internally */ + HTTPREQ_PUT, + HTTPREQ_HEAD +} Curl_HttpReq; + +#ifndef CURL_DISABLE_HTTP + +#if defined(USE_HTTP3) +#include +#endif + +extern const struct Curl_handler Curl_handler_http; + +#ifdef USE_SSL +extern const struct Curl_handler Curl_handler_https; +#endif + +struct dynhds; + +CURLcode Curl_bump_headersize(struct Curl_easy *data, + size_t delta, + bool connect_only); + +/* Header specific functions */ +bool Curl_compareheader(const char *headerline, /* line to check */ + const char *header, /* header keyword _with_ colon */ + const size_t hlen, /* len of the keyword in bytes */ + const char *content, /* content string to find */ + const size_t clen); /* len of the content in bytes */ + +char *Curl_copy_header_value(const char *header); + +char *Curl_checkProxyheaders(struct Curl_easy *data, + const struct connectdata *conn, + const char *thisheader, + const size_t thislen); + +CURLcode Curl_add_timecondition(struct Curl_easy *data, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *headers +#endif + ); +CURLcode Curl_add_custom_headers(struct Curl_easy *data, + bool is_connect, +#ifndef USE_HYPER + struct dynbuf *req +#else + void *headers +#endif + ); + +void Curl_http_method(struct Curl_easy *data, struct connectdata *conn, + const char **method, Curl_HttpReq *); +CURLcode Curl_http_useragent(struct Curl_easy *data); +CURLcode Curl_http_host(struct Curl_easy *data, struct connectdata *conn); +CURLcode Curl_http_target(struct Curl_easy *data, struct connectdata *conn, + struct dynbuf *req); +CURLcode Curl_http_statusline(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_http_header(struct Curl_easy *data, + const char *hd, size_t hdlen); +CURLcode Curl_transferencode(struct Curl_easy *data); +CURLcode Curl_http_req_set_reader(struct Curl_easy *data, + Curl_HttpReq httpreq, + const char **tep); +CURLcode Curl_http_req_complete(struct Curl_easy *data, + struct dynbuf *r, Curl_HttpReq httpreq); +bool Curl_use_http_1_1plus(const struct Curl_easy *data, + const struct connectdata *conn); +#ifndef CURL_DISABLE_COOKIES +CURLcode Curl_http_cookies(struct Curl_easy *data, + struct connectdata *conn, + struct dynbuf *r); +#else +#define Curl_http_cookies(a,b,c) CURLE_OK +#endif +CURLcode Curl_http_range(struct Curl_easy *data, + Curl_HttpReq httpreq); +CURLcode Curl_http_firstwrite(struct Curl_easy *data); + +/* protocol-specific functions set up to be called by the main engine */ +CURLcode Curl_http_setup_conn(struct Curl_easy *data, + struct connectdata *conn); +CURLcode Curl_http(struct Curl_easy *data, bool *done); +CURLcode Curl_http_done(struct Curl_easy *data, CURLcode, bool premature); +CURLcode Curl_http_connect(struct Curl_easy *data, bool *done); +int Curl_http_getsock_do(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +CURLcode Curl_http_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); +CURLcode Curl_http_write_resp_hd(struct Curl_easy *data, + const char *hd, size_t hdlen, + bool is_eos); + +/* These functions are in http.c */ +CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy, + const char *auth); +CURLcode Curl_http_auth_act(struct Curl_easy *data); + +/* If only the PICKNONE bit is set, there has been a round-trip and we + selected to use no auth at all. Ie, we actively select no auth, as opposed + to not having one selected. The other CURLAUTH_* defines are present in the + public curl/curl.h header. */ +#define CURLAUTH_PICKNONE (1<<30) /* do not use auth */ + +/* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST + data get included in the initial data chunk sent to the server. If the + data is larger than this, it will automatically get split up in multiple + system calls. + + This value used to be fairly big (100K), but we must take into account that + if the server rejects the POST due for authentication reasons, this data + will always be unconditionally sent and thus it may not be larger than can + always be afforded to send twice. + + It must not be greater than 64K to work on VMS. +*/ +#ifndef MAX_INITIAL_POST_SIZE +#define MAX_INITIAL_POST_SIZE (64*1024) +#endif + +/* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will + * automatically add an "Expect: 100-continue" header in HTTP requests. When + * the size is unknown, it will always add it. + * + */ +#ifndef EXPECT_100_THRESHOLD +#define EXPECT_100_THRESHOLD (1024*1024) +#endif + +/* MAX_HTTP_RESP_HEADER_SIZE is the maximum size of all response headers + combined that libcurl allows for a single HTTP response, any HTTP + version. This count includes CONNECT response headers. */ +#define MAX_HTTP_RESP_HEADER_SIZE (300*1024) + +bool Curl_http_exp100_is_selected(struct Curl_easy *data); +void Curl_http_exp100_got100(struct Curl_easy *data); + +#endif /* CURL_DISABLE_HTTP */ + +/**************************************************************************** + * HTTP unique setup + ***************************************************************************/ + +CURLcode Curl_http_size(struct Curl_easy *data); + +CURLcode Curl_http_write_resp_hds(struct Curl_easy *data, + const char *buf, size_t blen, + size_t *pconsumed); + +/** + * Curl_http_output_auth() setups the authentication headers for the + * host/proxy and the correct authentication + * method. data->state.authdone is set to TRUE when authentication is + * done. + * + * @param data all information about the current transfer + * @param conn all information about the current connection + * @param request pointer to the request keyword + * @param httpreq is the request type + * @param path pointer to the requested path + * @param proxytunnel boolean if this is the request setting up a "proxy + * tunnel" + * + * @returns CURLcode + */ +CURLcode +Curl_http_output_auth(struct Curl_easy *data, + struct connectdata *conn, + const char *request, + Curl_HttpReq httpreq, + const char *path, + bool proxytunnel); /* TRUE if this is the request setting + up the proxy tunnel */ + +/* Decode HTTP status code string. */ +CURLcode Curl_http_decode_status(int *pstatus, const char *s, size_t len); + + +/** + * All about a core HTTP request, excluding body and trailers + */ +struct httpreq { + char method[24]; + char *scheme; + char *authority; + char *path; + struct dynhds headers; + struct dynhds trailers; +}; + +/** + * Create an HTTP request struct. + */ +CURLcode Curl_http_req_make(struct httpreq **preq, + const char *method, size_t m_len, + const char *scheme, size_t s_len, + const char *authority, size_t a_len, + const char *path, size_t p_len); + +CURLcode Curl_http_req_make2(struct httpreq **preq, + const char *method, size_t m_len, + CURLU *url, const char *scheme_default); + +void Curl_http_req_free(struct httpreq *req); + +#define HTTP_PSEUDO_METHOD ":method" +#define HTTP_PSEUDO_SCHEME ":scheme" +#define HTTP_PSEUDO_AUTHORITY ":authority" +#define HTTP_PSEUDO_PATH ":path" +#define HTTP_PSEUDO_STATUS ":status" + +/** + * Create the list of HTTP/2 headers which represent the request, + * using HTTP/2 pseudo headers preceding the `req->headers`. + * + * Applies the following transformations: + * - if `authority` is set, any "Host" header is removed. + * - if `authority` is unset and a "Host" header is present, use + * that as `authority` and remove "Host" + * - removes and Connection header fields as defined in rfc9113 ch. 8.2.2 + * - lower-cases the header field names + * + * @param h2_headers will contain the HTTP/2 headers on success + * @param req the request to transform + * @param data the handle to lookup defaults like ' :scheme' from + */ +CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers, + struct httpreq *req, struct Curl_easy *data); + +/** + * All about a core HTTP response, excluding body and trailers + */ +struct http_resp { + int status; + char *description; + struct dynhds headers; + struct dynhds trailers; + struct http_resp *prev; +}; + +/** + * Create an HTTP response struct. + */ +CURLcode Curl_http_resp_make(struct http_resp **presp, + int status, + const char *description); + +void Curl_http_resp_free(struct http_resp *resp); + +#endif /* HEADER_CURL_HTTP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/http1.c b/local-test-curl-full-01/afc-curl/lib/http1.c new file mode 100644 index 0000000000000000000000000000000000000000..f135b2072a2451d6e0386ebdfa52bec1886c9576 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http1.c @@ -0,0 +1,346 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP + +#include "urldata.h" +#include +#include "http.h" +#include "http1.h" +#include "urlapi-int.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define H1_MAX_URL_LEN (8*1024) + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len) +{ + memset(parser, 0, sizeof(*parser)); + parser->max_line_len = max_line_len; + Curl_dyn_init(&parser->scratch, max_line_len); +} + +void Curl_h1_req_parse_free(struct h1_req_parser *parser) +{ + if(parser) { + Curl_http_req_free(parser->req); + Curl_dyn_free(&parser->scratch); + parser->req = NULL; + parser->done = FALSE; + } +} + +static CURLcode trim_line(struct h1_req_parser *parser, int options) +{ + DEBUGASSERT(parser->line); + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\n') + --parser->line_len; + if(parser->line_len) { + if(parser->line[parser->line_len - 1] == '\r') + --parser->line_len; + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + } + else if(options & H1_PARSE_OPT_STRICT) + return CURLE_URL_MALFORMAT; + + if(parser->line_len > parser->max_line_len) { + return CURLE_URL_MALFORMAT; + } + return CURLE_OK; +} + +static ssize_t detect_line(struct h1_req_parser *parser, + const char *buf, const size_t buflen, + CURLcode *err) +{ + const char *line_end; + + DEBUGASSERT(!parser->line); + line_end = memchr(buf, '\n', buflen); + if(!line_end) { + *err = CURLE_AGAIN; + return -1; + } + parser->line = buf; + parser->line_len = line_end - buf + 1; + *err = CURLE_OK; + return (ssize_t)parser->line_len; +} + +static ssize_t next_line(struct h1_req_parser *parser, + const char *buf, const size_t buflen, int options, + CURLcode *err) +{ + ssize_t nread = 0; + + if(parser->line) { + parser->line = NULL; + parser->line_len = 0; + Curl_dyn_reset(&parser->scratch); + } + + nread = detect_line(parser, buf, buflen, err); + if(nread >= 0) { + if(Curl_dyn_len(&parser->scratch)) { + /* append detected line to scratch to have the complete line */ + *err = Curl_dyn_addn(&parser->scratch, parser->line, parser->line_len); + if(*err) + return -1; + parser->line = Curl_dyn_ptr(&parser->scratch); + parser->line_len = Curl_dyn_len(&parser->scratch); + } + *err = trim_line(parser, options); + if(*err) + return -1; + } + else if(*err == CURLE_AGAIN) { + /* no line end in `buf`, add it to our scratch */ + *err = Curl_dyn_addn(&parser->scratch, (const unsigned char *)buf, buflen); + nread = (*err) ? -1 : (ssize_t)buflen; + } + return nread; +} + +static CURLcode start_req(struct h1_req_parser *parser, + const char *scheme_default, int options) +{ + const char *p, *m, *target, *hv, *scheme, *authority, *path; + size_t m_len, target_len, hv_len, scheme_len, authority_len, path_len; + size_t i; + CURLU *url = NULL; + CURLcode result = CURLE_URL_MALFORMAT; /* Use this as default fail */ + + DEBUGASSERT(!parser->req); + /* line must match: "METHOD TARGET HTTP_VERSION" */ + p = memchr(parser->line, ' ', parser->line_len); + if(!p || p == parser->line) + goto out; + + m = parser->line; + m_len = p - parser->line; + target = p + 1; + target_len = hv_len = 0; + hv = NULL; + + /* URL may contain spaces so scan backwards */ + for(i = parser->line_len; i > m_len; --i) { + if(parser->line[i] == ' ') { + hv = &parser->line[i + 1]; + hv_len = parser->line_len - i; + target_len = (hv - target) - 1; + break; + } + } + /* no SPACE found or empty TARGET or empty HTTP_VERSION */ + if(!target_len || !hv_len) + goto out; + + /* TODO: we do not check HTTP_VERSION for conformity, should + + do that when STRICT option is supplied. */ + (void)hv; + + /* The TARGET can be (rfc 9112, ch. 3.2): + * origin-form: path + optional query + * absolute-form: absolute URI + * authority-form: host+port for CONNECT + * asterisk-form: '*' for OPTIONS + * + * from TARGET, we derive `scheme` `authority` `path` + * origin-form -- -- TARGET + * absolute-form URL* URL* URL* + * authority-form -- TARGET -- + * asterisk-form -- -- TARGET + */ + scheme = authority = path = NULL; + scheme_len = authority_len = path_len = 0; + + if(target_len == 1 && target[0] == '*') { + /* asterisk-form */ + path = target; + path_len = target_len; + } + else if(!strncmp("CONNECT", m, m_len)) { + /* authority-form */ + authority = target; + authority_len = target_len; + } + else if(target[0] == '/') { + /* origin-form */ + path = target; + path_len = target_len; + } + else { + /* origin-form OR absolute-form */ + CURLUcode uc; + char tmp[H1_MAX_URL_LEN]; + + /* default, unless we see an absolute URL */ + path = target; + path_len = target_len; + + /* URL parser wants 0-termination */ + if(target_len >= sizeof(tmp)) + goto out; + memcpy(tmp, target, target_len); + tmp[target_len] = '\0'; + /* See if treating TARGET as an absolute URL makes sense */ + if(Curl_is_absolute_url(tmp, NULL, 0, FALSE)) { + unsigned int url_options; + + url = curl_url(); + if(!url) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + url_options = (CURLU_NON_SUPPORT_SCHEME| + CURLU_PATH_AS_IS| + CURLU_NO_DEFAULT_PORT); + if(!(options & H1_PARSE_OPT_STRICT)) + url_options |= CURLU_ALLOW_SPACE; + uc = curl_url_set(url, CURLUPART_URL, tmp, url_options); + if(uc) { + goto out; + } + } + + if(!url && (options & H1_PARSE_OPT_STRICT)) { + /* we should have an absolute URL or have seen `/` earlier */ + goto out; + } + } + + if(url) { + result = Curl_http_req_make2(&parser->req, m, m_len, url, scheme_default); + } + else { + if(!scheme && scheme_default) { + scheme = scheme_default; + scheme_len = strlen(scheme_default); + } + result = Curl_http_req_make(&parser->req, m, m_len, scheme, scheme_len, + authority, authority_len, path, path_len); + } + +out: + curl_url_cleanup(url); + return result; +} + +ssize_t Curl_h1_req_parse_read(struct h1_req_parser *parser, + const char *buf, size_t buflen, + const char *scheme_default, int options, + CURLcode *err) +{ + ssize_t nread = 0, n; + + *err = CURLE_OK; + while(!parser->done) { + n = next_line(parser, buf, buflen, options, err); + if(n < 0) { + if(*err != CURLE_AGAIN) { + nread = -1; + } + *err = CURLE_OK; + goto out; + } + + /* Consume this line */ + nread += (size_t)n; + buf += (size_t)n; + buflen -= (size_t)n; + + if(!parser->line) { + /* consumed bytes, but line not complete */ + if(!buflen) + goto out; + } + else if(!parser->req) { + *err = start_req(parser, scheme_default, options); + if(*err) { + nread = -1; + goto out; + } + } + else if(parser->line_len == 0) { + /* last, empty line, we are finished */ + if(!parser->req) { + *err = CURLE_URL_MALFORMAT; + nread = -1; + goto out; + } + parser->done = TRUE; + Curl_dyn_reset(&parser->scratch); + /* last chance adjustments */ + } + else { + *err = Curl_dynhds_h1_add_line(&parser->req->headers, + parser->line, parser->line_len); + if(*err) { + nread = -1; + goto out; + } + } + } + +out: + return nread; +} + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf) +{ + CURLcode result; + + result = Curl_dyn_addf(dbuf, "%s %s%s%s%s HTTP/1.%d\r\n", + req->method, + req->scheme ? req->scheme : "", + req->scheme ? "://" : "", + req->authority ? req->authority : "", + req->path ? req->path : "", + http_minor); + if(result) + goto out; + + result = Curl_dynhds_h1_dprint(&req->headers, dbuf); + if(result) + goto out; + + result = Curl_dyn_addn(dbuf, STRCONST("\r\n")); + +out: + return result; +} + +#endif /* !CURL_DISABLE_HTTP */ diff --git a/local-test-curl-full-01/afc-curl/lib/http1.h b/local-test-curl-full-01/afc-curl/lib/http1.h new file mode 100644 index 0000000000000000000000000000000000000000..2de302f1f6c871453043e3b7c40beeb7b36acad9 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http1.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_HTTP1_H +#define HEADER_CURL_HTTP1_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_HTTP +#include "bufq.h" +#include "http.h" + +#define H1_PARSE_OPT_NONE (0) +#define H1_PARSE_OPT_STRICT (1 << 0) + +#define H1_PARSE_DEFAULT_MAX_LINE_LEN DYN_HTTP_REQUEST + +struct h1_req_parser { + struct httpreq *req; + struct dynbuf scratch; + size_t scratch_skip; + const char *line; + size_t max_line_len; + size_t line_len; + bool done; +}; + +void Curl_h1_req_parse_init(struct h1_req_parser *parser, size_t max_line_len); +void Curl_h1_req_parse_free(struct h1_req_parser *parser); + +ssize_t Curl_h1_req_parse_read(struct h1_req_parser *parser, + const char *buf, size_t buflen, + const char *scheme_default, int options, + CURLcode *err); + +CURLcode Curl_h1_req_dprint(const struct httpreq *req, + struct dynbuf *dbuf); + +CURLcode Curl_h1_req_write_head(struct httpreq *req, int http_minor, + struct dynbuf *dbuf); + +#endif /* !CURL_DISABLE_HTTP */ +#endif /* HEADER_CURL_HTTP1_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/http2.h b/local-test-curl-full-01/afc-curl/lib/http2.h new file mode 100644 index 0000000000000000000000000000000000000000..dbb1784661e7448debeb5158bd822efcf73b97f6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http2.h @@ -0,0 +1,82 @@ +#ifndef HEADER_CURL_HTTP2_H +#define HEADER_CURL_HTTP2_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef USE_NGHTTP2 +#include "http.h" + +/* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting + from the peer */ +#define DEFAULT_MAX_CONCURRENT_STREAMS 100 + +/* + * Store nghttp2 version info in this buffer. + */ +void Curl_http2_ver(char *p, size_t len); + +CURLcode Curl_http2_request_upgrade(struct dynbuf *req, + struct Curl_easy *data); + +/* returns true if the HTTP/2 stream error was HTTP_1_1_REQUIRED */ +bool Curl_h2_http_1_1_error(struct Curl_easy *data); + +bool Curl_conn_is_http2(const struct Curl_easy *data, + const struct connectdata *conn, + int sockindex); +bool Curl_http2_may_switch(struct Curl_easy *data, + struct connectdata *conn, + int sockindex); + +CURLcode Curl_http2_switch(struct Curl_easy *data, + struct connectdata *conn, int sockindex); + +CURLcode Curl_http2_switch_at(struct Curl_cfilter *cf, struct Curl_easy *data); + +CURLcode Curl_http2_upgrade(struct Curl_easy *data, + struct connectdata *conn, int sockindex, + const char *ptr, size_t nread); + +void *Curl_nghttp2_malloc(size_t size, void *user_data); +void Curl_nghttp2_free(void *ptr, void *user_data); +void *Curl_nghttp2_calloc(size_t nmemb, size_t size, void *user_data); +void *Curl_nghttp2_realloc(void *ptr, size_t size, void *user_data); + +extern struct Curl_cftype Curl_cft_nghttp2; + +#else /* USE_NGHTTP2 */ + +#define Curl_cf_is_http2(a,b) FALSE +#define Curl_conn_is_http2(a,b,c) FALSE +#define Curl_http2_may_switch(a,b,c) FALSE + +#define Curl_http2_request_upgrade(x,y) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_http2_switch(a,b,c) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_http2_upgrade(a,b,c,d,e) CURLE_UNSUPPORTED_PROTOCOL +#define Curl_h2_http_1_1_error(x) 0 +#endif + +#endif /* HEADER_CURL_HTTP2_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/http_aws_sigv4.c b/local-test-curl-full-01/afc-curl/lib/http_aws_sigv4.c new file mode 100644 index 0000000000000000000000000000000000000000..5d4848fed2b4dc83d32726cfe4e182f18e5eeabc --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http_aws_sigv4.c @@ -0,0 +1,867 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) + +#include "urldata.h" +#include "strcase.h" +#include "strdup.h" +#include "http_aws_sigv4.h" +#include "curl_sha256.h" +#include "transfer.h" +#include "parsedate.h" +#include "sendf.h" +#include "escape.h" + +#include + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#include "slist.h" + +#define HMAC_SHA256(k, kl, d, dl, o) \ + do { \ + result = Curl_hmacit(&Curl_HMAC_SHA256, \ + (unsigned char *)k, \ + kl, \ + (unsigned char *)d, \ + dl, o); \ + if(result) { \ + goto fail; \ + } \ + } while(0) + +#define TIMESTAMP_SIZE 17 + +/* hex-encoded with trailing null */ +#define SHA256_HEX_LENGTH (2 * CURL_SHA256_DIGEST_LENGTH + 1) + +static void sha256_to_hex(char *dst, unsigned char *sha) +{ + Curl_hexencode(sha, CURL_SHA256_DIGEST_LENGTH, + (unsigned char *)dst, SHA256_HEX_LENGTH); +} + +static char *find_date_hdr(struct Curl_easy *data, const char *sig_hdr) +{ + char *tmp = Curl_checkheaders(data, sig_hdr, strlen(sig_hdr)); + + if(tmp) + return tmp; + return Curl_checkheaders(data, STRCONST("Date")); +} + +/* remove whitespace, and lowercase all headers */ +static void trim_headers(struct curl_slist *head) +{ + struct curl_slist *l; + for(l = head; l; l = l->next) { + char *value; /* to read from */ + char *store; + size_t colon = strcspn(l->data, ":"); + Curl_strntolower(l->data, l->data, colon); + + value = &l->data[colon]; + if(!*value) + continue; + ++value; + store = value; + + /* skip leading whitespace */ + while(*value && ISBLANK(*value)) + value++; + + while(*value) { + int space = 0; + while(*value && ISBLANK(*value)) { + value++; + space++; + } + if(space) { + /* replace any number of consecutive whitespace with a single space, + unless at the end of the string, then nothing */ + if(*value) + *store++ = ' '; + } + else + *store++ = *value++; + } + *store = 0; /* null terminate */ + } +} + +/* maximum length for the aws sivg4 parts */ +#define MAX_SIGV4_LEN 64 +#define MAX_SIGV4_LEN_TXT "64" + +#define DATE_HDR_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Date")) + +/* string been x-PROVIDER-date:TIMESTAMP, I need +1 for ':' */ +#define DATE_FULL_HDR_LEN (DATE_HDR_KEY_LEN + TIMESTAMP_SIZE + 1) + +/* alphabetically compare two headers by their name, expecting + headers to use ':' at this point */ +static int compare_header_names(const char *a, const char *b) +{ + const char *colon_a; + const char *colon_b; + size_t len_a; + size_t len_b; + size_t min_len; + int cmp; + + colon_a = strchr(a, ':'); + colon_b = strchr(b, ':'); + + DEBUGASSERT(colon_a); + DEBUGASSERT(colon_b); + + len_a = colon_a ? (size_t)(colon_a - a) : strlen(a); + len_b = colon_b ? (size_t)(colon_b - b) : strlen(b); + + min_len = (len_a < len_b) ? len_a : len_b; + + cmp = strncmp(a, b, min_len); + + /* return the shorter of the two if one is shorter */ + if(!cmp) + return (int)(len_a - len_b); + + return cmp; +} + +/* timestamp should point to a buffer of at last TIMESTAMP_SIZE bytes */ +static CURLcode make_headers(struct Curl_easy *data, + const char *hostname, + char *timestamp, + char *provider1, + char **date_header, + char *content_sha256_header, + struct dynbuf *canonical_headers, + struct dynbuf *signed_headers) +{ + char date_hdr_key[DATE_HDR_KEY_LEN]; + char date_full_hdr[DATE_FULL_HDR_LEN]; + struct curl_slist *head = NULL; + struct curl_slist *tmp_head = NULL; + CURLcode ret = CURLE_OUT_OF_MEMORY; + struct curl_slist *l; + bool again = TRUE; + + /* provider1 mid */ + Curl_strntolower(provider1, provider1, strlen(provider1)); + provider1[0] = Curl_raw_toupper(provider1[0]); + + msnprintf(date_hdr_key, DATE_HDR_KEY_LEN, "X-%s-Date", provider1); + + /* provider1 lowercase */ + Curl_strntolower(provider1, provider1, 1); /* first byte only */ + msnprintf(date_full_hdr, DATE_FULL_HDR_LEN, + "x-%s-date:%s", provider1, timestamp); + + if(!Curl_checkheaders(data, STRCONST("Host"))) { + char *fullhost; + + if(data->state.aptr.host) { + /* remove /r/n as the separator for canonical request must be '\n' */ + size_t pos = strcspn(data->state.aptr.host, "\n\r"); + fullhost = Curl_memdup0(data->state.aptr.host, pos); + } + else + fullhost = aprintf("host:%s", hostname); + + if(fullhost) + head = Curl_slist_append_nodup(NULL, fullhost); + if(!head) { + free(fullhost); + goto fail; + } + } + + + if(*content_sha256_header) { + tmp_head = curl_slist_append(head, content_sha256_header); + if(!tmp_head) + goto fail; + head = tmp_head; + } + + /* copy user headers to our header list. the logic is based on how http.c + handles user headers. + + user headers in format 'name:' with no value are used to signal that an + internal header of that name should be removed. those user headers are not + added to this list. + + user headers in format 'name;' with no value are used to signal that a + header of that name with no value should be sent. those user headers are + added to this list but in the format that they will be sent, ie the + semi-colon is changed to a colon for format 'name:'. + + user headers with a value of whitespace only, or without a colon or + semi-colon, are not added to this list. + */ + for(l = data->set.headers; l; l = l->next) { + char *dupdata, *ptr; + char *sep = strchr(l->data, ':'); + if(!sep) + sep = strchr(l->data, ';'); + if(!sep || (*sep == ':' && !*(sep + 1))) + continue; + for(ptr = sep + 1; ISSPACE(*ptr); ++ptr) + ; + if(!*ptr && ptr != sep + 1) /* a value of whitespace only */ + continue; + dupdata = strdup(l->data); + if(!dupdata) + goto fail; + dupdata[sep - l->data] = ':'; + tmp_head = Curl_slist_append_nodup(head, dupdata); + if(!tmp_head) { + free(dupdata); + goto fail; + } + head = tmp_head; + } + + trim_headers(head); + + *date_header = find_date_hdr(data, date_hdr_key); + if(!*date_header) { + tmp_head = curl_slist_append(head, date_full_hdr); + if(!tmp_head) + goto fail; + head = tmp_head; + *date_header = aprintf("%s: %s\r\n", date_hdr_key, timestamp); + } + else { + char *value; + char *endp; + value = strchr(*date_header, ':'); + if(!value) { + *date_header = NULL; + goto fail; + } + ++value; + while(ISBLANK(*value)) + ++value; + endp = value; + while(*endp && ISALNUM(*endp)) + ++endp; + /* 16 bytes => "19700101T000000Z" */ + if((endp - value) == TIMESTAMP_SIZE - 1) { + memcpy(timestamp, value, TIMESTAMP_SIZE - 1); + timestamp[TIMESTAMP_SIZE - 1] = 0; + } + else + /* bad timestamp length */ + timestamp[0] = 0; + *date_header = NULL; + } + + /* alpha-sort by header name in a case sensitive manner */ + do { + again = FALSE; + for(l = head; l; l = l->next) { + struct curl_slist *next = l->next; + + if(next && compare_header_names(l->data, next->data) > 0) { + char *tmp = l->data; + + l->data = next->data; + next->data = tmp; + again = TRUE; + } + } + } while(again); + + for(l = head; l; l = l->next) { + char *tmp; + + if(Curl_dyn_add(canonical_headers, l->data)) + goto fail; + if(Curl_dyn_add(canonical_headers, "\n")) + goto fail; + + tmp = strchr(l->data, ':'); + if(tmp) + *tmp = 0; + + if(l != head) { + if(Curl_dyn_add(signed_headers, ";")) + goto fail; + } + if(Curl_dyn_add(signed_headers, l->data)) + goto fail; + } + + ret = CURLE_OK; +fail: + curl_slist_free_all(head); + + return ret; +} + +#define CONTENT_SHA256_KEY_LEN (MAX_SIGV4_LEN + sizeof("X--Content-Sha256")) +/* add 2 for ": " between header name and value */ +#define CONTENT_SHA256_HDR_LEN (CONTENT_SHA256_KEY_LEN + 2 + \ + SHA256_HEX_LENGTH) + +/* try to parse a payload hash from the content-sha256 header */ +static char *parse_content_sha_hdr(struct Curl_easy *data, + const char *provider1, + size_t *value_len) +{ + char key[CONTENT_SHA256_KEY_LEN]; + size_t key_len; + char *value; + size_t len; + + key_len = msnprintf(key, sizeof(key), "x-%s-content-sha256", provider1); + + value = Curl_checkheaders(data, key, key_len); + if(!value) + return NULL; + + value = strchr(value, ':'); + if(!value) + return NULL; + ++value; + + while(*value && ISBLANK(*value)) + ++value; + + len = strlen(value); + while(len > 0 && ISBLANK(value[len-1])) + --len; + + *value_len = len; + return value; +} + +static CURLcode calc_payload_hash(struct Curl_easy *data, + unsigned char *sha_hash, char *sha_hex) +{ + const char *post_data = data->set.postfields; + size_t post_data_len = 0; + CURLcode result; + + if(post_data) { + if(data->set.postfieldsize < 0) + post_data_len = strlen(post_data); + else + post_data_len = (size_t)data->set.postfieldsize; + } + result = Curl_sha256it(sha_hash, (const unsigned char *) post_data, + post_data_len); + if(!result) + sha256_to_hex(sha_hex, sha_hash); + return result; +} + +#define S3_UNSIGNED_PAYLOAD "UNSIGNED-PAYLOAD" + +static CURLcode calc_s3_payload_hash(struct Curl_easy *data, + Curl_HttpReq httpreq, char *provider1, + unsigned char *sha_hash, + char *sha_hex, char *header) +{ + bool empty_method = (httpreq == HTTPREQ_GET || httpreq == HTTPREQ_HEAD); + /* The request method or filesize indicate no request payload */ + bool empty_payload = (empty_method || data->set.filesize == 0); + /* The POST payload is in memory */ + bool post_payload = (httpreq == HTTPREQ_POST && data->set.postfields); + CURLcode ret = CURLE_OUT_OF_MEMORY; + + if(empty_payload || post_payload) { + /* Calculate a real hash when we know the request payload */ + ret = calc_payload_hash(data, sha_hash, sha_hex); + if(ret) + goto fail; + } + else { + /* Fall back to s3's UNSIGNED-PAYLOAD */ + size_t len = sizeof(S3_UNSIGNED_PAYLOAD) - 1; + DEBUGASSERT(len < SHA256_HEX_LENGTH); /* 16 < 65 */ + memcpy(sha_hex, S3_UNSIGNED_PAYLOAD, len); + sha_hex[len] = 0; + } + + /* format the required content-sha256 header */ + msnprintf(header, CONTENT_SHA256_HDR_LEN, + "x-%s-content-sha256: %s", provider1, sha_hex); + + ret = CURLE_OK; +fail: + return ret; +} + +struct pair { + const char *p; + size_t len; +}; + +static int compare_func(const void *a, const void *b) +{ + const struct pair *aa = a; + const struct pair *bb = b; + /* If one element is empty, the other is always sorted higher */ + if(aa->len == 0) + return -1; + if(bb->len == 0) + return 1; + return strncmp(aa->p, bb->p, aa->len < bb->len ? aa->len : bb->len); +} + +#define MAX_QUERYPAIRS 64 + +/** + * found_equals have a double meaning, + * detect if an equal have been found when called from canon_query, + * and mark that this function is called to compute the path, + * if found_equals is NULL. + */ +static CURLcode canon_string(const char *q, size_t len, + struct dynbuf *dq, bool *found_equals) +{ + CURLcode result = CURLE_OK; + + for(; len && !result; q++, len--) { + if(ISALNUM(*q)) + result = Curl_dyn_addn(dq, q, 1); + else { + switch(*q) { + case '-': + case '.': + case '_': + case '~': + /* allowed as-is */ + result = Curl_dyn_addn(dq, q, 1); + break; + case '%': + /* uppercase the following if hexadecimal */ + if(ISXDIGIT(q[1]) && ISXDIGIT(q[2])) { + char tmp[3]="%"; + tmp[1] = Curl_raw_toupper(q[1]); + tmp[2] = Curl_raw_toupper(q[2]); + result = Curl_dyn_addn(dq, tmp, 3); + q += 2; + len -= 2; + } + else + /* '%' without a following two-digit hex, encode it */ + result = Curl_dyn_addn(dq, "%25", 3); + break; + default: { + const char hex[] = "0123456789ABCDEF"; + char out[3]={'%'}; + + if(!found_equals) { + /* if found_equals is NULL assuming, been in path */ + if(*q == '/') { + /* allowed as if */ + result = Curl_dyn_addn(dq, q, 1); + break; + } + } + else { + /* allowed as-is */ + if(*q == '=') { + result = Curl_dyn_addn(dq, q, 1); + *found_equals = TRUE; + break; + } + } + /* URL encode */ + out[1] = hex[((unsigned char)*q) >> 4]; + out[2] = hex[*q & 0xf]; + result = Curl_dyn_addn(dq, out, 3); + break; + } + } + } + } + return result; +} + + +static CURLcode canon_query(struct Curl_easy *data, + const char *query, struct dynbuf *dq) +{ + CURLcode result = CURLE_OK; + int entry = 0; + int i; + const char *p = query; + struct pair array[MAX_QUERYPAIRS]; + struct pair *ap = &array[0]; + if(!query) + return result; + + /* sort the name=value pairs first */ + do { + char *amp; + entry++; + ap->p = p; + amp = strchr(p, '&'); + if(amp) + ap->len = amp - p; /* excluding the ampersand */ + else { + ap->len = strlen(p); + break; + } + ap++; + p = amp + 1; + } while(entry < MAX_QUERYPAIRS); + if(entry == MAX_QUERYPAIRS) { + /* too many query pairs for us */ + failf(data, "aws-sigv4: too many query pairs in URL"); + return CURLE_URL_MALFORMAT; + } + + qsort(&array[0], entry, sizeof(struct pair), compare_func); + + ap = &array[0]; + for(i = 0; !result && (i < entry); i++, ap++) { + const char *q = ap->p; + bool found_equals = FALSE; + if(!ap->len) + continue; + result = canon_string(q, ap->len, dq, &found_equals); + if(!result && !found_equals) { + /* queries without value still need an equals */ + result = Curl_dyn_addn(dq, "=", 1); + } + if(!result && i < entry - 1) { + /* insert ampersands between query pairs */ + result = Curl_dyn_addn(dq, "&", 1); + } + } + return result; +} + + +CURLcode Curl_output_aws_sigv4(struct Curl_easy *data, bool proxy) +{ + CURLcode result = CURLE_OUT_OF_MEMORY; + struct connectdata *conn = data->conn; + size_t len; + const char *arg; + char provider0[MAX_SIGV4_LEN + 1]=""; + char provider1[MAX_SIGV4_LEN + 1]=""; + char region[MAX_SIGV4_LEN + 1]=""; + char service[MAX_SIGV4_LEN + 1]=""; + bool sign_as_s3 = FALSE; + const char *hostname = conn->host.name; + time_t clock; + struct tm tm; + char timestamp[TIMESTAMP_SIZE]; + char date[9]; + struct dynbuf canonical_headers; + struct dynbuf signed_headers; + struct dynbuf canonical_query; + struct dynbuf canonical_path; + char *date_header = NULL; + Curl_HttpReq httpreq; + const char *method = NULL; + char *payload_hash = NULL; + size_t payload_hash_len = 0; + unsigned char sha_hash[CURL_SHA256_DIGEST_LENGTH]; + char sha_hex[SHA256_HEX_LENGTH]; + char content_sha256_hdr[CONTENT_SHA256_HDR_LEN + 2] = ""; /* add \r\n */ + char *canonical_request = NULL; + char *request_type = NULL; + char *credential_scope = NULL; + char *str_to_sign = NULL; + const char *user = data->state.aptr.user ? data->state.aptr.user : ""; + char *secret = NULL; + unsigned char sign0[CURL_SHA256_DIGEST_LENGTH] = {0}; + unsigned char sign1[CURL_SHA256_DIGEST_LENGTH] = {0}; + char *auth_headers = NULL; + + DEBUGASSERT(!proxy); + (void)proxy; + + if(Curl_checkheaders(data, STRCONST("Authorization"))) { + /* Authorization already present, Bailing out */ + return CURLE_OK; + } + + /* we init those buffers here, so goto fail will free initialized dynbuf */ + Curl_dyn_init(&canonical_headers, CURL_MAX_HTTP_HEADER); + Curl_dyn_init(&canonical_query, CURL_MAX_HTTP_HEADER); + Curl_dyn_init(&signed_headers, CURL_MAX_HTTP_HEADER); + Curl_dyn_init(&canonical_path, CURL_MAX_HTTP_HEADER); + + /* + * Parameters parsing + * Google and Outscale use the same OSC or GOOG, + * but Amazon uses AWS and AMZ for header arguments. + * AWS is the default because most of non-amazon providers + * are still using aws:amz as a prefix. + */ + arg = data->set.str[STRING_AWS_SIGV4] ? + data->set.str[STRING_AWS_SIGV4] : "aws:amz"; + + /* provider1[:provider2[:region[:service]]] + + No string can be longer than N bytes of non-whitespace + */ + (void)sscanf(arg, "%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "[^:]" + ":%" MAX_SIGV4_LEN_TXT "s", + provider0, provider1, region, service); + if(!provider0[0]) { + failf(data, "first aws-sigv4 provider cannot be empty"); + result = CURLE_BAD_FUNCTION_ARGUMENT; + goto fail; + } + else if(!provider1[0]) + strcpy(provider1, provider0); + + if(!service[0]) { + char *hostdot = strchr(hostname, '.'); + if(!hostdot) { + failf(data, "aws-sigv4: service missing in parameters and hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + len = hostdot - hostname; + if(len > MAX_SIGV4_LEN) { + failf(data, "aws-sigv4: service too long in hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + memcpy(service, hostname, len); + service[len] = '\0'; + + infof(data, "aws_sigv4: picked service %s from host", service); + + if(!region[0]) { + const char *reg = hostdot + 1; + const char *hostreg = strchr(reg, '.'); + if(!hostreg) { + failf(data, "aws-sigv4: region missing in parameters and hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + len = hostreg - reg; + if(len > MAX_SIGV4_LEN) { + failf(data, "aws-sigv4: region too long in hostname"); + result = CURLE_URL_MALFORMAT; + goto fail; + } + memcpy(region, reg, len); + region[len] = '\0'; + infof(data, "aws_sigv4: picked region %s from host", region); + } + } + + Curl_http_method(data, conn, &method, &httpreq); + + /* AWS S3 requires a x-amz-content-sha256 header, and supports special + * values like UNSIGNED-PAYLOAD */ + sign_as_s3 = (strcasecompare(provider0, "aws") && + strcasecompare(service, "s3")); + + payload_hash = parse_content_sha_hdr(data, provider1, &payload_hash_len); + + if(!payload_hash) { + if(sign_as_s3) + result = calc_s3_payload_hash(data, httpreq, provider1, sha_hash, + sha_hex, content_sha256_hdr); + else + result = calc_payload_hash(data, sha_hash, sha_hex); + if(result) + goto fail; + + payload_hash = sha_hex; + /* may be shorter than SHA256_HEX_LENGTH, like S3_UNSIGNED_PAYLOAD */ + payload_hash_len = strlen(sha_hex); + } + +#ifdef DEBUGBUILD + { + char *force_timestamp = getenv("CURL_FORCETIME"); + if(force_timestamp) + clock = 0; + else + clock = time(NULL); + } +#else + clock = time(NULL); +#endif + result = Curl_gmtime(clock, &tm); + if(result) { + goto fail; + } + if(!strftime(timestamp, sizeof(timestamp), "%Y%m%dT%H%M%SZ", &tm)) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + result = make_headers(data, hostname, timestamp, provider1, + &date_header, content_sha256_hdr, + &canonical_headers, &signed_headers); + if(result) + goto fail; + + if(*content_sha256_hdr) { + /* make_headers() needed this without the \r\n for canonicalization */ + size_t hdrlen = strlen(content_sha256_hdr); + DEBUGASSERT(hdrlen + 3 < sizeof(content_sha256_hdr)); + memcpy(content_sha256_hdr + hdrlen, "\r\n", 3); + } + + memcpy(date, timestamp, sizeof(date)); + date[sizeof(date) - 1] = 0; + + result = canon_query(data, data->state.up.query, &canonical_query); + if(result) + goto fail; + + result = canon_string(data->state.up.path, strlen(data->state.up.path), + &canonical_path, NULL); + if(result) + goto fail; + result = CURLE_OUT_OF_MEMORY; + + canonical_request = + aprintf("%s\n" /* HTTPRequestMethod */ + "%s\n" /* CanonicalURI */ + "%s\n" /* CanonicalQueryString */ + "%s\n" /* CanonicalHeaders */ + "%s\n" /* SignedHeaders */ + "%.*s", /* HashedRequestPayload in hex */ + method, + Curl_dyn_ptr(&canonical_path), + Curl_dyn_ptr(&canonical_query) ? + Curl_dyn_ptr(&canonical_query) : "", + Curl_dyn_ptr(&canonical_headers), + Curl_dyn_ptr(&signed_headers), + (int)payload_hash_len, payload_hash); + if(!canonical_request) + goto fail; + + DEBUGF(infof(data, "Canonical request: %s", canonical_request)); + + /* provider 0 lowercase */ + Curl_strntolower(provider0, provider0, strlen(provider0)); + request_type = aprintf("%s4_request", provider0); + if(!request_type) + goto fail; + + credential_scope = aprintf("%s/%s/%s/%s", + date, region, service, request_type); + if(!credential_scope) + goto fail; + + if(Curl_sha256it(sha_hash, (unsigned char *) canonical_request, + strlen(canonical_request))) + goto fail; + + sha256_to_hex(sha_hex, sha_hash); + + /* provider 0 uppercase */ + Curl_strntoupper(provider0, provider0, strlen(provider0)); + + /* + * Google allows using RSA key instead of HMAC, so this code might change + * in the future. For now we only support HMAC. + */ + str_to_sign = aprintf("%s4-HMAC-SHA256\n" /* Algorithm */ + "%s\n" /* RequestDateTime */ + "%s\n" /* CredentialScope */ + "%s", /* HashedCanonicalRequest in hex */ + provider0, + timestamp, + credential_scope, + sha_hex); + if(!str_to_sign) { + goto fail; + } + + /* provider 0 uppercase */ + secret = aprintf("%s4%s", provider0, + data->state.aptr.passwd ? + data->state.aptr.passwd : ""); + if(!secret) + goto fail; + + HMAC_SHA256(secret, strlen(secret), date, strlen(date), sign0); + HMAC_SHA256(sign0, sizeof(sign0), region, strlen(region), sign1); + HMAC_SHA256(sign1, sizeof(sign1), service, strlen(service), sign0); + HMAC_SHA256(sign0, sizeof(sign0), request_type, strlen(request_type), sign1); + HMAC_SHA256(sign1, sizeof(sign1), str_to_sign, strlen(str_to_sign), sign0); + + sha256_to_hex(sha_hex, sign0); + + /* provider 0 uppercase */ + auth_headers = aprintf("Authorization: %s4-HMAC-SHA256 " + "Credential=%s/%s, " + "SignedHeaders=%s, " + "Signature=%s\r\n" + /* + * date_header is added here, only if it was not + * user-specified (using CURLOPT_HTTPHEADER). + * date_header includes \r\n + */ + "%s" + "%s", /* optional sha256 header includes \r\n */ + provider0, + user, + credential_scope, + Curl_dyn_ptr(&signed_headers), + sha_hex, + date_header ? date_header : "", + content_sha256_hdr); + if(!auth_headers) { + goto fail; + } + + Curl_safefree(data->state.aptr.userpwd); + data->state.aptr.userpwd = auth_headers; + data->state.authhost.done = TRUE; + result = CURLE_OK; + +fail: + Curl_dyn_free(&canonical_query); + Curl_dyn_free(&canonical_path); + Curl_dyn_free(&canonical_headers); + Curl_dyn_free(&signed_headers); + free(canonical_request); + free(request_type); + free(credential_scope); + free(str_to_sign); + free(secret); + free(date_header); + return result; +} + +#endif /* !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_AWS) */ diff --git a/local-test-curl-full-01/afc-curl/lib/http_negotiate.c b/local-test-curl-full-01/afc-curl/lib/http_negotiate.c new file mode 100644 index 0000000000000000000000000000000000000000..5d76bddf7248b470934b637811f5127b53ed863d --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http_negotiate.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 + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) + +#include "urldata.h" +#include "sendf.h" +#include "http_negotiate.h" +#include "vauth/vauth.h" +#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" + +CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, + bool proxy, const char *header) +{ + CURLcode result; + size_t len; + + /* Point to the username, password, service and host */ + const char *userp; + const char *passwdp; + const char *service; + const char *host; + + /* Point to the correct struct with this */ + struct negotiatedata *neg_ctx; + curlnegotiate state; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + userp = conn->http_proxy.user; + passwdp = conn->http_proxy.passwd; + service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; + host = conn->http_proxy.host.name; + neg_ctx = &conn->proxyneg; + state = conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + userp = conn->user; + passwdp = conn->passwd; + service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : "HTTP"; + host = conn->host.name; + neg_ctx = &conn->negotiate; + state = conn->http_negotiate_state; + } + + /* Not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + + /* Obtain the input token, if any */ + header += strlen("Negotiate"); + while(*header && ISBLANK(*header)) + header++; + + len = strlen(header); + neg_ctx->havenegdata = len != 0; + if(!len) { + if(state == GSS_AUTHSUCC) { + infof(data, "Negotiate auth restarted"); + Curl_http_auth_cleanup_negotiate(conn); + } + else if(state != GSS_AUTHNONE) { + /* The server rejected our authentication and has not supplied any more + negotiation mechanisms */ + Curl_http_auth_cleanup_negotiate(conn); + return CURLE_LOGIN_DENIED; + } + } + + /* Supports SSL channel binding for Windows ISS extended protection */ +#if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) + neg_ctx->sslContext = conn->sslContext; +#endif + /* Check if the connection is using SSL and get the channel binding data */ +#if defined(USE_SSL) && defined(HAVE_GSSAPI) + if(conn->handler->flags & PROTOPT_SSL) { + Curl_dyn_init(&neg_ctx->channel_binding_data, SSL_CB_MAX_SIZE + 1); + result = Curl_ssl_get_channel_binding( + data, FIRSTSOCKET, &neg_ctx->channel_binding_data); + if(result) { + Curl_http_auth_cleanup_negotiate(conn); + return result; + } + } +#endif + + /* Initialize the security context and decode our challenge */ + result = Curl_auth_decode_spnego_message(data, userp, passwdp, service, + host, header, neg_ctx); + +#if defined(USE_SSL) && defined(HAVE_GSSAPI) + Curl_dyn_free(&neg_ctx->channel_binding_data); +#endif + + if(result) + Curl_http_auth_cleanup_negotiate(conn); + + return result; +} + +CURLcode Curl_output_negotiate(struct Curl_easy *data, + struct connectdata *conn, bool proxy) +{ + struct negotiatedata *neg_ctx; + struct auth *authp; + curlnegotiate *state; + char *base64 = NULL; + size_t len = 0; + char *userp; + CURLcode result; + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + neg_ctx = &conn->proxyneg; + authp = &data->state.authproxy; + state = &conn->proxy_negotiate_state; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + neg_ctx = &conn->negotiate; + authp = &data->state.authhost; + state = &conn->http_negotiate_state; + } + + authp->done = FALSE; + + if(*state == GSS_AUTHRECV) { + if(neg_ctx->havenegdata) { + neg_ctx->havemultiplerequests = TRUE; + } + } + else if(*state == GSS_AUTHSUCC) { + if(!neg_ctx->havenoauthpersist) { + neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests; + } + } + + if(neg_ctx->noauthpersist || + (*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) { + + if(neg_ctx->noauthpersist && *state == GSS_AUTHSUCC) { + infof(data, "Curl_output_negotiate, " + "no persistent authentication: cleanup existing context"); + Curl_http_auth_cleanup_negotiate(conn); + } + if(!neg_ctx->context) { + result = Curl_input_negotiate(data, conn, proxy, "Negotiate"); + if(result == CURLE_AUTH_ERROR) { + /* negotiate auth failed, let's continue unauthenticated to stay + * compatible with the behavior before curl-7_64_0-158-g6c6035532 */ + authp->done = TRUE; + return CURLE_OK; + } + else if(result) + return result; + } + + result = Curl_auth_create_spnego_message(neg_ctx, &base64, &len); + if(result) + return result; + + userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", + base64); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + Curl_safefree(data->state.aptr.proxyuserpwd); + data->state.aptr.proxyuserpwd = userp; +#endif + } + else { + Curl_safefree(data->state.aptr.userpwd); + data->state.aptr.userpwd = userp; + } + + free(base64); + + if(!userp) { + return CURLE_OUT_OF_MEMORY; + } + + *state = GSS_AUTHSENT; + #ifdef HAVE_GSSAPI + if(neg_ctx->status == GSS_S_COMPLETE || + neg_ctx->status == GSS_S_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } + #else + #ifdef USE_WINDOWS_SSPI + if(neg_ctx->status == SEC_E_OK || + neg_ctx->status == SEC_I_CONTINUE_NEEDED) { + *state = GSS_AUTHDONE; + } + #endif + #endif + } + + if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) { + /* connection is already authenticated, + * do not send a header in future requests */ + authp->done = TRUE; + } + + neg_ctx->havenegdata = FALSE; + + return CURLE_OK; +} + +void Curl_http_auth_cleanup_negotiate(struct connectdata *conn) +{ + conn->http_negotiate_state = GSS_AUTHNONE; + conn->proxy_negotiate_state = GSS_AUTHNONE; + + Curl_auth_cleanup_spnego(&conn->negotiate); + Curl_auth_cleanup_spnego(&conn->proxyneg); +} + +#endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */ diff --git a/local-test-curl-full-01/afc-curl/lib/http_ntlm.c b/local-test-curl-full-01/afc-curl/lib/http_ntlm.c new file mode 100644 index 0000000000000000000000000000000000000000..49230bc1bdf0423ab4a2060aaed3172e7bc75546 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/http_ntlm.c @@ -0,0 +1,270 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) + +/* + * NTLM details: + * + * https://davenport.sourceforge.net/ntlm.html + * https://www.innovation.ch/java/ntlm.html + */ + +#define DEBUG_ME 0 + +#include "urldata.h" +#include "sendf.h" +#include "strcase.h" +#include "http_ntlm.h" +#include "curl_ntlm_core.h" +#include "curl_base64.h" +#include "vauth/vauth.h" +#include "url.h" + +/* SSL backend-specific #if branches in this file must be kept in the order + documented in curl_ntlm_core. */ +#if defined(USE_WINDOWS_SSPI) +#include "curl_sspi.h" +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if DEBUG_ME +# define DEBUG_OUT(x) x +#else +# define DEBUG_OUT(x) Curl_nop_stmt +#endif + +CURLcode Curl_input_ntlm(struct Curl_easy *data, + bool proxy, /* if proxy or not */ + const char *header) /* rest of the www-authenticate: + header */ +{ + /* point to the correct struct with this */ + struct ntlmdata *ntlm; + curlntlm *state; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + + ntlm = proxy ? &conn->proxyntlm : &conn->ntlm; + state = proxy ? &conn->proxy_ntlm_state : &conn->http_ntlm_state; + + if(checkprefix("NTLM", header)) { + header += strlen("NTLM"); + + while(*header && ISSPACE(*header)) + header++; + + if(*header) { + unsigned char *hdr; + size_t hdrlen; + + result = Curl_base64_decode(header, &hdr, &hdrlen); + if(!result) { + struct bufref hdrbuf; + + Curl_bufref_init(&hdrbuf); + Curl_bufref_set(&hdrbuf, hdr, hdrlen, curl_free); + result = Curl_auth_decode_ntlm_type2_message(data, &hdrbuf, ntlm); + Curl_bufref_free(&hdrbuf); + } + if(result) + return result; + + *state = NTLMSTATE_TYPE2; /* We got a type-2 message */ + } + else { + if(*state == NTLMSTATE_LAST) { + infof(data, "NTLM auth restarted"); + Curl_http_auth_cleanup_ntlm(conn); + } + else if(*state == NTLMSTATE_TYPE3) { + infof(data, "NTLM handshake rejected"); + Curl_http_auth_cleanup_ntlm(conn); + *state = NTLMSTATE_NONE; + return CURLE_REMOTE_ACCESS_DENIED; + } + else if(*state >= NTLMSTATE_TYPE1) { + infof(data, "NTLM handshake failure (internal error)"); + return CURLE_REMOTE_ACCESS_DENIED; + } + + *state = NTLMSTATE_TYPE1; /* We should send away a type-1 */ + } + } + + return result; +} + +/* + * This is for creating NTLM header output + */ +CURLcode Curl_output_ntlm(struct Curl_easy *data, bool proxy) +{ + char *base64 = NULL; + size_t len = 0; + CURLcode result = CURLE_OK; + struct bufref ntlmmsg; + + /* point to the address of the pointer that holds the string to send to the + server, which is for a plain host or for an HTTP proxy */ + char **allocuserpwd; + + /* point to the username, password, service and host */ + const char *userp; + const char *passwdp; + const char *service = NULL; + const char *hostname = NULL; + + /* point to the correct struct with this */ + struct ntlmdata *ntlm; + curlntlm *state; + struct auth *authp; + struct connectdata *conn = data->conn; + + DEBUGASSERT(conn); + DEBUGASSERT(data); + + if(proxy) { +#ifndef CURL_DISABLE_PROXY + allocuserpwd = &data->state.aptr.proxyuserpwd; + userp = data->state.aptr.proxyuser; + passwdp = data->state.aptr.proxypasswd; + service = data->set.str[STRING_PROXY_SERVICE_NAME] ? + data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; + hostname = conn->http_proxy.host.name; + ntlm = &conn->proxyntlm; + state = &conn->proxy_ntlm_state; + authp = &data->state.authproxy; +#else + return CURLE_NOT_BUILT_IN; +#endif + } + else { + allocuserpwd = &data->state.aptr.userpwd; + userp = data->state.aptr.user; + passwdp = data->state.aptr.passwd; + service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : "HTTP"; + hostname = conn->host.name; + ntlm = &conn->ntlm; + state = &conn->http_ntlm_state; + authp = &data->state.authhost; + } + authp->done = FALSE; + + /* not set means empty */ + if(!userp) + userp = ""; + + if(!passwdp) + passwdp = ""; + +#ifdef USE_WINDOWS_SSPI + if(!Curl_hSecDll) { + /* not thread safe and leaks - use curl_global_init() to avoid */ + CURLcode err = Curl_sspi_global_init(); + if(!Curl_hSecDll) + return err; + } +#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS + ntlm->sslContext = conn->sslContext; +#endif +#endif + + Curl_bufref_init(&ntlmmsg); + + /* connection is already authenticated, do not send a header in future + * requests so go directly to NTLMSTATE_LAST */ + if(*state == NTLMSTATE_TYPE3) + *state = NTLMSTATE_LAST; + + switch(*state) { + case NTLMSTATE_TYPE1: + default: /* for the weird cases we (re)start here */ + /* Create a type-1 message */ + result = Curl_auth_create_ntlm_type1_message(data, userp, passwdp, + service, hostname, + ntlm, &ntlmmsg); + if(!result) { + DEBUGASSERT(Curl_bufref_len(&ntlmmsg) != 0); + result = Curl_base64_encode((const char *) Curl_bufref_ptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + free(*allocuserpwd); + *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", + base64); + free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + } + } + break; + + case NTLMSTATE_TYPE2: + /* We already received the type-2 message, create a type-3 message */ + result = Curl_auth_create_ntlm_type3_message(data, userp, passwdp, + ntlm, &ntlmmsg); + if(!result && Curl_bufref_len(&ntlmmsg)) { + result = Curl_base64_encode((const char *) Curl_bufref_ptr(&ntlmmsg), + Curl_bufref_len(&ntlmmsg), &base64, &len); + if(!result) { + free(*allocuserpwd); + *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", + proxy ? "Proxy-" : "", + base64); + free(base64); + if(!*allocuserpwd) + result = CURLE_OUT_OF_MEMORY; + else { + *state = NTLMSTATE_TYPE3; /* we send a type-3 */ + authp->done = TRUE; + } + } + } + break; + + case NTLMSTATE_LAST: + Curl_safefree(*allocuserpwd); + authp->done = TRUE; + break; + } + Curl_bufref_free(&ntlmmsg); + + return result; +} + +void Curl_http_auth_cleanup_ntlm(struct connectdata *conn) +{ + Curl_auth_cleanup_ntlm(&conn->ntlm); + Curl_auth_cleanup_ntlm(&conn->proxyntlm); +} + +#endif /* !CURL_DISABLE_HTTP && USE_NTLM */ diff --git a/local-test-curl-full-01/afc-curl/lib/inet_ntop.c b/local-test-curl-full-01/afc-curl/lib/inet_ntop.c new file mode 100644 index 0000000000000000000000000000000000000000..a2812cf8e245bd13fdebcea7b1aa7e10bb25ddd1 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/inet_ntop.c @@ -0,0 +1,204 @@ +/* + * Copyright (C) 1996-2022 Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM + * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL + * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ +/* + * Original code by Paul Vixie. "curlified" by Gisle Vanem. + */ + +#include "curl_setup.h" + +#ifndef HAVE_INET_NTOP + +#ifdef HAVE_SYS_PARAM_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "inet_ntop.h" +#include "curl_printf.h" + +#define IN6ADDRSZ 16 +#define INADDRSZ 4 +#define INT16SZ 2 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* + * Format an IPv4 address, more or less like inet_ntop(). + * + * Returns `dst' (as a const) + * Note: + * - uses no statics + * - takes a unsigned char* not an in_addr as input + */ +static char *inet_ntop4(const unsigned char *src, char *dst, size_t size) +{ + char tmp[sizeof("255.255.255.255")]; + size_t len; + + DEBUGASSERT(size >= 16); + + tmp[0] = '\0'; + (void)msnprintf(tmp, sizeof(tmp), "%d.%d.%d.%d", + ((int)((unsigned char)src[0])) & 0xff, + ((int)((unsigned char)src[1])) & 0xff, + ((int)((unsigned char)src[2])) & 0xff, + ((int)((unsigned char)src[3])) & 0xff); + + len = strlen(tmp); + if(len == 0 || len >= size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return dst; +} + +/* + * Convert IPv6 binary address into presentation (printable) format. + */ +static char *inet_ntop6(const unsigned char *src, char *dst, size_t size) +{ + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")]; + char *tp; + struct { + int base; + int len; + } best, cur; + unsigned int words[IN6ADDRSZ / INT16SZ]; + int i; + + /* Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof(words)); + for(i = 0; i < IN6ADDRSZ; i++) + words[i/2] |= ((unsigned int)src[i] << ((1 - (i % 2)) << 3)); + + best.base = -1; + cur.base = -1; + best.len = 0; + cur.len = 0; + + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + if(words[i] == 0) { + if(cur.base == -1) { + cur.base = i; cur.len = 1; + } + else + cur.len++; + } + else if(cur.base != -1) { + if(best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + if((cur.base != -1) && (best.base == -1 || cur.len > best.len)) + best = cur; + if(best.base != -1 && best.len < 2) + best.base = -1; + /* Format the result. */ + tp = tmp; + for(i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if(best.base != -1 && i >= best.base && i < (best.base + best.len)) { + if(i == best.base) + *tp++ = ':'; + continue; + } + + /* Are we following an initial run of 0x00s or any real hex? + */ + if(i) + *tp++ = ':'; + + /* Is this address an encapsulated IPv4? + */ + if(i == 6 && best.base == 0 && + (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { + if(!inet_ntop4(src + 12, tp, sizeof(tmp) - (tp - tmp))) { + errno = ENOSPC; + return (NULL); + } + tp += strlen(tp); + break; + } + tp += msnprintf(tp, 5, "%x", words[i]); + } + + /* Was it a trailing run of 0x00's? + */ + if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) + *tp++ = ':'; + *tp++ = '\0'; + + /* Check for overflow, copy, and we are done. + */ + if((size_t)(tp - tmp) > size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return dst; +} + +/* + * Convert a network format address to presentation format. + * + * Returns pointer to presentation format address (`buf'). + * Returns NULL on error and errno set with the specific + * error, EAFNOSUPPORT or ENOSPC. + * + * On Windows we store the error in the thread errno, not in the Winsock error + * code. This is to avoid losing the actual last Winsock error. When this + * function returns NULL, check errno not SOCKERRNO. + */ +char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size) +{ + switch(af) { + case AF_INET: + return inet_ntop4((const unsigned char *)src, buf, size); + case AF_INET6: + return inet_ntop6((const unsigned char *)src, buf, size); + default: + errno = EAFNOSUPPORT; + return NULL; + } +} +#endif /* HAVE_INET_NTOP */ diff --git a/local-test-curl-full-01/afc-curl/lib/inet_ntop.h b/local-test-curl-full-01/afc-curl/lib/inet_ntop.h new file mode 100644 index 0000000000000000000000000000000000000000..f592f252517cadb1967e9e553ada6453a1253cd7 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/inet_ntop.h @@ -0,0 +1,44 @@ +#ifndef HEADER_CURL_INET_NTOP_H +#define HEADER_CURL_INET_NTOP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +char *Curl_inet_ntop(int af, const void *addr, char *buf, size_t size); + +#ifdef HAVE_INET_NTOP +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef _WIN32 +#define Curl_inet_ntop(af,addr,buf,size) \ + inet_ntop(af, addr, buf, size) +#else +#define Curl_inet_ntop(af,addr,buf,size) \ + inet_ntop(af, addr, buf, (curl_socklen_t)(size)) +#endif +#endif + +#endif /* HEADER_CURL_INET_NTOP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/krb5.c b/local-test-curl-full-01/afc-curl/lib/krb5.c new file mode 100644 index 0000000000000000000000000000000000000000..e310a1b57a8ff0bff67ff7fe5f6e3bae96666cf6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/krb5.c @@ -0,0 +1,927 @@ +/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c + * + * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * Copyright (C) Daniel Stenberg + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. */ + +#include "curl_setup.h" + +#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP) + +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "urldata.h" +#include "cfilters.h" +#include "cf-socket.h" +#include "curl_base64.h" +#include "ftp.h" +#include "curl_gssapi.h" +#include "sendf.h" +#include "transfer.h" +#include "curl_krb5.h" +#include "warnless.h" +#include "strcase.h" +#include "strdup.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn, + const char *cmd) +{ + size_t bytes_written; +#define SBUF_SIZE 1024 + char s[SBUF_SIZE]; + size_t write_len; + char *sptr = s; + CURLcode result = CURLE_OK; +#ifdef HAVE_GSSAPI + unsigned char data_sec = conn->data_prot; +#endif + + DEBUGASSERT(cmd); + + write_len = strlen(cmd); + if(!write_len || write_len > (sizeof(s) -3)) + return CURLE_BAD_FUNCTION_ARGUMENT; + + memcpy(&s, cmd, write_len); + strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */ + write_len += 2; + bytes_written = 0; + + for(;;) { +#ifdef HAVE_GSSAPI + conn->data_prot = PROT_CMD; +#endif + result = Curl_xfer_send(data, sptr, write_len, FALSE, &bytes_written); +#ifdef HAVE_GSSAPI + DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); + conn->data_prot = data_sec; +#endif + + if(result) + break; + + Curl_debug(data, CURLINFO_HEADER_OUT, sptr, bytes_written); + + if(bytes_written != write_len) { + write_len -= bytes_written; + sptr += bytes_written; + } + else + break; + } + + return result; +} + +static int +krb5_init(void *app_data) +{ + gss_ctx_id_t *context = app_data; + /* Make sure our context is initialized for krb5_end. */ + *context = GSS_C_NO_CONTEXT; + return 0; +} + +static int +krb5_check_prot(void *app_data, int level) +{ + (void)app_data; /* unused */ + if(level == PROT_CONFIDENTIAL) + return -1; + return 0; +} + +static int +krb5_decode(void *app_data, void *buf, int len, + int level UNUSED_PARAM, + struct connectdata *conn UNUSED_PARAM) +{ + gss_ctx_id_t *context = app_data; + OM_uint32 maj, min; + gss_buffer_desc enc, dec; + + (void)level; + (void)conn; + + enc.value = buf; + enc.length = len; + maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL); + if(maj != GSS_S_COMPLETE) + return -1; + + memcpy(buf, dec.value, dec.length); + len = curlx_uztosi(dec.length); + gss_release_buffer(&min, &dec); + + return len; +} + +static int +krb5_encode(void *app_data, const void *from, int length, int level, void **to) +{ + gss_ctx_id_t *context = app_data; + gss_buffer_desc dec, enc; + OM_uint32 maj, min; + int state; + int len; + + /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal + * libraries modify the input buffer in gss_wrap() + */ + dec.value = (void *)from; + dec.length = (size_t)length; + maj = gss_wrap(&min, *context, + level == PROT_PRIVATE, + GSS_C_QOP_DEFAULT, + &dec, &state, &enc); + + if(maj != GSS_S_COMPLETE) + return -1; + + /* malloc a new buffer, in case gss_release_buffer does not work as + expected */ + *to = malloc(enc.length); + if(!*to) + return -1; + memcpy(*to, enc.value, enc.length); + len = curlx_uztosi(enc.length); + gss_release_buffer(&min, &enc); + return len; +} + +static int +krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn) +{ + int ret = AUTH_OK; + char *p; + const char *host = conn->host.name; + ssize_t nread; + curl_socklen_t l = sizeof(conn->local_addr); + CURLcode result; + const char *service = data->set.str[STRING_SERVICE_NAME] ? + data->set.str[STRING_SERVICE_NAME] : + "ftp"; + const char *srv_host = "host"; + gss_buffer_desc input_buffer, output_buffer, *gssresp; + gss_buffer_desc _gssresp = GSS_C_EMPTY_BUFFER; + OM_uint32 maj, min; + gss_name_t gssname; + gss_ctx_id_t *context = app_data; + struct gss_channel_bindings_struct chan; + size_t base64_sz = 0; + struct sockaddr_in *remote_addr = + (struct sockaddr_in *)(void *)&conn->remote_addr->curl_sa_addr; + char *stringp; + + if(getsockname(conn->sock[FIRSTSOCKET], + (struct sockaddr *)&conn->local_addr, &l) < 0) + perror("getsockname()"); + + chan.initiator_addrtype = GSS_C_AF_INET; + chan.initiator_address.length = l - 4; + chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr; + chan.acceptor_addrtype = GSS_C_AF_INET; + chan.acceptor_address.length = l - 4; + chan.acceptor_address.value = &remote_addr->sin_addr.s_addr; + chan.application_data.length = 0; + chan.application_data.value = NULL; + + /* this loop will execute twice (once for service, once for host) */ + for(;;) { + /* this really should not be repeated here, but cannot help it */ + if(service == srv_host) { + result = ftpsend(data, conn, "AUTH GSSAPI"); + if(result) + return -2; + + if(Curl_GetFTPResponse(data, &nread, NULL)) + return -1; + else { + struct pingpong *pp = &conn->proto.ftpc.pp; + char *line = Curl_dyn_ptr(&pp->recvbuf); + if(line[0] != '3') + return -1; + } + } + + stringp = aprintf("%s@%s", service, host); + if(!stringp) + return -2; + + input_buffer.value = stringp; + input_buffer.length = strlen(stringp); + maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE, + &gssname); + free(stringp); + if(maj != GSS_S_COMPLETE) { + gss_release_name(&min, &gssname); + if(service == srv_host) { + failf(data, "Error importing service name %s@%s", service, host); + return AUTH_ERROR; + } + service = srv_host; + continue; + } + /* We pass NULL as |output_name_type| to avoid a leak. */ + gss_display_name(&min, gssname, &output_buffer, NULL); + infof(data, "Trying against %s", (char *)output_buffer.value); + gssresp = GSS_C_NO_BUFFER; + *context = GSS_C_NO_CONTEXT; + + do { + /* Release the buffer at each iteration to avoid leaking: the first time + we are releasing the memory from gss_display_name. The last item is + taken care by a final gss_release_buffer. */ + gss_release_buffer(&min, &output_buffer); + ret = AUTH_OK; + maj = Curl_gss_init_sec_context(data, + &min, + context, + gssname, + &Curl_krb5_mech_oid, + &chan, + gssresp, + &output_buffer, + TRUE, + NULL); + + if(gssresp) { + free(_gssresp.value); + gssresp = NULL; + } + + if(GSS_ERROR(maj)) { + infof(data, "Error creating security context"); + ret = AUTH_ERROR; + break; + } + + if(output_buffer.length) { + char *cmd; + + result = Curl_base64_encode((char *)output_buffer.value, + output_buffer.length, &p, &base64_sz); + if(result) { + infof(data, "base64-encoding: %s", curl_easy_strerror(result)); + ret = AUTH_ERROR; + break; + } + + cmd = aprintf("ADAT %s", p); + if(cmd) + result = ftpsend(data, conn, cmd); + else + result = CURLE_OUT_OF_MEMORY; + + free(p); + free(cmd); + + if(result) { + ret = -2; + break; + } + + if(Curl_GetFTPResponse(data, &nread, NULL)) { + ret = -1; + break; + } + else { + struct pingpong *pp = &conn->proto.ftpc.pp; + size_t len = Curl_dyn_len(&pp->recvbuf); + p = Curl_dyn_ptr(&pp->recvbuf); + if((len < 4) || (p[0] != '2' && p[0] != '3')) { + infof(data, "Server did not accept auth data"); + ret = AUTH_ERROR; + break; + } + } + + _gssresp.value = NULL; /* make sure it is initialized */ + _gssresp.length = 0; + p += 4; /* over '789 ' */ + p = strstr(p, "ADAT="); + if(p) { + unsigned char *outptr; + size_t outlen; + result = Curl_base64_decode(p + 5, &outptr, &outlen); + if(result) { + failf(data, "base64-decoding: %s", curl_easy_strerror(result)); + ret = AUTH_CONTINUE; + break; + } + _gssresp.value = outptr; + _gssresp.length = outlen; + } + + gssresp = &_gssresp; + } + } while(maj == GSS_S_CONTINUE_NEEDED); + + gss_release_name(&min, &gssname); + gss_release_buffer(&min, &output_buffer); + + if(gssresp) + free(_gssresp.value); + + if(ret == AUTH_OK || service == srv_host) + break; + + service = srv_host; + } + return ret; +} + +static void krb5_end(void *app_data) +{ + OM_uint32 min; + gss_ctx_id_t *context = app_data; + if(*context != GSS_C_NO_CONTEXT) { + OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER); + (void)maj; + DEBUGASSERT(maj == GSS_S_COMPLETE); + } +} + +static const struct Curl_sec_client_mech Curl_krb5_client_mech = { + "GSSAPI", + sizeof(gss_ctx_id_t), + krb5_init, + krb5_auth, + krb5_end, + krb5_check_prot, + + krb5_encode, + krb5_decode +}; + +static const struct { + unsigned char level; + const char *name; +} level_names[] = { + { PROT_CLEAR, "clear" }, + { PROT_SAFE, "safe" }, + { PROT_CONFIDENTIAL, "confidential" }, + { PROT_PRIVATE, "private" } +}; + +static unsigned char name_to_level(const char *name) +{ + int i; + for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++) + if(curl_strequal(name, level_names[i].name)) + return level_names[i].level; + return PROT_NONE; +} + +/* Convert a protocol |level| to its char representation. + We take an int to catch programming mistakes. */ +static char level_to_char(int level) +{ + switch(level) { + case PROT_CLEAR: + return 'C'; + case PROT_SAFE: + return 'S'; + case PROT_CONFIDENTIAL: + return 'E'; + case PROT_PRIVATE: + return 'P'; + case PROT_CMD: + default: + /* Those 2 cases should not be reached! */ + break; + } + DEBUGASSERT(0); + /* Default to the most secure alternative. */ + return 'P'; +} + +/* Send an FTP command defined by |message| and the optional arguments. The + function returns the ftp_code. If an error occurs, -1 is returned. */ +static int ftp_send_command(struct Curl_easy *data, const char *message, ...) + CURL_PRINTF(2, 3); + +static int ftp_send_command(struct Curl_easy *data, const char *message, ...) +{ + int ftp_code; + ssize_t nread = 0; + va_list args; + char print_buffer[50]; + + va_start(args, message); + mvsnprintf(print_buffer, sizeof(print_buffer), message, args); + va_end(args); + + if(ftpsend(data, data->conn, print_buffer)) { + ftp_code = -1; + } + else { + if(Curl_GetFTPResponse(data, &nread, &ftp_code)) + ftp_code = -1; + } + + (void)nread; /* Unused */ + return ftp_code; +} + +/* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode + saying whether an error occurred or CURLE_OK if |len| was read. */ +static CURLcode +socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len) +{ + char *to_p = to; + CURLcode result; + ssize_t nread = 0; + + while(len > 0) { + result = Curl_conn_recv(data, sockindex, to_p, len, &nread); + if(nread > 0) { + len -= nread; + to_p += nread; + } + else { + if(result == CURLE_AGAIN) + continue; + return result; + } + } + return CURLE_OK; +} + + +/* Write |len| bytes from the buffer |to| to the socket |fd|. Return a + CURLcode saying whether an error occurred or CURLE_OK if |len| was + written. */ +static CURLcode +socket_write(struct Curl_easy *data, int sockindex, const void *to, + size_t len) +{ + const char *to_p = to; + CURLcode result; + size_t written; + + while(len > 0) { + result = Curl_conn_send(data, sockindex, to_p, len, FALSE, &written); + if(!result && written > 0) { + len -= written; + to_p += written; + } + else { + if(result == CURLE_AGAIN) + continue; + return result; + } + } + return CURLE_OK; +} + +static CURLcode read_data(struct Curl_easy *data, int sockindex, + struct krb5buffer *buf) +{ + struct connectdata *conn = data->conn; + int len; + CURLcode result; + int nread; + + result = socket_read(data, sockindex, &len, sizeof(len)); + if(result) + return result; + + if(len) { + len = (int)ntohl((uint32_t)len); + if(len > CURL_MAX_INPUT_LENGTH) + return CURLE_TOO_LARGE; + + Curl_dyn_reset(&buf->buf); + } + else + return CURLE_RECV_ERROR; + + do { + char buffer[1024]; + nread = CURLMIN(len, (int)sizeof(buffer)); + result = socket_read(data, sockindex, buffer, (size_t)nread); + if(result) + return result; + result = Curl_dyn_addn(&buf->buf, buffer, nread); + if(result) + return result; + len -= nread; + } while(len); + /* this decodes the dynbuf *in place* */ + nread = conn->mech->decode(conn->app_data, + Curl_dyn_ptr(&buf->buf), + len, conn->data_prot, conn); + if(nread < 0) + return CURLE_RECV_ERROR; + Curl_dyn_setlen(&buf->buf, nread); + buf->index = 0; + return CURLE_OK; +} + +static size_t +buffer_read(struct krb5buffer *buf, void *data, size_t len) +{ + size_t size = Curl_dyn_len(&buf->buf); + if(size - buf->index < len) + len = size - buf->index; + memcpy(data, Curl_dyn_ptr(&buf->buf) + buf->index, len); + buf->index += len; + return len; +} + +/* Matches Curl_recv signature */ +static ssize_t sec_recv(struct Curl_easy *data, int sockindex, + char *buffer, size_t len, CURLcode *err) +{ + size_t bytes_read; + size_t total_read = 0; + struct connectdata *conn = data->conn; + + *err = CURLE_OK; + + /* Handle clear text response. */ + if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR) { + ssize_t nread; + *err = Curl_conn_recv(data, sockindex, buffer, len, &nread); + return nread; + } + + if(conn->in_buffer.eof_flag) { + conn->in_buffer.eof_flag = 0; + return 0; + } + + bytes_read = buffer_read(&conn->in_buffer, buffer, len); + len -= bytes_read; + total_read += bytes_read; + buffer += bytes_read; + + while(len > 0) { + if(read_data(data, sockindex, &conn->in_buffer)) + return -1; + if(Curl_dyn_len(&conn->in_buffer.buf) == 0) { + if(bytes_read > 0) + conn->in_buffer.eof_flag = 1; + return bytes_read; + } + bytes_read = buffer_read(&conn->in_buffer, buffer, len); + len -= bytes_read; + total_read += bytes_read; + buffer += bytes_read; + } + return total_read; +} + +/* Send |length| bytes from |from| to the |sockindex| socket taking care of + encoding and negotiating with the server. |from| can be NULL. */ +static void do_sec_send(struct Curl_easy *data, struct connectdata *conn, + int sockindex, const char *from, int length) +{ + int bytes, htonl_bytes; /* 32-bit integers for htonl */ + char *buffer = NULL; + char *cmd_buffer; + size_t cmd_size = 0; + CURLcode error; + enum protection_level prot_level = conn->data_prot; + bool iscmd = (prot_level == PROT_CMD); + + DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST); + + if(iscmd) { + if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5)) + prot_level = PROT_PRIVATE; + else + prot_level = conn->command_prot; + } + bytes = conn->mech->encode(conn->app_data, from, length, (int)prot_level, + (void **)&buffer); + if(!buffer || bytes <= 0) + return; /* error */ + + if(iscmd) { + error = Curl_base64_encode(buffer, curlx_sitouz(bytes), + &cmd_buffer, &cmd_size); + if(error) { + free(buffer); + return; /* error */ + } + if(cmd_size > 0) { + static const char *enc = "ENC "; + static const char *mic = "MIC "; + if(prot_level == PROT_PRIVATE) + socket_write(data, sockindex, enc, 4); + else + socket_write(data, sockindex, mic, 4); + + socket_write(data, sockindex, cmd_buffer, cmd_size); + socket_write(data, sockindex, "\r\n", 2); + infof(data, "Send: %s%s", prot_level == PROT_PRIVATE ? enc : mic, + cmd_buffer); + free(cmd_buffer); + } + } + else { + htonl_bytes = (int)htonl((OM_uint32)bytes); + socket_write(data, sockindex, &htonl_bytes, sizeof(htonl_bytes)); + socket_write(data, sockindex, buffer, curlx_sitouz(bytes)); + } + free(buffer); +} + +static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn, + int sockindex, const char *buffer, size_t length) +{ + ssize_t tx = 0, len = conn->buffer_size; + + if(len <= 0) + len = length; + while(length) { + if(length < (size_t)len) + len = length; + + do_sec_send(data, conn, sockindex, buffer, curlx_sztosi(len)); + length -= len; + buffer += len; + tx += len; + } + return tx; +} + +/* Matches Curl_send signature */ +static ssize_t sec_send(struct Curl_easy *data, int sockindex, + const void *buffer, size_t len, bool eos, + CURLcode *err) +{ + struct connectdata *conn = data->conn; + (void)eos; /* unused */ + *err = CURLE_OK; + return sec_write(data, conn, sockindex, buffer, len); +} + +int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn, + char *buffer, enum protection_level level) +{ + /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an + int */ + int decoded_len; + char *buf; + int ret_code = 0; + size_t decoded_sz = 0; + CURLcode error; + + (void) data; + + if(!conn->mech) + /* not initialized, return error */ + return -1; + + DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); + + error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz); + if(error || decoded_sz == 0) + return -1; + + if(decoded_sz > (size_t)INT_MAX) { + free(buf); + return -1; + } + decoded_len = curlx_uztosi(decoded_sz); + + decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len, + (int)level, conn); + if(decoded_len <= 0) { + free(buf); + return -1; + } + + { + buf[decoded_len] = '\n'; + Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1); + } + + buf[decoded_len] = '\0'; + if(decoded_len <= 3) + /* suspiciously short */ + return 0; + + if(buf[3] != '-') + ret_code = atoi(buf); + + if(buf[decoded_len - 1] == '\n') + buf[decoded_len - 1] = '\0'; + strcpy(buffer, buf); + free(buf); + return ret_code; +} + +static int sec_set_protection_level(struct Curl_easy *data) +{ + int code; + struct connectdata *conn = data->conn; + unsigned char level = conn->request_data_prot; + + DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); + + if(!conn->sec_complete) { + infof(data, "Trying to change the protection level after the" + " completion of the data exchange."); + return -1; + } + + /* Bail out if we try to set up the same level */ + if(conn->data_prot == level) + return 0; + + if(level) { + char *pbsz; + unsigned int buffer_size = 1 << 20; /* 1048576 */ + struct pingpong *pp = &conn->proto.ftpc.pp; + char *line; + + code = ftp_send_command(data, "PBSZ %u", buffer_size); + if(code < 0) + return -1; + + if(code/100 != 2) { + failf(data, "Failed to set the protection's buffer size."); + return -1; + } + conn->buffer_size = buffer_size; + + line = Curl_dyn_ptr(&pp->recvbuf); + pbsz = strstr(line, "PBSZ="); + if(pbsz) { + /* stick to default value if the check fails */ + if(ISDIGIT(pbsz[5])) + buffer_size = (unsigned int)atoi(&pbsz[5]); + if(buffer_size < conn->buffer_size) + conn->buffer_size = buffer_size; + } + } + + /* Now try to negotiate the protection level. */ + code = ftp_send_command(data, "PROT %c", level_to_char(level)); + + if(code < 0) + return -1; + + if(code/100 != 2) { + failf(data, "Failed to set the protection level."); + return -1; + } + + conn->data_prot = level; + if(level == PROT_PRIVATE) + conn->command_prot = level; + + return 0; +} + +int +Curl_sec_request_prot(struct connectdata *conn, const char *level) +{ + unsigned char l = name_to_level(level); + if(l == PROT_NONE) + return -1; + DEBUGASSERT(l > PROT_NONE && l < PROT_LAST); + conn->request_data_prot = l; + return 0; +} + +static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn) +{ + int ret; + void *tmp_allocation; + const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech; + + tmp_allocation = realloc(conn->app_data, mech->size); + if(!tmp_allocation) { + failf(data, "Failed realloc of size %zu", mech->size); + mech = NULL; + return CURLE_OUT_OF_MEMORY; + } + conn->app_data = tmp_allocation; + + if(mech->init) { + ret = mech->init(conn->app_data); + if(ret) { + infof(data, "Failed initialization for %s. Skipping it.", + mech->name); + return CURLE_FAILED_INIT; + } + Curl_dyn_init(&conn->in_buffer.buf, CURL_MAX_INPUT_LENGTH); + } + + infof(data, "Trying mechanism %s...", mech->name); + ret = ftp_send_command(data, "AUTH %s", mech->name); + if(ret < 0) + return CURLE_COULDNT_CONNECT; + + if(ret/100 != 3) { + switch(ret) { + case 504: + infof(data, "Mechanism %s is not supported by the server (server " + "returned ftp code: 504).", mech->name); + break; + case 534: + infof(data, "Mechanism %s was rejected by the server (server returned " + "ftp code: 534).", mech->name); + break; + default: + if(ret/100 == 5) { + infof(data, "server does not support the security extensions"); + return CURLE_USE_SSL_FAILED; + } + break; + } + return CURLE_LOGIN_DENIED; + } + + /* Authenticate */ + ret = mech->auth(conn->app_data, data, conn); + + if(ret != AUTH_CONTINUE) { + if(ret != AUTH_OK) { + /* Mechanism has dumped the error to stderr, do not error here. */ + return CURLE_USE_SSL_FAILED; + } + DEBUGASSERT(ret == AUTH_OK); + + conn->mech = mech; + conn->sec_complete = 1; + conn->recv[FIRSTSOCKET] = sec_recv; + conn->send[FIRSTSOCKET] = sec_send; + conn->recv[SECONDARYSOCKET] = sec_recv; + conn->send[SECONDARYSOCKET] = sec_send; + conn->command_prot = PROT_SAFE; + /* Set the requested protection level */ + /* BLOCKING */ + (void)sec_set_protection_level(data); + } + + return CURLE_OK; +} + +CURLcode +Curl_sec_login(struct Curl_easy *data, struct connectdata *conn) +{ + return choose_mech(data, conn); +} + + +void +Curl_sec_end(struct connectdata *conn) +{ + if(conn->mech && conn->mech->end) + conn->mech->end(conn->app_data); + Curl_safefree(conn->app_data); + Curl_dyn_free(&conn->in_buffer.buf); + conn->in_buffer.index = 0; + conn->in_buffer.eof_flag = 0; + conn->sec_complete = 0; + conn->data_prot = PROT_CLEAR; + conn->mech = NULL; +} + +#endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */ diff --git a/local-test-curl-full-01/afc-curl/lib/ldap.c b/local-test-curl-full-01/afc-curl/lib/ldap.c new file mode 100644 index 0000000000000000000000000000000000000000..2cbdb9c214255418895684cdb1767ec9cca49893 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/ldap.c @@ -0,0 +1,1116 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP) + +/* + * Notice that USE_OPENLDAP is only a source code selection switch. When + * libcurl is built with USE_OPENLDAP defined the libcurl source code that + * gets compiled is the code from openldap.c, otherwise the code that gets + * compiled is the code from ldap.c. + * + * When USE_OPENLDAP is defined a recent version of the OpenLDAP library + * might be required for compilation and runtime. In order to use ancient + * OpenLDAP library versions, USE_OPENLDAP shall not be defined. + */ + +/* Wincrypt must be included before anything that could include OpenSSL. */ +#if defined(USE_WIN32_CRYPTO) +#include +/* Undefine wincrypt conflicting symbols for BoringSSL. */ +#undef X509_NAME +#undef X509_EXTENSIONS +#undef PKCS7_ISSUER_AND_SERIAL +#undef PKCS7_SIGNER_INFO +#undef OCSP_REQUEST +#undef OCSP_RESPONSE +#endif + +#ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */ +# ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4201) +# endif +# include /* for [P]UNICODE_STRING */ +# ifdef _MSC_VER +# pragma warning(pop) +# endif +# include +# ifndef LDAP_VENDOR_NAME +# error Your Platform SDK is NOT sufficient for LDAP support! \ + Update your Platform SDK, or disable LDAP support! +# else +# include +# endif +#else +# define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */ +# ifdef HAVE_LBER_H +# include +# endif +# include +# if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H)) +# include +# endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */ +#endif + +#include "urldata.h" +#include +#include "sendf.h" +#include "escape.h" +#include "progress.h" +#include "transfer.h" +#include "strcase.h" +#include "strtok.h" +#include "curl_ldap.h" +#include "curl_multibyte.h" +#include "curl_base64.h" +#include "connect.h" +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#ifndef HAVE_LDAP_URL_PARSE + +/* Use our own implementation. */ + +struct ldap_urldesc { + char *lud_host; + int lud_port; +#if defined(USE_WIN32_LDAP) + TCHAR *lud_dn; + TCHAR **lud_attrs; +#else + char *lud_dn; + char **lud_attrs; +#endif + int lud_scope; +#if defined(USE_WIN32_LDAP) + TCHAR *lud_filter; +#else + char *lud_filter; +#endif + char **lud_exts; + size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the + "real" struct so can only be used in code + without HAVE_LDAP_URL_PARSE defined */ +}; + +#undef LDAPURLDesc +#define LDAPURLDesc struct ldap_urldesc + +static int _ldap_url_parse(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludp); +static void _ldap_free_urldesc(LDAPURLDesc *ludp); + +#undef ldap_free_urldesc +#define ldap_free_urldesc _ldap_free_urldesc +#endif + +#ifdef DEBUG_LDAP + #define LDAP_TRACE(x) do { \ + _ldap_trace("%u: ", __LINE__); \ + _ldap_trace x; \ + } while(0) + + static void _ldap_trace(const char *fmt, ...) CURL_PRINTF(1, 2); +#else + #define LDAP_TRACE(x) Curl_nop_stmt +#endif + +#if defined(USE_WIN32_LDAP) && defined(ldap_err2string) +/* Use ANSI error strings in Unicode builds */ +#undef ldap_err2string +#define ldap_err2string ldap_err2stringA +#endif + +#if defined(USE_WIN32_LDAP) && defined(_MSC_VER) && (_MSC_VER <= 1600) +/* Workaround for warning: + 'type cast' : conversion from 'int' to 'void *' of greater size */ +#undef LDAP_OPT_ON +#undef LDAP_OPT_OFF +#define LDAP_OPT_ON ((void *)(size_t)1) +#define LDAP_OPT_OFF ((void *)(size_t)0) +#endif + +static CURLcode ldap_do(struct Curl_easy *data, bool *done); + +/* + * LDAP protocol handler. + */ + +const struct Curl_handler Curl_handler_ldap = { + "ldap", /* scheme */ + ZERO_NULL, /* setup_connection */ + ldap_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAP, /* defport */ + CURLPROTO_LDAP, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_NONE /* flags */ +}; + +#ifdef HAVE_LDAP_SSL +/* + * LDAPS protocol handler. + */ + +const struct Curl_handler Curl_handler_ldaps = { + "ldaps", /* scheme */ + ZERO_NULL, /* setup_connection */ + ldap_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_LDAPS, /* defport */ + CURLPROTO_LDAPS, /* protocol */ + CURLPROTO_LDAP, /* family */ + PROTOPT_SSL /* flags */ +}; +#endif + +#if defined(USE_WIN32_LDAP) + +#if defined(USE_WINDOWS_SSPI) +static int ldap_win_bind_auth(LDAP *server, const char *user, + const char *passwd, unsigned long authflags) +{ + ULONG method = 0; + SEC_WINNT_AUTH_IDENTITY cred; + int rc = LDAP_AUTH_METHOD_NOT_SUPPORTED; + + memset(&cred, 0, sizeof(cred)); + +#if defined(USE_SPNEGO) + if(authflags & CURLAUTH_NEGOTIATE) { + method = LDAP_AUTH_NEGOTIATE; + } + else +#endif +#if defined(USE_NTLM) + if(authflags & CURLAUTH_NTLM) { + method = LDAP_AUTH_NTLM; + } + else +#endif +#if !defined(CURL_DISABLE_DIGEST_AUTH) + if(authflags & CURLAUTH_DIGEST) { + method = LDAP_AUTH_DIGEST; + } + else +#endif + { + /* required anyway if one of upper preprocessor definitions enabled */ + } + + if(method && user && passwd) { + CURLcode res = Curl_create_sspi_identity(user, passwd, &cred); + rc = (int)res; + if(!rc) { + rc = (int)ldap_bind_s(server, NULL, (TCHAR *)&cred, method); + Curl_sspi_free_identity(&cred); + } + } + else { + /* proceed with current user credentials */ + method = LDAP_AUTH_NEGOTIATE; + rc = (int)ldap_bind_s(server, NULL, NULL, method); + } + return rc; +} +#endif /* #if defined(USE_WINDOWS_SSPI) */ + +static int ldap_win_bind(struct Curl_easy *data, LDAP *server, + const char *user, const char *passwd) +{ + int rc = LDAP_INVALID_CREDENTIALS; + + PTCHAR inuser = NULL; + PTCHAR inpass = NULL; + + if(user && passwd && (data->set.httpauth & CURLAUTH_BASIC)) { + inuser = curlx_convert_UTF8_to_tchar((char *) user); + inpass = curlx_convert_UTF8_to_tchar((char *) passwd); + + rc = (int)ldap_simple_bind_s(server, inuser, inpass); + + curlx_unicodefree(inuser); + curlx_unicodefree(inpass); + } +#if defined(USE_WINDOWS_SSPI) + else { + rc = (int)ldap_win_bind_auth(server, user, passwd, data->set.httpauth); + } +#endif + + return rc; +} +#endif /* #if defined(USE_WIN32_LDAP) */ + +#if defined(USE_WIN32_LDAP) +#define FREE_ON_WINLDAP(x) curlx_unicodefree(x) +#define curl_ldap_num_t ULONG +#else +#define FREE_ON_WINLDAP(x) +#define curl_ldap_num_t int +#endif + + +static CURLcode ldap_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + int rc = 0; + LDAP *server = NULL; + LDAPURLDesc *ludp = NULL; + LDAPMessage *ldapmsg = NULL; + LDAPMessage *entryIterator; + int num = 0; + struct connectdata *conn = data->conn; + int ldap_proto = LDAP_VERSION3; + int ldap_ssl = 0; + char *val_b64 = NULL; + size_t val_b64_sz = 0; +#ifdef LDAP_OPT_NETWORK_TIMEOUT + struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */ +#endif +#if defined(USE_WIN32_LDAP) + TCHAR *host = NULL; +#else + char *host = NULL; +#endif + char *user = NULL; + char *passwd = NULL; + + *done = TRUE; /* unconditionally */ + infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d", + LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); + infof(data, "LDAP local: %s", data->state.url); + +#ifdef HAVE_LDAP_URL_PARSE + rc = ldap_url_parse(data->state.url, &ludp); +#else + rc = _ldap_url_parse(data, conn, &ludp); +#endif + if(rc) { + failf(data, "Bad LDAP URL: %s", ldap_err2string((curl_ldap_num_t)rc)); + result = CURLE_URL_MALFORMAT; + goto quit; + } + + /* Get the URL scheme (either ldap or ldaps) */ + if(conn->given->flags & PROTOPT_SSL) + ldap_ssl = 1; + infof(data, "LDAP local: trying to establish %s connection", + ldap_ssl ? "encrypted" : "cleartext"); + +#if defined(USE_WIN32_LDAP) + host = curlx_convert_UTF8_to_tchar(conn->host.name); + if(!host) { + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + host = conn->host.name; +#endif + + if(data->state.aptr.user) { + user = conn->user; + passwd = conn->passwd; + } + +#ifdef LDAP_OPT_NETWORK_TIMEOUT + ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); +#endif + ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); + + if(ldap_ssl) { +#ifdef HAVE_LDAP_SSL +#ifdef USE_WIN32_LDAP + /* Win32 LDAP SDK does not support insecure mode without CA! */ + server = ldap_sslinit(host, (curl_ldap_num_t)conn->primary.remote_port, 1); + ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); +#else + int ldap_option; + char *ldap_ca = conn->ssl_config.CAfile; +#if defined(CURL_HAS_NOVELL_LDAPSDK) + rc = ldapssl_client_init(NULL, NULL); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + if(conn->ssl_config.verifypeer) { + /* Novell SDK supports DER or BASE64 files. */ + int cert_type = LDAPSSL_CERT_FILETYPE_B64; + if((data->set.ssl.cert_type) && + (strcasecompare(data->set.ssl.cert_type, "DER"))) + cert_type = LDAPSSL_CERT_FILETYPE_DER; + if(!ldap_ca) { + failf(data, "LDAP local: ERROR %s CA cert not set", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM")); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + infof(data, "LDAP local: using %s CA cert '%s'", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), + ldap_ca); + rc = ldapssl_add_trusted_cert(ldap_ca, cert_type); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting %s CA cert: %s", + (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAPSSL_VERIFY_SERVER; + } + else + ldap_option = LDAPSSL_VERIFY_NONE; + rc = ldapssl_set_verify_mode(ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting cert verify mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + server = ldapssl_init(host, conn->primary.remote_port, 1); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } +#elif defined(LDAP_OPT_X_TLS) + if(conn->ssl_config.verifypeer) { + /* OpenLDAP SDK supports BASE64 files. */ + if((data->set.ssl.cert_type) && + (!strcasecompare(data->set.ssl.cert_type, "PEM"))) { + failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + if(!ldap_ca) { + failf(data, "LDAP local: ERROR PEM CA cert not set"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + infof(data, "LDAP local: using PEM CA cert: %s", ldap_ca); + rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting PEM CA cert: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_DEMAND; + } + else + ldap_option = LDAP_OPT_X_TLS_NEVER; + + rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting cert verify mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } + server = ldap_init(host, conn->primary.remote_port); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } + ldap_option = LDAP_OPT_X_TLS_HARD; + rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } +/* + rc = ldap_start_tls_s(server, NULL, NULL); + if(rc != LDAP_SUCCESS) { + failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s", + ldap_err2string(rc)); + result = CURLE_SSL_CERTPROBLEM; + goto quit; + } +*/ +#else + (void)ldap_option; + (void)ldap_ca; + /* we should probably never come up to here since configure + should check in first place if we can support LDAP SSL/TLS */ + failf(data, "LDAP local: SSL/TLS not supported with this version " + "of the OpenLDAP toolkit\n"); + result = CURLE_SSL_CERTPROBLEM; + goto quit; +#endif +#endif +#endif /* CURL_LDAP_USE_SSL */ + } + else if(data->set.use_ssl > CURLUSESSL_TRY) { + failf(data, "LDAP local: explicit TLS not supported"); + result = CURLE_NOT_BUILT_IN; + goto quit; + } + else { + server = ldap_init(host, (curl_ldap_num_t)conn->primary.remote_port); + if(!server) { + failf(data, "LDAP local: Cannot connect to %s:%u", + conn->host.dispname, conn->primary.remote_port); + result = CURLE_COULDNT_CONNECT; + goto quit; + } + } +#ifdef USE_WIN32_LDAP + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + if(!ldap_ssl && rc) { + ldap_proto = LDAP_VERSION2; + ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); +#ifdef USE_WIN32_LDAP + rc = ldap_win_bind(data, server, user, passwd); +#else + rc = ldap_simple_bind_s(server, user, passwd); +#endif + } + if(rc) { +#ifdef USE_WIN32_LDAP + failf(data, "LDAP local: bind via ldap_win_bind %s", + ldap_err2string((ULONG)rc)); +#else + failf(data, "LDAP local: bind via ldap_simple_bind_s %s", + ldap_err2string(rc)); +#endif + result = CURLE_LDAP_CANNOT_BIND; + goto quit; + } + + Curl_pgrsSetDownloadCounter(data, 0); + rc = (int)ldap_search_s(server, ludp->lud_dn, + (curl_ldap_num_t)ludp->lud_scope, + ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); + + if(rc && rc != LDAP_SIZELIMIT_EXCEEDED) { + failf(data, "LDAP remote: %s", ldap_err2string((curl_ldap_num_t)rc)); + result = CURLE_LDAP_SEARCH_FAILED; + goto quit; + } + + num = 0; + for(entryIterator = ldap_first_entry(server, ldapmsg); + entryIterator; + entryIterator = ldap_next_entry(server, entryIterator), num++) { + BerElement *ber = NULL; +#if defined(USE_WIN32_LDAP) + TCHAR *attribute; +#else + char *attribute; +#endif + int i; + + /* Get the DN and write it to the client */ + { + char *name; + size_t name_len; +#if defined(USE_WIN32_LDAP) + TCHAR *dn = ldap_get_dn(server, entryIterator); + name = curlx_convert_tchar_to_UTF8(dn); + if(!name) { + ldap_memfree(dn); + + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + char *dn = name = ldap_get_dn(server, entryIterator); +#endif + name_len = strlen(name); + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, name, name_len); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) { + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + + goto quit; + } + + FREE_ON_WINLDAP(name); + ldap_memfree(dn); + } + + /* Get the attributes and write them to the client */ + for(attribute = ldap_first_attribute(server, entryIterator, &ber); + attribute; + attribute = ldap_next_attribute(server, entryIterator, ber)) { + BerValue **vals; + size_t attr_len; +#if defined(USE_WIN32_LDAP) + char *attr = curlx_convert_tchar_to_UTF8(attribute); + if(!attr) { + if(ber) + ber_free(ber, 0); + + result = CURLE_OUT_OF_MEMORY; + + goto quit; + } +#else + char *attr = attribute; +#endif + attr_len = strlen(attr); + + vals = ldap_get_values_len(server, entryIterator, attribute); + if(vals) { + for(i = 0; (vals[i] != NULL); i++) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, attr, attr_len); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + if((attr_len > 7) && + (strcmp(";binary", attr + (attr_len - 7)) == 0)) { + /* Binary attribute, encode to base64. */ + result = Curl_base64_encode(vals[i]->bv_val, vals[i]->bv_len, + &val_b64, &val_b64_sz); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + + if(val_b64_sz > 0) { + result = Curl_client_write(data, CLIENTWRITE_BODY, val_b64, + val_b64_sz); + free(val_b64); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + } + else { + result = Curl_client_write(data, CLIENTWRITE_BODY, vals[i]->bv_val, + vals[i]->bv_len); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) { + ldap_value_free_len(vals); + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + if(ber) + ber_free(ber, 0); + + goto quit; + } + } + + /* Free memory used to store values */ + ldap_value_free_len(vals); + } + + /* Free the attribute as we are done with it */ + FREE_ON_WINLDAP(attr); + ldap_memfree(attribute); + + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); + if(result) + goto quit; + } + + if(ber) + ber_free(ber, 0); + } + +quit: + if(ldapmsg) { + ldap_msgfree(ldapmsg); + LDAP_TRACE(("Received %d entries\n", num)); + } + if(rc == LDAP_SIZELIMIT_EXCEEDED) + infof(data, "There are more than %d entries", num); + if(ludp) + ldap_free_urldesc(ludp); + if(server) + ldap_unbind_s(server); +#if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK) + if(ldap_ssl) + ldapssl_client_deinit(); +#endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */ + + FREE_ON_WINLDAP(host); + + /* no data to transfer */ + Curl_xfer_setup_nop(data); + connclose(conn, "LDAP connection always disable reuse"); + + return result; +} + +#ifdef DEBUG_LDAP +static void _ldap_trace(const char *fmt, ...) +{ + static int do_trace = -1; + va_list args; + + if(do_trace == -1) { + const char *env = getenv("CURL_TRACE"); + do_trace = (env && strtol(env, NULL, 10) > 0); + } + if(!do_trace) + return; + + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); +} +#endif + +#ifndef HAVE_LDAP_URL_PARSE + +/* + * Return scope-value for a scope-string. + */ +static int str2scope(const char *p) +{ + if(strcasecompare(p, "one")) + return LDAP_SCOPE_ONELEVEL; + if(strcasecompare(p, "onetree")) + return LDAP_SCOPE_ONELEVEL; + if(strcasecompare(p, "base")) + return LDAP_SCOPE_BASE; + if(strcasecompare(p, "sub")) + return LDAP_SCOPE_SUBTREE; + if(strcasecompare(p, "subtree")) + return LDAP_SCOPE_SUBTREE; + return (-1); +} + +/* + * Split 'str' into strings separated by commas. + * Note: out[] points into 'str'. + */ +static bool split_str(char *str, char ***out, size_t *count) +{ + char **res; + char *lasts; + char *s; + size_t i; + size_t items = 1; + + s = strchr(str, ','); + while(s) { + items++; + s = strchr(++s, ','); + } + + res = calloc(items, sizeof(char *)); + if(!res) + return FALSE; + + for(i = 0, s = Curl_strtok_r(str, ",", &lasts); s && i < items; + s = Curl_strtok_r(NULL, ",", &lasts), i++) + res[i] = s; + + *out = res; + *count = items; + + return TRUE; +} + +/* + * Break apart the pieces of an LDAP URL. + * Syntax: + * ldap://:/???? + * + * already known from 'conn->host.name'. + * already known from 'conn->remote_port'. + * extract the rest from 'data->state.path+1'. All fields are optional. + * e.g. + * ldap://:/??? + * yields ludp->lud_dn = "". + * + * Defined in RFC4516 section 2. + */ +static int _ldap_url_parse2(struct Curl_easy *data, + const struct connectdata *conn, LDAPURLDesc *ludp) +{ + int rc = LDAP_SUCCESS; + char *p; + char *path; + char *q = NULL; + char *query = NULL; + size_t i; + + if(!data || + !data->state.up.path || + data->state.up.path[0] != '/' || + !strncasecompare("LDAP", data->state.up.scheme, 4)) + return LDAP_INVALID_SYNTAX; + + ludp->lud_scope = LDAP_SCOPE_BASE; + ludp->lud_port = conn->remote_port; + ludp->lud_host = conn->host.name; + + /* Duplicate the path */ + p = path = strdup(data->state.up.path + 1); + if(!path) + return LDAP_NO_MEMORY; + + /* Duplicate the query if present */ + if(data->state.up.query) { + q = query = strdup(data->state.up.query); + if(!query) { + free(path); + return LDAP_NO_MEMORY; + } + } + + /* Parse the DN (Distinguished Name) */ + if(*p) { + char *dn = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("DN '%s'\n", dn)); + + /* Unescape the DN */ + result = Curl_urldecode(dn, 0, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_dn = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_dn) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_dn = unescaped; +#endif + } + + p = q; + if(!p) + goto quit; + + /* Parse the attributes. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + char **attributes; + size_t count = 0; + + /* Split the string into an array of attributes */ + if(!split_str(p, &attributes, &count)) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + + /* Allocate our array (+1 for the NULL entry) */ +#if defined(USE_WIN32_LDAP) + ludp->lud_attrs = calloc(count + 1, sizeof(TCHAR *)); +#else + ludp->lud_attrs = calloc(count + 1, sizeof(char *)); +#endif + if(!ludp->lud_attrs) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } + + for(i = 0; i < count; i++) { + char *unescaped; + CURLcode result; + + LDAP_TRACE(("attr[%zu] '%s'\n", i, attributes[i])); + + /* Unescape the attribute */ + result = Curl_urldecode(attributes[i], 0, &unescaped, NULL, + REJECT_ZERO); + if(result) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_attrs[i] = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_attrs[i]) { + free(attributes); + + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_attrs[i] = unescaped; +#endif + + ludp->lud_attrs_dups++; + } + + free(attributes); + } + + p = q; + if(!p) + goto quit; + + /* Parse the scope. skip "??" */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + ludp->lud_scope = str2scope(p); + if(ludp->lud_scope == -1) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + LDAP_TRACE(("scope %d\n", ludp->lud_scope)); + } + + p = q; + if(!p) + goto quit; + + /* Parse the filter */ + q = strchr(p, '?'); + if(q) + *q++ = '\0'; + + if(*p) { + char *filter = p; + char *unescaped; + CURLcode result; + + LDAP_TRACE(("filter '%s'\n", filter)); + + /* Unescape the filter */ + result = Curl_urldecode(filter, 0, &unescaped, NULL, REJECT_ZERO); + if(result) { + rc = LDAP_NO_MEMORY; + + goto quit; + } + +#if defined(USE_WIN32_LDAP) + /* Convert the unescaped string to a tchar */ + ludp->lud_filter = curlx_convert_UTF8_to_tchar(unescaped); + + /* Free the unescaped string as we are done with it */ + free(unescaped); + + if(!ludp->lud_filter) { + rc = LDAP_NO_MEMORY; + + goto quit; + } +#else + ludp->lud_filter = unescaped; +#endif + } + + p = q; + if(p && !*p) { + rc = LDAP_INVALID_SYNTAX; + + goto quit; + } + +quit: + free(path); + free(query); + + return rc; +} + +static int _ldap_url_parse(struct Curl_easy *data, + const struct connectdata *conn, + LDAPURLDesc **ludpp) +{ + LDAPURLDesc *ludp = calloc(1, sizeof(*ludp)); + int rc; + + *ludpp = NULL; + if(!ludp) + return LDAP_NO_MEMORY; + + rc = _ldap_url_parse2(data, conn, ludp); + if(rc != LDAP_SUCCESS) { + _ldap_free_urldesc(ludp); + ludp = NULL; + } + *ludpp = ludp; + return (rc); +} + +static void _ldap_free_urldesc(LDAPURLDesc *ludp) +{ + if(!ludp) + return; + +#if defined(USE_WIN32_LDAP) + curlx_unicodefree(ludp->lud_dn); + curlx_unicodefree(ludp->lud_filter); +#else + free(ludp->lud_dn); + free(ludp->lud_filter); +#endif + + if(ludp->lud_attrs) { + size_t i; + for(i = 0; i < ludp->lud_attrs_dups; i++) { +#if defined(USE_WIN32_LDAP) + curlx_unicodefree(ludp->lud_attrs[i]); +#else + free(ludp->lud_attrs[i]); +#endif + } + free(ludp->lud_attrs); + } + + free(ludp); +} +#endif /* !HAVE_LDAP_URL_PARSE */ +#endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */ diff --git a/local-test-curl-full-01/afc-curl/lib/libcurl.rc b/local-test-curl-full-01/afc-curl/lib/libcurl.rc new file mode 100644 index 0000000000000000000000000000000000000000..1ceb4691fb8476d2246ffaf50c5ddbeb4ab138d6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/libcurl.rc @@ -0,0 +1,65 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include +#include "../include/curl/curlver.h" + +LANGUAGE 0, 0 + +#define RC_VERSION LIBCURL_VERSION_MAJOR, LIBCURL_VERSION_MINOR, LIBCURL_VERSION_PATCH, 0 + +VS_VERSION_INFO VERSIONINFO + FILEVERSION RC_VERSION + PRODUCTVERSION RC_VERSION + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#if defined(DEBUGBUILD) || defined(UNITTESTS) || defined(CURLDEBUG) || defined(_DEBUG) + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0L + +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "The curl library, https://curl.se/\0" + VALUE "FileDescription", "libcurl Shared Library\0" + VALUE "FileVersion", LIBCURL_VERSION "\0" + VALUE "InternalName", "libcurl\0" + VALUE "OriginalFilename", "libcurl.dll\0" + VALUE "ProductName", "The curl library\0" + VALUE "ProductVersion", LIBCURL_VERSION "\0" + VALUE "LegalCopyright", "Copyright (C) " LIBCURL_COPYRIGHT "\0" + VALUE "License", "https://curl.se/docs/copyright.html\0" + END + END + + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END diff --git a/local-test-curl-full-01/afc-curl/lib/llist.h b/local-test-curl-full-01/afc-curl/lib/llist.h new file mode 100644 index 0000000000000000000000000000000000000000..26581869a3f662cf9cd112d0852fe863cd7a69bf --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/llist.h @@ -0,0 +1,89 @@ +#ifndef HEADER_CURL_LLIST_H +#define HEADER_CURL_LLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#include + +typedef void (*Curl_llist_dtor)(void *user, void *elem); + +/* none of these struct members should be referenced directly, use the + dedicated functions */ + +struct Curl_llist { + struct Curl_llist_node *_head; + struct Curl_llist_node *_tail; + Curl_llist_dtor _dtor; + size_t _size; +#ifdef DEBUGBUILD + int _init; /* detect API usage mistakes */ +#endif +}; + +struct Curl_llist_node { + struct Curl_llist *_list; /* the list where this belongs */ + void *_ptr; + struct Curl_llist_node *_prev; + struct Curl_llist_node *_next; +#ifdef DEBUGBUILD + int _init; /* detect API usage mistakes */ +#endif +}; + +void Curl_llist_init(struct Curl_llist *, Curl_llist_dtor); +void Curl_llist_insert_next(struct Curl_llist *, struct Curl_llist_node *, + const void *, struct Curl_llist_node *node); +void Curl_llist_append(struct Curl_llist *, + const void *, struct Curl_llist_node *node); +void Curl_node_uremove(struct Curl_llist_node *, void *); +void Curl_node_remove(struct Curl_llist_node *); +void Curl_llist_destroy(struct Curl_llist *, void *); + +/* Curl_llist_head() returns the first 'struct Curl_llist_node *', which + might be NULL */ +struct Curl_llist_node *Curl_llist_head(struct Curl_llist *list); + +/* Curl_llist_tail() returns the last 'struct Curl_llist_node *', which + might be NULL */ +struct Curl_llist_node *Curl_llist_tail(struct Curl_llist *list); + +/* Curl_llist_count() returns a size_t the number of nodes in the list */ +size_t Curl_llist_count(struct Curl_llist *list); + +/* Curl_node_elem() returns the custom data from a Curl_llist_node */ +void *Curl_node_elem(struct Curl_llist_node *n); + +/* Curl_node_next() returns the next element in a list from a given + Curl_llist_node */ +struct Curl_llist_node *Curl_node_next(struct Curl_llist_node *n); + +/* Curl_node_prev() returns the previous element in a list from a given + Curl_llist_node */ +struct Curl_llist_node *Curl_node_prev(struct Curl_llist_node *n); + +/* Curl_node_llist() return the list the node is in or NULL. */ +struct Curl_llist *Curl_node_llist(struct Curl_llist_node *n); + +#endif /* HEADER_CURL_LLIST_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/macos.h b/local-test-curl-full-01/afc-curl/lib/macos.h new file mode 100644 index 0000000000000000000000000000000000000000..637860e80fc1ba31d50d09b4a378452ef711d7ed --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/macos.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_MACOS_H +#define HEADER_CURL_MACOS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef CURL_MACOS_CALL_COPYPROXIES + +CURLcode Curl_macos_init(void); + +#else + +#define Curl_macos_init() CURLE_OK + +#endif + +#endif /* HEADER_CURL_MACOS_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/md5.c b/local-test-curl-full-01/afc-curl/lib/md5.c new file mode 100644 index 0000000000000000000000000000000000000000..1cf12318107655a616c1db89297453ede7567022 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/md5.c @@ -0,0 +1,673 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if (defined(USE_CURL_NTLM_CORE) && !defined(USE_WINDOWS_SSPI)) \ + || !defined(CURL_DISABLE_DIGEST_AUTH) + +#include +#include + +#include "curl_md5.h" +#include "curl_hmac.h" +#include "warnless.h" + +#ifdef USE_MBEDTLS +#include + +#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ + (MBEDTLS_VERSION_NUMBER < 0x03000000) + #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS +#endif +#endif /* USE_MBEDTLS */ + +#ifdef USE_OPENSSL + #include + #if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_DEPRECATED_3_0) + #define USE_OPENSSL_MD5 + #endif +#endif + +#ifdef USE_WOLFSSL + #include + #ifndef NO_MD5 + #define USE_WOLFSSL_MD5 + #endif +#endif + +#if defined(USE_GNUTLS) +#include +#elif defined(USE_OPENSSL_MD5) +#include +#elif defined(USE_WOLFSSL_MD5) +#include +#elif defined(USE_MBEDTLS) +#include +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ + defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \ + (__MAC_OS_X_VERSION_MIN_REQUIRED < 101500)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000) && \ + defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \ + (__IPHONE_OS_VERSION_MIN_REQUIRED < 130000)) +#define AN_APPLE_OS +#include +#elif defined(USE_WIN32_CRYPTO) +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +#if defined(USE_GNUTLS) + +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + md5_init(ctx); + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, + unsigned int inputLen) +{ + md5_update(ctx, inputLen, input); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + md5_digest(ctx, 16, digest); +} + +#elif defined(USE_OPENSSL_MD5) || \ + (defined(USE_WOLFSSL_MD5) && !defined(OPENSSL_COEXIST)) + +typedef MD5_CTX my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + if(!MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, + unsigned int len) +{ + (void)MD5_Update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + (void)MD5_Final(digest, ctx); +} + +#elif defined(USE_WOLFSSL_MD5) + +typedef WOLFSSL_MD5_CTX my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ + if(!wolfSSL_MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, + unsigned int len) +{ + (void)wolfSSL_MD5_Update(ctx, input, len); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + (void)wolfSSL_MD5_Final(digest, ctx); +} + +#elif defined(USE_MBEDTLS) + +typedef mbedtls_md5_context my_md5_ctx; + +static CURLcode my_md5_init(void *ctx) +{ +#if (MBEDTLS_VERSION_NUMBER >= 0x03000000) + if(mbedtls_md5_starts(ctx)) + return CURLE_OUT_OF_MEMORY; +#elif defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + if(mbedtls_md5_starts_ret(ctx)) + return CURLE_OUT_OF_MEMORY; +#else + (void)mbedtls_md5_starts(ctx); +#endif + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_md5_update(ctx, data, length); +#else + (void) mbedtls_md5_update_ret(ctx, data, length); +#endif +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_md5_finish(ctx, digest); +#else + (void) mbedtls_md5_finish_ret(ctx, digest); +#endif +} + +#elif defined(AN_APPLE_OS) + +/* For Apple operating systems: CommonCrypto has the functions we need. + These functions are available on Tiger and later, as well as iOS 2.0 + and later. If you are building for an older cat, well, sorry. + + Declaring the functions as static like this seems to be a bit more + reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */ +# define my_md5_ctx CC_MD5_CTX + +static CURLcode my_md5_init(void *ctx) +{ + if(!CC_MD5_Init(ctx)) + return CURLE_OUT_OF_MEMORY; + + return CURLE_OK; +} + +static void my_md5_update(void *ctx, + const unsigned char *input, + unsigned int inputLen) +{ + CC_MD5_Update(ctx, input, inputLen); +} + +static void my_md5_final(unsigned char *digest, void *ctx) +{ + CC_MD5_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) + +struct md5_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_md5_update(void *in, + const unsigned char *input, + unsigned int inputLen) +{ + my_md5_ctx *ctx = in; + CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0); +} + +static void my_md5_final(unsigned char *digest, void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + unsigned long length = 0; + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == 16) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* + * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. + * MD5 Message-Digest Algorithm (RFC 1321). + * + * Homepage: + https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 + * + * Author: + * Alexander Peslyak, better known as Solar Designer + * + * This software was written by Alexander Peslyak in 2001. No copyright is + * claimed, and the software is hereby placed in the public domain. + * In case this attempt to disclaim copyright and place the software in the + * public domain is deemed null and void, then the software is + * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the + * general public under the following terms: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * There is ABSOLUTELY NO WARRANTY, express or implied. + * + * (This is a heavily cut-down "BSD license".) + * + * This differs from Colin Plumb's older public domain implementation in that + * no exactly 32-bit integer data type is required (any 32-bit or wider + * unsigned integer data type will do), there is no compile-time endianness + * configuration, and the function prototypes match OpenSSL's. No code from + * Colin Plumb's implementation has been reused; this comment merely compares + * the properties of the two independent implementations. + * + * The primary goals of this implementation are portability and ease of use. + * It is meant to be fast, but not as fast as possible. Some known + * optimizations are not included to reduce source code size and avoid + * compile-time configuration. + */ + +/* Any 32-bit or wider unsigned integer data type will do */ +typedef unsigned int MD5_u32plus; + +struct md5_ctx { + MD5_u32plus lo, hi; + MD5_u32plus a, b, c, d; + unsigned char buffer[64]; + MD5_u32plus block[16]; +}; +typedef struct md5_ctx my_md5_ctx; + +static CURLcode my_md5_init(void *ctx); +static void my_md5_update(void *ctx, const unsigned char *data, + unsigned int size); +static void my_md5_final(unsigned char *result, void *ctx); + +/* + * The basic MD5 functions. + * + * F and G are optimized compared to their RFC 1321 definitions for + * architectures that lack an AND-NOT instruction, just like in Colin Plumb's + * implementation. + */ +#define MD5_F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define MD5_G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) +#define MD5_H(x, y, z) (((x) ^ (y)) ^ (z)) +#define MD5_H2(x, y, z) ((x) ^ ((y) ^ (z))) +#define MD5_I(x, y, z) ((y) ^ ((x) | ~(z))) + +/* + * The MD5 transformation for all four rounds. + */ +#define MD5_STEP(f, a, b, c, d, x, t, s) \ + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); + +/* + * SET reads 4 input bytes in little-endian byte order and stores them + * in a properly aligned word in host byte order. + * + * The check for little-endian architectures that tolerate unaligned + * memory accesses is just an optimization. Nothing will break if it + * does not work. + */ +#if defined(__i386__) || defined(__x86_64__) || defined(__vax__) +#define MD5_SET(n) \ + (*(MD5_u32plus *)(void *)&ptr[(n) * 4]) +#define MD5_GET(n) \ + MD5_SET(n) +#else +#define MD5_SET(n) \ + (ctx->block[(n)] = \ + (MD5_u32plus)ptr[(n) * 4] | \ + ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ + ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ + ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) +#define MD5_GET(n) \ + (ctx->block[(n)]) +#endif + +/* + * This processes one or more 64-byte data blocks, but does NOT update + * the bit counters. There are no alignment requirements. + */ +static const void *my_md5_body(my_md5_ctx *ctx, + const void *data, unsigned long size) +{ + const unsigned char *ptr; + MD5_u32plus a, b, c, d; + + ptr = (const unsigned char *)data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + MD5_u32plus saved_a, saved_b, saved_c, saved_d; + + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + +/* Round 1 */ + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(0), 0xd76aa478, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(1), 0xe8c7b756, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(2), 0x242070db, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(3), 0xc1bdceee, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(4), 0xf57c0faf, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(5), 0x4787c62a, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(6), 0xa8304613, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(7), 0xfd469501, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(8), 0x698098d8, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(9), 0x8b44f7af, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(10), 0xffff5bb1, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(11), 0x895cd7be, 22) + MD5_STEP(MD5_F, a, b, c, d, MD5_SET(12), 0x6b901122, 7) + MD5_STEP(MD5_F, d, a, b, c, MD5_SET(13), 0xfd987193, 12) + MD5_STEP(MD5_F, c, d, a, b, MD5_SET(14), 0xa679438e, 17) + MD5_STEP(MD5_F, b, c, d, a, MD5_SET(15), 0x49b40821, 22) + +/* Round 2 */ + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(1), 0xf61e2562, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(6), 0xc040b340, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(11), 0x265e5a51, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(0), 0xe9b6c7aa, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(5), 0xd62f105d, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(10), 0x02441453, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(15), 0xd8a1e681, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(4), 0xe7d3fbc8, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(9), 0x21e1cde6, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(14), 0xc33707d6, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(3), 0xf4d50d87, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(8), 0x455a14ed, 20) + MD5_STEP(MD5_G, a, b, c, d, MD5_GET(13), 0xa9e3e905, 5) + MD5_STEP(MD5_G, d, a, b, c, MD5_GET(2), 0xfcefa3f8, 9) + MD5_STEP(MD5_G, c, d, a, b, MD5_GET(7), 0x676f02d9, 14) + MD5_STEP(MD5_G, b, c, d, a, MD5_GET(12), 0x8d2a4c8a, 20) + +/* Round 3 */ + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(5), 0xfffa3942, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(8), 0x8771f681, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(11), 0x6d9d6122, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(14), 0xfde5380c, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(1), 0xa4beea44, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(4), 0x4bdecfa9, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(7), 0xf6bb4b60, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(10), 0xbebfbc70, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(13), 0x289b7ec6, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(0), 0xeaa127fa, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(3), 0xd4ef3085, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(6), 0x04881d05, 23) + MD5_STEP(MD5_H, a, b, c, d, MD5_GET(9), 0xd9d4d039, 4) + MD5_STEP(MD5_H2, d, a, b, c, MD5_GET(12), 0xe6db99e5, 11) + MD5_STEP(MD5_H, c, d, a, b, MD5_GET(15), 0x1fa27cf8, 16) + MD5_STEP(MD5_H2, b, c, d, a, MD5_GET(2), 0xc4ac5665, 23) + +/* Round 4 */ + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(0), 0xf4292244, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(7), 0x432aff97, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(14), 0xab9423a7, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(5), 0xfc93a039, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(12), 0x655b59c3, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(3), 0x8f0ccc92, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(10), 0xffeff47d, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(1), 0x85845dd1, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(8), 0x6fa87e4f, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(15), 0xfe2ce6e0, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(6), 0xa3014314, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(13), 0x4e0811a1, 21) + MD5_STEP(MD5_I, a, b, c, d, MD5_GET(4), 0xf7537e82, 6) + MD5_STEP(MD5_I, d, a, b, c, MD5_GET(11), 0xbd3af235, 10) + MD5_STEP(MD5_I, c, d, a, b, MD5_GET(2), 0x2ad7d2bb, 15) + MD5_STEP(MD5_I, b, c, d, a, MD5_GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += 64; + } while(size -= 64); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; +} + +static CURLcode my_md5_init(void *in) +{ + my_md5_ctx *ctx = (my_md5_ctx *)in; + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; + + ctx->lo = 0; + ctx->hi = 0; + + return CURLE_OK; +} + +static void my_md5_update(void *in, const unsigned char *data, + unsigned int size) +{ + MD5_u32plus saved_lo; + unsigned int used; + my_md5_ctx *ctx = (my_md5_ctx *)in; + + saved_lo = ctx->lo; + ctx->lo = (saved_lo + size) & 0x1fffffff; + if(ctx->lo < saved_lo) + ctx->hi++; + ctx->hi += (MD5_u32plus)size >> 29; + + used = saved_lo & 0x3f; + + if(used) { + unsigned int available = 64 - used; + + if(size < available) { + memcpy(&ctx->buffer[used], data, size); + return; + } + + memcpy(&ctx->buffer[used], data, available); + data = (const unsigned char *)data + available; + size -= available; + my_md5_body(ctx, ctx->buffer, 64); + } + + if(size >= 64) { + data = my_md5_body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); +} + +static void my_md5_final(unsigned char *result, void *in) +{ + unsigned int used, available; + my_md5_ctx *ctx = (my_md5_ctx *)in; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + available = 64 - used; + + if(available < 8) { + memset(&ctx->buffer[used], 0, available); + my_md5_body(ctx, ctx->buffer, 64); + used = 0; + available = 64; + } + + memset(&ctx->buffer[used], 0, available - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); + ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); + ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); + ctx->buffer[59] = curlx_ultouc(ctx->lo >> 24); + ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); + ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); + ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); + ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); + + my_md5_body(ctx, ctx->buffer, 64); + + result[0] = curlx_ultouc((ctx->a)&0xff); + result[1] = curlx_ultouc((ctx->a >> 8)&0xff); + result[2] = curlx_ultouc((ctx->a >> 16)&0xff); + result[3] = curlx_ultouc(ctx->a >> 24); + result[4] = curlx_ultouc((ctx->b)&0xff); + result[5] = curlx_ultouc((ctx->b >> 8)&0xff); + result[6] = curlx_ultouc((ctx->b >> 16)&0xff); + result[7] = curlx_ultouc(ctx->b >> 24); + result[8] = curlx_ultouc((ctx->c)&0xff); + result[9] = curlx_ultouc((ctx->c >> 8)&0xff); + result[10] = curlx_ultouc((ctx->c >> 16)&0xff); + result[11] = curlx_ultouc(ctx->c >> 24); + result[12] = curlx_ultouc((ctx->d)&0xff); + result[13] = curlx_ultouc((ctx->d >> 8)&0xff); + result[14] = curlx_ultouc((ctx->d >> 16)&0xff); + result[15] = curlx_ultouc(ctx->d >> 24); + + memset(ctx, 0, sizeof(*ctx)); +} + +#endif /* CRYPTO LIBS */ + +const struct HMAC_params Curl_HMAC_MD5 = { + my_md5_init, /* Hash initialization function. */ + my_md5_update, /* Hash update function. */ + my_md5_final, /* Hash computation end function. */ + sizeof(my_md5_ctx), /* Size of hash context structure. */ + 64, /* Maximum key length. */ + 16 /* Result size. */ +}; + +const struct MD5_params Curl_DIGEST_MD5 = { + my_md5_init, /* Digest initialization function */ + my_md5_update, /* Digest update function */ + my_md5_final, /* Digest computation end function */ + sizeof(my_md5_ctx), /* Size of digest context struct */ + 16 /* Result size */ +}; + +/* + * @unittest: 1601 + * Returns CURLE_OK on success. + */ +CURLcode Curl_md5it(unsigned char *outbuffer, const unsigned char *input, + const size_t len) +{ + CURLcode result; + my_md5_ctx ctx; + + result = my_md5_init(&ctx); + if(!result) { + my_md5_update(&ctx, input, curlx_uztoui(len)); + my_md5_final(outbuffer, &ctx); + } + return result; +} + +struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params) +{ + struct MD5_context *ctxt; + + /* Create MD5 context */ + ctxt = malloc(sizeof(*ctxt)); + + if(!ctxt) + return ctxt; + + ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize); + + if(!ctxt->md5_hashctx) { + free(ctxt); + return NULL; + } + + ctxt->md5_hash = md5params; + + if((*md5params->md5_init_func)(ctxt->md5_hashctx)) { + free(ctxt->md5_hashctx); + free(ctxt); + return NULL; + } + + return ctxt; +} + +CURLcode Curl_MD5_update(struct MD5_context *context, + const unsigned char *data, + unsigned int len) +{ + (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len); + + return CURLE_OK; +} + +CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result) +{ + (*context->md5_hash->md5_final_func)(result, context->md5_hashctx); + + free(context->md5_hashctx); + free(context); + + return CURLE_OK; +} + +#endif /* Using NTLM (without SSPI) || Digest */ diff --git a/local-test-curl-full-01/afc-curl/lib/mime.h b/local-test-curl-full-01/afc-curl/lib/mime.h new file mode 100644 index 0000000000000000000000000000000000000000..5073a38f709a03b8c910a477303f44a13d973c23 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/mime.h @@ -0,0 +1,176 @@ +#ifndef HEADER_CURL_MIME_H +#define HEADER_CURL_MIME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#define MIME_BOUNDARY_DASHES 24 /* leading boundary dashes */ +#define MIME_RAND_BOUNDARY_CHARS 22 /* Nb. of random boundary chars. */ +#define MAX_ENCODED_LINE_LENGTH 76 /* Maximum encoded line length. */ +#define ENCODING_BUFFER_SIZE 256 /* Encoding temp buffers size. */ + +/* Part flags. */ +#define MIME_USERHEADERS_OWNER (1 << 0) +#define MIME_BODY_ONLY (1 << 1) +#define MIME_FAST_READ (1 << 2) + +#define FILE_CONTENTTYPE_DEFAULT "application/octet-stream" +#define MULTIPART_CONTENTTYPE_DEFAULT "multipart/mixed" +#define DISPOSITION_DEFAULT "attachment" + +/* Part source kinds. */ +enum mimekind { + MIMEKIND_NONE = 0, /* Part not set. */ + MIMEKIND_DATA, /* Allocated mime data. */ + MIMEKIND_FILE, /* Data from file. */ + MIMEKIND_CALLBACK, /* Data from `read' callback. */ + MIMEKIND_MULTIPART, /* Data is a mime subpart. */ + MIMEKIND_LAST +}; + +/* Readback state tokens. */ +enum mimestate { + MIMESTATE_BEGIN, /* Readback has not yet started. */ + MIMESTATE_CURLHEADERS, /* In curl-generated headers. */ + MIMESTATE_USERHEADERS, /* In caller's supplied headers. */ + MIMESTATE_EOH, /* End of headers. */ + MIMESTATE_BODY, /* Placeholder. */ + MIMESTATE_BOUNDARY1, /* In boundary prefix. */ + MIMESTATE_BOUNDARY2, /* In boundary. */ + MIMESTATE_CONTENT, /* In content. */ + MIMESTATE_END, /* End of part reached. */ + MIMESTATE_LAST +}; + +/* Mime headers strategies. */ +enum mimestrategy { + MIMESTRATEGY_MAIL, /* Mime mail. */ + MIMESTRATEGY_FORM, /* HTTP post form. */ + MIMESTRATEGY_LAST +}; + +/* Content transfer encoder. */ +struct mime_encoder { + const char * name; /* Encoding name. */ + size_t (*encodefunc)(char *buffer, size_t size, bool ateof, + curl_mimepart *part); /* Encoded read. */ + curl_off_t (*sizefunc)(curl_mimepart *part); /* Encoded size. */ +}; + +/* Content transfer encoder state. */ +struct mime_encoder_state { + size_t pos; /* Position on output line. */ + size_t bufbeg; /* Next data index in input buffer. */ + size_t bufend; /* First unused byte index in input buffer. */ + char buf[ENCODING_BUFFER_SIZE]; /* Input buffer. */ +}; + +/* Mime readback state. */ +struct mime_state { + enum mimestate state; /* Current state token. */ + void *ptr; /* State-dependent pointer. */ + curl_off_t offset; /* State-dependent offset. */ +}; + +/* Boundary string length. */ +#define MIME_BOUNDARY_LEN (MIME_BOUNDARY_DASHES + MIME_RAND_BOUNDARY_CHARS) + +/* A mime multipart. */ +struct curl_mime { + curl_mimepart *parent; /* Parent part. */ + curl_mimepart *firstpart; /* First part. */ + curl_mimepart *lastpart; /* Last part. */ + char boundary[MIME_BOUNDARY_LEN + 1]; /* The part boundary. */ + struct mime_state state; /* Current readback state. */ +}; + +/* A mime part. */ +struct curl_mimepart { + curl_mime *parent; /* Parent mime structure. */ + curl_mimepart *nextpart; /* Forward linked list. */ + enum mimekind kind; /* The part kind. */ + unsigned int flags; /* Flags. */ + char *data; /* Memory data or filename. */ + curl_read_callback readfunc; /* Read function. */ + curl_seek_callback seekfunc; /* Seek function. */ + curl_free_callback freefunc; /* Argument free function. */ + void *arg; /* Argument to callback functions. */ + FILE *fp; /* File pointer. */ + struct curl_slist *curlheaders; /* Part headers. */ + struct curl_slist *userheaders; /* Part headers. */ + char *mimetype; /* Part mime type. */ + char *filename; /* Remote filename. */ + char *name; /* Data name. */ + curl_off_t datasize; /* Expected data size. */ + struct mime_state state; /* Current readback state. */ + const struct mime_encoder *encoder; /* Content data encoder. */ + struct mime_encoder_state encstate; /* Data encoder state. */ + size_t lastreadstatus; /* Last read callback returned status. */ +}; + +CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...) + CURL_PRINTF(2, 3); + +#if !defined(CURL_DISABLE_MIME) && (!defined(CURL_DISABLE_HTTP) || \ + !defined(CURL_DISABLE_SMTP) || \ + !defined(CURL_DISABLE_IMAP)) + +/* Prototypes. */ +void Curl_mime_initpart(struct curl_mimepart *part); +void Curl_mime_cleanpart(struct curl_mimepart *part); +CURLcode Curl_mime_duppart(struct Curl_easy *data, + struct curl_mimepart *dst, + const curl_mimepart *src); +CURLcode Curl_mime_set_subparts(struct curl_mimepart *part, + struct curl_mime *subparts, + int take_ownership); +CURLcode Curl_mime_prepare_headers(struct Curl_easy *data, + struct curl_mimepart *part, + const char *contenttype, + const char *disposition, + enum mimestrategy strategy); +size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, + void *instream); +const char *Curl_mime_contenttype(const char *filename); + +/** + * Install a client reader as upload source that reads the given + * mime part. + */ +CURLcode Curl_creader_set_mime(struct Curl_easy *data, curl_mimepart *part); + +#else +/* if disabled */ +#define Curl_mime_initpart(x) +#define Curl_mime_cleanpart(x) +#define Curl_mime_duppart(x,y,z) CURLE_OK /* Nothing to duplicate. Succeed */ +#define Curl_mime_set_subparts(a,b,c) CURLE_NOT_BUILT_IN +#define Curl_mime_prepare_headers(a,b,c,d,e) CURLE_NOT_BUILT_IN +#define Curl_mime_read NULL +#define Curl_creader_set_mime(x,y) ((void)x, CURLE_NOT_BUILT_IN) +#endif + + +#endif /* HEADER_CURL_MIME_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/mprintf.c b/local-test-curl-full-01/afc-curl/lib/mprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..35e40e302dea62b88f793c1d34e092fd1ba4d126 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/mprintf.c @@ -0,0 +1,1218 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + */ + +#include "curl_setup.h" +#include "dynbuf.h" +#include "curl_printf.h" + +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * If SIZEOF_SIZE_T has not been defined, default to the size of long. + */ + +#ifdef HAVE_LONGLONG +# define LONG_LONG_TYPE long long +# define HAVE_LONG_LONG_TYPE +#else +# if defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define LONG_LONG_TYPE __int64 +# define HAVE_LONG_LONG_TYPE +# else +# undef LONG_LONG_TYPE +# undef HAVE_LONG_LONG_TYPE +# endif +#endif + +/* + * Max integer data types that mprintf.c is capable + */ + +#ifdef HAVE_LONG_LONG_TYPE +# define mp_intmax_t LONG_LONG_TYPE +# define mp_uintmax_t unsigned LONG_LONG_TYPE +#else +# define mp_intmax_t long +# define mp_uintmax_t unsigned long +#endif + +#define BUFFSIZE 326 /* buffer for long-to-str and float-to-str calcs, should + fit negative DBL_MAX (317 letters) */ +#define MAX_PARAMETERS 128 /* number of input arguments */ +#define MAX_SEGMENTS 128 /* number of output segments */ + +#ifdef __AMIGA__ +# undef FORMAT_INT +#endif + +/* Lower-case digits. */ +static const char lower_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/* Upper-case digits. */ +static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +#define OUTCHAR(x) \ + do { \ + if(!stream((unsigned char)x, userp)) \ + done++; \ + else \ + return done; /* return on failure */ \ + } while(0) + +/* Data type to read from the arglist */ +typedef enum { + FORMAT_STRING, + FORMAT_PTR, + FORMAT_INTPTR, + FORMAT_INT, + FORMAT_LONG, + FORMAT_LONGLONG, + FORMAT_INTU, + FORMAT_LONGU, + FORMAT_LONGLONGU, + FORMAT_DOUBLE, + FORMAT_LONGDOUBLE, + FORMAT_WIDTH, + FORMAT_PRECISION +} FormatType; + +/* conversion and display flags */ +enum { + FLAGS_SPACE = 1 << 0, + FLAGS_SHOWSIGN = 1 << 1, + FLAGS_LEFT = 1 << 2, + FLAGS_ALT = 1 << 3, + FLAGS_SHORT = 1 << 4, + FLAGS_LONG = 1 << 5, + FLAGS_LONGLONG = 1 << 6, + FLAGS_LONGDOUBLE = 1 << 7, + FLAGS_PAD_NIL = 1 << 8, + FLAGS_UNSIGNED = 1 << 9, + FLAGS_OCTAL = 1 << 10, + FLAGS_HEX = 1 << 11, + FLAGS_UPPER = 1 << 12, + FLAGS_WIDTH = 1 << 13, /* '*' or '*$' used */ + FLAGS_WIDTHPARAM = 1 << 14, /* width PARAMETER was specified */ + FLAGS_PREC = 1 << 15, /* precision was specified */ + FLAGS_PRECPARAM = 1 << 16, /* precision PARAMETER was specified */ + FLAGS_CHAR = 1 << 17, /* %c story */ + FLAGS_FLOATE = 1 << 18, /* %e or %E */ + FLAGS_FLOATG = 1 << 19, /* %g or %G */ + FLAGS_SUBSTR = 1 << 20 /* no input, only substring */ +}; + +enum { + DOLLAR_UNKNOWN, + DOLLAR_NOPE, + DOLLAR_USE +}; + +/* + * Describes an input va_arg type and hold its value. + */ +struct va_input { + FormatType type; /* FormatType */ + union { + char *str; + void *ptr; + mp_intmax_t nums; /* signed */ + mp_uintmax_t numu; /* unsigned */ + double dnum; + } val; +}; + +/* + * Describes an output segment. + */ +struct outsegment { + int width; /* width OR width parameter number */ + int precision; /* precision OR precision parameter number */ + unsigned int flags; + unsigned int input; /* input argument array index */ + char *start; /* format string start to output */ + size_t outlen; /* number of bytes from the format string to output */ +}; + +struct nsprintf { + char *buffer; + size_t length; + size_t max; +}; + +struct asprintf { + struct dynbuf *b; + char merr; +}; + +/* the provided input number is 1-based but this returns the number 0-based. + + returns -1 if no valid number was provided. +*/ +static int dollarstring(char *input, char **end) +{ + if(ISDIGIT(*input)) { + int number = 0; + do { + if(number < MAX_PARAMETERS) { + number *= 10; + number += *input - '0'; + } + input++; + } while(ISDIGIT(*input)); + + if(number && (number <= MAX_PARAMETERS) && ('$' == *input)) { + *end = ++input; + return number - 1; + } + } + return -1; +} + +/* + * Parse the format string. + * + * Create two arrays. One describes the inputs, one describes the outputs. + * + * Returns zero on success. + */ + +#define PFMT_OK 0 +#define PFMT_DOLLAR 1 /* bad dollar for main param */ +#define PFMT_DOLLARWIDTH 2 /* bad dollar use for width */ +#define PFMT_DOLLARPREC 3 /* bad dollar use for precision */ +#define PFMT_MANYARGS 4 /* too many input arguments used */ +#define PFMT_PREC 5 /* precision overflow */ +#define PFMT_PRECMIX 6 /* bad mix of precision specifiers */ +#define PFMT_WIDTH 7 /* width overflow */ +#define PFMT_INPUTGAP 8 /* gap in arguments */ +#define PFMT_WIDTHARG 9 /* attempted to use same arg twice, for width */ +#define PFMT_PRECARG 10 /* attempted to use same arg twice, for prec */ +#define PFMT_MANYSEGS 11 /* maxed out output segments */ + +static int parsefmt(const char *format, + struct outsegment *out, + struct va_input *in, + int *opieces, + int *ipieces, va_list arglist) +{ + char *fmt = (char *)format; + int param_num = 0; + int param; + int width; + int precision; + unsigned int flags; + FormatType type; + int max_param = -1; + int i; + int ocount = 0; + unsigned char usedinput[MAX_PARAMETERS/8]; + size_t outlen = 0; + struct outsegment *optr; + int use_dollar = DOLLAR_UNKNOWN; + char *start = fmt; + + /* clear, set a bit for each used input */ + memset(usedinput, 0, sizeof(usedinput)); + + while(*fmt) { + if(*fmt == '%') { + struct va_input *iptr; + bool loopit = TRUE; + fmt++; + outlen = (size_t)(fmt - start - 1); + if(*fmt == '%') { + /* this means a %% that should be output only as %. Create an output + segment. */ + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + start = fmt; + fmt++; + continue; /* while */ + } + + flags = 0; + width = precision = 0; + + if(use_dollar != DOLLAR_NOPE) { + param = dollarstring(fmt, &fmt); + if(param < 0) { + if(use_dollar == DOLLAR_USE) + /* illegal combo */ + return PFMT_DOLLAR; + + /* we got no positional, just get the next arg */ + param = -1; + use_dollar = DOLLAR_NOPE; + } + else + use_dollar = DOLLAR_USE; + } + else + param = -1; + + /* Handle the flags */ + while(loopit) { + switch(*fmt++) { + case ' ': + flags |= FLAGS_SPACE; + break; + case '+': + flags |= FLAGS_SHOWSIGN; + break; + case '-': + flags |= FLAGS_LEFT; + flags &= ~(unsigned int)FLAGS_PAD_NIL; + break; + case '#': + flags |= FLAGS_ALT; + break; + case '.': + if('*' == *fmt) { + /* The precision is picked from a specified parameter */ + flags |= FLAGS_PRECPARAM; + fmt++; + + if(use_dollar == DOLLAR_USE) { + precision = dollarstring(fmt, &fmt); + if(precision < 0) + /* illegal combo */ + return PFMT_DOLLARPREC; + } + else + /* get it from the next argument */ + precision = -1; + } + else { + bool is_neg = FALSE; + flags |= FLAGS_PREC; + precision = 0; + if('-' == *fmt) { + is_neg = TRUE; + fmt++; + } + while(ISDIGIT(*fmt)) { + int n = *fmt - '0'; + if(precision > (INT_MAX - n) / 10) + return PFMT_PREC; + precision = precision * 10 + n; + fmt++; + } + if(is_neg) + precision = -precision; + } + if((flags & (FLAGS_PREC | FLAGS_PRECPARAM)) == + (FLAGS_PREC | FLAGS_PRECPARAM)) + /* it is not permitted to use both kinds of precision for the same + argument */ + return PFMT_PRECMIX; + break; + case 'h': + flags |= FLAGS_SHORT; + break; +#if defined(_WIN32) || defined(_WIN32_WCE) + case 'I': + /* Non-ANSI integer extensions I32 I64 */ + if((fmt[0] == '3') && (fmt[1] == '2')) { + flags |= FLAGS_LONG; + fmt += 2; + } + else if((fmt[0] == '6') && (fmt[1] == '4')) { + flags |= FLAGS_LONGLONG; + fmt += 2; + } + else { +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + } + break; +#endif /* _WIN32 || _WIN32_WCE */ + case 'l': + if(flags & FLAGS_LONG) + flags |= FLAGS_LONGLONG; + else + flags |= FLAGS_LONG; + break; + case 'L': + flags |= FLAGS_LONGDOUBLE; + break; + case 'q': + flags |= FLAGS_LONGLONG; + break; + case 'z': + /* the code below generates a warning if -Wunreachable-code is + used */ +#if (SIZEOF_SIZE_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case 'O': +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) + flags |= FLAGS_LONGLONG; +#else + flags |= FLAGS_LONG; +#endif + break; + case '0': + if(!(flags & FLAGS_LEFT)) + flags |= FLAGS_PAD_NIL; + FALLTHROUGH(); + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + flags |= FLAGS_WIDTH; + width = 0; + fmt--; + do { + int n = *fmt - '0'; + if(width > (INT_MAX - n) / 10) + return PFMT_WIDTH; + width = width * 10 + n; + fmt++; + } while(ISDIGIT(*fmt)); + break; + case '*': /* read width from argument list */ + flags |= FLAGS_WIDTHPARAM; + if(use_dollar == DOLLAR_USE) { + width = dollarstring(fmt, &fmt); + if(width < 0) + /* illegal combo */ + return PFMT_DOLLARWIDTH; + } + else + /* pick from the next argument */ + width = -1; + break; + default: + loopit = FALSE; + fmt--; + break; + } /* switch */ + } /* while */ + + switch(*fmt) { + case 'S': + flags |= FLAGS_ALT; + FALLTHROUGH(); + case 's': + type = FORMAT_STRING; + break; + case 'n': + type = FORMAT_INTPTR; + break; + case 'p': + type = FORMAT_PTR; + break; + case 'd': + case 'i': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONG; + else if(flags & FLAGS_LONG) + type = FORMAT_LONG; + else + type = FORMAT_INT; + break; + case 'u': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONGU; + else if(flags & FLAGS_LONG) + type = FORMAT_LONGU; + else + type = FORMAT_INTU; + flags |= FLAGS_UNSIGNED; + break; + case 'o': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONGU; + else if(flags & FLAGS_LONG) + type = FORMAT_LONGU; + else + type = FORMAT_INTU; + flags |= FLAGS_OCTAL|FLAGS_UNSIGNED; + break; + case 'x': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONGU; + else if(flags & FLAGS_LONG) + type = FORMAT_LONGU; + else + type = FORMAT_INTU; + flags |= FLAGS_HEX|FLAGS_UNSIGNED; + break; + case 'X': + if(flags & FLAGS_LONGLONG) + type = FORMAT_LONGLONGU; + else if(flags & FLAGS_LONG) + type = FORMAT_LONGU; + else + type = FORMAT_INTU; + flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED; + break; + case 'c': + type = FORMAT_INT; + flags |= FLAGS_CHAR; + break; + case 'f': + type = FORMAT_DOUBLE; + break; + case 'e': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATE; + break; + case 'E': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATE|FLAGS_UPPER; + break; + case 'g': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATG; + break; + case 'G': + type = FORMAT_DOUBLE; + flags |= FLAGS_FLOATG|FLAGS_UPPER; + break; + default: + /* invalid instruction, disregard and continue */ + continue; + } /* switch */ + + if(flags & FLAGS_WIDTHPARAM) { + if(width < 0) + width = param_num++; + else { + /* if this identifies a parameter already used, this + is illegal */ + if(usedinput[width/8] & (1 << (width&7))) + return PFMT_WIDTHARG; + } + if(width >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(width >= max_param) + max_param = width; + + in[width].type = FORMAT_WIDTH; + /* mark as used */ + usedinput[width/8] |= (unsigned char)(1 << (width&7)); + } + + if(flags & FLAGS_PRECPARAM) { + if(precision < 0) + precision = param_num++; + else { + /* if this identifies a parameter already used, this + is illegal */ + if(usedinput[precision/8] & (1 << (precision&7))) + return PFMT_PRECARG; + } + if(precision >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(precision >= max_param) + max_param = precision; + + in[precision].type = FORMAT_PRECISION; + usedinput[precision/8] |= (unsigned char)(1 << (precision&7)); + } + + /* Handle the specifier */ + if(param < 0) + param = param_num++; + if(param >= MAX_PARAMETERS) + return PFMT_MANYARGS; + if(param >= max_param) + max_param = param; + + iptr = &in[param]; + iptr->type = type; + + /* mark this input as used */ + usedinput[param/8] |= (unsigned char)(1 << (param&7)); + + fmt++; + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = (unsigned int)param; + optr->flags = flags; + optr->width = width; + optr->precision = precision; + optr->start = start; + optr->outlen = outlen; + start = fmt; + } + else + fmt++; + } + + /* is there a trailing piece */ + outlen = (size_t)(fmt - start); + if(outlen) { + optr = &out[ocount++]; + if(ocount > MAX_SEGMENTS) + return PFMT_MANYSEGS; + optr->input = 0; + optr->flags = FLAGS_SUBSTR; + optr->start = start; + optr->outlen = outlen; + } + + /* Read the arg list parameters into our data list */ + for(i = 0; i < max_param + 1; i++) { + struct va_input *iptr = &in[i]; + if(!(usedinput[i/8] & (1 << (i&7)))) + /* bad input */ + return PFMT_INPUTGAP; + + /* based on the type, read the correct argument */ + switch(iptr->type) { + case FORMAT_STRING: + iptr->val.str = va_arg(arglist, char *); + break; + + case FORMAT_INTPTR: + case FORMAT_PTR: + iptr->val.ptr = va_arg(arglist, void *); + break; + + case FORMAT_LONGLONGU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, mp_uintmax_t); + break; + + case FORMAT_LONGLONG: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, mp_intmax_t); + break; + + case FORMAT_LONGU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned long); + break; + + case FORMAT_LONG: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, long); + break; + + case FORMAT_INTU: + iptr->val.numu = (mp_uintmax_t)va_arg(arglist, unsigned int); + break; + + case FORMAT_INT: + case FORMAT_WIDTH: + case FORMAT_PRECISION: + iptr->val.nums = (mp_intmax_t)va_arg(arglist, int); + break; + + case FORMAT_DOUBLE: + iptr->val.dnum = va_arg(arglist, double); + break; + + default: + DEBUGASSERT(NULL); /* unexpected */ + break; + } + } + *ipieces = max_param + 1; + *opieces = ocount; + + return PFMT_OK; +} + +/* + * formatf() - the general printf function. + * + * It calls parsefmt() to parse the format string. It populates two arrays; + * one that describes the input arguments and one that describes a number of + * output segments. + * + * On success, the input array describes the type of all arguments and their + * values. + * + * The function then iterates over the output segments and outputs them one + * by one until done. Using the appropriate input arguments (if any). + * + * All output is sent to the 'stream()' callback, one byte at a time. + */ + +static int formatf( + void *userp, /* untouched by format(), just sent to the stream() function in + the second argument */ + /* function pointer called for each output character */ + int (*stream)(unsigned char, void *), + const char *format, /* %-formatted string */ + va_list ap_save) /* list of parameters */ +{ + static const char nilstr[] = "(nil)"; + const char *digits = lower_digits; /* Base-36 digits for numbers. */ + int done = 0; /* number of characters written */ + int i; + int ocount = 0; /* number of output segments */ + int icount = 0; /* number of input arguments */ + + struct outsegment output[MAX_SEGMENTS]; + struct va_input input[MAX_PARAMETERS]; + char work[BUFFSIZE]; + + /* 'workend' points to the final buffer byte position, but with an extra + byte as margin to avoid the (FALSE?) warning Coverity gives us + otherwise */ + char *workend = &work[sizeof(work) - 2]; + + /* Parse the format string */ + if(parsefmt(format, output, input, &ocount, &icount, ap_save)) + return 0; + + for(i = 0; i < ocount; i++) { + struct outsegment *optr = &output[i]; + struct va_input *iptr; + bool is_alt; /* Format spec modifiers. */ + int width; /* Width of a field. */ + int prec; /* Precision of a field. */ + bool is_neg; /* Decimal integer is negative. */ + unsigned long base; /* Base of a number to be written. */ + mp_uintmax_t num; /* Integral values to be written. */ + mp_intmax_t signed_num; /* Used to convert negative in positive. */ + char *w; + size_t outlen = optr->outlen; + unsigned int flags = optr->flags; + + if(outlen) { + char *str = optr->start; + for(; outlen && *str; outlen--) + OUTCHAR(*str++); + if(optr->flags & FLAGS_SUBSTR) + /* this is just a substring */ + continue; + } + + /* pick up the specified width */ + if(flags & FLAGS_WIDTHPARAM) { + width = (int)input[optr->width].val.nums; + if(width < 0) { + /* "A negative field width is taken as a '-' flag followed by a + positive field width." */ + if(width == INT_MIN) + width = INT_MAX; + else + width = -width; + flags |= FLAGS_LEFT; + flags &= ~(unsigned int)FLAGS_PAD_NIL; + } + } + else + width = optr->width; + + /* pick up the specified precision */ + if(flags & FLAGS_PRECPARAM) { + prec = (int)input[optr->precision].val.nums; + if(prec < 0) + /* "A negative precision is taken as if the precision were + omitted." */ + prec = -1; + } + else if(flags & FLAGS_PREC) + prec = optr->precision; + else + prec = -1; + + is_alt = (flags & FLAGS_ALT) ? 1 : 0; + iptr = &input[optr->input]; + + switch(iptr->type) { + case FORMAT_INTU: + case FORMAT_LONGU: + case FORMAT_LONGLONGU: + flags |= FLAGS_UNSIGNED; + FALLTHROUGH(); + case FORMAT_INT: + case FORMAT_LONG: + case FORMAT_LONGLONG: + num = iptr->val.numu; + if(flags & FLAGS_CHAR) { + /* Character. */ + if(!(flags & FLAGS_LEFT)) + while(--width > 0) + OUTCHAR(' '); + OUTCHAR((char) num); + if(flags & FLAGS_LEFT) + while(--width > 0) + OUTCHAR(' '); + break; + } + if(flags & FLAGS_OCTAL) { + /* Octal unsigned integer */ + base = 8; + is_neg = FALSE; + } + else if(flags & FLAGS_HEX) { + /* Hexadecimal unsigned integer */ + digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits; + base = 16; + is_neg = FALSE; + } + else if(flags & FLAGS_UNSIGNED) { + /* Decimal unsigned integer */ + base = 10; + is_neg = FALSE; + } + else { + /* Decimal integer. */ + base = 10; + + is_neg = (iptr->val.nums < (mp_intmax_t)0); + if(is_neg) { + /* signed_num might fail to hold absolute negative minimum by 1 */ + signed_num = iptr->val.nums + (mp_intmax_t)1; + signed_num = -signed_num; + num = (mp_uintmax_t)signed_num; + num += (mp_uintmax_t)1; + } + } +number: + /* Supply a default precision if none was given. */ + if(prec == -1) + prec = 1; + + /* Put the number in WORK. */ + w = workend; + switch(base) { + case 10: + while(num > 0) { + *w-- = (char)('0' + (num % 10)); + num /= 10; + } + break; + default: + while(num > 0) { + *w-- = digits[num % base]; + num /= base; + } + break; + } + width -= (int)(workend - w); + prec -= (int)(workend - w); + + if(is_alt && base == 8 && prec <= 0) { + *w-- = '0'; + --width; + } + + if(prec > 0) { + width -= prec; + while(prec-- > 0 && w >= work) + *w-- = '0'; + } + + if(is_alt && base == 16) + width -= 2; + + if(is_neg || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE)) + --width; + + if(!(flags & FLAGS_LEFT) && !(flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR(' '); + + if(is_neg) + OUTCHAR('-'); + else if(flags & FLAGS_SHOWSIGN) + OUTCHAR('+'); + else if(flags & FLAGS_SPACE) + OUTCHAR(' '); + + if(is_alt && base == 16) { + OUTCHAR('0'); + if(flags & FLAGS_UPPER) + OUTCHAR('X'); + else + OUTCHAR('x'); + } + + if(!(flags & FLAGS_LEFT) && (flags & FLAGS_PAD_NIL)) + while(width-- > 0) + OUTCHAR('0'); + + /* Write the number. */ + while(++w <= workend) { + OUTCHAR(*w); + } + + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + break; + + case FORMAT_STRING: { + const char *str; + size_t len; + + str = (char *)iptr->val.str; + if(!str) { + /* Write null string if there is space. */ + if(prec == -1 || prec >= (int) sizeof(nilstr) - 1) { + str = nilstr; + len = sizeof(nilstr) - 1; + /* Disable quotes around (nil) */ + flags &= ~(unsigned int)FLAGS_ALT; + } + else { + str = ""; + len = 0; + } + } + else if(prec != -1) + len = (size_t)prec; + else if(*str == '\0') + len = 0; + else + len = strlen(str); + + width -= (len > INT_MAX) ? INT_MAX : (int)len; + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + + for(; len && *str; len--) + OUTCHAR(*str++); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + + if(flags & FLAGS_ALT) + OUTCHAR('"'); + break; + } + + case FORMAT_PTR: + /* Generic pointer. */ + if(iptr->val.ptr) { + /* If the pointer is not NULL, write it as a %#x spec. */ + base = 16; + digits = (flags & FLAGS_UPPER) ? upper_digits : lower_digits; + is_alt = TRUE; + num = (size_t) iptr->val.ptr; + is_neg = FALSE; + goto number; + } + else { + /* Write "(nil)" for a nil pointer. */ + const char *point; + + width -= (int)(sizeof(nilstr) - 1); + if(flags & FLAGS_LEFT) + while(width-- > 0) + OUTCHAR(' '); + for(point = nilstr; *point != '\0'; ++point) + OUTCHAR(*point); + if(!(flags & FLAGS_LEFT)) + while(width-- > 0) + OUTCHAR(' '); + } + break; + + case FORMAT_DOUBLE: { + char formatbuf[32]="%"; + char *fptr = &formatbuf[1]; + size_t left = sizeof(formatbuf)-strlen(formatbuf); + int len; + + if(flags & FLAGS_WIDTH) + width = optr->width; + + if(flags & FLAGS_PREC) + prec = optr->precision; + + if(flags & FLAGS_LEFT) + *fptr++ = '-'; + if(flags & FLAGS_SHOWSIGN) + *fptr++ = '+'; + if(flags & FLAGS_SPACE) + *fptr++ = ' '; + if(flags & FLAGS_ALT) + *fptr++ = '#'; + + *fptr = 0; + + if(width >= 0) { + size_t dlen; + if(width >= (int)sizeof(work)) + width = sizeof(work)-1; + /* RECURSIVE USAGE */ + dlen = (size_t)curl_msnprintf(fptr, left, "%d", width); + fptr += dlen; + left -= dlen; + } + if(prec >= 0) { + /* for each digit in the integer part, we can have one less + precision */ + size_t maxprec = sizeof(work) - 2; + double val = iptr->val.dnum; + if(width > 0 && prec <= width) + maxprec -= (size_t)width; + while(val >= 10.0) { + val /= 10; + maxprec--; + } + + if(prec > (int)maxprec) + prec = (int)maxprec-1; + if(prec < 0) + prec = 0; + /* RECURSIVE USAGE */ + len = curl_msnprintf(fptr, left, ".%d", prec); + fptr += len; + } + if(flags & FLAGS_LONG) + *fptr++ = 'l'; + + if(flags & FLAGS_FLOATE) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'E' : 'e'); + else if(flags & FLAGS_FLOATG) + *fptr++ = (char)((flags & FLAGS_UPPER) ? 'G' : 'g'); + else + *fptr++ = 'f'; + + *fptr = 0; /* and a final null-termination */ + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#endif + /* NOTE NOTE NOTE!! Not all sprintf implementations return number of + output characters */ +#ifdef HAVE_SNPRINTF + (snprintf)(work, sizeof(work), formatbuf, iptr->val.dnum); +#else + (sprintf)(work, formatbuf, iptr->val.dnum); +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + DEBUGASSERT(strlen(work) <= sizeof(work)); + for(fptr = work; *fptr; fptr++) + OUTCHAR(*fptr); + break; + } + + case FORMAT_INTPTR: + /* Answer the count of characters written. */ +#ifdef HAVE_LONG_LONG_TYPE + if(flags & FLAGS_LONGLONG) + *(LONG_LONG_TYPE *) iptr->val.ptr = (LONG_LONG_TYPE)done; + else +#endif + if(flags & FLAGS_LONG) + *(long *) iptr->val.ptr = (long)done; + else if(!(flags & FLAGS_SHORT)) + *(int *) iptr->val.ptr = (int)done; + else + *(short *) iptr->val.ptr = (short)done; + break; + + default: + break; + } + } + return done; +} + +/* fputc() look-alike */ +static int addbyter(unsigned char outc, void *f) +{ + struct nsprintf *infop = f; + if(infop->length < infop->max) { + /* only do this if we have not reached max length yet */ + *infop->buffer++ = (char)outc; /* store */ + infop->length++; /* we are now one byte larger */ + return 0; /* fputc() returns like this on success */ + } + return 1; +} + +int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format, + va_list ap_save) +{ + int retcode; + struct nsprintf info; + + info.buffer = buffer; + info.length = 0; + info.max = maxlength; + + retcode = formatf(&info, addbyter, format, ap_save); + if(info.max) { + /* we terminate this with a zero byte */ + if(info.max == info.length) { + /* we are at maximum, scrap the last letter */ + info.buffer[-1] = 0; + DEBUGASSERT(retcode); + retcode--; /* do not count the nul byte */ + } + else + info.buffer[0] = 0; + } + return retcode; +} + +int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save); + va_end(ap_save); + return retcode; +} + +/* fputc() look-alike */ +static int alloc_addbyter(unsigned char outc, void *f) +{ + struct asprintf *infop = f; + CURLcode result = Curl_dyn_addn(infop->b, &outc, 1); + if(result) { + infop->merr = result == CURLE_TOO_LARGE ? MERR_TOO_LARGE : MERR_MEM; + return 1 ; /* fail */ + } + return 0; +} + +/* appends the formatted string, returns MERR error code */ +int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save) +{ + struct asprintf info; + info.b = dyn; + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, ap_save); + if(info.merr) { + Curl_dyn_free(info.b); + return info.merr; + } + return 0; +} + +char *curl_mvaprintf(const char *format, va_list ap_save) +{ + struct asprintf info; + struct dynbuf dyn; + info.b = &dyn; + Curl_dyn_init(info.b, DYN_APRINTF); + info.merr = MERR_OK; + + (void)formatf(&info, alloc_addbyter, format, ap_save); + if(info.merr) { + Curl_dyn_free(info.b); + return NULL; + } + if(Curl_dyn_len(info.b)) + return Curl_dyn_ptr(info.b); + return strdup(""); +} + +char *curl_maprintf(const char *format, ...) +{ + va_list ap_save; + char *s; + va_start(ap_save, format); + s = curl_mvaprintf(format, ap_save); + va_end(ap_save); + return s; +} + +static int storebuffer(unsigned char outc, void *f) +{ + char **buffer = f; + **buffer = (char)outc; + (*buffer)++; + return 0; +} + +int curl_msprintf(char *buffer, const char *format, ...) +{ + va_list ap_save; /* argument pointer */ + int retcode; + va_start(ap_save, format); + retcode = formatf(&buffer, storebuffer, format, ap_save); + va_end(ap_save); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +static int fputc_wrapper(unsigned char outc, void *f) +{ + int out = outc; + FILE *s = f; + int rc = fputc(out, s); + return rc == EOF; +} + +int curl_mprintf(const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + + retcode = formatf(stdout, fputc_wrapper, format, ap_save); + va_end(ap_save); + return retcode; +} + +int curl_mfprintf(FILE *whereto, const char *format, ...) +{ + int retcode; + va_list ap_save; /* argument pointer */ + va_start(ap_save, format); + retcode = formatf(whereto, fputc_wrapper, format, ap_save); + va_end(ap_save); + return retcode; +} + +int curl_mvsprintf(char *buffer, const char *format, va_list ap_save) +{ + int retcode = formatf(&buffer, storebuffer, format, ap_save); + *buffer = 0; /* we terminate this with a zero byte */ + return retcode; +} + +int curl_mvprintf(const char *format, va_list ap_save) +{ + return formatf(stdout, fputc_wrapper, format, ap_save); +} + +int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save) +{ + return formatf(whereto, fputc_wrapper, format, ap_save); +} diff --git a/local-test-curl-full-01/afc-curl/lib/mqtt.c b/local-test-curl-full-01/afc-curl/lib/mqtt.c new file mode 100644 index 0000000000000000000000000000000000000000..69eaf344aea5ba06f7c0a9bc9f4cf7e3522bec4a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/mqtt.c @@ -0,0 +1,842 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * Copyright (C) Björn Stenberg, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_MQTT + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" +#include "progress.h" +#include "mqtt.h" +#include "select.h" +#include "strdup.h" +#include "url.h" +#include "escape.h" +#include "warnless.h" +#include "curl_printf.h" +#include "curl_memory.h" +#include "multiif.h" +#include "rand.h" + +/* The last #include file should be: */ +#include "memdebug.h" + +#define MQTT_MSG_CONNECT 0x10 +#define MQTT_MSG_CONNACK 0x20 +#define MQTT_MSG_PUBLISH 0x30 +#define MQTT_MSG_SUBSCRIBE 0x82 +#define MQTT_MSG_SUBACK 0x90 +#define MQTT_MSG_DISCONNECT 0xe0 + +#define MQTT_CONNACK_LEN 2 +#define MQTT_SUBACK_LEN 3 +#define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */ + +/* + * Forward declarations. + */ + +static CURLcode mqtt_do(struct Curl_easy *data, bool *done); +static CURLcode mqtt_done(struct Curl_easy *data, + CURLcode status, bool premature); +static CURLcode mqtt_doing(struct Curl_easy *data, bool *done); +static int mqtt_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *sock); +static CURLcode mqtt_setup_conn(struct Curl_easy *data, + struct connectdata *conn); + +/* + * MQTT protocol handler. + */ + +const struct Curl_handler Curl_handler_mqtt = { + "mqtt", /* scheme */ + mqtt_setup_conn, /* setup_connection */ + mqtt_do, /* do_it */ + mqtt_done, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + mqtt_doing, /* doing */ + ZERO_NULL, /* proto_getsock */ + mqtt_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_MQTT, /* defport */ + CURLPROTO_MQTT, /* protocol */ + CURLPROTO_MQTT, /* family */ + PROTOPT_NONE /* flags */ +}; + +static CURLcode mqtt_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* allocate the HTTP-specific struct for the Curl_easy, only to survive + during this request */ + struct MQTT *mq; + (void)conn; + DEBUGASSERT(data->req.p.mqtt == NULL); + + mq = calloc(1, sizeof(struct MQTT)); + if(!mq) + return CURLE_OUT_OF_MEMORY; + Curl_dyn_init(&mq->recvbuf, DYN_MQTT_RECV); + data->req.p.mqtt = mq; + return CURLE_OK; +} + +static CURLcode mqtt_send(struct Curl_easy *data, + char *buf, size_t len) +{ + CURLcode result = CURLE_OK; + struct MQTT *mq = data->req.p.mqtt; + size_t n; + result = Curl_xfer_send(data, buf, len, FALSE, &n); + if(result) + return result; + Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n); + if(len != n) { + size_t nsend = len - n; + char *sendleftovers = Curl_memdup(&buf[n], nsend); + if(!sendleftovers) + return CURLE_OUT_OF_MEMORY; + mq->sendleftovers = sendleftovers; + mq->nsend = nsend; + } + else { + mq->sendleftovers = NULL; + mq->nsend = 0; + } + return result; +} + +/* Generic function called by the multi interface to figure out what socket(s) + to wait for and for what actions during the DOING and PROTOCONNECT + states */ +static int mqtt_getsock(struct Curl_easy *data, + struct connectdata *conn, + curl_socket_t *sock) +{ + (void)data; + sock[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(FIRSTSOCKET); +} + +static int mqtt_encode_len(char *buf, size_t len) +{ + int i; + + for(i = 0; (len > 0) && (i < 4); i++) { + unsigned char encoded; + encoded = len % 0x80; + len /= 0x80; + if(len) + encoded |= 0x80; + buf[i] = (char)encoded; + } + + return i; +} + +/* add the passwd to the CONNECT packet */ +static int add_passwd(const char *passwd, const size_t plen, + char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(plen > 0xffff) + return 1; + + /* set password flag */ + pkt[conn_flags_pos] |= 0x40; + + /* length of password provided */ + pkt[start] = (char)((plen >> 8) & 0xFF); + pkt[start + 1] = (char)(plen & 0xFF); + memcpy(&pkt[start + 2], passwd, plen); + return 0; +} + +/* add user to the CONNECT packet */ +static int add_user(const char *username, const size_t ulen, + unsigned char *pkt, const size_t start, int remain_pos) +{ + /* magic number that need to be set properly */ + const size_t conn_flags_pos = remain_pos + 8; + if(ulen > 0xffff) + return 1; + + /* set username flag */ + pkt[conn_flags_pos] |= 0x80; + /* length of username provided */ + pkt[start] = (unsigned char)((ulen >> 8) & 0xFF); + pkt[start + 1] = (unsigned char)(ulen & 0xFF); + memcpy(&pkt[start + 2], username, ulen); + return 0; +} + +/* add client ID to the CONNECT packet */ +static int add_client_id(const char *client_id, const size_t client_id_len, + char *pkt, const size_t start) +{ + if(client_id_len != MQTT_CLIENTID_LEN) + return 1; + pkt[start] = 0x00; + pkt[start + 1] = MQTT_CLIENTID_LEN; + memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN); + return 0; +} + +/* Set initial values of CONNECT packet */ +static int init_connpack(char *packet, char *remain, int remain_pos) +{ + /* Fixed header starts */ + /* packet type */ + packet[0] = MQTT_MSG_CONNECT; + /* remaining length field */ + memcpy(&packet[1], remain, remain_pos); + /* Fixed header ends */ + + /* Variable header starts */ + /* protocol length */ + packet[remain_pos + 1] = 0x00; + packet[remain_pos + 2] = 0x04; + /* protocol name */ + packet[remain_pos + 3] = 'M'; + packet[remain_pos + 4] = 'Q'; + packet[remain_pos + 5] = 'T'; + packet[remain_pos + 6] = 'T'; + /* protocol level */ + packet[remain_pos + 7] = 0x04; + /* CONNECT flag: CleanSession */ + packet[remain_pos + 8] = 0x02; + /* keep-alive 0 = disabled */ + packet[remain_pos + 9] = 0x00; + packet[remain_pos + 10] = 0x3c; + /* end of variable header */ + return remain_pos + 10; +} + +static CURLcode mqtt_connect(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + int pos = 0; + int rc = 0; + /* remain length */ + int remain_pos = 0; + char remain[4] = {0}; + size_t packetlen = 0; + size_t payloadlen = 0; + size_t start_user = 0; + size_t start_pwd = 0; + char client_id[MQTT_CLIENTID_LEN + 1] = "curl"; + const size_t clen = strlen("curl"); + char *packet = NULL; + + /* extracting username from request */ + const char *username = data->state.aptr.user ? + data->state.aptr.user : ""; + const size_t ulen = strlen(username); + /* extracting password from request */ + const char *passwd = data->state.aptr.passwd ? + data->state.aptr.passwd : ""; + const size_t plen = strlen(passwd); + + payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2; + /* The plus 2 are for the MSB and LSB describing the length of the string to + * be added on the payload. Refer to spec 1.5.2 and 1.5.4 */ + if(ulen) + payloadlen += 2; + if(plen) + payloadlen += 2; + + /* getting how much occupy the remain length */ + remain_pos = mqtt_encode_len(remain, payloadlen + 10); + + /* 10 length of variable header and 1 the first byte of the fixed header */ + packetlen = payloadlen + 10 + remain_pos + 1; + + /* allocating packet */ + if(packetlen > 268435455) + return CURLE_WEIRD_SERVER_REPLY; + packet = malloc(packetlen); + if(!packet) + return CURLE_OUT_OF_MEMORY; + memset(packet, 0, packetlen); + + /* set initial values for the CONNECT packet */ + pos = init_connpack(packet, remain, remain_pos); + + result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen], + MQTT_CLIENTID_LEN - clen + 1); + /* add client id */ + rc = add_client_id(client_id, strlen(client_id), packet, pos + 1); + if(rc) { + failf(data, "Client ID length mismatched: [%zu]", strlen(client_id)); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + infof(data, "Using client id '%s'", client_id); + + /* position where starts the user payload */ + start_user = pos + 3 + MQTT_CLIENTID_LEN; + /* position where starts the password payload */ + start_pwd = start_user + ulen; + /* if username was provided, add it to the packet */ + if(ulen) { + start_pwd += 2; + + rc = add_user(username, ulen, + (unsigned char *)packet, start_user, remain_pos); + if(rc) { + failf(data, "Username is too large: [%zu]", ulen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + /* if passwd was provided, add it to the packet */ + if(plen) { + rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos); + if(rc) { + failf(data, "Password is too large: [%zu]", plen); + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + } + + if(!result) + result = mqtt_send(data, packet, packetlen); + +end: + if(packet) + free(packet); + Curl_safefree(data->state.aptr.user); + Curl_safefree(data->state.aptr.passwd); + return result; +} + +static CURLcode mqtt_disconnect(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + struct MQTT *mq = data->req.p.mqtt; + result = mqtt_send(data, (char *)"\xe0\x00", 2); + Curl_safefree(mq->sendleftovers); + Curl_dyn_free(&mq->recvbuf); + return result; +} + +static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = data->req.p.mqtt; + size_t rlen = Curl_dyn_len(&mq->recvbuf); + CURLcode result; + + if(rlen < nbytes) { + unsigned char readbuf[1024]; + ssize_t nread; + + DEBUGASSERT(nbytes - rlen < sizeof(readbuf)); + result = Curl_xfer_recv(data, (char *)readbuf, nbytes - rlen, &nread); + if(result) + return result; + DEBUGASSERT(nread >= 0); + if(Curl_dyn_addn(&mq->recvbuf, readbuf, (size_t)nread)) + return CURLE_OUT_OF_MEMORY; + rlen = Curl_dyn_len(&mq->recvbuf); + } + return (rlen >= nbytes) ? CURLE_OK : CURLE_AGAIN; +} + +static void mqtt_recv_consume(struct Curl_easy *data, size_t nbytes) +{ + struct MQTT *mq = data->req.p.mqtt; + size_t rlen = Curl_dyn_len(&mq->recvbuf); + if(rlen <= nbytes) + Curl_dyn_reset(&mq->recvbuf); + else + Curl_dyn_tail(&mq->recvbuf, rlen - nbytes); +} + +static CURLcode mqtt_verify_connack(struct Curl_easy *data) +{ + struct MQTT *mq = data->req.p.mqtt; + CURLcode result; + char *ptr; + + result = mqtt_recv_atleast(data, MQTT_CONNACK_LEN); + if(result) + goto fail; + + /* verify CONNACK */ + DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_CONNACK_LEN); + ptr = Curl_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_CONNACK_LEN); + + if(ptr[0] != 0x00 || ptr[1] != 0x00) { + failf(data, "Expected %02x%02x but got %02x%02x", + 0x00, 0x00, ptr[0], ptr[1]); + Curl_dyn_reset(&mq->recvbuf); + result = CURLE_WEIRD_SERVER_REPLY; + goto fail; + } + mqtt_recv_consume(data, MQTT_CONNACK_LEN); +fail: + return result; +} + +static CURLcode mqtt_get_topic(struct Curl_easy *data, + char **topic, size_t *topiclen) +{ + char *path = data->state.up.path; + CURLcode result = CURLE_URL_MALFORMAT; + if(strlen(path) > 1) { + result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_NADA); + if(!result && (*topiclen > 0xffff)) { + failf(data, "Too long MQTT topic"); + result = CURLE_URL_MALFORMAT; + } + } + else + failf(data, "No MQTT topic found. Forgot to URL encode it?"); + + return result; +} + +static CURLcode mqtt_subscribe(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + char *topic = NULL; + size_t topiclen; + unsigned char *packet = NULL; + size_t packetlen; + char encodedsize[4]; + size_t n; + struct connectdata *conn = data->conn; + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + conn->proto.mqtt.packetid++; + + packetlen = topiclen + 5; /* packetid + topic (has a two byte length field) + + 2 bytes topic length + QoS byte */ + n = mqtt_encode_len((char *)encodedsize, packetlen); + packetlen += n + 1; /* add one for the control packet type byte */ + + packet = malloc(packetlen); + if(!packet) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + packet[0] = MQTT_MSG_SUBSCRIBE; + memcpy(&packet[1], encodedsize, n); + packet[1 + n] = (conn->proto.mqtt.packetid >> 8) & 0xff; + packet[2 + n] = conn->proto.mqtt.packetid & 0xff; + packet[3 + n] = (topiclen >> 8) & 0xff; + packet[4 + n ] = topiclen & 0xff; + memcpy(&packet[5 + n], topic, topiclen); + packet[5 + n + topiclen] = 0; /* QoS zero */ + + result = mqtt_send(data, (char *)packet, packetlen); + +fail: + free(topic); + free(packet); + return result; +} + +/* + * Called when the first byte was already read. + */ +static CURLcode mqtt_verify_suback(struct Curl_easy *data) +{ + struct MQTT *mq = data->req.p.mqtt; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + CURLcode result; + char *ptr; + + result = mqtt_recv_atleast(data, MQTT_SUBACK_LEN); + if(result) + goto fail; + + /* verify SUBACK */ + DEBUGASSERT(Curl_dyn_len(&mq->recvbuf) >= MQTT_SUBACK_LEN); + ptr = Curl_dyn_ptr(&mq->recvbuf); + Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_SUBACK_LEN); + + if(((unsigned char)ptr[0]) != ((mqtt->packetid >> 8) & 0xff) || + ((unsigned char)ptr[1]) != (mqtt->packetid & 0xff) || + ptr[2] != 0x00) { + Curl_dyn_reset(&mq->recvbuf); + result = CURLE_WEIRD_SERVER_REPLY; + goto fail; + } + mqtt_recv_consume(data, MQTT_SUBACK_LEN); +fail: + return result; +} + +static CURLcode mqtt_publish(struct Curl_easy *data) +{ + CURLcode result; + char *payload = data->set.postfields; + size_t payloadlen; + char *topic = NULL; + size_t topiclen; + unsigned char *pkt = NULL; + size_t i = 0; + size_t remaininglength; + size_t encodelen; + char encodedbytes[4]; + curl_off_t postfieldsize = data->set.postfieldsize; + + if(!payload) { + DEBUGF(infof(data, "mqtt_publish without payload, return bad arg")); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + if(postfieldsize < 0) + payloadlen = strlen(payload); + else + payloadlen = (size_t)postfieldsize; + + result = mqtt_get_topic(data, &topic, &topiclen); + if(result) + goto fail; + + remaininglength = payloadlen + 2 + topiclen; + encodelen = mqtt_encode_len(encodedbytes, remaininglength); + + /* add the control byte and the encoded remaining length */ + pkt = malloc(remaininglength + 1 + encodelen); + if(!pkt) { + result = CURLE_OUT_OF_MEMORY; + goto fail; + } + + /* assemble packet */ + pkt[i++] = MQTT_MSG_PUBLISH; + memcpy(&pkt[i], encodedbytes, encodelen); + i += encodelen; + pkt[i++] = (topiclen >> 8) & 0xff; + pkt[i++] = (topiclen & 0xff); + memcpy(&pkt[i], topic, topiclen); + i += topiclen; + memcpy(&pkt[i], payload, payloadlen); + i += payloadlen; + result = mqtt_send(data, (char *)pkt, i); + +fail: + free(pkt); + free(topic); + return result; +} + +static size_t mqtt_decode_len(unsigned char *buf, + size_t buflen, size_t *lenbytes) +{ + size_t len = 0; + size_t mult = 1; + size_t i; + unsigned char encoded = 128; + + for(i = 0; (i < buflen) && (encoded & 128); i++) { + encoded = buf[i]; + len += (encoded & 127) * mult; + mult *= 128; + } + + if(lenbytes) + *lenbytes = i; + + return len; +} + +#ifdef DEBUGBUILD +static const char *statenames[]={ + "MQTT_FIRST", + "MQTT_REMAINING_LENGTH", + "MQTT_CONNACK", + "MQTT_SUBACK", + "MQTT_SUBACK_COMING", + "MQTT_PUBWAIT", + "MQTT_PUB_REMAIN", + + "NOT A STATE" +}; +#endif + +/* The only way to change state */ +static void mqstate(struct Curl_easy *data, + enum mqttstate state, + enum mqttstate nextstate) /* used if state == FIRST */ +{ + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; +#ifdef DEBUGBUILD + infof(data, "%s (from %s) (next is %s)", + statenames[state], + statenames[mqtt->state], + (state == MQTT_FIRST) ? statenames[nextstate] : ""); +#endif + mqtt->state = state; + if(state == MQTT_FIRST) + mqtt->nextstate = nextstate; +} + + +static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + ssize_t nread; + size_t remlen; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + struct MQTT *mq = data->req.p.mqtt; + unsigned char packet; + + switch(mqtt->state) { +MQTT_SUBACK_COMING: + case MQTT_SUBACK_COMING: + result = mqtt_verify_suback(data); + if(result) + break; + + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + /* we are expecting PUBLISH or SUBACK */ + packet = mq->firstbyte & 0xf0; + if(packet == MQTT_MSG_PUBLISH) + mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE); + else if(packet == MQTT_MSG_SUBACK) { + mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE); + goto MQTT_SUBACK_COMING; + } + else if(packet == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + goto end; + } + else { + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } + + /* -- switched state -- */ + remlen = mq->remaining_length; + infof(data, "Remaining length: %zu bytes", remlen); + if(data->set.max_filesize && + (curl_off_t)remlen > data->set.max_filesize) { + failf(data, "Maximum file size exceeded"); + result = CURLE_FILESIZE_EXCEEDED; + goto end; + } + Curl_pgrsSetDownloadSize(data, remlen); + data->req.bytecount = 0; + data->req.size = remlen; + mq->npacket = remlen; /* get this many bytes */ + FALLTHROUGH(); + case MQTT_PUB_REMAIN: { + /* read rest of packet, but no more. Cap to buffer size */ + char buffer[4*1024]; + size_t rest = mq->npacket; + if(rest > sizeof(buffer)) + rest = sizeof(buffer); + result = Curl_xfer_recv(data, buffer, rest, &nread); + if(result) { + if(CURLE_AGAIN == result) { + infof(data, "EEEE AAAAGAIN"); + } + goto end; + } + if(!nread) { + infof(data, "server disconnected"); + result = CURLE_PARTIAL_FILE; + goto end; + } + + /* if QoS is set, message contains packet id */ + result = Curl_client_write(data, CLIENTWRITE_BODY, buffer, nread); + if(result) + goto end; + + mq->npacket -= nread; + if(!mq->npacket) + /* no more PUBLISH payload, back to subscribe wait state */ + mqstate(data, MQTT_FIRST, MQTT_PUBWAIT); + break; + } + default: + DEBUGASSERT(NULL); /* illegal state */ + result = CURLE_WEIRD_SERVER_REPLY; + goto end; + } +end: + return result; +} + +static CURLcode mqtt_do(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + *done = FALSE; /* unconditionally */ + + result = mqtt_connect(data); + if(result) { + failf(data, "Error %d sending MQTT CONNECT request", result); + return result; + } + mqstate(data, MQTT_FIRST, MQTT_CONNACK); + return CURLE_OK; +} + +static CURLcode mqtt_done(struct Curl_easy *data, + CURLcode status, bool premature) +{ + struct MQTT *mq = data->req.p.mqtt; + (void)status; + (void)premature; + Curl_safefree(mq->sendleftovers); + Curl_dyn_free(&mq->recvbuf); + return CURLE_OK; +} + +static CURLcode mqtt_doing(struct Curl_easy *data, bool *done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct mqtt_conn *mqtt = &conn->proto.mqtt; + struct MQTT *mq = data->req.p.mqtt; + ssize_t nread; + unsigned char recvbyte; + + *done = FALSE; + + if(mq->nsend) { + /* send the remainder of an outgoing packet */ + char *ptr = mq->sendleftovers; + result = mqtt_send(data, mq->sendleftovers, mq->nsend); + free(ptr); + if(result) + return result; + } + + infof(data, "mqtt_doing: state [%d]", (int) mqtt->state); + switch(mqtt->state) { + case MQTT_FIRST: + /* Read the initial byte only */ + result = Curl_xfer_recv(data, (char *)&mq->firstbyte, 1, &nread); + if(result) + break; + else if(!nread) { + failf(data, "Connection disconnected"); + *done = TRUE; + result = CURLE_RECV_ERROR; + break; + } + Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1); + /* remember the first byte */ + mq->npacket = 0; + mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE); + FALLTHROUGH(); + case MQTT_REMAINING_LENGTH: + do { + result = Curl_xfer_recv(data, (char *)&recvbyte, 1, &nread); + if(result || !nread) + break; + Curl_debug(data, CURLINFO_HEADER_IN, (char *)&recvbyte, 1); + mq->pkt_hd[mq->npacket++] = recvbyte; + } while((recvbyte & 0x80) && (mq->npacket < 4)); + if(!result && nread && (recvbyte & 0x80)) + /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 + + 127 * 128^3 bytes. server tried to send more */ + result = CURLE_WEIRD_SERVER_REPLY; + if(result) + break; + mq->remaining_length = mqtt_decode_len(mq->pkt_hd, mq->npacket, NULL); + mq->npacket = 0; + if(mq->remaining_length) { + mqstate(data, mqtt->nextstate, MQTT_NOSTATE); + break; + } + mqstate(data, MQTT_FIRST, MQTT_FIRST); + + if(mq->firstbyte == MQTT_MSG_DISCONNECT) { + infof(data, "Got DISCONNECT"); + *done = TRUE; + } + break; + case MQTT_CONNACK: + result = mqtt_verify_connack(data); + if(result) + break; + + if(data->state.httpreq == HTTPREQ_POST) { + result = mqtt_publish(data); + if(!result) { + result = mqtt_disconnect(data); + *done = TRUE; + } + mqtt->nextstate = MQTT_FIRST; + } + else { + result = mqtt_subscribe(data); + if(!result) { + mqstate(data, MQTT_FIRST, MQTT_SUBACK); + } + } + break; + + case MQTT_SUBACK: + case MQTT_PUBWAIT: + case MQTT_PUB_REMAIN: + result = mqtt_read_publish(data, done); + break; + + default: + failf(data, "State not handled yet"); + *done = TRUE; + break; + } + + if(result == CURLE_AGAIN) + result = CURLE_OK; + return result; +} + +#endif /* CURL_DISABLE_MQTT */ diff --git a/local-test-curl-full-01/afc-curl/lib/mqtt.h b/local-test-curl-full-01/afc-curl/lib/mqtt.h new file mode 100644 index 0000000000000000000000000000000000000000..99ab12a98a40577889db0f155a9ad56a2b11bcb6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/mqtt.h @@ -0,0 +1,63 @@ +#ifndef HEADER_CURL_MQTT_H +#define HEADER_CURL_MQTT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Björn Stenberg, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#ifndef CURL_DISABLE_MQTT +extern const struct Curl_handler Curl_handler_mqtt; +#endif + +enum mqttstate { + MQTT_FIRST, /* 0 */ + MQTT_REMAINING_LENGTH, /* 1 */ + MQTT_CONNACK, /* 2 */ + MQTT_SUBACK, /* 3 */ + MQTT_SUBACK_COMING, /* 4 - the SUBACK remainder */ + MQTT_PUBWAIT, /* 5 - wait for publish */ + MQTT_PUB_REMAIN, /* 6 - wait for the remainder of the publish */ + + MQTT_NOSTATE /* 7 - never used an actual state */ +}; + +struct mqtt_conn { + enum mqttstate state; + enum mqttstate nextstate; /* switch to this after remaining length is + done */ + unsigned int packetid; +}; + +/* protocol-specific transfer-related data */ +struct MQTT { + char *sendleftovers; + size_t nsend; /* size of sendleftovers */ + + /* when receiving */ + size_t npacket; /* byte counter */ + unsigned char firstbyte; + size_t remaining_length; + struct dynbuf recvbuf; + unsigned char pkt_hd[4]; /* for decoding the arriving packet length */ +}; + +#endif /* HEADER_CURL_MQTT_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/multiif.h b/local-test-curl-full-01/afc-curl/lib/multiif.h new file mode 100644 index 0000000000000000000000000000000000000000..fd0e21519fa3f81197f9b0ef6fd246373686994b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/multiif.h @@ -0,0 +1,177 @@ +#ifndef HEADER_CURL_MULTIIF_H +#define HEADER_CURL_MULTIIF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Prototypes for library-wide functions provided by multi.c + */ + +CURLcode Curl_updatesocket(struct Curl_easy *data); +void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id); +bool Curl_expire_clear(struct Curl_easy *data); +void Curl_expire_done(struct Curl_easy *data, expire_id id); +CURLMcode Curl_update_timer(struct Curl_multi *multi) WARN_UNUSED_RESULT; +void Curl_attach_connection(struct Curl_easy *data, + struct connectdata *conn); +void Curl_detach_connection(struct Curl_easy *data); +bool Curl_multiplex_wanted(const struct Curl_multi *multi); +void Curl_set_in_callback(struct Curl_easy *data, bool value); +bool Curl_is_in_callback(struct Curl_easy *data); +CURLcode Curl_preconnect(struct Curl_easy *data); + +void Curl_multi_connchanged(struct Curl_multi *multi); + +/* Internal version of curl_multi_init() accepts size parameters for the + socket, connection and dns hashes */ +struct Curl_multi *Curl_multi_handle(size_t hashsize, + size_t chashsize, + size_t dnssize); + +/* the write bits start at bit 16 for the *getsock() bitmap */ +#define GETSOCK_WRITEBITSTART 16 + +#define GETSOCK_BLANK 0 /* no bits set */ + +/* set the bit for the given sock number to make the bitmap for writable */ +#define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x))) + +/* set the bit for the given sock number to make the bitmap for readable */ +#define GETSOCK_READSOCK(x) (1 << (x)) + +/* mask for checking if read and/or write is set for index x */ +#define GETSOCK_MASK_RW(x) (GETSOCK_READSOCK(x)|GETSOCK_WRITESOCK(x)) + +/* + * Curl_multi_closed() + * + * Used by the connect code to tell the multi_socket code that one of the + * sockets we were using is about to be closed. This function will then + * remove it from the sockethash for this handle to make the multi_socket API + * behave properly, especially for the case when libcurl will create another + * socket again and it gets the same file descriptor number. + */ + +void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s); + +/* Compare the two pollsets to notify the multi_socket API of changes + * in socket polling, e.g calling multi->socket_cb() with the changes if + * differences are seen. + */ +CURLMcode Curl_multi_pollset_ev(struct Curl_multi *multi, + struct Curl_easy *data, + struct easy_pollset *ps, + struct easy_pollset *last_ps); + +/* + * Add a handle and move it into PERFORM state at once. For pushed streams. + */ +CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, + struct Curl_easy *data, + struct connectdata *conn); + + +/* Return the value of the CURLMOPT_MAX_CONCURRENT_STREAMS option */ +unsigned int Curl_multi_max_concurrent_streams(struct Curl_multi *multi); + +/** + * Borrow the transfer buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_buf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); +/** + * Release the borrowed buffer. All references into the buffer become + * invalid after this. + * @param buf the buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_buf_release(struct Curl_easy *data, char *buf); + +/** + * Borrow the upload buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used in one + * multi processing of the easy handle. It MUST be returned to the + * multi before it can be borrowed again. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param pbuf on return, the buffer to use or NULL on error + * @param pbuflen on return, the size of *pbuf or 0 on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_ulbuf_borrow(struct Curl_easy *data, + char **pbuf, size_t *pbuflen); + +/** + * Release the borrowed upload buffer. All references into the buffer become + * invalid after this. + * @param buf the upload buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_ulbuf_release(struct Curl_easy *data, char *buf); + +/** + * Borrow the socket scratch buffer from the multi, suitable + * for the given transfer `data`. The buffer may only be used for + * direct socket I/O operation by one connection at a time and MUST be + * returned to the multi before the I/O call returns. + * Pointers into the buffer remain only valid as long as it is borrowed. + * + * @param data the easy handle + * @param blen requested length of the buffer + * @param pbuf on return, the buffer to use or NULL on error + * @return CURLE_OK when buffer is available and is returned. + * CURLE_OUT_OF_MEMORy on failure to allocate the buffer, + * CURLE_FAILED_INIT if the easy handle is without multi. + * CURLE_AGAIN if the buffer is borrowed already. + */ +CURLcode Curl_multi_xfer_sockbuf_borrow(struct Curl_easy *data, + size_t blen, char **pbuf); +/** + * Release the borrowed buffer. All references into the buffer become + * invalid after this. + * @param buf the buffer pointer borrowed for coding error checks. + */ +void Curl_multi_xfer_sockbuf_release(struct Curl_easy *data, char *buf); + +/** + * Get the transfer handle for the given id. Returns NULL if not found. + */ +struct Curl_easy *Curl_multi_get_handle(struct Curl_multi *multi, + curl_off_t id); + +#endif /* HEADER_CURL_MULTIIF_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/netrc.c b/local-test-curl-full-01/afc-curl/lib/netrc.c new file mode 100644 index 0000000000000000000000000000000000000000..d5ee3c0fd564a8ad2a50c5dcf9183989e90dc9d2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/netrc.c @@ -0,0 +1,421 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_NETRC + +#ifdef HAVE_PWD_H +#include +#endif + +#include +#include "netrc.h" +#include "strcase.h" +#include "curl_get_line.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Get user and password from .netrc when given a machine name */ + +enum host_lookup_state { + NOTHING, + HOSTFOUND, /* the 'machine' keyword was found */ + HOSTVALID, /* this is "our" machine! */ + MACDEF +}; + +enum found_state { + NONE, + LOGIN, + PASSWORD +}; + +#define FOUND_LOGIN 1 +#define FOUND_PASSWORD 2 + +#define NETRC_FILE_MISSING 1 +#define NETRC_FAILED -1 +#define NETRC_SUCCESS 0 + +#define MAX_NETRC_LINE 16384 +#define MAX_NETRC_FILE (128*1024) +#define MAX_NETRC_TOKEN 4096 + +static CURLcode file2memory(const char *filename, struct dynbuf *filebuf) +{ + CURLcode result = CURLE_OK; + FILE *file = fopen(filename, FOPEN_READTEXT); + struct dynbuf linebuf; + Curl_dyn_init(&linebuf, MAX_NETRC_LINE); + + if(file) { + while(Curl_get_line(&linebuf, file)) { + const char *line = Curl_dyn_ptr(&linebuf); + /* skip comments on load */ + while(ISBLANK(*line)) + line++; + if(*line == '#') + continue; + result = Curl_dyn_add(filebuf, line); + if(result) + goto done; + } + } +done: + Curl_dyn_free(&linebuf); + if(file) + fclose(file); + return result; +} + +/* + * Returns zero on success. + */ +static int parsenetrc(struct store_netrc *store, + const char *host, + char **loginp, /* might point to a username */ + char **passwordp, + const char *netrcfile) +{ + int retcode = NETRC_FILE_MISSING; + char *login = *loginp; + char *password = NULL; + bool specific_login = !!login; /* points to something */ + enum host_lookup_state state = NOTHING; + enum found_state keyword = NONE; + unsigned char found = 0; /* login + password found bits, as they can come in + any order */ + bool our_login = FALSE; /* found our login name */ + bool done = FALSE; + char *netrcbuffer; + struct dynbuf token; + struct dynbuf *filebuf = &store->filebuf; + DEBUGASSERT(!*passwordp); + Curl_dyn_init(&token, MAX_NETRC_TOKEN); + + if(!store->loaded) { + if(file2memory(netrcfile, filebuf)) + return NETRC_FAILED; + store->loaded = TRUE; + } + + netrcbuffer = Curl_dyn_ptr(filebuf); + + while(!done) { + char *tok = netrcbuffer; + while(tok && !done) { + char *tok_end; + bool quoted; + Curl_dyn_reset(&token); + while(ISBLANK(*tok)) + tok++; + /* tok is first non-space letter */ + if(state == MACDEF) { + if((*tok == '\n') || (*tok == '\r')) + state = NOTHING; /* end of macro definition */ + } + + if(!*tok || (*tok == '\n')) + /* end of line */ + break; + + /* leading double-quote means quoted string */ + quoted = (*tok == '\"'); + + tok_end = tok; + if(!quoted) { + size_t len = 0; + while(!ISSPACE(*tok_end)) { + tok_end++; + len++; + } + if(!len || Curl_dyn_addn(&token, tok, len)) { + retcode = NETRC_FAILED; + goto out; + } + } + else { + bool escape = FALSE; + bool endquote = FALSE; + tok_end++; /* pass the leading quote */ + while(*tok_end) { + char s = *tok_end; + if(escape) { + escape = FALSE; + switch(s) { + case 'n': + s = '\n'; + break; + case 'r': + s = '\r'; + break; + case 't': + s = '\t'; + break; + } + } + else if(s == '\\') { + escape = TRUE; + tok_end++; + continue; + } + else if(s == '\"') { + tok_end++; /* pass the ending quote */ + endquote = TRUE; + break; + } + if(Curl_dyn_addn(&token, &s, 1)) { + retcode = NETRC_FAILED; + goto out; + } + tok_end++; + } + if(escape || !endquote) { + /* bad syntax, get out */ + retcode = NETRC_FAILED; + goto out; + } + } + + tok = Curl_dyn_ptr(&token); + + switch(state) { + case NOTHING: + if(strcasecompare("macdef", tok)) + /* Define a macro. A macro is defined with the specified name; its + contents begin with the next .netrc line and continue until a + null line (consecutive new-line characters) is encountered. */ + state = MACDEF; + else if(strcasecompare("machine", tok)) { + /* the next tok is the machine name, this is in itself the delimiter + that starts the stuff entered for this machine, after this we + need to search for 'login' and 'password'. */ + state = HOSTFOUND; + keyword = NONE; + found = 0; + our_login = FALSE; + Curl_safefree(password); + if(!specific_login) + Curl_safefree(login); + } + else if(strcasecompare("default", tok)) { + state = HOSTVALID; + retcode = NETRC_SUCCESS; /* we did find our host */ + } + break; + case MACDEF: + if(!*tok) + state = NOTHING; + break; + case HOSTFOUND: + if(strcasecompare(host, tok)) { + /* and yes, this is our host! */ + state = HOSTVALID; + retcode = NETRC_SUCCESS; /* we did find our host */ + } + else + /* not our host */ + state = NOTHING; + break; + case HOSTVALID: + /* we are now parsing sub-keywords concerning "our" host */ + if(keyword == LOGIN) { + if(specific_login) + our_login = !Curl_timestrcmp(login, tok); + else { + our_login = TRUE; + free(login); + login = strdup(tok); + if(!login) { + retcode = NETRC_FAILED; /* allocation failed */ + goto out; + } + } + found |= FOUND_LOGIN; + keyword = NONE; + } + else if(keyword == PASSWORD) { + free(password); + password = strdup(tok); + if(!password) { + retcode = NETRC_FAILED; /* allocation failed */ + goto out; + } + found |= FOUND_PASSWORD; + keyword = NONE; + } + else if(strcasecompare("login", tok)) + keyword = LOGIN; + else if(strcasecompare("password", tok)) + keyword = PASSWORD; + else if(strcasecompare("machine", tok)) { + /* a new machine here */ + state = HOSTFOUND; + keyword = NONE; + found = 0; + Curl_safefree(password); + if(!specific_login) + Curl_safefree(login); + } + else if(strcasecompare("default", tok)) { + state = HOSTVALID; + retcode = NETRC_SUCCESS; /* we did find our host */ + Curl_safefree(password); + if(!specific_login) + Curl_safefree(login); + } + if((found == (FOUND_PASSWORD|FOUND_LOGIN)) && our_login) { + done = TRUE; + break; + } + break; + } /* switch (state) */ + tok = ++tok_end; + } + if(!done) { + char *nl = NULL; + if(tok) + nl = strchr(tok, '\n'); + if(!nl) + break; + /* point to next line */ + netrcbuffer = &nl[1]; + } + } /* while !done */ + +out: + Curl_dyn_free(&token); + if(!retcode && !password && our_login) { + /* success without a password, set a blank one */ + password = strdup(""); + if(!password) + retcode = 1; /* out of memory */ + } + if(!retcode) { + /* success */ + if(!specific_login) + *loginp = login; + *passwordp = password; + } + else { + Curl_dyn_free(filebuf); + if(!specific_login) + free(login); + free(password); + } + + return retcode; +} + +/* + * @unittest: 1304 + * + * *loginp and *passwordp MUST be allocated if they are not NULL when passed + * in. + */ +int Curl_parsenetrc(struct store_netrc *store, const char *host, + char **loginp, char **passwordp, + char *netrcfile) +{ + int retcode = 1; + char *filealloc = NULL; + + if(!netrcfile) { +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + char pwbuf[1024]; +#endif + char *home = NULL; + char *homea = curl_getenv("HOME"); /* portable environment reader */ + if(homea) { + home = homea; +#if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) + } + else { + struct passwd pw, *pw_res; + if(!getpwuid_r(geteuid(), &pw, pwbuf, sizeof(pwbuf), &pw_res) + && pw_res) { + home = pw.pw_dir; + } +#elif defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) + } + else { + struct passwd *pw; + pw = getpwuid(geteuid()); + if(pw) { + home = pw->pw_dir; + } +#elif defined(_WIN32) + } + else { + homea = curl_getenv("USERPROFILE"); + if(homea) { + home = homea; + } +#endif + } + + if(!home) + return retcode; /* no home directory found (or possibly out of + memory) */ + + filealloc = aprintf("%s%s.netrc", home, DIR_CHAR); + if(!filealloc) { + free(homea); + return -1; + } + retcode = parsenetrc(store, host, loginp, passwordp, filealloc); + free(filealloc); +#ifdef _WIN32 + if(retcode == NETRC_FILE_MISSING) { + /* fallback to the old-style "_netrc" file */ + filealloc = aprintf("%s%s_netrc", home, DIR_CHAR); + if(!filealloc) { + free(homea); + return -1; + } + retcode = parsenetrc(store, host, loginp, passwordp, filealloc); + free(filealloc); + } +#endif + free(homea); + } + else + retcode = parsenetrc(store, host, loginp, passwordp, netrcfile); + return retcode; +} + +void Curl_netrc_init(struct store_netrc *s) +{ + Curl_dyn_init(&s->filebuf, MAX_NETRC_FILE); + s->loaded = FALSE; +} +void Curl_netrc_cleanup(struct store_netrc *s) +{ + Curl_dyn_free(&s->filebuf); + s->loaded = FALSE; +} +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/netrc.h b/local-test-curl-full-01/afc-curl/lib/netrc.h new file mode 100644 index 0000000000000000000000000000000000000000..0ef9ff78ea2a0e4905bab9776153cc83538a9854 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/netrc.h @@ -0,0 +1,55 @@ +#ifndef HEADER_CURL_NETRC_H +#define HEADER_CURL_NETRC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" +#ifndef CURL_DISABLE_NETRC +#include "dynbuf.h" + +struct store_netrc { + struct dynbuf filebuf; + char *filename; + BIT(loaded); +}; + +void Curl_netrc_init(struct store_netrc *s); +void Curl_netrc_cleanup(struct store_netrc *s); + +/* returns -1 on failure, 0 if the host is found, 1 is the host is not found */ +int Curl_parsenetrc(struct store_netrc *s, const char *host, char **loginp, + char **passwordp, char *filename); + /* Assume: (*passwordp)[0]=0, host[0] != 0. + * If (*loginp)[0] = 0, search for login and password within a machine + * section in the netrc. + * If (*loginp)[0] != 0, search for password within machine and login. + */ +#else +/* disabled */ +#define Curl_parsenetrc(a,b,c,d,e,f) 1 +#define Curl_netrc_init(x) +#define Curl_netrc_cleanup(x) +#endif + +#endif /* HEADER_CURL_NETRC_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/nonblock.c b/local-test-curl-full-01/afc-curl/lib/nonblock.c new file mode 100644 index 0000000000000000000000000000000000000000..6dcf42a7eab096af83a383c46f658648c99e7fb3 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/nonblock.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 "curl_setup.h" + +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef __VMS +#include +#include +#endif + +#include "nonblock.h" + +/* + * curlx_nonblock() set the given socket to either blocking or non-blocking + * mode based on the 'nonblock' boolean argument. This function is highly + * portable. + */ +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */) +{ +#if defined(HAVE_FCNTL_O_NONBLOCK) + /* most recent Unix versions */ + int flags; + flags = sfcntl(sockfd, F_GETFL, 0); + if(flags < 0) + return -1; + /* Check if the current file status flags have already satisfied + * the request, if so, it is no need to call fcntl() to replicate it. + */ + if(!!(flags & O_NONBLOCK) == !!nonblock) + return 0; + if(nonblock) + flags |= O_NONBLOCK; + else + flags &= ~O_NONBLOCK; + return sfcntl(sockfd, F_SETFL, flags); + +#elif defined(HAVE_IOCTL_FIONBIO) + + /* older Unix versions */ + int flags = nonblock ? 1 : 0; + return ioctl(sockfd, FIONBIO, &flags); + +#elif defined(HAVE_IOCTLSOCKET_FIONBIO) + + /* Windows */ + unsigned long flags = nonblock ? 1UL : 0UL; + return ioctlsocket(sockfd, (long)FIONBIO, &flags); + +#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) + + /* Amiga */ + long flags = nonblock ? 1L : 0L; + return IoctlSocket(sockfd, FIONBIO, (char *)&flags); + +#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) + + /* Orbis OS */ + long b = nonblock ? 1L : 0L; + return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); + +#else +# error "no non-blocking method was found/used/set" +#endif +} diff --git a/local-test-curl-full-01/afc-curl/lib/nonblock.h b/local-test-curl-full-01/afc-curl/lib/nonblock.h new file mode 100644 index 0000000000000000000000000000000000000000..4a1a6151f248a617897a5782505fa976e01baa96 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/nonblock.h @@ -0,0 +1,32 @@ +#ifndef HEADER_CURL_NONBLOCK_H +#define HEADER_CURL_NONBLOCK_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include /* for curl_socket_t */ + +int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ + int nonblock /* TRUE or FALSE */); + +#endif /* HEADER_CURL_NONBLOCK_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/noproxy.c b/local-test-curl-full-01/afc-curl/lib/noproxy.c new file mode 100644 index 0000000000000000000000000000000000000000..dbfafc93eb8172d250405148944efd0aeb25c323 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/noproxy.c @@ -0,0 +1,264 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#include "inet_pton.h" +#include "strcase.h" +#include "noproxy.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_ARPA_INET_H +#include +#endif + +/* + * Curl_cidr4_match() returns TRUE if the given IPv4 address is within the + * specified CIDR address range. + */ +UNITTEST bool Curl_cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits) +{ + unsigned int address = 0; + unsigned int check = 0; + + if(bits > 32) + /* strange input */ + return FALSE; + + if(1 != Curl_inet_pton(AF_INET, ipv4, &address)) + return FALSE; + if(1 != Curl_inet_pton(AF_INET, network, &check)) + return FALSE; + + if(bits && (bits != 32)) { + unsigned int mask = 0xffffffff << (32 - bits); + unsigned int haddr = htonl(address); + unsigned int hcheck = htonl(check); +#if 0 + fprintf(stderr, "Host %s (%x) network %s (%x) bits %u mask %x => %x\n", + ipv4, haddr, network, hcheck, bits, mask, + (haddr ^ hcheck) & mask); +#endif + if((haddr ^ hcheck) & mask) + return FALSE; + return TRUE; + } + return (address == check); +} + +UNITTEST bool Curl_cidr6_match(const char *ipv6, + const char *network, + unsigned int bits) +{ +#ifdef USE_IPV6 + unsigned int bytes; + unsigned int rest; + unsigned char address[16]; + unsigned char check[16]; + + if(!bits) + bits = 128; + + bytes = bits / 8; + rest = bits & 0x07; + if((bytes > 16) || ((bytes == 16) && rest)) + return FALSE; + if(1 != Curl_inet_pton(AF_INET6, ipv6, address)) + return FALSE; + if(1 != Curl_inet_pton(AF_INET6, network, check)) + return FALSE; + if(bytes && memcmp(address, check, bytes)) + return FALSE; + if(rest && !((address[bytes] ^ check[bytes]) & (0xff << (8 - rest)))) + return FALSE; + + return TRUE; +#else + (void)ipv6; + (void)network; + (void)bits; + return FALSE; +#endif +} + +enum nametype { + TYPE_HOST, + TYPE_IPV4, + TYPE_IPV6 +}; + +/**************************************************************** +* Checks if the host is in the noproxy list. returns TRUE if it matches and +* therefore the proxy should NOT be used. +****************************************************************/ +bool Curl_check_noproxy(const char *name, const char *no_proxy) +{ + char hostip[128]; + + /* + * If we do not have a hostname at all, like for example with a FILE + * transfer, we have nothing to interrogate the noproxy list with. + */ + if(!name || name[0] == '\0') + return FALSE; + + /* no_proxy=domain1.dom,host.domain2.dom + * (a comma-separated list of hosts which should + * not be proxied, or an asterisk to override + * all proxy variables) + */ + if(no_proxy && no_proxy[0]) { + const char *p = no_proxy; + size_t namelen; + enum nametype type = TYPE_HOST; + if(!strcmp("*", no_proxy)) + return TRUE; + + /* NO_PROXY was specified and it was not just an asterisk */ + + if(name[0] == '[') { + char *endptr; + /* IPv6 numerical address */ + endptr = strchr(name, ']'); + if(!endptr) + return FALSE; + name++; + namelen = endptr - name; + if(namelen >= sizeof(hostip)) + return FALSE; + memcpy(hostip, name, namelen); + hostip[namelen] = 0; + name = hostip; + type = TYPE_IPV6; + } + else { + unsigned int address; + namelen = strlen(name); + if(1 == Curl_inet_pton(AF_INET, name, &address)) + type = TYPE_IPV4; + else { + /* ignore trailing dots in the hostname */ + if(name[namelen - 1] == '.') + namelen--; + } + } + + while(*p) { + const char *token; + size_t tokenlen = 0; + bool match = FALSE; + + /* pass blanks */ + while(*p && ISBLANK(*p)) + p++; + + token = p; + /* pass over the pattern */ + while(*p && !ISBLANK(*p) && (*p != ',')) { + p++; + tokenlen++; + } + + if(tokenlen) { + switch(type) { + case TYPE_HOST: + /* ignore trailing dots in the token to check */ + if(token[tokenlen - 1] == '.') + tokenlen--; + + if(tokenlen && (*token == '.')) { + /* ignore leading token dot as well */ + token++; + tokenlen--; + } + /* A: example.com matches 'example.com' + B: www.example.com matches 'example.com' + C: nonexample.com DOES NOT match 'example.com' + */ + if(tokenlen == namelen) + /* case A, exact match */ + match = strncasecompare(token, name, namelen); + else if(tokenlen < namelen) { + /* case B, tailmatch domain */ + match = (name[namelen - tokenlen - 1] == '.') && + strncasecompare(token, name + (namelen - tokenlen), + tokenlen); + } + /* case C passes through, not a match */ + break; + case TYPE_IPV4: + case TYPE_IPV6: { + const char *check = token; + char *slash; + unsigned int bits = 0; + char checkip[128]; + if(tokenlen >= sizeof(checkip)) + /* this cannot match */ + break; + /* copy the check name to a temp buffer */ + memcpy(checkip, check, tokenlen); + checkip[tokenlen] = 0; + check = checkip; + + slash = strchr(check, '/'); + /* if the slash is part of this token, use it */ + if(slash) { + /* if the bits variable gets a crazy value here, that is fine as + the value will then be rejected in the cidr function */ + bits = (unsigned int)atoi(slash + 1); + *slash = 0; /* null terminate there */ + } + if(type == TYPE_IPV6) + match = Curl_cidr6_match(name, check, bits); + else + match = Curl_cidr4_match(name, check, bits); + break; + } + } + if(match) + return TRUE; + } /* if(tokenlen) */ + /* pass blanks after pattern */ + while(ISBLANK(*p)) + p++; + /* if not a comma, this ends the loop */ + if(*p != ',') + break; + /* pass any number of commas */ + while(*p == ',') + p++; + } /* while(*p) */ + } /* NO_PROXY was specified and it was not just an asterisk */ + + return FALSE; +} + +#endif /* CURL_DISABLE_PROXY */ diff --git a/local-test-curl-full-01/afc-curl/lib/noproxy.h b/local-test-curl-full-01/afc-curl/lib/noproxy.h new file mode 100644 index 0000000000000000000000000000000000000000..71ae7eaafa097d40780e3ef6142840de94824633 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/noproxy.h @@ -0,0 +1,43 @@ +#ifndef HEADER_CURL_NOPROXY_H +#define HEADER_CURL_NOPROXY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" + +#ifndef CURL_DISABLE_PROXY + +#ifdef UNITTESTS + +UNITTEST bool Curl_cidr4_match(const char *ipv4, /* 1.2.3.4 address */ + const char *network, /* 1.2.3.4 address */ + unsigned int bits); +UNITTEST bool Curl_cidr6_match(const char *ipv6, + const char *network, + unsigned int bits); +#endif + +bool Curl_check_noproxy(const char *name, const char *no_proxy); +#endif + +#endif /* HEADER_CURL_NOPROXY_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/optiontable.pl b/local-test-curl-full-01/afc-curl/lib/optiontable.pl new file mode 100644 index 0000000000000000000000000000000000000000..2727784e7bdd5dfbeb6ecd7bdf3a502c3da451b0 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/optiontable.pl @@ -0,0 +1,152 @@ +#!/usr/bin/env perl + +print <, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This source code is generated by optiontable.pl - DO NOT EDIT BY HAND */ + +#include "curl_setup.h" +#include "easyoptions.h" + +/* all easy setopt options listed in alphabetical order */ +struct curl_easyoption Curl_easyopts[] = { +HEAD + ; + +my $lastnum=0; + +sub add { + my($opt, $type, $num)=@_; + my $name; + # remove all spaces from the type + $type =~ s/ //g; + my $ext = $type; + + if($opt =~ /OBSOLETE/) { + # skip obsolete options + next; + } + + if($opt =~ /^CURLOPT_(.*)/) { + $name=$1; + } + $ext =~ s/CURLOPTTYPE_//; + $ext =~ s/CBPOINT/CBPTR/; + $ext =~ s/POINT\z//; + $type = "CURLOT_$ext"; + + $opt{$name} = $opt; + $type{$name} = $type; + push @names, $name; + if($num < $lastnum) { + print STDERR "ERROR: $opt has bad number: $num < $lastnum\n"; + exit 2; + } + else { + $lastnum = $num; + } +} + + +my $fl; +while() { + my $l = $_; + if($fl) { + # continued deprecation + if($l =~ /(.*)\),/) { + $fl .= $1; + + # the end + my @p=split(/, */, $fl); + add($p[0], $p[1], $p[2]); + undef $fl; + } + else { + # another line to append + chomp $l; + $fl .= $l; + } + } + + if(/^ *CURLOPTDEPRECATED\((.*)/) { + $fl = $1; + chomp $fl; + } + + if(/^ *CURLOPT\(([^,]*), ([^,]*), (\d+)\)/) { + my($opt, $type, $num)=($1,$2,$3); + add($opt, $type, $num); + } + + # alias for an older option + # old = new + if(/^#define (CURLOPT_[^ ]*) *(CURLOPT_\S*)/) { + my ($o, $n)=($1, $2); + # skip obsolete ones + if(($n !~ /OBSOLETE/) && ($o !~ /OBSOLETE/)) { + $o =~ s/^CURLOPT_//; + $n =~ s/^CURLOPT_//; + $alias{$o} = $n; + push @names, $o, + } + } +} + + +for my $name (sort @names) { + my $oname = $name; + my $a = $alias{$name}; + my $flag = "0"; + if($a) { + $name = $alias{$name}; + $flag = "CURLOT_FLAG_ALIAS"; + } + $o = sprintf(" {\"%s\", %s, %s, %s},\n", + $oname, $opt{$name}, $type{$name}, $flag); + if(length($o) < 80) { + print $o; + } + else { + printf(" {\"%s\", %s,\n %s, %s},\n", + $oname, $opt{$name}, $type{$name}, $flag); + } +} + +print <, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +/* + A brief summary of the date string formats this parser groks: + + RFC 2616 3.3.1 + + Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 + Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 + Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format + + we support dates without week day name: + + 06 Nov 1994 08:49:37 GMT + 06-Nov-94 08:49:37 GMT + Nov 6 08:49:37 1994 + + without the time zone: + + 06 Nov 1994 08:49:37 + 06-Nov-94 08:49:37 + + weird order: + + 1994 Nov 6 08:49:37 (GNU date fails) + GMT 08:49:37 06-Nov-94 Sunday + 94 6 Nov 08:49:37 (GNU date fails) + + time left out: + + 1994 Nov 6 + 06-Nov-94 + Sun Nov 6 94 + + unusual separators: + + 1994.Nov.6 + Sun/Nov/6/94/GMT + + commonly used time zone names: + + Sun, 06 Nov 1994 08:49:37 CET + 06 Nov 1994 08:49:37 EST + + time zones specified using RFC822 style: + + Sun, 12 Sep 2004 15:05:58 -0700 + Sat, 11 Sep 2004 21:32:11 +0200 + + compact numerical date strings: + + 20040912 15:05:58 -0700 + 20040911 +0200 + +*/ + +#include "curl_setup.h" + +#include + +#include +#include "strcase.h" +#include "warnless.h" +#include "parsedate.h" + +/* + * parsedate() + * + * Returns: + * + * PARSEDATE_OK - a fine conversion + * PARSEDATE_FAIL - failed to convert + * PARSEDATE_LATER - time overflow at the far end of time_t + * PARSEDATE_SOONER - time underflow at the low end of time_t + */ + +static int parsedate(const char *date, time_t *output); + +#define PARSEDATE_OK 0 +#define PARSEDATE_FAIL -1 +#define PARSEDATE_LATER 1 +#define PARSEDATE_SOONER 2 + +#if !defined(CURL_DISABLE_PARSEDATE) || !defined(CURL_DISABLE_FTP) || \ + !defined(CURL_DISABLE_FILE) +/* These names are also used by FTP and FILE code */ +const char * const Curl_wkday[] = +{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; +const char * const Curl_month[]= +{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; +#endif + +#ifndef CURL_DISABLE_PARSEDATE +static const char * const weekday[] = +{ "Monday", "Tuesday", "Wednesday", "Thursday", + "Friday", "Saturday", "Sunday" }; + +struct tzinfo { + char name[5]; + int offset; /* +/- in minutes */ +}; + +/* Here's a bunch of frequently used time zone names. These were supported + by the old getdate parser. */ +#define tDAYZONE -60 /* offset for daylight savings time */ +static const struct tzinfo tz[]= { + {"GMT", 0}, /* Greenwich Mean */ + {"UT", 0}, /* Universal Time */ + {"UTC", 0}, /* Universal (Coordinated) */ + {"WET", 0}, /* Western European */ + {"BST", 0 tDAYZONE}, /* British Summer */ + {"WAT", 60}, /* West Africa */ + {"AST", 240}, /* Atlantic Standard */ + {"ADT", 240 tDAYZONE}, /* Atlantic Daylight */ + {"EST", 300}, /* Eastern Standard */ + {"EDT", 300 tDAYZONE}, /* Eastern Daylight */ + {"CST", 360}, /* Central Standard */ + {"CDT", 360 tDAYZONE}, /* Central Daylight */ + {"MST", 420}, /* Mountain Standard */ + {"MDT", 420 tDAYZONE}, /* Mountain Daylight */ + {"PST", 480}, /* Pacific Standard */ + {"PDT", 480 tDAYZONE}, /* Pacific Daylight */ + {"YST", 540}, /* Yukon Standard */ + {"YDT", 540 tDAYZONE}, /* Yukon Daylight */ + {"HST", 600}, /* Hawaii Standard */ + {"HDT", 600 tDAYZONE}, /* Hawaii Daylight */ + {"CAT", 600}, /* Central Alaska */ + {"AHST", 600}, /* Alaska-Hawaii Standard */ + {"NT", 660}, /* Nome */ + {"IDLW", 720}, /* International Date Line West */ + {"CET", -60}, /* Central European */ + {"MET", -60}, /* Middle European */ + {"MEWT", -60}, /* Middle European Winter */ + {"MEST", -60 tDAYZONE}, /* Middle European Summer */ + {"CEST", -60 tDAYZONE}, /* Central European Summer */ + {"MESZ", -60 tDAYZONE}, /* Middle European Summer */ + {"FWT", -60}, /* French Winter */ + {"FST", -60 tDAYZONE}, /* French Summer */ + {"EET", -120}, /* Eastern Europe, USSR Zone 1 */ + {"WAST", -420}, /* West Australian Standard */ + {"WADT", -420 tDAYZONE}, /* West Australian Daylight */ + {"CCT", -480}, /* China Coast, USSR Zone 7 */ + {"JST", -540}, /* Japan Standard, USSR Zone 8 */ + {"EAST", -600}, /* Eastern Australian Standard */ + {"EADT", -600 tDAYZONE}, /* Eastern Australian Daylight */ + {"GST", -600}, /* Guam Standard, USSR Zone 9 */ + {"NZT", -720}, /* New Zealand */ + {"NZST", -720}, /* New Zealand Standard */ + {"NZDT", -720 tDAYZONE}, /* New Zealand Daylight */ + {"IDLE", -720}, /* International Date Line East */ + /* Next up: Military timezone names. RFC822 allowed these, but (as noted in + RFC 1123) had their signs wrong. Here we use the correct signs to match + actual military usage. + */ + {"A", 1 * 60}, /* Alpha */ + {"B", 2 * 60}, /* Bravo */ + {"C", 3 * 60}, /* Charlie */ + {"D", 4 * 60}, /* Delta */ + {"E", 5 * 60}, /* Echo */ + {"F", 6 * 60}, /* Foxtrot */ + {"G", 7 * 60}, /* Golf */ + {"H", 8 * 60}, /* Hotel */ + {"I", 9 * 60}, /* India */ + /* "J", Juliet is not used as a timezone, to indicate the observer's local + time */ + {"K", 10 * 60}, /* Kilo */ + {"L", 11 * 60}, /* Lima */ + {"M", 12 * 60}, /* Mike */ + {"N", -1 * 60}, /* November */ + {"O", -2 * 60}, /* Oscar */ + {"P", -3 * 60}, /* Papa */ + {"Q", -4 * 60}, /* Quebec */ + {"R", -5 * 60}, /* Romeo */ + {"S", -6 * 60}, /* Sierra */ + {"T", -7 * 60}, /* Tango */ + {"U", -8 * 60}, /* Uniform */ + {"V", -9 * 60}, /* Victor */ + {"W", -10 * 60}, /* Whiskey */ + {"X", -11 * 60}, /* X-ray */ + {"Y", -12 * 60}, /* Yankee */ + {"Z", 0}, /* Zulu, zero meridian, a.k.a. UTC */ +}; + +/* returns: + -1 no day + 0 monday - 6 sunday +*/ + +static int checkday(const char *check, size_t len) +{ + int i; + const char * const *what; + if(len > 3) + what = &weekday[0]; + else if(len == 3) + what = &Curl_wkday[0]; + else + return -1; /* too short */ + for(i = 0; i < 7; i++) { + size_t ilen = strlen(what[0]); + if((ilen == len) && + strncasecompare(check, what[0], len)) + return i; + what++; + } + return -1; +} + +static int checkmonth(const char *check, size_t len) +{ + int i; + const char * const *what = &Curl_month[0]; + if(len != 3) + return -1; /* not a month */ + + for(i = 0; i < 12; i++) { + if(strncasecompare(check, what[0], 3)) + return i; + what++; + } + return -1; /* return the offset or -1, no real offset is -1 */ +} + +/* return the time zone offset between GMT and the input one, in number + of seconds or -1 if the timezone was not found/legal */ + +static int checktz(const char *check, size_t len) +{ + unsigned int i; + const struct tzinfo *what = tz; + if(len > 4) /* longer than any valid timezone */ + return -1; + + for(i = 0; i < sizeof(tz)/sizeof(tz[0]); i++) { + size_t ilen = strlen(what->name); + if((ilen == len) && + strncasecompare(check, what->name, len)) + return what->offset*60; + what++; + } + return -1; +} + +static void skip(const char **date) +{ + /* skip everything that are not letters or digits */ + while(**date && !ISALNUM(**date)) + (*date)++; +} + +enum assume { + DATE_MDAY, + DATE_YEAR, + DATE_TIME +}; + +/* + * time2epoch: time stamp to seconds since epoch in GMT time zone. Similar to + * mktime but for GMT only. + */ +static time_t time2epoch(int sec, int min, int hour, + int mday, int mon, int year) +{ + static const int month_days_cumulative [12] = + { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; + int leap_days = year - (mon <= 1); + leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400) + - (1969 / 4) + (1969 / 100) - (1969 / 400)); + return ((((time_t) (year - 1970) * 365 + + leap_days + month_days_cumulative[mon] + mday - 1) * 24 + + hour) * 60 + min) * 60 + sec; +} + +/* Returns the value of a single-digit or two-digit decimal number, return + then pointer to after the number. The 'date' pointer is known to point to a + digit. */ +static int oneortwodigit(const char *date, const char **endp) +{ + int num = date[0] - '0'; + if(ISDIGIT(date[1])) { + *endp = &date[2]; + return num*10 + (date[1] - '0'); + } + *endp = &date[1]; + return num; +} + + +/* HH:MM:SS or HH:MM and accept single-digits too */ +static bool match_time(const char *date, + int *h, int *m, int *s, char **endp) +{ + const char *p; + int hh, mm, ss = 0; + hh = oneortwodigit(date, &p); + if((hh < 24) && (*p == ':') && ISDIGIT(p[1])) { + mm = oneortwodigit(&p[1], &p); + if(mm < 60) { + if((*p == ':') && ISDIGIT(p[1])) { + ss = oneortwodigit(&p[1], &p); + if(ss <= 60) { + /* valid HH:MM:SS */ + goto match; + } + } + else { + /* valid HH:MM */ + goto match; + } + } + } + return FALSE; /* not a time string */ +match: + *h = hh; + *m = mm; + *s = ss; + *endp = (char *)p; + return TRUE; +} + +/* + * parsedate() + * + * Returns: + * + * PARSEDATE_OK - a fine conversion + * PARSEDATE_FAIL - failed to convert + * PARSEDATE_LATER - time overflow at the far end of time_t + * PARSEDATE_SOONER - time underflow at the low end of time_t + */ + +/* Wednesday is the longest name this parser knows about */ +#define NAME_LEN 12 + +static int parsedate(const char *date, time_t *output) +{ + time_t t = 0; + int wdaynum = -1; /* day of the week number, 0-6 (mon-sun) */ + int monnum = -1; /* month of the year number, 0-11 */ + int mdaynum = -1; /* day of month, 1 - 31 */ + int hournum = -1; + int minnum = -1; + int secnum = -1; + int yearnum = -1; + int tzoff = -1; + enum assume dignext = DATE_MDAY; + const char *indate = date; /* save the original pointer */ + int part = 0; /* max 6 parts */ + + while(*date && (part < 6)) { + bool found = FALSE; + + skip(&date); + + if(ISALPHA(*date)) { + /* a name coming up */ + size_t len = 0; + const char *p = date; + while(ISALPHA(*p) && (len < NAME_LEN)) { + p++; + len++; + } + + if(len != NAME_LEN) { + if(wdaynum == -1) { + wdaynum = checkday(date, len); + if(wdaynum != -1) + found = TRUE; + } + if(!found && (monnum == -1)) { + monnum = checkmonth(date, len); + if(monnum != -1) + found = TRUE; + } + + if(!found && (tzoff == -1)) { + /* this just must be a time zone string */ + tzoff = checktz(date, len); + if(tzoff != -1) + found = TRUE; + } + } + if(!found) + return PARSEDATE_FAIL; /* bad string */ + + date += len; + } + else if(ISDIGIT(*date)) { + /* a digit */ + int val; + char *end; + if((secnum == -1) && + match_time(date, &hournum, &minnum, &secnum, &end)) { + /* time stamp */ + date = end; + } + else { + long lval; + int error; + int old_errno; + + old_errno = errno; + errno = 0; + lval = strtol(date, &end, 10); + error = errno; + if(errno != old_errno) + errno = old_errno; + + if(error) + return PARSEDATE_FAIL; + +#if LONG_MAX != INT_MAX + if((lval > (long)INT_MAX) || (lval < (long)INT_MIN)) + return PARSEDATE_FAIL; +#endif + + val = curlx_sltosi(lval); + + if((tzoff == -1) && + ((end - date) == 4) && + (val <= 1400) && + (indate < date) && + ((date[-1] == '+' || date[-1] == '-'))) { + /* four digits and a value less than or equal to 1400 (to take into + account all sorts of funny time zone diffs) and it is preceded + with a plus or minus. This is a time zone indication. 1400 is + picked since +1300 is frequently used and +1400 is mentioned as + an edge number in the document "ISO C 200X Proposal: Timezone + Functions" at http://david.tribble.com/text/c0xtimezone.html If + anyone has a more authoritative source for the exact maximum time + zone offsets, please speak up! */ + found = TRUE; + tzoff = (val/100 * 60 + val%100)*60; + + /* the + and - prefix indicates the local time compared to GMT, + this we need their reversed math to get what we want */ + tzoff = date[-1]=='+' ? -tzoff : tzoff; + } + + if(((end - date) == 8) && + (yearnum == -1) && + (monnum == -1) && + (mdaynum == -1)) { + /* 8 digits, no year, month or day yet. This is YYYYMMDD */ + found = TRUE; + yearnum = val/10000; + monnum = (val%10000)/100-1; /* month is 0 - 11 */ + mdaynum = val%100; + } + + if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) { + if((val > 0) && (val < 32)) { + mdaynum = val; + found = TRUE; + } + dignext = DATE_YEAR; + } + + if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) { + yearnum = val; + found = TRUE; + if(yearnum < 100) { + if(yearnum > 70) + yearnum += 1900; + else + yearnum += 2000; + } + if(mdaynum == -1) + dignext = DATE_MDAY; + } + + if(!found) + return PARSEDATE_FAIL; + + date = end; + } + } + + part++; + } + + if(-1 == secnum) + secnum = minnum = hournum = 0; /* no time, make it zero */ + + if((-1 == mdaynum) || + (-1 == monnum) || + (-1 == yearnum)) + /* lacks vital info, fail */ + return PARSEDATE_FAIL; + +#ifdef HAVE_TIME_T_UNSIGNED + if(yearnum < 1970) { + /* only positive numbers cannot return earlier */ + *output = TIME_T_MIN; + return PARSEDATE_SOONER; + } +#endif + +#if (SIZEOF_TIME_T < 5) + +#ifdef HAVE_TIME_T_UNSIGNED + /* an unsigned 32-bit time_t can only hold dates to 2106 */ + if(yearnum > 2105) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; + } +#else + /* a signed 32-bit time_t can only hold dates to the beginning of 2038 */ + if(yearnum > 2037) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; + } + if(yearnum < 1903) { + *output = TIME_T_MIN; + return PARSEDATE_SOONER; + } +#endif + +#else + /* The Gregorian calendar was introduced 1582 */ + if(yearnum < 1583) + return PARSEDATE_FAIL; +#endif + + if((mdaynum > 31) || (monnum > 11) || + (hournum > 23) || (minnum > 59) || (secnum > 60)) + return PARSEDATE_FAIL; /* clearly an illegal date */ + + /* time2epoch() returns a time_t. time_t is often 32 bits, sometimes even on + architectures that feature a 64 bits 'long' but ultimately time_t is the + correct data type to use. + */ + t = time2epoch(secnum, minnum, hournum, mdaynum, monnum, yearnum); + + /* Add the time zone diff between local time zone and GMT. */ + if(tzoff == -1) + tzoff = 0; + + if((tzoff > 0) && (t > TIME_T_MAX - tzoff)) { + *output = TIME_T_MAX; + return PARSEDATE_LATER; /* time_t overflow */ + } + + t += tzoff; + + *output = t; + + return PARSEDATE_OK; +} +#else +/* disabled */ +static int parsedate(const char *date, time_t *output) +{ + (void)date; + *output = 0; + return PARSEDATE_OK; /* a lie */ +} +#endif + +time_t curl_getdate(const char *p, const time_t *now) +{ + time_t parsed = -1; + int rc = parsedate(p, &parsed); + (void)now; /* legacy argument from the past that we ignore */ + + if(rc == PARSEDATE_OK) { + if(parsed == -1) + /* avoid returning -1 for a working scenario */ + parsed++; + return parsed; + } + /* everything else is fail */ + return -1; +} + +/* Curl_getdate_capped() differs from curl_getdate() in that this will return + TIME_T_MAX in case the parsed time value was too big, instead of an + error. */ + +time_t Curl_getdate_capped(const char *p) +{ + time_t parsed = -1; + int rc = parsedate(p, &parsed); + + switch(rc) { + case PARSEDATE_OK: + if(parsed == -1) + /* avoid returning -1 for a working scenario */ + parsed++; + return parsed; + case PARSEDATE_LATER: + /* this returns the maximum time value */ + return parsed; + default: + return -1; /* everything else is fail */ + } + /* UNREACHABLE */ +} + +/* + * Curl_gmtime() is a gmtime() replacement for portability. Do not use the + * gmtime_r() or gmtime() functions anywhere else but here. + * + */ + +CURLcode Curl_gmtime(time_t intime, struct tm *store) +{ + const struct tm *tm; +#ifdef HAVE_GMTIME_R + /* thread-safe version */ + tm = (struct tm *)gmtime_r(&intime, store); +#else + /* !checksrc! disable BANNEDFUNC 1 */ + tm = gmtime(&intime); + if(tm) + *store = *tm; /* copy the pointed struct to the local copy */ +#endif + + if(!tm) + return CURLE_BAD_FUNCTION_ARGUMENT; + return CURLE_OK; +} diff --git a/local-test-curl-full-01/afc-curl/lib/parsedate.h b/local-test-curl-full-01/afc-curl/lib/parsedate.h new file mode 100644 index 0000000000000000000000000000000000000000..84c37f1675cffe190f4956c5b4591eda794cb6e2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/parsedate.h @@ -0,0 +1,38 @@ +#ifndef HEADER_CURL_PARSEDATE_H +#define HEADER_CURL_PARSEDATE_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +extern const char * const Curl_wkday[7]; +extern const char * const Curl_month[12]; + +CURLcode Curl_gmtime(time_t intime, struct tm *store); + +/* Curl_getdate_capped() differs from curl_getdate() in that this will return + TIME_T_MAX in case the parsed time value was too big, instead of an + error. */ + +time_t Curl_getdate_capped(const char *p); + +#endif /* HEADER_CURL_PARSEDATE_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/rename.h b/local-test-curl-full-01/afc-curl/lib/rename.h new file mode 100644 index 0000000000000000000000000000000000000000..04440820c542ba834868fcab3f4ab70d5a61f3b2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/rename.h @@ -0,0 +1,29 @@ +#ifndef HEADER_CURL_RENAME_H +#define HEADER_CURL_RENAME_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +int Curl_rename(const char *oldpath, const char *newpath); + +#endif /* HEADER_CURL_RENAME_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/request.c b/local-test-curl-full-01/afc-curl/lib/request.c new file mode 100644 index 0000000000000000000000000000000000000000..310e4eac00000b9ba54af771a34d15137d1c8654 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/request.c @@ -0,0 +1,479 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "cfilters.h" +#include "dynbuf.h" +#include "doh.h" +#include "multiif.h" +#include "progress.h" +#include "request.h" +#include "sendf.h" +#include "transfer.h" +#include "url.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +void Curl_req_init(struct SingleRequest *req) +{ + memset(req, 0, sizeof(*req)); +} + +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data) +{ + CURLcode result; + + req->done = FALSE; + req->upload_done = FALSE; + req->upload_aborted = FALSE; + req->download_done = FALSE; + req->eos_written = FALSE; + req->eos_read = FALSE; + req->eos_sent = FALSE; + req->ignorebody = FALSE; + req->shutdown = FALSE; + req->bytecount = 0; + req->writebytecount = 0; + req->header = TRUE; /* assume header */ + req->headerline = 0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + + result = Curl_client_start(data); + if(result) + return result; + + if(!req->sendbuf_init) { + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + req->sendbuf_init = TRUE; + } + else { + Curl_bufq_reset(&req->sendbuf); + if(data->set.upload_buffer_size != req->sendbuf.chunk_size) { + Curl_bufq_free(&req->sendbuf); + Curl_bufq_init2(&req->sendbuf, data->set.upload_buffer_size, 1, + BUFQ_OPT_SOFT_LIMIT); + } + } + + return CURLE_OK; +} + +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data) +{ + req->start = Curl_now(); + return Curl_req_soft_reset(req, data); +} + +static CURLcode req_flush(struct Curl_easy *data); + +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted) +{ + (void)req; + if(!aborted) + (void)req_flush(data); + Curl_client_reset(data); +#ifndef CURL_DISABLE_DOH + Curl_doh_close(data); +#endif + return CURLE_OK; +} + +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data) +{ + struct curltime t0 = {0, 0}; + + /* This is a bit ugly. `req->p` is a union and we assume we can + * free this safely without leaks. */ + Curl_safefree(req->p.ftp); + Curl_safefree(req->newurl); + Curl_client_reset(data); + if(req->sendbuf_init) + Curl_bufq_reset(&req->sendbuf); + +#ifndef CURL_DISABLE_DOH + Curl_doh_close(data); +#endif + /* Can no longer memset() this struct as we need to keep some state */ + req->size = -1; + req->maxdownload = -1; + req->bytecount = 0; + req->writebytecount = 0; + req->start = t0; + req->headerbytecount = 0; + req->allheadercount = 0; + req->deductheadercount = 0; + req->headerline = 0; + req->offset = 0; + req->httpcode = 0; + req->keepon = 0; + req->upgr101 = UPGR101_INIT; + req->timeofdoc = 0; + req->location = NULL; + req->newurl = NULL; +#ifndef CURL_DISABLE_COOKIES + req->setcookies = 0; +#endif + req->header = FALSE; + req->content_range = FALSE; + req->download_done = FALSE; + req->eos_written = FALSE; + req->eos_read = FALSE; + req->eos_sent = FALSE; + req->upload_done = FALSE; + req->upload_aborted = FALSE; + req->ignorebody = FALSE; + req->http_bodyless = FALSE; + req->chunk = FALSE; + req->ignore_cl = FALSE; + req->upload_chunky = FALSE; + req->getheader = FALSE; + req->no_body = data->set.opt_no_body; + req->authneg = FALSE; + req->shutdown = FALSE; +#ifdef USE_HYPER + req->bodywritten = FALSE; +#endif +} + +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data) +{ + /* This is a bit ugly. `req->p` is a union and we assume we can + * free this safely without leaks. */ + Curl_safefree(req->p.ftp); + Curl_safefree(req->newurl); + if(req->sendbuf_init) + Curl_bufq_free(&req->sendbuf); + Curl_client_cleanup(data); + +#ifndef CURL_DISABLE_DOH + Curl_doh_cleanup(data); +#endif +} + +static CURLcode xfer_send(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len, size_t *pnwritten) +{ + CURLcode result = CURLE_OK; + bool eos = FALSE; + + *pnwritten = 0; + DEBUGASSERT(hds_len <= blen); +#ifdef DEBUGBUILD + { + /* Allow debug builds to override this logic to force short initial + sends */ + size_t body_len = blen - hds_len; + char *p = getenv("CURL_SMALLREQSEND"); + if(p) { + size_t body_small = (size_t)strtoul(p, NULL, 10); + if(body_small && body_small < body_len) + blen = hds_len + body_small; + } + } +#endif + /* Make sure this does not send more body bytes than what the max send + speed says. The headers do not count to the max speed. */ + if(data->set.max_send_speed) { + size_t body_bytes = blen - hds_len; + if((curl_off_t)body_bytes > data->set.max_send_speed) + blen = hds_len + (size_t)data->set.max_send_speed; + } + + if(data->req.eos_read && + (Curl_bufq_is_empty(&data->req.sendbuf) || + Curl_bufq_len(&data->req.sendbuf) == blen)) { + DEBUGF(infof(data, "sending last upload chunk of %zu bytes", blen)); + eos = TRUE; + } + result = Curl_xfer_send(data, buf, blen, eos, pnwritten); + if(!result) { + if(eos && (blen == *pnwritten)) + data->req.eos_sent = TRUE; + if(*pnwritten) { + if(hds_len) + Curl_debug(data, CURLINFO_HEADER_OUT, (char *)buf, + CURLMIN(hds_len, *pnwritten)); + if(*pnwritten > hds_len) { + size_t body_len = *pnwritten - hds_len; + Curl_debug(data, CURLINFO_DATA_OUT, (char *)buf + hds_len, body_len); + data->req.writebytecount += body_len; + Curl_pgrsSetUploadCounter(data, data->req.writebytecount); + } + } + } + return result; +} + +static CURLcode req_send_buffer_flush(struct Curl_easy *data) +{ + CURLcode result = CURLE_OK; + const unsigned char *buf; + size_t blen; + + while(Curl_bufq_peek(&data->req.sendbuf, &buf, &blen)) { + size_t nwritten, hds_len = CURLMIN(data->req.sendbuf_hds_len, blen); + result = xfer_send(data, (const char *)buf, blen, hds_len, &nwritten); + if(result) + break; + + Curl_bufq_skip(&data->req.sendbuf, nwritten); + if(hds_len) { + data->req.sendbuf_hds_len -= CURLMIN(hds_len, nwritten); + } + /* leave if we could not send all. Maybe network blocking or + * speed limits on transfer */ + if(nwritten < blen) + break; + } + return result; +} + +CURLcode Curl_req_set_upload_done(struct Curl_easy *data) +{ + DEBUGASSERT(!data->req.upload_done); + data->req.upload_done = TRUE; + data->req.keepon &= ~(KEEP_SEND|KEEP_SEND_TIMED); /* we are done sending */ + + Curl_pgrsTime(data, TIMER_POSTRANSFER); + Curl_creader_done(data, data->req.upload_aborted); + + if(data->req.upload_aborted) { + Curl_bufq_reset(&data->req.sendbuf); + if(data->req.writebytecount) + infof(data, "abort upload after having sent %" FMT_OFF_T " bytes", + data->req.writebytecount); + else + infof(data, "abort upload"); + } + else if(data->req.writebytecount) + infof(data, "upload completely sent off: %" FMT_OFF_T " bytes", + data->req.writebytecount); + else if(!data->req.download_done) { + DEBUGASSERT(Curl_bufq_is_empty(&data->req.sendbuf)); + infof(data, Curl_creader_total_length(data) ? + "We are completely uploaded and fine" : + "Request completely sent off"); + } + + return Curl_xfer_send_close(data); +} + +static CURLcode req_flush(struct Curl_easy *data) +{ + CURLcode result; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + result = req_send_buffer_flush(data); + if(result) + return result; + if(!Curl_bufq_is_empty(&data->req.sendbuf)) { + DEBUGF(infof(data, "Curl_req_flush(len=%zu) -> EAGAIN", + Curl_bufq_len(&data->req.sendbuf))); + return CURLE_AGAIN; + } + } + else if(Curl_xfer_needs_flush(data)) { + DEBUGF(infof(data, "Curl_req_flush(), xfer send_pending")); + return Curl_xfer_flush(data); + } + + if(data->req.eos_read && !data->req.eos_sent) { + char tmp; + size_t nwritten; + result = xfer_send(data, &tmp, 0, 0, &nwritten); + if(result) + return result; + DEBUGASSERT(data->req.eos_sent); + } + + if(!data->req.upload_done && data->req.eos_read && data->req.eos_sent) { + DEBUGASSERT(Curl_bufq_is_empty(&data->req.sendbuf)); + if(data->req.shutdown) { + bool done; + result = Curl_xfer_send_shutdown(data, &done); + if(result && data->req.shutdown_err_ignore) { + infof(data, "Shutdown send direction error: %d. Broken server? " + "Proceeding as if everything is ok.", result); + result = CURLE_OK; + done = TRUE; + } + + if(result) + return result; + if(!done) + return CURLE_AGAIN; + } + return Curl_req_set_upload_done(data); + } + return CURLE_OK; +} + +static ssize_t add_from_client(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_easy *data = reader_ctx; + size_t nread; + bool eos; + + *err = Curl_client_read(data, (char *)buf, buflen, &nread, &eos); + if(*err) + return -1; + if(eos) + data->req.eos_read = TRUE; + return (ssize_t)nread; +} + +#ifndef USE_HYPER + +static CURLcode req_send_buffer_add(struct Curl_easy *data, + const char *buf, size_t blen, + size_t hds_len) +{ + CURLcode result = CURLE_OK; + ssize_t n; + n = Curl_bufq_write(&data->req.sendbuf, + (const unsigned char *)buf, blen, &result); + if(n < 0) + return result; + /* We rely on a SOFTLIMIT on sendbuf, so it can take all data in */ + DEBUGASSERT((size_t)n == blen); + data->req.sendbuf_hds_len += hds_len; + return CURLE_OK; +} + +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *req) +{ + CURLcode result; + const char *buf; + size_t blen, nwritten; + + if(!data || !data->conn) + return CURLE_FAILED_INIT; + + buf = Curl_dyn_ptr(req); + blen = Curl_dyn_len(req); + if(!Curl_creader_total_length(data)) { + /* Request without body. Try to send directly from the buf given. */ + data->req.eos_read = TRUE; + result = xfer_send(data, buf, blen, blen, &nwritten); + if(result) + return result; + buf += nwritten; + blen -= nwritten; + } + + if(blen) { + /* Either we have a request body, or we could not send the complete + * request in one go. Buffer the remainder and try to add as much + * body bytes as room is left in the buffer. Then flush. */ + result = req_send_buffer_add(data, buf, blen, blen); + if(result) + return result; + + return Curl_req_send_more(data); + } + return CURLE_OK; +} +#endif /* !USE_HYPER */ + +bool Curl_req_sendbuf_empty(struct Curl_easy *data) +{ + return !data->req.sendbuf_init || Curl_bufq_is_empty(&data->req.sendbuf); +} + +bool Curl_req_want_send(struct Curl_easy *data) +{ + /* Not done and + * - KEEP_SEND and not PAUSEd. + * - or request has buffered data to send + * - or transfer connection has pending data to send */ + return !data->req.done && + (((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) || + !Curl_req_sendbuf_empty(data) || + Curl_xfer_needs_flush(data)); +} + +bool Curl_req_done_sending(struct Curl_easy *data) +{ + return data->req.upload_done && !Curl_req_want_send(data); +} + +CURLcode Curl_req_send_more(struct Curl_easy *data) +{ + CURLcode result; + + /* Fill our send buffer if more from client can be read. */ + if(!data->req.upload_aborted && + !data->req.eos_read && + !(data->req.keepon & KEEP_SEND_PAUSE) && + !Curl_bufq_is_full(&data->req.sendbuf)) { + ssize_t nread = Curl_bufq_sipn(&data->req.sendbuf, 0, + add_from_client, data, &result); + if(nread < 0 && result != CURLE_AGAIN) + return result; + } + + result = req_flush(data); + if(result == CURLE_AGAIN) + result = CURLE_OK; + + return result; +} + +CURLcode Curl_req_abort_sending(struct Curl_easy *data) +{ + if(!data->req.upload_done) { + Curl_bufq_reset(&data->req.sendbuf); + data->req.upload_aborted = TRUE; + /* no longer KEEP_SEND and KEEP_SEND_PAUSE */ + data->req.keepon &= ~KEEP_SENDBITS; + return Curl_req_set_upload_done(data); + } + return CURLE_OK; +} + +CURLcode Curl_req_stop_send_recv(struct Curl_easy *data) +{ + /* stop receiving and ALL sending as well, including PAUSE and HOLD. + * We might still be paused on receive client writes though, so + * keep those bits around. */ + data->req.keepon &= ~(KEEP_RECV|KEEP_SENDBITS); + return Curl_req_abort_sending(data); +} diff --git a/local-test-curl-full-01/afc-curl/lib/request.h b/local-test-curl-full-01/afc-curl/lib/request.h new file mode 100644 index 0000000000000000000000000000000000000000..bb722477882da2258b1b82fe413a9ef0f809dd78 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/request.h @@ -0,0 +1,251 @@ +#ifndef HEADER_CURL_REQUEST_H +#define HEADER_CURL_REQUEST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* This file is for lib internal stuff */ + +#include "curl_setup.h" + +#include "bufq.h" + +/* forward declarations */ +struct UserDefined; +#ifndef CURL_DISABLE_DOH +struct doh_probes; +#endif + +enum expect100 { + EXP100_SEND_DATA, /* enough waiting, just send the body now */ + EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */ + EXP100_SENDING_REQUEST, /* still sending the request but will wait for + the 100 header once done with the request */ + EXP100_FAILED /* used on 417 Expectation Failed */ +}; + +enum upgrade101 { + UPGR101_INIT, /* default state */ + UPGR101_WS, /* upgrade to WebSockets requested */ + UPGR101_H2, /* upgrade to HTTP/2 requested */ + UPGR101_RECEIVED, /* 101 response received */ + UPGR101_WORKING /* talking upgraded protocol */ +}; + + +/* + * Request specific data in the easy handle (Curl_easy). Previously, + * these members were on the connectdata struct but since a conn struct may + * now be shared between different Curl_easys, we store connection-specific + * data here. This struct only keeps stuff that is interesting for *this* + * request, as it will be cleared between multiple ones + */ +struct SingleRequest { + curl_off_t size; /* -1 if unknown at this point */ + curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch, + -1 means unlimited */ + curl_off_t bytecount; /* total number of bytes read */ + curl_off_t writebytecount; /* number of bytes written */ + + struct curltime start; /* transfer started at this time */ + unsigned int headerbytecount; /* received server headers (not CONNECT + headers) */ + unsigned int allheadercount; /* all received headers (server + CONNECT) */ + unsigned int deductheadercount; /* this amount of bytes does not count when + we check if anything has been transferred + at the end of a connection. We use this + counter to make only a 100 reply (without + a following second response code) result + in a CURLE_GOT_NOTHING error code */ + int headerline; /* counts header lines to better track the + first one */ + curl_off_t offset; /* possible resume offset read from the + Content-Range: header */ + int httpversion; /* Version in response (09, 10, 11, etc.) */ + int httpcode; /* error code from the 'HTTP/1.? XXX' or + 'RTSP/1.? XXX' line */ + int keepon; + enum upgrade101 upgr101; /* 101 upgrade state */ + + /* Client Writer stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct Curl_cwriter *writer_stack; + /* Client Reader stack, handles transfer- and content-encodings, protocol + * checks, pausing by client callbacks. */ + struct Curl_creader *reader_stack; + struct bufq sendbuf; /* data which needs to be send to the server */ + size_t sendbuf_hds_len; /* amount of header bytes in sendbuf */ + time_t timeofdoc; + char *location; /* This points to an allocated version of the Location: + header data */ + char *newurl; /* Set to the new URL to use when a redirect or a retry is + wanted */ + + /* Allocated protocol-specific data. Each protocol handler makes sure this + points to data it needs. */ + union { + struct FILEPROTO *file; + struct FTP *ftp; + struct IMAP *imap; + struct ldapreqinfo *ldap; + struct MQTT *mqtt; + struct POP3 *pop3; + struct RTSP *rtsp; + struct smb_request *smb; + struct SMTP *smtp; + struct SSHPROTO *ssh; + struct TELNET *telnet; + } p; +#ifndef CURL_DISABLE_DOH + struct doh_probes *doh; /* DoH specific data for this request */ +#endif +#ifndef CURL_DISABLE_COOKIES + unsigned char setcookies; +#endif + BIT(header); /* incoming data has HTTP header */ + BIT(done); /* request is done, e.g. no more send/recv should + * happen. This can be TRUE before `upload_done` or + * `download_done` is TRUE. */ + BIT(content_range); /* set TRUE if Content-Range: was found */ + BIT(download_done); /* set to TRUE when download is complete */ + BIT(eos_written); /* iff EOS has been written to client */ + BIT(eos_read); /* iff EOS has been read from the client */ + BIT(eos_sent); /* iff EOS has been sent to the server */ + BIT(rewind_read); /* iff reader needs rewind at next start */ + BIT(upload_done); /* set to TRUE when all request data has been sent */ + BIT(upload_aborted); /* set to TRUE when upload was aborted. Will also + * show `upload_done` as TRUE. */ + BIT(ignorebody); /* we read a response-body but we ignore it! */ + BIT(http_bodyless); /* HTTP response status code is between 100 and 199, + 204 or 304 */ + BIT(chunk); /* if set, this is a chunked transfer-encoding */ + BIT(resp_trailer); /* response carried 'Trailer:' header field */ + BIT(ignore_cl); /* ignore content-length */ + BIT(upload_chunky); /* set TRUE if we are doing chunked transfer-encoding + on upload */ + BIT(getheader); /* TRUE if header parsing is wanted */ + BIT(no_body); /* the response has no body */ + BIT(authneg); /* TRUE when the auth phase has started, which means + that we are creating a request with an auth header, + but it is not the final request in the auth + negotiation. */ + BIT(sendbuf_init); /* sendbuf is initialized */ + BIT(shutdown); /* request end will shutdown connection */ + BIT(shutdown_err_ignore); /* errors in shutdown will not fail request */ +#ifdef USE_HYPER + BIT(bodywritten); +#endif +}; + +/** + * Initialize the state of the request for first use. + */ +void Curl_req_init(struct SingleRequest *req); + +/** + * The request is about to start. Record time and do a soft reset. + */ +CURLcode Curl_req_start(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request may continue with a follow up. Reset + * members, but keep start time for overall duration calc. + */ +CURLcode Curl_req_soft_reset(struct SingleRequest *req, + struct Curl_easy *data); + +/** + * The request is done. If not aborted, make sure that buffers are + * flushed to the client. + * @param req the request + * @param data the transfer + * @param aborted TRUE iff the request was aborted/errored + */ +CURLcode Curl_req_done(struct SingleRequest *req, + struct Curl_easy *data, bool aborted); + +/** + * Free the state of the request, not usable afterwards. + */ +void Curl_req_free(struct SingleRequest *req, struct Curl_easy *data); + +/** + * Hard reset the state of the request to virgin state base on + * transfer settings. + */ +void Curl_req_hard_reset(struct SingleRequest *req, struct Curl_easy *data); + +#ifndef USE_HYPER +/** + * Send request headers. If not all could be sent + * they will be buffered. Use `Curl_req_flush()` to make sure + * bytes are really send. + * @param data the transfer making the request + * @param buf the complete header bytes, no body + * @return CURLE_OK (on blocking with *pnwritten == 0) or error. + */ +CURLcode Curl_req_send(struct Curl_easy *data, struct dynbuf *buf); + +#endif /* !USE_HYPER */ + +/** + * TRUE iff the request has sent all request headers and data. + */ +bool Curl_req_done_sending(struct Curl_easy *data); + +/* + * Read more from client and flush all buffered request bytes. + * @return CURLE_OK on success or the error on the sending. + * Never returns CURLE_AGAIN. + */ +CURLcode Curl_req_send_more(struct Curl_easy *data); + +/** + * TRUE iff the request wants to send, e.g. has buffered bytes. + */ +bool Curl_req_want_send(struct Curl_easy *data); + +/** + * TRUE iff the request has no buffered bytes yet to send. + */ +bool Curl_req_sendbuf_empty(struct Curl_easy *data); + +/** + * Stop sending any more request data to the server. + * Will clear the send buffer and mark request sending as done. + */ +CURLcode Curl_req_abort_sending(struct Curl_easy *data); + +/** + * Stop sending and receiving any more request data. + * Will abort sending if not done. + */ +CURLcode Curl_req_stop_send_recv(struct Curl_easy *data); + +/** + * Invoked when all request data has been uploaded. + */ +CURLcode Curl_req_set_upload_done(struct Curl_easy *data); + +#endif /* HEADER_CURL_REQUEST_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/select.c b/local-test-curl-full-01/afc-curl/lib/select.c new file mode 100644 index 0000000000000000000000000000000000000000..c1779ad1e51188c0c45af9165dc78adf562048ac --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/select.c @@ -0,0 +1,543 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(HAVE_SELECT) && !defined(HAVE_POLL) +#error "We cannot compile without select() or poll() support." +#endif + +#include + +#ifdef HAVE_SYS_SELECT_H +#include +#elif defined(HAVE_UNISTD_H) +#include +#endif + +#ifdef MSDOS +#include /* delay() */ +#endif + +#include + +#include "urldata.h" +#include "connect.h" +#include "select.h" +#include "timediff.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" + +/* + * Internal function used for waiting a specific amount of ms in + * Curl_socket_check() and Curl_poll() when no file descriptor is provided to + * wait on, just being used to delay execution. Winsock select() and poll() + * timeout mechanisms need a valid socket descriptor in a not null file + * descriptor set to work. Waiting indefinitely with this function is not + * allowed, a zero or negative timeout value will return immediately. Timeout + * resolution, accuracy, as well as maximum supported value is system + * dependent, neither factor is a critical issue for the intended use of this + * function in the library. + * + * Return values: + * -1 = system call error, or invalid timeout value + * 0 = specified timeout has elapsed, or interrupted + */ +int Curl_wait_ms(timediff_t timeout_ms) +{ + int r = 0; + + if(!timeout_ms) + return 0; + if(timeout_ms < 0) { + SET_SOCKERRNO(EINVAL); + return -1; + } +#if defined(MSDOS) + delay(timeout_ms); +#elif defined(_WIN32) + /* prevent overflow, timeout_ms is typecast to ULONG/DWORD. */ +#if TIMEDIFF_T_MAX >= ULONG_MAX + if(timeout_ms >= ULONG_MAX) + timeout_ms = ULONG_MAX-1; + /* do not use ULONG_MAX, because that is equal to INFINITE */ +#endif + Sleep((ULONG)timeout_ms); +#else + /* avoid using poll() for this since it behaves incorrectly with no sockets + on Apple operating systems */ + { + struct timeval pending_tv; + r = select(0, NULL, NULL, NULL, curlx_mstotv(&pending_tv, timeout_ms)); + } +#endif /* _WIN32 */ + if(r) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + else + r = -1; + } + return r; +} + +#ifndef HAVE_POLL +/* + * This is a wrapper around select() to aid in Windows compatibility. A + * negative timeout value makes this function wait indefinitely, unless no + * valid file descriptor is given, when this happens the negative timeout is + * ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of signalled file descriptors + */ +static int our_select(curl_socket_t maxfd, /* highest socket number */ + fd_set *fds_read, /* sockets ready for reading */ + fd_set *fds_write, /* sockets ready for writing */ + fd_set *fds_err, /* sockets with errors */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct timeval pending_tv; + struct timeval *ptimeout; + +#ifdef USE_WINSOCK + /* Winsock select() cannot handle zero events. See the comment below. */ + if((!fds_read || fds_read->fd_count == 0) && + (!fds_write || fds_write->fd_count == 0) && + (!fds_err || fds_err->fd_count == 0)) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } +#endif + + ptimeout = curlx_mstotv(&pending_tv, timeout_ms); + +#ifdef USE_WINSOCK + /* Winsock select() must not be called with an fd_set that contains zero + fd flags, or it will return WSAEINVAL. But, it also cannot be called + with no fd_sets at all! From the documentation: + + Any two of the parameters, readfds, writefds, or exceptfds, can be + given as null. At least one must be non-null, and any non-null + descriptor set must contain at least one handle to a socket. + + It is unclear why Winsock does not just handle this for us instead of + calling this an error. Luckily, with Winsock, we can _also_ ask how + many bits are set on an fd_set. So, let's just check it beforehand. + */ + return select((int)maxfd + 1, + fds_read && fds_read->fd_count ? fds_read : NULL, + fds_write && fds_write->fd_count ? fds_write : NULL, + fds_err && fds_err->fd_count ? fds_err : NULL, ptimeout); +#else + return select((int)maxfd + 1, fds_read, fds_write, fds_err, ptimeout); +#endif +} + +#endif + +/* + * Wait for read or write events on a set of file descriptors. It uses poll() + * when poll() is available, in order to avoid limits with FD_SETSIZE, + * otherwise select() is used. An error is returned if select() is being used + * and a file descriptor is too large for FD_SETSIZE. + * + * A negative timeout value makes this function wait indefinitely, unless no + * valid file descriptor is given, when this happens the negative timeout is + * ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * [bitmask] = action as described below + * + * CURL_CSELECT_IN - first socket is readable + * CURL_CSELECT_IN2 - second socket is readable + * CURL_CSELECT_OUT - write socket is writable + * CURL_CSELECT_ERR - an error condition occurred + */ +int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ + curl_socket_t readfd1, + curl_socket_t writefd, /* socket to write to */ + timediff_t timeout_ms) /* milliseconds to wait */ +{ + struct pollfd pfd[3]; + int num; + int r; + + if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) && + (writefd == CURL_SOCKET_BAD)) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid Curl_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd0; + pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; + pfd[num].revents = 0; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + pfd[num].fd = readfd1; + pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; + pfd[num].revents = 0; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + pfd[num].fd = writefd; + pfd[num].events = POLLWRNORM|POLLOUT|POLLPRI; + pfd[num].revents = 0; + num++; + } + + r = Curl_poll(pfd, (unsigned int)num, timeout_ms); + if(r <= 0) + return r; + + r = 0; + num = 0; + if(readfd0 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) + r |= CURL_CSELECT_IN; + if(pfd[num].revents & (POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(readfd1 != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) + r |= CURL_CSELECT_IN2; + if(pfd[num].revents & (POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + num++; + } + if(writefd != CURL_SOCKET_BAD) { + if(pfd[num].revents & (POLLWRNORM|POLLOUT)) + r |= CURL_CSELECT_OUT; + if(pfd[num].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) + r |= CURL_CSELECT_ERR; + } + + return r; +} + +/* + * This is a wrapper around poll(). If poll() does not exist, then + * select() is used instead. An error is returned if select() is + * being used and a file descriptor is too large for FD_SETSIZE. + * A negative timeout value makes this function wait indefinitely, + * unless no valid file descriptor is given, when this happens the + * negative timeout is ignored and the function times out immediately. + * + * Return values: + * -1 = system call error or fd >= FD_SETSIZE + * 0 = timeout + * N = number of structures with non zero revent fields + */ +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms) +{ +#ifdef HAVE_POLL + int pending_ms; +#else + fd_set fds_read; + fd_set fds_write; + fd_set fds_err; + curl_socket_t maxfd; +#endif + bool fds_none = TRUE; + unsigned int i; + int r; + + if(ufds) { + for(i = 0; i < nfds; i++) { + if(ufds[i].fd != CURL_SOCKET_BAD) { + fds_none = FALSE; + break; + } + } + } + if(fds_none) { + /* no sockets, just wait */ + return Curl_wait_ms(timeout_ms); + } + + /* Avoid initial timestamp, avoid Curl_now() call, when elapsed + time in this function does not need to be measured. This happens + when function is called with a zero timeout or a negative timeout + value indicating a blocking call should be performed. */ + +#ifdef HAVE_POLL + + /* prevent overflow, timeout_ms is typecast to int. */ +#if TIMEDIFF_T_MAX > INT_MAX + if(timeout_ms > INT_MAX) + timeout_ms = INT_MAX; +#endif + if(timeout_ms > 0) + pending_ms = (int)timeout_ms; + else if(timeout_ms < 0) + pending_ms = -1; + else + pending_ms = 0; + r = poll(ufds, nfds, pending_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + for(i = 0; i < nfds; i++) { + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(ufds[i].revents & POLLHUP) + ufds[i].revents |= POLLIN; + if(ufds[i].revents & POLLERR) + ufds[i].revents |= POLLIN|POLLOUT; + } + +#else /* HAVE_POLL */ + + FD_ZERO(&fds_read); + FD_ZERO(&fds_write); + FD_ZERO(&fds_err); + maxfd = (curl_socket_t)-1; + + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + VERIFY_SOCK(ufds[i].fd); + if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI| + POLLRDNORM|POLLWRNORM|POLLRDBAND)) { + if(ufds[i].fd > maxfd) + maxfd = ufds[i].fd; + if(ufds[i].events & (POLLRDNORM|POLLIN)) + FD_SET(ufds[i].fd, &fds_read); + if(ufds[i].events & (POLLWRNORM|POLLOUT)) + FD_SET(ufds[i].fd, &fds_write); + if(ufds[i].events & (POLLRDBAND|POLLPRI)) + FD_SET(ufds[i].fd, &fds_err); + } + } + + /* + Note also that Winsock ignores the first argument, so we do not worry + about the fact that maxfd is computed incorrectly with Winsock (since + curl_socket_t is unsigned in such cases and thus -1 is the largest + value). + */ + r = our_select(maxfd, &fds_read, &fds_write, &fds_err, timeout_ms); + if(r <= 0) { + if((r == -1) && (SOCKERRNO == EINTR)) + /* make EINTR from select or poll not a "lethal" error */ + r = 0; + return r; + } + + r = 0; + for(i = 0; i < nfds; i++) { + ufds[i].revents = 0; + if(ufds[i].fd == CURL_SOCKET_BAD) + continue; + if(FD_ISSET(ufds[i].fd, &fds_read)) { + if(ufds[i].events & POLLRDNORM) + ufds[i].revents |= POLLRDNORM; + if(ufds[i].events & POLLIN) + ufds[i].revents |= POLLIN; + } + if(FD_ISSET(ufds[i].fd, &fds_write)) { + if(ufds[i].events & POLLWRNORM) + ufds[i].revents |= POLLWRNORM; + if(ufds[i].events & POLLOUT) + ufds[i].revents |= POLLOUT; + } + if(FD_ISSET(ufds[i].fd, &fds_err)) { + if(ufds[i].events & POLLRDBAND) + ufds[i].revents |= POLLRDBAND; + if(ufds[i].events & POLLPRI) + ufds[i].revents |= POLLPRI; + } + if(ufds[i].revents) + r++; + } + +#endif /* HAVE_POLL */ + + return r; +} + +void Curl_pollfds_init(struct curl_pollfds *cpfds, + struct pollfd *static_pfds, + unsigned int static_count) +{ + DEBUGASSERT(cpfds); + memset(cpfds, 0, sizeof(*cpfds)); + if(static_pfds && static_count) { + cpfds->pfds = static_pfds; + cpfds->count = static_count; + } +} + +void Curl_pollfds_cleanup(struct curl_pollfds *cpfds) +{ + DEBUGASSERT(cpfds); + if(cpfds->allocated_pfds) { + free(cpfds->pfds); + } + memset(cpfds, 0, sizeof(*cpfds)); +} + +static CURLcode cpfds_increase(struct curl_pollfds *cpfds, unsigned int inc) +{ + struct pollfd *new_fds; + unsigned int new_count = cpfds->count + inc; + + new_fds = calloc(new_count, sizeof(struct pollfd)); + if(!new_fds) + return CURLE_OUT_OF_MEMORY; + + memcpy(new_fds, cpfds->pfds, cpfds->count * sizeof(struct pollfd)); + if(cpfds->allocated_pfds) + free(cpfds->pfds); + cpfds->pfds = new_fds; + cpfds->count = new_count; + cpfds->allocated_pfds = TRUE; + return CURLE_OK; +} + +static CURLcode cpfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events, bool fold) +{ + int i; + + if(fold && cpfds->n <= INT_MAX) { + for(i = (int)cpfds->n - 1; i >= 0; --i) { + if(sock == cpfds->pfds[i].fd) { + cpfds->pfds[i].events |= events; + return CURLE_OK; + } + } + } + /* not folded, add new entry */ + if(cpfds->n >= cpfds->count) { + if(cpfds_increase(cpfds, 100)) + return CURLE_OUT_OF_MEMORY; + } + cpfds->pfds[cpfds->n].fd = sock; + cpfds->pfds[cpfds->n].events = events; + ++cpfds->n; + return CURLE_OK; +} + +CURLcode Curl_pollfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events) +{ + return cpfds_add_sock(cpfds, sock, events, FALSE); +} + +CURLcode Curl_pollfds_add_ps(struct curl_pollfds *cpfds, + struct easy_pollset *ps) +{ + size_t i; + + DEBUGASSERT(cpfds); + DEBUGASSERT(ps); + for(i = 0; i < ps->num; i++) { + short events = 0; + if(ps->actions[i] & CURL_POLL_IN) + events |= POLLIN; + if(ps->actions[i] & CURL_POLL_OUT) + events |= POLLOUT; + if(events) { + if(cpfds_add_sock(cpfds, ps->sockets[i], events, TRUE)) + return CURLE_OUT_OF_MEMORY; + } + } + return CURLE_OK; +} + +void Curl_waitfds_init(struct curl_waitfds *cwfds, + struct curl_waitfd *static_wfds, + unsigned int static_count) +{ + DEBUGASSERT(cwfds); + DEBUGASSERT(static_wfds); + memset(cwfds, 0, sizeof(*cwfds)); + cwfds->wfds = static_wfds; + cwfds->count = static_count; +} + +static CURLcode cwfds_add_sock(struct curl_waitfds *cwfds, + curl_socket_t sock, short events) +{ + int i; + + if(cwfds->n <= INT_MAX) { + for(i = (int)cwfds->n - 1; i >= 0; --i) { + if(sock == cwfds->wfds[i].fd) { + cwfds->wfds[i].events |= events; + return CURLE_OK; + } + } + } + /* not folded, add new entry */ + if(cwfds->n >= cwfds->count) + return CURLE_OUT_OF_MEMORY; + cwfds->wfds[cwfds->n].fd = sock; + cwfds->wfds[cwfds->n].events = events; + ++cwfds->n; + return CURLE_OK; +} + +CURLcode Curl_waitfds_add_ps(struct curl_waitfds *cwfds, + struct easy_pollset *ps) +{ + size_t i; + + DEBUGASSERT(cwfds); + DEBUGASSERT(ps); + for(i = 0; i < ps->num; i++) { + short events = 0; + if(ps->actions[i] & CURL_POLL_IN) + events |= CURL_WAIT_POLLIN; + if(ps->actions[i] & CURL_POLL_OUT) + events |= CURL_WAIT_POLLOUT; + if(events) { + if(cwfds_add_sock(cwfds, ps->sockets[i], events)) + return CURLE_OUT_OF_MEMORY; + } + } + return CURLE_OK; +} diff --git a/local-test-curl-full-01/afc-curl/lib/select.h b/local-test-curl-full-01/afc-curl/lib/select.h new file mode 100644 index 0000000000000000000000000000000000000000..f01acbdefc21d3dd935dca5863356e4b29f76e82 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/select.h @@ -0,0 +1,147 @@ +#ifndef HEADER_CURL_SELECT_H +#define HEADER_CURL_SELECT_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifdef HAVE_POLL_H +#include +#elif defined(HAVE_SYS_POLL_H) +#include +#endif + +/* + * Definition of pollfd struct and constants for platforms lacking them. + */ + +#if !defined(HAVE_SYS_POLL_H) && \ + !defined(HAVE_POLL_H) && \ + !defined(POLLIN) + +#define POLLIN 0x01 +#define POLLPRI 0x02 +#define POLLOUT 0x04 +#define POLLERR 0x08 +#define POLLHUP 0x10 +#define POLLNVAL 0x20 + +struct pollfd +{ + curl_socket_t fd; + short events; + short revents; +}; + +#endif + +#ifndef POLLRDNORM +#define POLLRDNORM POLLIN +#endif + +#ifndef POLLWRNORM +#define POLLWRNORM POLLOUT +#endif + +#ifndef POLLRDBAND +#define POLLRDBAND POLLPRI +#endif + +/* there are three CSELECT defines that are defined in the public header that + are exposed to users, but this *IN2 bit is only ever used internally and + therefore defined here */ +#define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1) + +int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2, + curl_socket_t writefd, + timediff_t timeout_ms); +#define SOCKET_READABLE(x,z) \ + Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z) +#define SOCKET_WRITABLE(x,z) \ + Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z) + +int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms); +int Curl_wait_ms(timediff_t timeout_ms); + +/* + With Winsock the valid range is [0..INVALID_SOCKET-1] according to + https://docs.microsoft.com/en-us/windows/win32/winsock/socket-data-type-2 +*/ +#ifdef USE_WINSOCK +#define VALID_SOCK(s) ((s) < INVALID_SOCKET) +#define FDSET_SOCK(x) 1 +#define VERIFY_SOCK(x) do { \ + if(!VALID_SOCK(x)) { \ + SET_SOCKERRNO(WSAEINVAL); \ + return -1; \ + } \ +} while(0) +#else +#define VALID_SOCK(s) ((s) >= 0) + +/* If the socket is small enough to get set or read from an fdset */ +#define FDSET_SOCK(s) ((s) < FD_SETSIZE) + +#define VERIFY_SOCK(x) do { \ + if(!VALID_SOCK(x) || !FDSET_SOCK(x)) { \ + SET_SOCKERRNO(EINVAL); \ + return -1; \ + } \ + } while(0) +#endif + +struct curl_pollfds { + struct pollfd *pfds; + unsigned int n; + unsigned int count; + BIT(allocated_pfds); +}; + +void Curl_pollfds_init(struct curl_pollfds *cpfds, + struct pollfd *static_pfds, + unsigned int static_count); + +void Curl_pollfds_cleanup(struct curl_pollfds *cpfds); + +CURLcode Curl_pollfds_add_ps(struct curl_pollfds *cpfds, + struct easy_pollset *ps); + +CURLcode Curl_pollfds_add_sock(struct curl_pollfds *cpfds, + curl_socket_t sock, short events); + +struct curl_waitfds { + struct curl_waitfd *wfds; + unsigned int n; + unsigned int count; +}; + +void Curl_waitfds_init(struct curl_waitfds *cwfds, + struct curl_waitfd *static_wfds, + unsigned int static_count); + +CURLcode Curl_waitfds_add_ps(struct curl_waitfds *cwfds, + struct easy_pollset *ps); + + +#endif /* HEADER_CURL_SELECT_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/sendf.h b/local-test-curl-full-01/afc-curl/lib/sendf.h new file mode 100644 index 0000000000000000000000000000000000000000..dc1b82edfecd6269db51438b6225fd56273903dc --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/sendf.h @@ -0,0 +1,415 @@ +#ifndef HEADER_CURL_SENDF_H +#define HEADER_CURL_SENDF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "curl_trc.h" + +/** + * Type of data that is being written to the client (application) + * - data written can be either BODY or META data + * - META data is either INFO or HEADER + * - INFO is meta information, e.g. not BODY, that cannot be interpreted + * as headers of a response. Example FTP/IMAP pingpong answers. + * - HEADER can have additional bits set (more than one) + * - STATUS special "header", e.g. response status line in HTTP + * - CONNECT header was received during proxying the connection + * - 1XX header is part of an intermediate response, e.g. HTTP 1xx code + * - TRAILER header is trailing response data, e.g. HTTP trailers + * BODY, INFO and HEADER should not be mixed, as this would lead to + * confusion on how to interpret/format/convert the data. + */ +#define CLIENTWRITE_BODY (1<<0) /* non-meta information, BODY */ +#define CLIENTWRITE_INFO (1<<1) /* meta information, not a HEADER */ +#define CLIENTWRITE_HEADER (1<<2) /* meta information, HEADER */ +#define CLIENTWRITE_STATUS (1<<3) /* a special status HEADER */ +#define CLIENTWRITE_CONNECT (1<<4) /* a CONNECT related HEADER */ +#define CLIENTWRITE_1XX (1<<5) /* a 1xx response related HEADER */ +#define CLIENTWRITE_TRAILER (1<<6) /* a trailer HEADER */ +#define CLIENTWRITE_EOS (1<<7) /* End Of transfer download Stream */ + +/** + * Write `len` bytes at `prt` to the client. `type` indicates what + * kind of data is being written. + */ +CURLcode Curl_client_write(struct Curl_easy *data, int type, const char *ptr, + size_t len) WARN_UNUSED_RESULT; + +/** + * Free all resources related to client writing. + */ +void Curl_client_cleanup(struct Curl_easy *data); + +/** + * Reset readers and writer chains, keep rewind information + * when necessary. + */ +void Curl_client_reset(struct Curl_easy *data); + +/** + * A new request is starting, perform any ops like rewinding + * previous readers when needed. + */ +CURLcode Curl_client_start(struct Curl_easy *data); + +/** + * Client Writers - a chain passing transfer BODY data to the client. + * Main application: HTTP and related protocols + * Other uses: monitoring of download progress + * + * Writers in the chain are order by their `phase`. First come all + * writers in CURL_CW_RAW, followed by any in CURL_CW_TRANSFER_DECODE, + * followed by any in CURL_CW_PROTOCOL, etc. + * + * When adding a writer, it is inserted as first in its phase. This means + * the order of adding writers of the same phase matters, but writers for + * different phases may be added in any order. + * + * Writers which do modify the BODY data written are expected to be of + * phases TRANSFER_DECODE or CONTENT_DECODE. The other phases are intended + * for monitoring writers. Which do *not* modify the data but gather + * statistics or update progress reporting. + */ + +/* Phase a writer operates at. */ +typedef enum { + CURL_CW_RAW, /* raw data written, before any decoding */ + CURL_CW_TRANSFER_DECODE, /* remove transfer-encodings */ + CURL_CW_PROTOCOL, /* after transfer, but before content decoding */ + CURL_CW_CONTENT_DECODE, /* remove content-encodings */ + CURL_CW_CLIENT /* data written to client */ +} Curl_cwriter_phase; + +/* Client Writer Type, provides the implementation */ +struct Curl_cwtype { + const char *name; /* writer name. */ + const char *alias; /* writer name alias, maybe NULL. */ + CURLcode (*do_init)(struct Curl_easy *data, + struct Curl_cwriter *writer); + CURLcode (*do_write)(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); + void (*do_close)(struct Curl_easy *data, + struct Curl_cwriter *writer); + size_t cwriter_size; /* sizeof() allocated struct Curl_cwriter */ +}; + +/* Client writer instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_cwriter { + const struct Curl_cwtype *cwt; /* type implementation */ + struct Curl_cwriter *next; /* Downstream writer. */ + void *ctx; /* allocated instance pointer */ + Curl_cwriter_phase phase; /* phase at which it operates */ +}; + +/** + * Create a new cwriter instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `writer->do_init()`. + */ +CURLcode Curl_cwriter_create(struct Curl_cwriter **pwriter, + struct Curl_easy *data, + const struct Curl_cwtype *ce_handler, + Curl_cwriter_phase phase); + +/** + * Free a cwriter instance. + * Invokes `writer->do_close()`. + */ +void Curl_cwriter_free(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Count the number of writers installed of the given phase. + */ +size_t Curl_cwriter_count(struct Curl_easy *data, Curl_cwriter_phase phase); + +/** + * Adds a writer to the transfer's writer chain. + * The writers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_cwriter_add(struct Curl_easy *data, + struct Curl_cwriter *writer); + +/** + * Look up an installed client writer on `data` by its type. + * @return first writer with that type or NULL + */ +struct Curl_cwriter *Curl_cwriter_get_by_type(struct Curl_easy *data, + const struct Curl_cwtype *cwt); + +void Curl_cwriter_remove_by_name(struct Curl_easy *data, + const char *name); + +struct Curl_cwriter *Curl_cwriter_get_by_name(struct Curl_easy *data, + const char *name); + +/** + * Convenience method for calling `writer->do_write()` that + * checks for NULL writer. + */ +CURLcode Curl_cwriter_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); + +/** + * Return TRUE iff client writer is paused. + */ +bool Curl_cwriter_is_paused(struct Curl_easy *data); + +/** + * Unpause client writer and flush any buffered date to the client. + */ +CURLcode Curl_cwriter_unpause(struct Curl_easy *data); + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_cwriter_def_init(struct Curl_easy *data, + struct Curl_cwriter *writer); +CURLcode Curl_cwriter_def_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes); +void Curl_cwriter_def_close(struct Curl_easy *data, + struct Curl_cwriter *writer); + + + +/* Client Reader Type, provides the implementation */ +struct Curl_crtype { + const char *name; /* writer name. */ + CURLcode (*do_init)(struct Curl_easy *data, struct Curl_creader *reader); + CURLcode (*do_read)(struct Curl_easy *data, struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + void (*do_close)(struct Curl_easy *data, struct Curl_creader *reader); + bool (*needs_rewind)(struct Curl_easy *data, struct Curl_creader *reader); + curl_off_t (*total_length)(struct Curl_easy *data, + struct Curl_creader *reader); + CURLcode (*resume_from)(struct Curl_easy *data, + struct Curl_creader *reader, curl_off_t offset); + CURLcode (*rewind)(struct Curl_easy *data, struct Curl_creader *reader); + CURLcode (*unpause)(struct Curl_easy *data, struct Curl_creader *reader); + bool (*is_paused)(struct Curl_easy *data, struct Curl_creader *reader); + void (*done)(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + size_t creader_size; /* sizeof() allocated struct Curl_creader */ +}; + +/* Phase a reader operates at. */ +typedef enum { + CURL_CR_NET, /* data send to the network (connection filters) */ + CURL_CR_TRANSFER_ENCODE, /* add transfer-encodings */ + CURL_CR_PROTOCOL, /* before transfer, but after content decoding */ + CURL_CR_CONTENT_ENCODE, /* add content-encodings */ + CURL_CR_CLIENT /* data read from client */ +} Curl_creader_phase; + +/* Client reader instance, allocated on creation. + * `void *ctx` is the pointer from the allocation of + * the `struct Curl_cwriter` itself. This is suitable for "downcasting" + * by the writers implementation. See https://github.com/curl/curl/pull/13054 + * for the alignment problems that arise otherwise. + */ +struct Curl_creader { + const struct Curl_crtype *crt; /* type implementation */ + struct Curl_creader *next; /* Downstream reader. */ + void *ctx; + Curl_creader_phase phase; /* phase at which it operates */ +}; + +/** + * Default implementations for do_init, do_write, do_close that + * do nothing and pass the data through. + */ +CURLcode Curl_creader_def_init(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_close(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, + size_t *nread, bool *eos); +bool Curl_creader_def_needs_rewind(struct Curl_easy *data, + struct Curl_creader *reader); +curl_off_t Curl_creader_def_total_length(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_resume_from(struct Curl_easy *data, + struct Curl_creader *reader, + curl_off_t offset); +CURLcode Curl_creader_def_rewind(struct Curl_easy *data, + struct Curl_creader *reader); +CURLcode Curl_creader_def_unpause(struct Curl_easy *data, + struct Curl_creader *reader); +bool Curl_creader_def_is_paused(struct Curl_easy *data, + struct Curl_creader *reader); +void Curl_creader_def_done(struct Curl_easy *data, + struct Curl_creader *reader, int premature); + +/** + * Convenience method for calling `reader->do_read()` that + * checks for NULL reader. + */ +CURLcode Curl_creader_read(struct Curl_easy *data, + struct Curl_creader *reader, + char *buf, size_t blen, size_t *nread, bool *eos); + +/** + * Create a new creader instance with given type and phase. Is not + * inserted into the writer chain by this call. + * Invokes `reader->do_init()`. + */ +CURLcode Curl_creader_create(struct Curl_creader **preader, + struct Curl_easy *data, + const struct Curl_crtype *cr_handler, + Curl_creader_phase phase); + +/** + * Free a creader instance. + * Invokes `reader->do_close()`. + */ +void Curl_creader_free(struct Curl_easy *data, struct Curl_creader *reader); + +/** + * Adds a reader to the transfer's reader chain. + * The readers `phase` determines where in the chain it is inserted. + */ +CURLcode Curl_creader_add(struct Curl_easy *data, + struct Curl_creader *reader); + +/** + * Set the given reader, which needs to be of type CURL_CR_CLIENT, + * as the new first reader. Discard any installed readers and init + * the reader chain anew. + * The function takes ownership of `r`. + */ +CURLcode Curl_creader_set(struct Curl_easy *data, struct Curl_creader *r); + +/** + * Read at most `blen` bytes at `buf` from the client. + * @param data the transfer to read client bytes for + * @param buf the memory location to read to + * @param blen the amount of memory at `buf` + * @param nread on return the number of bytes read into `buf` + * @param eos TRUE iff bytes are the end of data from client + * @return CURLE_OK on successful read (even 0 length) or error + */ +CURLcode Curl_client_read(struct Curl_easy *data, char *buf, size_t blen, + size_t *nread, bool *eos) WARN_UNUSED_RESULT; + +/** + * TRUE iff client reader needs rewing before it can be used for + * a retry request. + */ +bool Curl_creader_needs_rewind(struct Curl_easy *data); + +/** + * TRUE iff client reader will rewind at next start + */ +bool Curl_creader_will_rewind(struct Curl_easy *data); + +/** + * En-/disable rewind of client reader at next start. + */ +void Curl_creader_set_rewind(struct Curl_easy *data, bool enable); + +/** + * Get the total length of bytes provided by the installed readers. + * This is independent of the amount already delivered and is calculated + * by all readers in the stack. If a reader like "chunked" or + * "crlf conversion" is installed, the returned length will be -1. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_total_length(struct Curl_easy *data); + +/** + * Get the total length of bytes provided by the reader at phase + * CURL_CR_CLIENT. This may not match the amount of bytes read + * for a request, depending if other, encoding readers are also installed. + * However it allows for rough estimation of the overall length. + * @return -1 if length is indeterminate + */ +curl_off_t Curl_creader_client_length(struct Curl_easy *data); + +/** + * Ask the installed reader at phase CURL_CR_CLIENT to start + * reading from the given offset. On success, this will reduce + * the `total_length()` by the amount. + * @param data the transfer to read client bytes for + * @param offset the offset where to start reads from, negative + * values will be ignored. + * @return CURLE_OK if offset could be set + * CURLE_READ_ERROR if not supported by reader or seek/read failed + * of offset larger then total length + * CURLE_PARTIAL_FILE if offset led to 0 total length + */ +CURLcode Curl_creader_resume_from(struct Curl_easy *data, curl_off_t offset); + +/** + * Unpause all installed readers. + */ +CURLcode Curl_creader_unpause(struct Curl_easy *data); + +/** + * Return TRUE iff any of the installed readers is paused. + */ +bool Curl_creader_is_paused(struct Curl_easy *data); + +/** + * Tell all client readers that they are done. + */ +void Curl_creader_done(struct Curl_easy *data, int premature); + +/** + * Look up an installed client reader on `data` by its type. + * @return first reader with that type or NULL + */ +struct Curl_creader *Curl_creader_get_by_type(struct Curl_easy *data, + const struct Curl_crtype *crt); + + +/** + * Set the client reader to provide 0 bytes, immediate EOS. + */ +CURLcode Curl_creader_set_null(struct Curl_easy *data); + +/** + * Set the client reader the reads from fread callback. + */ +CURLcode Curl_creader_set_fread(struct Curl_easy *data, curl_off_t len); + +/** + * Set the client reader the reads from the supplied buf (NOT COPIED). + */ +CURLcode Curl_creader_set_buf(struct Curl_easy *data, + const char *buf, size_t blen); + +#endif /* HEADER_CURL_SENDF_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/setup-os400.h b/local-test-curl-full-01/afc-curl/lib/setup-os400.h new file mode 100644 index 0000000000000000000000000000000000000000..ef7baca67efff4022e5de3ceabff04d37e3dfba2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/setup-os400.h @@ -0,0 +1,157 @@ +#ifndef HEADER_CURL_SETUP_OS400_H +#define HEADER_CURL_SETUP_OS400_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + + +/* OS/400 netdb.h does not define NI_MAXHOST. */ +#define NI_MAXHOST 1025 + +/* OS/400 netdb.h does not define NI_MAXSERV. */ +#define NI_MAXSERV 32 + +/* No OS/400 header file defines u_int32_t. */ +typedef unsigned long u_int32_t; + +/* OS/400 has no idea of a tty! */ +#define isatty(fd) 0 + + +/* Workaround bug in IBM QADRT runtime library: + * function puts() does not output the implicit trailing newline. + */ + +#include /* Be sure it is loaded. */ +#undef puts +#define puts(s) (fputs((s), stdout) == EOF? EOF: putchar('\n')) + + +/* System API wrapper prototypes & definitions to support ASCII parameters. */ + +#include +#include +#include +#include +#include + +#ifdef BUILDING_LIBCURL + +extern int Curl_getaddrinfo_a(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); +#define getaddrinfo Curl_getaddrinfo_a + +/* Note socklen_t must be used as this is declared before curl_socklen_t */ +extern int Curl_getnameinfo_a(const struct sockaddr *sa, + socklen_t salen, + char *nodename, socklen_t nodenamelen, + char *servname, socklen_t servnamelen, + int flags); +#define getnameinfo Curl_getnameinfo_a + +/* GSSAPI wrappers. */ + +extern OM_uint32 Curl_gss_import_name_a(OM_uint32 * minor_status, + gss_buffer_t in_name, + gss_OID in_name_type, + gss_name_t * out_name); +#define gss_import_name Curl_gss_import_name_a + + +extern OM_uint32 Curl_gss_display_status_a(OM_uint32 * minor_status, + OM_uint32 status_value, + int status_type, gss_OID mech_type, + gss_msg_ctx_t * message_context, + gss_buffer_t status_string); +#define gss_display_status Curl_gss_display_status_a + + +extern OM_uint32 Curl_gss_init_sec_context_a(OM_uint32 * minor_status, + gss_cred_id_t cred_handle, + gss_ctx_id_t * context_handle, + gss_name_t target_name, + gss_OID mech_type, + gss_flags_t req_flags, + OM_uint32 time_req, + gss_channel_bindings_t + input_chan_bindings, + gss_buffer_t input_token, + gss_OID * actual_mech_type, + gss_buffer_t output_token, + gss_flags_t * ret_flags, + OM_uint32 * time_rec); +#define gss_init_sec_context Curl_gss_init_sec_context_a + + +extern OM_uint32 Curl_gss_delete_sec_context_a(OM_uint32 * minor_status, + gss_ctx_id_t * context_handle, + gss_buffer_t output_token); +#define gss_delete_sec_context Curl_gss_delete_sec_context_a + + +/* LDAP wrappers. */ + +#define BerValue struct berval + +#define ldap_url_parse ldap_url_parse_utf8 +#define ldap_init Curl_ldap_init_a +#define ldap_simple_bind_s Curl_ldap_simple_bind_s_a +#define ldap_search_s Curl_ldap_search_s_a +#define ldap_get_values_len Curl_ldap_get_values_len_a +#define ldap_err2string Curl_ldap_err2string_a +#define ldap_get_dn Curl_ldap_get_dn_a +#define ldap_first_attribute Curl_ldap_first_attribute_a +#define ldap_next_attribute Curl_ldap_next_attribute_a + +/* Some socket functions must be wrapped to process textual addresses + like AF_UNIX. */ + +extern int Curl_os400_connect(int sd, struct sockaddr *destaddr, int addrlen); +extern int Curl_os400_bind(int sd, struct sockaddr *localaddr, int addrlen); +extern int Curl_os400_sendto(int sd, char *buffer, int buflen, int flags, + const struct sockaddr *dstaddr, int addrlen); +extern int Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags, + struct sockaddr *fromaddr, int *addrlen); +extern int Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen); +extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen); + +#define connect Curl_os400_connect +#define bind Curl_os400_bind +#define sendto Curl_os400_sendto +#define recvfrom Curl_os400_recvfrom +#define getpeername Curl_os400_getpeername +#define getsockname Curl_os400_getsockname + +#ifdef HAVE_LIBZ +#define zlibVersion Curl_os400_zlibVersion +#define inflateInit_ Curl_os400_inflateInit_ +#define inflateInit2_ Curl_os400_inflateInit2_ +#define inflate Curl_os400_inflate +#define inflateEnd Curl_os400_inflateEnd +#endif + +#endif /* BUILDING_LIBCURL */ + +#endif /* HEADER_CURL_SETUP_OS400_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/sha256.c b/local-test-curl-full-01/afc-curl/lib/sha256.c new file mode 100644 index 0000000000000000000000000000000000000000..c5bb921bb3029c09360a81433c064df61a74304e --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/sha256.c @@ -0,0 +1,537 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Florin Petriuc, + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if !defined(CURL_DISABLE_AWS) || !defined(CURL_DISABLE_DIGEST_AUTH) \ + || defined(USE_LIBSSH2) + +#include "warnless.h" +#include "curl_sha256.h" +#include "curl_hmac.h" + +#ifdef USE_WOLFSSL +#include +#endif + +#if defined(USE_OPENSSL) + +#include + +#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) +#define USE_OPENSSL_SHA256 +#endif + +#endif /* USE_OPENSSL */ + +#ifdef USE_MBEDTLS +#include + +#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ + (MBEDTLS_VERSION_NUMBER < 0x03000000) + #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS +#endif +#endif /* USE_MBEDTLS */ + +#if defined(USE_OPENSSL_SHA256) + +/* When OpenSSL or wolfSSL is available we use their SHA256-functions. */ +#if defined(USE_OPENSSL) +#include +#elif defined(USE_WOLFSSL) +#include +#endif + +#elif defined(USE_GNUTLS) +#include +#elif defined(USE_MBEDTLS) +#include +#elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ + (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040)) || \ + (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ + (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000)) +#include +#define AN_APPLE_OS +#elif defined(USE_WIN32_CRYPTO) +#include +#endif + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* Please keep the SSL backend-specific #if branches in this order: + * + * 1. USE_OPENSSL + * 2. USE_GNUTLS + * 3. USE_MBEDTLS + * 4. USE_COMMON_CRYPTO + * 5. USE_WIN32_CRYPTO + * + * This ensures that the same SSL branch gets activated throughout this source + * file even if multiple backends are enabled at the same time. + */ + +#if defined(USE_OPENSSL_SHA256) + +struct ossl_sha256_ctx { + EVP_MD_CTX *openssl_ctx; +}; +typedef struct ossl_sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + ctx->openssl_ctx = EVP_MD_CTX_create(); + if(!ctx->openssl_ctx) + return CURLE_OUT_OF_MEMORY; + + if(!EVP_DigestInit_ex(ctx->openssl_ctx, EVP_sha256(), NULL)) { + EVP_MD_CTX_destroy(ctx->openssl_ctx); + return CURLE_FAILED_INIT; + } + return CURLE_OK; +} + +static void my_sha256_update(void *in, + const unsigned char *data, + unsigned int length) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + EVP_DigestUpdate(ctx->openssl_ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + EVP_DigestFinal_ex(ctx->openssl_ctx, digest, NULL); + EVP_MD_CTX_destroy(ctx->openssl_ctx); +} + +#elif defined(USE_GNUTLS) + +typedef struct sha256_ctx my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ + sha256_init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ + sha256_update(ctx, length, data); +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ + sha256_digest(ctx, SHA256_DIGEST_SIZE, digest); +} + +#elif defined(USE_MBEDTLS) + +typedef mbedtls_sha256_context my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_starts(ctx, 0); +#else + (void) mbedtls_sha256_starts_ret(ctx, 0); +#endif + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_update(ctx, data, length); +#else + (void) mbedtls_sha256_update_ret(ctx, data, length); +#endif +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ +#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) + (void) mbedtls_sha256_finish(ctx, digest); +#else + (void) mbedtls_sha256_finish_ret(ctx, digest); +#endif +} + +#elif defined(AN_APPLE_OS) +typedef CC_SHA256_CTX my_sha256_ctx; + +static CURLcode my_sha256_init(void *ctx) +{ + (void) CC_SHA256_Init(ctx); + return CURLE_OK; +} + +static void my_sha256_update(void *ctx, + const unsigned char *data, + unsigned int length) +{ + (void) CC_SHA256_Update(ctx, data, length); +} + +static void my_sha256_final(unsigned char *digest, void *ctx) +{ + (void) CC_SHA256_Final(digest, ctx); +} + +#elif defined(USE_WIN32_CRYPTO) + +struct sha256_ctx { + HCRYPTPROV hCryptProv; + HCRYPTHASH hHash; +}; +typedef struct sha256_ctx my_sha256_ctx; + +#if !defined(CALG_SHA_256) +#define CALG_SHA_256 0x0000800c +#endif + +static CURLcode my_sha256_init(void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + if(!CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_AES, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) + return CURLE_OUT_OF_MEMORY; + + if(!CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash)) { + CryptReleaseContext(ctx->hCryptProv, 0); + ctx->hCryptProv = 0; + return CURLE_FAILED_INIT; + } + + return CURLE_OK; +} + +static void my_sha256_update(void *in, + const unsigned char *data, + unsigned int length) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + CryptHashData(ctx->hHash, (unsigned char *) data, length, 0); +} + +static void my_sha256_final(unsigned char *digest, void *in) +{ + my_sha256_ctx *ctx = (my_sha256_ctx *)in; + unsigned long length = 0; + + CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); + if(length == CURL_SHA256_DIGEST_LENGTH) + CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); + + if(ctx->hHash) + CryptDestroyHash(ctx->hHash); + + if(ctx->hCryptProv) + CryptReleaseContext(ctx->hCryptProv, 0); +} + +#else + +/* When no other crypto library is available we use this code segment */ + +/* This is based on SHA256 implementation in LibTomCrypt that was released into + * public domain by Tom St Denis. */ + +#define WPA_GET_BE32(a) ((((unsigned long)(a)[0]) << 24) | \ + (((unsigned long)(a)[1]) << 16) | \ + (((unsigned long)(a)[2]) << 8) | \ + ((unsigned long)(a)[3])) +#define WPA_PUT_BE32(a, val) \ +do { \ + (a)[0] = (unsigned char)((((unsigned long) (val)) >> 24) & 0xff); \ + (a)[1] = (unsigned char)((((unsigned long) (val)) >> 16) & 0xff); \ + (a)[2] = (unsigned char)((((unsigned long) (val)) >> 8) & 0xff); \ + (a)[3] = (unsigned char)(((unsigned long) (val)) & 0xff); \ +} while(0) + +#ifdef HAVE_LONGLONG +#define WPA_PUT_BE64(a, val) \ +do { \ + (a)[0] = (unsigned char)(((unsigned long long)(val)) >> 56); \ + (a)[1] = (unsigned char)(((unsigned long long)(val)) >> 48); \ + (a)[2] = (unsigned char)(((unsigned long long)(val)) >> 40); \ + (a)[3] = (unsigned char)(((unsigned long long)(val)) >> 32); \ + (a)[4] = (unsigned char)(((unsigned long long)(val)) >> 24); \ + (a)[5] = (unsigned char)(((unsigned long long)(val)) >> 16); \ + (a)[6] = (unsigned char)(((unsigned long long)(val)) >> 8); \ + (a)[7] = (unsigned char)(((unsigned long long)(val)) & 0xff); \ +} while(0) +#else +#define WPA_PUT_BE64(a, val) \ +do { \ + (a)[0] = (unsigned char)(((unsigned __int64)(val)) >> 56); \ + (a)[1] = (unsigned char)(((unsigned __int64)(val)) >> 48); \ + (a)[2] = (unsigned char)(((unsigned __int64)(val)) >> 40); \ + (a)[3] = (unsigned char)(((unsigned __int64)(val)) >> 32); \ + (a)[4] = (unsigned char)(((unsigned __int64)(val)) >> 24); \ + (a)[5] = (unsigned char)(((unsigned __int64)(val)) >> 16); \ + (a)[6] = (unsigned char)(((unsigned __int64)(val)) >> 8); \ + (a)[7] = (unsigned char)(((unsigned __int64)(val)) & 0xff); \ +} while(0) +#endif + +struct sha256_state { +#ifdef HAVE_LONGLONG + unsigned long long length; +#else + unsigned __int64 length; +#endif + unsigned long state[8], curlen; + unsigned char buf[64]; +}; +typedef struct sha256_state my_sha256_ctx; + +/* The K array */ +static const unsigned long K[64] = { + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, + 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, + 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, + 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, + 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, + 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, + 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, + 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, + 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, + 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL +}; + +/* Various logical functions */ +#define RORc(x, y) \ +(((((unsigned long)(x) & 0xFFFFFFFFUL) >> (unsigned long)((y) & 31)) | \ + ((unsigned long)(x) << (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL) +#define Sha256_Ch(x,y,z) (z ^ (x & (y ^ z))) +#define Sha256_Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Sha256_S(x, n) RORc((x), (n)) +#define Sha256_R(x, n) (((x)&0xFFFFFFFFUL)>>(n)) +#define Sigma0(x) (Sha256_S(x, 2) ^ Sha256_S(x, 13) ^ Sha256_S(x, 22)) +#define Sigma1(x) (Sha256_S(x, 6) ^ Sha256_S(x, 11) ^ Sha256_S(x, 25)) +#define Gamma0(x) (Sha256_S(x, 7) ^ Sha256_S(x, 18) ^ Sha256_R(x, 3)) +#define Gamma1(x) (Sha256_S(x, 17) ^ Sha256_S(x, 19) ^ Sha256_R(x, 10)) + +/* Compress 512-bits */ +static int sha256_compress(struct sha256_state *md, + unsigned char *buf) +{ + unsigned long S[8], W[64]; + int i; + + /* Copy state into S */ + for(i = 0; i < 8; i++) { + S[i] = md->state[i]; + } + /* copy the state into 512-bits into W[0..15] */ + for(i = 0; i < 16; i++) + W[i] = WPA_GET_BE32(buf + (4 * i)); + /* fill W[16..63] */ + for(i = 16; i < 64; i++) { + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + + W[i - 16]; + } + + /* Compress */ +#define RND(a,b,c,d,e,f,g,h,i) \ + do { \ + unsigned long t0 = h + Sigma1(e) + Sha256_Ch(e, f, g) + K[i] + W[i]; \ + unsigned long t1 = Sigma0(a) + Sha256_Maj(a, b, c); \ + d += t0; \ + h = t0 + t1; \ + } while(0) + + for(i = 0; i < 64; ++i) { + unsigned long t; + RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i); + t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; + S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t; + } + + /* Feedback */ + for(i = 0; i < 8; i++) { + md->state[i] = md->state[i] + S[i]; + } + + return 0; +} + +/* Initialize the hash state */ +static CURLcode my_sha256_init(void *in) +{ + struct sha256_state *md = (struct sha256_state *)in; + md->curlen = 0; + md->length = 0; + md->state[0] = 0x6A09E667UL; + md->state[1] = 0xBB67AE85UL; + md->state[2] = 0x3C6EF372UL; + md->state[3] = 0xA54FF53AUL; + md->state[4] = 0x510E527FUL; + md->state[5] = 0x9B05688CUL; + md->state[6] = 0x1F83D9ABUL; + md->state[7] = 0x5BE0CD19UL; + + return CURLE_OK; +} + +/* + Process a block of memory though the hash + @param md The hash state + @param in The data to hash + @param inlen The length of the data (octets) +*/ +static void my_sha256_update(void *ctx, + const unsigned char *in, + unsigned int len) +{ + unsigned long inlen = len; + unsigned long n; + struct sha256_state *md = (struct sha256_state *)ctx; +#define CURL_SHA256_BLOCK_SIZE 64 + if(md->curlen > sizeof(md->buf)) + return; + while(inlen > 0) { + if(md->curlen == 0 && inlen >= CURL_SHA256_BLOCK_SIZE) { + if(sha256_compress(md, (unsigned char *)in) < 0) + return; + md->length += CURL_SHA256_BLOCK_SIZE * 8; + in += CURL_SHA256_BLOCK_SIZE; + inlen -= CURL_SHA256_BLOCK_SIZE; + } + else { + n = CURLMIN(inlen, (CURL_SHA256_BLOCK_SIZE - md->curlen)); + memcpy(md->buf + md->curlen, in, n); + md->curlen += n; + in += n; + inlen -= n; + if(md->curlen == CURL_SHA256_BLOCK_SIZE) { + if(sha256_compress(md, md->buf) < 0) + return; + md->length += 8 * CURL_SHA256_BLOCK_SIZE; + md->curlen = 0; + } + } + } +} + +/* + Terminate the hash to get the digest + @param md The hash state + @param out [out] The destination of the hash (32 bytes) + @return 0 if successful +*/ +static void my_sha256_final(unsigned char *out, void *ctx) +{ + struct sha256_state *md = ctx; + int i; + + if(md->curlen >= sizeof(md->buf)) + return; + + /* Increase the length of the message */ + md->length += md->curlen * 8; + + /* Append the '1' bit */ + md->buf[md->curlen++] = (unsigned char)0x80; + + /* If the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if(md->curlen > 56) { + while(md->curlen < 64) { + md->buf[md->curlen++] = (unsigned char)0; + } + sha256_compress(md, md->buf); + md->curlen = 0; + } + + /* Pad up to 56 bytes of zeroes */ + while(md->curlen < 56) { + md->buf[md->curlen++] = (unsigned char)0; + } + + /* Store length */ + WPA_PUT_BE64(md->buf + 56, md->length); + sha256_compress(md, md->buf); + + /* Copy output */ + for(i = 0; i < 8; i++) + WPA_PUT_BE32(out + (4 * i), md->state[i]); +} + +#endif /* CRYPTO LIBS */ + +/* + * Curl_sha256it() + * + * Generates a SHA256 hash for the given input data. + * + * Parameters: + * + * output [in/out] - The output buffer. + * input [in] - The input data. + * length [in] - The input length. + * + * Returns CURLE_OK on success. + */ +CURLcode Curl_sha256it(unsigned char *output, const unsigned char *input, + const size_t length) +{ + CURLcode result; + my_sha256_ctx ctx; + + result = my_sha256_init(&ctx); + if(!result) { + my_sha256_update(&ctx, input, curlx_uztoui(length)); + my_sha256_final(output, &ctx); + } + return result; +} + + +const struct HMAC_params Curl_HMAC_SHA256 = { + my_sha256_init, /* Hash initialization function. */ + my_sha256_update, /* Hash update function. */ + my_sha256_final, /* Hash computation end function. */ + sizeof(my_sha256_ctx), /* Size of hash context structure. */ + 64, /* Maximum key length. */ + 32 /* Result size. */ +}; + + +#endif /* AWS, DIGEST, or libssh2 */ diff --git a/local-test-curl-full-01/afc-curl/lib/slist.h b/local-test-curl-full-01/afc-curl/lib/slist.h new file mode 100644 index 0000000000000000000000000000000000000000..9561fd022686024191b4e61a418353120c14a635 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/slist.h @@ -0,0 +1,41 @@ +#ifndef HEADER_CURL_SLIST_H +#define HEADER_CURL_SLIST_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +/* + * Curl_slist_duplicate() duplicates a linked list. It always returns the + * address of the first record of the cloned list or NULL in case of an + * error (or if the input list was NULL). + */ +struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); + +/* + * Curl_slist_append_nodup() takes ownership of the given string and appends + * it to the list. + */ +struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, + char *data); + +#endif /* HEADER_CURL_SLIST_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/smb.h b/local-test-curl-full-01/afc-curl/lib/smb.h new file mode 100644 index 0000000000000000000000000000000000000000..9ea2a8cc31c8bc47137a9744adf4aa75761c8875 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/smb.h @@ -0,0 +1,61 @@ +#ifndef HEADER_CURL_SMB_H +#define HEADER_CURL_SMB_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Bill Nagel , Exacq Technologies + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +enum smb_conn_state { + SMB_NOT_CONNECTED = 0, + SMB_CONNECTING, + SMB_NEGOTIATE, + SMB_SETUP, + SMB_CONNECTED +}; + +struct smb_conn { + enum smb_conn_state state; + char *user; + char *domain; + char *share; + unsigned char challenge[8]; + unsigned int session_key; + unsigned short uid; + char *recv_buf; + char *send_buf; + size_t upload_size; + size_t send_size; + size_t sent; + size_t got; +}; + +#if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \ + (SIZEOF_CURL_OFF_T > 4) + +extern const struct Curl_handler Curl_handler_smb; +extern const struct Curl_handler Curl_handler_smbs; + +#endif /* CURL_DISABLE_SMB && USE_CURL_NTLM_CORE && + SIZEOF_CURL_OFF_T > 4 */ + +#endif /* HEADER_CURL_SMB_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/smtp.h b/local-test-curl-full-01/afc-curl/lib/smtp.h new file mode 100644 index 0000000000000000000000000000000000000000..7c2af6807390f5dc2a53dc3759dfa804f2278851 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/smtp.h @@ -0,0 +1,87 @@ +#ifndef HEADER_CURL_SMTP_H +#define HEADER_CURL_SMTP_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "pingpong.h" +#include "curl_sasl.h" + +/**************************************************************************** + * SMTP unique setup + ***************************************************************************/ +typedef enum { + SMTP_STOP, /* do nothing state, stops the state machine */ + SMTP_SERVERGREET, /* waiting for the initial greeting immediately after + a connect */ + SMTP_EHLO, + SMTP_HELO, + SMTP_STARTTLS, + SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS + (multi mode only) */ + SMTP_AUTH, + SMTP_COMMAND, /* VRFY, EXPN, NOOP, RSET and HELP */ + SMTP_MAIL, /* MAIL FROM */ + SMTP_RCPT, /* RCPT TO */ + SMTP_DATA, + SMTP_POSTDATA, + SMTP_QUIT, + SMTP_LAST /* never used */ +} smtpstate; + +/* This SMTP struct is used in the Curl_easy. All SMTP data that is + connection-oriented must be in smtp_conn to properly deal with the fact that + perhaps the Curl_easy is changed between the times the connection is + used. */ +struct SMTP { + curl_pp_transfer transfer; + char *custom; /* Custom Request */ + struct curl_slist *rcpt; /* Recipient list */ + int rcpt_last_error; /* The last error received for RCPT TO command */ + size_t eob; /* Number of bytes of the EOB (End Of Body) that + have been received so far */ + BIT(rcpt_had_ok); /* Whether any of RCPT TO commands (depends on + total number of recipients) succeeded so far */ + BIT(trailing_crlf); /* Specifies if the trailing CRLF is present */ +}; + +/* smtp_conn is used for struct connection-oriented data in the connectdata + struct */ +struct smtp_conn { + struct pingpong pp; + struct SASL sasl; /* SASL-related storage */ + smtpstate state; /* Always use smtp.c:state() to change state! */ + char *domain; /* Client address/name to send in the EHLO */ + BIT(ssldone); /* Is connect() over SSL done? */ + BIT(tls_supported); /* StartTLS capability supported by server */ + BIT(size_supported); /* If server supports SIZE extension according to + RFC 1870 */ + BIT(utf8_supported); /* If server supports SMTPUTF8 extension according + to RFC 6531 */ + BIT(auth_supported); /* AUTH capability supported by server */ +}; + +extern const struct Curl_handler Curl_handler_smtp; +extern const struct Curl_handler Curl_handler_smtps; + +#endif /* HEADER_CURL_SMTP_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/splay.h b/local-test-curl-full-01/afc-curl/lib/splay.h new file mode 100644 index 0000000000000000000000000000000000000000..b8c9360e5734367514989e4397284a5282183eeb --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/splay.h @@ -0,0 +1,58 @@ +#ifndef HEADER_CURL_SPLAY_H +#define HEADER_CURL_SPLAY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include "timeval.h" + +/* only use function calls to access this struct */ +struct Curl_tree { + struct Curl_tree *smaller; /* smaller node */ + struct Curl_tree *larger; /* larger node */ + struct Curl_tree *samen; /* points to the next node with identical key */ + struct Curl_tree *samep; /* points to the prev node with identical key */ + struct curltime key; /* this node's "sort" key */ + void *ptr; /* data the splay code does not care about */ +}; + +struct Curl_tree *Curl_splay(struct curltime i, + struct Curl_tree *t); + +struct Curl_tree *Curl_splayinsert(struct curltime key, + struct Curl_tree *t, + struct Curl_tree *newnode); + +struct Curl_tree *Curl_splaygetbest(struct curltime key, + struct Curl_tree *t, + struct Curl_tree **removed); + +int Curl_splayremove(struct Curl_tree *t, + struct Curl_tree *removenode, + struct Curl_tree **newroot); + +/* set and get the custom payload for this tree node */ +void Curl_splayset(struct Curl_tree *node, void *payload); +void *Curl_splayget(struct Curl_tree *node); + +#endif /* HEADER_CURL_SPLAY_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/strcase.c b/local-test-curl-full-01/afc-curl/lib/strcase.c new file mode 100644 index 0000000000000000000000000000000000000000..b22dd31fc862296af4919115edac0194d075c440 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/strcase.c @@ -0,0 +1,204 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include + +#include "strcase.h" + +/* Mapping table to go from lowercase to uppercase for plain ASCII.*/ +static const unsigned char touppermap[256] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, +22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, +41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, +60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, +79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, +66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, +85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, +134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, +150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, +166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, +182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, +198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, +214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, +230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, +246, 247, 248, 249, 250, 251, 252, 253, 254, 255 +}; + +/* Mapping table to go from uppercase to lowercase for plain ASCII.*/ +static const unsigned char tolowermap[256] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, +22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, +42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, +62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, +111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, +96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, +112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, +128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, +144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, +160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, +176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, +192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, +208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, +224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, +240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 +}; + + +/* Portable, consistent toupper. Do not use toupper() because its behavior is + altered by the current locale. */ +char Curl_raw_toupper(char in) +{ + return (char)touppermap[(unsigned char) in]; +} + + +/* Portable, consistent tolower. Do not use tolower() because its behavior is + altered by the current locale. */ +char Curl_raw_tolower(char in) +{ + return (char)tolowermap[(unsigned char) in]; +} + +/* + * curl_strequal() is for doing "raw" case insensitive strings. This is meant + * to be locale independent and only compare strings we know are safe for + * this. See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for + * further explanations as to why this function is necessary. + */ + +static int casecompare(const char *first, const char *second) +{ + while(*first && *second) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + /* get out of the loop as soon as they do not match */ + return 0; + first++; + second++; + } + /* If we are here either the strings are the same or the length is different. + We can just test if the "current" character is non-zero for one and zero + for the other. Note that the characters may not be exactly the same even + if they match, we only want to compare zero-ness. */ + return !*first == !*second; +} + +/* --- public function --- */ +int curl_strequal(const char *first, const char *second) +{ + if(first && second) + /* both pointers point to something then compare them */ + return casecompare(first, second); + + /* if both pointers are NULL then treat them as equal */ + return (NULL == first && NULL == second); +} + +static int ncasecompare(const char *first, const char *second, size_t max) +{ + while(*first && *second && max) { + if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) + return 0; + max--; + first++; + second++; + } + if(0 == max) + return 1; /* they are equal this far */ + + return Curl_raw_toupper(*first) == Curl_raw_toupper(*second); +} + +/* --- public function --- */ +int curl_strnequal(const char *first, const char *second, size_t max) +{ + if(first && second) + /* both pointers point to something then compare them */ + return ncasecompare(first, second, max); + + /* if both pointers are NULL then treat them as equal if max is non-zero */ + return (NULL == first && NULL == second && max); +} +/* Copy an upper case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * NUL-terminated if that limit is reached. + */ +void Curl_strntoupper(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_toupper(*src); + } while(*src++ && --n); +} + +/* Copy a lower case version of the string from src to dest. The + * strings may overlap. No more than n characters of the string are copied + * (including any NUL) and the destination string will NOT be + * NUL-terminated if that limit is reached. + */ +void Curl_strntolower(char *dest, const char *src, size_t n) +{ + if(n < 1) + return; + + do { + *dest++ = Curl_raw_tolower(*src); + } while(*src++ && --n); +} + +/* Compare case-sensitive NUL-terminated strings, taking care of possible + * null pointers. Return true if arguments match. + */ +bool Curl_safecmp(char *a, char *b) +{ + if(a && b) + return !strcmp(a, b); + return !a && !b; +} + +/* + * Curl_timestrcmp() returns 0 if the two strings are identical. The time this + * function spends is a function of the shortest string, not of the contents. + */ +int Curl_timestrcmp(const char *a, const char *b) +{ + int match = 0; + int i = 0; + + if(a && b) { + while(1) { + match |= a[i]^b[i]; + if(!a[i] || !b[i]) + break; + i++; + } + } + else + return a || b; + return match; +} diff --git a/local-test-curl-full-01/afc-curl/lib/strerror.h b/local-test-curl-full-01/afc-curl/lib/strerror.h new file mode 100644 index 0000000000000000000000000000000000000000..6806867345315e4b19b8db6d065a24b0661f3dff --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/strerror.h @@ -0,0 +1,39 @@ +#ifndef HEADER_CURL_STRERROR_H +#define HEADER_CURL_STRERROR_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "urldata.h" + +#define STRERROR_LEN 256 /* a suitable length */ + +const char *Curl_strerror(int err, char *buf, size_t buflen); +#if defined(_WIN32) || defined(_WIN32_WCE) +const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen); +#endif +#ifdef USE_WINDOWS_SSPI +const char *Curl_sspi_strerror(int err, char *buf, size_t buflen); +#endif + +#endif /* HEADER_CURL_STRERROR_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/strtok.c b/local-test-curl-full-01/afc-curl/lib/strtok.c new file mode 100644 index 0000000000000000000000000000000000000000..d2cc71c47dc546fa4a403703ff66c7c12d82f8cb --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/strtok.c @@ -0,0 +1,68 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef HAVE_STRTOK_R +#include + +#include "strtok.h" + +char * +Curl_strtok_r(char *ptr, const char *sep, char **end) +{ + if(!ptr) + /* we got NULL input so then we get our last position instead */ + ptr = *end; + + /* pass all letters that are including in the separator string */ + while(*ptr && strchr(sep, *ptr)) + ++ptr; + + if(*ptr) { + /* so this is where the next piece of string starts */ + char *start = ptr; + + /* set the end pointer to the first byte after the start */ + *end = start + 1; + + /* scan through the string to find where it ends, it ends on a + null byte or a character that exists in the separator string */ + while(**end && !strchr(sep, **end)) + ++*end; + + if(**end) { + /* the end is not a null byte */ + **end = '\0'; /* null-terminate it! */ + ++*end; /* advance the last pointer to beyond the null byte */ + } + + return start; /* return the position where the string starts */ + } + + /* we ended up on a null byte, there are no more strings to find! */ + return NULL; +} + +#endif /* this was only compiled if strtok_r was not present */ diff --git a/local-test-curl-full-01/afc-curl/lib/strtoofft.c b/local-test-curl-full-01/afc-curl/lib/strtoofft.c new file mode 100644 index 0000000000000000000000000000000000000000..f1c7ba2711046807b808e40e4eb6e877ff1fb3e6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/strtoofft.c @@ -0,0 +1,240 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include +#include "curl_setup.h" + +#include "strtoofft.h" + +/* + * NOTE: + * + * In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we + * could use in case strtoll() does not exist... See + * https://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html + */ + +#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG) +# ifdef HAVE_STRTOLL +# define strtooff strtoll +# else +# if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_INTEGRAL_MAX_BITS >= 64) +# if defined(_SAL_VERSION) + _Check_return_ _CRTIMP __int64 __cdecl _strtoi64( + _In_z_ const char *_String, + _Out_opt_ _Deref_post_z_ char **_EndPtr, _In_ int _Radix); +# else + _CRTIMP __int64 __cdecl _strtoi64(const char *_String, + char **_EndPtr, int _Radix); +# endif +# define strtooff _strtoi64 +# else +# define PRIVATE_STRTOOFF 1 +# endif +# endif +#else +# define strtooff strtol +#endif + +#ifdef PRIVATE_STRTOOFF + +/* Range tests can be used for alphanum decoding if characters are consecutive, + like in ASCII. Else an array is scanned. Determine this condition now. */ + +#if('9' - '0') != 9 || ('Z' - 'A') != 25 || ('z' - 'a') != 25 + +#define NO_RANGE_TEST + +static const char valchars[] = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +#endif + +static int get_char(char c, int base); + +/** + * Custom version of the strtooff function. This extracts a curl_off_t + * value from the given input string and returns it. + */ +static curl_off_t strtooff(const char *nptr, char **endptr, int base) +{ + char *end; + bool is_negative = FALSE; + bool overflow = FALSE; + int i; + curl_off_t value = 0; + + /* Skip leading whitespace. */ + end = (char *)nptr; + while(ISBLANK(end[0])) { + end++; + } + + /* Handle the sign, if any. */ + if(end[0] == '-') { + is_negative = TRUE; + end++; + } + else if(end[0] == '+') { + end++; + } + else if(end[0] == '\0') { + /* We had nothing but perhaps some whitespace -- there was no number. */ + if(endptr) { + *endptr = end; + } + return 0; + } + + /* Handle special beginnings, if present and allowed. */ + if(end[0] == '0' && end[1] == 'x') { + if(base == 16 || base == 0) { + end += 2; + base = 16; + } + } + else if(end[0] == '0') { + if(base == 8 || base == 0) { + end++; + base = 8; + } + } + + /* Matching strtol, if the base is 0 and it does not look like + * the number is octal or hex, we assume it is base 10. + */ + if(base == 0) { + base = 10; + } + + /* Loop handling digits. */ + for(i = get_char(end[0], base); + i != -1; + end++, i = get_char(end[0], base)) { + + if(value > (CURL_OFF_T_MAX - i) / base) { + overflow = TRUE; + break; + } + value = base * value + i; + } + + if(!overflow) { + if(is_negative) { + /* Fix the sign. */ + value *= -1; + } + } + else { + if(is_negative) + value = CURL_OFF_T_MIN; + else + value = CURL_OFF_T_MAX; + + errno = ERANGE; + } + + if(endptr) + *endptr = end; + + return value; +} + +/** + * Returns the value of c in the given base, or -1 if c cannot + * be interpreted properly in that base (i.e., is out of range, + * is a null, etc.). + * + * @param c the character to interpret according to base + * @param base the base in which to interpret c + * + * @return the value of c in base, or -1 if c is not in range + */ +static int get_char(char c, int base) +{ +#ifndef NO_RANGE_TEST + int value = -1; + if(c <= '9' && c >= '0') { + value = c - '0'; + } + else if(c <= 'Z' && c >= 'A') { + value = c - 'A' + 10; + } + else if(c <= 'z' && c >= 'a') { + value = c - 'a' + 10; + } +#else + const char *cp; + int value; + + cp = memchr(valchars, c, 10 + 26 + 26); + + if(!cp) + return -1; + + value = cp - valchars; + + if(value >= 10 + 26) + value -= 26; /* Lowercase. */ +#endif + + if(value >= base) { + value = -1; + } + + return value; +} +#endif /* Only present if we need strtoll, but do not have it. */ + +/* + * Parse a *positive* up to 64-bit number written in ASCII. + */ +CURLofft curlx_strtoofft(const char *str, char **endp, int base, + curl_off_t *num) +{ + char *end = NULL; + curl_off_t number; + errno = 0; + *num = 0; /* clear by default */ + DEBUGASSERT(base); /* starting now, avoid base zero */ + + while(*str && ISBLANK(*str)) + str++; + if(('-' == *str) || (ISSPACE(*str))) { + if(endp) + *endp = (char *)str; /* did not actually move */ + return CURL_OFFT_INVAL; /* nothing parsed */ + } + number = strtooff(str, &end, base); + if(endp) + *endp = end; + if(errno == ERANGE) + /* overflow/underflow */ + return CURL_OFFT_FLOW; + else if(str == end) + /* nothing parsed */ + return CURL_OFFT_INVAL; + + *num = number; + return CURL_OFFT_OK; +} diff --git a/local-test-curl-full-01/afc-curl/lib/system_win32.h b/local-test-curl-full-01/afc-curl/lib/system_win32.h new file mode 100644 index 0000000000000000000000000000000000000000..024d959f327542976862be1284bc4a30477f97c2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/system_win32.h @@ -0,0 +1,51 @@ +#ifndef HEADER_CURL_SYSTEM_WIN32_H +#define HEADER_CURL_SYSTEM_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Steve Holme, . + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#if defined(_WIN32) + +#include + +extern LARGE_INTEGER Curl_freq; +extern bool Curl_isVistaOrGreater; + +CURLcode Curl_win32_init(long flags); +void Curl_win32_cleanup(long init_flags); + +/* We use our own typedef here since some headers might lack this */ +typedef unsigned int(WINAPI *IF_NAMETOINDEX_FN)(const char *); + +/* This is used instead of if_nametoindex if available on Windows */ +extern IF_NAMETOINDEX_FN Curl_if_nametoindex; + +/* This is used to dynamically load DLLs */ +HMODULE Curl_load_library(LPCTSTR filename); +#else /* _WIN32 */ +#define Curl_win32_init(x) CURLE_OK +#endif /* !_WIN32 */ + +#endif /* HEADER_CURL_SYSTEM_WIN32_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/tftp.c b/local-test-curl-full-01/afc-curl/lib/tftp.c new file mode 100644 index 0000000000000000000000000000000000000000..e92e5127a56bde76934bb2a2d676511c401b594a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/tftp.c @@ -0,0 +1,1400 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_TFTP + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETDB_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif +#ifdef HAVE_NET_IF_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_SYS_PARAM_H +#include +#endif + +#include "urldata.h" +#include +#include "cf-socket.h" +#include "transfer.h" +#include "sendf.h" +#include "tftp.h" +#include "progress.h" +#include "connect.h" +#include "strerror.h" +#include "sockaddr.h" /* required for Curl_sockaddr_storage */ +#include "multiif.h" +#include "url.h" +#include "strcase.h" +#include "speedcheck.h" +#include "select.h" +#include "escape.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + +/* RFC2348 allows the block size to be negotiated */ +#define TFTP_BLKSIZE_DEFAULT 512 +#define TFTP_OPTION_BLKSIZE "blksize" + +/* from RFC2349: */ +#define TFTP_OPTION_TSIZE "tsize" +#define TFTP_OPTION_INTERVAL "timeout" + +typedef enum { + TFTP_MODE_NETASCII = 0, + TFTP_MODE_OCTET +} tftp_mode_t; + +typedef enum { + TFTP_STATE_START = 0, + TFTP_STATE_RX, + TFTP_STATE_TX, + TFTP_STATE_FIN +} tftp_state_t; + +typedef enum { + TFTP_EVENT_NONE = -1, + TFTP_EVENT_INIT = 0, + TFTP_EVENT_RRQ = 1, + TFTP_EVENT_WRQ = 2, + TFTP_EVENT_DATA = 3, + TFTP_EVENT_ACK = 4, + TFTP_EVENT_ERROR = 5, + TFTP_EVENT_OACK = 6, + TFTP_EVENT_TIMEOUT +} tftp_event_t; + +typedef enum { + TFTP_ERR_UNDEF = 0, + TFTP_ERR_NOTFOUND, + TFTP_ERR_PERM, + TFTP_ERR_DISKFULL, + TFTP_ERR_ILLEGAL, + TFTP_ERR_UNKNOWNID, + TFTP_ERR_EXISTS, + TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */ + + /* The remaining error codes are internal to curl */ + TFTP_ERR_NONE = -100, + TFTP_ERR_TIMEOUT, + TFTP_ERR_NORESPONSE +} tftp_error_t; + +struct tftp_packet { + unsigned char *data; +}; + +struct tftp_state_data { + tftp_state_t state; + tftp_mode_t mode; + tftp_error_t error; + tftp_event_t event; + struct Curl_easy *data; + curl_socket_t sockfd; + int retries; + int retry_time; + int retry_max; + time_t rx_time; + struct Curl_sockaddr_storage local_addr; + struct Curl_sockaddr_storage remote_addr; + curl_socklen_t remote_addrlen; + int rbytes; + int sbytes; + int blksize; + int requested_blksize; + unsigned short block; + struct tftp_packet rpacket; + struct tftp_packet spacket; +}; + + +/* Forward declarations */ +static CURLcode tftp_rx(struct tftp_state_data *state, tftp_event_t event); +static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event); +static CURLcode tftp_connect(struct Curl_easy *data, bool *done); +static CURLcode tftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection); +static CURLcode tftp_do(struct Curl_easy *data, bool *done); +static CURLcode tftp_done(struct Curl_easy *data, + CURLcode, bool premature); +static CURLcode tftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn); +static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done); +static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done); +static int tftp_getsock(struct Curl_easy *data, struct connectdata *conn, + curl_socket_t *socks); +static CURLcode tftp_translate_code(tftp_error_t error); + + +/* + * TFTP protocol handler. + */ + +const struct Curl_handler Curl_handler_tftp = { + "tftp", /* scheme */ + tftp_setup_connection, /* setup_connection */ + tftp_do, /* do_it */ + tftp_done, /* done */ + ZERO_NULL, /* do_more */ + tftp_connect, /* connect_it */ + tftp_multi_statemach, /* connecting */ + tftp_doing, /* doing */ + tftp_getsock, /* proto_getsock */ + tftp_getsock, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + tftp_disconnect, /* disconnect */ + ZERO_NULL, /* write_resp */ + ZERO_NULL, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_TFTP, /* defport */ + CURLPROTO_TFTP, /* protocol */ + CURLPROTO_TFTP, /* family */ + PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY /* flags */ +}; + +/********************************************************** + * + * tftp_set_timeouts - + * + * Set timeouts based on state machine state. + * Use user provided connect timeouts until DATA or ACK + * packet is received, then use user-provided transfer timeouts + * + * + **********************************************************/ +static CURLcode tftp_set_timeouts(struct tftp_state_data *state) +{ + time_t maxtime, timeout; + timediff_t timeout_ms; + bool start = (state->state == TFTP_STATE_START); + + /* Compute drop-dead time */ + timeout_ms = Curl_timeleft(state->data, NULL, start); + + if(timeout_ms < 0) { + /* time-out, bail out, go home */ + failf(state->data, "Connection time-out"); + return CURLE_OPERATION_TIMEDOUT; + } + + if(timeout_ms > 0) + maxtime = (time_t)(timeout_ms + 500) / 1000; + else + maxtime = 3600; /* use for calculating block timeouts */ + + /* Set per-block timeout to total */ + timeout = maxtime; + + /* Average reposting an ACK after 5 seconds */ + state->retry_max = (int)timeout/5; + + /* But bound the total number */ + if(state->retry_max < 3) + state->retry_max = 3; + + if(state->retry_max > 50) + state->retry_max = 50; + + /* Compute the re-ACK interval to suit the timeout */ + state->retry_time = (int)(timeout/state->retry_max); + if(state->retry_time < 1) + state->retry_time = 1; + + infof(state->data, + "set timeouts for state %d; Total % " FMT_OFF_T ", retry %d maxtry %d", + (int)state->state, timeout_ms, state->retry_time, state->retry_max); + + /* init RX time */ + state->rx_time = time(NULL); + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_set_send_first + * + * Event handler for the START state + * + **********************************************************/ + +static void setpacketevent(struct tftp_packet *packet, unsigned short num) +{ + packet->data[0] = (unsigned char)(num >> 8); + packet->data[1] = (unsigned char)(num & 0xff); +} + + +static void setpacketblock(struct tftp_packet *packet, unsigned short num) +{ + packet->data[2] = (unsigned char)(num >> 8); + packet->data[3] = (unsigned char)(num & 0xff); +} + +static unsigned short getrpacketevent(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[0] << 8) | packet->data[1]); +} + +static unsigned short getrpacketblock(const struct tftp_packet *packet) +{ + return (unsigned short)((packet->data[2] << 8) | packet->data[3]); +} + +static size_t tftp_strnlen(const char *string, size_t maxlen) +{ + const char *end = memchr(string, '\0', maxlen); + return end ? (size_t) (end - string) : maxlen; +} + +static const char *tftp_option_get(const char *buf, size_t len, + const char **option, const char **value) +{ + size_t loc; + + loc = tftp_strnlen(buf, len); + loc++; /* NULL term */ + + if(loc >= len) + return NULL; + *option = buf; + + loc += tftp_strnlen(buf + loc, len-loc); + loc++; /* NULL term */ + + if(loc > len) + return NULL; + *value = &buf[strlen(*option) + 1]; + + return &buf[loc]; +} + +static CURLcode tftp_parse_option_ack(struct tftp_state_data *state, + const char *ptr, int len) +{ + const char *tmp = ptr; + struct Curl_easy *data = state->data; + + /* if OACK does not contain blksize option, the default (512) must be used */ + state->blksize = TFTP_BLKSIZE_DEFAULT; + + while(tmp < ptr + len) { + const char *option, *value; + + tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value); + if(!tmp) { + failf(data, "Malformed ACK packet, rejecting"); + return CURLE_TFTP_ILLEGAL; + } + + infof(data, "got option=(%s) value=(%s)", option, value); + + if(checkprefix(TFTP_OPTION_BLKSIZE, option)) { + long blksize; + + blksize = strtol(value, NULL, 10); + + if(!blksize) { + failf(data, "invalid blocksize value in OACK packet"); + return CURLE_TFTP_ILLEGAL; + } + if(blksize > TFTP_BLKSIZE_MAX) { + failf(data, "%s (%d)", "blksize is larger than max supported", + TFTP_BLKSIZE_MAX); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize < TFTP_BLKSIZE_MIN) { + failf(data, "%s (%d)", "blksize is smaller than min supported", + TFTP_BLKSIZE_MIN); + return CURLE_TFTP_ILLEGAL; + } + else if(blksize > state->requested_blksize) { + /* could realloc pkt buffers here, but the spec does not call out + * support for the server requesting a bigger blksize than the client + * requests */ + failf(data, "%s (%ld)", + "server requested blksize larger than allocated", blksize); + return CURLE_TFTP_ILLEGAL; + } + + state->blksize = (int)blksize; + infof(data, "%s (%d) %s (%d)", "blksize parsed from OACK", + state->blksize, "requested", state->requested_blksize); + } + else if(checkprefix(TFTP_OPTION_TSIZE, option)) { + long tsize = 0; + + tsize = strtol(value, NULL, 10); + infof(data, "%s (%ld)", "tsize parsed from OACK", tsize); + + /* tsize should be ignored on upload: Who cares about the size of the + remote file? */ + if(!data->state.upload) { + if(!tsize) { + failf(data, "invalid tsize -:%s:- value in OACK packet", value); + return CURLE_TFTP_ILLEGAL; + } + Curl_pgrsSetDownloadSize(data, tsize); + } + } + } + + return CURLE_OK; +} + +static CURLcode tftp_option_add(struct tftp_state_data *state, size_t *csize, + char *buf, const char *option) +{ + if(( strlen(option) + *csize + 1) > (size_t)state->blksize) + return CURLE_TFTP_ILLEGAL; + strcpy(buf, option); + *csize += strlen(option) + 1; + return CURLE_OK; +} + +static CURLcode tftp_connect_for_tx(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + struct Curl_easy *data = state->data; + + infof(data, "%s", "Connected for transmit"); +#endif + state->state = TFTP_STATE_TX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_tx(state, event); +} + +static CURLcode tftp_connect_for_rx(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result; +#ifndef CURL_DISABLE_VERBOSE_STRINGS + struct Curl_easy *data = state->data; + + infof(data, "%s", "Connected for receive"); +#endif + state->state = TFTP_STATE_RX; + result = tftp_set_timeouts(state); + if(result) + return result; + return tftp_rx(state, event); +} + +static CURLcode tftp_send_first(struct tftp_state_data *state, + tftp_event_t event) +{ + size_t sbytes; + ssize_t senddata; + const char *mode = "octet"; + char *filename; + struct Curl_easy *data = state->data; + CURLcode result = CURLE_OK; + + /* Set ASCII mode if -B flag was used */ + if(data->state.prefer_ascii) + mode = "netascii"; + + switch(event) { + + case TFTP_EVENT_INIT: /* Send the first packet out */ + case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */ + /* Increment the retry counter, quit if over the limit */ + state->retries++; + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_NORESPONSE; + state->state = TFTP_STATE_FIN; + return result; + } + + if(data->state.upload) { + /* If we are uploading, send an WRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_WRQ); + if(data->state.infilesize != -1) + Curl_pgrsSetUploadSize(data, data->state.infilesize); + } + else { + /* If we are downloading, send an RRQ */ + setpacketevent(&state->spacket, TFTP_EVENT_RRQ); + } + /* As RFC3617 describes the separator slash is not actually part of the + filename so we skip the always-present first letter of the path + string. */ + result = Curl_urldecode(&state->data->state.up.path[1], 0, + &filename, NULL, REJECT_ZERO); + if(result) + return result; + + if(strlen(filename) > (state->blksize - strlen(mode) - 4)) { + failf(data, "TFTP filename too long"); + free(filename); + return CURLE_TFTP_ILLEGAL; /* too long filename field */ + } + + msnprintf((char *)state->spacket.data + 2, + state->blksize, + "%s%c%s%c", filename, '\0', mode, '\0'); + sbytes = 4 + strlen(filename) + strlen(mode); + + /* optional addition of TFTP options */ + if(!data->set.tftp_no_options) { + char buf[64]; + /* add tsize option */ + msnprintf(buf, sizeof(buf), "%" FMT_OFF_T, + data->state.upload && (data->state.infilesize != -1) ? + data->state.infilesize : 0); + + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_TSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + /* add blksize option */ + msnprintf(buf, sizeof(buf), "%d", state->requested_blksize); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_BLKSIZE); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + /* add timeout option */ + msnprintf(buf, sizeof(buf), "%d", state->retry_time); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, + TFTP_OPTION_INTERVAL); + if(result == CURLE_OK) + result = tftp_option_add(state, &sbytes, + (char *)state->spacket.data + sbytes, buf); + + if(result != CURLE_OK) { + failf(data, "TFTP buffer too small for options"); + free(filename); + return CURLE_TFTP_ILLEGAL; + } + } + + /* the typecase for the 3rd argument is mostly for systems that do + not have a size_t argument, like older unixes that want an 'int' */ + senddata = sendto(state->sockfd, (void *)state->spacket.data, + (SEND_TYPE_ARG3)sbytes, 0, + &data->conn->remote_addr->curl_sa_addr, + (curl_socklen_t)data->conn->remote_addr->addrlen); + if(senddata != (ssize_t)sbytes) { + char buffer[STRERROR_LEN]; + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + } + free(filename); + break; + + case TFTP_EVENT_OACK: + if(data->state.upload) { + result = tftp_connect_for_tx(state, event); + } + else { + result = tftp_connect_for_rx(state, event); + } + break; + + case TFTP_EVENT_ACK: /* Connected for transmit */ + result = tftp_connect_for_tx(state, event); + break; + + case TFTP_EVENT_DATA: /* Connected for receive */ + result = tftp_connect_for_rx(state, event); + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + break; + + default: + failf(state->data, "tftp_send_first: internal error"); + break; + } + + return result; +} + +/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit + boundary */ +#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff) + +/********************************************************** + * + * tftp_rx + * + * Event handler for the RX state + * + **********************************************************/ +static CURLcode tftp_rx(struct tftp_state_data *state, + tftp_event_t event) +{ + ssize_t sbytes; + int rblock; + struct Curl_easy *data = state->data; + char buffer[STRERROR_LEN]; + + switch(event) { + + case TFTP_EVENT_DATA: + /* Is this the block we expect? */ + rblock = getrpacketblock(&state->rpacket); + if(NEXT_BLOCKNUM(state->block) == rblock) { + /* This is the expected block. Reset counters and ACK it. */ + state->retries = 0; + } + else if(state->block == rblock) { + /* This is the last recently received block again. Log it and ACK it + again. */ + infof(data, "Received last DATA packet block %d again.", rblock); + } + else { + /* totally unexpected, just log it */ + infof(data, + "Received unexpected DATA packet block %d, expecting block %d", + rblock, NEXT_BLOCKNUM(state->block)); + break; + } + + /* ACK this block. */ + state->block = (unsigned short)rblock; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* Check if completed (That is, a less than full packet is received) */ + if(state->rbytes < (ssize_t)state->blksize + 4) { + state->state = TFTP_STATE_FIN; + } + else { + state->state = TFTP_STATE_RX; + } + state->rx_time = time(NULL); + break; + + case TFTP_EVENT_OACK: + /* ACK option acknowledgement so we can move on to data */ + state->block = 0; + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_ACK); + setpacketblock(&state->spacket, state->block); + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + + /* we are ready to RX data */ + state->state = TFTP_STATE_RX; + state->rx_time = time(NULL); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry count and fail if over the limit */ + state->retries++; + infof(data, + "Timeout waiting for block %d ACK. Retries = %d", + NEXT_BLOCKNUM(state->block), state->retries); + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Resend the previous ACK */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + } + break; + + case TFTP_EVENT_ERROR: + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, + 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* do not bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we are done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "%s", "tftp_rx: internal error"); + return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for + this */ + } + return CURLE_OK; +} + +/********************************************************** + * + * tftp_tx + * + * Event handler for the TX state + * + **********************************************************/ +static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event) +{ + struct Curl_easy *data = state->data; + ssize_t sbytes; + CURLcode result = CURLE_OK; + struct SingleRequest *k = &data->req; + size_t cb; /* Bytes currently read */ + char buffer[STRERROR_LEN]; + char *bufptr; + bool eos; + + switch(event) { + + case TFTP_EVENT_ACK: + case TFTP_EVENT_OACK: + if(event == TFTP_EVENT_ACK) { + /* Ack the packet */ + int rblock = getrpacketblock(&state->rpacket); + + if(rblock != state->block && + /* There is a bug in tftpd-hpa that causes it to send us an ack for + * 65535 when the block number wraps to 0. So when we are expecting + * 0, also accept 65535. See + * https://www.syslinux.org/archives/2010-September/015612.html + * */ + !(state->block == 0 && rblock == 65535)) { + /* This is not the expected block. Log it and up the retry counter */ + infof(data, "Received ACK for block %d, expecting %d", + rblock, state->block); + state->retries++; + /* Bail out if over the maximum */ + if(state->retries > state->retry_max) { + failf(data, "tftp_tx: giving up waiting for block %d ack", + state->block); + result = CURLE_SEND_ERROR; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, + buffer, sizeof(buffer))); + result = CURLE_SEND_ERROR; + } + } + + return result; + } + /* This is the expected packet. Reset the counters and send the next + block */ + state->rx_time = time(NULL); + state->block++; + } + else + state->block = 1; /* first data block is 1 when using OACK */ + + state->retries = 0; + setpacketevent(&state->spacket, TFTP_EVENT_DATA); + setpacketblock(&state->spacket, state->block); + if(state->block > 1 && state->sbytes < state->blksize) { + state->state = TFTP_STATE_FIN; + return CURLE_OK; + } + + /* TFTP considers data block size < 512 bytes as an end of session. So + * in some cases we must wait for additional data to build full (512 bytes) + * data block. + * */ + state->sbytes = 0; + bufptr = (char *)state->spacket.data + 4; + do { + result = Curl_client_read(data, bufptr, state->blksize - state->sbytes, + &cb, &eos); + if(result) + return result; + state->sbytes += (int)cb; + bufptr += cb; + } while(state->sbytes < state->blksize && cb); + + sbytes = sendto(state->sockfd, (void *) state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* Update the progress meter */ + k->writebytecount += state->sbytes; + Curl_pgrsSetUploadCounter(data, k->writebytecount); + break; + + case TFTP_EVENT_TIMEOUT: + /* Increment the retry counter and log the timeout */ + state->retries++; + infof(data, "Timeout waiting for block %d ACK. " + " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries); + /* Decide if we have had enough */ + if(state->retries > state->retry_max) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + } + else { + /* Re-send the data packet */ + sbytes = sendto(state->sockfd, (void *)state->spacket.data, + 4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* Check all sbytes were sent */ + if(sbytes < 0) { + failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_SEND_ERROR; + } + /* since this was a re-send, we remain at the still byte position */ + Curl_pgrsSetUploadCounter(data, k->writebytecount); + } + break; + + case TFTP_EVENT_ERROR: + state->state = TFTP_STATE_FIN; + setpacketevent(&state->spacket, TFTP_EVENT_ERROR); + setpacketblock(&state->spacket, state->block); + (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, + (struct sockaddr *)&state->remote_addr, + state->remote_addrlen); + /* do not bother with the return code, but if the socket is still up we + * should be a good TFTP client and let the server know we are done */ + state->state = TFTP_STATE_FIN; + break; + + default: + failf(data, "tftp_tx: internal error, event: %i", (int)(event)); + break; + } + + return result; +} + +/********************************************************** + * + * tftp_translate_code + * + * Translate internal error codes to CURL error codes + * + **********************************************************/ +static CURLcode tftp_translate_code(tftp_error_t error) +{ + CURLcode result = CURLE_OK; + + if(error != TFTP_ERR_NONE) { + switch(error) { + case TFTP_ERR_NOTFOUND: + result = CURLE_TFTP_NOTFOUND; + break; + case TFTP_ERR_PERM: + result = CURLE_TFTP_PERM; + break; + case TFTP_ERR_DISKFULL: + result = CURLE_REMOTE_DISK_FULL; + break; + case TFTP_ERR_UNDEF: + case TFTP_ERR_ILLEGAL: + result = CURLE_TFTP_ILLEGAL; + break; + case TFTP_ERR_UNKNOWNID: + result = CURLE_TFTP_UNKNOWNID; + break; + case TFTP_ERR_EXISTS: + result = CURLE_REMOTE_FILE_EXISTS; + break; + case TFTP_ERR_NOSUCHUSER: + result = CURLE_TFTP_NOSUCHUSER; + break; + case TFTP_ERR_TIMEOUT: + result = CURLE_OPERATION_TIMEDOUT; + break; + case TFTP_ERR_NORESPONSE: + result = CURLE_COULDNT_CONNECT; + break; + default: + result = CURLE_ABORTED_BY_CALLBACK; + break; + } + } + else + result = CURLE_OK; + + return result; +} + +/********************************************************** + * + * tftp_state_machine + * + * The tftp state machine event dispatcher + * + **********************************************************/ +static CURLcode tftp_state_machine(struct tftp_state_data *state, + tftp_event_t event) +{ + CURLcode result = CURLE_OK; + struct Curl_easy *data = state->data; + + switch(state->state) { + case TFTP_STATE_START: + DEBUGF(infof(data, "TFTP_STATE_START")); + result = tftp_send_first(state, event); + break; + case TFTP_STATE_RX: + DEBUGF(infof(data, "TFTP_STATE_RX")); + result = tftp_rx(state, event); + break; + case TFTP_STATE_TX: + DEBUGF(infof(data, "TFTP_STATE_TX")); + result = tftp_tx(state, event); + break; + case TFTP_STATE_FIN: + infof(data, "%s", "TFTP finished"); + break; + default: + DEBUGF(infof(data, "STATE: %d", state->state)); + failf(data, "%s", "Internal state machine error"); + result = CURLE_TFTP_ILLEGAL; + break; + } + + return result; +} + +/********************************************************** + * + * tftp_disconnect + * + * The disconnect callback + * + **********************************************************/ +static CURLcode tftp_disconnect(struct Curl_easy *data, + struct connectdata *conn, bool dead_connection) +{ + struct tftp_state_data *state = conn->proto.tftpc; + (void) data; + (void) dead_connection; + + /* done, free dynamically allocated pkt buffers */ + if(state) { + Curl_safefree(state->rpacket.data); + Curl_safefree(state->spacket.data); + free(state); + } + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_connect + * + * The connect callback + * + **********************************************************/ +static CURLcode tftp_connect(struct Curl_easy *data, bool *done) +{ + struct tftp_state_data *state; + int blksize; + int need_blksize; + struct connectdata *conn = data->conn; + + blksize = TFTP_BLKSIZE_DEFAULT; + + state = conn->proto.tftpc = calloc(1, sizeof(struct tftp_state_data)); + if(!state) + return CURLE_OUT_OF_MEMORY; + + /* alloc pkt buffers based on specified blksize */ + if(data->set.tftp_blksize) + /* range checked when set */ + blksize = (int)data->set.tftp_blksize; + + need_blksize = blksize; + /* default size is the fallback when no OACK is received */ + if(need_blksize < TFTP_BLKSIZE_DEFAULT) + need_blksize = TFTP_BLKSIZE_DEFAULT; + + if(!state->rpacket.data) { + state->rpacket.data = calloc(1, need_blksize + 2 + 2); + + if(!state->rpacket.data) + return CURLE_OUT_OF_MEMORY; + } + + if(!state->spacket.data) { + state->spacket.data = calloc(1, need_blksize + 2 + 2); + + if(!state->spacket.data) + return CURLE_OUT_OF_MEMORY; + } + + /* we do not keep TFTP connections up basically because there is none or + * little gain for UDP */ + connclose(conn, "TFTP"); + + state->data = data; + state->sockfd = conn->sock[FIRSTSOCKET]; + state->state = TFTP_STATE_START; + state->error = TFTP_ERR_NONE; + state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */ + state->requested_blksize = blksize; + + ((struct sockaddr *)&state->local_addr)->sa_family = + (CURL_SA_FAMILY_T)(conn->remote_addr->family); + + tftp_set_timeouts(state); + + if(!conn->bits.bound) { + /* If not already bound, bind to any interface, random UDP port. If it is + * reused or a custom local port was desired, this has already been done! + * + * We once used the size of the local_addr struct as the third argument + * for bind() to better work with IPv6 or whatever size the struct could + * have, but we learned that at least Tru64, AIX and IRIX *requires* the + * size of that argument to match the exact size of a 'sockaddr_in' struct + * when running IPv4-only. + * + * Therefore we use the size from the address we connected to, which we + * assume uses the same IP version and thus hopefully this works for both + * IPv4 and IPv6... + */ + int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr, + (curl_socklen_t)conn->remote_addr->addrlen); + if(rc) { + char buffer[STRERROR_LEN]; + failf(data, "bind() failed; %s", + Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); + return CURLE_COULDNT_CONNECT; + } + conn->bits.bound = TRUE; + } + + Curl_pgrsStartNow(data); + + *done = TRUE; + + return CURLE_OK; +} + +/********************************************************** + * + * tftp_done + * + * The done callback + * + **********************************************************/ +static CURLcode tftp_done(struct Curl_easy *data, CURLcode status, + bool premature) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + (void)status; /* unused */ + (void)premature; /* not used */ + + if(Curl_pgrsDone(data)) + return CURLE_ABORTED_BY_CALLBACK; + + /* If we have encountered an error */ + if(state) + result = tftp_translate_code(state->error); + + return result; +} + +/********************************************************** + * + * tftp_getsock + * + * The getsock callback + * + **********************************************************/ +static int tftp_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks) +{ + (void)data; + socks[0] = conn->sock[FIRSTSOCKET]; + return GETSOCK_READSOCK(0); +} + +/********************************************************** + * + * tftp_receive_packet + * + * Called once select fires and data is ready on the socket + * + **********************************************************/ +static CURLcode tftp_receive_packet(struct Curl_easy *data) +{ + curl_socklen_t fromlen; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + /* Receive the packet */ + fromlen = sizeof(state->remote_addr); + state->rbytes = (int)recvfrom(state->sockfd, + (void *)state->rpacket.data, + (RECV_TYPE_ARG3)state->blksize + 4, + 0, + (struct sockaddr *)&state->remote_addr, + &fromlen); + state->remote_addrlen = fromlen; + + /* Sanity check packet length */ + if(state->rbytes < 4) { + failf(data, "Received too short packet"); + /* Not a timeout, but how best to handle it? */ + state->event = TFTP_EVENT_TIMEOUT; + } + else { + /* The event is given by the TFTP packet time */ + unsigned short event = getrpacketevent(&state->rpacket); + state->event = (tftp_event_t)event; + + switch(state->event) { + case TFTP_EVENT_DATA: + /* Do not pass to the client empty or retransmitted packets */ + if(state->rbytes > 4 && + (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) { + result = Curl_client_write(data, CLIENTWRITE_BODY, + (char *)state->rpacket.data + 4, + state->rbytes-4); + if(result) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return result; + } + } + break; + case TFTP_EVENT_ERROR: + { + unsigned short error = getrpacketblock(&state->rpacket); + char *str = (char *)state->rpacket.data + 4; + size_t strn = state->rbytes - 4; + state->error = (tftp_error_t)error; + if(tftp_strnlen(str, strn) < strn) + infof(data, "TFTP error: %s", str); + break; + } + case TFTP_EVENT_ACK: + break; + case TFTP_EVENT_OACK: + result = tftp_parse_option_ack(state, + (const char *)state->rpacket.data + 2, + state->rbytes-2); + if(result) + return result; + break; + case TFTP_EVENT_RRQ: + case TFTP_EVENT_WRQ: + default: + failf(data, "%s", "Internal error: Unexpected packet"); + break; + } + + /* Update the progress meter */ + if(Curl_pgrsUpdate(data)) { + tftp_state_machine(state, TFTP_EVENT_ERROR); + return CURLE_ABORTED_BY_CALLBACK; + } + } + return result; +} + +/********************************************************** + * + * tftp_state_timeout + * + * Check if timeouts have been reached + * + **********************************************************/ +static timediff_t tftp_state_timeout(struct Curl_easy *data, + tftp_event_t *event) +{ + time_t current; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + timediff_t timeout_ms; + + if(event) + *event = TFTP_EVENT_NONE; + + timeout_ms = Curl_timeleft(state->data, NULL, + (state->state == TFTP_STATE_START)); + if(timeout_ms < 0) { + state->error = TFTP_ERR_TIMEOUT; + state->state = TFTP_STATE_FIN; + return 0; + } + current = time(NULL); + if(current > state->rx_time + state->retry_time) { + if(event) + *event = TFTP_EVENT_TIMEOUT; + state->rx_time = time(NULL); /* update even though we received nothing */ + } + + return timeout_ms; +} + +/********************************************************** + * + * tftp_multi_statemach + * + * Handle single RX socket event and return + * + **********************************************************/ +static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done) +{ + tftp_event_t event; + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + timediff_t timeout_ms = tftp_state_timeout(data, &event); + + *done = FALSE; + + if(timeout_ms < 0) { + failf(data, "TFTP response timeout"); + return CURLE_OPERATION_TIMEDOUT; + } + if(event != TFTP_EVENT_NONE) { + result = tftp_state_machine(state, event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN); + if(*done) + /* Tell curl we are done */ + Curl_xfer_setup_nop(data); + } + else { + /* no timeouts to handle, check our socket */ + int rc = SOCKET_READABLE(state->sockfd, 0); + + if(rc == -1) { + /* bail out */ + int error = SOCKERRNO; + char buffer[STRERROR_LEN]; + failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer))); + state->event = TFTP_EVENT_ERROR; + } + else if(rc) { + result = tftp_receive_packet(data); + if(result) + return result; + result = tftp_state_machine(state, state->event); + if(result) + return result; + *done = (state->state == TFTP_STATE_FIN); + if(*done) + /* Tell curl we are done */ + Curl_xfer_setup_nop(data); + } + /* if rc == 0, then select() timed out */ + } + + return result; +} + +/********************************************************** + * + * tftp_doing + * + * Called from multi.c while DOing + * + **********************************************************/ +static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result; + result = tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) { + DEBUGF(infof(data, "DO phase is complete")); + } + else if(!result) { + /* The multi code does not have this logic for the DOING state so we + provide it for TFTP since it may do the entire transfer in this + state. */ + if(Curl_pgrsUpdate(data)) + result = CURLE_ABORTED_BY_CALLBACK; + else + result = Curl_speedcheck(data, Curl_now()); + } + return result; +} + +/********************************************************** + * + * tftp_perform + * + * Entry point for transfer from tftp_do, starts state mach + * + **********************************************************/ +static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn = data->conn; + struct tftp_state_data *state = conn->proto.tftpc; + + *dophase_done = FALSE; + + result = tftp_state_machine(state, TFTP_EVENT_INIT); + + if((state->state == TFTP_STATE_FIN) || result) + return result; + + tftp_multi_statemach(data, dophase_done); + + if(*dophase_done) + DEBUGF(infof(data, "DO phase is complete")); + + return result; +} + + +/********************************************************** + * + * tftp_do + * + * The do callback + * + * This callback initiates the TFTP transfer + * + **********************************************************/ + +static CURLcode tftp_do(struct Curl_easy *data, bool *done) +{ + struct tftp_state_data *state; + CURLcode result; + struct connectdata *conn = data->conn; + + *done = FALSE; + + if(!conn->proto.tftpc) { + result = tftp_connect(data, done); + if(result) + return result; + } + + state = conn->proto.tftpc; + if(!state) + return CURLE_TFTP_ILLEGAL; + + result = tftp_perform(data, done); + + /* If tftp_perform() returned an error, use that for return code. If it + was OK, see if tftp_translate_code() has an error. */ + if(!result) + /* If we have encountered an internal tftp error, translate it. */ + result = tftp_translate_code(state->error); + + return result; +} + +static CURLcode tftp_setup_connection(struct Curl_easy *data, + struct connectdata *conn) +{ + char *type; + + conn->transport = TRNSPRT_UDP; + + /* TFTP URLs support an extension like ";mode=" that + * we will try to get now! */ + type = strstr(data->state.up.path, ";mode="); + + if(!type) + type = strstr(conn->host.rawalloc, ";mode="); + + if(type) { + char command; + *type = 0; /* it was in the middle of the hostname */ + command = Curl_raw_toupper(type[6]); + + switch(command) { + case 'A': /* ASCII mode */ + case 'N': /* NETASCII mode */ + data->state.prefer_ascii = TRUE; + break; + + case 'O': /* octet mode */ + case 'I': /* binary mode */ + default: + /* switch off ASCII */ + data->state.prefer_ascii = FALSE; + break; + } + } + + return CURLE_OK; +} +#endif diff --git a/local-test-curl-full-01/afc-curl/lib/timediff.h b/local-test-curl-full-01/afc-curl/lib/timediff.h new file mode 100644 index 0000000000000000000000000000000000000000..75f996c55cf956140b2d3d2cc86f70e7ff5fdd9a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/timediff.h @@ -0,0 +1,52 @@ +#ifndef HEADER_CURL_TIMEDIFF_H +#define HEADER_CURL_TIMEDIFF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +/* Use a larger type even for 32-bit time_t systems so that we can keep + microsecond accuracy in it */ +typedef curl_off_t timediff_t; +#define FMT_TIMEDIFF_T FMT_OFF_T + +#define TIMEDIFF_T_MAX CURL_OFF_T_MAX +#define TIMEDIFF_T_MIN CURL_OFF_T_MIN + +/* + * Converts number of milliseconds into a timeval structure. + * + * Return values: + * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select) + * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select) + * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select) + */ +struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms); + +/* + * Converts a timeval structure into number of milliseconds. + */ +timediff_t curlx_tvtoms(struct timeval *tv); + +#endif /* HEADER_CURL_TIMEDIFF_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/timeval.h b/local-test-curl-full-01/afc-curl/lib/timeval.h new file mode 100644 index 0000000000000000000000000000000000000000..33dfb5b10dd26b94c8348f03a170423bf5f0da4a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/timeval.h @@ -0,0 +1,62 @@ +#ifndef HEADER_CURL_TIMEVAL_H +#define HEADER_CURL_TIMEVAL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "timediff.h" + +struct curltime { + time_t tv_sec; /* seconds */ + int tv_usec; /* microseconds */ +}; + +struct curltime Curl_now(void); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds. + */ +timediff_t Curl_timediff(struct curltime newer, struct curltime older); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of milliseconds, rounded up. + */ +timediff_t Curl_timediff_ceil(struct curltime newer, struct curltime older); + +/* + * Make sure that the first argument (newer) is the more recent time and older + * is the older time, as otherwise you get a weird negative time-diff back... + * + * Returns: the time difference in number of microseconds. + */ +timediff_t Curl_timediff_us(struct curltime newer, struct curltime older); + +#endif /* HEADER_CURL_TIMEVAL_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/transfer.h b/local-test-curl-full-01/afc-curl/lib/transfer.h new file mode 100644 index 0000000000000000000000000000000000000000..8c9b88c17850e7680b45a4304912a42782e64284 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/transfer.h @@ -0,0 +1,154 @@ +#ifndef HEADER_CURL_TRANSFER_H +#define HEADER_CURL_TRANSFER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#define Curl_headersep(x) ((((x)==':') || ((x)==';'))) +char *Curl_checkheaders(const struct Curl_easy *data, + const char *thisheader, + const size_t thislen); + +void Curl_init_CONNECT(struct Curl_easy *data); + +CURLcode Curl_pretransfer(struct Curl_easy *data); + +typedef enum { + FOLLOW_NONE, /* not used within the function, just a placeholder to + allow initing to this */ + FOLLOW_FAKE, /* only records stuff, not actually following */ + FOLLOW_RETRY, /* set if this is a request retry as opposed to a real + redirect following */ + FOLLOW_REDIR /* a full true redirect */ +} followtype; + +CURLcode Curl_sendrecv(struct Curl_easy *data, struct curltime *nowp); +int Curl_single_getsock(struct Curl_easy *data, + struct connectdata *conn, curl_socket_t *socks); +CURLcode Curl_retry_request(struct Curl_easy *data, char **url); +bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc); + +/** + * Write the transfer raw response bytes, as received from the connection. + * Will handle all passed bytes or return an error. By default, this will + * write the bytes as BODY to the client. Protocols may provide a + * "write_resp" callback in their handler to add specific treatment. E.g. + * HTTP parses response headers and passes them differently to the client. + * @param data the transfer + * @param buf the raw response bytes + * @param blen the amount of bytes in `buf` + * @param is_eos TRUE iff the connection indicates this to be the last + * bytes of the response + */ +CURLcode Curl_xfer_write_resp(struct Curl_easy *data, + const char *buf, size_t blen, + bool is_eos); + +/** + * Write a single "header" line from a server response. + * @param hd0 the 0-terminated, single header line + * @param hdlen the length of the header line + * @param is_eos TRUE iff this is the end of the response + */ +CURLcode Curl_xfer_write_resp_hd(struct Curl_easy *data, + const char *hd0, size_t hdlen, bool is_eos); + +#define CURL_XFER_NOP (0) +#define CURL_XFER_RECV (1<<(0)) +#define CURL_XFER_SEND (1<<(1)) +#define CURL_XFER_SENDRECV (CURL_XFER_RECV|CURL_XFER_SEND) + +/** + * The transfer is neither receiving nor sending now. + */ +void Curl_xfer_setup_nop(struct Curl_easy *data); + +/** + * The transfer will use socket 1 to send/recv. `recv_size` is + * the amount to receive or -1 if unknown. `getheader` indicates + * response header processing is expected. + */ +void Curl_xfer_setup1(struct Curl_easy *data, + int send_recv, + curl_off_t recv_size, + bool getheader); + +/** + * The transfer will use socket 2 to send/recv. `recv_size` is + * the amount to receive or -1 if unknown. With `shutdown` being + * set, the transfer is only allowed to either send OR receive + * and the socket 2 connection will be shutdown at the end of + * the transfer. An unclean shutdown will fail the transfer + * unless `shutdown_err_ignore` is TRUE. + */ +void Curl_xfer_setup2(struct Curl_easy *data, + int send_recv, + curl_off_t recv_size, + bool shutdown, bool shutdown_err_ignore); + +/** + * Multi has set transfer to DONE. Last chance to trigger + * missing response things like writing an EOS to the client. + */ +CURLcode Curl_xfer_write_done(struct Curl_easy *data, bool premature); + +/** + * Return TRUE iff transfer has pending data to send. Checks involved + * connection filters. + */ +bool Curl_xfer_needs_flush(struct Curl_easy *data); + +/** + * Flush any pending send data on the transfer connection. + */ +CURLcode Curl_xfer_flush(struct Curl_easy *data); + +/** + * Send data on the socket/connection filter designated + * for transfer's outgoing data. + * Will return CURLE_OK on blocking with (*pnwritten == 0). + */ +CURLcode Curl_xfer_send(struct Curl_easy *data, + const void *buf, size_t blen, bool eos, + size_t *pnwritten); + +/** + * Receive data on the socket/connection filter designated + * for transfer's incoming data. + * Will return CURLE_AGAIN on blocking with (*pnrcvd == 0). + */ +CURLcode Curl_xfer_recv(struct Curl_easy *data, + char *buf, size_t blen, + ssize_t *pnrcvd); + +CURLcode Curl_xfer_send_close(struct Curl_easy *data); +CURLcode Curl_xfer_send_shutdown(struct Curl_easy *data, bool *done); + +/** + * Return TRUE iff the transfer is not done, but further progress + * is blocked. For example when it is only receiving and its writer + * is PAUSED. + */ +bool Curl_xfer_is_blocked(struct Curl_easy *data); + +#endif /* HEADER_CURL_TRANSFER_H */ diff --git a/local-test-curl-full-01/afc-curl/lib/urlapi.c b/local-test-curl-full-01/afc-curl/lib/urlapi.c new file mode 100644 index 0000000000000000000000000000000000000000..98c8f6fe6d5ce08c919edfbf6a5a87aa1e263484 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/urlapi.c @@ -0,0 +1,2015 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ + +#include "curl_setup.h" + +#include "urldata.h" +#include "urlapi-int.h" +#include "strcase.h" +#include "url.h" +#include "escape.h" +#include "curl_ctype.h" +#include "inet_pton.h" +#include "inet_ntop.h" +#include "strdup.h" +#include "idn.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + /* MS-DOS/Windows style drive prefix, eg c: in c:foo */ +#define STARTS_WITH_DRIVE_PREFIX(str) \ + ((('a' <= str[0] && str[0] <= 'z') || \ + ('A' <= str[0] && str[0] <= 'Z')) && \ + (str[1] == ':')) + + /* MS-DOS/Windows style drive prefix, optionally with + * a '|' instead of ':', followed by a slash or NUL */ +#define STARTS_WITH_URL_DRIVE_PREFIX(str) \ + ((('a' <= (str)[0] && (str)[0] <= 'z') || \ + ('A' <= (str)[0] && (str)[0] <= 'Z')) && \ + ((str)[1] == ':' || (str)[1] == '|') && \ + ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0)) + +/* scheme is not URL encoded, the longest libcurl supported ones are... */ +#define MAX_SCHEME_LEN 40 + +/* + * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make + * sure we have _some_ value for AF_INET6 without polluting our fake value + * everywhere. + */ +#if !defined(USE_IPV6) && !defined(AF_INET6) +#define AF_INET6 (AF_INET + 1) +#endif + +/* Internal representation of CURLU. Point to URL-encoded strings. */ +struct Curl_URL { + char *scheme; + char *user; + char *password; + char *options; /* IMAP only? */ + char *host; + char *zoneid; /* for numerical IPv6 addresses */ + char *port; + char *path; + char *query; + char *fragment; + unsigned short portnum; /* the numerical version (if 'port' is set) */ + BIT(query_present); /* to support blank */ + BIT(fragment_present); /* to support blank */ + BIT(guessed_scheme); /* when a URL without scheme is parsed */ +}; + +#define DEFAULT_SCHEME "https" + +static void free_urlhandle(struct Curl_URL *u) +{ + free(u->scheme); + free(u->user); + free(u->password); + free(u->options); + free(u->host); + free(u->zoneid); + free(u->port); + free(u->path); + free(u->query); + free(u->fragment); +} + +/* + * Find the separator at the end of the hostname, or the '?' in cases like + * http://www.example.com?id=2380 + */ +static const char *find_host_sep(const char *url) +{ + const char *sep; + const char *query; + + /* Find the start of the hostname */ + sep = strstr(url, "//"); + if(!sep) + sep = url; + else + sep += 2; + + query = strchr(sep, '?'); + sep = strchr(sep, '/'); + + if(!sep) + sep = url + strlen(url); + + if(!query) + query = url + strlen(url); + + return sep < query ? sep : query; +} + +/* convert CURLcode to CURLUcode */ +#define cc2cu(x) ((x) == CURLE_TOO_LARGE ? CURLUE_TOO_LARGE : \ + CURLUE_OUT_OF_MEMORY) +/* + * Decide whether a character in a URL must be escaped. + */ +#define urlchar_needs_escaping(c) (!(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c))) + +static const char hexdigits[] = "0123456789abcdef"; +/* urlencode_str() writes data into an output dynbuf and URL-encodes the + * spaces in the source URL accordingly. + * + * URL encoding should be skipped for hostnames, otherwise IDN resolution + * will fail. + */ +static CURLUcode urlencode_str(struct dynbuf *o, const char *url, + size_t len, bool relative, + bool query) +{ + /* we must add this with whitespace-replacing */ + bool left = !query; + const unsigned char *iptr; + const unsigned char *host_sep = (const unsigned char *) url; + CURLcode result; + + if(!relative) + host_sep = (const unsigned char *) find_host_sep(url); + + for(iptr = (unsigned char *)url; /* read from here */ + len; iptr++, len--) { + + if(iptr < host_sep) { + result = Curl_dyn_addn(o, iptr, 1); + if(result) + return cc2cu(result); + continue; + } + + if(*iptr == ' ') { + if(left) + result = Curl_dyn_addn(o, "%20", 3); + else + result = Curl_dyn_addn(o, "+", 1); + if(result) + return cc2cu(result); + continue; + } + + if(*iptr == '?') + left = FALSE; + + if(urlchar_needs_escaping(*iptr)) { + char out[3]={'%'}; + out[1] = hexdigits[*iptr >> 4]; + out[2] = hexdigits[*iptr & 0xf]; + result = Curl_dyn_addn(o, out, 3); + } + else + result = Curl_dyn_addn(o, iptr, 1); + if(result) + return cc2cu(result); + } + + return CURLUE_OK; +} + +/* + * Returns the length of the scheme if the given URL is absolute (as opposed + * to relative). Stores the scheme in the buffer if TRUE and 'buf' is + * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set. + * + * If 'guess_scheme' is TRUE, it means the URL might be provided without + * scheme. + */ +size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen, + bool guess_scheme) +{ + size_t i = 0; + DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN)); + (void)buflen; /* only used in debug-builds */ + if(buf) + buf[0] = 0; /* always leave a defined value in buf */ +#ifdef _WIN32 + if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url)) + return 0; +#endif + if(ISALPHA(url[0])) + for(i = 1; i < MAX_SCHEME_LEN; ++i) { + char s = url[i]; + if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') )) { + /* RFC 3986 3.1 explains: + scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + */ + } + else { + break; + } + } + if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) { + /* If this does not guess scheme, the scheme always ends with the colon so + that this also detects data: URLs etc. In guessing mode, data: could + be the hostname "data" with a specified port number. */ + + /* the length of the scheme is the name part only */ + size_t len = i; + if(buf) { + Curl_strntolower(buf, url, i); + buf[i] = 0; + } + return len; + } + return 0; +} + +/* + * Concatenate a relative URL to a base URL making it absolute. + * URL-encodes any spaces. + * The returned pointer must be freed by the caller unless NULL + * (returns NULL on out of memory). + * + * Note that this function destroys the 'base' string. + */ +static CURLcode concat_url(char *base, const char *relurl, char **newurl) +{ + /*** + TRY to append this new path to the old URL + to the right of the host part. Oh crap, this is doomed to cause + problems in the future... + */ + struct dynbuf newest; + char *protsep; + char *pathsep; + bool host_changed = FALSE; + const char *useurl = relurl; + CURLcode result = CURLE_OK; + CURLUcode uc; + bool skip_slash = FALSE; + *newurl = NULL; + + /* protsep points to the start of the hostname */ + protsep = strstr(base, "//"); + if(!protsep) + protsep = base; + else + protsep += 2; /* pass the slashes */ + + if('/' != relurl[0]) { + int level = 0; + + /* First we need to find out if there is a ?-letter in the URL, + and cut it and the right-side of that off */ + pathsep = strchr(protsep, '?'); + if(pathsep) + *pathsep = 0; + + /* we have a relative path to append to the last slash if there is one + available, or the new URL is just a query string (starts with a '?') or + a fragment (starts with '#') we append the new one at the end of the + current URL */ + if((useurl[0] != '?') && (useurl[0] != '#')) { + pathsep = strrchr(protsep, '/'); + if(pathsep) + *pathsep = 0; + + /* Check if there is any slash after the hostname, and if so, remember + that position instead */ + pathsep = strchr(protsep, '/'); + if(pathsep) + protsep = pathsep + 1; + else + protsep = NULL; + + /* now deal with one "./" or any amount of "../" in the newurl + and act accordingly */ + + if((useurl[0] == '.') && (useurl[1] == '/')) + useurl += 2; /* just skip the "./" */ + + while((useurl[0] == '.') && + (useurl[1] == '.') && + (useurl[2] == '/')) { + level++; + useurl += 3; /* pass the "../" */ + } + + if(protsep) { + while(level--) { + /* cut off one more level from the right of the original URL */ + pathsep = strrchr(protsep, '/'); + if(pathsep) + *pathsep = 0; + else { + *protsep = 0; + break; + } + } + } + } + else + skip_slash = TRUE; + } + else { + /* We got a new absolute path for this server */ + + if(relurl[1] == '/') { + /* the new URL starts with //, just keep the protocol part from the + original one */ + *protsep = 0; + useurl = &relurl[2]; /* we keep the slashes from the original, so we + skip the new ones */ + host_changed = TRUE; + } + else { + /* cut off the original URL from the first slash, or deal with URLs + without slash */ + pathsep = strchr(protsep, '/'); + if(pathsep) { + /* When people use badly formatted URLs, such as + "http://www.example.com?dir=/home/daniel" we must not use the first + slash, if there is a ?-letter before it! */ + char *sep = strchr(protsep, '?'); + if(sep && (sep < pathsep)) + pathsep = sep; + *pathsep = 0; + } + else { + /* There was no slash. Now, since we might be operating on a badly + formatted URL, such as "http://www.example.com?id=2380" which does + not use a slash separator as it is supposed to, we need to check + for a ?-letter as well! */ + pathsep = strchr(protsep, '?'); + if(pathsep) + *pathsep = 0; + } + } + } + + Curl_dyn_init(&newest, CURL_MAX_INPUT_LENGTH); + + /* copy over the root URL part */ + result = Curl_dyn_add(&newest, base); + if(result) + return result; + + /* check if we need to append a slash */ + if(('/' == useurl[0]) || (protsep && !*protsep) || skip_slash) + ; + else { + result = Curl_dyn_addn(&newest, "/", 1); + if(result) + return result; + } + + /* then append the new piece on the right side */ + uc = urlencode_str(&newest, useurl, strlen(useurl), !host_changed, + FALSE); + if(uc) + return (uc == CURLUE_TOO_LARGE) ? CURLE_TOO_LARGE : CURLE_OUT_OF_MEMORY; + + *newurl = Curl_dyn_ptr(&newest); + return CURLE_OK; +} + +/* scan for byte values <= 31, 127 and sometimes space */ +static CURLUcode junkscan(const char *url, size_t *urllen, unsigned int flags) +{ + static const char badbytes[]={ + /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x7f, 0x00 /* null-terminate */ + }; + size_t n = strlen(url); + size_t nfine; + + if(n > CURL_MAX_INPUT_LENGTH) + /* excessive input length */ + return CURLUE_MALFORMED_INPUT; + + nfine = strcspn(url, badbytes); + if((nfine != n) || + (!(flags & CURLU_ALLOW_SPACE) && strchr(url, ' '))) + return CURLUE_MALFORMED_INPUT; + + *urllen = n; + return CURLUE_OK; +} + +/* + * parse_hostname_login() + * + * Parse the login details (username, password and options) from the URL and + * strip them out of the hostname + * + */ +static CURLUcode parse_hostname_login(struct Curl_URL *u, + const char *login, + size_t len, + unsigned int flags, + size_t *offset) /* to the hostname */ +{ + CURLUcode result = CURLUE_OK; + CURLcode ccode; + char *userp = NULL; + char *passwdp = NULL; + char *optionsp = NULL; + const struct Curl_handler *h = NULL; + + /* At this point, we assume all the other special cases have been taken + * care of, so the host is at most + * + * [user[:password][;options]]@]hostname + * + * We need somewhere to put the embedded details, so do that first. + */ + char *ptr; + + DEBUGASSERT(login); + + *offset = 0; + ptr = memchr(login, '@', len); + if(!ptr) + goto out; + + /* We will now try to extract the + * possible login information in a string like: + * ftp://user:password@ftp.my.site:8021/README */ + ptr++; + + /* if this is a known scheme, get some details */ + if(u->scheme) + h = Curl_get_scheme_handler(u->scheme); + + /* We could use the login information in the URL so extract it. Only parse + options if the handler says we should. Note that 'h' might be NULL! */ + ccode = Curl_parse_login_details(login, ptr - login - 1, + &userp, &passwdp, + (h && (h->flags & PROTOPT_URLOPTIONS)) ? + &optionsp : NULL); + if(ccode) { + result = CURLUE_BAD_LOGIN; + goto out; + } + + if(userp) { + if(flags & CURLU_DISALLOW_USER) { + /* Option DISALLOW_USER is set and URL contains username. */ + result = CURLUE_USER_NOT_ALLOWED; + goto out; + } + free(u->user); + u->user = userp; + } + + if(passwdp) { + free(u->password); + u->password = passwdp; + } + + if(optionsp) { + free(u->options); + u->options = optionsp; + } + + /* the hostname starts at this offset */ + *offset = ptr - login; + return CURLUE_OK; + +out: + + free(userp); + free(passwdp); + free(optionsp); + u->user = NULL; + u->password = NULL; + u->options = NULL; + + return result; +} + +UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host, + bool has_scheme) +{ + char *portptr; + char *hostname = Curl_dyn_ptr(host); + /* + * Find the end of an IPv6 address on the ']' ending bracket. + */ + if(hostname[0] == '[') { + portptr = strchr(hostname, ']'); + if(!portptr) + return CURLUE_BAD_IPV6; + portptr++; + /* this is a RFC2732-style specified IP-address */ + if(*portptr) { + if(*portptr != ':') + return CURLUE_BAD_PORT_NUMBER; + } + else + portptr = NULL; + } + else + portptr = strchr(hostname, ':'); + + if(portptr) { + char *rest = NULL; + unsigned long port; + size_t keep = portptr - hostname; + + /* Browser behavior adaptation. If there is a colon with no digits after, + just cut off the name there which makes us ignore the colon and just + use the default port. Firefox, Chrome and Safari all do that. + + Do not do it if the URL has no scheme, to make something that looks like + a scheme not work! + */ + Curl_dyn_setlen(host, keep); + portptr++; + if(!*portptr) + return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER; + + if(!ISDIGIT(*portptr)) + return CURLUE_BAD_PORT_NUMBER; + + errno = 0; + port = strtoul(portptr, &rest, 10); /* Port number must be decimal */ + + if(errno || (port > 0xffff) || *rest) + return CURLUE_BAD_PORT_NUMBER; + + u->portnum = (unsigned short) port; + /* generate a new port number string to get rid of leading zeroes etc */ + free(u->port); + u->port = aprintf("%ld", port); + if(!u->port) + return CURLUE_OUT_OF_MEMORY; + } + + return CURLUE_OK; +} + +/* this assumes 'hostname' now starts with [ */ +static CURLUcode ipv6_parse(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(*hostname == '['); + if(hlen < 4) /* '[::]' is the shortest possible valid string */ + return CURLUE_BAD_IPV6; + hostname++; + hlen -= 2; + + /* only valid IPv6 letters are ok */ + len = strspn(hostname, "0123456789abcdefABCDEF:."); + + if(hlen != len) { + hlen = len; + if(hostname[len] == '%') { + /* this could now be '%[zone id]' */ + char zoneid[16]; + int i = 0; + char *h = &hostname[len + 1]; + /* pass '25' if present and is a URL encoded percent sign */ + if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']')) + h += 2; + while(*h && (*h != ']') && (i < 15)) + zoneid[i++] = *h++; + if(!i || (']' != *h)) + return CURLUE_BAD_IPV6; + zoneid[i] = 0; + u->zoneid = strdup(zoneid); + if(!u->zoneid) + return CURLUE_OUT_OF_MEMORY; + hostname[len] = ']'; /* insert end bracket */ + hostname[len + 1] = 0; /* terminate the hostname */ + } + else + return CURLUE_BAD_IPV6; + /* hostname is fine */ + } + + /* Normalize the IPv6 address */ + { + char dest[16]; /* fits a binary IPv6 address */ + hostname[hlen] = 0; /* end the address there */ + if(1 != Curl_inet_pton(AF_INET6, hostname, dest)) + return CURLUE_BAD_IPV6; + if(Curl_inet_ntop(AF_INET6, dest, hostname, hlen)) { + hlen = strlen(hostname); /* might be shorter now */ + hostname[hlen + 1] = 0; + } + hostname[hlen] = ']'; /* restore ending bracket */ + } + return CURLUE_OK; +} + +static CURLUcode hostname_check(struct Curl_URL *u, char *hostname, + size_t hlen) /* length of hostname */ +{ + size_t len; + DEBUGASSERT(hostname); + + if(!hlen) + return CURLUE_NO_HOST; + else if(hostname[0] == '[') + return ipv6_parse(u, hostname, hlen); + else { + /* letters from the second string are not ok */ + len = strcspn(hostname, " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,+&()%"); + if(hlen != len) + /* hostname with bad content */ + return CURLUE_BAD_HOSTNAME; + } + return CURLUE_OK; +} + +/* + * Handle partial IPv4 numerical addresses and different bases, like + * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc. + * + * If the given input string is syntactically wrong IPv4 or any part for + * example is too big, this function returns HOST_NAME. + * + * Output the "normalized" version of that input string in plain quad decimal + * integers. + * + * Returns the host type. + */ + +#define HOST_ERROR -1 /* out of memory */ + +#define HOST_NAME 1 +#define HOST_IPV4 2 +#define HOST_IPV6 3 + +static int ipv4_normalize(struct dynbuf *host) +{ + bool done = FALSE; + int n = 0; + const char *c = Curl_dyn_ptr(host); + unsigned long parts[4] = {0, 0, 0, 0}; + CURLcode result = CURLE_OK; + + if(*c == '[') + return HOST_IPV6; + + errno = 0; /* for strtoul */ + while(!done) { + char *endp = NULL; + unsigned long l; + if(!ISDIGIT(*c)) + /* most importantly this does not allow a leading plus or minus */ + return HOST_NAME; + l = strtoul(c, &endp, 0); + if(errno) + return HOST_NAME; +#if SIZEOF_LONG > 4 + /* a value larger than 32 bits */ + if(l > UINT_MAX) + return HOST_NAME; +#endif + + parts[n] = l; + c = endp; + + switch(*c) { + case '.': + if(n == 3) + return HOST_NAME; + n++; + c++; + break; + + case '\0': + done = TRUE; + break; + + default: + return HOST_NAME; + } + } + + switch(n) { + case 0: /* a -- 32 bits */ + Curl_dyn_reset(host); + + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0] >> 24), + (unsigned int)((parts[0] >> 16) & 0xff), + (unsigned int)((parts[0] >> 8) & 0xff), + (unsigned int)(parts[0] & 0xff)); + break; + case 1: /* a.b -- 8.24 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xffffff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)((parts[1] >> 16) & 0xff), + (unsigned int)((parts[1] >> 8) & 0xff), + (unsigned int)(parts[1] & 0xff)); + break; + case 2: /* a.b.c -- 8.8.16 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)(parts[1]), + (unsigned int)((parts[2] >> 8) & 0xff), + (unsigned int)(parts[2] & 0xff)); + break; + case 3: /* a.b.c.d -- 8.8.8.8 bits */ + if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) || + (parts[3] > 0xff)) + return HOST_NAME; + Curl_dyn_reset(host); + result = Curl_dyn_addf(host, "%u.%u.%u.%u", + (unsigned int)(parts[0]), + (unsigned int)(parts[1]), + (unsigned int)(parts[2]), + (unsigned int)(parts[3])); + break; + } + if(result) + return HOST_ERROR; + return HOST_IPV4; +} + +/* if necessary, replace the host content with a URL decoded version */ +static CURLUcode urldecode_host(struct dynbuf *host) +{ + char *per = NULL; + const char *hostname = Curl_dyn_ptr(host); + per = strchr(hostname, '%'); + if(!per) + /* nothing to decode */ + return CURLUE_OK; + else { + /* encoded */ + size_t dlen; + char *decoded; + CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen, + REJECT_CTRL); + if(result) + return CURLUE_BAD_HOSTNAME; + Curl_dyn_reset(host); + result = Curl_dyn_addn(host, decoded, dlen); + free(decoded); + if(result) + return cc2cu(result); + } + + return CURLUE_OK; +} + +static CURLUcode parse_authority(struct Curl_URL *u, + const char *auth, size_t authlen, + unsigned int flags, + struct dynbuf *host, + bool has_scheme) +{ + size_t offset; + CURLUcode uc; + CURLcode result; + + /* + * Parse the login details and strip them out of the hostname. + */ + uc = parse_hostname_login(u, auth, authlen, flags, &offset); + if(uc) + goto out; + + result = Curl_dyn_addn(host, auth + offset, authlen - offset); + if(result) { + uc = cc2cu(result); + goto out; + } + + uc = Curl_parse_port(u, host, has_scheme); + if(uc) + goto out; + + if(!Curl_dyn_len(host)) + return CURLUE_NO_HOST; + + switch(ipv4_normalize(host)) { + case HOST_IPV4: + break; + case HOST_IPV6: + uc = ipv6_parse(u, Curl_dyn_ptr(host), Curl_dyn_len(host)); + break; + case HOST_NAME: + uc = urldecode_host(host); + if(!uc) + uc = hostname_check(u, Curl_dyn_ptr(host), Curl_dyn_len(host)); + break; + case HOST_ERROR: + uc = CURLUE_OUT_OF_MEMORY; + break; + default: + uc = CURLUE_BAD_HOSTNAME; /* Bad IPv4 address even */ + break; + } + +out: + return uc; +} + +/* used for HTTP/2 server push */ +CURLUcode Curl_url_set_authority(CURLU *u, const char *authority) +{ + CURLUcode result; + struct dynbuf host; + + DEBUGASSERT(authority); + Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + result = parse_authority(u, authority, strlen(authority), + CURLU_DISALLOW_USER, &host, !!u->scheme); + if(result) + Curl_dyn_free(&host); + else { + free(u->host); + u->host = Curl_dyn_ptr(&host); + } + return result; +} + +/* + * "Remove Dot Segments" + * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + +/* + * dedotdotify() + * @unittest: 1395 + * + * This function gets a null-terminated path with dot and dotdot sequences + * passed in and strips them off according to the rules in RFC 3986 section + * 5.2.4. + * + * The function handles a query part ('?' + stuff) appended but it expects + * that fragments ('#' + stuff) have already been cut off. + * + * RETURNS + * + * Zero for success and 'out' set to an allocated dedotdotified string. + */ +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp); +UNITTEST int dedotdotify(const char *input, size_t clen, char **outp) +{ + char *outptr; + const char *endp = &input[clen]; + char *out; + + *outp = NULL; + /* the path always starts with a slash, and a slash has not dot */ + if((clen < 2) || !memchr(input, '.', clen)) + return 0; + + out = malloc(clen + 1); + if(!out) + return 1; /* out of memory */ + + *out = 0; /* null-terminates, for inputs like "./" */ + outptr = out; + + do { + bool dotdot = TRUE; + if(*input == '.') { + /* A. If the input buffer begins with a prefix of "../" or "./", then + remove that prefix from the input buffer; otherwise, */ + + if(!strncmp("./", input, 2)) { + input += 2; + clen -= 2; + } + else if(!strncmp("../", input, 3)) { + input += 3; + clen -= 3; + } + /* D. if the input buffer consists only of "." or "..", then remove + that from the input buffer; otherwise, */ + + else if(!strcmp(".", input) || !strcmp("..", input) || + !strncmp(".?", input, 2) || !strncmp("..?", input, 3)) { + *out = 0; + break; + } + else + dotdot = FALSE; + } + else if(*input == '/') { + /* B. if the input buffer begins with a prefix of "/./" or "/.", where + "." is a complete path segment, then replace that prefix with "/" in + the input buffer; otherwise, */ + if(!strncmp("/./", input, 3)) { + input += 2; + clen -= 2; + } + else if(!strcmp("/.", input) || !strncmp("/.?", input, 3)) { + *outptr++ = '/'; + *outptr = 0; + break; + } + + /* C. if the input buffer begins with a prefix of "/../" or "/..", + where ".." is a complete path segment, then replace that prefix with + "/" in the input buffer and remove the last segment and its + preceding "/" (if any) from the output buffer; otherwise, */ + + else if(!strncmp("/../", input, 4)) { + input += 3; + clen -= 3; + /* remove the last segment from the output buffer */ + while(outptr > out) { + outptr--; + if(*outptr == '/') + break; + } + *outptr = 0; /* null-terminate where it stops */ + } + else if(!strcmp("/..", input) || !strncmp("/..?", input, 4)) { + /* remove the last segment from the output buffer */ + while(outptr > out) { + outptr--; + if(*outptr == '/') + break; + } + *outptr++ = '/'; + *outptr = 0; /* null-terminate where it stops */ + break; + } + else + dotdot = FALSE; + } + else + dotdot = FALSE; + + if(!dotdot) { + /* E. move the first path segment in the input buffer to the end of + the output buffer, including the initial "/" character (if any) and + any subsequent characters up to, but not including, the next "/" + character or the end of the input buffer. */ + + do { + *outptr++ = *input++; + clen--; + } while(*input && (*input != '/') && (*input != '?')); + *outptr = 0; + } + + /* continue until end of path */ + } while(input < endp); + + *outp = out; + return 0; /* success */ +} + +static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags) +{ + const char *path; + size_t pathlen; + char *query = NULL; + char *fragment = NULL; + char schemebuf[MAX_SCHEME_LEN + 1]; + size_t schemelen = 0; + size_t urllen; + CURLUcode result = CURLUE_OK; + size_t fraglen = 0; + struct dynbuf host; + + DEBUGASSERT(url); + + Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH); + + result = junkscan(url, &urllen, flags); + if(result) + goto fail; + + schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf), + flags & (CURLU_GUESS_SCHEME| + CURLU_DEFAULT_SCHEME)); + + /* handle the file: scheme */ + if(schemelen && !strcmp(schemebuf, "file")) { + bool uncpath = FALSE; + if(urllen <= 6) { + /* file:/ is not enough to actually be a complete file: URL */ + result = CURLUE_BAD_FILE_URL; + goto fail; + } + + /* path has been allocated large enough to hold this */ + path = (char *)&url[5]; + pathlen = urllen - 5; + + u->scheme = strdup("file"); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + + /* Extra handling URLs with an authority component (i.e. that start with + * "file://") + * + * We allow omitted hostname (e.g. file:/) -- valid according to + * RFC 8089, but not the (current) WHAT-WG URL spec. + */ + if(path[0] == '/' && path[1] == '/') { + /* swallow the two slashes */ + const char *ptr = &path[2]; + + /* + * According to RFC 8089, a file: URL can be reliably dereferenced if: + * + * o it has no/blank hostname, or + * + * o the hostname matches "localhost" (case-insensitively), or + * + * o the hostname is a FQDN that resolves to this machine, or + * + * o it is an UNC String transformed to an URI (Windows only, RFC 8089 + * Appendix E.3). + * + * For brevity, we only consider URLs with empty, "localhost", or + * "127.0.0.1" hostnames as local, otherwise as an UNC String. + * + * Additionally, there is an exception for URLs with a Windows drive + * letter in the authority (which was accidentally omitted from RFC 8089 + * Appendix E, but believe me, it was meant to be there. --MK) + */ + if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) { + /* the URL includes a hostname, it must match "localhost" or + "127.0.0.1" to be valid */ + if(checkprefix("localhost/", ptr) || + checkprefix("127.0.0.1/", ptr)) { + ptr += 9; /* now points to the slash after the host */ + } + else { +#if defined(_WIN32) + size_t len; + + /* the hostname, NetBIOS computer name, can not contain disallowed + chars, and the delimiting slash character must be appended to the + hostname */ + path = strpbrk(ptr, "/\\:*?\"<>|"); + if(!path || *path != '/') { + result = CURLUE_BAD_FILE_URL; + goto fail; + } + + len = path - ptr; + if(len) { + CURLcode code = Curl_dyn_addn(&host, ptr, len); + if(code) { + result = cc2cu(code); + goto fail; + } + uncpath = TRUE; + } + + ptr -= 2; /* now points to the // before the host in UNC */ +#else + /* Invalid file://hostname/, expected localhost or 127.0.0.1 or + none */ + result = CURLUE_BAD_FILE_URL; + goto fail; +#endif + } + } + + path = ptr; + pathlen = urllen - (ptr - url); + } + + if(!uncpath) + /* no host for file: URLs by default */ + Curl_dyn_reset(&host); + +#if !defined(_WIN32) && !defined(MSDOS) && !defined(__CYGWIN__) + /* Do not allow Windows drive letters when not in Windows. + * This catches both "file:/c:" and "file:c:" */ + if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) || + STARTS_WITH_URL_DRIVE_PREFIX(path)) { + /* File drive letters are only accepted in MS-DOS/Windows */ + result = CURLUE_BAD_FILE_URL; + goto fail; + } +#else + /* If the path starts with a slash and a drive letter, ditch the slash */ + if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) { + /* This cannot be done with strcpy, as the memory chunks overlap! */ + path++; + pathlen--; + } +#endif + + } + else { + /* clear path */ + const char *schemep = NULL; + const char *hostp; + size_t hostlen; + + if(schemelen) { + int i = 0; + const char *p = &url[schemelen + 1]; + while((*p == '/') && (i < 4)) { + p++; + i++; + } + + schemep = schemebuf; + if(!Curl_get_scheme_handler(schemep) && + !(flags & CURLU_NON_SUPPORT_SCHEME)) { + result = CURLUE_UNSUPPORTED_SCHEME; + goto fail; + } + + if((i < 1) || (i > 3)) { + /* less than one or more than three slashes */ + result = CURLUE_BAD_SLASHES; + goto fail; + } + hostp = p; /* hostname starts here */ + } + else { + /* no scheme! */ + + if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME))) { + result = CURLUE_BAD_SCHEME; + goto fail; + } + if(flags & CURLU_DEFAULT_SCHEME) + schemep = DEFAULT_SCHEME; + + /* + * The URL was badly formatted, let's try without scheme specified. + */ + hostp = url; + } + + if(schemep) { + u->scheme = strdup(schemep); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + + /* find the end of the hostname + port number */ + hostlen = strcspn(hostp, "/?#"); + path = &hostp[hostlen]; + + /* this pathlen also contains the query and the fragment */ + pathlen = urllen - (path - url); + if(hostlen) { + + result = parse_authority(u, hostp, hostlen, flags, &host, schemelen); + if(result) + goto fail; + + if((flags & CURLU_GUESS_SCHEME) && !schemep) { + const char *hostname = Curl_dyn_ptr(&host); + /* legacy curl-style guess based on hostname */ + if(checkprefix("ftp.", hostname)) + schemep = "ftp"; + else if(checkprefix("dict.", hostname)) + schemep = "dict"; + else if(checkprefix("ldap.", hostname)) + schemep = "ldap"; + else if(checkprefix("imap.", hostname)) + schemep = "imap"; + else if(checkprefix("smtp.", hostname)) + schemep = "smtp"; + else if(checkprefix("pop3.", hostname)) + schemep = "pop3"; + else + schemep = "http"; + + u->scheme = strdup(schemep); + if(!u->scheme) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + u->guessed_scheme = TRUE; + } + } + else if(flags & CURLU_NO_AUTHORITY) { + /* allowed to be empty. */ + if(Curl_dyn_add(&host, "")) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + else { + result = CURLUE_NO_HOST; + goto fail; + } + } + + fragment = strchr(path, '#'); + if(fragment) { + fraglen = pathlen - (fragment - path); + u->fragment_present = TRUE; + if(fraglen > 1) { + /* skip the leading '#' in the copy but include the terminating null */ + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + result = urlencode_str(&enc, fragment + 1, fraglen - 1, TRUE, FALSE); + if(result) + goto fail; + u->fragment = Curl_dyn_ptr(&enc); + } + else { + u->fragment = Curl_memdup0(fragment + 1, fraglen - 1); + if(!u->fragment) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + /* after this, pathlen still contains the query */ + pathlen -= fraglen; + } + + query = memchr(path, '?', pathlen); + if(query) { + size_t qlen = fragment ? (size_t)(fragment - query) : + pathlen - (query - path); + pathlen -= qlen; + u->query_present = TRUE; + if(qlen > 1) { + if(flags & CURLU_URLENCODE) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + /* skip the leading question mark */ + result = urlencode_str(&enc, query + 1, qlen - 1, TRUE, TRUE); + if(result) + goto fail; + u->query = Curl_dyn_ptr(&enc); + } + else { + u->query = Curl_memdup0(query + 1, qlen - 1); + if(!u->query) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + else { + /* single byte query */ + u->query = strdup(""); + if(!u->query) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + } + } + + if(pathlen && (flags & CURLU_URLENCODE)) { + struct dynbuf enc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + result = urlencode_str(&enc, path, pathlen, TRUE, FALSE); + if(result) + goto fail; + pathlen = Curl_dyn_len(&enc); + path = u->path = Curl_dyn_ptr(&enc); + } + + if(pathlen <= 1) { + /* there is no path left or just the slash, unset */ + path = NULL; + } + else { + if(!u->path) { + u->path = Curl_memdup0(path, pathlen); + if(!u->path) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + path = u->path; + } + else if(flags & CURLU_URLENCODE) + /* it might have encoded more than just the path so cut it */ + u->path[pathlen] = 0; + + if(!(flags & CURLU_PATH_AS_IS)) { + /* remove ../ and ./ sequences according to RFC3986 */ + char *dedot; + int err = dedotdotify((char *)path, pathlen, &dedot); + if(err) { + result = CURLUE_OUT_OF_MEMORY; + goto fail; + } + if(dedot) { + free(u->path); + u->path = dedot; + } + } + } + + u->host = Curl_dyn_ptr(&host); + + return result; +fail: + Curl_dyn_free(&host); + free_urlhandle(u); + return result; +} + +/* + * Parse the URL and, if successful, replace everything in the Curl_URL struct. + */ +static CURLUcode parseurl_and_replace(const char *url, CURLU *u, + unsigned int flags) +{ + CURLUcode result; + CURLU tmpurl; + memset(&tmpurl, 0, sizeof(tmpurl)); + result = parseurl(url, &tmpurl, flags); + if(!result) { + free_urlhandle(u); + *u = tmpurl; + } + return result; +} + +/* + */ +CURLU *curl_url(void) +{ + return calloc(1, sizeof(struct Curl_URL)); +} + +void curl_url_cleanup(CURLU *u) +{ + if(u) { + free_urlhandle(u); + free(u); + } +} + +#define DUP(dest, src, name) \ + do { \ + if(src->name) { \ + dest->name = strdup(src->name); \ + if(!dest->name) \ + goto fail; \ + } \ + } while(0) + +CURLU *curl_url_dup(const CURLU *in) +{ + struct Curl_URL *u = calloc(1, sizeof(struct Curl_URL)); + if(u) { + DUP(u, in, scheme); + DUP(u, in, user); + DUP(u, in, password); + DUP(u, in, options); + DUP(u, in, host); + DUP(u, in, port); + DUP(u, in, path); + DUP(u, in, query); + DUP(u, in, fragment); + DUP(u, in, zoneid); + u->portnum = in->portnum; + u->fragment_present = in->fragment_present; + u->query_present = in->query_present; + } + return u; +fail: + curl_url_cleanup(u); + return NULL; +} + +CURLUcode curl_url_get(const CURLU *u, CURLUPart what, + char **part, unsigned int flags) +{ + const char *ptr; + CURLUcode ifmissing = CURLUE_UNKNOWN_PART; + char portbuf[7]; + bool urldecode = (flags & CURLU_URLDECODE) ? 1 : 0; + bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0; + bool punycode = FALSE; + bool depunyfy = FALSE; + bool plusdecode = FALSE; + (void)flags; + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) + return CURLUE_BAD_PARTPOINTER; + *part = NULL; + + switch(what) { + case CURLUPART_SCHEME: + ptr = u->scheme; + ifmissing = CURLUE_NO_SCHEME; + urldecode = FALSE; /* never for schemes */ + if((flags & CURLU_NO_GUESS_SCHEME) && u->guessed_scheme) + return CURLUE_NO_SCHEME; + break; + case CURLUPART_USER: + ptr = u->user; + ifmissing = CURLUE_NO_USER; + break; + case CURLUPART_PASSWORD: + ptr = u->password; + ifmissing = CURLUE_NO_PASSWORD; + break; + case CURLUPART_OPTIONS: + ptr = u->options; + ifmissing = CURLUE_NO_OPTIONS; + break; + case CURLUPART_HOST: + ptr = u->host; + ifmissing = CURLUE_NO_HOST; + punycode = (flags & CURLU_PUNYCODE) ? 1 : 0; + depunyfy = (flags & CURLU_PUNY2IDN) ? 1 : 0; + break; + case CURLUPART_ZONEID: + ptr = u->zoneid; + ifmissing = CURLUE_NO_ZONEID; + break; + case CURLUPART_PORT: + ptr = u->port; + ifmissing = CURLUE_NO_PORT; + urldecode = FALSE; /* never for port */ + if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) { + /* there is no stored port number, but asked to deliver + a default one for the scheme */ + const struct Curl_handler *h = Curl_get_scheme_handler(u->scheme); + if(h) { + msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + ptr = portbuf; + } + } + else if(ptr && u->scheme) { + /* there is a stored port number, but ask to inhibit if + it matches the default one for the scheme */ + const struct Curl_handler *h = Curl_get_scheme_handler(u->scheme); + if(h && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) + ptr = NULL; + } + break; + case CURLUPART_PATH: + ptr = u->path; + if(!ptr) + ptr = "/"; + break; + case CURLUPART_QUERY: + ptr = u->query; + ifmissing = CURLUE_NO_QUERY; + plusdecode = urldecode; + if(ptr && !ptr[0] && !(flags & CURLU_GET_EMPTY)) + /* there was a blank query and the user do not ask for it */ + ptr = NULL; + break; + case CURLUPART_FRAGMENT: + ptr = u->fragment; + ifmissing = CURLUE_NO_FRAGMENT; + if(!ptr && u->fragment_present && flags & CURLU_GET_EMPTY) + /* there was a blank fragment and the user asks for it */ + ptr = ""; + break; + case CURLUPART_URL: { + char *url; + char *scheme; + char *options = u->options; + char *port = u->port; + char *allochost = NULL; + bool show_fragment = + u->fragment || (u->fragment_present && flags & CURLU_GET_EMPTY); + bool show_query = + (u->query && u->query[0]) || + (u->query_present && flags & CURLU_GET_EMPTY); + punycode = (flags & CURLU_PUNYCODE) ? 1 : 0; + depunyfy = (flags & CURLU_PUNY2IDN) ? 1 : 0; + if(u->scheme && strcasecompare("file", u->scheme)) { + url = aprintf("file://%s%s%s", + u->path, + show_fragment ? "#": "", + u->fragment ? u->fragment : ""); + } + else if(!u->host) + return CURLUE_NO_HOST; + else { + const struct Curl_handler *h = NULL; + char schemebuf[MAX_SCHEME_LEN + 5]; + if(u->scheme) + scheme = u->scheme; + else if(flags & CURLU_DEFAULT_SCHEME) + scheme = (char *) DEFAULT_SCHEME; + else + return CURLUE_NO_SCHEME; + + h = Curl_get_scheme_handler(scheme); + if(!port && (flags & CURLU_DEFAULT_PORT)) { + /* there is no stored port number, but asked to deliver + a default one for the scheme */ + if(h) { + msnprintf(portbuf, sizeof(portbuf), "%u", h->defport); + port = portbuf; + } + } + else if(port) { + /* there is a stored port number, but asked to inhibit if it matches + the default one for the scheme */ + if(h && (h->defport == u->portnum) && + (flags & CURLU_NO_DEFAULT_PORT)) + port = NULL; + } + + if(h && !(h->flags & PROTOPT_URLOPTIONS)) + options = NULL; + + if(u->host[0] == '[') { + if(u->zoneid) { + /* make it '[ host %25 zoneid ]' */ + struct dynbuf enc; + size_t hostlen = strlen(u->host); + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + if(Curl_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host, + u->zoneid)) + return CURLUE_OUT_OF_MEMORY; + allochost = Curl_dyn_ptr(&enc); + } + } + else if(urlencode) { + allochost = curl_easy_escape(NULL, u->host, 0); + if(!allochost) + return CURLUE_OUT_OF_MEMORY; + } + else if(punycode) { + if(!Curl_is_ASCII_name(u->host)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + CURLcode result = Curl_idn_decode(u->host, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; +#endif + } + } + else if(depunyfy) { + if(Curl_is_ASCII_name(u->host) && !strncmp("xn--", u->host, 4)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + CURLcode result = Curl_idn_encode(u->host, &allochost); + if(result) + /* this is the most likely error */ + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; +#endif + } + } + + if(!(flags & CURLU_NO_GUESS_SCHEME) || !u->guessed_scheme) + msnprintf(schemebuf, sizeof(schemebuf), "%s://", scheme); + else + schemebuf[0] = 0; + + url = aprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", + schemebuf, + u->user ? u->user : "", + u->password ? ":": "", + u->password ? u->password : "", + options ? ";" : "", + options ? options : "", + (u->user || u->password || options) ? "@": "", + allochost ? allochost : u->host, + port ? ":": "", + port ? port : "", + u->path ? u->path : "/", + show_query ? "?": "", + u->query ? u->query : "", + show_fragment ? "#": "", + u->fragment ? u->fragment : ""); + free(allochost); + } + if(!url) + return CURLUE_OUT_OF_MEMORY; + *part = url; + return CURLUE_OK; + } + default: + ptr = NULL; + break; + } + if(ptr) { + size_t partlen = strlen(ptr); + size_t i = 0; + *part = Curl_memdup0(ptr, partlen); + if(!*part) + return CURLUE_OUT_OF_MEMORY; + if(plusdecode) { + /* convert + to space */ + char *plus = *part; + for(i = 0; i < partlen; ++plus, i++) { + if(*plus == '+') + *plus = ' '; + } + } + if(urldecode) { + char *decoded; + size_t dlen; + /* this unconditional rejection of control bytes is documented + API behavior */ + CURLcode res = Curl_urldecode(*part, 0, &decoded, &dlen, REJECT_CTRL); + free(*part); + if(res) { + *part = NULL; + return CURLUE_URLDECODE; + } + *part = decoded; + partlen = dlen; + } + if(urlencode) { + struct dynbuf enc; + CURLUcode uc; + Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH); + uc = urlencode_str(&enc, *part, partlen, TRUE, what == CURLUPART_QUERY); + if(uc) + return uc; + free(*part); + *part = Curl_dyn_ptr(&enc); + } + else if(punycode) { + if(!Curl_is_ASCII_name(u->host)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + char *allochost; + CURLcode result = Curl_idn_decode(*part, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + free(*part); + *part = allochost; +#endif + } + } + else if(depunyfy) { + if(Curl_is_ASCII_name(u->host) && !strncmp("xn--", u->host, 4)) { +#ifndef USE_IDN + return CURLUE_LACKS_IDN; +#else + char *allochost; + CURLcode result = Curl_idn_encode(*part, &allochost); + if(result) + return (result == CURLE_OUT_OF_MEMORY) ? + CURLUE_OUT_OF_MEMORY : CURLUE_BAD_HOSTNAME; + free(*part); + *part = allochost; +#endif + } + } + + return CURLUE_OK; + } + else + return ifmissing; +} + +CURLUcode curl_url_set(CURLU *u, CURLUPart what, + const char *part, unsigned int flags) +{ + char **storep = NULL; + bool urlencode = (flags & CURLU_URLENCODE) ? 1 : 0; + bool plusencode = FALSE; + bool urlskipslash = FALSE; + bool leadingslash = FALSE; + bool appendquery = FALSE; + bool equalsencode = FALSE; + size_t nalloc; + + if(!u) + return CURLUE_BAD_HANDLE; + if(!part) { + /* setting a part to NULL clears it */ + switch(what) { + case CURLUPART_URL: + break; + case CURLUPART_SCHEME: + storep = &u->scheme; + u->guessed_scheme = FALSE; + break; + case CURLUPART_USER: + storep = &u->user; + break; + case CURLUPART_PASSWORD: + storep = &u->password; + break; + case CURLUPART_OPTIONS: + storep = &u->options; + break; + case CURLUPART_HOST: + storep = &u->host; + break; + case CURLUPART_ZONEID: + storep = &u->zoneid; + break; + case CURLUPART_PORT: + u->portnum = 0; + storep = &u->port; + break; + case CURLUPART_PATH: + storep = &u->path; + break; + case CURLUPART_QUERY: + storep = &u->query; + u->query_present = FALSE; + break; + case CURLUPART_FRAGMENT: + storep = &u->fragment; + u->fragment_present = FALSE; + break; + default: + return CURLUE_UNKNOWN_PART; + } + if(storep && *storep) { + Curl_safefree(*storep); + } + else if(!storep) { + free_urlhandle(u); + memset(u, 0, sizeof(struct Curl_URL)); + } + return CURLUE_OK; + } + + nalloc = strlen(part); + if(nalloc > CURL_MAX_INPUT_LENGTH) + /* excessive input length */ + return CURLUE_MALFORMED_INPUT; + + switch(what) { + case CURLUPART_SCHEME: { + size_t plen = strlen(part); + const char *s = part; + if((plen > MAX_SCHEME_LEN) || (plen < 1)) + /* too long or too short */ + return CURLUE_BAD_SCHEME; + /* verify that it is a fine scheme */ + if(!(flags & CURLU_NON_SUPPORT_SCHEME) && !Curl_get_scheme_handler(part)) + return CURLUE_UNSUPPORTED_SCHEME; + storep = &u->scheme; + urlencode = FALSE; /* never */ + if(ISALPHA(*s)) { + /* ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ + while(--plen) { + if(ISALNUM(*s) || (*s == '+') || (*s == '-') || (*s == '.')) + s++; /* fine */ + else + return CURLUE_BAD_SCHEME; + } + } + else + return CURLUE_BAD_SCHEME; + u->guessed_scheme = FALSE; + break; + } + case CURLUPART_USER: + storep = &u->user; + break; + case CURLUPART_PASSWORD: + storep = &u->password; + break; + case CURLUPART_OPTIONS: + storep = &u->options; + break; + case CURLUPART_HOST: + storep = &u->host; + Curl_safefree(u->zoneid); + break; + case CURLUPART_ZONEID: + storep = &u->zoneid; + break; + case CURLUPART_PORT: + if(!ISDIGIT(part[0])) + /* not a number */ + return CURLUE_BAD_PORT_NUMBER; + else { + char *tmp; + char *endp; + unsigned long port; + errno = 0; + port = strtoul(part, &endp, 10); /* must be decimal */ + if(errno || (port > 0xffff) || *endp) + /* weirdly provided number, not good! */ + return CURLUE_BAD_PORT_NUMBER; + tmp = strdup(part); + if(!tmp) + return CURLUE_OUT_OF_MEMORY; + free(u->port); + u->port = tmp; + u->portnum = (unsigned short)port; + return CURLUE_OK; + } + case CURLUPART_PATH: + urlskipslash = TRUE; + leadingslash = TRUE; /* enforce */ + storep = &u->path; + break; + case CURLUPART_QUERY: + plusencode = urlencode; + appendquery = (flags & CURLU_APPENDQUERY) ? 1 : 0; + equalsencode = appendquery; + storep = &u->query; + u->query_present = TRUE; + break; + case CURLUPART_FRAGMENT: + storep = &u->fragment; + u->fragment_present = TRUE; + break; + case CURLUPART_URL: { + /* + * Allow a new URL to replace the existing (if any) contents. + * + * If the existing contents is enough for a URL, allow a relative URL to + * replace it. + */ + CURLcode result; + CURLUcode uc; + char *oldurl; + char *redired_url; + + if(!nalloc) + /* a blank URL is not a valid URL */ + return CURLUE_MALFORMED_INPUT; + + /* if the new thing is absolute or the old one is not + * (we could not get an absolute URL in 'oldurl'), + * then replace the existing with the new. */ + if(Curl_is_absolute_url(part, NULL, 0, + flags & (CURLU_GUESS_SCHEME| + CURLU_DEFAULT_SCHEME)) + || curl_url_get(u, CURLUPART_URL, &oldurl, flags)) { + return parseurl_and_replace(part, u, flags); + } + + /* apply the relative part to create a new URL + * and replace the existing one with it. */ + result = concat_url(oldurl, part, &redired_url); + free(oldurl); + if(result) + return cc2cu(result); + + uc = parseurl_and_replace(redired_url, u, flags); + free(redired_url); + return uc; + } + default: + return CURLUE_UNKNOWN_PART; + } + DEBUGASSERT(storep); + { + const char *newp; + struct dynbuf enc; + Curl_dyn_init(&enc, nalloc * 3 + 1 + leadingslash); + + if(leadingslash && (part[0] != '/')) { + CURLcode result = Curl_dyn_addn(&enc, "/", 1); + if(result) + return cc2cu(result); + } + if(urlencode) { + const unsigned char *i; + + for(i = (const unsigned char *)part; *i; i++) { + CURLcode result; + if((*i == ' ') && plusencode) { + result = Curl_dyn_addn(&enc, "+", 1); + if(result) + return CURLUE_OUT_OF_MEMORY; + } + else if(ISUNRESERVED(*i) || + ((*i == '/') && urlskipslash) || + ((*i == '=') && equalsencode)) { + if((*i == '=') && equalsencode) + /* only skip the first equals sign */ + equalsencode = FALSE; + result = Curl_dyn_addn(&enc, i, 1); + if(result) + return cc2cu(result); + } + else { + char out[3]={'%'}; + out[1] = hexdigits[*i >> 4]; + out[2] = hexdigits[*i & 0xf]; + result = Curl_dyn_addn(&enc, out, 3); + if(result) + return cc2cu(result); + } + } + } + else { + char *p; + CURLcode result = Curl_dyn_add(&enc, part); + if(result) + return cc2cu(result); + p = Curl_dyn_ptr(&enc); + while(*p) { + /* make sure percent encoded are lower case */ + if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) && + (ISUPPER(p[1]) || ISUPPER(p[2]))) { + p[1] = Curl_raw_tolower(p[1]); + p[2] = Curl_raw_tolower(p[2]); + p += 3; + } + else + p++; + } + } + newp = Curl_dyn_ptr(&enc); + + if(appendquery && newp) { + /* Append the 'newp' string onto the old query. Add a '&' separator if + none is present at the end of the existing query already */ + + size_t querylen = u->query ? strlen(u->query) : 0; + bool addamperand = querylen && (u->query[querylen -1] != '&'); + if(querylen) { + struct dynbuf qbuf; + Curl_dyn_init(&qbuf, CURL_MAX_INPUT_LENGTH); + + if(Curl_dyn_addn(&qbuf, u->query, querylen)) /* add original query */ + goto nomem; + + if(addamperand) { + if(Curl_dyn_addn(&qbuf, "&", 1)) + goto nomem; + } + if(Curl_dyn_add(&qbuf, newp)) + goto nomem; + Curl_dyn_free(&enc); + free(*storep); + *storep = Curl_dyn_ptr(&qbuf); + return CURLUE_OK; +nomem: + Curl_dyn_free(&enc); + return CURLUE_OUT_OF_MEMORY; + } + } + + else if(what == CURLUPART_HOST) { + size_t n = Curl_dyn_len(&enc); + if(!n && (flags & CURLU_NO_AUTHORITY)) { + /* Skip hostname check, it is allowed to be empty. */ + } + else { + bool bad = FALSE; + if(!n) + bad = TRUE; /* empty hostname is not okay */ + else if(!urlencode) { + /* if the host name part was not URL encoded here, it was set ready + URL encoded so we need to decode it to check */ + size_t dlen; + char *decoded = NULL; + CURLcode result = + Curl_urldecode(newp, n, &decoded, &dlen, REJECT_CTRL); + if(result || hostname_check(u, decoded, dlen)) + bad = TRUE; + free(decoded); + } + else if(hostname_check(u, (char *)newp, n)) + bad = TRUE; + if(bad) { + Curl_dyn_free(&enc); + return CURLUE_BAD_HOSTNAME; + } + } + } + + free(*storep); + *storep = (char *)newp; + } + return CURLUE_OK; +} diff --git a/local-test-curl-full-01/afc-curl/lib/ws.c b/local-test-curl-full-01/afc-curl/lib/ws.c new file mode 100644 index 0000000000000000000000000000000000000000..3d739a538a1742615e543366593f6746dd997074 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/lib/ws.c @@ -0,0 +1,1393 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + * SPDX-License-Identifier: curl + * + ***************************************************************************/ +#include "curl_setup.h" +#include + +#if !defined(CURL_DISABLE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP) + +#include "urldata.h" +#include "bufq.h" +#include "dynbuf.h" +#include "rand.h" +#include "curl_base64.h" +#include "connect.h" +#include "sendf.h" +#include "multiif.h" +#include "ws.h" +#include "easyif.h" +#include "transfer.h" +#include "select.h" +#include "nonblock.h" + +/* The last 3 #include files should be in this order */ +#include "curl_printf.h" +#include "curl_memory.h" +#include "memdebug.h" + + +#define WSBIT_FIN 0x80 +#define WSBIT_OPCODE_CONT 0 +#define WSBIT_OPCODE_TEXT (1) +#define WSBIT_OPCODE_BIN (2) +#define WSBIT_OPCODE_CLOSE (8) +#define WSBIT_OPCODE_PING (9) +#define WSBIT_OPCODE_PONG (0xa) +#define WSBIT_OPCODE_MASK (0xf) + +#define WSBIT_MASK 0x80 + +/* buffer dimensioning */ +#define WS_CHUNK_SIZE 65535 +#define WS_CHUNK_COUNT 2 + +struct ws_frame_meta { + char proto_opcode; + int flags; + const char *name; +}; + +static struct ws_frame_meta WS_FRAMES[] = { + { WSBIT_OPCODE_CONT, CURLWS_CONT, "CONT" }, + { WSBIT_OPCODE_TEXT, CURLWS_TEXT, "TEXT" }, + { WSBIT_OPCODE_BIN, CURLWS_BINARY, "BIN" }, + { WSBIT_OPCODE_CLOSE, CURLWS_CLOSE, "CLOSE" }, + { WSBIT_OPCODE_PING, CURLWS_PING, "PING" }, + { WSBIT_OPCODE_PONG, CURLWS_PONG, "PONG" }, +}; + +static const char *ws_frame_name_of_op(unsigned char proto_opcode) +{ + unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK; + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].proto_opcode == opcode) + return WS_FRAMES[i].name; + } + return "???"; +} + +static int ws_frame_op2flags(unsigned char proto_opcode) +{ + unsigned char opcode = proto_opcode & WSBIT_OPCODE_MASK; + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].proto_opcode == opcode) + return WS_FRAMES[i].flags; + } + return 0; +} + +static unsigned char ws_frame_flags2op(int flags) +{ + size_t i; + for(i = 0; i < sizeof(WS_FRAMES)/sizeof(WS_FRAMES[0]); ++i) { + if(WS_FRAMES[i].flags & flags) + return (unsigned char)WS_FRAMES[i].proto_opcode; + } + return 0; +} + +static void ws_dec_info(struct ws_decoder *dec, struct Curl_easy *data, + const char *msg) +{ + switch(dec->head_len) { + case 0: + break; + case 1: + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s]", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL"); + break; + default: + if(dec->head_len < dec->head_total) { + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s](%d/%d)", msg, + ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL", + dec->head_len, dec->head_total); + } + else { + CURL_TRC_WRITE(data, "websocket, decoded %s [%s%s payload=%" + FMT_OFF_T "/%" FMT_OFF_T "]", + msg, ws_frame_name_of_op(dec->head[0]), + (dec->head[0] & WSBIT_FIN) ? "" : " NON-FINAL", + dec->payload_offset, dec->payload_len); + } + break; + } +} + +static CURLcode ws_send_raw_blocking(CURL *data, struct websocket *ws, + const char *buffer, size_t buflen); + +typedef ssize_t ws_write_payload(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + CURLcode *err); + + +static void ws_dec_reset(struct ws_decoder *dec) +{ + dec->frame_age = 0; + dec->frame_flags = 0; + dec->payload_offset = 0; + dec->payload_len = 0; + dec->head_len = dec->head_total = 0; + dec->state = WS_DEC_INIT; +} + +static void ws_dec_init(struct ws_decoder *dec) +{ + ws_dec_reset(dec); +} + +static CURLcode ws_dec_read_head(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw) +{ + const unsigned char *inbuf; + size_t inlen; + + while(Curl_bufq_peek(inraw, &inbuf, &inlen)) { + if(dec->head_len == 0) { + dec->head[0] = *inbuf; + Curl_bufq_skip(inraw, 1); + + dec->frame_flags = ws_frame_op2flags(dec->head[0]); + if(!dec->frame_flags) { + failf(data, "WS: unknown opcode: %x", dec->head[0]); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + dec->head_len = 1; + /* ws_dec_info(dec, data, "seeing opcode"); */ + continue; + } + else if(dec->head_len == 1) { + dec->head[1] = *inbuf; + Curl_bufq_skip(inraw, 1); + dec->head_len = 2; + + if(dec->head[1] & WSBIT_MASK) { + /* A client MUST close a connection if it detects a masked frame. */ + failf(data, "WS: masked input frame"); + ws_dec_reset(dec); + return CURLE_RECV_ERROR; + } + /* How long is the frame head? */ + if(dec->head[1] == 126) { + dec->head_total = 4; + continue; + } + else if(dec->head[1] == 127) { + dec->head_total = 10; + continue; + } + else { + dec->head_total = 2; + } + } + + if(dec->head_len < dec->head_total) { + dec->head[dec->head_len] = *inbuf; + Curl_bufq_skip(inraw, 1); + ++dec->head_len; + if(dec->head_len < dec->head_total) { + /* ws_dec_info(dec, data, "decoding head"); */ + continue; + } + } + /* got the complete frame head */ + DEBUGASSERT(dec->head_len == dec->head_total); + switch(dec->head_total) { + case 2: + dec->payload_len = dec->head[1]; + break; + case 4: + dec->payload_len = (dec->head[2] << 8) | dec->head[3]; + break; + case 10: + if(dec->head[2] > 127) { + failf(data, "WS: frame length longer than 64 signed not supported"); + return CURLE_RECV_ERROR; + } + dec->payload_len = ((curl_off_t)dec->head[2] << 56) | + (curl_off_t)dec->head[3] << 48 | + (curl_off_t)dec->head[4] << 40 | + (curl_off_t)dec->head[5] << 32 | + (curl_off_t)dec->head[6] << 24 | + (curl_off_t)dec->head[7] << 16 | + (curl_off_t)dec->head[8] << 8 | + dec->head[9]; + break; + default: + /* this should never happen */ + DEBUGASSERT(0); + failf(data, "WS: unexpected frame header length"); + return CURLE_RECV_ERROR; + } + + dec->frame_age = 0; + dec->payload_offset = 0; + ws_dec_info(dec, data, "decoded"); + return CURLE_OK; + } + return CURLE_AGAIN; +} + +static CURLcode ws_dec_pass_payload(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_payload, + void *write_ctx) +{ + const unsigned char *inbuf; + size_t inlen; + ssize_t nwritten; + CURLcode result; + curl_off_t remain = dec->payload_len - dec->payload_offset; + + (void)data; + while(remain && Curl_bufq_peek(inraw, &inbuf, &inlen)) { + if((curl_off_t)inlen > remain) + inlen = (size_t)remain; + nwritten = write_payload(inbuf, inlen, dec->frame_age, dec->frame_flags, + dec->payload_offset, dec->payload_len, + write_ctx, &result); + if(nwritten < 0) + return result; + Curl_bufq_skip(inraw, (size_t)nwritten); + dec->payload_offset += (curl_off_t)nwritten; + remain = dec->payload_len - dec->payload_offset; + CURL_TRC_WRITE(data, "websocket, passed %zd bytes payload, %" + FMT_OFF_T " remain", nwritten, remain); + } + + return remain ? CURLE_AGAIN : CURLE_OK; +} + +static CURLcode ws_dec_pass(struct ws_decoder *dec, + struct Curl_easy *data, + struct bufq *inraw, + ws_write_payload *write_payload, + void *write_ctx) +{ + CURLcode result; + + if(Curl_bufq_is_empty(inraw)) + return CURLE_AGAIN; + + switch(dec->state) { + case WS_DEC_INIT: + ws_dec_reset(dec); + dec->state = WS_DEC_HEAD; + FALLTHROUGH(); + case WS_DEC_HEAD: + result = ws_dec_read_head(dec, data, inraw); + if(result) { + if(result != CURLE_AGAIN) { + infof(data, "WS: decode error %d", (int)result); + break; /* real error */ + } + /* incomplete ws frame head */ + DEBUGASSERT(Curl_bufq_is_empty(inraw)); + break; + } + /* head parsing done */ + dec->state = WS_DEC_PAYLOAD; + if(dec->payload_len == 0) { + ssize_t nwritten; + const unsigned char tmp = '\0'; + /* special case of a 0 length frame, need to write once */ + nwritten = write_payload(&tmp, 0, dec->frame_age, dec->frame_flags, + 0, 0, write_ctx, &result); + if(nwritten < 0) + return result; + dec->state = WS_DEC_INIT; + break; + } + FALLTHROUGH(); + case WS_DEC_PAYLOAD: + result = ws_dec_pass_payload(dec, data, inraw, write_payload, write_ctx); + ws_dec_info(dec, data, "passing"); + if(result) + return result; + /* paylod parsing done */ + dec->state = WS_DEC_INIT; + break; + default: + /* we covered all enums above, but some code analyzers are whimps */ + result = CURLE_FAILED_INIT; + } + return result; +} + +static void update_meta(struct websocket *ws, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + size_t cur_len) +{ + ws->frame.age = frame_age; + ws->frame.flags = frame_flags; + ws->frame.offset = payload_offset; + ws->frame.len = cur_len; + ws->frame.bytesleft = (payload_len - payload_offset - cur_len); +} + +/* WebSockets decoding client writer */ +struct ws_cw_ctx { + struct Curl_cwriter super; + struct bufq buf; +}; + +static CURLcode ws_cw_init(struct Curl_easy *data, + struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void)data; + Curl_bufq_init2(&ctx->buf, WS_CHUNK_SIZE, 1, BUFQ_OPT_SOFT_LIMIT); + return CURLE_OK; +} + +static void ws_cw_close(struct Curl_easy *data, struct Curl_cwriter *writer) +{ + struct ws_cw_ctx *ctx = writer->ctx; + (void) data; + Curl_bufq_free(&ctx->buf); +} + +struct ws_cw_dec_ctx { + struct Curl_easy *data; + struct websocket *ws; + struct Curl_cwriter *next_writer; + int cw_type; +}; + +static ssize_t ws_cw_dec_next(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *user_data, + CURLcode *err) +{ + struct ws_cw_dec_ctx *ctx = user_data; + struct Curl_easy *data = ctx->data; + struct websocket *ws = ctx->ws; + curl_off_t remain = (payload_len - (payload_offset + buflen)); + + (void)frame_age; + if((frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + size_t bytes; + infof(data, "WS: auto-respond to PING with a PONG"); + /* send back the exact same content as a PONG */ + *err = curl_ws_send(data, buf, buflen, &bytes, 0, CURLWS_PONG); + if(*err) + return -1; + } + else if(buflen || !remain) { + /* forward the decoded frame to the next client writer. */ + update_meta(ws, frame_age, frame_flags, payload_offset, + payload_len, buflen); + + *err = Curl_cwriter_write(data, ctx->next_writer, ctx->cw_type, + (const char *)buf, buflen); + if(*err) + return -1; + } + *err = CURLE_OK; + return (ssize_t)buflen; +} + +static CURLcode ws_cw_write(struct Curl_easy *data, + struct Curl_cwriter *writer, int type, + const char *buf, size_t nbytes) +{ + struct ws_cw_ctx *ctx = writer->ctx; + struct websocket *ws; + CURLcode result; + + if(!(type & CLIENTWRITE_BODY) || data->set.ws_raw_mode) + return Curl_cwriter_write(data, writer->next, type, buf, nbytes); + + ws = data->conn->proto.ws; + if(!ws) { + failf(data, "WS: not a websocket transfer"); + return CURLE_FAILED_INIT; + } + + if(nbytes) { + ssize_t nwritten; + nwritten = Curl_bufq_write(&ctx->buf, (const unsigned char *)buf, + nbytes, &result); + if(nwritten < 0) { + infof(data, "WS: error adding data to buffer %d", result); + return result; + } + } + + while(!Curl_bufq_is_empty(&ctx->buf)) { + struct ws_cw_dec_ctx pass_ctx; + pass_ctx.data = data; + pass_ctx.ws = ws; + pass_ctx.next_writer = writer->next; + pass_ctx.cw_type = type; + result = ws_dec_pass(&ws->dec, data, &ctx->buf, + ws_cw_dec_next, &pass_ctx); + if(result == CURLE_AGAIN) { + /* insufficient amount of data, keep it for later. + * we pretend to have written all since we have a copy */ + CURL_TRC_WRITE(data, "websocket, buffered incomplete frame head"); + return CURLE_OK; + } + else if(result) { + infof(data, "WS: decode error %d", (int)result); + return result; + } + } + + if((type & CLIENTWRITE_EOS) && !Curl_bufq_is_empty(&ctx->buf)) { + infof(data, "WS: decode ending with %zd frame bytes remaining", + Curl_bufq_len(&ctx->buf)); + return CURLE_RECV_ERROR; + } + + return CURLE_OK; +} + +/* WebSocket payload decoding client writer. */ +static const struct Curl_cwtype ws_cw_decode = { + "ws-decode", + NULL, + ws_cw_init, + ws_cw_write, + ws_cw_close, + sizeof(struct ws_cw_ctx) +}; + + +static void ws_enc_info(struct ws_encoder *enc, struct Curl_easy *data, + const char *msg) +{ + infof(data, "WS-ENC: %s [%s%s%s payload=%" FMT_OFF_T "/%" FMT_OFF_T "]", + msg, ws_frame_name_of_op(enc->firstbyte), + (enc->firstbyte & WSBIT_OPCODE_MASK) == WSBIT_OPCODE_CONT ? + " CONT" : "", + (enc->firstbyte & WSBIT_FIN) ? "" : " NON-FIN", + enc->payload_len - enc->payload_remain, enc->payload_len); +} + +static void ws_enc_reset(struct ws_encoder *enc) +{ + enc->payload_remain = 0; + enc->xori = 0; + enc->contfragment = FALSE; +} + +static void ws_enc_init(struct ws_encoder *enc) +{ + ws_enc_reset(enc); +} + +/*** + RFC 6455 Section 5.2 + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ +*/ + +static ssize_t ws_enc_write_head(struct Curl_easy *data, + struct ws_encoder *enc, + unsigned int flags, + curl_off_t payload_len, + struct bufq *out, + CURLcode *err) +{ + unsigned char firstbyte = 0; + unsigned char opcode; + unsigned char head[14]; + size_t hlen; + ssize_t n; + + if(payload_len < 0) { + failf(data, "WS: starting new frame with negative payload length %" + FMT_OFF_T, payload_len); + *err = CURLE_SEND_ERROR; + return -1; + } + + if(enc->payload_remain > 0) { + /* trying to write a new frame before the previous one is finished */ + failf(data, "WS: starting new frame with %zd bytes from last one " + "remaining to be sent", (ssize_t)enc->payload_remain); + *err = CURLE_SEND_ERROR; + return -1; + } + + opcode = ws_frame_flags2op((int)flags & ~CURLWS_CONT); + if(!opcode) { + failf(data, "WS: provided flags not recognized '%x'", flags); + *err = CURLE_SEND_ERROR; + return -1; + } + + if(!(flags & CURLWS_CONT)) { + if(!enc->contfragment) + /* not marked as continuing, this is the final fragment */ + firstbyte |= WSBIT_FIN | opcode; + else + /* marked as continuing, this is the final fragment; set CONT + opcode and FIN bit */ + firstbyte |= WSBIT_FIN | WSBIT_OPCODE_CONT; + + enc->contfragment = FALSE; + } + else if(enc->contfragment) { + /* the previous fragment was not a final one and this is not either, keep a + CONT opcode and no FIN bit */ + firstbyte |= WSBIT_OPCODE_CONT; + } + else { + firstbyte = opcode; + enc->contfragment = TRUE; + } + + head[0] = enc->firstbyte = firstbyte; + if(payload_len > 65535) { + head[1] = 127 | WSBIT_MASK; + head[2] = (unsigned char)((payload_len >> 56) & 0xff); + head[3] = (unsigned char)((payload_len >> 48) & 0xff); + head[4] = (unsigned char)((payload_len >> 40) & 0xff); + head[5] = (unsigned char)((payload_len >> 32) & 0xff); + head[6] = (unsigned char)((payload_len >> 24) & 0xff); + head[7] = (unsigned char)((payload_len >> 16) & 0xff); + head[8] = (unsigned char)((payload_len >> 8) & 0xff); + head[9] = (unsigned char)(payload_len & 0xff); + hlen = 10; + } + else if(payload_len >= 126) { + head[1] = 126 | WSBIT_MASK; + head[2] = (unsigned char)((payload_len >> 8) & 0xff); + head[3] = (unsigned char)(payload_len & 0xff); + hlen = 4; + } + else { + head[1] = (unsigned char)payload_len | WSBIT_MASK; + hlen = 2; + } + + enc->payload_remain = enc->payload_len = payload_len; + ws_enc_info(enc, data, "sending"); + + /* add 4 bytes mask */ + memcpy(&head[hlen], &enc->mask, 4); + hlen += 4; + /* reset for payload to come */ + enc->xori = 0; + + n = Curl_bufq_write(out, head, hlen, err); + if(n < 0) + return -1; + if((size_t)n != hlen) { + /* We use a bufq with SOFT_LIMIT, writing should always succeed */ + DEBUGASSERT(0); + *err = CURLE_SEND_ERROR; + return -1; + } + return n; +} + +static ssize_t ws_enc_write_payload(struct ws_encoder *enc, + struct Curl_easy *data, + const unsigned char *buf, size_t buflen, + struct bufq *out, CURLcode *err) +{ + ssize_t n; + size_t i, len; + + if(Curl_bufq_is_full(out)) { + *err = CURLE_AGAIN; + return -1; + } + + /* not the most performant way to do this */ + len = buflen; + if((curl_off_t)len > enc->payload_remain) + len = (size_t)enc->payload_remain; + + for(i = 0; i < len; ++i) { + unsigned char c = buf[i] ^ enc->mask[enc->xori]; + n = Curl_bufq_write(out, &c, 1, err); + if(n < 0) { + if((*err != CURLE_AGAIN) || !i) + return -1; + break; + } + enc->xori++; + enc->xori &= 3; + } + enc->payload_remain -= (curl_off_t)i; + ws_enc_info(enc, data, "buffered"); + return (ssize_t)i; +} + + +struct wsfield { + const char *name; + const char *val; +}; + +CURLcode Curl_ws_request(struct Curl_easy *data, REQTYPE *req) +{ + unsigned int i; + CURLcode result = CURLE_OK; + unsigned char rand[16]; + char *randstr; + size_t randlen; + char keyval[40]; + struct SingleRequest *k = &data->req; + struct wsfield heads[]= { + { + /* The request MUST contain an |Upgrade| header field whose value + MUST include the "websocket" keyword. */ + "Upgrade:", "websocket" + }, + { + /* The request MUST contain a |Connection| header field whose value + MUST include the "Upgrade" token. */ + "Connection:", "Upgrade", + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Version|. The value of this header field MUST be + 13. */ + "Sec-WebSocket-Version:", "13", + }, + { + /* The request MUST include a header field with the name + |Sec-WebSocket-Key|. The value of this header field MUST be a nonce + consisting of a randomly selected 16-byte value that has been + base64-encoded (see Section 4 of [RFC4648]). The nonce MUST be + selected randomly for each connection. */ + "Sec-WebSocket-Key:", NULL, + } + }; + heads[3].val = &keyval[0]; + + /* 16 bytes random */ + result = Curl_rand(data, (unsigned char *)rand, sizeof(rand)); + if(result) + return result; + result = Curl_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen); + if(result) + return result; + DEBUGASSERT(randlen < sizeof(keyval)); + if(randlen >= sizeof(keyval)) { + free(randstr); + return CURLE_FAILED_INIT; + } + strcpy(keyval, randstr); + free(randstr); + for(i = 0; !result && (i < sizeof(heads)/sizeof(heads[0])); i++) { + if(!Curl_checkheaders(data, STRCONST(heads[i].name))) { +#ifdef USE_HYPER + char field[128]; + msnprintf(field, sizeof(field), "%s %s", heads[i].name, + heads[i].val); + result = Curl_hyper_header(data, req, field); +#else + (void)data; + result = Curl_dyn_addf(req, "%s %s\r\n", heads[i].name, + heads[i].val); +#endif + } + } + k->upgr101 = UPGR101_WS; + return result; +} + +/* + * 'nread' is number of bytes of websocket data already in the buffer at + * 'mem'. + */ +CURLcode Curl_ws_accept(struct Curl_easy *data, + const char *mem, size_t nread) +{ + struct SingleRequest *k = &data->req; + struct websocket *ws; + struct Curl_cwriter *ws_dec_writer; + CURLcode result; + + DEBUGASSERT(data->conn); + ws = data->conn->proto.ws; + if(!ws) { + size_t chunk_size = WS_CHUNK_SIZE; + ws = calloc(1, sizeof(*ws)); + if(!ws) + return CURLE_OUT_OF_MEMORY; + data->conn->proto.ws = ws; +#ifdef DEBUGBUILD + { + char *p = getenv("CURL_WS_CHUNK_SIZE"); + if(p) { + long l = strtol(p, NULL, 10); + if(l > 0 && l <= (1*1024*1024)) { + chunk_size = (size_t)l; + } + } + } +#endif + CURL_TRC_WS(data, "WS, using chunk size %zu", chunk_size); + Curl_bufq_init2(&ws->recvbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + Curl_bufq_init2(&ws->sendbuf, chunk_size, WS_CHUNK_COUNT, + BUFQ_OPT_SOFT_LIMIT); + ws_dec_init(&ws->dec); + ws_enc_init(&ws->enc); + } + else { + Curl_bufq_reset(&ws->recvbuf); + ws_dec_reset(&ws->dec); + ws_enc_reset(&ws->enc); + } + /* Verify the Sec-WebSocket-Accept response. + + The sent value is the base64 encoded version of a SHA-1 hash done on the + |Sec-WebSocket-Key| header field concatenated with + the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11". + */ + + /* If the response includes a |Sec-WebSocket-Extensions| header field and + this header field indicates the use of an extension that was not present + in the client's handshake (the server has indicated an extension not + requested by the client), the client MUST Fail the WebSocket Connection. + */ + + /* If the response includes a |Sec-WebSocket-Protocol| header field + and this header field indicates the use of a subprotocol that was + not present in the client's handshake (the server has indicated a + subprotocol not requested by the client), the client MUST Fail + the WebSocket Connection. */ + + /* 4 bytes random */ + + result = Curl_rand(data, (unsigned char *)&ws->enc.mask, + sizeof(ws->enc.mask)); + if(result) + return result; + infof(data, "Received 101, switch to WebSocket; mask %02x%02x%02x%02x", + ws->enc.mask[0], ws->enc.mask[1], ws->enc.mask[2], ws->enc.mask[3]); + + /* Install our client writer that decodes WS frames payload */ + result = Curl_cwriter_create(&ws_dec_writer, data, &ws_cw_decode, + CURL_CW_CONTENT_DECODE); + if(result) + return result; + + result = Curl_cwriter_add(data, ws_dec_writer); + if(result) { + Curl_cwriter_free(data, ws_dec_writer); + return result; + } + + if(data->set.connect_only) { + ssize_t nwritten; + /* In CONNECT_ONLY setup, the payloads from `mem` need to be received + * when using `curl_ws_recv` later on after this transfer is already + * marked as DONE. */ + nwritten = Curl_bufq_write(&ws->recvbuf, (const unsigned char *)mem, + nread, &result); + if(nwritten < 0) + return result; + infof(data, "%zu bytes websocket payload", nread); + } + else { /* !connect_only */ + /* And pass any additional data to the writers */ + if(nread) { + result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)mem, nread); + } + } + k->upgr101 = UPGR101_RECEIVED; + + return result; +} + +struct ws_collect { + struct Curl_easy *data; + unsigned char *buffer; + size_t buflen; + size_t bufidx; + int frame_age; + int frame_flags; + curl_off_t payload_offset; + curl_off_t payload_len; + bool written; +}; + +static ssize_t ws_client_collect(const unsigned char *buf, size_t buflen, + int frame_age, int frame_flags, + curl_off_t payload_offset, + curl_off_t payload_len, + void *userp, + CURLcode *err) +{ + struct ws_collect *ctx = userp; + size_t nwritten; + curl_off_t remain = (payload_len - (payload_offset + buflen)); + + if(!ctx->bufidx) { + /* first write */ + ctx->frame_age = frame_age; + ctx->frame_flags = frame_flags; + ctx->payload_offset = payload_offset; + ctx->payload_len = payload_len; + } + + if((frame_flags & CURLWS_PING) && !remain) { + /* auto-respond to PINGs, only works for single-frame payloads atm */ + size_t bytes; + infof(ctx->data, "WS: auto-respond to PING with a PONG"); + /* send back the exact same content as a PONG */ + *err = curl_ws_send(ctx->data, buf, buflen, &bytes, 0, CURLWS_PONG); + if(*err) + return -1; + nwritten = bytes; + } + else { + ctx->written = TRUE; + DEBUGASSERT(ctx->buflen >= ctx->bufidx); + nwritten = CURLMIN(buflen, ctx->buflen - ctx->bufidx); + if(!nwritten) { + if(!buflen) { /* 0 length write, we accept that */ + *err = CURLE_OK; + return 0; + } + *err = CURLE_AGAIN; /* no more space */ + return -1; + } + *err = CURLE_OK; + memcpy(ctx->buffer + ctx->bufidx, buf, nwritten); + ctx->bufidx += nwritten; + } + return nwritten; +} + +static ssize_t nw_in_recv(void *reader_ctx, + unsigned char *buf, size_t buflen, + CURLcode *err) +{ + struct Curl_easy *data = reader_ctx; + size_t nread; + + *err = curl_easy_recv(data, buf, buflen, &nread); + if(*err) + return -1; + return (ssize_t)nread; +} + +CURL_EXTERN CURLcode curl_ws_recv(CURL *d, void *buffer, + size_t buflen, size_t *nread, + const struct curl_ws_frame **metap) +{ + struct Curl_easy *data = d; + struct connectdata *conn = data->conn; + struct websocket *ws; + struct ws_collect ctx; + + *nread = 0; + *metap = NULL; + + if(!conn) { + /* Unhappy hack with lifetimes of transfers and connection */ + if(!data->set.connect_only) { + failf(data, "CONNECT_ONLY is required"); + return CURLE_UNSUPPORTED_PROTOCOL; + } + + Curl_getconnectinfo(data, &conn); + if(!conn) { + failf(data, "connection not found"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + } + ws = conn->proto.ws; + if(!ws) { + failf(data, "connection is not setup for websocket"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + + + memset(&ctx, 0, sizeof(ctx)); + ctx.data = data; + ctx.buffer = buffer; + ctx.buflen = buflen; + + while(1) { + CURLcode result; + + /* receive more when our buffer is empty */ + if(Curl_bufq_is_empty(&ws->recvbuf)) { + ssize_t n = Curl_bufq_slurp(&ws->recvbuf, nw_in_recv, data, &result); + if(n < 0) { + return result; + } + else if(n == 0) { + /* connection closed */ + infof(data, "connection expectedly closed?"); + return CURLE_GOT_NOTHING; + } + CURL_TRC_WS(data, "curl_ws_recv, added %zu bytes from network", + Curl_bufq_len(&ws->recvbuf)); + } + + result = ws_dec_pass(&ws->dec, data, &ws->recvbuf, + ws_client_collect, &ctx); + if(result == CURLE_AGAIN) { + if(!ctx.written) { + ws_dec_info(&ws->dec, data, "need more input"); + continue; /* nothing written, try more input */ + } + break; + } + else if(result) { + return result; + } + else if(ctx.written) { + /* The decoded frame is passed back to our caller. + * There are frames like PING were we auto-respond to and + * that we do not return. For these `ctx.written` is not set. */ + break; + } + } + + /* update frame information to be passed back */ + update_meta(ws, ctx.frame_age, ctx.frame_flags, ctx.payload_offset, + ctx.payload_len, ctx.bufidx); + *metap = &ws->frame; + *nread = ws->frame.len; + CURL_TRC_WS(data, "curl_ws_recv(len=%zu) -> %zu bytes (frame at %" + FMT_OFF_T ", %" FMT_OFF_T " left)", + buflen, *nread, ws->frame.offset, ws->frame.bytesleft); + return CURLE_OK; +} + +static CURLcode ws_flush(struct Curl_easy *data, struct websocket *ws, + bool blocking) +{ + if(!Curl_bufq_is_empty(&ws->sendbuf)) { + CURLcode result; + const unsigned char *out; + size_t outlen, n; + + while(Curl_bufq_peek(&ws->sendbuf, &out, &outlen)) { + if(blocking) { + result = ws_send_raw_blocking(data, ws, (char *)out, outlen); + n = result ? 0 : outlen; + } + else if(data->set.connect_only || Curl_is_in_callback(data)) + result = Curl_senddata(data, out, outlen, &n); + else { + result = Curl_xfer_send(data, out, outlen, FALSE, &n); + if(!result && !n && outlen) + result = CURLE_AGAIN; + } + + if(result == CURLE_AGAIN) { + CURL_TRC_WS(data, "flush EAGAIN, %zu bytes remain in buffer", + Curl_bufq_len(&ws->sendbuf)); + return result; + } + else if(result) { + failf(data, "WS: flush, write error %d", result); + return result; + } + else { + infof(data, "WS: flushed %zu bytes", n); + Curl_bufq_skip(&ws->sendbuf, n); + } + } + } + return CURLE_OK; +} + +static CURLcode ws_send_raw_blocking(CURL *d, struct websocket *ws, + const char *buffer, size_t buflen) +{ + CURLcode result = CURLE_OK; + size_t nwritten; + struct Curl_easy *data = d; + + (void)ws; + while(buflen) { + result = Curl_xfer_send(data, buffer, buflen, FALSE, &nwritten); + if(result) + return result; + DEBUGASSERT(nwritten <= buflen); + buffer += nwritten; + buflen -= nwritten; + if(buflen) { + curl_socket_t sock = data->conn->sock[FIRSTSOCKET]; + timediff_t left_ms; + int ev; + + CURL_TRC_WS(data, "ws_send_raw_blocking() partial, %zu left to send", + buflen); + left_ms = Curl_timeleft(data, NULL, FALSE); + if(left_ms < 0) { + failf(data, "Timeout waiting for socket becoming writable"); + return CURLE_SEND_ERROR; + } + + /* POLLOUT socket */ + if(sock == CURL_SOCKET_BAD) + return CURLE_SEND_ERROR; + ev = Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, sock, + left_ms ? left_ms : 500); + if(ev < 0) { + failf(data, "Error while waiting for socket becoming writable"); + return CURLE_SEND_ERROR; + } + } + } + return result; +} + +static CURLcode ws_send_raw(struct Curl_easy *data, const void *buffer, + size_t buflen, size_t *pnwritten) +{ + struct websocket *ws = data->conn->proto.ws; + CURLcode result; + + if(!ws) { + failf(data, "Not a websocket transfer"); + return CURLE_SEND_ERROR; + } + if(!buflen) + return CURLE_OK; + + if(Curl_is_in_callback(data)) { + /* When invoked from inside callbacks, we do a blocking send as the + * callback will probably not implement partial writes that may then + * mess up the ws framing subsequently. + * We need any pending data to be flushed before sending. */ + result = ws_flush(data, ws, TRUE); + if(result) + return result; + result = ws_send_raw_blocking(data, ws, buffer, buflen); + } + else { + /* We need any pending data to be sent or EAGAIN this call. */ + result = ws_flush(data, ws, FALSE); + if(result) + return result; + result = Curl_senddata(data, buffer, buflen, pnwritten); + } + + CURL_TRC_WS(data, "ws_send_raw(len=%zu) -> %d, %zu", + buflen, result, *pnwritten); + return result; +} + +CURL_EXTERN CURLcode curl_ws_send(CURL *d, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + struct websocket *ws; + ssize_t n; + size_t space, payload_added; + CURLcode result; + struct Curl_easy *data = d; + + CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T + ", flags=%x), raw=%d", + buflen, fragsize, flags, data->set.ws_raw_mode); + *sent = 0; + if(!data->conn && data->set.connect_only) { + result = Curl_connect_only_attach(data); + if(result) + goto out; + } + if(!data->conn) { + failf(data, "No associated connection"); + result = CURLE_SEND_ERROR; + goto out; + } + if(!data->conn->proto.ws) { + failf(data, "Not a websocket transfer"); + result = CURLE_SEND_ERROR; + goto out; + } + ws = data->conn->proto.ws; + + /* try flushing any content still waiting to be sent. */ + result = ws_flush(data, ws, FALSE); + if(result) + goto out; + + if(data->set.ws_raw_mode) { + /* In raw mode, we write directly to the connection */ + if(fragsize || flags) { + failf(data, "ws_send, raw mode: fragsize and flags cannot be non-zero"); + return CURLE_BAD_FUNCTION_ARGUMENT; + } + result = ws_send_raw(data, buffer, buflen, sent); + goto out; + } + + /* Not RAW mode, buf we do the frame encoding */ + space = Curl_bufq_space(&ws->sendbuf); + CURL_TRC_WS(data, "curl_ws_send(len=%zu), sendbuf=%zu space_left=%zu", + buflen, Curl_bufq_len(&ws->sendbuf), space); + if(space < 14) { + result = CURLE_AGAIN; + goto out; + } + + if(flags & CURLWS_OFFSET) { + if(fragsize) { + /* a frame series 'fragsize' bytes big, this is the first */ + n = ws_enc_write_head(data, &ws->enc, flags, fragsize, + &ws->sendbuf, &result); + if(n < 0) + goto out; + } + else { + if((curl_off_t)buflen > ws->enc.payload_remain) { + infof(data, "WS: unaligned frame size (sending %zu instead of %" + FMT_OFF_T ")", + buflen, ws->enc.payload_remain); + } + } + } + else if(!ws->enc.payload_remain) { + n = ws_enc_write_head(data, &ws->enc, flags, (curl_off_t)buflen, + &ws->sendbuf, &result); + if(n < 0) + goto out; + } + + n = ws_enc_write_payload(&ws->enc, data, + buffer, buflen, &ws->sendbuf, &result); + if(n < 0) + goto out; + payload_added = (size_t)n; + + while(!result && (buflen || !Curl_bufq_is_empty(&ws->sendbuf))) { + /* flush, blocking when in callback */ + result = ws_flush(data, ws, Curl_is_in_callback(data)); + if(!result) { + DEBUGASSERT(payload_added <= buflen); + /* all buffered data sent. Try sending the rest if there is any. */ + *sent += payload_added; + buffer = (const char *)buffer + payload_added; + buflen -= payload_added; + payload_added = 0; + if(buflen) { + n = ws_enc_write_payload(&ws->enc, data, + buffer, buflen, &ws->sendbuf, &result); + if(n < 0) + goto out; + payload_added = Curl_bufq_len(&ws->sendbuf); + } + } + else if(result == CURLE_AGAIN) { + /* partially sent. how much of the call data has been part of it? what + * should we report to out caller so it can retry/send the rest? */ + if(payload_added < buflen) { + /* We did not add everything the caller wanted. Return just + * the partial write to our buffer. */ + *sent = payload_added; + result = CURLE_OK; + goto out; + } + else if(!buflen) { + /* We have no payload to report a partial write. EAGAIN would make + * the caller repeat this and add the frame again. + * Flush blocking seems the only way out of this. */ + *sent = (size_t)n; + result = ws_flush(data, ws, TRUE); + goto out; + } + /* We added the complete data to our sendbuf. Report one byte less as + * sent. This partial success should make the caller invoke us again + * with the last byte. */ + *sent = payload_added - 1; + result = Curl_bufq_unwrite(&ws->sendbuf, 1); + if(!result) + result = CURLE_AGAIN; + } + } + +out: + CURL_TRC_WS(data, "curl_ws_send(len=%zu, fragsize=%" FMT_OFF_T + ", flags=%x, raw=%d) -> %d, %zu", + buflen, fragsize, flags, data->set.ws_raw_mode, result, *sent); + return result; +} + +static void ws_free(struct connectdata *conn) +{ + if(conn && conn->proto.ws) { + Curl_bufq_free(&conn->proto.ws->recvbuf); + Curl_bufq_free(&conn->proto.ws->sendbuf); + Curl_safefree(conn->proto.ws); + } +} + +static CURLcode ws_setup_conn(struct Curl_easy *data, + struct connectdata *conn) +{ + /* WebSockets is 1.1 only (for now) */ + data->state.httpwant = CURL_HTTP_VERSION_1_1; + return Curl_http_setup_conn(data, conn); +} + + +static CURLcode ws_disconnect(struct Curl_easy *data, + struct connectdata *conn, + bool dead_connection) +{ + (void)data; + (void)dead_connection; + ws_free(conn); + return CURLE_OK; +} + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *d) +{ + /* we only return something for websocket, called from within the callback + when not using raw mode */ + struct Curl_easy *data = d; + if(GOOD_EASY_HANDLE(data) && Curl_is_in_callback(data) && data->conn && + data->conn->proto.ws && !data->set.ws_raw_mode) + return &data->conn->proto.ws->frame; + return NULL; +} + +const struct Curl_handler Curl_handler_ws = { + "WS", /* scheme */ + ws_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ws_disconnect, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTP, /* defport */ + CURLPROTO_WS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL +}; + +#ifdef USE_SSL +const struct Curl_handler Curl_handler_wss = { + "WSS", /* scheme */ + ws_setup_conn, /* setup_connection */ + Curl_http, /* do_it */ + Curl_http_done, /* done */ + ZERO_NULL, /* do_more */ + Curl_http_connect, /* connect_it */ + NULL, /* connecting */ + ZERO_NULL, /* doing */ + NULL, /* proto_getsock */ + Curl_http_getsock_do, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ws_disconnect, /* disconnect */ + Curl_http_write_resp, /* write_resp */ + Curl_http_write_resp_hd, /* write_resp_hd */ + ZERO_NULL, /* connection_check */ + ZERO_NULL, /* attach connection */ + PORT_HTTPS, /* defport */ + CURLPROTO_WSS, /* protocol */ + CURLPROTO_HTTP, /* family */ + PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | /* flags */ + PROTOPT_USERPWDCTRL +}; +#endif + + +#else + +CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen, + size_t *nread, + const struct curl_ws_frame **metap) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)nread; + (void)metap; + return CURLE_NOT_BUILT_IN; +} + +CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer, + size_t buflen, size_t *sent, + curl_off_t fragsize, + unsigned int flags) +{ + (void)curl; + (void)buffer; + (void)buflen; + (void)sent; + (void)fragsize; + (void)flags; + return CURLE_NOT_BUILT_IN; +} + +CURL_EXTERN const struct curl_ws_frame *curl_ws_meta(CURL *data) +{ + (void)data; + return NULL; +} +#endif /* !CURL_DISABLE_WEBSOCKETS */ diff --git a/local-test-curl-full-01/afc-curl/scripts/Makefile.am b/local-test-curl-full-01/afc-curl/scripts/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..4454d42cf23ed6271e7fc305da4aca4f141dcc28 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/Makefile.am @@ -0,0 +1,83 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +EXTRA_DIST = coverage.sh completion.pl firefox-db2pem.sh checksrc.pl \ + mk-ca-bundle.pl mk-unity.pl schemetable.c cd2nroff nroff2cd cdall cd2cd managen \ + dmaketgz maketgz release-tools.sh verify-release cmakelint.sh + +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +FISH_FUNCTIONS_DIR = @FISH_FUNCTIONS_DIR@ +PERL = @PERL@ + +if USE_ZSH_COMPLETION +ZSH_COMPLETION_FUNCTION_FILENAME = _curl +endif +if USE_FISH_COMPLETION +FISH_COMPLETION_FUNCTION_FILENAME = curl.fish +endif + +CLEANFILES = $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) + +all-local: $(ZSH_COMPLETION_FUNCTION_FILENAME) $(FISH_COMPLETION_FUNCTION_FILENAME) + +if USE_ZSH_COMPLETION +$(ZSH_COMPLETION_FUNCTION_FILENAME): completion.pl +if CROSSCOMPILING + @echo "NOTICE: we can't generate zsh completion when cross-compiling!" +else # if not cross-compiling: + if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ + $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell zsh > $@ ; fi +endif +endif + +if USE_FISH_COMPLETION +$(FISH_COMPLETION_FUNCTION_FILENAME): completion.pl +if CROSSCOMPILING + @echo "NOTICE: we can't generate fish completion when cross-compiling!" +else # if not cross-compiling: + if test -z "$(PERL)"; then echo "No perl: can't install completion script"; else \ + $(PERL) $(srcdir)/completion.pl --curl $(top_builddir)/src/curl$(EXEEXT) --shell fish > $@ ; fi +endif +endif + +install-data-local: +if CROSSCOMPILING + @echo "NOTICE: we can't install completion scripts when cross-compiling!" +else # if not cross-compiling: +if USE_ZSH_COMPLETION + if test -n "$(PERL)"; then \ + $(MKDIR_P) $(DESTDIR)$(ZSH_FUNCTIONS_DIR); \ + $(INSTALL_DATA) $(ZSH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(ZSH_FUNCTIONS_DIR)/$(ZSH_COMPLETION_FUNCTION_FILENAME) ; \ + fi +endif +if USE_FISH_COMPLETION + if test -n "$(PERL)"; then \ + $(MKDIR_P) $(DESTDIR)$(FISH_FUNCTIONS_DIR); \ + $(INSTALL_DATA) $(FISH_COMPLETION_FUNCTION_FILENAME) $(DESTDIR)$(FISH_FUNCTIONS_DIR)/$(FISH_COMPLETION_FUNCTION_FILENAME) ; \ + fi +endif +endif + +distclean: + rm -f $(CLEANFILES) diff --git a/local-test-curl-full-01/afc-curl/scripts/cd2cd b/local-test-curl-full-01/afc-curl/scripts/cd2cd new file mode 100644 index 0000000000000000000000000000000000000000..a4de2f8757f410516e7b52758d0d816671c79e15 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/cd2cd @@ -0,0 +1,226 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +This script updates a curldown file to current/better curldown. + +Example: cd2cd [--in-place] > + +--in-place: if used, it replaces the original file with the cleaned up + version. When this is used, cd2cd accepts multiple files to work + on and it ignores errors on single files. + +=end comment +=cut + +my $cd2cd = "0.1"; # to keep check +my $dir; +my $extension; +my $inplace = 0; + +while(1) { + if($ARGV[0] eq "--in-place") { + shift @ARGV; + $inplace = 1; + } + else { + last; + } +} + + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = localtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%B %d %Y", @ts; + +sub outseealso { + my (@sa) = @_; + my $comma = 0; + my @o; + push @o, ".SH SEE ALSO\n"; + for my $s (sort @sa) { + push @o, sprintf "%s.BR $s", $comma ? ",\n": ""; + $comma = 1; + } + push @o, "\n"; + return @o; +} + +sub single { + my @head; + my @seealso; + my ($f)=@_; + my $title; + my $section; + my $source; + my $start = 0; + my $d; + my $line = 0; + open(F, "<:crlf", "$f") || + return 1; + while() { + $line++; + $d = $_; + if(!$start) { + if(/^---/) { + # header starts here + $start = 1; + push @head, $d; + } + next; + } + if(/^Title: *(.*)/i) { + $title=$1; + } + elsif(/^Section: *(.*)/i) { + $section=$1; + } + elsif(/^Source: *(.*)/i) { + $source=$1; + } + elsif(/^See-also: +(.*)/i) { + $salist = 0; + push @seealso, $1; + } + elsif(/^See-also: */i) { + if($seealso[0]) { + print STDERR "$f:$line:1:ERROR: bad See-Also, needs list\n"; + return 2; + } + $salist = 1; + } + elsif(/^ +- (.*)/i) { + # the only list we support is the see-also + if($salist) { + push @seealso, $1; + } + } + # REUSE-IgnoreStart + elsif(/^C: (.*)/i) { + $copyright=$1; + } + elsif(/^SPDX-License-Identifier: (.*)/i) { + $spdx=$1; + } + # REUSE-IgnoreEnd + elsif(/^---/) { + # end of the header section + if(!$title) { + print STDERR "ERROR: no 'Title:' in $f\n"; + return 1; + } + if(!$section) { + print STDERR "ERROR: no 'Section:' in $f\n"; + return 2; + } + if(!$seealso[0]) { + print STDERR "$f:$line:1:ERROR: no 'See-also:' present\n"; + return 2; + } + if(!$copyright) { + print STDERR "$f:$line:1:ERROR: no 'C:' field present\n"; + return 2; + } + if(!$spdx) { + print STDERR "$f:$line:1:ERROR: no 'SPDX-License-Identifier:' field present\n"; + return 2; + } + last; + } + else { + chomp; + print STDERR "WARN: unrecognized line in $f, ignoring:\n:'$_';" + } + } + + if(!$start) { + print STDERR "$f:$line:1:ERROR: no header present\n"; + return 2; + } + + my @desc; + + push @desc, sprintf <, et al. +SPDX-License-Identifier: curl +Title: $title +Section: $section +Source: $source +HEAD + ; + push @desc, "See-also:\n"; + for my $s (sort @seealso) { + push @desc, " - $s\n" if($s); + } + push @desc, "---\n"; + + my $blankline = 0; + while() { + $d = $_; + $line++; + if($d =~ /^[ \t]*\n/) { + $blankline++; + } + else { + $blankline = 0; + } + # *italics* for curl symbol links get the asterisks removed + $d =~ s/\*((lib|)curl[^ ]*\(3\))\*/$1/gi; + + if(length($d) > 90) { + print STDERR "$f:$line:1:WARN: excessive line length\n"; + } + + push @desc, $d if($blankline < 2); + } + close(F); + + if($inplace) { + open(O, ">$f") || return 1; + print O @desc; + close(O); + } + else { + print @desc; + } + return 0; +} + +if($inplace) { + for my $a (@ARGV) { + # this ignores errors + single($a); + } +} +else { + exit single($ARGV[0]); +} diff --git a/local-test-curl-full-01/afc-curl/scripts/cd2nroff b/local-test-curl-full-01/afc-curl/scripts/cd2nroff new file mode 100644 index 0000000000000000000000000000000000000000..4c9050098682dc9263e180016d6149bf4b2687ea --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/cd2nroff @@ -0,0 +1,575 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +Converts a curldown file to nroff (manpage). + +=end comment +=cut + +use strict; +use warnings; + +my $cd2nroff = "0.1"; # to keep check +my $dir; +my $extension; +my $keepfilename; + +while(@ARGV) { + if($ARGV[0] eq "-d") { + shift @ARGV; + $dir = shift @ARGV; + } + elsif($ARGV[0] eq "-e") { + shift @ARGV; + $extension = shift @ARGV; + } + elsif($ARGV[0] eq "-k") { + shift @ARGV; + $keepfilename = 1; + } + elsif($ARGV[0] eq "-h") { + print < Write the output to the file name from the meta-data in the + specified directory, instead of writing to stdout +-e If -d is used, this option can provide an added "extension", arbitrary + text really, to append to the file name. +-h This help text, +-v Show version then exit +HELP + ; + exit 0; + } + elsif($ARGV[0] eq "-v") { + print "cd2nroff version $cd2nroff\n"; + exit 0; + } + else { + last; + } +} + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = gmtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%Y-%m-%d", @ts; + +sub outseealso { + my (@sa) = @_; + my $comma = 0; + my @o; + push @o, ".SH SEE ALSO\n"; + for my $s (sort @sa) { + push @o, sprintf "%s.BR $s", $comma ? ",\n": ""; + $comma = 1; + } + push @o, "\n"; + return @o; +} + +sub outprotocols { + my (@p) = @_; + my $comma = 0; + my @o; + push @o, ".SH PROTOCOLS\n"; + + if($p[0] eq "TLS") { + push @o, "This functionality affects all TLS based protocols: HTTPS, FTPS, IMAPS, POP3S, SMTPS etc."; + } + else { + my @s = sort @p; + push @o, "This functionality affects "; + for my $e (sort @s) { + push @o, sprintf "%s%s", + $comma ? (($e eq $s[-1]) ? " and " : ", "): "", + lc($e); + $comma = 1; + } + if($#s == 0) { + if($s[0] eq "All") { + push @o, " supported protocols"; + } + else { + push @o, " only"; + } + } + } + push @o, "\n"; + return @o; +} + +sub outtls { + my (@t) = @_; + my $comma = 0; + my @o; + if($t[0] eq "All") { + push @o, "\nAll TLS backends support this option."; + } + else { + push @o, "\nThis option works only with the following TLS backends:\n"; + my @s = sort @t; + for my $e (@s) { + push @o, sprintf "%s$e", + $comma ? (($e eq $s[-1]) ? " and " : ", "): ""; + $comma = 1; + } + } + push @o, "\n"; + return @o; +} + +my %knownprotos = ( + 'DICT' => 1, + 'FILE' => 1, + 'FTP' => 1, + 'FTPS' => 1, + 'GOPHER' => 1, + 'GOPHERS' => 1, + 'HTTP' => 1, + 'HTTPS' => 1, + 'IMAP' => 1, + 'IMAPS' => 1, + 'LDAP' => 1, + 'LDAPS' => 1, + 'MQTT' => 1, + 'POP3' => 1, + 'POP3S' => 1, + 'RTMP' => 1, + 'RTMPS' => 1, + 'RTSP' => 1, + 'SCP' => 1, + 'SFTP' => 1, + 'SMB' => 1, + 'SMBS' => 1, + 'SMTP' => 1, + 'SMTPS' => 1, + 'TELNET' => 1, + 'TFTP' => 1, + 'WS' => 1, + 'WSS' => 1, + 'TLS' => 1, + 'TCP' => 1, + 'QUIC' => 1, + 'All' => 1 + ); + +my %knowntls = ( + 'BearSSL' => 1, + 'GnuTLS' => 1, + 'mbedTLS' => 1, + 'OpenSSL' => 1, + 'rustls' => 1, + 'Schannel' => 1, + 'Secure Transport' => 1, + 'wolfSSL' => 1, + 'All' => 1, + ); + +sub single { + my @seealso; + my @proto; + my @tls; + my $d; + my ($f)=@_; + my $copyright; + my $errors = 0; + my $fh; + my $line; + my $list; + my $tlslist; + my $section; + my $source; + my $addedin; + my $spdx; + my $start = 0; + my $title; + + if(defined($f)) { + if(!open($fh, "<:crlf", "$f")) { + print STDERR "cd2nroff failed to open '$f' for reading: $!\n"; + return 1; + } + } + else { + $f = "STDIN"; + $fh = \*STDIN; + binmode($fh, ":crlf"); + } + while(<$fh>) { + $line++; + if(!$start) { + if(/^---/) { + # header starts here + $start = 1; + } + next; + } + if(/^Title: *(.*)/i) { + $title=$1; + } + elsif(/^Section: *(.*)/i) { + $section=$1; + } + elsif(/^Source: *(.*)/i) { + $source=$1; + } + elsif(/^See-also: +(.*)/i) { + $list = 1; # 1 for see-also + push @seealso, $1; + } + elsif(/^See-also: */i) { + if($seealso[0]) { + print STDERR "$f:$line:1:ERROR: bad See-Also, needs list\n"; + return 2; + } + $list = 1; # 1 for see-also + } + elsif(/^Protocol:/i) { + $list = 2; # 2 for protocol + } + elsif(/^TLS-backend:/i) { + $list = 3; # 3 for TLS backend + } + elsif(/^Added-in: *(.*)/i) { + $addedin=$1; + if(($addedin !~ /^[0-9.]+[0-9]\z/) && + ($addedin ne "n/a")) { + print STDERR "$f:$line:1:ERROR: invalid version number in Added-in line: $addedin\n"; + return 2; + } + } + elsif(/^ +- (.*)/i) { + # the only lists we support are see-also and protocol + if($list == 1) { + push @seealso, $1; + } + elsif($list == 2) { + push @proto, $1; + } + elsif($list == 3) { + push @tls, $1; + } + else { + print STDERR "$f:$line:1:ERROR: list item without owner?\n"; + return 2; + } + } + # REUSE-IgnoreStart + elsif(/^C: (.*)/i) { + $copyright=$1; + } + elsif(/^SPDX-License-Identifier: (.*)/i) { + $spdx=$1; + } + # REUSE-IgnoreEnd + elsif(/^---/) { + # end of the header section + if(!$title) { + print STDERR "$f:$line:1:ERROR: no 'Title:' in $f\n"; + return 1; + } + if(!$section) { + print STDERR "$f:$line:1:ERROR: no 'Section:' in $f\n"; + return 2; + } + if(!$source) { + print STDERR "$f:$line:1:ERROR: no 'Source:' in $f\n"; + return 2; + } + if(($source eq "libcurl") && !$addedin) { + print STDERR "$f:$line:1:ERROR: no 'Added-in:' in $f\n"; + return 2; + } + if(!$seealso[0]) { + print STDERR "$f:$line:1:ERROR: no 'See-also:' present\n"; + return 2; + } + if(!$copyright) { + print STDERR "$f:$line:1:ERROR: no 'C:' field present\n"; + return 2; + } + if(!$spdx) { + print STDERR "$f:$line:1:ERROR: no 'SPDX-License-Identifier:' field present\n"; + return 2; + } + if($section == 3) { + if(!$proto[0]) { + printf STDERR "$f:$line:1:ERROR: missing Protocol:\n"; + exit 2; + } + my $tls = 0; + for my $p (@proto) { + if($p eq "TLS") { + $tls = 1; + } + if(!$knownprotos{$p}) { + printf STDERR "$f:$line:1:ERROR: invalid protocol used: $p:\n"; + exit 2; + } + } + # This is for TLS, require TLS-backend: + if($tls) { + if(!$tls[0]) { + printf STDERR "$f:$line:1:ERROR: missing TLS-backend:\n"; + exit 2; + } + for my $t (@tls) { + if(!$knowntls{$t}) { + printf STDERR "$f:$line:1:ERROR: invalid TLS backend: $t:\n"; + exit 2; + } + } + } + } + last; + } + else { + chomp; + print STDERR "$f:$line:1:ERROR: unrecognized header keyword: '$_'\n"; + $errors++; + } + } + + if(!$start) { + print STDERR "$f:$line:1:ERROR: no header present\n"; + return 2; + } + + my @desc; + my $quote = 0; + my $blankline = 0; + my $header = 0; + + # cut off the leading path from the file name, if any + $f =~ s/^(.*[\\\/])//; + + push @desc, ".\\\" generated by cd2nroff $cd2nroff from $f\n"; + push @desc, ".TH $title $section \"$date\" $source\n"; + while(<$fh>) { + $line++; + + $d = $_; + + if($quote) { + if($quote == 4) { + # remove the indentation + if($d =~ /^ (.*)/) { + push @desc, "$1\n"; + next; + } + else { + # end of quote + $quote = 0; + push @desc, ".fi\n"; + next; + } + } + if(/^~~~/) { + # end of quote + $quote = 0; + push @desc, ".fi\n"; + next; + } + # convert single backslahes to doubles + $d =~ s/\\/\\\\/g; + # lines starting with a period needs it escaped + $d =~ s/^\./\\&./; + push @desc, $d; + next; + } + + # remove single line HTML comments + $d =~ s///g; + + # **bold** + $d =~ s/\*\*(\S.*?)\*\*/\\fB$1\\fP/g; + # *italics* + $d =~ s/\*(\S.*?)\*/\\fI$1\\fP/g; + + if($d =~ /[^\\][\<\>]/) { + print STDERR "$f:$line:1:ERROR: un-escaped < or > used\n"; + $errors++; + } + # convert backslash-'<' or '> to just the second character + $d =~ s/\\([<>])/$1/g; + + # mentions of curl symbols with manpages use italics by default + $d =~ s/((lib|)curl([^ ]*\(3\)))/\\fI$1\\fP/gi; + + # backticked becomes italics + $d =~ s/\`(.*?)\`/\\fI$1\\fP/g; + + if(/^## (.*)/) { + my $word = $1; + # if there are enclosing quotes, remove them first + $word =~ s/[\"\'\`](.*)[\"\'\`]\z/$1/; + + # enclose in double quotes if there is a space present + if($word =~ / /) { + push @desc, ".IP \"$word\"\n"; + } + else { + push @desc, ".IP $word\n"; + } + $header = 1; + } + elsif(/^##/) { + # end of IP sequence + push @desc, ".PP\n"; + $header = 1; + } + elsif(/^# (.*)/) { + my $word = $1; + # if there are enclosing quotes, remove them first + $word =~ s/[\"\'](.*)[\"\']\z/$1/; + + if($word eq "PROTOCOLS") { + print STDERR "$f:$line:1:WARN: PROTOCOLS section in source file\n"; + } + elsif($word eq "AVAILABILITY") { + print STDERR "$f:$line:1:WARN: AVAILABILITY section in source file\n"; + } + elsif($word eq "%PROTOCOLS%") { + # insert the generated PROTOCOLS section + push @desc, outprotocols(@proto); + + if($proto[0] eq "TLS") { + push @desc, outtls(@tls); + } + $header = 1; + next; + } + elsif($word eq "%AVAILABILITY%") { + if($addedin ne "n/a") { + # insert the generated AVAILABILITY section + push @desc, ".SH AVAILABILITY\n"; + push @desc, "Added in curl $addedin\n"; + } + $header = 1; + next; + } + push @desc, ".SH $word\n"; + $header = 1; + } + elsif(/^~~~c/) { + # start of a code section, not indented + $quote = 1; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n"; + } + elsif(/^~~~/) { + # start of a quote section; not code, not indented + $quote = 1; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n"; + } + elsif(/^ (.*)/) { + # quoted, indented by 4 space + $quote = 4; + push @desc, "\n" if($blankline && !$header); + $header = 0; + push @desc, ".nf\n$1\n"; + } + elsif(/^[ \t]*\n/) { + # count and ignore blank lines + $blankline++; + } + else { + # don't output newlines if this is the first content after a + # header + push @desc, "\n" if($blankline && !$header); + $blankline = 0; + $header = 0; + + # quote minuses in the output + $d =~ s/([^\\])-/$1\\-/g; + # replace single quotes + $d =~ s/\'/\\(aq/g; + # handle double quotes first on the line + $d =~ s/^(\s*)\"/$1\\&\"/; + + # lines starting with a period needs it escaped + $d =~ s/^\./\\&./; + + if($d =~ /^(.*) /) { + printf STDERR "$f:$line:%d:ERROR: 2 spaces detected\n", + length($1); + $errors++; + } + if($d =~ /^[ \t]*\n/) { + # replaced away all contents + $blankline= 1; + } + else { + push @desc, $d; + } + } + } + if($fh != \*STDIN) { + close($fh); + } + push @desc, outseealso(@seealso); + if($dir) { + if($keepfilename) { + $title = $f; + $title =~ s/\.[^.]*$//; + } + my $outfile = "$dir/$title.$section"; + if(defined($extension)) { + $outfile .= $extension; + } + if(!open(O, ">", $outfile)) { + print STDERR "Failed to open $outfile : $!\n"; + return 1; + } + print O @desc; + close(O); + } + else { + print @desc; + } + return $errors; +} + +if(@ARGV) { + for my $f (@ARGV) { + my $r = single($f); + if($r) { + exit $r; + } + } +} +else { + exit single(); +} diff --git a/local-test-curl-full-01/afc-curl/scripts/cdall b/local-test-curl-full-01/afc-curl/scripts/cdall new file mode 100644 index 0000000000000000000000000000000000000000..507ccc6be2515dd079f4bfd611d04d0c9ee071ca --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/cdall @@ -0,0 +1,44 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# provide all dir names to scan on the cmdline + +sub convert { + my ($dir)=@_; + opendir(my $dh, $dir) || die "could not open $dir"; + my @cd = grep { /\.md\z/ && -f "$dir/$_" } readdir($dh); + closedir $dh; + + for my $cd (@cd) { + my $nroff = "$cd"; + $nroff =~ s/\.md\z/.3/; + print "$dir/$cd = $dir/$nroff\n"; + system("./scripts/cd2nroff -d $dir $dir/$cd"); + } +} + +for my $d (sort @ARGV) { + convert($d); +} diff --git a/local-test-curl-full-01/afc-curl/scripts/checksrc.pl b/local-test-curl-full-01/afc-curl/scripts/checksrc.pl new file mode 100644 index 0000000000000000000000000000000000000000..7075278de2f7ccfb2acc03cba068f8829ffb8494 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/checksrc.pl @@ -0,0 +1,1088 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +use strict; +use warnings; + +my $max_column = 79; +my $indent = 2; + +my $warnings = 0; +my $swarnings = 0; +my $errors = 0; +my $serrors = 0; +my $suppressed; # skipped problems +my $file; +my $dir="."; +my $wlist=""; +my @alist; +my $windows_os = $^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys'; +my $verbose; +my %skiplist; + +my %ignore; +my %ignore_set; +my %ignore_used; +my @ignore_line; + +my %warnings_extended = ( + 'COPYRIGHTYEAR' => 'copyright year incorrect', + 'STRERROR', => 'strerror() detected', + 'STRNCPY', => 'strncpy() detected', + 'STDERR', => 'stderr detected', + ); + +my %warnings = ( + 'ASSIGNWITHINCONDITION' => 'assignment within conditional expression', + 'ASTERISKNOSPACE' => 'pointer declared without space before asterisk', + 'ASTERISKSPACE' => 'pointer declared with space after asterisk', + 'BADCOMMAND' => 'bad !checksrc! instruction', + 'BANNEDFUNC' => 'a banned function was used', + 'BANNEDPREPROC' => 'a banned symbol was used on a preprocessor line', + 'BRACEELSE' => '} else on the same line', + 'BRACEPOS' => 'wrong position for an open brace', + 'BRACEWHILE' => 'A single space between open brace and while', + 'COMMANOSPACE' => 'comma without following space', + 'COMMENTNOSPACEEND' => 'no space before */', + 'COMMENTNOSPACESTART' => 'no space following /*', + 'COPYRIGHT' => 'file missing a copyright statement', + 'CPPCOMMENTS' => '// comment detected', + 'DOBRACE' => 'A single space between do and open brace', + 'EMPTYLINEBRACE' => 'Empty line before the open brace', + 'EQUALSNOSPACE' => 'equals sign without following space', + 'EQUALSNULL' => 'if/while comparison with == NULL', + 'EXCLAMATIONSPACE' => 'Whitespace after exclamation mark in expression', + 'FOPENMODE' => 'fopen needs a macro for the mode string', + 'INCLUDEDUP', => 'same file is included again', + 'INDENTATION' => 'wrong start column for code', + 'LONGLINE' => "Line longer than $max_column", + 'SPACEBEFORELABEL' => 'labels not at the start of the line', + 'MULTISPACE' => 'multiple spaces used when not suitable', + 'NOSPACEAND' => 'missing space around Logical AND operator', + 'NOSPACEC' => 'missing space around ternary colon operator', + 'NOSPACEEQUALS' => 'equals sign without preceding space', + 'NOSPACEQ' => 'missing space around ternary question mark operator', + 'NOSPACETHAN' => 'missing space around less or greater than', + 'NOTEQUALSZERO', => 'if/while comparison with != 0', + 'ONELINECONDITION' => 'conditional block on the same line as the if()', + 'OPENCOMMENT' => 'file ended with a /* comment still "open"', + 'PARENBRACE' => '){ without sufficient space', + 'RETURNNOSPACE' => 'return without space', + 'SEMINOSPACE' => 'semicolon without following space', + 'SIZEOFNOPAREN' => 'use of sizeof without parentheses', + 'SNPRINTF' => 'use of snprintf', + 'SPACEAFTERPAREN' => 'space after open parenthesis', + 'SPACEBEFORECLOSE' => 'space before a close parenthesis', + 'SPACEBEFORECOMMA' => 'space before a comma', + 'SPACEBEFOREPAREN' => 'space before an open parenthesis', + 'SPACESEMICOLON' => 'space before semicolon', + 'SPACESWITCHCOLON' => 'space before colon of switch label', + 'TABS' => 'TAB characters not allowed', + 'TRAILINGSPACE' => 'Trailing whitespace on the line', + 'TYPEDEFSTRUCT' => 'typedefed struct', + 'UNUSEDIGNORE' => 'a warning ignore was not used', + ); + +sub readskiplist { + open(my $W, '<', "$dir/checksrc.skip") or return; + my @all=<$W>; + for(@all) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + $skiplist{$_}=1; + } + close($W); +} + +# Reads the .checksrc in $dir for any extended warnings to enable locally. +# Currently there is no support for disabling warnings from the standard set, +# and since that's already handled via !checksrc! commands there is probably +# little use to add it. +sub readlocalfile { + my ($file) = @_; + my $i = 0; + my $rcfile; + + if(($dir eq ".") && $file =~ /\//) { + my $ldir; + if($file =~ /(.*)\//) { + $ldir = $1; + open($rcfile, "<", "$dir/$ldir/.checksrc") or return; + } + } + else { + open($rcfile, "<", "$dir/.checksrc") or return; + } + + while(<$rcfile>) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + $i++; + + # Lines starting with '#' are considered comments + if (/^\s*(#.*)/) { + next; + } + elsif (/^\s*enable ([A-Z]+)$/) { + if(!defined($warnings_extended{$1})) { + print STDERR "invalid warning specified in .checksrc: \"$1\"\n"; + next; + } + $warnings{$1} = $warnings_extended{$1}; + } + elsif (/^\s*disable ([A-Z]+)$/) { + if(!defined($warnings{$1})) { + print STDERR "invalid warning specified in .checksrc: \"$1\"\n"; + next; + } + # Accept-list + push @alist, $1; + } + else { + die "Invalid format in $dir/.checksrc on line $i\n"; + } + } + close($rcfile); +} + +sub checkwarn { + my ($name, $num, $col, $file, $line, $msg, $error) = @_; + + my $w=$error?"error":"warning"; + my $nowarn=0; + + #if(!$warnings{$name}) { + # print STDERR "Dev! there's no description for $name!\n"; + #} + + # checksrc.skip + if($skiplist{$line}) { + $nowarn = 1; + } + # !checksrc! controlled + elsif($ignore{$name}) { + $ignore{$name}--; + $ignore_used{$name}++; + $nowarn = 1; + if(!$ignore{$name}) { + # reached zero, enable again + enable_warn($name, $num, $file, $line); + } + } + + if($nowarn) { + $suppressed++; + if($w) { + $swarnings++; + } + else { + $serrors++; + } + return; + } + + if($w) { + $warnings++; + } + else { + $errors++; + } + + $col++; + print "$file:$num:$col: $w: $msg ($name)\n"; + print " $line\n"; + + if($col < 80) { + my $pref = (' ' x $col); + print "${pref}^\n"; + } +} + +$file = shift @ARGV; + +while(defined $file) { + + if($file =~ /-D(.*)/) { + $dir = $1; + $file = shift @ARGV; + next; + } + elsif($file =~ /-W(.*)/) { + $wlist .= " $1 "; + $file = shift @ARGV; + next; + } + elsif($file =~ /-A(.+)/) { + push @alist, $1; + $file = shift @ARGV; + next; + } + elsif($file =~ /-i([1-9])/) { + $indent = $1 + 0; + $file = shift @ARGV; + next; + } + elsif($file =~ /-m([0-9]+)/) { + $max_column = $1 + 0; + $file = shift @ARGV; + next; + } + elsif($file =~ /^(-h|--help)/) { + undef $file; + last; + } + + last; +} + +if(!$file) { + print "checksrc.pl [option] [file2] ...\n"; + print " Options:\n"; + print " -A[rule] Accept this violation, can be used multiple times\n"; + print " -D[DIR] Directory to prepend file names\n"; + print " -h Show help output\n"; + print " -W[file] Skip the given file - ignore all its flaws\n"; + print " -i Indent spaces. Default: 2\n"; + print " -m Maximum line length. Default: 79\n"; + print "\nDetects and warns for these problems:\n"; + my @allw = keys %warnings; + push @allw, keys %warnings_extended; + for my $w (sort @allw) { + if($warnings{$w}) { + printf (" %-18s: %s\n", $w, $warnings{$w}); + } + else { + printf (" %-18s: %s[*]\n", $w, $warnings_extended{$w}); + } + } + print " [*] = disabled by default\n"; + exit; +} + +readskiplist(); +readlocalfile($file); + +do { + if("$wlist" !~ / $file /) { + my $fullname = $file; + $fullname = "$dir/$file" if ($fullname !~ '^\.?\.?/'); + scanfile($fullname); + } + $file = shift @ARGV; + +} while($file); + +sub accept_violations { + for my $r (@alist) { + if(!$warnings{$r}) { + print "'$r' is not a warning to accept!\n"; + exit; + } + $ignore{$r}=999999; + $ignore_used{$r}=0; + } +} + +sub checksrc_clear { + undef %ignore; + undef %ignore_set; + undef @ignore_line; +} + +sub checksrc_endoffile { + my ($file) = @_; + for(keys %ignore_set) { + if($ignore_set{$_} && !$ignore_used{$_}) { + checkwarn("UNUSEDIGNORE", $ignore_set{$_}, + length($_)+11, $file, + $ignore_line[$ignore_set{$_}], + "Unused ignore: $_"); + } + } +} + +sub enable_warn { + my ($what, $line, $file, $l) = @_; + + # switch it back on, but warn if not triggered! + if(!$ignore_used{$what}) { + checkwarn("UNUSEDIGNORE", + $line, length($what) + 11, $file, $l, + "No warning was inhibited!"); + } + $ignore_set{$what}=0; + $ignore_used{$what}=0; + $ignore{$what}=0; +} +sub checksrc { + my ($cmd, $line, $file, $l) = @_; + if($cmd =~ / *([^ ]*) *(.*)/) { + my ($enable, $what) = ($1, $2); + $what =~ s: *\*/$::; # cut off end of C comment + # print "ENABLE $enable WHAT $what\n"; + if($enable eq "disable") { + my ($warn, $scope)=($1, $2); + if($what =~ /([^ ]*) +(.*)/) { + ($warn, $scope)=($1, $2); + } + else { + $warn = $what; + $scope = 1; + } + # print "IGNORE $warn for SCOPE $scope\n"; + if($scope eq "all") { + $scope=999999; + } + + # Comparing for a literal zero rather than the scalar value zero + # covers the case where $scope contains the ending '*' from the + # comment. If we use a scalar comparison (==) we induce warnings + # on non-scalar contents. + if($scope eq "0") { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "Disable zero not supported, did you mean to enable?"); + } + elsif($ignore_set{$warn}) { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "$warn already disabled from line $ignore_set{$warn}"); + } + else { + $ignore{$warn}=$scope; + $ignore_set{$warn}=$line; + $ignore_line[$line]=$l; + } + } + elsif($enable eq "enable") { + enable_warn($what, $line, $file, $l); + } + else { + checkwarn("BADCOMMAND", + $line, 0, $file, $l, + "Illegal !checksrc! command"); + } + } +} + +sub nostrings { + my ($str) = @_; + $str =~ s/\".*\"//g; + return $str; +} + +sub scanfile { + my ($file) = @_; + + my $line = 1; + my $prevl=""; + my $prevpl=""; + my $l = ""; + my $prep = 0; + my $prevp = 0; + open(my $R, '<', $file) || die "failed to open $file"; + + my $incomment=0; + my @copyright=(); + my %includes; + checksrc_clear(); # for file based ignores + accept_violations(); + + while(<$R>) { + $windows_os ? $_ =~ s/\r?\n$// : chomp; + my $l = $_; + my $ol = $l; # keep the unmodified line for error reporting + my $column = 0; + + # check for !checksrc! commands + if($l =~ /\!checksrc\! (.*)/) { + my $cmd = $1; + checksrc($cmd, $line, $file, $l) + } + + if($l =~ /^#line (\d+) \"([^\"]*)\"/) { + # a #line instruction + $file = $2; + $line = $1; + next; + } + + # check for a copyright statement and save the years + if($l =~ /\* +copyright .* (\d\d\d\d|)/i) { + my $count = 0; + while($l =~ /([\d]{4})/g) { + push @copyright, { + year => $1, + line => $line, + col => index($l, $1), + code => $l + }; + $count++; + } + if(!$count) { + # year-less + push @copyright, { + year => -1, + line => $line, + col => index($l, $1), + code => $l + }; + } + } + + # detect long lines + if(length($l) > $max_column) { + checkwarn("LONGLINE", $line, length($l), $file, $l, + "Longer than $max_column columns"); + } + # detect TAB characters + if($l =~ /^(.*)\t/) { + checkwarn("TABS", + $line, length($1), $file, $l, "Contains TAB character", 1); + } + # detect trailing whitespace + if($l =~ /^(.*)[ \t]+\z/) { + checkwarn("TRAILINGSPACE", + $line, length($1), $file, $l, "Trailing whitespace"); + } + + # no space after comment start + if($l =~ /^(.*)\/\*\w/) { + checkwarn("COMMENTNOSPACESTART", + $line, length($1) + 2, $file, $l, + "Missing space after comment start"); + } + # no space at comment end + if($l =~ /^(.*)\w\*\//) { + checkwarn("COMMENTNOSPACEEND", + $line, length($1) + 1, $file, $l, + "Missing space end comment end"); + } + # ------------------------------------------------------------ + # Above this marker, the checks were done on lines *including* + # comments + # ------------------------------------------------------------ + + # strip off C89 comments + + comment: + if(!$incomment) { + if($l =~ s/\/\*.*\*\// /g) { + # full /* comments */ were removed! + } + if($l =~ s/\/\*.*//) { + # start of /* comment was removed + $incomment = 1; + } + } + else { + if($l =~ s/.*\*\///) { + # end of comment */ was removed + $incomment = 0; + goto comment; + } + else { + # still within a comment + $l=""; + } + } + + # ------------------------------------------------------------ + # Below this marker, the checks were done on lines *without* + # comments + # ------------------------------------------------------------ + + # prev line was a preprocessor **and** ended with a backslash + if($prep && ($prevpl =~ /\\ *\z/)) { + # this is still a preprocessor line + $prep = 1; + goto preproc; + } + $prep = 0; + + # crude attempt to detect // comments without too many false + # positives + if($l =~ /^(([^"\*]*)[^:"]|)\/\//) { + checkwarn("CPPCOMMENTS", + $line, length($1), $file, $l, "\/\/ comment"); + } + + if($l =~ /^(\#\s*include\s+)([\">].*[>}"])/) { + my ($pre, $path) = ($1, $2); + if($includes{$path}) { + checkwarn("INCLUDEDUP", + $line, length($1), $file, $l, "duplicated include"); + } + $includes{$path} = $l; + } + + # detect and strip preprocessor directives + if($l =~ /^[ \t]*\#/) { + # preprocessor line + $prep = 1; + goto preproc; + } + + my $nostr = nostrings($l); + # check spaces after for/if/while/function call + if($nostr =~ /^(.*)(for|if|while|switch| ([a-zA-Z0-9_]+)) \((.)/) { + my ($leading, $word, $extra, $first)=($1,$2,$3,$4); + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + elsif(defined $3 && $3 eq "return") { + # return must have a space + } + elsif(defined $3 && $3 eq "case") { + # case must have a space + } + elsif(($first eq "*") && ($word !~ /(for|if|while|switch)/)) { + # A "(*" beginning makes the space OK because it wants to + # allow function pointer declared + } + elsif($1 =~ / *typedef/) { + # typedefs can use space-paren + } + else { + checkwarn("SPACEBEFOREPAREN", $line, length($leading)+length($word), $file, $l, + "$word with space"); + } + } + # check for '== NULL' in if/while conditions but not if the thing on + # the left of it is a function call + if($nostr =~ /^(.*)(if|while)(\(.*?)([!=]= NULL|NULL [!=]=)/) { + checkwarn("EQUALSNULL", $line, + length($1) + length($2) + length($3), + $file, $l, "we prefer !variable instead of \"== NULL\" comparisons"); + } + + # check for '!= 0' in if/while conditions but not if the thing on + # the left of it is a function call + if($nostr =~ /^(.*)(if|while)(\(.*[^)]) != 0[^x]/) { + checkwarn("NOTEQUALSZERO", $line, + length($1) + length($2) + length($3), + $file, $l, "we prefer if(rc) instead of \"rc != 0\" comparisons"); + } + + # check spaces in 'do {' + if($nostr =~ /^( *)do( *)\{/ && length($2) != 1) { + checkwarn("DOBRACE", $line, length($1) + 2, $file, $l, "one space after do before brace"); + } + # check spaces in 'do {' + elsif($nostr =~ /^( *)\}( *)while/ && length($2) != 1) { + checkwarn("BRACEWHILE", $line, length($1) + 2, $file, $l, "one space between brace and while"); + } + if($nostr =~ /^((.*\s)(if) *\()(.*)\)(.*)/) { + my $pos = length($1); + my $postparen = $5; + my $cond = $4; + if($cond =~ / = /) { + checkwarn("ASSIGNWITHINCONDITION", + $line, $pos+1, $file, $l, + "assignment within conditional expression"); + } + my $temp = $cond; + $temp =~ s/\(//g; # remove open parens + my $openc = length($cond) - length($temp); + + $temp = $cond; + $temp =~ s/\)//g; # remove close parens + my $closec = length($cond) - length($temp); + my $even = $openc == $closec; + + if($l =~ / *\#/) { + # this is a #if, treat it differently + } + elsif($even && $postparen && + ($postparen !~ /^ *$/) && ($postparen !~ /^ *[,{&|\\]+/)) { + checkwarn("ONELINECONDITION", + $line, length($l)-length($postparen), $file, $l, + "conditional block on the same line"); + } + } + # check spaces after open parentheses + if($l =~ /^(.*[a-z])\( /i) { + checkwarn("SPACEAFTERPAREN", + $line, length($1)+1, $file, $l, + "space after open parenthesis"); + } + + # check spaces before Logical AND operator + if($nostr =~ /^(.*)\w&&/i) { + checkwarn("NOSPACEAND", + $line, length($1)+1, $file, $l, + "missing space before Logical AND"); + } + + # check spaces after Logical AND operator + if($nostr =~ /^(.*&&)\w/i) { + checkwarn("NOSPACEAND", + $line, length($1), $file, $l, + "missing space after Logical AND"); + } + + # check spaces before colon + if($nostr =~ /^(.*[^']\?[^'].*)(\w|\)|\]|')\:/i) { + my $m = $1; + my $e = $nostr; + $e =~ s/'(.)':'(.)'/$1:$2/g; # eliminate chars quotes that surround colon + $e =~ s/':'//g; # ignore these + if($e =~ /^(.*[^']\?[^'].*)(\w|\)|\]|')\:/i) { + checkwarn("NOSPACEC", + $line, length($m)+1, $file, $l, + "missing space before colon"); + } + } + # check spaces after colon + if($nostr =~ /^(.*[^'"]\?[^'"].*)\:(\w|\)|\]|')/i) { + my $m = $1; + my $e = $nostr; + $e =~ s/'(.)':'(.)'/$1:$2/g; # eliminate chars quotes that surround colon + $e =~ s/':'//g; # ignore these + if($e =~ /^(.*[^'"]\?[^'"].*)\:(\w|\)|\]|')/i) { + checkwarn("NOSPACEC", + $line, length($m)+1, $file, $l, + "missing space after colon"); + } + } + + # check spaces before question mark + if($nostr =~ /^(.*)(\w|\)|\]|')\?/i) { + my $m = $1; + my $e = $nostr; + $e =~ s/'?'//g; # ignore these + if($e =~ /^(.*)(\w|\)|\]|')\?/i) { + checkwarn("NOSPACEQ", + $line, length($m)+1, $file, $l, + "missing space before question mark"); + } + } + # check spaces after question mark + if($nostr =~ /^(.*)\?\w/i) { + checkwarn("NOSPACEQ", + $line, length($1)+1, $file, $l, + "missing space after question mark"); + } + + # check spaces before less or greater than + if($nostr =~ /^(.*)(\w|\)|\])[<>]/) { + checkwarn("NOSPACETHAN", + $line, length($1)+1, $file, $l, + "missing space before less or greater than"); + } + # check spaces after less or greater than + if($nostr =~ /^(.*)[^-][<>](\w|\(|\[)/) { + checkwarn("NOSPACETHAN", + $line, length($1)+1, $file, $l, + "missing space after less or greater than"); + } + + # check spaces before close parentheses, unless it was a space or a + # close parenthesis! + if($l =~ /(.*[^\) ]) \)/) { + checkwarn("SPACEBEFORECLOSE", + $line, length($1)+1, $file, $l, + "space before close parenthesis"); + } + + # check spaces before comma! + if($l =~ /(.*[^ ]) ,/) { + checkwarn("SPACEBEFORECOMMA", + $line, length($1)+1, $file, $l, + "space before comma"); + } + + # check for "return(" without space + if($l =~ /^(.*)return\(/) { + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + else { + checkwarn("RETURNNOSPACE", $line, length($1)+6, $file, $l, + "return without space before paren"); + } + } + + # check for "sizeof" without parenthesis + if(($l =~ /^(.*)sizeof *([ (])/) && ($2 ne "(")) { + if($1 =~ / *\#/) { + # this is a #if, treat it differently + } + else { + checkwarn("SIZEOFNOPAREN", $line, length($1)+6, $file, $l, + "sizeof without parenthesis"); + } + } + + # check for comma without space + if($l =~ /^(.*),[^ \n]/) { + my $pref=$1; + my $ign=0; + if($pref =~ / *\#/) { + # this is a #if, treat it differently + $ign=1; + } + elsif($pref =~ /\/\*/) { + # this is a comment + $ign=1; + } + elsif($pref =~ /[\"\']/) { + $ign = 1; + # There is a quote here, figure out whether the comma is + # within a string or '' or not. + if($pref =~ /\"/) { + # within a string + } + elsif($pref =~ /\'$/) { + # a single letter + } + else { + $ign = 0; + } + } + if(!$ign) { + checkwarn("COMMANOSPACE", $line, length($pref)+1, $file, $l, + "comma without following space"); + } + } + + # check for "} else" + if($l =~ /^(.*)\} *else/) { + checkwarn("BRACEELSE", + $line, length($1), $file, $l, "else after closing brace on same line"); + } + # check for "){" + if($l =~ /^(.*)\)\{/) { + checkwarn("PARENBRACE", + $line, length($1)+1, $file, $l, "missing space after close paren"); + } + # check for "^{" with an empty line before it + if(($l =~ /^\{/) && ($prevl =~ /^[ \t]*\z/)) { + checkwarn("EMPTYLINEBRACE", + $line, 0, $file, $l, "empty line before open brace"); + } + + # check for space before the semicolon last in a line + if($l =~ /^(.*[^ ].*) ;$/) { + checkwarn("SPACESEMICOLON", + $line, length($1), $file, $ol, "no space before semicolon"); + } + + # check for space before the colon in a switch label + if($l =~ /^( *(case .+|default)) :/) { + checkwarn("SPACESWITCHCOLON", + $line, length($1), $file, $ol, "no space before colon of switch label"); + } + + if($prevl !~ /\?\z/ && $l =~ /^ +([A-Za-z_][A-Za-z0-9_]*):$/ && $1 ne 'default') { + checkwarn("SPACEBEFORELABEL", + $line, length($1), $file, $ol, "no space before label"); + } + + # scan for use of banned functions + if($l =~ /^(.*\W) + (gmtime|localtime| + gets| + strtok| + v?sprintf| + (str|_mbs|_tcs|_wcs)n?cat| + LoadLibrary(Ex)?(A|W)?| + _?w?access) + \s*\( + /x) { + checkwarn("BANNEDFUNC", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + if($warnings{"STRERROR"}) { + # scan for use of banned strerror. This is not a BANNEDFUNC to + # allow for individual enable/disable of this warning. + if($l =~ /^(.*\W)(strerror)\s*\(/x) { + if($1 !~ /^ *\#/) { + # skip preprocessor lines + checkwarn("STRERROR", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + } + } + if($warnings{"STRNCPY"}) { + # scan for use of banned strncpy. This is not a BANNEDFUNC to + # allow for individual enable/disable of this warning. + if($l =~ /^(.*\W)(strncpy)\s*\(/x) { + if($1 !~ /^ *\#/) { + # skip preprocessor lines + checkwarn("STRNCPY", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + } + } + if($warnings{"STDERR"}) { + # scan for use of banned stderr. This is not a BANNEDFUNC to + # allow for individual enable/disable of this warning. + if($l =~ /^([^\"-]*\W)(stderr)[^\"_]/x) { + if($1 !~ /^ *\#/) { + # skip preprocessor lines + checkwarn("STDERR", + $line, length($1), $file, $ol, + "use of $2 is banned (use tool_stderr instead)"); + } + } + } + # scan for use of snprintf for curl-internals reasons + if($l =~ /^(.*\W)(v?snprintf)\s*\(/x) { + checkwarn("SNPRINTF", + $line, length($1), $file, $ol, + "use of $2 is banned"); + } + + # scan for use of non-binary fopen without the macro + if($l =~ /^(.*\W)fopen\s*\([^,]*, *\"([^"]*)/) { + my $mode = $2; + if($mode !~ /b/) { + checkwarn("FOPENMODE", + $line, length($1), $file, $ol, + "use of non-binary fopen without FOPEN_* macro: $mode"); + } + } + + # check for open brace first on line but not first column only alert + # if previous line ended with a close paren and it wasn't a cpp line + if(($prevl =~ /\)\z/) && ($l =~ /^( +)\{/) && !$prevp) { + checkwarn("BRACEPOS", + $line, length($1), $file, $ol, "badly placed open brace"); + } + + # if the previous line starts with if/while/for AND ends with an open + # brace, or an else statement, check that this line is indented $indent + # more steps, if not a cpp line + if(!$prevp && ($prevl =~ /^( *)((if|while|for)\(.*\{|else)\z/)) { + my $first = length($1); + # this line has some character besides spaces + if($l =~ /^( *)[^ ]/) { + my $second = length($1); + my $expect = $first+$indent; + if($expect != $second) { + my $diff = $second - $first; + checkwarn("INDENTATION", $line, length($1), $file, $ol, + "not indented $indent steps (uses $diff)"); + + } + } + } + + # if the previous line starts with if/while/for AND ends with a closed + # parenthesis and there's an equal number of open and closed + # parentheses, check that this line is indented $indent more steps, if + # not a cpp line + elsif(!$prevp && ($prevl =~ /^( *)(if|while|for)(\(.*\))\z/)) { + my $first = length($1); + my $op = $3; + my $cl = $3; + + $op =~ s/[^(]//g; + $cl =~ s/[^)]//g; + + if(length($op) == length($cl)) { + # this line has some character besides spaces + if($l =~ /^( *)[^ ]/) { + my $second = length($1); + my $expect = $first+$indent; + if($expect != $second) { + my $diff = $second - $first; + checkwarn("INDENTATION", $line, length($1), $file, $ol, + "not indented $indent steps (uses $diff)"); + } + } + } + } + + # check for 'char * name' + if(($l =~ /(^.*(char|int|long|void|CURL|CURLM|CURLMsg|[cC]url_[A-Za-z_]+|struct [a-zA-Z_]+) *(\*+)) (\w+)/) && ($4 !~ /^(const|volatile)$/)) { + checkwarn("ASTERISKSPACE", + $line, length($1), $file, $ol, + "space after declarative asterisk"); + } + # check for 'char*' + if(($l =~ /(^.*(char|int|long|void|curl_slist|CURL|CURLM|CURLMsg|curl_httppost|sockaddr_in|FILE)\*)/)) { + checkwarn("ASTERISKNOSPACE", + $line, length($1)-1, $file, $ol, + "no space before asterisk"); + } + + # check for 'void func() {', but avoid false positives by requiring + # both an open and closed parentheses before the open brace + if($l =~ /^((\w).*)\{\z/) { + my $k = $1; + $k =~ s/const *//; + $k =~ s/static *//; + if($k =~ /\(.*\)/) { + checkwarn("BRACEPOS", + $line, length($l)-1, $file, $ol, + "wrongly placed open brace"); + } + } + + # check for equals sign without spaces next to it + if($nostr =~ /(.*)\=[a-z0-9]/i) { + checkwarn("EQUALSNOSPACE", + $line, length($1)+1, $file, $ol, + "no space after equals sign"); + } + # check for equals sign without spaces before it + elsif($nostr =~ /(.*)[a-z0-9]\=/i) { + checkwarn("NOSPACEEQUALS", + $line, length($1)+1, $file, $ol, + "no space before equals sign"); + } + + # check for plus signs without spaces next to it + if($nostr =~ /(.*)[^+]\+[a-z0-9]/i) { + checkwarn("PLUSNOSPACE", + $line, length($1)+1, $file, $ol, + "no space after plus sign"); + } + # check for plus sign without spaces before it + elsif($nostr =~ /(.*)[a-z0-9]\+[^+]/i) { + checkwarn("NOSPACEPLUS", + $line, length($1)+1, $file, $ol, + "no space before plus sign"); + } + + # check for semicolons without space next to it + if($nostr =~ /(.*)\;[a-z0-9]/i) { + checkwarn("SEMINOSPACE", + $line, length($1)+1, $file, $ol, + "no space after semicolon"); + } + + # typedef struct ... { + if($nostr =~ /^(.*)typedef struct.*{/) { + checkwarn("TYPEDEFSTRUCT", + $line, length($1)+1, $file, $ol, + "typedef'ed struct"); + } + + if($nostr =~ /(.*)! +(\w|\()/) { + checkwarn("EXCLAMATIONSPACE", + $line, length($1)+1, $file, $ol, + "space after exclamation mark"); + } + + # check for more than one consecutive space before open brace or + # question mark. Skip lines containing strings since they make it hard + # due to artificially getting multiple spaces + if(($l eq $nostr) && + $nostr =~ /^(.*(\S)) + [{?]/i) { + checkwarn("MULTISPACE", + $line, length($1)+1, $file, $ol, + "multiple spaces"); + } + preproc: + if($prep) { + # scan for use of banned symbols on a preprocessor line + if($l =~ /^(^|.*\W) + (WIN32) + (\W|$) + /x) { + checkwarn("BANNEDPREPROC", + $line, length($1), $file, $ol, + "use of $2 is banned from preprocessor lines" . + (($2 eq "WIN32") ? ", use _WIN32 instead" : "")); + } + } + $line++; + $prevp = $prep; + $prevl = $ol if(!$prep); + $prevpl = $ol if($prep); + } + + if(!scalar(@copyright)) { + checkwarn("COPYRIGHT", 1, 0, $file, "", "Missing copyright statement", 1); + } + + # COPYRIGHTYEAR is an extended warning so we must first see if it has been + # enabled in .checksrc + if(defined($warnings{"COPYRIGHTYEAR"})) { + # The check for updated copyrightyear is overly complicated in order to + # not punish current hacking for past sins. The copyright years are + # right now a bit behind, so enforcing copyright year checking on all + # files would cause hundreds of errors. Instead we only look at files + # which are tracked in the Git repo and edited in the workdir, or + # committed locally on the branch without being in upstream master. + # + # The simple and naive test is to simply check for the current year, + # but updating the year even without an edit is against project policy + # (and it would fail every file on January 1st). + # + # A rather more interesting, and correct, check would be to not test + # only locally committed files but inspect all files wrt the year of + # their last commit. Removing the `git rev-list origin/master..HEAD` + # condition below will enforce copyright year checks against the year + # the file was last committed (and thus edited to some degree). + my $commityear = undef; + @copyright = sort {$$b{year} cmp $$a{year}} @copyright; + + # if the file is modified, assume commit year this year + if(`git status -s -- "$file"` =~ /^ [MARCU]/) { + $commityear = (localtime(time))[5] + 1900; + } + else { + # min-parents=1 to ignore wrong initial commit in truncated repos + my $grl = `git rev-list --max-count=1 --min-parents=1 --timestamp HEAD -- "$file"`; + if($grl) { + chomp $grl; + $commityear = (localtime((split(/ /, $grl))[0]))[5] + 1900; + } + } + + if(defined($commityear) && scalar(@copyright) && + $copyright[0]{year} != $commityear) { + checkwarn("COPYRIGHTYEAR", $copyright[0]{line}, $copyright[0]{col}, + $file, $copyright[0]{code}, + "Copyright year out of date, should be $commityear, " . + "is $copyright[0]{year}", 1); + } + } + + if($incomment) { + checkwarn("OPENCOMMENT", 1, 0, $file, "", "Missing closing comment", 1); + } + + checksrc_endoffile($file); + + close($R); + +} + + +if($errors || $warnings || $verbose) { + printf "checksrc: %d errors and %d warnings\n", $errors, $warnings; + if($suppressed) { + printf "checksrc: %d errors and %d warnings suppressed\n", + $serrors, + $swarnings; + } + exit 5; # return failure +} diff --git a/local-test-curl-full-01/afc-curl/scripts/ciconfig.pl b/local-test-curl-full-01/afc-curl/scripts/ciconfig.pl new file mode 100644 index 0000000000000000000000000000000000000000..93358def21dde7fd90df1ae3503e802ea3b83f5d --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/ciconfig.pl @@ -0,0 +1,190 @@ +#!/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 +# +########################################################################### + +# these options are enabled by default in the sense that they will attempt to +# check for and use this feature without the configure flag +my %defaulton = ( + # --enable- + 'shared' => 1, + 'static' => 1, + 'fast-install' => 1, + 'silent-rules' => 1, + 'optimize' => 1, + 'http' => 1, + 'ftp' => 1, + 'file' => 1, + 'ldap' => 1, + 'ldaps' => 1, + 'rtsp' => 1, + 'proxy' => 1, + 'dict' => 1, + 'telnet' => 1, + 'tftp' => 1, + 'pop3' => 1, + 'imap' => 1, + 'smb' => 1, + 'smtp' => 1, + 'gopher' => 1, + 'mqtt' => 1, + 'manual' => 1, + 'libcurl-option' => 1, + 'libgcc' => 1, + 'ipv6' => 1, + 'openssl-auto-load-config' => 1, + 'versioned-symbols' => 1, + 'symbol-hiding' => 1, + 'threaded-resolver' => 1, + 'pthreads' => 1, + 'verbose' => 1, + 'basic-auth' => 1, + 'bearer-auth' => 1, + 'digest-auth' => 1, + 'kerberos-auth' => 1, + 'negotiate-auth' => 1, + 'aws' => 1, + 'ntlm' => 1, + 'ntlm-wb' => 1, + 'tls-srp' => 1, + 'unix-sockets' => 1, + 'cookies' => 1, + 'socketpair' => 1, + 'http-auth' => 1, + 'doh' => 1, + 'mime' => 1, + 'dateparse' => 1, + 'netrc' => 1, + 'progress-meter' => 1, + 'dnsshuffle' => 1, + 'get-easy-options' => 1, + 'alt-svc' => 1, + 'hsts' => 1, + + # --with- + 'aix-soname' => 1, + 'pic' => 1, + 'zlib' => 1, + 'zstd' => 1, + 'brotli' => 1, + 'random' => 1, + 'ca-bundle' => 1, + 'ca-path' => 1, + 'libssh2' => 1, + 'nghttp2' => 1, + 'librtmp' => 1, + 'libidn2' => 1, + 'sysroot' => 1, + 'lber-lib' => 1, + 'ldap-lib' => 1, + + ); + + +sub configureopts { + my ($opts)=@_; + my %thisin; + my %thisout; + + while($opts =~ s/--with-([^ =]*)//) { + $with{$1}++; + $used{$1}++; + $thisin{$1}++; + } + while($opts =~ s/--enable-([^ =]*)//) { + $with{$1}++; + $used{$1}++; + $thisin{$1}++; + } + + while($opts =~ s/--without-([^ =]*)//) { + $without{$1}++; + $used{$1}++; + $thisout{$1}++; + } + while($opts =~ s/--disable-([^ =]*)//) { + $without{$1}++; + $used{$1}++; + $thisout{$1}++; + } + return join(" ", sort(keys %thisin), "/", sort(keys %thisout)); +} + +# run configure --help and check what available WITH/ENABLE options that exist +sub configurehelp { + open(C, "./configure --help|"); + while() { + if($_ =~ /^ --(with|enable)-([a-z0-9-]+)/) { + $avail{$2}++; + } + } + close(C); +} + +sub scanjobs { + + my $jobs; + open(CI, "./scripts/cijobs.pl|"); + while() { + if($_ =~ /^\#\#\#/) { + $jobs++; + } + if($_ =~ /^configure: (.*)/) { + my $c= configureopts($1); + #print "C: $c\n"; + } + } + close(CI); +} + +configurehelp(); +scanjobs(); + +print "Used configure options (with / without)\n"; +for my $w (sort keys %used) { + printf " %s: %d %d%s\n", $w, $with{$w}, $without{$w}, + $defaulton{$w} ? " (auto)":""; +} + +print "Never used configure options\n"; +for my $w (sort keys %avail) { + if(!$used{$w}) { + printf " %s%s\n", $w, + $defaulton{$w} ? " (auto)":""; + } +} + +print "Never ENABLED configure options that aren't on by default\n"; +for my $w (sort keys %avail) { + if(!$with{$w} && !$defaulton{$w}) { + printf " %s\n", $w; + } +} + + +print "ENABLED configure options that aren't available\n"; +for my $w (sort keys %with) { + if(!$avail{$w}) { + printf " %s\n", $w; + } +} diff --git a/local-test-curl-full-01/afc-curl/scripts/cijobs.pl b/local-test-curl-full-01/afc-curl/scripts/cijobs.pl new file mode 100644 index 0000000000000000000000000000000000000000..7d0a2dec7a563a9922ec48e2a5fbf853475137aa --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/cijobs.pl @@ -0,0 +1,510 @@ +#!/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 +# +########################################################################### + +my %filelevel= ('file' => 1, + 'service' => 1); + +my $jobid = 1; + +sub submit { + my ($jref)=@_; + my %job = %$jref; + + printf "\n##### job %u \n", $jobid++; + for my $k (sort keys %job) { + printf "%s: %s\n", $k, $job{$k} if($job{$k}); + undef $$jref{$k} if(!$filelevel{$k}); + } +} + +sub githubactions { + my ($tag)=@_; + my @files= `git ls-tree -r --name-only $tag .github/workflows 2>/dev/null`; + my $c = 0; + foreach my $f (sort @files) { + my $j = 0; + my $m = -1; + my $done = 0; + chomp $f; + open(G, "git show $tag:$f 2>/dev/null|"); + # start counting file jobs + undef %job; + $job{'file'} = $f; + $job{'service'} = "gha"; + my @cc; + my $os; + my $topname; + my $line = 1; + while() { + $job{'line'} = $line; + if($_ =~ /^name: (.*)/) { + $topname=$1; + } + elsif($_ =~ /runs-on: (.*)/) { + my $r = $1; + #print "runs-on: $r\n"; + if($r =~ /ubuntu/) { + $os = "linux"; + } + elsif($r =~ /macos/) { + $os = "macos"; + } + elsif($r =~ /windows/) { + $os = "windows"; + } + + # commit previously counted jobs + $c += $j; + # non-matrix job + $j = 1; + } + elsif($_ =~ /^\s*matrix:/) { + # switch to matrix mode + $m = 0; + $j = 0; + } + elsif($_ =~ /^ - run: .* apt-get install (.*)/) { + $job{'install'} = $1; + } + elsif($m >= 0) { + if($_ =~ /^ - name: (.*)/) { + # matrix job + #print "name: $1\n"; + $job{'name'} = $1; + $j += ($m?$m:1); + } + elsif($_ =~ /install: (.*)/) { + $job{'install'} = $1; + } + elsif($_ =~ /( |curl-)configure: (.*)/) { + $job{'configure'} = $2; + $job{'os'}=$os; + submit(\%job); + $done++; + } + elsif($_ =~ /generate: (.*)/) { + $job{'cmake'} = $1; + if($m) { + # matrix mode, multiple copies + my %dupe = %job; + for my $cc (@cc) { + %job = %dupe; + $job{'cc'} = $cc; + $job{'os'}=$os; + submit(\%job); + $done++; + } + } + else { + $job{'os'}=$os; + submit(\%job); + $done++; + } + } + elsif($_ =~ /- CC: (.*)/) { + # matrix multiplier + push @cc, $1; + $m++; + } + elsif($_ =~ /^\s*steps:/) { + # disable matrix mode + $m = -1; + } + } + $line++; + } + close(G); + # commit final counted jobs + $c += $j; + + if(!$done) { + $job{'name'} = $topname? $topname : '[unnamed]'; + $job{'os'}=$os; + submit(\%job); + $done++; + } + # reset internal job counter + $j = 0; + } + #print "Jobs: $c\n"; + return $c; +} + +sub azurepipelines { + my ($tag)=@_; + open(G, "git show $tag:.azure-pipelines.yml 2>/dev/null|"); + my $c = 0; + my $j = 0; + my $m = -1; + my $image; + my %job; + my $line = 1; + my $os; + $job{'file'} = ".azure-pipelines.yml"; + $job{'service'} = "azure"; + while() { + if($_ =~ /^ vmImage: (.*)/) { + my $i = $1; + if($i =~ /ubuntu/) { + $os = "linux"; + } + elsif($i =~ /windows/) { + $os = "windows"; + } + } + elsif($_ =~ /^ - stage: (.*)/) { + my $topname = $1; + if($topname !~ /(windows|linux)/) { + $job{'name'} = $topname; + $job{'line'}=$line; + submit(\%job); + } + } + elsif($_ =~ /job:/) { + # commit previously counted jobs + $c += $j; + # initial value for non-matrix job + $j = 1; + } + elsif($_ =~ /matrix:/) { + # start of new matrix list(!) + $m = 0; + $j = 0; + } + elsif($m >= 0) { + if($_ =~ /^ name: (.*)/) { + # single matrix list entry job + $j++; + $job{'name'} = $1; + } + # azure matrix is a simple list, + # therefore no multiplier needed + elsif($_ =~ /steps:/) { + # disable matrix mode + $m = -1; + } + elsif($_ =~ /^ configure: (.*)/) { + $job{'configure'} = $1; + $job{'line'}=$line; + $job{'os'}=$os; + submit(\%job); + } + } + $line++; + } + close(G); + # commit final counted jobs + $c += $j; + + return $c; +} + +sub appveyor { + my ($tag)=@_; + open(G, "git show $tag:appveyor.yml 2>/dev/null|"); + my $c = 0; + my %job; + my $line=0; + $job{'file'} = "appveyor.yml"; + $job{'service'} = "appveyor"; + + while() { + $line++; + if($_ =~ /^( - |install)/) { + if($job{'image'}) { + $job{'os'} = "windows"; + submit(\%job); + $c++; + } + } + $job{'line'} = $line; + if($_ =~ /^ APPVEYOR_BUILD_WORKER_IMAGE: \'(.*)\'/) { + $job{'image'}= $1; + } + elsif($_ =~ /^ BUILD_SYSTEM: (.*)/) { + $job{'build'} = lc($1); + } + elsif($_ =~ /^ PRJ_GEN: \'(.*)\'/) { + $job{'compiler'} = $1; + } + elsif($_ =~ /^ PRJ_CFG: (.*)/) { + $job{'config'} = $1; + } + elsif($_ =~ /^ OPENSSL: \'(.*)\'/) { + $job{'openssl'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ SCHANNEL: \'(.*)\'/) { + $job{'schannel'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ ENABLE_UNICODE: \'(.*)\'/) { + $job{'unicode'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ HTTP_ONLY: \'(.*)\'/) { + $job{'http-only'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ TESTING: \'(.*)\'/) { + $job{'testing'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ SHARED: \'(.*)\'/) { + $job{'shared'} = $1 eq "ON" ? "true": "false"; + } + elsif($_ =~ /^ TARGET: \'-A (.*)\'/) { + $job{'target'} = $1; + } + } + close(G); + + return $c; +} + +sub cirrus { + my ($tag)=@_; + open(G, "git show $tag:.cirrus.yml 2>/dev/null|"); + my $c = 0; + my %job; + my $line=0; + my $name = 0; + my $os; + $job{'file'} = ".cirrus.yml"; + $job{'service'} = "cirrus"; + while() { + $line++; + if($_ =~ /^ ( |-) (name|image_family|image):/) { + $c++; + } + if($_ =~ /^ - name:/) { + if($name) { + $job{'os'} = $os; + $job{'line'} = $line; + submit(\%job); + $name = 0; + } + } + if($_ =~ /^ - name: (.*)/) { + $job{'name'} = $1; + $name = 1; + } + elsif($_ =~ /^ image_family: (.*)/) { + $os = "freebsd"; + } + elsif($_ =~ /^windows_task:/) { + $os = "windows"; + } + elsif($_ =~ /^ prepare: pacman -S --needed --noconfirm --noprogressbar (.*)/) { + $job{'install'} = $1; + } + elsif($_ =~ /^ configure: (.*)/) { + $job{'configure'} = $1; + } + } + close(G); + if($name) { + $job{'os'} = $os; + $job{'line'} = $line; + submit(\%job); + } + return $c; +} + +sub circle { + my ($tag)=@_; + open(G, "git show $tag:.circleci/config.yml 2>/dev/null|"); + my $c = 0; + my $wf = 0; + my %job; + my %cmd; + my %configure; + my %target; + my $line=0; + my $cmds; + my $jobs; + my $workflow; + $job{'file'} = ".circleci/config.yml"; + $job{'service'} = "circleci"; + while() { + $line++; + if($_ =~ /^commands:/) { + # we record configure lines in this state + $cmds = 1; + } + elsif($cmds) { + if($_ =~ /^ ([^ ]*):/) { + $cmdname = $1; + } + elsif($_ =~ /^ .*.\/configure (.*)/) { + $cmd{$cmdname}=$1; + } + } + if($_ =~ /^jobs:/) { + # we record which job runs with configure here + $jobs = 1; + $cmds = 0; + } + elsif($jobs) { + if($_ =~ /^ ([^ ]*):/) { + $jobname = $1; + } + elsif($_ =~ /^ - (configure.*)/) { + $configure{$jobname}=$1; + } + elsif($_ =~ /^ resource_class: arm.medium/) { + $target{$jobname}="arm"; + } + } + if($_ =~ /^workflows:/) { + $wf = 1; + $cmds = 0; + } + elsif($wf) { + if($_ =~ /^ ([^ ]+):/) { + $workflow = $1; + } + elsif($_ =~ /^ - (.*)\n/) { + my $jb = $1; + my $cnfgure = $configure{$jb}; + my $trgt = $target{$jb}; + $job{'configure'} = $cmd{$cnfgure}; + $job{'name' }=$workflow; + $job{'os'} = "linux"; + $job{'line'} = $line; + $job{'target'} = $trgt if($trgt); + submit(\%job); + } + if($_ =~ / *jobs:/) { + $c++; + } + } + } + close(G); + return $c; +} + +sub zuul { + my ($tag)=@_; + open(G, "git show $tag:zuul.d/jobs.yaml 2>/dev/null|"); + my $c = 0; + my %job; + my $line=0; + my $type; + $job{'file'} = "zuul.d/jobs.yaml"; + $job{'service'} = "zuul"; + while() { + $line++; + #print "L: ($jobmode / $env) $_"; + if($_ =~ /^- job:/) { + $jobmode = 1; # start a new + $type="configure"; + } + if($jobmode) { + if($apt) { + if($_ =~ /^ - (.*)/) { + my $value = $1; + $job{'install'} .= "$value "; + } + else { + $apt = 0; # end of curl_apt_packages + } + } + if($env) { + if($envcont) { + if($_ =~ /^ (.*)/) { + $job{$envcont} .= "$1 "; + } + else { + $envcont = ""; + } + } + if($_ =~ /^ ([^:]+): (.*)/) { + my ($var, $value) = ($1, $2); + + if($var eq "C") { + $var = $type; + } + elsif($var eq "T") { + $var = "tests"; + if($value eq "cmake") { + # otherwise it remains configure + $type = "cmake"; + } + } + elsif($var eq "CC") { + $var = "compiler"; + } + elsif($var eq "CHECKSRC") { + $job{'checksrc'} = $value ? "true": "false"; + $var = ""; + } + else { + $var = ""; + } + if($value eq ">-") { + $envcont = $var; + } + elsif($var) { + $job{$var} = $value; + } + } + elsif($_ !~ /^ /) { + # end of envs + $env = 0; + } + } + if($_ =~ /^ curl_env:/) { + $env = 1; # start of envs + } + elsif($_ =~ /^ curl_apt_packages:/) { + $apt = 1; # start of apt packages + } + elsif($_ =~ /^ name: (.*)/) { + my $n = $1; + if($n eq "curl-base") { + # not counted + $jobmode = 0; + next; + } + $job{'name'} = $n; + } + elsif($_ =~ /^\n\z/) { + # a job is complete + $job{'line'}=$line; + $job{'os'}="linux"; + submit(\%job); + $jobmode = 0; + $c++; + } + } + } + close(G); + return $c; +} + +my $tag = `git rev-parse --abbrev-ref HEAD 2>/dev/null` || "master"; +chomp $tag; +githubactions($tag); +azurepipelines($tag); +appveyor($tag); +zuul($tag); +cirrus($tag); +circle($tag); diff --git a/local-test-curl-full-01/afc-curl/scripts/cmakelint.sh b/local-test-curl-full-01/afc-curl/scripts/cmakelint.sh new file mode 100644 index 0000000000000000000000000000000000000000..070079656972b1b552510df8536fdad8c51316e6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/cmakelint.sh @@ -0,0 +1,50 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Dan Fandrich, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# Run cmakelint on the curl source code. It will check all files given on the +# command-line, or else all relevant files in git, or if not in a git +# repository, all files starting in the tree rooted in the current directory. +# +# cmakelint can be installed from PyPi with the command "python3 -m pip install +# cmakelint". +# +# The xargs invocation is portable, but does not preserve spaces in file names. +# If such a file is ever added, then this can be portably fixed by switching to +# "xargs -I{}" and appending {} to the end of the xargs arguments (which will +# call cmakelint once per file) or by using the GNU extension "xargs -d'\n'". +{ + if [ -n "$1" ]; then + for A in "$@"; do printf "%s\n" "$A"; done + elif git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + git ls-files + else + # strip off the leading ./ to make the grep regexes work properly + find . -type f | sed 's@^\./@@' + fi +} | grep -E '(^CMake|/CMake|\.cmake$)' | grep -v -E '(\.h\.cmake|\.in)$' \ + | xargs \ + cmakelint \ + --spaces=2 --linelength=132 \ + --filter=-whitespace/indent,-convention/filename,-package/stdargs diff --git a/local-test-curl-full-01/afc-curl/scripts/completion.pl b/local-test-curl-full-01/afc-curl/scripts/completion.pl new file mode 100644 index 0000000000000000000000000000000000000000..00c736898a11961dd012e902f220ef63989d5740 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/completion.pl @@ -0,0 +1,166 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +use strict; +use warnings; +use Getopt::Long(); +use Pod::Usage(); + +my $curl = 'curl'; +my $shell = 'zsh'; +my $help = 0; +Getopt::Long::GetOptions( + 'curl=s' => \$curl, + 'shell=s' => \$shell, + 'help' => \$help, +) or Pod::Usage::pod2usage(); +Pod::Usage::pod2usage() if $help; + +my $regex = '\s+(?:(-[^\s]+),\s)?(--[^\s]+)\s*(\<.+?\>)?\s+(.*)'; +my @opts = parse_main_opts('--help all', $regex); + +if ($shell eq 'fish') { + print "# curl fish completion\n\n"; + print qq{$_ \n} foreach (@opts); +} elsif ($shell eq 'zsh') { + my $opts_str; + + $opts_str .= qq{ $_ \\\n} foreach (@opts); + chomp $opts_str; + +my $tmpl = <<"EOS"; +#compdef curl + +# curl zsh completion + +local curcontext="\$curcontext" state state_descr line +typeset -A opt_args + +local rc=1 + +_arguments -C -S \\ +$opts_str + '*:URL:_urls' && rc=0 + +return rc +EOS + + print $tmpl; +} else { + die("Unsupported shell: $shell"); +} + +sub parse_main_opts { + my ($cmd, $regex) = @_; + + my @list; + my @lines = call_curl($cmd); + + foreach my $line (@lines) { + my ($short, $long, $arg, $desc) = ($line =~ /^$regex/) or next; + + my $option = ''; + + $arg =~ s/\:/\\\:/g if defined $arg; + + $desc =~ s/'/'\\''/g if defined $desc; + $desc =~ s/\[/\\\[/g if defined $desc; + $desc =~ s/\]/\\\]/g if defined $desc; + $desc =~ s/\:/\\\:/g if defined $desc; + + if ($shell eq 'fish') { + $option .= "complete --command curl"; + $option .= " --short-option '" . strip_dash(trim($short)) . "'" + if defined $short; + $option .= " --long-option '" . strip_dash(trim($long)) . "'" + if defined $long; + $option .= " --description '" . strip_dash(trim($desc)) . "'" + if defined $desc; + } elsif ($shell eq 'zsh') { + $option .= '{' . trim($short) . ',' if defined $short; + $option .= trim($long) if defined $long; + $option .= '}' if defined $short; + $option .= '\'[' . trim($desc) . ']\'' if defined $desc; + + if (defined $arg) { + $option .= ":'$arg'"; + if ($arg =~ /|/) { + $option .= ':_files'; + } elsif ($arg =~ //) { + $option .= ":'_path_files -/'"; + } elsif ($arg =~ //i) { + $option .= ':_urls'; + } elsif ($long =~ /ftp/ && $arg =~ //) { + $option .= ":'(multicwd nocwd singlecwd)'"; + } elsif ($arg =~ //) { + $option .= ":'(DELETE GET HEAD POST PUT)'"; + } + } + } + + push @list, $option; + } + + # Sort longest first, because zsh won't complete an option listed + # after one that's a prefix of it. + @list = sort { + $a =~ /([^=]*)/; my $ma = $1; + $b =~ /([^=]*)/; my $mb = $1; + + length($mb) <=> length($ma) + } @list if $shell eq 'zsh'; + + return @list; +} + +sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s }; +sub strip_dash { my $s = shift; $s =~ s/^-+//g; return $s }; + +sub call_curl { + my ($cmd) = @_; + my $output = `"$curl" $cmd`; + if ($? == -1) { + die "Could not run curl: $!"; + } elsif ((my $exit_code = $? >> 8) != 0) { + die "curl returned $exit_code with output:\n$output"; + } + return split /\n/, $output; +} + +__END__ + +=head1 NAME + +completion.pl - Generates tab-completion files for various shells + +=head1 SYNOPSIS + +completion.pl [options...] + + --curl path to curl executable + --shell zsh/fish + --help prints this help + +=cut diff --git a/local-test-curl-full-01/afc-curl/scripts/contributors.sh b/local-test-curl-full-01/afc-curl/scripts/contributors.sh new file mode 100644 index 0000000000000000000000000000000000000000..ad6f0b566286385ad50d9dab3b8cb657fdd03b11 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/contributors.sh @@ -0,0 +1,99 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# +# This script shows all mentioned contributors from the given / +# until HEAD and adds the contributors already mentioned in the existing +# RELEASE-NOTES. +# + +set -eu + +start="${1:-}" + +if test "$start" = "-h"; then + echo "Usage: $0 [--releasenotes]" + exit +fi +if test -z "$start"; then + start=$(git tag --sort=taggerdate | grep "^curl-" | tail -1) + echo "Since $start:" +fi + +# We also include curl-www if possible. Override by setting CURLWWW +CURLWWW="${CURLWWW:-../curl-www}" + +# filter out Author:, Commit: and *by: lines +# cut off the email parts +# split list of names at comma +# split list of names at " and " +# cut off spaces first and last on the line +# filter alternatives through THANKS-filter +# only count names with a space (ie more than one word) +# sort all unique names +# awk them into RELEASE-NOTES format + +{ + { + git log --pretty=full --use-mailmap "$start..HEAD" + if [ -d "$CURLWWW" ]; then + git -C "$CURLWWW" log --pretty=full --use-mailmap "$start..HEAD" + fi + } | \ + grep -Eai '(^Author|^Commit|by):' | \ + cut -d: -f2- | \ + cut '-d(' -f1 | \ + cut '-d<' -f1 | \ + tr , '\012' | \ + sed 's/ at github/ on github/' | \ + sed 's/ and /\n/' | \ + sed -e 's/^ *//' -e 's/ $//g' -e 's/@users.noreply.github.com$/ on github/' + + grep -a "^ [^ \(]" RELEASE-NOTES| \ + sed 's/, */\n/g'| \ + sed 's/^ *//' +} | \ +sed -f ./docs/THANKS-filter | \ +sort -fu | \ +awk ' +{ + if(length($0)) { + num++; + n = sprintf("%s%s%s,", n, length(n)?" ":"", $0); + #print n; + if(length(n) > 77) { + printf(" %s\n", p); + n=sprintf("%s,", $0); + } + p=n; + } +} + +END { + pp=substr(p,1,length(p)-1); + printf(" %s\n", pp); + printf(" (%d contributors)\n", num); +} +' diff --git a/local-test-curl-full-01/afc-curl/scripts/contrithanks.sh b/local-test-curl-full-01/afc-curl/scripts/contrithanks.sh new file mode 100644 index 0000000000000000000000000000000000000000..2afc30c24406f46779f0490649c808789a381722 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/contrithanks.sh @@ -0,0 +1,73 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# +# This script shows all mentioned contributors from until HEAD and +# puts them at the end of the THANKS document on stdout +# + +set -eu + +start="${1:-}" + +if test "$start" = "-h"; then + echo "Usage: $0 " + exit +fi +if test -z "$start"; then + start=$(git tag --sort=taggerdate | grep "^curl-" | tail -1) +fi + +# We also include curl-www if possible. Override by setting CURLWWW +CURLWWW="${CURLWWW:-../curl-www}" + +cat ./docs/THANKS + +{ + { + git log --use-mailmap "$start..HEAD" + if [ -d "$CURLWWW" ]; then + git -C "$CURLWWW" log --use-mailmap "$start..HEAD" + fi + } | \ + grep -Eai '(^Author|^Commit|by):' | \ + cut -d: -f2- | \ + cut '-d(' -f1 | \ + cut '-d<' -f1 | \ + tr , '\012' | \ + sed 's/ at github/ on github/' | \ + sed 's/ and /\n/' | \ + sed -e 's/^ //' -e 's/ $//g' -e 's/@users.noreply.github.com$/ on github/' + + # grep out the list of names from RELEASE-NOTES + # split on ", " + # remove leading whitespace + grep -a "^ [^ (]" RELEASE-NOTES| \ + sed 's/, */\n/g'| \ + sed 's/^ *//' +} | \ +sed -f ./docs/THANKS-filter | \ +sort -fu | \ +grep -aixvFf ./docs/THANKS diff --git a/local-test-curl-full-01/afc-curl/scripts/coverage.sh b/local-test-curl-full-01/afc-curl/scripts/coverage.sh new file mode 100644 index 0000000000000000000000000000000000000000..b5540568ff0fc0569d5eeb438fcf9d26cc4b7b4a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/coverage.sh @@ -0,0 +1,41 @@ +#!/bin/sh +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +autoreconf -fi +mkdir -p cvr +cd cvr +../configure --disable-shared --enable-debug --enable-maintainer-mode --enable-code-coverage +make -sj +# the regular test run +make TFLAGS=-n test-nonflaky +# make all allocs/file operations fail +#make TFLAGS=-n test-torture +# do everything event-based +make TFLAGS=-n test-event +lcov -d . -c -o cov.lcov +genhtml cov.lcov --output-directory coverage --title "curl code coverage" +tar -cjf curl-coverage.tar.bz2 coverage diff --git a/local-test-curl-full-01/afc-curl/scripts/delta b/local-test-curl-full-01/afc-curl/scripts/delta new file mode 100644 index 0000000000000000000000000000000000000000..43bc25ce1bc0c2ca817507f95dd31bcdb89ad177 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/delta @@ -0,0 +1,169 @@ +#!/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 +# +########################################################################### + +# Display changes done in the repository from [tag] until now. +# +# Uses git for repo data. +# Uses docs/THANKS and RELEASE-NOTES for current status. +# +# In the git clone root, invoke 'scripts/delta [release tag]' + +$start = $ARGV[0]; + +if($start eq "-h") { + print "Usage: summary [tag]\n"; + exit; +} +elsif($start eq "") { + $start = `git tag --sort=taggerdate | grep "^curl-" | tail -1`; + chomp $start; +} + +$commits = `git log --oneline $start.. | wc -l`; +$committers = `git shortlog -s $start.. | wc -l`; +$bcommitters = `git shortlog -s $start | wc -l`; + +$acommits = `git log --oneline | wc -l`; +$acommitters = `git shortlog -s | wc -l`; + +# delta from now compared to before +$ncommitters = $acommitters - $bcommitters; + +# number of contributors right now +$acontribs = `./scripts/contrithanks.sh | grep -c '^[^ ]'`; +# number when the tag was set +$bcontribs = `git show $start:docs/THANKS | grep -c '^[^ ]'`; +# delta +$contribs = $acontribs - $bcontribs; + +# number of setops: +sub setopts { + my ($f)=@_; + open(H, "$f"); + my $opts; + while() { + if(/^ CURLOPT(|DEPRECATED)\(/ && ($_ !~ /OBSOLETE/)) { + $opts++; + } + } + close(H); + return $opts; +} +$asetopts = setopts("/dev/null | grep -c '{"....--'`; +$noptions=$aoptions - $boptions; + +# current local branch +$branch=`git rev-parse --abbrev-ref HEAD 2>/dev/null`; +chomp $branch; +# Number of files in git +$afiles=`git ls-files | wc -l`; +$deletes=`git diff-tree --diff-filter=A -r --summary origin/$branch $start 2>/dev/null | wc -l`; +$creates=`git diff-tree --diff-filter=D -r --summary origin/$branch $start 2>/dev/null| wc -l`; + +# Time since that tag +$tagged=`git for-each-ref --format="%(refname:short) | %(taggerdate:unix)" refs/tags/* | grep ^$start | cut "-d|" -f2`; # Unix timestamp +$taggednice=`git for-each-ref --format="%(refname:short) | %(creatordate)" refs/tags/* | grep ^$start | cut '-d|' -f2`; # human readable time +chomp $taggednice; +$now=`date +%s`; +$elapsed=$now - $tagged; # number of seconds since tag +$total=$now - `date -d 19980320 +%s`; + +# Number of public functions in libcurl +$apublic=`git grep ^CURL_EXTERN -- include/curl | wc -l`; +$bpublic=`git grep ^CURL_EXTERN $start -- include/curl | wc -l`; +$public = $apublic - $bpublic; + +# diffstat +$diffstat=`git diff --stat $start.. | tail -1`; +if($diffstat =~ /^ *(\d+) files changed, (\d+) insertions\(\+\), (\d+)/) { + ($fileschanged, $insertions, $deletions)=($1, $2, $3); +} + +# Changes/bug-fixes currently logged +open(F, ") { + if($_ =~ /following changes:/) { + $mode=1; + } + elsif($_ =~ /following bugfixes:/) { + $mode=2; + } + elsif($_ =~ /known bugs:/) { + $mode=3; + } + elsif($_ =~ /like these:/) { + $mode=4; + } + if($_ =~ /^ o /) { + if($mode == 1) { + $numchanges++; + } + elsif($mode == 2) { + $numbugfixes++; + } + } + if(($mode == 4) && ($_ =~ /^ \((\d+) contributors/)) { + $numcontributors = $1; + } +} +close(F); + +######################################################################## +# Produce the summary + +print "== Since $start $taggednice ==\n"; +my $days = $elapsed / 3600 / 24; +printf "Elapsed time: %.1f days (total %d)\n", + $days, $total / 3600 / 24; +printf "Commits: %d (total %d)\n", + $commits, $acommits; +printf "Commit authors: %d, %d new (total %d)\n", + $committers, $ncommitters, $acommitters; +printf "Contributors: %d, %d new (total %d)\n", + $numcontributors, $contribs, $acontribs; +printf "New public functions: %d (total %d)\n", + $public, $apublic; +printf "New curl_easy_setopt() options: %d (total %d)\n", + $nsetopts, $asetopts; +printf "New command line options: %d (total %d)\n", + $noptions, $aoptions; +printf "Changes logged: %d\n", $numchanges; +printf "Bugfixes logged: %d (%.2f per day)\n", + $numbugfixes, $numbugfixes / $days; +printf "Added files: %d (total %d)\n", + $creates, $afiles; +printf "Deleted files: %d (delta: %d)\n", $deletes, + $creates - $deletes; +print "Diffstat:$diffstat" if(!$fileschanged); +printf "Files changed: %d (%.2f%%)\n", $fileschanged, $fileschanged*100/$afiles; +printf "Lines inserted: %d\n", $insertions; +printf "Lines deleted: %d (delta: %d)\n", $deletions, + $insertions - $deletions; diff --git a/local-test-curl-full-01/afc-curl/scripts/dmaketgz b/local-test-curl-full-01/afc-curl/scripts/dmaketgz new file mode 100644 index 0000000000000000000000000000000000000000..fb7bfef2aa8212625135146a5e7a37f154634f5b --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/dmaketgz @@ -0,0 +1,55 @@ +#!/bin/sh +# docker-maketgz +# +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +version="${1:-}" + +if [ -z "$version" ]; then + echo "Specify a version number!" + exit +fi + +timestamp="${2:-$(date -u +%s)}" + +if test -f Makefile; then + make distclean +fi +docker build \ + --no-cache \ + --build-arg SOURCE_DATE_EPOCH="$timestamp" \ + --build-arg UID="$(id -u)" \ + --build-arg GID="$(id -g)" \ + -t curl/curl . + +docker run --rm -u "$(id -u):$(id -g)" \ + -v "$(pwd):/usr/src" -w /usr/src curl/curl sh -c " + set -e + autoreconf -fi + ./configure --without-ssl --without-libpsl + make -sj8 + ./scripts/maketgz $version" diff --git a/local-test-curl-full-01/afc-curl/scripts/firefox-db2pem.sh b/local-test-curl-full-01/afc-curl/scripts/firefox-db2pem.sh new file mode 100644 index 0000000000000000000000000000000000000000..57252b40578e9da4de356e9bf42fbb3eaf62babc --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/firefox-db2pem.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# *************************************************************************** +# * _ _ ____ _ +# * Project ___| | | | _ \| | +# * / __| | | | |_) | | +# * | (__| |_| | _ <| |___ +# * \___|\___/|_| \_\_____| +# * +# * Copyright (C) Daniel Stenberg, , et al. +# * +# * This software is licensed as described in the file COPYING, which +# * you should have received as part of this distribution. The terms +# * are also available at https://curl.se/docs/copyright.html. +# * +# * You may opt to use, copy, modify, merge, publish, distribute and/or sell +# * copies of the Software, and permit persons to whom the Software is +# * furnished to do so, under the terms of the COPYING file. +# * +# * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# * KIND, either express or implied. +# * +# * SPDX-License-Identifier: curl +# * +# *************************************************************************** +# This shell script creates a fresh ca-bundle.crt file for use with libcurl. +# It extracts all ca certs it finds in the local Firefox database and converts +# them all into PEM format. +# +# It uses the "certutil" command line tool from the NSS project to perform the +# conversion. On Debian it comes in the "libnss3-tools" package. +# + +set -eu + +db=$(ls -1d "$HOME"/.mozilla/firefox/*default*) +out="${1:-}" + +if test -z "$out"; then + out="ca-bundle.crt" # use a sensible default +fi + +currentdate=$(date) + +cat > "$out" <> "$out" diff --git a/local-test-curl-full-01/afc-curl/scripts/installcheck.sh b/local-test-curl-full-01/afc-curl/scripts/installcheck.sh new file mode 100644 index 0000000000000000000000000000000000000000..b13db2aa3933c3379c0aaf0cd73086597a87cb2f --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/installcheck.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +PREFIX="${1:-}" + +# Run this script in the root of the git clone. Point out the install prefix +# where 'make install' has already installed curl. + +if test -z "$PREFIX"; then + echo "scripts/installcheck.sh [PREFIX]" + exit +fi + +diff -u <(find docs/libcurl/ -name "*.3" -printf "%f\n" | grep -v template | sort) <(find "$PREFIX/share/man/" -name "*.3" -printf "%f\n" | sort) + +if test "$?" -ne "0"; then + echo "ERROR: installed libcurl docs mismatch" + exit 2 +fi + +diff -u <(find include/ -name "*.h" -printf "%f\n" | sort) <(find "$PREFIX/include/" -name "*.h" -printf "%f\n" | sort) + +if test "$?" -ne "0"; then + echo "ERROR: installed include files mismatch" + exit 1 +fi + +echo "installcheck: installed libcurl docs and include files look good" diff --git a/local-test-curl-full-01/afc-curl/scripts/maketgz b/local-test-curl-full-01/afc-curl/scripts/maketgz new file mode 100644 index 0000000000000000000000000000000000000000..af62708bc1c92570fd5c74b13cdffee1cef75040 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/maketgz @@ -0,0 +1,247 @@ +#!/bin/sh +# Script to build release-archives with. Note that this requires a checkout +# from git and you should first run autoreconf -fi and build curl once. +# +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +set -eu + +export LC_ALL=C +export TZ=UTC + +version="${1:-}" +cmd="${2:-}" + +if [ -z "$version" ]; then + echo "Specify a version number!" + exit +fi + +echo "$cmd" + +only="" +if [ "only" = "$cmd" ]; then + echo "Setup version number only!" + only=1 +fi + +commit="" +if [ "commit" = "$cmd" ]; then + commit=1 +fi + +libversion="$version" + +# we make curl the same version as libcurl +curlversion="$libversion" + +major=$(echo "$libversion" | cut -d. -f1 | sed -e "s/[^0-9]//g") +minor=$(echo "$libversion" | cut -d. -f2 | sed -e "s/[^0-9]//g") +patch=$(echo "$libversion" | cut -d. -f3 | cut -d- -f1 | sed -e "s/[^0-9]//g") + +if test -z "$patch"; then + echo "invalid version number? needs to be z.y.z" + exit +fi + +# +# As a precaution, remove all *.dist files that may be lying around, to reduce +# the risk of old leftovers getting shipped. The root 'Makefile.dist' is the +# exception. +echo "removing all old *.dist files" +find . -name "*.dist" -a ! -name Makefile.dist -exec rm {} \; + +numeric="$(printf "%02x%02x%02x\n" "$major" "$minor" "$patch")" + +HEADER=include/curl/curlver.h +CHEADER=src/tool_version.h + +if test -z "$only"; then + ext=".dist" + # when not setting up version numbers locally + for a in $HEADER $CHEADER; do + cp "$a" "$a$ext" + done + HEADER="$HEADER$ext" + CHEADER="$CHEADER$ext" +fi + +# requires a date command that knows + for format and -d for date input +timestamp=${SOURCE_DATE_EPOCH:-$(date +"%s")} +datestamp=$(date -d "@$timestamp" +"%F") +filestamp=$(date -d "@$timestamp" +"%Y%m%d%H%M.%S") + +# Replace version number in header file: +sed -i \ + -e "s/^#define LIBCURL_VERSION .*/#define LIBCURL_VERSION \"$libversion\"/g" \ + -e "s/^#define LIBCURL_VERSION_NUM .*/#define LIBCURL_VERSION_NUM 0x$numeric/g" \ + -e "s/^#define LIBCURL_VERSION_MAJOR .*/#define LIBCURL_VERSION_MAJOR $major/g" \ + -e "s/^#define LIBCURL_VERSION_MINOR .*/#define LIBCURL_VERSION_MINOR $minor/g" \ + -e "s/^#define LIBCURL_VERSION_PATCH .*/#define LIBCURL_VERSION_PATCH $patch/g" \ + -e "s/^#define LIBCURL_TIMESTAMP .*/#define LIBCURL_TIMESTAMP \"$datestamp\"/g" \ + "$HEADER" + +# Replace version number in header file: +sed -i "s/#define CURL_VERSION .*/#define CURL_VERSION \"$curlversion\"/g" "$CHEADER" + +if test -n "$only"; then + # done! + exit +fi + +echo "curl version $curlversion" +echo "libcurl version $libversion" +echo "libcurl numerical $numeric" +echo "datestamp $datestamp" + +findprog() { + file="$1" + for part in $(echo "$PATH" | tr ':' ' '); do + path="$part/$file" + if [ -x "$path" ]; then + # there it is! + return 1 + fi + done + + # no such executable + return 0 +} + +############################################################################ +# +# Enforce a rerun of configure (updates the VERSION) +# + +echo "Re-running config.status" +./config.status --recheck >/dev/null + +echo "Recreate the built-in manual (with correct version)" +export CURL_MAKETGZ_VERSION="$version" +rm -f docs/cmdline-opts/curl.txt +make -C src + +############################################################################ +# +# automake is needed to run to make a non-GNU Makefile.in if Makefile.am has +# been modified. +# + +if { findprog automake >/dev/null 2>/dev/null; } then + echo "- Could not find or run automake, I hope you know what you are doing!" +else + echo "Runs automake --include-deps" + automake --include-deps Makefile >/dev/null +fi + +if test -n "$commit"; then + echo "produce docs/tarball-commit.txt" + git rev-parse HEAD >docs/tarball-commit.txt.dist +fi + +echo "produce RELEASE-TOOLS.md" +./scripts/release-tools.sh "$timestamp" "$version" "$commit" > docs/RELEASE-TOOLS.md.dist + +############################################################################ +# +# Now run make dist to generate a tar.gz archive +# + +echo "make dist" +targz="curl-$version.tar.gz" +make -sj dist "VERSION=$version" +res=$? + +if test "$res" != 0; then + echo "make dist failed" + exit 2 +fi + +retar() { + tempdir=$1 + rm -rf "$tempdir" + mkdir "$tempdir" + cd "$tempdir" + gzip -dc "../$targz" | tar -xf - + find curl-* -depth -exec touch -c -t "$filestamp" '{}' + + tar --create --format=ustar --owner=0 --group=0 --numeric-owner --sort=name curl-* | gzip --best --no-name > out.tar.gz + mv out.tar.gz ../ + cd .. + rm -rf "$tempdir" +} + +retar ".tarbuild" +echo "replace $targz with out.tar.gz" +mv out.tar.gz "$targz" + +############################################################################ +# +# Now make a bz2 archive from the tar.gz original +# + +bzip2="curl-$version.tar.bz2" +echo "Generating $bzip2" +gzip -dc "$targz" | bzip2 --best > "$bzip2" + +############################################################################ +# +# Now make an xz archive from the tar.gz original +# + +xz="curl-$version.tar.xz" +echo "Generating $xz" +gzip -dc "$targz" | xz -6e - > "$xz" + +############################################################################ +# +# Now make a zip archive from the tar.gz original +# +makezip() { + rm -rf "$tempdir" + mkdir "$tempdir" + cd "$tempdir" + gzip -dc "../$targz" | tar -xf - + find . | sort | zip -9 -X "$zip" -@ >/dev/null + mv "$zip" ../ + cd .. + rm -rf "$tempdir" +} + +zip="curl-$version.zip" +echo "Generating $zip" +tempdir=".builddir" +makezip + +# Set deterministic timestamp +touch -c -t "$filestamp" "$targz" "$bzip2" "$xz" "$zip" + +echo "------------------" +echo "maketgz report:" +echo "" +ls -l "$targz" "$bzip2" "$xz" "$zip" +sha256sum "$targz" "$bzip2" "$xz" "$zip" + +echo "Run this:" +echo "gpg -b -a '$targz' && gpg -b -a '$bzip2' && gpg -b -a '$xz' && gpg -b -a '$zip'" diff --git a/local-test-curl-full-01/afc-curl/scripts/managen b/local-test-curl-full-01/afc-curl/scripts/managen new file mode 100644 index 0000000000000000000000000000000000000000..20abfc12efefbfd0d008322cfbd2004e876c6639 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/scripts/managen @@ -0,0 +1,1279 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +=begin comment + +This script generates the manpage. + +Example: managen [files] > curl.1 + +Dev notes: + +We open *input* files in :crlf translation (a no-op on many platforms) in +case we have CRLF line endings in Windows but a perl that defaults to LF. +Unfortunately it seems some perls like msysgit cannot handle a global input-only +:crlf so it has to be specified on each file open for text input. + +=end comment +=cut + +my %optshort; +my %optlong; +my %helplong; +my %arglong; +my %redirlong; +my %protolong; +my %catlong; + +use POSIX qw(strftime); +my @ts; +if (defined($ENV{SOURCE_DATE_EPOCH})) { + @ts = gmtime($ENV{SOURCE_DATE_EPOCH}); +} else { + @ts = localtime; +} +my $date = strftime "%Y-%m-%d", @ts; +my $year = strftime "%Y", @ts; +my $version = "unknown"; +my $globals; +my $error = 0; +my $indent = 4; + +# get the long name version, return the manpage string +sub manpageify { + my ($k)=@_; + my $l; + my $trail; + # the matching pattern might include a trailing dot that cannot be part of + # the option name + if($k =~ s/\.$//) { + # cut off trailing dot + $trail = "."; + } + my $klong = $k; + # quote "bare" minuses in the long name + $klong =~ s/-/\\-/g; + if($optlong{$k}) { + # both short + long + $l = "\\fI-".$optlong{$k}.", \\-\\-$klong\\fP$trail"; + } + else { + # only long + $l = "\\fI\\-\\-$klong\\fP$trail"; + } + return $l; +} + + +my $colwidth=79; # max number of columns + +sub prefixline { + my ($num) = @_; + print "\t" x ($num/8); + print ' ' x ($num%8); +} + +sub justline { + my ($lvl, @line) = @_; + my $w = -1; + my $spaces = -1; + my $width = $colwidth - ($lvl * $indent); + for(@line) { + $w += length($_); + $w++; + $spaces++; + } + my $inject = $width - $w; + my $ratio = 0; # stay at zero if no spaces at all + if($spaces) { + $ratio = $inject / $spaces; + } + my $spare = 0; + prefixline($lvl * $indent); + my $prev; + for(@line) { + while($spare >= 0.90) { + print " "; + $spare--; + } + printf "%s%s", $prev?" ":"", $_; + $prev = 1; + $spare += $ratio; + } + print "\n"; +} + +sub lastline { + my ($lvl, @line) = @_; + $line[0] =~ s/^( +)//; + prefixline($lvl * $indent + length($1)); + my $prev = 0; + for(@line) { + printf "%s%s", $prev?" ":"", $_; + $prev = 1; + } + print "\n"; +} + +sub outputpara { + my ($lvl, $f) = @_; + $f =~ s/\n/ /g; + + my $w = 0; + my @words = split(/ */, $f); + my $width = $colwidth - ($lvl * $indent); + + my @line; + for my $e (@words) { + my $l = length($e); + my $spaces = scalar(@line); + if(($w + $l + $spaces) >= $width) { + justline($lvl, @line); + undef @line; + $w = 0; + } + + push @line, $e; + $w += $l; # new width + } + if($w) { + lastline($lvl, @line); + print "\n"; + } +} + +sub printdesc { + my ($manpage, $baselvl, @desc) = @_; + + if($manpage) { + for my $d (@desc) { + print $d; + } + } + else { + my $p = -1; + my $para; + for my $l (@desc) { + my $lvl; + if($l !~ /^[\n\r]+/) { + # get the indent level off the string + $l =~ s/^\[([0-9q]*)\]//; + $lvl = $1; + } + if(($p =~ /q/) && ($lvl !~ /q/)) { + # the previous was quoted, this is not + print "\n"; + } + if($lvl != $p) { + outputpara($baselvl + $p, $para); + $para = ""; + } + if($lvl =~ /q/) { + # quoted, do not right-justify + chomp $l; + lastline($baselvl + $lvl + 1, $l); + my $w = ($baselvl + $lvl + 1) * $indent + length($l); + if ($w > $colwidth) { + print STDERR "ERROR: $w columns is too long\n"; + print STDERR "$l\n"; + $error++; + } + } + else { + $para .= $l; + } + + $p = $lvl; + } + outputpara($baselvl + $p, $para); + } +} + +sub seealso { + my($standalone, $data)=@_; + if($standalone) { + return sprintf + ".SH \"SEE ALSO\"\n$data\n"; + } + else { + return "See also $data. "; + } +} + +sub overrides { + my ($standalone, $data)=@_; + if($standalone) { + return ".SH \"OVERRIDES\"\n$data\n"; + } + else { + return $data; + } +} + +sub protocols { + my ($manpage, $standalone, $data)=@_; + if($standalone) { + return ".SH \"PROTOCOLS\"\n$data\n"; + } + else { + return "($data) " if($manpage); + return "[1]($data) " if(!$manpage); + } +} + +sub too_old { + my ($version)=@_; + my $a = 999999; + if($version =~ /^(\d+)\.(\d+)\.(\d+)/) { + $a = $1 * 1000 + $2 * 10 + $3; + } + elsif($version =~ /^(\d+)\.(\d+)/) { + $a = $1 * 1000 + $2 * 10; + } + if($a < 7600) { + # we consider everything before 7.60.0 to be too old to mention + # specific changes for + return 1; + } + return 0; +} + +sub added { + my ($standalone, $data)=@_; + if(too_old($data)) { + # do not mention ancient additions + return ""; + } + if($standalone) { + return ".SH \"ADDED\"\nAdded in curl version $data\n"; + } + else { + return "Added in $data. "; + } +} + +sub render { + my ($manpage, $fh, $f, $line) = @_; + my @desc; + my $tablemode = 0; + my $header = 0; + # if $top is TRUE, it means a top-level page and not a command line option + my $top = ($line == 1); + my $quote; + my $level; + my $finalblank; + $start = 0; + + while(<$fh>) { + my $d = $_; + $line++; + $finalblank = ($d eq "\n"); + if($d =~ /^\.(SH|BR|IP|B)/) { + print STDERR "$f:$line:1:ERROR: nroff instruction in input: \".$1\"\n"; + return 4; + } + if(/^ * + +# Continuous Integration for curl + +Curl runs in many different environments, so every change is run against a +large number of test suites. + +Every pull request is verified for each of the following: + + - ... it still builds, warning-free, on Linux and macOS, with both + clang and gcc + - ... it still builds fine on Windows with several MSVC versions + - ... it still builds with cmake on Linux, with gcc and clang + - ... it follows rudimentary code style rules + - ... the test suite still runs 100% fine + - ... the release tarball (the "dist") still works + - ... it builds fine in-tree as well as out-of-tree + - ... code coverage does not shrink drastically + - ... different TLS backends still compile and pass tests + +If the pull-request fails one of these tests, it shows up as a red X and you +are expected to fix the problem. If you do not understand when the issue is or +have other problems to fix the complaint, just ask and other project members +can likely help out. + +Consider the following table while looking at pull request failures: + + | CI platform as shown in PR | State | What to look at next | + | ----------------------------------- | ------ | -------------------------- | + | CI / codeql | stable | quality check results | + | CI / fuzzing | stable | fuzzing results | + | CI / macos ... | stable | all errors and failures | + | Code scanning results / CodeQL | stable | quality check results | + | FreeBSD FreeBSD: ... | stable | all errors and failures | + | LGTM analysis: Python | stable | new findings | + | LGTM analysis: C/C++ | stable | new findings | + | buildbot/curl_winssl_ ... | stable | all errors and failures | + | AppVeyor | flaky | all errors and failures | + | curl.curl (linux ...) | stable | all errors and failures | + | curl.curl (windows ...) | flaky | repetitive errors/failures | + | CodeQL | stable | new findings | + +Sometimes the tests fail due to a dependency service temporarily being offline +or otherwise unavailable, for example package downloads. In this case you can +just try to update your pull requests to rerun the tests later as described +below. + +## CI servers + +Here are the different CI environments that are currently in use, and how they +are configured: + +### GitHub Actions + +GitHub Actions runs the following tests: + +- macOS tests with a variety of different compilation options +- Fuzz tests ([see the curl-fuzzer repo for more + info](https://github.com/curl/curl-fuzzer)). +- Curl compiled using the Rust TLS backend with Hyper +- CodeQL static analysis + +These are each configured in different files in `.github/workflows`. + +### Azure + +Not used anymore. + +### AppVeyor + +AppVeyor runs a variety of different Windows builds, with different compilation +options. + +As of November 2021 `@bagder`, `@mback2k`, `@jay`, `@vszakats`, `@dfandrich` +and `@danielgustafsson` have administrator access to the AppVeyor CI +environment. Additional admins/group members can be added on request. + +The tests are configured in `appveyor.yml`. + +### Zuul + +Not used anymore. + +### Circle CI + +Circle CI runs a basic Linux test suite on Ubuntu for both x86 and ARM +processors. This is configured in `.circleci/config.yml`. + +You can [view the full list of CI jobs on Circle CI's +website](https://app.circleci.com/pipelines/github/curl/curl). + +`@bagder` has access to edit the "Project Settings" on that page. Additional +admins/group members can be added on request. + +### Cirrus CI + +Not used anymore. diff --git a/local-test-curl-full-01/afc-curl/tests/CMakeLists.txt b/local-test-curl-full-01/afc-curl/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0e40b2e19243a36a4d562dc51cb3b8c6a4d3c801 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/CMakeLists.txt @@ -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 +# +########################################################################### +option(CURL_TEST_BUNDLES "Bundle libtest and unittest tests into single binaries" OFF) + +find_program(TEST_NGHTTPX "nghttpx") +if(NOT TEST_NGHTTPX) + set(TEST_NGHTTPX "nghttpx") +endif() +mark_as_advanced(TEST_NGHTTPX) +# Consumed variables: TEST_NGHTTPX +configure_file("config.in" "${CMAKE_CURRENT_BINARY_DIR}/config" @ONLY) + +add_custom_target(testdeps) +add_subdirectory(http) +add_subdirectory(http/clients) +add_subdirectory(server) +add_subdirectory(libtest) +add_subdirectory(unit) +add_subdirectory(certs EXCLUDE_FROM_ALL) + +function(add_runtests _targetname _test_flags) + if(CURL_TEST_BUNDLES) + set(_test_flags "${_test_flags} -bundle") + endif() + if(NOT BUILD_LIBCURL_DOCS) + set(_test_flags "${_test_flags} !documentation") + endif() + # Skip walking through dependent targets before running tests in CI. + # This avoids: GNU Make doing a slow re-evaluation of all targets and + # skipping them, MSBuild doing a re-evaluation, and actually rebuilding them. + unset(_depends) + if(NOT _targetname STREQUAL "test-ci") + set(_depends "testdeps") + endif() + # Use a special '$TFLAGS' placeholder as last argument which will be + # replaced by the contents of the environment variable in runtests.pl. + # This is a workaround for CMake's limitation where commands executed by + # 'make' or 'ninja' cannot portably reference environment variables. + string(REPLACE " " ";" _test_flags_list "${_test_flags}") + add_custom_target(${_targetname} + COMMAND + "${PERL_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/runtests.pl" + ${_test_flags_list} + "\$TFLAGS" + DEPENDS "${_depends}" + VERBATIM USES_TERMINAL + ) +endfunction() + +function(add_pytest _targetname _test_flags) + unset(_depends) + if(NOT _targetname STREQUAL "pytest-ci") + set(_depends "test-http-clients") + endif() + string(REPLACE " " ";" _test_flags_list "${_test_flags}") + add_custom_target(${_targetname} + COMMAND pytest ${_test_flags_list} "${CMAKE_CURRENT_SOURCE_DIR}/http" + DEPENDS "${_depends}" + VERBATIM USES_TERMINAL + ) +endfunction() + +# Create configurehelp.pm, used by tests needing to run the C preprocessor. +if(MSVC OR CMAKE_COMPILER_IS_GNUCC OR CMAKE_C_COMPILER_ID MATCHES "Clang") + set(CURL_CPP "\"${CMAKE_C_COMPILER}\" -E") + if(APPLE AND CMAKE_OSX_SYSROOT) + set(CURL_CPP "${CURL_CPP} -isysroot ${CMAKE_OSX_SYSROOT}") + endif() + # Add header directories, like autotools builds do. + get_property(_include_dirs TARGET ${LIB_SELECTED} PROPERTY INCLUDE_DIRECTORIES) + foreach(_include_dir IN LISTS _include_dirs) + set(CURL_CPP "${CURL_CPP} -I${_include_dir}") + endforeach() +else() + set(CURL_CPP "cpp") +endif() +# Generate version script for the linker, for versioned symbols. +# Consumed variable: +# CURL_CPP +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/configurehelp.pm.in" + "${CMAKE_CURRENT_BINARY_DIR}/configurehelp.pm" @ONLY) + +add_runtests(test-quiet "-a -s") +add_runtests(test-am "-a -am") +add_runtests(test-full "-a -p -r") +# ~flaky means that it ignores results of tests using the flaky keyword +add_runtests(test-nonflaky "-a -p ~flaky ~timing-dependent") +add_runtests(test-ci "-a -p ~flaky ~timing-dependent -r -rm -j20") +add_runtests(test-torture "-a -t -j20") +add_runtests(test-event "-a -e") + +add_pytest(curl-pytest "") +add_pytest(curl-pytest-ci "-v") diff --git a/local-test-curl-full-01/afc-curl/tests/FILEFORMAT.md b/local-test-curl-full-01/afc-curl/tests/FILEFORMAT.md new file mode 100644 index 0000000000000000000000000000000000000000..b15274e17ae9b455a09086afc6f2e644b7ff8115 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/FILEFORMAT.md @@ -0,0 +1,720 @@ + + +# curl test suite file format + +The curl test suite's file format is simple and extendable, closely resembling +XML. All data for a single test case resides in a single ASCII file. Labels +mark the beginning and the end of all sections, and each label must be written +in its own line. Comments are either XML-style (enclosed with ``) or shell script style (beginning with `#`) and must appear on their own +lines and not alongside actual test data. Most test data files are +syntactically valid XML, although a few files are not (lack of support for +character entities and the preservation of CR/LF characters at the end of +lines are the biggest differences). + +Each test case source exists as a file matching the format +`tests/data/testNUM`, where `NUM` is the unique test number, and must begin +with a `testcase` tag, which encompasses the remainder of the file. + +# Preprocessing + +When a test is to be executed, the source file is first preprocessed and +variables are substituted by their respective contents and the output version +of the test file is stored as `%LOGDIR/testNUM`. That version is what is read +and used by the test servers. + +## Base64 Encoding + +In the preprocess stage, a special instruction can be used to have runtests.pl +base64 encode a certain section and insert in the generated output file. This +is in particular good for test cases where the test tool is expected to pass +in base64 encoded content that might use dynamic information that is unique +for this particular test invocation, like the server port number. + +To insert a base64 encoded string into the output, use this syntax: + + %b64[ data to encode ]b64% + +The data to encode can then use any of the existing variables mentioned below, +or even percent-encoded individual bytes. As an example, insert the HTTP +server's port number (in ASCII) followed by a space and the hexadecimal byte +9a: + + %b64[%HTTPPORT %9a]b64% + +## Hexadecimal decoding + +In the preprocess stage, a special instruction can be used to have runtests.pl +generate a sequence of binary bytes. + +To insert a sequence of bytes from a hex encoded string, use this syntax: + + %hex[ %XX-encoded data to decode ]hex% + +For example, to insert the binary octets 0, 1 and 255 into the test file: + + %hex[ %00%01%FF ]hex% + +## Repeat content + +In the preprocess stage, a special instruction can be used to have runtests.pl +generate a repetitive sequence of bytes. + +To insert a sequence of repeat bytes, use this syntax to make the `` +get repeated `` of times. The number has to be 1 or larger and the +string may contain `%HH` hexadecimal codes: + + %repeat[ x ]% + +For example, to insert the word hello 100 times: + + %repeat[100 x hello]% + +## Include file + +This instruction allows a test case to include another file. It is helpful to +remember that the ordinary variables are expanded before the include happens +so `%LOGDIR` and the others can be used in the include line. + +The filename cannot contain `%` as that letter is used to end the name for +the include instruction: + + %include filename% + +## Conditional lines + +Lines in the test file can be made to appear conditionally on a specific +feature (see the "features" section below) being set or not set. If the +specific feature is present, the following lines are output, otherwise it +outputs nothing, until a following else or `endif` clause. Like this: + + %if brotli + Accept-Encoding + %endif + +It can also check for the inverse condition, so if the feature is *not* set by +the use of an exclamation mark: + + %if !brotli + Accept-Encoding: not-brotli + %endif + +You can also make an "else" clause to get output for the opposite condition, +like: + + %if brotli + Accept-Encoding: brotli + %else + Accept-Encoding: nothing + %endif + +Nested conditions are supported. + +# Variables + +When the test is preprocessed, a range of "variables" in the test file is +replaced by their content at that time. + +Available substitute variables include: + +- `%CLIENT6IP` - IPv6 address of the client running curl (including brackets) +- `%CLIENT6IP-NB` - IPv6 address of the client running curl (no brackets) +- `%CLIENTIP` - IPv4 address of the client running curl +- `%CURL` - Path to the curl executable +- `%DATE` - current YYYY-MM-DD date +- `%DEV_NULL` - Null device (e.g. /dev/null) +- `%FILE_PWD` - Current directory, on Windows prefixed with a slash +- `%FTP6PORT` - IPv6 port number of the FTP server +- `%FTPPORT` - Port number of the FTP server +- `%FTPSPORT` - Port number of the FTPS server +- `%FTPTIME2` - Timeout in seconds that should be just sufficient to receive a + response from the test FTP server +- `%GOPHER6PORT` - IPv6 port number of the Gopher server +- `%GOPHERPORT` - Port number of the Gopher server +- `%GOPHERSPORT` - Port number of the Gophers server +- `%HOST6IP` - IPv6 address of the host running this test +- `%HOSTIP` - IPv4 address of the host running this test +- `%HTTP2PORT` - Port number of the HTTP/2 server +- `%HTTP6PORT` - IPv6 port number of the HTTP server +- `%HTTPPORT` - Port number of the HTTP server +- `%HTTPSPORT` - Port number of the HTTPS server +- `%HTTPSPROXYPORT` - Port number of the HTTPS-proxy +- `%HTTPTLS6PORT` - IPv6 port number of the HTTP TLS server +- `%HTTPTLSPORT` - Port number of the HTTP TLS server +- `%HTTPUNIXPATH` - Path to the Unix socket of the HTTP server +- `%IMAP6PORT` - IPv6 port number of the IMAP server +- `%IMAPPORT` - Port number of the IMAP server +- `%LOGDIR` - Log directory relative to %PWD +- `%MQTTPORT` - Port number of the MQTT server +- `%NOLISTENPORT` - Port number where no service is listening +- `%POP36PORT` - IPv6 port number of the POP3 server +- `%POP3PORT` - Port number of the POP3 server +- `%POSIX_PWD` - Current directory somewhat MinGW friendly +- `%PROXYPORT` - Port number of the HTTP proxy +- `%PWD` - Current directory +- `%RTSP6PORT` - IPv6 port number of the RTSP server +- `%RTSPPORT` - Port number of the RTSP server +- `%SMBPORT` - Port number of the SMB server +- `%SMBSPORT` - Port number of the SMBS server +- `%SMTP6PORT` - IPv6 port number of the SMTP server +- `%SMTPPORT` - Port number of the SMTP server +- `%SOCKSPORT` - Port number of the SOCKS4/5 server +- `%SOCKSUNIXPATH` - Path to the Unix socket of the SOCKS server +- `%SRCDIR` - Full path to the source dir +- `%SSH_PWD` - Current directory friendly for the SSH server +- `%SSHPORT` - Port number of the SCP/SFTP server +- `%SSHSRVMD5` - MD5 of SSH server's public key +- `%SSHSRVSHA256` - SHA256 of SSH server's public key +- `%TELNETPORT` - Port number of the telnet server +- `%TESTNUMBER` - Number of the test case +- `%TFTP6PORT` - IPv6 port number of the TFTP server +- `%TFTPPORT` - Port number of the TFTP server +- `%USER` - Login ID of the user running the test +- `%VERNUM` - the version number of the tested curl (without -DEV) +- `%VERSION` - the full version number of the tested curl + +# `` + +Each test is always specified entirely within the `testcase` tag. Each test +case is split up in four main sections: `info`, `reply`, `client` and +`verify`. + +- **info** provides information about the test case + +- **reply** is used for the server to know what to send as a reply for the +requests curl sends + +- **client** defines how the client should behave + +- **verify** defines how to verify that the data stored after a command has +been run ended up correct + +Each main section has a number of available subsections that can be specified, +that are checked/used if specified. + +## `` + +### `` +A newline-separated list of keywords describing what this test case uses and +tests. Try to use already used keywords. These keywords are used for +statistical/informational purposes and for choosing or skipping classes of +tests. Keywords must begin with an alphabetic character, `-`, `[` or `{` and +may actually consist of multiple words separated by spaces which are treated +together as a single identifier. Most keywords are only there to provide a way +for users to skip certain classes of tests, if desired, but a few are treated +specially by the test harness or build system. + +When using curl built with Hyper, the keywords must include `HTTP` or `HTTPS` +for 'hyper mode' to kick in and make line ending checks work for tests. + +When running a unit test and the keywords include `unittest`, the `` +section can be left empty to use the standard unit test tool name `unitN` where +`N` is the test number. + +The `text-ci` make target automatically skips test with the `flaky` keyword. + +Tests that have strict timing dependencies have the `timing-dependent` keyword. +These are intended to eventually be treated specially on CI builds which are +often run on overloaded machines with unpredictable timing. + +## `` + +### `` + +data to be sent to the client on its request and later verified that it +arrived safely. Set `nocheck="yes"` to prevent the test script from verifying +the arrival of this data. + +If the data contains `swsclose` anywhere within the start and end tag, and +this is an HTTP test, then the connection is closed by the server after this +response is sent. If not, the connection is kept persistent. + +If the data contains `swsbounce` anywhere within the start and end tag, the +HTTP server detects if this is a second request using the same test and part +number and then increases the part number with one. This is useful for auth +tests and similar. + +`sendzero=yes` means that the (FTP) server "sends" the data even if the size +is zero bytes. Used to verify curl's behavior on zero bytes transfers. + +`base64=yes` means that the data provided in the test-file is a chunk of data +encoded with base64. It is the only way a test case can contain binary +data. (This attribute can in fact be used on any section, but it does not make +much sense for other sections than "data"). + +`hex=yes` means that the data is a sequence of hex pairs. It gets decoded and +used as "raw" data. + +`nonewline=yes` means that the last byte (the trailing newline character) +should be cut off from the data before sending or comparing it. + +`crlf=yes` forces *header* newlines to become CRLF even if not written so in +the source file. Note that this makes runtests.pl parse and "guess" what is a +header and what is not in order to apply the CRLF line endings appropriately. + +For FTP file listings, the `` section is be used *only* if you make sure +that there has been a CWD done first to a directory named `test-[NUM]` where +`NUM` is the test case number. Otherwise the ftp server cannot know from which +test file to load the list content. + +### `` + +Send back this contents instead of the `` one. The `NUM` is set by: + + - The test number in the request line is >10000 and this is the remainder + of [test case number]%10000. + - The request was HTTP and included digest details, which adds 1000 to `NUM` + - If an HTTP request is NTLM type-1, it adds 1001 to `NUM` + - If an HTTP request is NTLM type-3, it adds 1002 to `NUM` + - If an HTTP request is Basic and `NUM` is already >=1000, it adds 1 to `NUM` + - If an HTTP request is Negotiate, `NUM` gets incremented by one for each + request with Negotiate authorization header on the same test case. + +Dynamically changing `NUM` in this way allows the test harness to be used to +test authentication negotiation where several different requests must be sent +to complete a transfer. The response to each request is found in its own data +section. Validating the entire negotiation sequence can be done by specifying +a `datacheck` section. + +### `` +The connect section is used instead of the 'data' for all CONNECT +requests. The remainder of the rules for the data section then apply but with +a connect prefix. + +### `` +Address type and address details as logged by the SOCKS proxy. + +### `` +if the data is sent but this is what should be checked afterwards. If +`nonewline=yes` is set, runtests cuts off the trailing newline from the data +before comparing with the one actually received by the client. + +Use the `mode="text"` attribute if the output is in text mode on platforms +that have a text/binary difference. + +### `` +The contents of numbered `datacheck` sections are appended to the non-numbered +one. + +### `` +number to return on an ftp SIZE command (set to -1 to make this command fail) + +### `` +what to send back if the client sends a (FTP) `MDTM` command, set to -1 to +have it return that the file does not exist + +### `` +special purpose server-command to control its behavior *after* the +reply is sent +For HTTP/HTTPS, these are supported: + +`wait [secs]` - Pause for the given time + +### `` +Special-commands for the server. + +The first line of this file is always set to `Testnum [number]` by the test +script, to allow servers to read that to know what test the client is about to +issue. + +#### For FTP/SMTP/POP/IMAP + +- `REPLY [command] [return value] [response string]` - Changes how the server + responds to the [command]. [response string] is evaluated as a perl string, + so it can contain embedded \r\n, for example. There is a special [command] + named "welcome" (without quotes) which is the string sent immediately on + connect as a welcome. +- `REPLYLF` (like above but sends the response terminated with LF-only and not + CRLF) +- `COUNT [command] [num]` - Do the `REPLY` change for `[command]` only `[num]` + times and then go back to the built-in approach +- `DELAY [command] [secs]` - Delay responding to this command for the given + time +- `RETRWEIRDO` - Enable the "weirdo" RETR case when multiple response lines + appear at once when a file is transferred +- `RETRNOSIZE` - Make sure the RETR response does not contain the size of the + file +- `RETRSIZE [size]` - Force RETR response to contain the specified size +- `NOSAVE` - Do not actually save what is received +- `SLOWDOWN` - Send FTP responses with 0.01 sec delay between each byte +- `SLOWDOWNDATA` - Send FTP responses with 0.01 sec delay between each data + byte +- `PASVBADIP` - makes PASV send back an illegal IP in its 227 response +- `CAPA [capabilities]` - Enables support for and specifies a list of space + separated capabilities to return to the client for the IMAP `CAPABILITY`, + POP3 `CAPA` and SMTP `EHLO` commands +- `AUTH [mechanisms]` - Enables support for SASL authentication and specifies + a list of space separated mechanisms for IMAP, POP3 and SMTP +- `STOR [msg]` respond with this instead of default after `STOR` + +#### For HTTP/HTTPS + +- `auth_required` if this is set and a POST/PUT is made without auth, the + server does NOT wait for the full request body to get sent +- `delay: [msecs]` - delay this amount after connection +- `idle` - do nothing after receiving the request, just "sit idle" +- `stream` - continuously send data to the client, never-ending +- `writedelay: [msecs]` delay this amount between reply packets +- `skip: [num]` - instructs the server to ignore reading this many bytes from + a PUT or POST request +- `rtp: part [num] channel [num] size [num]` - stream a fake RTP packet for + the given part on a chosen channel with the given payload size +- `connection-monitor` - When used, this logs `[DISCONNECT]` to the + `server.input` log when the connection is disconnected. +- `upgrade` - when an HTTP upgrade header is found, the server upgrades to + http2 +- `swsclose` - instruct server to close connection after response +- `no-expect` - do not read the request body if Expect: is present + +#### For TFTP +`writedelay: [secs]` delay this amount between reply packets (each packet + being 512 bytes payload) + +## `` + +### `` +What server(s) this test case requires/uses. Available servers: + +- `dict` +- `file` +- `ftp` +- `ftp-ipv6` +- `ftps` +- `gopher` +- `gopher-ipv6` +- `gophers` +- `http` +- `http/2` +- `http-ipv6` +- `http-proxy` +- `https` +- `https-proxy` +- `httptls+srp` +- `httptls+srp-ipv6` +- `http-unix` +- `imap` +- `mqtt` +- `none` +- `pop3` +- `rtsp` +- `rtsp-ipv6` +- `scp` +- `sftp` +- `smb` +- `smtp` +- `socks4` +- `socks5` +- `socks5unix` +- `telnet` +- `tftp` + +Give only one per line. This subsection is mandatory (use `none` if no servers +are required). Servers that require a special server certificate can have the +PEM certificate filename (found in the `certs` directory) appended to the +server name separated by a space. + +### `` +A list of features that MUST be present in the client/library for this test to +be able to run. If a required feature is not present then the test is SKIPPED. + +Alternatively a feature can be prefixed with an exclamation mark to indicate a +feature is NOT required. If the feature is present then the test is SKIPPED. + +Features testable here are: + +- `alt-svc` +- `AppleIDN` +- `bearssl` +- `brotli` +- `c-ares` +- `CharConv` +- `codeset-utf8`. If the running codeset is UTF-8 capable. +- `cookies` +- `crypto` +- `Debug` +- `DoH` +- `getrlimit` +- `GnuTLS` +- `GSS-API` +- `h2c` +- `headers-api` +- `HSTS` +- `HTTP-auth` +- `http/2` +- `http/3` +- `HTTPS-proxy` +- `hyper` +- `IDN` +- `IPv6` +- `Kerberos` +- `Largefile` +- `large-time` (time_t is larger than 32-bit) +- `ld_preload` +- `libssh2` +- `libssh` +- `oldlibssh` (versions before 0.9.4) +- `libz` +- `local-http`. The HTTP server runs on 127.0.0.1 +- `manual` +- `mbedtls` +- `Mime` +- `netrc` +- `nghttpx` +- `nghttpx-h3` +- `NTLM` +- `NTLM_WB` +- `OpenSSL` +- `parsedate` +- `proxy` +- `PSL` +- `rustls` +- `Schannel` +- `sectransp` +- `shuffle-dns` +- `socks` +- `SPNEGO` +- `SSL` +- `SSLpinning` +- `SSPI` +- `threaded-resolver` +- `TLS-SRP` +- `TrackMemory` +- `typecheck` +- `threadsafe` +- `Unicode` +- `unittest` +- `UnixSockets` +- `verbose-strings` +- `wakeup` +- `win32` +- `WinIDN` +- `wolfssh` +- `wolfssl` +- `xattr` +- `zstd` + +as well as each protocol that curl supports. A protocol only needs to be +specified if it is different from the server (useful when the server is +`none`). + +### `` +Using the same syntax as in `` but when mentioned here these servers +are explicitly KILLED when this test case is completed. Only use this if there +is no other alternatives. Using this of course requires subsequent tests to +restart servers. + +### `` +A command line that if set gets run by the test script before the test. If an +output is displayed by the command or if the return code is non-zero, the test +is skipped and the (single-line) output is displayed as reason for not running +the test. + +### `` +Name of tool to invoke instead of "curl". This tool must be built and exist +either in the `libtest/` directory (if the tool name starts with `lib`) or in +the `unit/` directory (if the tool name starts with `unit`). + +### `` +Brief test case description, shown when the test runs. + +### `` + + variable1=contents1 + variable2=contents2 + variable3 + +Set the given environment variables to the specified value before the actual +command is run. They are restored back to their former values again after the +command has been run. + +If the variable name has no assignment, no `=`, then that variable is just +deleted. + +### `` +Command line to run. + +Note that the URL that gets passed to the server actually controls what data +that is returned. The last slash in the URL must be followed by a number. That +number (N) is used by the test-server to load test case N and return the data +that is defined within the `` section. + +If there is no test number found above, the HTTP test server uses the number +following the last dot in the given hostname (made so that a CONNECT can still +pass on test number) so that "foo.bar.123" gets treated as test case +123. Alternatively, if an IPv6 address is provided to CONNECT, the last +hexadecimal group in the address is used as the test number. For example the +address "[1234::ff]" would be treated as test case 255. + +Set `type="perl"` to write the test case as a perl script. It implies that +there is no memory debugging and valgrind gets shut off for this test. + +Set `type="shell"` to write the test case as a shell script. It implies that +there is no memory debugging and valgrind gets shut off for this test. + +Set `option="no-output"` to prevent the test script to slap on the `--output` +argument that directs the output to a file. The `--output` is also not added +if the verify/stdout section is used. + +Set `option="force-output"` to make use of `--output` even when the test is +otherwise written to verify stdout. + +Set `option="no-include"` to prevent the test script to slap on the +`--include` argument. + +Set `option="no-q"` avoid using `-q` as the first argument in the curl command +line. + +Set `option="binary-trace"` to use `--trace` instead of `--trace-ascii` for +tracing. Suitable for binary-oriented protocols such as MQTT. + +Set `timeout="secs"` to override default server logs advisor read lock +timeout. This timeout is used by the test harness, once that the command has +completed execution, to wait for the test server to write out server side log +files and remove the lock that advised not to read them. The "secs" parameter +is the not negative integer number of seconds for the timeout. This `timeout` +attribute is documented for completeness sake, but is deep test harness stuff +and only needed for singular and specific test cases. Avoid using it. + +Set `delay="secs"` to introduce a time delay once that the command has +completed execution and before the `` section runs. The "secs" +parameter is the not negative integer number of seconds for the delay. This +'delay' attribute is intended for specific test cases, and normally not +needed. + +### `` +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. + +If `nonewline="yes"` is used, the created file gets the final newline stripped +off. + +### `` +1 to 4 can be appended to 'file' to create more files. + +### `` + +### `` + +### `` + +### `` +Pass this given data on stdin to the tool. + +If `nonewline` is set, we cut off the trailing newline of this given data +before comparing with the one actually received by the client + +## `` + +If `test-duphandle` is a listed item here, this is not run when +`--test-duphandle` is used. + +## `` +### `` +numerical error code curl is supposed to return. Specify a list of accepted +error codes by separating multiple numbers with comma. See test 237 for an +example. + +### `` +One regex per line that is removed from the protocol dumps before the +comparison is made. This is useful to remove dependencies on dynamically +changing protocol data such as port numbers or user-agent strings. + +### `` +One perl op per line that operates on the protocol dump. This is pretty +advanced. Example: `s/^EPRT .*/EPRT stripped/`. + +### `` +A command line that if set gets run by the test script after the test. If the +command exists with a non-zero status code, the test is considered failed. + +### `` +A list of directory entries that are checked for after the test has completed +and that must not exist. A listed entry existing causes the test to fail. + +### `` + +the protocol dump curl should transmit, if `nonewline` is set, we cut off the +trailing newline of this given data before comparing with the one actually +sent by the client The `` and `` rules are applied before +comparisons are made. + +`crlf=yes` forces the newlines to become CRLF even if not written so in the +test. + +### `` + +The protocol dump curl should transmit to an HTTP proxy (when the http-proxy +server is used), if `nonewline` is set, we cut off the trailing newline of +this given data before comparing with the one actually sent by the client The +`` and `` rules are applied before comparisons are made. + +### `` +This verifies that this data was passed to stderr. + +Use the mode="text" attribute if the output is in text mode on platforms that +have a text/binary difference. + +`crlf=yes` forces the newlines to become CRLF even if not written so in the +test. + +If `nonewline` is set, we cut off the trailing newline of this given data +before comparing with the one actually received by the client + +### `` +This verifies that this data was passed to stdout. + +Use the mode="text" attribute if the output is in text mode on platforms that +have a text/binary difference. + +If `nonewline` is set, we cut off the trailing newline of this given data +before comparing with the one actually received by the client + +`crlf=yes` forces the newlines to become CRLF even if not written so in the +test. + +`loadfile="filename"` makes loading the data from an external file. + +### `` +The file's contents must be identical to this after the test is complete. Use +the mode="text" attribute if the output is in text mode on platforms that have +a text/binary difference. + +### `` +1 to 4 can be appended to 'file' to compare more files. + +### `` + +### `` + +### `` + +### `` +One perl op per line that operates on the output file or stdout before being +compared with what is stored in the test file. This is pretty +advanced. Example: "s/^EPRT .*/EPRT stripped/" + +### `` +1 to 4 can be appended to `stripfile` to strip the corresponding `` +content + +### `` + +### `` + +### `` + +### `` +the contents of the upload data curl should have sent + +`crlf=yes` forces *upload* newlines to become CRLF even if not written so in +the source file. + +`nonewline=yes` means that the last byte (the trailing newline character) +should be cut off from the upload data before comparing it. + +### `` +disable - disables the valgrind log check for this test diff --git a/local-test-curl-full-01/afc-curl/tests/Makefile.am b/local-test-curl-full-01/afc-curl/tests/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..46d58fed8552b5e575bd9c39fa0f503c8b38a1ab --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/Makefile.am @@ -0,0 +1,202 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 BUILD_DOCS +# if we disable man page building, ignore these +RUNTESTS_DOCS = runtests.1 +TESTCURL_DOCS = testcurl.1 +MANFILES = $(RUNTESTS_DOCS) $(TESTCURL_DOCS) +endif + +CURLPAGES = runtests.md testcurl.md + +# scripts used in test cases +TESTSCRIPTS = \ + test1119.pl \ + test1132.pl \ + test1135.pl \ + test1139.pl \ + test1140.pl \ + test1165.pl \ + test1167.pl \ + test1173.pl \ + test1175.pl \ + test1177.pl \ + test1222.pl \ + test1275.pl \ + test1276.pl \ + test1477.pl \ + test1486.pl \ + test1488.pl \ + test1544.pl \ + test1707.pl \ + test971.pl + +EXTRA_DIST = \ + CMakeLists.txt \ + FILEFORMAT.md \ + README.md \ + appveyor.pm \ + azure.pm \ + devtest.pl \ + dictserver.py \ + directories.pm \ + ech_combos.py \ + ech_tests.sh \ + ftpserver.pl \ + getpart.pm \ + globalconfig.pm \ + http-server.pl \ + http2-server.pl \ + http3-server.pl \ + memanalyze.pl \ + mk-bundle-hints.sh \ + mk-bundle.pl \ + negtelnetserver.py \ + nghttpx.conf \ + pathhelp.pm \ + processhelp.pm \ + requirements.txt \ + rtspserver.pl \ + runner.pm \ + runtests.pl \ + secureserver.pl \ + serverhelp.pm \ + servers.pm \ + smbserver.py \ + sshhelp.pm \ + sshserver.pl \ + stunnel.pem \ + testcurl.pl \ + testutil.pm \ + tftpserver.pl \ + util.py \ + valgrind.pm \ + valgrind.supp \ + $(TESTSCRIPTS) \ + $(CURLPAGES) + +# we have two variables here to make sure DIST_SUBDIRS won't get 'unit' +# added twice as then targets such as 'distclean' misbehave and try to +# do things twice in that subdir at times (and thus fails). +if BUILD_UNITTESTS +BUILD_UNIT = unit +DIST_UNIT = +else +BUILD_UNIT = +DIST_UNIT = unit +endif + +SUBDIRS = certs data server libtest http $(BUILD_UNIT) +DIST_SUBDIRS = $(SUBDIRS) $(DIST_UNIT) + +PERLFLAGS = -I$(srcdir) + +CLEANFILES = .http.pid .https.pid .ftp.pid .ftps.pid $(MANDISTPAGES) + +curl: + @cd $(top_builddir) && $(MAKE) + +TEST_COMMON = + +if CROSSCOMPILING +TEST = @echo "NOTICE: we can't run the tests when cross-compiling!" +PYTEST = $(TEST) +else # if not cross-compiling: +if USE_TEST_BUNDLES +TEST_COMMON += -bundle +endif + +if BUILD_DOCS +else +TEST_COMMON += !documentation +endif + +TEST = srcdir=$(srcdir) $(PERL) $(PERLFLAGS) $(srcdir)/runtests.pl $(TEST_COMMON) +TEST_Q = -a -s +TEST_AM = -a -am +TEST_F = -a -p -r +TEST_T = -a -t -j20 +TEST_E = -a -e + +# ~ means that it will run all tests matching the keyword, but will +# ignore their results (since these ones are likely to fail for no good reason) +TEST_NF = -a -p ~flaky ~timing-dependent + +# special CI target derived from nonflaky with CI-specific flags +TEST_CI = $(TEST_NF) -r -rm -j20 + +PYTEST = pytest +endif + +CD2NROFF = $(top_srcdir)/scripts/cd2nroff $< >$@ + +SUFFIXES = .1 .md + +.md.1: + $(CD2)$(CD2NROFF) + +# make sure that PERL is pointing to an executable +perlcheck: + @if ! test -x "$(PERL)"; then echo "No perl!"; exit 2; fi + +test: perlcheck all + $(TEST) $(TFLAGS) + +quiet-test: perlcheck all + $(TEST) $(TEST_Q) $(TFLAGS) + +am-test: perlcheck all + $(TEST) $(TEST_AM) $(TFLAGS) + +ci-test: perlcheck all + $(TEST) $(TEST_CI) $(TFLAGS) + +full-test: perlcheck all + $(TEST) $(TEST_F) $(TFLAGS) + +nonflaky-test: perlcheck all + $(TEST) $(TEST_NF) $(TFLAGS) + +torture-test: perlcheck all + $(TEST) $(TEST_T) $(TFLAGS) + +event-test: perlcheck all + $(TEST) $(TEST_E) $(TFLAGS) + +default-pytest: ci-pytest + +ci-pytest: all + srcdir=$(srcdir) $(PYTEST) -v $(srcdir)/http + +checksrc: + (cd libtest && $(MAKE) checksrc) + (cd unit && $(MAKE) checksrc) + (cd server && $(MAKE) checksrc) + (cd http && $(MAKE) checksrc) + +all-local: $(MANFILES) + +distclean: + rm -f $(MANFILES) diff --git a/local-test-curl-full-01/afc-curl/tests/README.md b/local-test-curl-full-01/afc-curl/tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..54fb6b3e938d5fc8596c25d5dbdcd79ca6e35ad2 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/README.md @@ -0,0 +1,269 @@ + + +# The curl Test Suite + +# Running + + See the "Requires to run" section for prerequisites. + + In the root of the curl repository: + + ./configure && make && make test + + To run a specific set of tests (e.g. 303 and 410): + + make test TFLAGS="303 410" + + To run the tests faster, pass the -j (parallelism) flag: + + make test TFLAGS="-j10" + + "make test" builds the test suite support code and invokes the 'runtests.pl' + perl script to run all the tests. The value of `TFLAGS` is passed + directly to 'runtests.pl'. + + When you run tests via make, the flags `-a` and `-s` are passed, meaning + to continue running tests even after one fails, and to emit short output. + + If you would like to not use those flags, you can run 'runtests.pl' directly. + You must `chdir` into the tests directory, then you can run it like so: + + ./runtests.pl 303 410 + + You must have run `make test` at least once first to build the support code. + + To see what flags are available for runtests.pl, and what output it emits, run: + + man ./tests/runtests.1 + + After a test fails, examine the tests/log directory for stdout, stderr, and + output from the servers used in the test. + +## Requires to run + + - perl (and a Unix-style shell) + - python (and a Unix-style shell, for SMB and TELNET tests) + - python-impacket (for SMB tests) + - diff (when a test fails, a diff is shown) + - stunnel (for HTTPS and FTPS tests) + - OpenSSH or SunSSH (for SCP and SFTP tests) + - nghttpx (for HTTP/2 and HTTP/3 tests) + - An available `en_US.UTF-8` locale + +### Installation of impacket + + The Python-based test servers support Python 3. + + Please install python-impacket in the correct Python environment. + You can use pip or your OS' package manager to install 'impacket'. + + On Debian/Ubuntu the package name is 'python3-impacket' + + On FreeBSD the package name is 'py311-impacket' + + On any system where pip is available: 'python3 -m pip install impacket' + + You may also need to manually install the Python package 'six' + as that may be a missing requirement for impacket. + +## Event-based + + If curl is built with `Debug` enabled (see below), then the `runtests.pl` + script offers a `-e` option that makes it perform *event-based*. Such tests + invokes the curl tool with `--test-event`, a debug-only option made for this + purpose. + + Performing event-based means that the curl tool uses the + `curl_multi_socket_action()` API call to drive the transfer(s), instead of + the otherwise "normal" functions it would use. This allows us to test drive + the socket_action API. Transfers done this way should work exactly the same + as with the non-event based API. + + To be able to use `--test-event` together with `--parallel`, curl requires + *libuv* to be present and enabled in the build: `configure --enable-libuv` + +### Port numbers used by test servers + + All test servers run on "random" port numbers. All tests should be written + to use suitable variables instead of fixed port numbers so that test cases + continue to work independent on what port numbers the test servers actually + use. + + See [`FILEFORMAT`](FILEFORMAT.md) for the port number variables. + +### Test servers + + The test suite runs stand-alone servers on random ports to which it makes + requests. For SSL tests, it runs stunnel to handle encryption to the regular + servers. For SSH, it runs a standard OpenSSH server. + + The listen port numbers for the test servers are picked randomly to allow + users to run multiple test cases concurrently and to not collide with other + existing services that might listen to ports on the machine. + + The HTTP server supports listening on a Unix domain socket, the default + location is 'http.sock'. + + For HTTP/2 and HTTP/3 testing an installed `nghttpx` is used. HTTP/3 + tests check if nghttpx supports the protocol. To override the nghttpx + used, set the environment variable `NGHTTPX`. The default can also be + changed by specifying `--with-test-nghttpx=` as argument to `configure`. + +### Shell startup scripts + + Tests which use the ssh test server, SCP/SFTP tests, might be badly + influenced by the output of system wide or user specific shell startup + scripts, .bashrc, .profile, /etc/csh.cshrc, .login, /etc/bashrc, etc. which + output text messages or escape sequences on user login. When these shell + startup messages or escape sequences are output they might corrupt the + expected stream of data which flows to the sftp-server or from the ssh + client which can result in bad test behavior or even prevent the test server + from running. + + If the test suite ssh or sftp server fails to start up and logs the message + 'Received message too long' then you are certainly suffering the unwanted + output of a shell startup script. Locate, cleanup or adjust the shell + script. + +### Memory test + + The test script checks that all allocated memory is freed properly IF curl + has been built with the `CURLDEBUG` define set. The script automatically + detects if that is the case, and it uses the `memanalyze.pl` script to + analyze the memory debugging output. + + Also, if you run tests on a machine where valgrind is found, the script uses + valgrind to run the test with (unless you use `-n`) to further verify + correctness. + + The `runtests.pl` `-t` option enables torture testing mode. It runs each + test many times and makes each different memory allocation fail on each + successive run. This tests the out of memory error handling code to ensure + that memory leaks do not occur even in those situations. It can help to + compile curl with `CPPFLAGS=-DMEMDEBUG_LOG_SYNC` when using this option, to + ensure that the memory log file is properly written even if curl crashes. + +### Debug + + If a test case fails, you can conveniently get the script to invoke the + debugger (gdb) for you with the server running and the same command line + parameters that failed. Just invoke `runtests.pl -g` and then + just type 'run' in the debugger to perform the command through the debugger. + +### Logs + + All logs are generated in the log/ subdirectory (it is emptied first in the + runtests.pl script). They remain in there after a test run. + +### Log Verbosity + + A curl build with `--enable-debug` offers more verbose output in the logs. + This applies not only for test cases, but also when running it standalone + with `curl -v`. While a curl debug built is + ***not suitable for production***, it is often helpful in tracking down + problems. + + Sometimes, one needs detailed logging of operations, but does not want + to drown in output. The newly introduced *connection filters* allows one to + dynamically increase log verbosity for a particular *filter type*. Example: + + CURL_DEBUG=ssl curl -v https://curl.se + + makes the `ssl` connection filter log more details. One may do that for + every filter type and also use a combination of names, separated by `,` or + space. + + CURL_DEBUG=ssl,http/2 curl -v https://curl.se + + The order of filter type names is not relevant. Names used here are + case insensitive. Note that these names are implementation internals and + subject to change. + + Some, likely stable names are `tcp`, `ssl`, `http/2`. For a current list, + one may search the sources for `struct Curl_cftype` definitions and find + the names there. Also, some filters are only available with certain build + options, of course. + +### Test input files + + All test cases are put in the `data/` subdirectory. Each test is stored in + the file named according to the test number. + + See [`FILEFORMAT`](FILEFORMAT.md) for a description of the test case file + format. + +### Code coverage + + gcc provides a tool that can determine the code coverage figures for the + test suite. To use it, configure curl with `CFLAGS='-fprofile-arcs + -ftest-coverage -g -O0'`. Make sure you run the normal and torture tests to + get more full coverage, i.e. do: + + make test + make test-torture + + The graphical tool `ggcov` can be used to browse the source and create + coverage reports on \*nix hosts: + + ggcov -r lib src + + The text mode tool `gcov` may also be used, but it does not handle object + files in more than one directory correctly. + +### Remote testing + + The runtests.pl script provides some hooks to allow curl to be tested on a + machine where perl can not be run. The test framework in this case runs on + a workstation where perl is available, while curl itself is run on a remote + system using ssh or some other remote execution method. See the comments at + the beginning of runtests.pl for details. + +## Test case numbering + + Test cases used to be numbered by category ranges, but the ranges filled + up. Subsets of tests can now be selected by passing keywords to the + runtests.pl script via the make `TFLAGS` variable. + + New tests are added by finding a free number in `tests/data/Makefile.am`. + +## Write tests + + Here's a quick description on writing test cases. We basically have three + kinds of tests: the ones that test the curl tool, the ones that build small + applications and test libcurl directly and the unit tests that test + individual (possibly internal) functions. + +### test data + + Each test has a master file that controls all the test data. What to read, + what the protocol exchange should look like, what exit code to expect and + what command line arguments to use etc. + + These files are `tests/data/test[num]` where `[num]` is just a unique + identifier described above, and the XML-like file format of them is + described in the separate [`FILEFORMAT`](FILEFORMAT.md) document. + +### curl tests + + A test case that runs the curl tool and verifies that it gets the correct + data, it sends the correct data, it uses the correct protocol primitives + etc. + +### libcurl tests + + The libcurl tests are identical to the curl ones, except that they use a + specific and dedicated custom-built program to run instead of "curl". This + tool is built from source code placed in `tests/libtest` and if you want to + make a new libcurl test that is where you add your code. + +### unit tests + + Unit tests are placed in `tests/unit`. There is a tests/unit/README + describing the specific set of checks and macros that may be used when + writing tests that verify behaviors of specific individual functions. + + The unit tests depend on curl being built with debug enabled. diff --git a/local-test-curl-full-01/afc-curl/tests/appveyor.pm b/local-test-curl-full-01/afc-curl/tests/appveyor.pm new file mode 100644 index 0000000000000000000000000000000000000000..2a6a5d58c0169c119bd407b60aa0d79132a1cc7c --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/appveyor.pm @@ -0,0 +1,130 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# Copyright (C) Marc Hoersken, +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +package appveyor; + +use strict; +use warnings; + +BEGIN { + use base qw(Exporter); + + our @EXPORT = qw( + appveyor_check_environment + appveyor_create_test_result + appveyor_update_test_result + ); +} + + +my %APPVEYOR_TEST_NAMES; # JSON and shell-quoted test names by test number + +sub appveyor_check_environment { + if(defined $ENV{'APPVEYOR_API_URL'} && $ENV{'APPVEYOR_API_URL'}) { + return 1; + } + return 0; +} + +sub appveyor_create_test_result { + my ($curl, $testnum, $testname)=@_; + $testname =~ s/\\/\\\\/g; + $testname =~ s/\"/\\\"/g; + $testname =~ s/\'/'"'"'/g; + my $appveyor_baseurl="$ENV{'APPVEYOR_API_URL'}"; + my $appveyor_result=`$curl --silent --noproxy '*' \\ + --header 'Content-Type: application/json' \\ + --data ' + { + "testName": "$testname", + "testFramework": "runtests.pl", + "fileName": "tests/data/test$testnum", + "outcome": "Running" + } + ' \\ + '$appveyor_baseurl/api/tests'`; + print "AppVeyor API result: $appveyor_result\n" if ($appveyor_result); + $APPVEYOR_TEST_NAMES{$testnum}=$testname; +} + +sub appveyor_update_test_result { + my ($curl, $testnum, $error, $start, $stop)=@_; + my $testname=$APPVEYOR_TEST_NAMES{$testnum}; + if(!defined $testname) { + return; + } + if(!defined $stop) { + $stop = $start; + } + my $appveyor_duration = sprintf("%.0f", ($stop-$start)*1000); + my $appveyor_outcome; + my $appveyor_category; + if($error == 2) { + $appveyor_outcome = 'Ignored'; + $appveyor_category = 'Error'; + } + elsif($error < 0) { + $appveyor_outcome = 'NotRunnable'; + $appveyor_category = 'Warning'; + } + elsif(!$error) { + $appveyor_outcome = 'Passed'; + $appveyor_category = 'Information'; + } + else { + $appveyor_outcome = 'Failed'; + $appveyor_category = 'Error'; + } + my $appveyor_baseurl="$ENV{'APPVEYOR_API_URL'}"; + my $appveyor_result=`$curl --silent --noproxy '*' --request PUT \\ + --header 'Content-Type: application/json' \\ + --data ' + { + "testName": "$testname", + "testFramework": "runtests.pl", + "fileName": "tests/data/test$testnum", + "outcome": "$appveyor_outcome", + "durationMilliseconds": $appveyor_duration, + "ErrorMessage": "Test $testnum $appveyor_outcome" + } + ' \\ + '$appveyor_baseurl/api/tests'`; + print "AppVeyor API result: $appveyor_result\n" if ($appveyor_result); + if($appveyor_category eq 'Error') { + $appveyor_result=`$curl --silent --noproxy '*' \\ + --header 'Content-Type: application/json' \\ + --data ' + { + "message": "$appveyor_outcome: $testname", + "category": "$appveyor_category", + "details": "Test $testnum $appveyor_outcome" + } + ' \\ + '$appveyor_baseurl/api/build/messages'`; + print "AppVeyor API result: $appveyor_result\n" if ($appveyor_result); + } +} + +1; diff --git a/local-test-curl-full-01/afc-curl/tests/azure.pm b/local-test-curl-full-01/afc-curl/tests/azure.pm new file mode 100644 index 0000000000000000000000000000000000000000..2810f48e1777c49e5510892d293804c52d13c3d4 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/azure.pm @@ -0,0 +1,165 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# Copyright (C) Marc Hoersken, +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +package azure; + +use strict; +use warnings; + +BEGIN { + use base qw(Exporter); + + our @EXPORT = qw( + azure_check_environment + azure_create_test_run + azure_create_test_result + azure_update_test_result + azure_update_test_run + ); +} + +use POSIX qw(strftime); + +sub azure_check_environment { + if(defined $ENV{'AZURE_ACCESS_TOKEN'} && $ENV{'AZURE_ACCESS_TOKEN'} && + defined $ENV{'AGENT_JOBNAME'} && $ENV{'BUILD_BUILDID'} && + defined $ENV{'SYSTEM_TEAMFOUNDATIONCOLLECTIONURI'} && + defined $ENV{'SYSTEM_TEAMPROJECTID'}) { + return 1; + } + return 0; +} + +sub azure_create_test_run { + my ($curl)=@_; + my $azure_baseurl="$ENV{'SYSTEM_TEAMFOUNDATIONCOLLECTIONURI'}$ENV{'SYSTEM_TEAMPROJECTID'}"; + my $azure_run=`$curl --silent --noproxy "*" \\ + --header "Authorization: Bearer $ENV{'AZURE_ACCESS_TOKEN'}" \\ + --header "Content-Type: application/json" \\ + --data " + { + 'name': '$ENV{'AGENT_JOBNAME'}', + 'automated': true, + 'build': {'id': '$ENV{'BUILD_BUILDID'}'} + } + " \\ + "$azure_baseurl/_apis/test/runs?api-version=5.1"`; + if($azure_run =~ /"id":(\d+)/) { + return $1; + } + return ""; +} + +sub azure_create_test_result { + my ($curl, $azure_run_id, $testnum, $testname)=@_; + $testname =~ s/\\/\\\\/g; + $testname =~ s/\"/\\\"/g; + $testname =~ s/\'/'"'"'/g; + my $title_testnum=sprintf("%04d", $testnum); + my $azure_baseurl="$ENV{'SYSTEM_TEAMFOUNDATIONCOLLECTIONURI'}$ENV{'SYSTEM_TEAMPROJECTID'}"; + my $azure_result=`$curl --silent --noproxy '*' \\ + --header "Authorization: Bearer $ENV{'AZURE_ACCESS_TOKEN'}" \\ + --header 'Content-Type: application/json' \\ + --data ' + [ + { + "build": {"id": "$ENV{'BUILD_BUILDID'}"}, + "testCase": {"id": $testnum}, + "testCaseTitle": "$title_testnum: $testname", + "testCaseRevision": 2, + "automatedTestName": "curl.tests.$testnum", + "outcome": "InProgress" + } + ] + ' \\ + '$azure_baseurl/_apis/test/runs/$azure_run_id/results?api-version=5.1'`; + if($azure_result =~ /\[\{"id":(\d+)/) { + return $1; + } + return ""; +} + +sub azure_update_test_result { + my ($curl, $azure_run_id, $azure_result_id, $testnum, $error, $start, $stop)=@_; + if(!defined $stop) { + $stop = $start; + } + my $azure_start = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime $start; + my $azure_complete = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime $stop; + my $azure_duration = sprintf("%.0f", ($stop-$start)*1000); + my $azure_outcome; + if($error == 2) { + $azure_outcome = 'NotApplicable'; + } + elsif($error < 0) { + $azure_outcome = 'NotExecuted'; + } + elsif(!$error) { + $azure_outcome = 'Passed'; + } + else { + $azure_outcome = 'Failed'; + } + my $azure_baseurl="$ENV{'SYSTEM_TEAMFOUNDATIONCOLLECTIONURI'}$ENV{'SYSTEM_TEAMPROJECTID'}"; + my $azure_result=`$curl --silent --noproxy '*' --request PATCH \\ + --header "Authorization: Bearer $ENV{'AZURE_ACCESS_TOKEN'}" \\ + --header "Content-Type: application/json" \\ + --data ' + [ + { + "id": $azure_result_id, + "outcome": "$azure_outcome", + "startedDate": "$azure_start", + "completedDate": "$azure_complete", + "durationInMs": $azure_duration + } + ] + ' \\ + '$azure_baseurl/_apis/test/runs/$azure_run_id/results?api-version=5.1'`; + if($azure_result =~ /\[\{"id":(\d+)/) { + return $1; + } + return ""; +} + +sub azure_update_test_run { + my ($curl, $azure_run_id)=@_; + my $azure_baseurl="$ENV{'SYSTEM_TEAMFOUNDATIONCOLLECTIONURI'}$ENV{'SYSTEM_TEAMPROJECTID'}"; + my $azure_run=`$curl --silent --noproxy '*' --request PATCH \\ + --header "Authorization: Bearer $ENV{'AZURE_ACCESS_TOKEN'}" \\ + --header 'Content-Type: application/json' \\ + --data ' + { + "state": "Completed" + } + ' \\ + '$azure_baseurl/_apis/test/runs/$azure_run_id?api-version=5.1'`; + if($azure_run =~ /"id":(\d+)/) { + return $1; + } + return ""; +} + +1; diff --git a/local-test-curl-full-01/afc-curl/tests/config.in b/local-test-curl-full-01/afc-curl/tests/config.in new file mode 100644 index 0000000000000000000000000000000000000000..f5aa9862a45e9f6826eb9d898b33573b410e2ef0 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/config.in @@ -0,0 +1,24 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +NGHTTPX: @TEST_NGHTTPX@ diff --git a/local-test-curl-full-01/afc-curl/tests/configurehelp.pm.in b/local-test-curl-full-01/afc-curl/tests/configurehelp.pm.in new file mode 100644 index 0000000000000000000000000000000000000000..626df2c511b065c80282e472da5227f863ebc8d7 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/configurehelp.pm.in @@ -0,0 +1,45 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +package configurehelp; + +use strict; +use warnings; +use Exporter; + +use vars qw( + @ISA + @EXPORT_OK + $Cpreprocessor + ); + +@ISA = qw(Exporter); + +@EXPORT_OK = qw( + $Cpreprocessor + ); + +$Cpreprocessor = '@CURL_CPP@'; + +1; diff --git a/local-test-curl-full-01/afc-curl/tests/devtest.pl b/local-test-curl-full-01/afc-curl/tests/devtest.pl new file mode 100644 index 0000000000000000000000000000000000000000..4fb0934e98ed80119340f3599a8d441d5d37f2fa --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/devtest.pl @@ -0,0 +1,202 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Fandrich, et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the 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 is intended for developers to test some internals of the +# runtests.pl harness. Don't try to use this unless you know what you're +# doing! + +# An example command-line that starts a test http server for test 11 and waits +# for the user before stopping it: +# ./devtest.pl --verbose serverfortest https echo "Started https" protoport https preprocess 11 pause echo Stopping stopservers echo Done +# curl can connect to the server while it's running like this: +# curl -vkL https://localhost:/11 + +use strict; +use warnings; +use 5.006; + +BEGIN { + # Define srcdir to the location of the tests source directory. This is + # usually set by the Makefile, but for out-of-tree builds with direct + # invocation of runtests.pl, it may not be set. + if(!defined $ENV{'srcdir'}) { + use File::Basename; + $ENV{'srcdir'} = dirname(__FILE__); + } + push(@INC, $ENV{'srcdir'}); +} + +use globalconfig; +use servers qw( + initserverconfig + protoport + serverfortest + stopservers +); +use runner qw( + readtestkeywords + singletest_preprocess +); +use testutil qw( + setlogfunc +); +use getpart; + + +####################################################################### +# logmsg is our general message logging subroutine. +# This function is currently required to be here by servers.pm +# This is copied from runtests.pl +# +my $uname_release = `uname -r`; +my $is_wsl = $uname_release =~ /Microsoft$/; +sub logmsg { + for(@_) { + my $line = $_; + if ($is_wsl) { + # use \r\n for WSL shell + $line =~ s/\r?\n$/\r\n/g; + } + print "$line"; + } +} + +####################################################################### +# Parse and store the protocols in curl's Protocols: line +# This is copied from runtests.pl +# +sub parseprotocols { + my ($line)=@_; + + @protocols = split(' ', lc($line)); + + # Generate a "proto-ipv6" version of each protocol to match the + # IPv6 name and a "proto-unix" to match the variant which + # uses Unix domain sockets. This works even if support isn't + # compiled in because the test will fail. + push @protocols, map(("$_-ipv6", "$_-unix"), @protocols); + + # 'http-proxy' is used in test cases to do CONNECT through + push @protocols, 'http-proxy'; + + # 'none' is used in test cases to mean no server + push @protocols, 'none'; +} + + +####################################################################### +# Initialize @protocols from the curl binary under test +# +sub init_protocols { + for (`$CURL -V 2>$dev_null`) { + if(m/^Protocols: (.*)$/) { + parseprotocols($1); + } + } +} + + +####################################################################### +# Initialize the test harness to run tests +# +sub init_tests { + setlogfunc(\&logmsg); + init_protocols(); + initserverconfig(); +} + +####################################################################### +# Main test loop + +init_tests(); + +#*************************************************************************** +# Parse command-line options and commands +# +while(@ARGV) { + if($ARGV[0] eq "-h") { + print "Usage: devtest.pl [--verbose] [command [arg]...]\n"; + print "command is one of:\n"; + print " echo X\n"; + print " pause\n"; + print " preprocess\n"; + print " protocols *|X[,Y...]\n"; + print " protoport X\n"; + print " serverfortest X[,Y...]\n"; + print " stopservers\n"; + print " sleep N\n"; + exit 0; + } + elsif($ARGV[0] eq "--verbose") { + $verbose = 1; + } + elsif($ARGV[0] eq "sleep") { + shift @ARGV; + sleep $ARGV[0]; + } + elsif($ARGV[0] eq "echo") { + shift @ARGV; + print $ARGV[0] . "\n"; + } + elsif($ARGV[0] eq "pause") { + print "Press Enter to continue: "; + readline STDIN; + } + elsif($ARGV[0] eq "protocols") { + shift @ARGV; + if($ARGV[0] eq "*") { + init_protocols(); + } + else { + @protocols = split(",", $ARGV[0]); + } + print "Set " . scalar @protocols . " protocols\n"; + } + elsif($ARGV[0] eq "preprocess") { + shift @ARGV; + loadtest("${TESTDIR}/test${ARGV[0]}"); + readtestkeywords(); + singletest_preprocess($ARGV[0]); + } + elsif($ARGV[0] eq "protoport") { + shift @ARGV; + my $port = protoport($ARGV[0]); + print "protoport: $port\n"; + } + elsif($ARGV[0] eq "serverfortest") { + shift @ARGV; + my ($why, $e) = serverfortest(split(/,/, $ARGV[0])); + print "serverfortest: $e $why\n"; + } + elsif($ARGV[0] eq "stopservers") { + my $err = stopservers(); + print "stopservers: $err\n"; + } + else { + print "Error: Unknown command: $ARGV[0]\n"; + print "Continuing anyway\n"; + } + shift @ARGV; +} diff --git a/local-test-curl-full-01/afc-curl/tests/dictserver.py b/local-test-curl-full-01/afc-curl/tests/dictserver.py new file mode 100644 index 0000000000000000000000000000000000000000..c28a22e5bd3535379aea9604c50b54e69ffd107a --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/dictserver.py @@ -0,0 +1,186 @@ +#!/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 +# +########################################################################### +# +"""DICT server.""" + +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +import argparse +import logging +import os +import sys + +from util import ClosingFileHandler + +try: # Python 2 + import SocketServer as socketserver # type: ignore +except ImportError: # Python 3 + import socketserver + +log = logging.getLogger(__name__) +HOST = "localhost" + +# The strings that indicate the test framework is checking our aliveness +VERIFIED_REQ = b"verifiedserver" +VERIFIED_RSP = "WE ROOLZ: {pid}" + + +def dictserver(options): + """Start up a TCP server with a DICT handler and serve DICT requests forever.""" + if options.pidfile: + pid = os.getpid() + # see tests/server/util.c function write_pidfile + if os.name == "nt": + pid += 65536 + with open(options.pidfile, "w") as f: + f.write(str(pid)) + + local_bind = (options.host, options.port) + log.info("[DICT] Listening on %s", local_bind) + + # Need to set the allow_reuse on the class, not on the instance. + socketserver.TCPServer.allow_reuse_address = True + server = socketserver.TCPServer(local_bind, DictHandler) + server.serve_forever() + + return ScriptRC.SUCCESS + + +class DictHandler(socketserver.BaseRequestHandler): + """Handler class for DICT connections.""" + + def handle(self): + """Respond to all queries with a 552.""" + try: + # First, send a response to allow the server to continue. + rsp = "220 dictserver \n" + self.request.sendall(rsp.encode("utf-8")) + + # Receive the request. + data = self.request.recv(1024).strip() + log.debug("[DICT] Incoming data: %r", data) + + if VERIFIED_REQ in data: + log.debug("[DICT] Received verification request from test " + "framework") + pid = os.getpid() + # see tests/server/util.c function write_pidfile + if os.name == "nt": + pid += 65536 + response_data = VERIFIED_RSP.format(pid=pid) + else: + log.debug("[DICT] Received normal request") + response_data = "No matches" + + # Send back a failure to find. + response = "552 {0}\n".format(response_data) + log.debug("[DICT] Responding with %r", response) + self.request.sendall(response.encode("utf-8")) + + except IOError: + log.exception("[DICT] IOError hit during request") + + +def get_options(): + parser = argparse.ArgumentParser() + + parser.add_argument("--port", action="store", default=9016, + type=int, help="port to listen on") + parser.add_argument("--host", action="store", default=HOST, + help="host to listen on") + parser.add_argument("--verbose", action="store", type=int, default=0, + help="verbose output") + parser.add_argument("--pidfile", action="store", + help="file name for the PID") + parser.add_argument("--logfile", action="store", + help="file name for the log") + parser.add_argument("--srcdir", action="store", help="test directory") + parser.add_argument("--id", action="store", help="server ID") + parser.add_argument("--ipv4", action="store_true", default=0, + help="IPv4 flag") + + return parser.parse_args() + + +def setup_logging(options): + """Set up logging from the command line options.""" + root_logger = logging.getLogger() + add_stdout = False + + formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s") + + # Write out to a logfile + if options.logfile: + handler = ClosingFileHandler(options.logfile) + handler.setFormatter(formatter) + handler.setLevel(logging.DEBUG) + root_logger.addHandler(handler) + else: + # The logfile wasn't specified. Add a stdout logger. + add_stdout = True + + if options.verbose: + # Add a stdout logger as well in verbose mode + root_logger.setLevel(logging.DEBUG) + add_stdout = True + else: + root_logger.setLevel(logging.INFO) + + if add_stdout: + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.setFormatter(formatter) + stdout_handler.setLevel(logging.DEBUG) + root_logger.addHandler(stdout_handler) + + +class ScriptRC(object): + """Enum for script return codes.""" + + SUCCESS = 0 + FAILURE = 1 + EXCEPTION = 2 + + +if __name__ == '__main__': + # Get the options from the user. + options = get_options() + + # Setup logging using the user options + setup_logging(options) + + # Run main script. + try: + rc = dictserver(options) + except Exception: + log.exception('Error running server') + rc = ScriptRC.EXCEPTION + + if options.pidfile and os.path.isfile(options.pidfile): + os.unlink(options.pidfile) + + log.info("[DICT] Returning %d", rc) + sys.exit(rc) diff --git a/local-test-curl-full-01/afc-curl/tests/directories.pm b/local-test-curl-full-01/afc-curl/tests/directories.pm new file mode 100644 index 0000000000000000000000000000000000000000..238f7e03ebdb6ea722555d6fb08c6b52cf476beb --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/directories.pm @@ -0,0 +1,307 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +package directories; + +use strict; +use warnings; + +BEGIN { + use base qw(Exporter); + + our @EXPORT = qw( + ftp_contentlist + wildcard_filesize + wildcard_getfile + ); +} + + +my %file_chmod1 = ( + 'name' => 'chmod1', + 'content' => "This file should have permissions 444\n", + 'perm' => 'r--r--r--', + 'time' => 'Jan 11 10:00', + 'dostime' => '01-11-10 10:00AM', +); + +my %file_chmod2 = ( + 'name' => 'chmod2', + 'content' => "This file should have permissions 666\n", + 'perm' => 'rw-rw-rw-', + 'time' => 'Feb 1 8:00', + 'dostime' => '02-01-10 08:00AM', +); + +my %file_chmod3 = ( + 'name' => 'chmod3', + 'content' => "This file should have permissions 777\n", + 'perm' => 'rwxrwxrwx', + 'time' => 'Feb 1 8:00', + 'dostime' => '02-01-10 08:00AM', +); + +my %file_chmod4 = ( + 'type' => 'd', + 'name' => 'chmod4', + 'content' => "This file should have permissions 001\n", + 'perm' => '--S--S--t', + 'time' => 'May 4 4:31', + 'dostime' => '05-04-10 04:31AM' +); + +my %file_chmod5 = ( + 'type' => 'd', + 'name' => 'chmod5', + 'content' => "This file should have permissions 110\n", + 'perm' => '--s--s--T', + 'time' => 'May 4 4:31', + 'dostime' => '05-04-10 04:31AM' +); + +my %link_link = ( + 'type' => 'l', + 'name' => 'link -> file.txt', + 'size' => '8', + 'perm' => 'rwxrwxrwx', + 'time' => 'Jan 6 4:42' +); + +my %link_link_absolute = ( + 'type' => 'l', + 'name' => 'link_absolute -> /data/ftp/file.txt', + 'size' => '15', + 'perm' => 'rwxrwxrwx', + 'time' => 'Jan 6 4:45' +); + +my %dir_dot = ( + 'type' => "d", + 'name' => ".", + 'hlink' => "4", + 'time' => "Apr 27 5:12", + 'size' => "20480", + 'dostime' => "04-27-10 05:12AM", + 'perm' => "rwxrwxrwx" +); + +my %dir_ddot = ( + 'type' => "d", + 'name' => "..", + 'hlink' => "4", + 'size' => "20480", + 'time' => "Apr 23 3:12", + 'dostime' => "04-23-10 03:12AM", + 'perm' => "rwxrwxrwx" +); + +my %dir_weirddir_txt = ( + 'type' => "d", + 'name' => "weirddir.txt", + 'hlink' => "2", + 'size' => "4096", + 'time' => "Apr 23 3:12", + 'dostime' => "04-23-10 03:12AM", + 'perm' => "rwxr-xrwx" +); + +my %dir_UNIX = ( + 'type' => "d", + 'name' => "UNIX", + 'hlink' => "11", + 'size' => "4096", + 'time' => "Nov 01 2008", + 'dostime' => "11-01-08 11:11AM", + 'perm' => "rwx--x--x" +); + +my %dir_DOS = ( + 'type' => "d", + 'name' => "DOS", + 'hlink' => "11", + 'size' => "4096", + 'time' => "Nov 01 2008", + 'dostime' => "11-01-08 11:11AM", + 'perm' => "rwx--x--x" +); + +my %dir_dot_NeXT = ( + 'type' => "d", + 'name' => ".NeXT", + 'hlink' => "4", + 'size' => "4096", + 'time' => "Jan 23 2:05", + 'dostime' => "01-23-05 02:05AM", + 'perm' => "rwxrwxrwx" +); + +my %file_empty_file_dat = ( + 'name' => "empty_file.dat", + 'content' => "", + 'perm' => "rw-r--r--", + 'time' => "Apr 27 11:01", + 'dostime' => "04-27-10 11:01AM" +); + +my %file_file_txt = ( + 'name' => "file.txt", + 'content' => "This is content of file \"file.txt\"\n", + 'time' => "Apr 27 11:01", + 'dostime' => "04-27-10 11:01AM", + 'perm' => "rw-r--r--" +); + +my %file_someothertext_txt = ( + 'name' => "someothertext.txt", + 'content' => "Some junk ;-) This file does not really exist.\n", + 'time' => "Apr 27 11:01", + 'dostime' => "04-27-10 11:01AM", + 'perm' => "rw-r--r--" +); + +my %lists = ( + '/fully_simulated/' => { + 'files' => [ \%dir_dot, \%dir_ddot, \%dir_DOS, \%dir_UNIX ], + 'eol' => "\r\n", + 'type' => "unix" + }, + '/fully_simulated/UNIX/' => { + 'files' => [ \%dir_dot, \%dir_ddot, + \%file_chmod1, \%file_chmod2, \%file_chmod3, \%file_chmod4, \%file_chmod5, + \%file_empty_file_dat, \%file_file_txt, + \%link_link, \%link_link_absolute, \%dir_dot_NeXT, + \%file_someothertext_txt, \%dir_weirddir_txt ], + 'eol' => "\r\n", + 'type' => 'unix' + }, + '/fully_simulated/DOS/' => { + 'files' => [ \%dir_dot, \%dir_ddot, + \%file_chmod1, \%file_chmod2, \%file_chmod3, \%file_chmod4, \%file_chmod5, + \%file_empty_file_dat, \%file_file_txt, + \%dir_dot_NeXT, \%file_someothertext_txt, \%dir_weirddir_txt ], + 'eol' => "\r\n", + 'type' => 'dos' + } +); + +sub ftp_createcontent { + my ($list) = $_[0]; + + my $type = $$list{'type'}; + my $eol = $$list{'eol'}; + my $list_ref = $$list{'files'}; + + my @diroutput; + my @contentlist; + if($type eq "unix") { + for(@$list_ref) { + my %file = %$_; + my $line = ""; + my $ftype = $file{'type'} ? $file{'type'} : "-"; + my $fperm = $file{'perm'} ? $file{'perm'} : "rwxr-xr-x"; + my $fuser = $file{'user'} ? sprintf("%15s", $file{'user'}) : "ftp-default"; + my $fgroup = $file{'group'} ? sprintf("%15s", $file{'group'}) : "ftp-default"; + my $fsize = ""; + if(exists($file{'type'}) && $file{'type'} eq "d") { + $fsize = $file{'size'} ? sprintf("%7s", $file{'size'}) : sprintf("%7d", 4096); + } + else { + $fsize = sprintf("%7d", exists($file{'content'}) ? length $file{'content'} : 0); + } + my $fhlink = $file{'hlink'} ? sprintf("%4d", $file{'hlink'}) : " 1"; + my $ftime = $file{'time'} ? sprintf("%10s", $file{'time'}) : "Jan 9 1933"; + push(@contentlist, "$ftype$fperm $fhlink $fuser $fgroup $fsize $ftime $file{'name'}$eol"); + } + + return @contentlist; + } + elsif($type =~ /^dos$/) { + for(@$list_ref) { + my %file = %$_; + my $line = ""; + my $time = $file{'dostime'} ? $file{'dostime'} : "06-25-97 09:12AM"; + my $size_or_dir; + if(exists($file{'type'}) && $file{'type'} =~ /^d$/) { + $size_or_dir = " "; + } + else { + $size_or_dir = sprintf("%20d", length $file{'content'}); + } + push(@contentlist, "$time $size_or_dir $file{'name'}$eol"); + } + return @contentlist; + } +} + +sub wildcard_filesize { + my ($list_type, $file) = @_; + my $list = $lists{$list_type}; + if($list) { + my $files = $list->{'files'}; + for(@$files) { + my %f = %$_; + if ($f{'name'} eq $file) { + if($f{'content'}) { + return length $f{'content'}; + } + elsif ($f{'type'} ne "d"){ + return 0; + } + else { + return -1; + } + } + } + } + return -1; +} + +sub wildcard_getfile { + my ($list_type, $file) = @_; + my $list = $lists{$list_type}; + if($list) { + my $files = $list->{'files'}; + for(@$files) { + my %f = %$_; + if ($f{'name'} eq $file) { + if($f{'content'}) { + return (length $f{'content'}, $f{'content'}); + } + elsif (!exists($f{'type'}) or $f{'type'} ne "d"){ + return (0, ""); + } + else { + return (-1, 0); + } + } + } + } + return (-1, 0); +} + +sub ftp_contentlist { + my $listname = $_[0]; + my $list = $lists{$listname}; + return ftp_createcontent($list); +} diff --git a/local-test-curl-full-01/afc-curl/tests/ech_combos.py b/local-test-curl-full-01/afc-curl/tests/ech_combos.py new file mode 100644 index 0000000000000000000000000000000000000000..66daaa373db424a313f6fe2127f0232b6528b673 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/ech_combos.py @@ -0,0 +1,98 @@ +#!/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 +# +########################################################################### +# +# Python3 program to print all combination of size r in an array of size n. +# This is used to generate test lines in tests/ech_test.sh. +# This will be discarded in the process of moving from experimental, +# but is worth preserving for the moment in case of changes to the +# ECH command line args + +def CombinationRepetitionUtil(chosen, arr, badarr, index, + r, start, end): + + # Current combination is ready, + # print it + if index == r: + # figure out if result should be good or bad and + # print prefix, assuming $turl does support ECH so + # should work if given "positive" parameters + res = 1 + j = len(chosen) - 1 + while res and j >= 0: + if chosen[j] in badarr: + res = 0 + j = j - 1 + print("cli_test $turl 1", res, end = " ") + # print combination but eliminating any runs of + # two identical params + for j in range(r): + if j != 0 and chosen[j] != chosen[j-1]: + print(chosen[j], end = " ") + + print() + return + + # When no more elements are + # there to put in chosen[] + if start > n: + return + + # Current is included, put + # next at next location + chosen[index] = arr[start] + + # Current is excluded, replace it + # with next (Note that i+1 is passed, + # but index is not changed) + CombinationRepetitionUtil(chosen, arr, badarr, index + 1, + r, start, end) + CombinationRepetitionUtil(chosen, arr, badarr, index, + r, start + 1, end) + +# The main function that prints all +# combinations of size r in arr[] of +# size n. This function mainly uses +# CombinationRepetitionUtil() +def CombinationRepetition(arr, badarr, n, r): + + # A temporary array to store + # all combination one by one + chosen = [0] * r + + # Print all combination using + # temporary array 'chosen[]' + CombinationRepetitionUtil(chosen, arr, badarr, 0, r, 0, n) + +# Driver code +badarr = [ '--ech grease', '--ech false', '--ech ecl:$badecl', '--ech pn:$badpn' ] +goodarr = [ '--ech hard', '--ech true', '--ech ecl:$goodecl', '--ech pn:$goodpn' ] +arr = badarr + goodarr +r = 8 +n = len(arr) - 1 + +CombinationRepetition(arr, badarr, n, r) + +# This code is contributed by Vaibhav Kumar 12. diff --git a/local-test-curl-full-01/afc-curl/tests/ech_tests.sh b/local-test-curl-full-01/afc-curl/tests/ech_tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..1746f1651164742c93b4e803c68b3bd7c8de9f10 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/ech_tests.sh @@ -0,0 +1,1156 @@ +#!/bin/bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### +# + +# Run some tests against servers we know to support ECH (CF, defo.ie, etc.). +# as well as some we know don't do ECH but have an HTTPS RR, and finally some +# for which neither is the case. + +# TODO: Translate this into something that approximates a valid curl test:-) +# Should be useful though even before such translation and a pile less work +# to do this than that. The pile of work required would include making an +# ECH-enabled server and a DoH server. For now, this is just run manually. +# + +# set -x + +# Exit with an error if there's an active ech stanza in ~/.curlrc +# as that'd likely skew some results (e.g. turning a fail into a +# success or vice versa) +: "${CURL_CFG_FILE=$HOME/.curlrc}" +active_ech=$(grep ech "$CURL_CFG_FILE" | grep -v "#.*ech") +if [[ "$active_ech" != "" ]] +then + echo "You seem to have an active ECH setting in $CURL_CFG_FILE" + echo "That might affect results so please remove that or comment" + echo "it out - exiting." + exit 1 +fi + + +# Targets we expect to be ECH-enabled servers +# for which an HTTPS RR is published. +# structure is host:port mapped to pathname +# TODO: add negative tests for these +declare -A ech_targets=( + [my-own.net]="ech-check.php" + [my-own.net:8443]="ech-check.php" + [defo.ie]="ech-check.php" + [cover.defo.ie]="" + [draft-13.esni.defo.ie:8413]="stats" + [draft-13.esni.defo.ie:8414]="stats" + [draft-13.esni.defo.ie:9413]="" + [draft-13.esni.defo.ie:10413]="" + [draft-13.esni.defo.ie:11413]="" + [draft-13.esni.defo.ie:12413]="" + [draft-13.esni.defo.ie:12414]="" + [crypto.cloudflare.com]="cdn-cgi/trace" + [tls-ech.dev]="" + # this one's gone away for now (possibly temporarily) + # [epochbelt.com]="" +) + +# Targets we expect not to be ECH-enabled servers +# but for which an HTTPS RR is published. +declare -A httpsrr_targets=( + [ietf.org]="" + [rte.ie]="" +) + +# Targets we expect not to be ECH-enabled servers +# and for which no HTTPS RR is published. +declare -A neither_targets=( + [www.tcd.ie]="" + [jell.ie]="" +) + +# +# Variables that can be over-ridden from environment +# + +# Top of curl test tree, assume we're there +: "${CTOP:=.}" + +# Place to put test log output +: "${LTOP:=$CTOP/tests/ech-log/}" + +# Place to stash outputs when things go wrong +: "${BTOP:=$LTOP}" + +# Time to wait for a remote access to work, 10 seconds +: "${tout:=10s}" + +# Where we find OpenSSL .so's +: "${OSSL:=$HOME/code/openssl-local-inst}" + +# Where we find wolfSSL .so's +: "${WSSL:=$HOME/code/wolfssl/inst/lib}" + +# Where we find BoringSSL .so's +: "${BSSL:=$HOME/code/boringssl/inst/lib}" + +# Where we send DoH queries when using kdig or curl +: "${DOHSERVER:=one.one.one.one}" +: "${DOHPATH:=dns-query}" + +# Whether to send mail when bad things happen (mostly for cronjob) +: "${DOMAIL:=no}" + +# Misc vars and functions + +DEFPORT=443 + +function whenisitagain() +{ + /bin/date -u +%Y%m%d-%H%M%S +} + +function fileage() +{ + echo $(($(date +%s) - $(date +%s -r "$1"))) +} + +function hostport2host() +{ + case $1 in + *:*) host=${1%:*} port=${1##*:};; + *) host=$1 port=$DEFPORT;; + esac + echo "$host" +} + +function hostport2port() +{ + case $1 in + *:*) host=${1%:*} port=${1##*:};; + *) host=$1 port=$DEFPORT;; + esac + echo "$port" +} + +function cli_test() +{ + # 1st param is target URL + turl=$1 + # 2nd param is 0 if we expect curl to not work or 1 if we expect it + # to have worked + curl_winorlose=$2 + # 3rd param is 0 if we expect ECH to not work or 1 if we expect it + # to have worked + ech_winorlose=$3 + # remaining params are passed to command line + # echparms=(${@:4}) + IFS=" " read -r -a echparms <<< "${@:4}" + + TMPF=$(mktemp) + cmd="timeout $tout $CURL ${CURL_PARAMS[*]} ${echparms[*]} $turl >$TMPF 2>&1" + echo "cli_test: $cmd " >> "$logfile" + timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" "${echparms[@]}" "$turl" >"$TMPF" 2>&1 + eres=$? + if [[ "$eres" == "124" ]] + then + allgood="no" + echo "cli_test: Timeout running $cmd" + cat "$TMPF" >> "$logfile" + echo "cli_test: Timeout running $cmd" >> "$logfile" + fi + if [[ "$eres" != "0" && "$curl_winorlose" == "1" ]] + then + allgood="no" + echo "cli_test: curl failure running $cmd" + cat "$TMPF" >> "$logfile" + echo "cli_test: curl failure running $cmd" >> "$logfile" + fi + ech_success=$(grep -c "ECH: result: status is succeeded" "$TMPF") + if [[ "$ech_success" == "$ech_winorlose" ]] + then + echo "cli_test ok for ${echparms[*]}" + else + allgood="no" + echo "cli_test: ECH failure running $cmd" + cat "$TMPF" >> "$logfile" + echo "cli_test: ECH failure running $cmd" >> "$logfile" + fi + rm -f "$TMPF" +} + +function get_ech_configlist() +{ + domain=$1 + ecl=$(dig +short https "$domain" | grep "ech=" | sed -e 's/^.*ech=//' | sed -e 's/ .*//') + echo "$ecl" +} + +# start of main script + +# start by assuming we have nothing we need... +have_ossl="no" +have_wolf="no" +have_bssl="no" +using_ossl="no" +using_wolf="no" +using_bssl="no" +have_curl="no" +have_dig="no" +have_kdig="no" +have_presout="no" +have_portsblocked="no" + +# setup logging +NOW=$(whenisitagain) +BINNAME=$(basename "$0" .sh) +if [ ! -d "$LTOP" ] +then + mkdir -p "$LTOP" +fi +if [ ! -d "$LTOP" ] +then + echo "Can't see $LTOP for logs - exiting" + exit 1 +fi +logfile=$LTOP/${BINNAME}_$NOW.log + +echo "-----" > "$logfile" +echo "Running $0 at $NOW" >> "$logfile" +echo "Running $0 at $NOW" + +# check we have the binaries needed and which TLS library we'll be using +if [ -f "$OSSL"/libssl.so ] +then + have_ossl="yes" +fi +if [ -f "$WSSL"/libwolfssl.so ] +then + have_wolf="yes" +fi +if [ -f "$BSSL"/libssl.so ] +then + have_bssl="yes" +fi +CURL="$CTOP/src/curl" +CURL_PARAMS=(-vvv --doh-url https://one.one.one.one/dns-query) +if [ -f "$CTOP"/src/curl ] +then + have_curl="yes" +fi +ossl_cnt=$(LD_LIBRARY_PATH=$OSSL $CURL "${CURL_PARAMS[@]}" -V 2> /dev/null | grep -c OpenSSL) +if ((ossl_cnt == 1)) +then + using_ossl="yes" + # setup access to our .so + export LD_LIBRARY_PATH=$OSSL +fi +bssl_cnt=$(LD_LIBRARY_PATH=$BSSL $CURL "${CURL_PARAMS[@]}" -V 2> /dev/null | grep -c BoringSSL) +if ((bssl_cnt == 1)) +then + using_bssl="yes" + # setup access to our .so + export LD_LIBRARY_PATH=$BSSL +fi +wolf_cnt=$($CURL "${CURL_PARAMS[@]}" -V 2> /dev/null | grep -c wolfSSL) +if ((wolf_cnt == 1)) +then + using_wolf="yes" + # for some reason curl+wolfSSL dislikes certs that are ok + # for browsers, so we'll test using "insecure" mode (-k) + # but that's ok here as we're only interested in ECH testing + CURL_PARAMS+=(-k) +fi +# check if we have dig and it knows https or not +digcmd="dig +short" +wdig=$(type -p dig) +if [[ "$wdig" != "" ]] +then + have_dig="yes" +fi +wkdig=$(type -p kdig) +if [[ "$wkdig" != "" ]] +then + have_kdig="yes" + digcmd="kdig @$DOHSERVER +https +short" +fi +# see if our dig version knows HTTPS +dout=$($digcmd https defo.ie) +if [[ $dout != "1 . "* ]] +then + dout=$($digcmd -t TYPE65 defo.ie) + if [[ $dout == "1 . "* ]] + then + # we're good + have_presout="yes" + fi +else + have_presout="yes" +fi + +# Check if ports other than 443 are blocked from this +# vantage point (I run tests in a n/w where that's +# sadly true sometimes;-) +# echo "Checking if ports other than 443 are maybe blocked" +not443testurl="https://draft-13.esni.defo.ie:9413/" +timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" "$not443testurl" >/dev/null 2>&1 +eres=$? +if [[ "$eres" == "124" ]] +then + echo "Timeout running curl for $not443testurl" >> "$logfile" + echo "Timeout running curl for $not443testurl" + have_portsblocked="yes" +fi + +{ + echo "have_ossl: $have_ossl" + echo "have_wolf: $have_wolf" + echo "have_bssl: $have_bssl" + echo "using_ossl: $using_ossl" + echo "using_wolf: $using_wolf" + echo "using_bssl: $using_bssl" + echo "have_curl: $have_curl" + echo "have_dig: $have_dig" + echo "have_kdig: $have_kdig" + echo "have_presout: $have_presout" + echo "have_portsblocked: $have_portsblocked" +} >> "$logfile" + +echo "curl: have $have_curl, cURL command: |$CURL ${CURL_PARAMS[*]}|" +echo "ossl: have: $have_ossl, using: $using_ossl" +echo "wolf: have: $have_wolf, using: $using_wolf" +echo "bssl: have: $have_bssl, using: $using_bssl" +echo "dig: $have_dig, kdig: $have_kdig, HTTPS pres format: $have_presout" +echo "dig command: |$digcmd|" +echo "ports != 443 blocked: $have_portsblocked" + +if [[ "$have_curl" == "no" ]] +then + echo "Can't proceed without curl - exiting" + exit 32 +fi + +allgood="yes" + +skip="false" + +if [[ "$skip" != "true" ]] +then + +# basic ECH good/bad +for targ in "${!ech_targets[@]}" +do + if [[ "$using_wolf" == "yes" ]] + then + case $targ in + "draft-13.esni.defo.ie:8414" | "tls-ech.dev" | \ + "crypto.cloudflare.com" | "epochbelt.com") + echo "Skipping $targ 'cause wolf"; continue;; + *) + ;; + esac + fi + host=$(hostport2host "$targ") + port=$(hostport2port "$targ") + if [[ "$port" != "443" && "$have_portsblocked" == "yes" ]] + then + echo "Skipping $targ as ports != 443 seem blocked" + continue + fi + path=${ech_targets[$targ]} + turl="https://$host:$port/$path" + echo "ECH check for $turl" + { + echo "" + echo "ECH check for $turl" + } >> "$logfile" + timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" --ech hard "$turl" >> "$logfile" 2>&1 + eres=$? + if [[ "$eres" == "124" ]] + then + allgood="no" + { + echo "Timeout for $turl" + echo -e "\tTimeout for $turl" + echo "Timeout running curl for $host:$port/$path" + } >> "$logfile" + fi + if [[ "$eres" != "0" ]] + then + allgood="no" + echo "Error ($eres) for $turl" >> "$logfile" + echo -e "\tError ($eres) for $turl" + fi + echo "" >> "$logfile" +done + +# check if public_name override works (OpenSSL only) +if [[ "$using_ossl" == "yes" ]] +then + for targ in "${!ech_targets[@]}" + do + host=$(hostport2host "$targ") + port=$(hostport2port "$targ") + if [[ "$port" != "443" && "$have_portsblocked" == "yes" ]] + then + echo "Skipping $targ as ports != 443 seem blocked" + continue + fi + if [[ "$host" == "crypto.cloudflare.com" ]] + then + echo "Skipping $host as they've blocked PN override" + continue + fi + path=${ech_targets[$targ]} + turl="https://$host:$port/$path" + echo "PN override check for $turl" + { + echo "" + echo "PN override check for $turl" + } >> "$logfile" + timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" --ech pn:override --ech hard "$turl" >> "$logfile" 2>&1 + eres=$? + if [[ "$eres" == "124" ]] + then + allgood="no" + { + echo "Timeout for $turl" + echo -e "\tTimeout for $turl" + echo "Timeout running curl for $host:$port/$path" + } >> "$logfile" + fi + if [[ "$eres" != "0" ]] + then + allgood="no" + echo "PN override Error ($eres) for $turl" >> "$logfile" + echo -e "\tPN override Error ($eres) for $turl" + fi + echo "" >> "$logfile" + done +fi + +for targ in "${!httpsrr_targets[@]}" +do + host=$(hostport2host "$targ") + port=$(hostport2port "$targ") + if [[ "$port" != "443" && "$have_portsblocked" == "yes" ]] + then + echo "Skipping $targ as ports != 443 seem blocked" + continue + fi + path=${httpsrr_targets[$targ]} + turl="https://$host:$port/$path" + echo "HTTPS RR but no ECHConfig check for $turl" + { + echo "" + echo "HTTPS RR but no ECHConfig check for $turl" + } >> "$logfile" + timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" --ech true "$turl" >> "$logfile" 2>&1 + eres=$? + if [[ "$eres" == "124" ]] + then + allgood="no" + { + echo "Timeout for $turl" + echo -e "\tTimeout for $turl" + echo "Timeout running curl for $host:$port/$path" + } >> "$logfile" + fi + if [[ "$eres" != "0" ]] + then + allgood="no" + echo "Error ($eres) for $turl" >> "$logfile" + echo -e "\tError ($eres) for $turl" + fi + echo "" >> "$logfile" +done + +for targ in "${!neither_targets[@]}" +do + host=$(hostport2host "$targ") + port=$(hostport2port "$targ") + if [[ "$port" != "443" && "$have_portsblocked" == "yes" ]] + then + echo "Skipping $targ as ports != 443 seem blocked" + continue + fi + path=${neither_targets[$targ]} + turl="https://$host:$port/$path" + echo "Neither HTTPS nor ECHConfig check for $turl" + { + echo "" + echo "Neither HTTPS nor ECHConfig check for $turl" + } >> "$logfile" + timeout "$tout" "$CURL" "${CURL_PARAMS[@]}" --ech true "$turl" >> "$logfile" 2>&1 + eres=$? + if [[ "$eres" == "124" ]] + then + allgood="no" + { + echo "Timeout for $turl" + echo -e "\tTimeout for $turl" + echo "Timeout running curl for $host:$port/$path" + } >> "$logfile" + fi + if [[ "$eres" != "0" ]] + then + allgood="no" + echo "Error ($eres) for $turl" >> "$logfile" + echo -e "\tError ($eres) for $turl" + fi + echo "" >> "$logfile" +done + + +# Check various command line options, if we're good so far +if [[ "$using_ossl" == "yes" && "$allgood" == "yes" ]] +then + # use this test URL as it'll tell us if things worked + turl="https://defo.ie/ech-check.php" + echo "cli_test with $turl" + echo "cli_test with $turl" >> "$logfile" + cli_test "$turl" 1 1 --ech true + cli_test "$turl" 1 0 --ech false + cli_test "$turl" 1 1 --ech false --ech true + cli_test "$turl" 1 1 --ech false --ech true --ech pn:foobar + cli_test "$turl" 1 1 --ech false --ech pn:foobar --ech true + echconfiglist=$(get_ech_configlist defo.ie) + cli_test "$turl" 1 1 --ech ecl:"$echconfiglist" + cli_test "$turl" 1 0 --ech ecl: +fi + +fi # skip + +# Check combinations of command line options, if we're good so far +# Most of this only works for OpenSSL, which is ok, as we're checking +# the argument handling here, not the ECH protocol +if [[ "$using_ossl" == "yes" && "$allgood" == "yes" ]] +then + # ech can be hard, true, grease or false + # ecl:ecl can be correct, incorrect or missing + # ech:pn can be correct, incorrect or missing + # in all cases the "last" argument provided should "win" + # but only one of hard, true, grease or false will apply + turl="https://defo.ie/ech-check.php" + echconfiglist=$(get_ech_configlist defo.ie) + goodecl=$echconfiglist + echconfiglist=$(get_ech_configlist hidden.hoba.ie) + badecl=$echconfiglist + goodpn="cover.defo.ie" + badpn="hoba.ie" + echo "more cli_test with $turl" + echo "more cli_test with $turl" >> "$logfile" + + # The combinatorics here are handled via the tests/ech_combos.py script + # which produces all the relevant combinations or inputs and orders + # thereof. We have to manually assess whether or not ECH is expected to + # work for each case. + cli_test "$turl" 0 0 + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" - 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$badecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech false --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech false --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 0 --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 1 1 --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + + # a target URL that doesn't support ECH + turl="https://tcd.ie" + echo "cli_test with $turl" + echo "cli_test with $turl" >> "$logfile" + # the params below don't matter much here as we'll fail anyway + echconfiglist=$(get_ech_configlist defo.ie) + goodecl=$echconfiglist + badecl="$goodecl" + goodpn="tcd.ie" + badpn="tcd.ie" + cli_test "$turl" 1 0 + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$badecl" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$badecl" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech false --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech hard --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$badpn" --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech ecl:"$goodecl" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech ecl:"$goodecl" --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi + cli_test "$turl" 0 0 --ech true --ech pn:"$goodpn" + if [[ "$allgood" != "yes" ]]; then echo "$LINENO"; fi +fi + + +END=$(whenisitagain) +echo "Finished $0 at $END" >> "$logfile" +echo "-----" >> "$logfile" + +if [[ "$allgood" == "yes" ]] +then + echo "Finished $0 at $END" + echo "All good, log in $logfile" + exit 0 +else + echo "Finished $0 at $END" + echo "NOT all good, log in $logfile" +fi + +# send a mail to root (will be fwd'd) but just once every 24 hours +# 'cause we only really need "new" news +itsnews="yes" +age_of_news=0 +if [ -f "$LTOP"/bad_runs ] +then + age_of_news=$(fileage "$LTOP"/bad_runs) + # only consider news "new" if we haven't mailed today + if ((age_of_news < 24*3600)) + then + itsnews="no" + fi +fi +if [[ "$DOMAIL" == "yes" && "$itsnews" == "yes" ]] +then + echo "ECH badness at $NOW" | mail -s "ECH badness at $NOW" root +fi +# add to list of bad runs (updating file age) +echo "ECH badness at $NOW" >>"$LTOP"/bad_runs +exit 2 diff --git a/local-test-curl-full-01/afc-curl/tests/ftpserver.pl b/local-test-curl-full-01/afc-curl/tests/ftpserver.pl new file mode 100644 index 0000000000000000000000000000000000000000..abe04959d92c6396b5ea50822f9bd151a3e86ec8 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/ftpserver.pl @@ -0,0 +1,3376 @@ +#!/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 is a server designed for the curl test suite. +# +# In December 2009 we started remaking the server to support more protocols +# that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP +# it already supported since a long time. Note that it still only supports one +# protocol per invoke. You need to start multiple servers to support multiple +# protocols simultaneously. +# +# It is meant to exercise curl, it is not meant to be a fully working +# or even very standard compliant server. +# +# You may optionally specify port on the command line, otherwise it'll +# default to port 8921. +# +# All socket/network/TCP related stuff is done by the 'sockfilt' program. +# + +use strict; +use warnings; + +BEGIN { + push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'}); + push(@INC, "."); +} + +use IPC::Open2; +use Digest::MD5; +use File::Basename; + +use directories; + +use getpart qw( + getpartattr + getpart + loadtest + ); + +use processhelp; + +use serverhelp qw( + logmsg + $logfile + servername_str + server_pidfilename + server_logfilename + mainsockf_pidfilename + mainsockf_logfilename + datasockf_pidfilename + datasockf_logfilename + ); + +use pathhelp qw( + exe_ext + ); + +use globalconfig qw( + $SERVERCMD + $LOCKDIR + ); + +#********************************************************************** +# global vars... +# +my $verbose = 0; # set to 1 for debugging +my $idstr = ""; # server instance string +my $idnum = 1; # server instance number +my $ipvnum = 4; # server IPv number (4 or 6) +my $proto = 'ftp'; # default server protocol +my $srcdir; # directory where ftpserver.pl is located +my $srvrname; # server name for presentation purposes +my $cwd_testno; # test case numbers extracted from CWD command +my $testno = 0; # test case number (read from server.cmd) +my $path = '.'; +my $logdir = $path .'/log'; +my $piddir; + +#********************************************************************** +# global vars used for server address and primary listener port +# +my $port = 8921; # default primary listener port +my $listenaddr = '127.0.0.1'; # default address for listener port + +#********************************************************************** +# global vars used for file names +# +my $PORTFILE="ftpserver.port"; # server port file name +my $portfile; # server port file path +my $pidfile; # server pid file name +my $mainsockf_pidfile; # pid file for primary connection sockfilt process +my $mainsockf_logfile; # log file for primary connection sockfilt process +my $datasockf_pidfile; # pid file for secondary connection sockfilt process +my $datasockf_logfile; # log file for secondary connection sockfilt process + +#********************************************************************** +# global vars used for server logs advisor read lock handling +# +my $serverlogs_lockfile; +my $serverlogslocked = 0; + +#********************************************************************** +# global vars used for child processes PID tracking +# +my $sfpid; # PID for primary connection sockfilt process +my $slavepid; # PID for secondary connection sockfilt process + +#********************************************************************** +# global typeglob filehandle vars to read/write from/to sockfilters +# +local *SFREAD; # used to read from primary connection +local *SFWRITE; # used to write to primary connection +local *DREAD; # used to read from secondary connection +local *DWRITE; # used to write to secondary connection + +my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads + +#********************************************************************** +# global vars which depend on server protocol selection +# +my %commandfunc; # protocol command specific function callbacks +my %displaytext; # text returned to client before callback runs + +#********************************************************************** +# global vars customized for each test from the server commands file +# +my $ctrldelay; # set if server should throttle ctrl stream +my $datadelay; # set if server should throttle data stream +my $retrweirdo; # set if ftp server should use RETRWEIRDO +my $retrnosize; # set if ftp server should use RETRNOSIZE +my $retrsize; # set if ftp server should use RETRSIZE +my $pasvbadip; # set if ftp server should use PASVBADIP +my $nosave; # set if ftp server should not save uploaded data +my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel +my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425 +my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421 +my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150 +my $storeresp; +my $postfetch; +my @capabilities; # set if server supports capability commands +my @auth_mechs; # set if server supports authentication commands +my %fulltextreply; # +my %commandreply; # +my %customcount; # +my %delayreply; # + +#********************************************************************** +# global variables for to test ftp wildcardmatching or other test that +# need flexible LIST responses.. and corresponding files. +# $ftptargetdir is keeping the fake "name" of LIST directory. +# +my $ftplistparserstate; +my $ftptargetdir=""; + +#********************************************************************** +# global variables used when running a ftp server to keep state info +# relative to the secondary or data sockfilt process. Values of these +# variables should only be modified using datasockf_state() sub, given +# that they are closely related and relationship is a bit awkward. +# +my $datasockf_state = 'STOPPED'; # see datasockf_state() sub +my $datasockf_mode = 'none'; # ['none','active','passive'] +my $datasockf_runs = 'no'; # ['no','yes'] +my $datasockf_conn = 'no'; # ['no','yes'] + +#********************************************************************** +# global vars used for signal handling +# +my $got_exit_signal = 0; # set if program should finish execution ASAP +my $exit_signal; # first signal handled in exit_signal_handler + +#********************************************************************** +# Mail related definitions +# +my $TEXT_PASSWORD = "secret"; +my $POP3_TIMESTAMP = "<1972.987654321\@curl>"; + +#********************************************************************** +# exit_signal_handler will be triggered to indicate that the program +# should finish its execution in a controlled way as soon as possible. +# For now, program will also terminate from within this handler. +# +sub exit_signal_handler { + my $signame = shift; + # For now, simply mimic old behavior. + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose); + unlink($pidfile); + unlink($portfile); + if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); + } + exit; +} + +sub ftpmsg { + # append to the server.input file + open(my $input, ">>", "$logdir/server$idstr.input") || + logmsg "failed to open $logdir/server$idstr.input\n"; + + print $input @_; + close($input); + + # use this, open->print->close system only to make the file + # open as little as possible, to make the test suite run + # better on Windows/Cygwin +} + +#********************************************************************** +# eXsysread is a wrapper around perl's sysread() function. This will +# repeat the call to sysread() until it has actually read the complete +# number of requested bytes or an unrecoverable condition occurs. +# On success returns a positive value, the number of bytes requested. +# On failure or timeout returns zero. +# +sub eXsysread { + my $FH = shift; + my $scalar = shift; + my $nbytes = shift; + my $timeout = shift; # A zero timeout disables eXsysread() time limit + # + my $time_limited = 0; + my $timeout_rest = 0; + my $start_time = 0; + my $nread = 0; + my $rc; + + $$scalar = ""; + + if((not defined $nbytes) || ($nbytes < 1)) { + logmsg "Error: eXsysread() failure: " . + "length argument must be positive\n"; + return 0; + } + if((not defined $timeout) || ($timeout < 0)) { + logmsg "Error: eXsysread() failure: " . + "timeout argument must be zero or positive\n"; + return 0; + } + if($timeout > 0) { + # caller sets eXsysread() time limit + $time_limited = 1; + $timeout_rest = $timeout; + $start_time = int(time()); + } + + while($nread < $nbytes) { + if($time_limited) { + eval { + local $SIG{ALRM} = sub { die "alarm\n"; }; + alarm $timeout_rest; + $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread); + alarm 0; + }; + $timeout_rest = $timeout - (int(time()) - $start_time); + if($timeout_rest < 1) { + logmsg "Error: eXsysread() failure: timed out\n"; + return 0; + } + } + else { + $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread); + } + if($got_exit_signal) { + logmsg "Error: eXsysread() failure: signalled to die\n"; + return 0; + } + if(not defined $rc) { + if($!{EINTR}) { + logmsg "Warning: retrying sysread() interrupted system call\n"; + next; + } + if($!{EAGAIN}) { + logmsg "Warning: retrying sysread() due to EAGAIN\n"; + next; + } + if($!{EWOULDBLOCK}) { + logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n"; + next; + } + logmsg "Error: sysread() failure: $!\n"; + return 0; + } + if($rc < 0) { + logmsg "Error: sysread() failure: returned negative value $rc\n"; + return 0; + } + if($rc == 0) { + logmsg "Error: sysread() failure: read zero bytes\n"; + return 0; + } + $nread += $rc; + } + return $nread; +} + +#********************************************************************** +# read_mainsockf attempts to read the given amount of output from the +# sockfilter which is in use for the main or primary connection. This +# reads untranslated sockfilt lingo which may hold data read from the +# main or primary socket. On success returns 1, otherwise zero. +# +sub read_mainsockf { + my $scalar = shift; + my $nbytes = shift; + my $timeout = shift; # Optional argument, if zero blocks indefinitely + my $FH = \*SFREAD; + + if(not defined $timeout) { + $timeout = $sockfilt_timeout + ($nbytes >> 12); + } + if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) { + my ($fcaller, $lcaller) = (caller)[1,2]; + logmsg "Error: read_mainsockf() failure at $fcaller " . + "line $lcaller. Due to eXsysread() failure\n"; + return 0; + } + return 1; +} + +#********************************************************************** +# read_datasockf attempts to read the given amount of output from the +# sockfilter which is in use for the data or secondary connection. This +# reads untranslated sockfilt lingo which may hold data read from the +# data or secondary socket. On success returns 1, otherwise zero. +# +sub read_datasockf { + my $scalar = shift; + my $nbytes = shift; + my $timeout = shift; # Optional argument, if zero blocks indefinitely + my $FH = \*DREAD; + + if(not defined $timeout) { + $timeout = $sockfilt_timeout + ($nbytes >> 12); + } + if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) { + my ($fcaller, $lcaller) = (caller)[1,2]; + logmsg "Error: read_datasockf() failure at $fcaller " . + "line $lcaller. Due to eXsysread() failure\n"; + return 0; + } + return 1; +} + +sub sysread_or_die { + my $FH = shift; + my $scalar = shift; + my $length = shift; + my $fcaller; + my $lcaller; + my $result; + + $result = sysread($$FH, $$scalar, $length); + + if(not defined $result) { + ($fcaller, $lcaller) = (caller)[1,2]; + logmsg "Failed to read input\n"; + logmsg "Error: $srvrname server, sysread error: $!\n"; + logmsg "Exited from sysread_or_die() at $fcaller " . + "line $lcaller. $srvrname server, sysread error: $!\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose); + unlink($pidfile); + unlink($portfile); + if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); + } + exit; + } + elsif($result == 0) { + ($fcaller, $lcaller) = (caller)[1,2]; + logmsg "Failed to read input\n"; + logmsg "Error: $srvrname server, read zero\n"; + logmsg "Exited from sysread_or_die() at $fcaller " . + "line $lcaller. $srvrname server, read zero\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose); + unlink($pidfile); + unlink($portfile); + if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); + } + exit; + } + + return $result; +} + +sub startsf { + my @mainsockfcmd = ("./server/sockfilt".exe_ext('SRV'), + "--ipv$ipvnum", + "--port", $port, + "--pidfile", $mainsockf_pidfile, + "--portfile", $portfile, + "--logfile", $mainsockf_logfile); + $sfpid = open2(*SFREAD, *SFWRITE, @mainsockfcmd); + + print STDERR "@mainsockfcmd\n" if($verbose); + + print SFWRITE "PING\n"; + my $pong; + sysread_or_die(\*SFREAD, \$pong, 5); + + if($pong !~ /^PONG/) { + logmsg "Failed sockfilt command: @mainsockfcmd\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose); + unlink($pidfile); + unlink($portfile); + if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); + } + die "Failed to start sockfilt!"; + } +} + +#********************************************************************** +# Returns the given test's reply data +# +sub getreplydata { + my ($num) = @_; + my $testpart = ""; + + $num =~ s/^([^0-9]*)//; + if($num > 10000) { + $testpart = $num % 10000; + } + + my @data = getpart("reply", "data$testpart"); + if((!@data) && ($testpart ne "")) { + @data = getpart("reply", "data"); + } + + return @data; +} + +sub sockfilt { + my $l; + foreach $l (@_) { + printf SFWRITE "DATA\n%04x\n", length($l); + print SFWRITE $l; + } +} + +sub sockfiltsecondary { + my $l; + foreach $l (@_) { + printf DWRITE "DATA\n%04x\n", length($l); + print DWRITE $l; + } +} + +#********************************************************************** +# Send data to the client on the control stream, which happens to be plain +# stdout. +# +sub sendcontrol { + if(!$ctrldelay) { + # spit it all out at once + sockfilt @_; + } + else { + my $a = join("", @_); + my @a = split("", $a); + + for(@a) { + sockfilt $_; + portable_sleep($ctrldelay); + } + } + my $log; + foreach $log (@_) { + my $l = $log; + $l =~ s/\r/[CR]/g; + $l =~ s/\n/[LF]/g; + logmsg "> \"$l\"\n"; + } +} + +#********************************************************************** +# Send data to the FTP client on the data stream when data connection +# is actually established. Given that this sub should only be called +# when a data connection is supposed to be established, calling this +# without a data connection is an indication of weak logic somewhere. +# +sub senddata { + my $l; + if($datasockf_conn eq 'no') { + logmsg "WARNING: Detected data sending attempt without DATA channel\n"; + foreach $l (@_) { + logmsg "WARNING: Data swallowed: $l\n" + } + return; + } + + foreach $l (@_) { + if(!$datadelay) { + # spit it all out at once + sockfiltsecondary $l; + } + else { + # pause between each byte + for (split(//,$l)) { + sockfiltsecondary $_; + portable_sleep($datadelay); + } + } + } +} + +#********************************************************************** +# protocolsetup initializes the 'displaytext' and 'commandfunc' hashes +# for the given protocol. References to protocol command callbacks are +# stored in 'commandfunc' hash, and text which will be returned to the +# client before the command callback runs is stored in 'displaytext'. +# +sub protocolsetup { + my $proto = $_[0]; + + if($proto eq 'ftp') { + %commandfunc = ( + 'PORT' => \&PORT_ftp, + 'EPRT' => \&PORT_ftp, + 'LIST' => \&LIST_ftp, + 'NLST' => \&NLST_ftp, + 'PASV' => \&PASV_ftp, + 'CWD' => \&CWD_ftp, + 'PWD' => \&PWD_ftp, + 'EPSV' => \&PASV_ftp, + 'RETR' => \&RETR_ftp, + 'SIZE' => \&SIZE_ftp, + 'REST' => \&REST_ftp, + 'STOR' => \&STOR_ftp, + 'APPE' => \&STOR_ftp, # append looks like upload + 'MDTM' => \&MDTM_ftp, + ); + %displaytext = ( + 'USER' => '331 We are happy you popped in!', + 'PASS' => '230 Welcome you silly person', + 'PORT' => '200 You said PORT - I say FINE', + 'TYPE' => '200 I modify TYPE as you wanted', + 'LIST' => '150 here comes a directory', + 'NLST' => '150 here comes a directory', + 'CWD' => '250 CWD command successful.', + 'SYST' => '215 UNIX Type: L8', # just fake something + 'QUIT' => '221 bye bye baby', # just reply something + 'MKD' => '257 Created your requested directory', + 'REST' => '350 Yeah yeah we set it there for you', + 'DELE' => '200 OK OK OK whatever you say', + 'RNFR' => '350 Received your order. Please provide more', + 'RNTO' => '250 Ok, thanks. File renaming completed.', + 'NOOP' => '200 Yes, I\'m very good at doing nothing.', + 'PBSZ' => '500 PBSZ not implemented', + 'PROT' => '500 PROT not implemented', + 'welcome' => join("", + '220- _ _ ____ _ '."\r\n", + '220- ___| | | | _ \| | '."\r\n", + '220- / __| | | | |_) | | '."\r\n", + '220- | (__| |_| | _ {| |___ '."\r\n", + '220 \___|\___/|_| \_\_____|'."\r\n") + ); + } + elsif($proto eq 'pop3') { + %commandfunc = ( + 'APOP' => \&APOP_pop3, + 'AUTH' => \&AUTH_pop3, + 'CAPA' => \&CAPA_pop3, + 'DELE' => \&DELE_pop3, + 'LIST' => \&LIST_pop3, + 'NOOP' => \&NOOP_pop3, + 'PASS' => \&PASS_pop3, + 'QUIT' => \&QUIT_pop3, + 'RETR' => \&RETR_pop3, + 'RSET' => \&RSET_pop3, + 'STAT' => \&STAT_pop3, + 'TOP' => \&TOP_pop3, + 'UIDL' => \&UIDL_pop3, + 'USER' => \&USER_pop3, + ); + %displaytext = ( + 'welcome' => join("", + ' _ _ ____ _ '."\r\n", + ' ___| | | | _ \| | '."\r\n", + ' / __| | | | |_) | | '."\r\n", + ' | (__| |_| | _ {| |___ '."\r\n", + ' \___|\___/|_| \_\_____|'."\r\n", + '+OK curl POP3 server ready to serve '."\r\n") + ); + } + elsif($proto eq 'imap') { + %commandfunc = ( + 'APPEND' => \&APPEND_imap, + 'CAPABILITY' => \&CAPABILITY_imap, + 'CHECK' => \&CHECK_imap, + 'CLOSE' => \&CLOSE_imap, + 'COPY' => \©_imap, + 'CREATE' => \&CREATE_imap, + 'DELETE' => \&DELETE_imap, + 'EXAMINE' => \&EXAMINE_imap, + 'EXPUNGE' => \&EXPUNGE_imap, + 'FETCH' => \&FETCH_imap, + 'LIST' => \&LIST_imap, + 'LSUB' => \&LSUB_imap, + 'LOGIN' => \&LOGIN_imap, + 'LOGOUT' => \&LOGOUT_imap, + 'NOOP' => \&NOOP_imap, + 'RENAME' => \&RENAME_imap, + 'SEARCH' => \&SEARCH_imap, + 'SELECT' => \&SELECT_imap, + 'STATUS' => \&STATUS_imap, + 'STORE' => \&STORE_imap, + 'UID' => \&UID_imap, + 'IDLE' => \&IDLE_imap, + ); + %displaytext = ( + 'welcome' => join("", + ' _ _ ____ _ '."\r\n", + ' ___| | | | _ \| | '."\r\n", + ' / __| | | | |_) | | '."\r\n", + ' | (__| |_| | _ {| |___ '."\r\n", + ' \___|\___/|_| \_\_____|'."\r\n", + '* OK curl IMAP server ready to serve'."\r\n") + ); + } + elsif($proto eq 'smtp') { + %commandfunc = ( + 'DATA' => \&DATA_smtp, + 'EHLO' => \&EHLO_smtp, + 'EXPN' => \&EXPN_smtp, + 'HELO' => \&HELO_smtp, + 'HELP' => \&HELP_smtp, + 'MAIL' => \&MAIL_smtp, + 'NOOP' => \&NOOP_smtp, + 'RSET' => \&RSET_smtp, + 'RCPT' => \&RCPT_smtp, + 'VRFY' => \&VRFY_smtp, + 'QUIT' => \&QUIT_smtp, + ); + %displaytext = ( + 'welcome' => join("", + '220- _ _ ____ _ '."\r\n", + '220- ___| | | | _ \| | '."\r\n", + '220- / __| | | | |_) | | '."\r\n", + '220- | (__| |_| | _ {| |___ '."\r\n", + '220 \___|\___/|_| \_\_____|'."\r\n") + ); + } +} + +# Perform the disconnect handshake with sockfilt on the secondary connection +# (the only connection we actively disconnect). +# This involves waiting for the disconnect acknowledgment after the DISC +# command, while throwing away anything else that might come in before +# that. +sub disc_handshake { + print DWRITE "DISC\n"; + my $line; + my $nr; + while (5 == ($nr = sysread DREAD, $line, 5)) { + if($line eq "DATA\n") { + # Must read the data bytes to stay in sync + my $i; + sysread DREAD, $i, 5; + + my $size = 0; + if($i =~ /^([0-9a-fA-F]{4})\n/) { + $size = hex($1); + } + + logmsg "> Throwing away $size bytes on closed connection\n"; + read_datasockf(\$line, $size); + } + elsif($line eq "DISC\n") { + logmsg "Fancy that; client wants to DISC, too\n"; + printf DWRITE "ACKD\n"; + } + elsif($line eq "ACKD\n") { + # Got the ack we were waiting for + last; + } + else { + logmsg "Ignoring: $line"; + # sockfilt should not be sending us any other commands + } + } + if(!defined($nr)) { + logmsg "Error: pipe read error ($!) while waiting for ACKD"; + } + elsif($nr <= 0) { + logmsg "Error: pipe EOF while waiting for ACKD"; + } +} + +sub close_dataconn { + my ($closed)=@_; # non-zero if already disconnected + + my $datapid = processexists($datasockf_pidfile); + + logmsg "=====> Closing $datasockf_mode DATA connection...\n"; + + if(!$closed) { + if($datapid > 0) { + logmsg "Server disconnects $datasockf_mode DATA connection\n"; + disc_handshake(); + logmsg "Server disconnected $datasockf_mode DATA connection\n"; + } + else { + logmsg "Server finds $datasockf_mode DATA connection already ". + "disconnected\n"; + } + } + else { + logmsg "Server knows $datasockf_mode DATA connection is already ". + "disconnected\n"; + } + + if($datapid > 0) { + logmsg "DATA sockfilt for $datasockf_mode data channel quits ". + "(pid $datapid)\n"; + print DWRITE "QUIT\n"; + pidwait($datapid, 0); + unlink($datasockf_pidfile) if(-f $datasockf_pidfile); + logmsg "DATA sockfilt for $datasockf_mode data channel quit ". + "(pid $datapid)\n"; + } + else { + logmsg "DATA sockfilt for $datasockf_mode data channel already ". + "dead\n"; + } + + logmsg "=====> Closed $datasockf_mode DATA connection\n"; + + datasockf_state('STOPPED'); +} + +################ +################ SMTP commands +################ + +# The type of server (SMTP or ESMTP) +my $smtp_type; + +# The client (which normally contains the test number) +my $smtp_client; + +sub EHLO_smtp { + my ($client) = @_; + my @data; + + # TODO: Get the IP address of the client connection to use in the + # EHLO response when the client doesn't specify one but for now use + # 127.0.0.1 + if(!$client) { + $client = "[127.0.0.1]"; + } + + # Set the server type to ESMTP + $smtp_type = "ESMTP"; + + # Calculate the EHLO response + push @data, "$smtp_type pingpong test server Hello $client"; + + if((@capabilities) || (@auth_mechs)) { + my $mechs; + + for my $c (@capabilities) { + push @data, $c; + } + + for my $am (@auth_mechs) { + if(!$mechs) { + $mechs = "$am"; + } + else { + $mechs .= " $am"; + } + } + + if($mechs) { + push @data, "AUTH $mechs"; + } + } + + # Send the EHLO response + for(my $i = 0; $i < @data; $i++) { + my $d = $data[$i]; + + if($i < @data - 1) { + sendcontrol "250-$d\r\n"; + } + else { + sendcontrol "250 $d\r\n"; + } + } + + # Store the client (as it may contain the test number) + $smtp_client = $client; + + return 0; +} + +sub HELO_smtp { + my ($client) = @_; + + # TODO: Get the IP address of the client connection to use in the HELO + # response when the client doesn't specify one but for now use 127.0.0.1 + if(!$client) { + $client = "[127.0.0.1]"; + } + + # Set the server type to SMTP + $smtp_type = "SMTP"; + + # Send the HELO response + sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n"; + + # Store the client (as it may contain the test number) + $smtp_client = $client; + + return 0; +} + +sub MAIL_smtp { + my ($args) = @_; + + logmsg "MAIL_smtp got $args\n"; + + if (!$args) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + my $from; + my $size; + my $smtputf8 = grep /^SMTPUTF8$/, @capabilities; + my @elements = split(/ /, $args); + + # Get the FROM and SIZE parameters + for my $e (@elements) { + if($e =~ /^FROM:(.*)$/) { + $from = $1; + } + elsif($e =~ /^SIZE=(\d+)$/) { + $size = $1; + } + } + + # this server doesn't "validate" MAIL FROM addresses + if (length($from)) { + my @found; + my $valid = 1; + + # Check the capabilities for SIZE and if the specified size is + # greater than the message size then reject it + if (@found = grep /^SIZE (\d+)$/, @capabilities) { + if ($found[0] =~ /^SIZE (\d+)$/) { + if ($size > $1) { + $valid = 0; + } + } + } + + if(!$valid) { + sendcontrol "552 Message size too large\r\n"; + } + else { + sendcontrol "250 Sender OK\r\n"; + } + } + else { + sendcontrol "501 Invalid address\r\n"; + } + } + + return 0; +} + +sub RCPT_smtp { + my ($args) = @_; + + logmsg "RCPT_smtp got $args\n"; + + # Get the TO parameter + if($args !~ /^TO:(.*)/) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + my $smtputf8 = grep /^SMTPUTF8$/, @capabilities; + my $to = $1; + + # Validate the to address (only a valid email address inside <> is + # allowed, such as ) + if ((!$smtputf8 && $to =~ + /^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) || + ($smtputf8 && $to =~ + /^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) { + sendcontrol "250 Recipient OK\r\n"; + } + else { + sendcontrol "501 Invalid address\r\n"; + } + } + + return 0; +} + +sub DATA_smtp { + my ($args) = @_; + + if ($args) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + elsif ($smtp_client !~ /^(\d*)$/) { + sendcontrol "501 Invalid arguments\r\n"; + } + else { + sendcontrol "354 Show me the mail\r\n"; + + my $testno = $smtp_client; + my $filename = "$logdir/upload.$testno"; + + logmsg "Store test number $testno in $filename\n"; + + open(my $file, ">", "$filename") || + return 0; # failed to open output + + my $line; + my $ulsize=0; + my $disc=0; + my $raw; + while (5 == (sysread \*SFREAD, $line, 5)) { + if($line eq "DATA\n") { + my $i; + my $eob; + sysread \*SFREAD, $i, 5; + + my $size = 0; + if($i =~ /^([0-9a-fA-F]{4})\n/) { + $size = hex($1); + } + + read_mainsockf(\$line, $size); + + $ulsize += $size; + print $file $line if(!$nosave); + + $raw .= $line; + if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) { + # end of data marker! + $eob = 1; + } + + logmsg "> Appending $size bytes to file\n"; + + if($eob) { + logmsg "Found SMTP EOB marker\n"; + last; + } + } + elsif($line eq "DISC\n") { + # disconnect! + $disc=1; + printf SFWRITE "ACKD\n"; + last; + } + else { + logmsg "No support for: $line"; + last; + } + } + + if($nosave) { + print $file "$ulsize bytes would've been stored here\n"; + } + + close($file); + + logmsg "received $ulsize bytes upload\n"; + + sendcontrol "250 OK, data received!\r\n"; + } + + return 0; +} + +sub NOOP_smtp { + my ($args) = @_; + + if($args) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + sendcontrol "250 OK\r\n"; + } + + return 0; +} + +sub RSET_smtp { + my ($args) = @_; + + if($args) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + sendcontrol "250 Resetting\r\n"; + } + + return 0; +} + +sub HELP_smtp { + my ($args) = @_; + + # One argument is optional + if($args) { + logmsg "HELP_smtp got $args\n"; + } + + if($smtp_client eq "verifiedserver") { + # This is the secret command that verifies that this actually is + # the curl test server + sendcontrol "214 WE ROOLZ: $$\r\n"; + + if($verbose) { + print STDERR "FTPD: We returned proof we are the test server\n"; + } + + logmsg "return proof we are we\n"; + } + else { + sendcontrol "214-This server supports the following commands:\r\n"; + + if(@auth_mechs) { + sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP AUTH\r\n"; + } + else { + sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP\r\n"; + } + } + + return 0; +} + +sub VRFY_smtp { + my ($args) = @_; + my ($username, $address) = split(/ /, $args, 2); + + logmsg "VRFY_smtp got $args\n"; + + if($username eq "") { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + my $smtputf8 = grep /^SMTPUTF8$/, @capabilities; + + # Validate the username (only a valid local or external username is + # allowed, such as user or user@example.com) + if ((!$smtputf8 && $username =~ + /^([a-zA-Z0-9._%+-]+)(\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4}))?$/) || + ($smtputf8 && $username =~ + /^([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)(\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4}))?$/)) { + + my @data = getreplydata($smtp_client); + + if(!@data) { + if ($username !~ + /^([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})$/) { + push @data, "250 <$username\@example.com>\r\n" + } + else { + push @data, "250 <$username>\r\n" + } + } + + for my $d (@data) { + sendcontrol $d; + } + } + else { + sendcontrol "501 Invalid address\r\n"; + } + } + + return 0; +} + +sub EXPN_smtp { + my ($list_name) = @_; + + logmsg "EXPN_smtp got $list_name\n"; + + if(!$list_name) { + sendcontrol "501 Unrecognized parameter\r\n"; + } + else { + my @data = getreplydata($smtp_client); + + for my $d (@data) { + sendcontrol $d; + } + } + + return 0; +} + +sub QUIT_smtp { + sendcontrol "221 curl $smtp_type server signing off\r\n"; + + return 0; +} + +# What was deleted by IMAP STORE / POP3 DELE commands +my @deleted; + +################ +################ IMAP commands +################ + +# global to allow the command functions to read it +my $cmdid; + +# what was picked by SELECT +my $selected; + +# Any IMAP parameter can come in escaped and in double quotes. +# This function is dumb (so far) and just removes the quotes if present. +sub fix_imap_params { + foreach (@_) { + $_ = $1 if /^"(.*)"$/; + } +} + +sub CAPABILITY_imap { + if((!@capabilities) && (!@auth_mechs)) { + sendcontrol "$cmdid BAD Command\r\n"; + } + else { + my $data; + + # Calculate the CAPABILITY response + $data = "* CAPABILITY IMAP4"; + + for my $c (@capabilities) { + $data .= " $c"; + } + + for my $am (@auth_mechs) { + $data .= " AUTH=$am"; + } + + $data .= " pingpong test server\r\n"; + + # Send the CAPABILITY response + sendcontrol $data; + sendcontrol "$cmdid OK CAPABILITY completed\r\n"; + } + + return 0; +} + +sub LOGIN_imap { + my ($args) = @_; + my ($user, $password) = split(/ /, $args, 2); + fix_imap_params($user, $password); + + logmsg "LOGIN_imap got $args\n"; + + if ($user eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK LOGIN completed\r\n"; + } + + return 0; +} + +sub SELECT_imap { + my ($mailbox) = @_; + fix_imap_params($mailbox); + + logmsg "SELECT_imap got test $mailbox\n"; + + if($mailbox eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + # Example from RFC 3501, 6.3.1. SELECT Command + sendcontrol "* 172 EXISTS\r\n"; + sendcontrol "* 1 RECENT\r\n"; + sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n"; + sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n"; + sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n"; + sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n"; + sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n"; + sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n"; + + $selected = $mailbox; + } + + return 0; +} + +sub FETCH_imap { + my ($args) = @_; + my ($uid, $how) = split(/ /, $args, 2); + fix_imap_params($uid, $how); + + logmsg "FETCH_imap got $args\n"; + + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + else { + my @data; + my $size; + + if($selected eq "verifiedserver") { + # this is the secret command that verifies that this actually is + # the curl test server + my $response = "WE ROOLZ: $$\r\n"; + if($verbose) { + print STDERR "FTPD: We returned proof we are the test server\n"; + } + $data[0] = $response; + logmsg "return proof we are we\n"; + } + else { + # send mail content + logmsg "retrieve a mail\n"; + + @data = getreplydata($selected); + } + + for (@data) { + $size += length($_); + } + + sendcontrol "* $uid FETCH ($how {$size}\r\n"; + + for my $d (@data) { + sendcontrol $d; + } + + # Set the custom extra header content with POSTFETCH + sendcontrol "$postfetch)\r\n"; + sendcontrol "$cmdid OK FETCH completed\r\n"; + } + + return 0; +} + +sub APPEND_imap { + my ($args) = @_; + + logmsg "APPEND_imap got $args\r\n"; + + $args =~ /^([^ ]+) [^{]*\{(\d+)\}$/; + my ($mailbox, $size) = ($1, $2); + fix_imap_params($mailbox); + + if($mailbox eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "+ Ready for literal data\r\n"; + + my $testno = $mailbox; + my $filename = "$logdir/upload.$testno"; + + logmsg "Store test number $testno in $filename\n"; + + open(my $file, ">", "$filename") || + return 0; # failed to open output + + my $received = 0; + my $line; + while(5 == (sysread \*SFREAD, $line, 5)) { + if($line eq "DATA\n") { + sysread \*SFREAD, $line, 5; + + my $chunksize = 0; + if($line =~ /^([0-9a-fA-F]{4})\n/) { + $chunksize = hex($1); + } + + read_mainsockf(\$line, $chunksize); + + my $left = $size - $received; + my $datasize = ($left > $chunksize) ? $chunksize : $left; + + if($datasize > 0) { + logmsg "> Appending $datasize bytes to file\n"; + print $file substr($line, 0, $datasize) if(!$nosave); + $line = substr($line, $datasize); + + $received += $datasize; + if($received == $size) { + logmsg "Received all data, waiting for final CRLF.\n"; + } + } + + if($received == $size && $line eq "\r\n") { + last; + } + } + elsif($line eq "DISC\n") { + logmsg "Unexpected disconnect!\n"; + printf SFWRITE "ACKD\n"; + last; + } + else { + logmsg "No support for: $line"; + last; + } + } + + if($nosave) { + print $file "$size bytes would've been stored here\n"; + } + + close($file); + + logmsg "received $size bytes upload\n"; + + sendcontrol "$cmdid OK APPEND completed\r\n"; + } + + return 0; +} + +sub STORE_imap { + my ($args) = @_; + my ($uid, $what, $value) = split(/ /, $args, 3); + fix_imap_params($uid); + + logmsg "STORE_imap got $args\n"; + + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + elsif (($uid eq "") || ($what ne "+Flags") || ($value eq "")) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + if($value eq "\\Deleted") { + push(@deleted, $uid); + } + + sendcontrol "* $uid FETCH (FLAGS (\\Seen $value))\r\n"; + sendcontrol "$cmdid OK STORE completed\r\n"; + } + + return 0; +} + +sub LIST_imap { + my ($args) = @_; + my ($reference, $mailbox) = split(/ /, $args, 2); + fix_imap_params($reference, $mailbox); + + logmsg "LIST_imap got $args\n"; + + if ($reference eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + elsif ($reference eq "verifiedserver") { + # this is the secret command that verifies that this actually is + # the curl test server + sendcontrol "* LIST () \"/\" \"WE ROOLZ: $$\"\r\n"; + sendcontrol "$cmdid OK LIST Completed\r\n"; + + if($verbose) { + print STDERR "FTPD: We returned proof we are the test server\n"; + } + + logmsg "return proof we are we\n"; + } + else { + my @data = getreplydata($reference); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK LIST Completed\r\n"; + } + + return 0; +} + +sub LSUB_imap { + my ($args) = @_; + my ($reference, $mailbox) = split(/ /, $args, 2); + fix_imap_params($reference, $mailbox); + + logmsg "LSUB_imap got $args\n"; + + if ($reference eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + my @data = getreplydata($reference); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK LSUB Completed\r\n"; + } + + return 0; +} + +sub EXAMINE_imap { + my ($mailbox) = @_; + fix_imap_params($mailbox); + + logmsg "EXAMINE_imap got $mailbox\n"; + + if ($mailbox eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + my @data = getreplydata($mailbox); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n"; + } + + return 0; +} + +sub STATUS_imap { + my ($args) = @_; + my ($mailbox, $what) = split(/ /, $args, 2); + fix_imap_params($mailbox); + + logmsg "STATUS_imap got $args\n"; + + if ($mailbox eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + my @data = getreplydata($mailbox); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK STATUS completed\r\n"; + } + + return 0; +} + +sub SEARCH_imap { + my ($what) = @_; + fix_imap_params($what); + + logmsg "SEARCH_imap got $what\n"; + + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + elsif ($what eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + my @data = getreplydata($selected); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK SEARCH completed\r\n"; + } + + return 0; +} + +sub CREATE_imap { + my ($args) = @_; + fix_imap_params($args); + + logmsg "CREATE_imap got $args\n"; + + if ($args eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK CREATE completed\r\n"; + } + + return 0; +} + +sub DELETE_imap { + my ($args) = @_; + fix_imap_params($args); + + logmsg "DELETE_imap got $args\n"; + + if ($args eq "") { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK DELETE completed\r\n"; + } + + return 0; +} + +sub RENAME_imap { + my ($args) = @_; + my ($from_mailbox, $to_mailbox) = split(/ /, $args, 2); + fix_imap_params($from_mailbox, $to_mailbox); + + logmsg "RENAME_imap got $args\n"; + + if (($from_mailbox eq "") || ($to_mailbox eq "")) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK RENAME completed\r\n"; + } + + return 0; +} + +sub CHECK_imap { + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + else { + sendcontrol "$cmdid OK CHECK completed\r\n"; + } + + return 0; +} + +sub CLOSE_imap { + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + elsif (!@deleted) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK CLOSE completed\r\n"; + + @deleted = (); + } + + return 0; +} + +sub EXPUNGE_imap { + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + else { + if (!@deleted) { + # Report the number of existing messages as per the SELECT + # command + sendcontrol "* 172 EXISTS\r\n"; + } + else { + # Report the message UIDs being deleted + for my $d (@deleted) { + sendcontrol "* $d EXPUNGE\r\n"; + } + + @deleted = (); + } + + sendcontrol "$cmdid OK EXPUNGE completed\r\n"; + } + + return 0; +} + +sub COPY_imap { + my ($args) = @_; + my ($uid, $mailbox) = split(/ /, $args, 2); + fix_imap_params($uid, $mailbox); + + logmsg "COPY_imap got $args\n"; + + if (($uid eq "") || ($mailbox eq "")) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + sendcontrol "$cmdid OK COPY completed\r\n"; + } + + return 0; +} + +sub IDLE_imap { + logmsg "IDLE received\n"; + + sendcontrol "+ entering idle mode\r\n"; + return 0; +} + +sub UID_imap { + my ($args) = @_; + my ($command) = split(/ /, $args, 1); + fix_imap_params($command); + + logmsg "UID_imap got $args\n"; + + if ($selected eq "") { + sendcontrol "$cmdid BAD Command received in Invalid state\r\n"; + } + elsif (substr($command, 0, 5) eq "FETCH"){ + my $func = $commandfunc{"FETCH"}; + if($func) { + &$func($args, $command); + } + } + elsif (($command ne "COPY") && + ($command ne "STORE") && ($command ne "SEARCH")) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + my @data = getreplydata($selected); + + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK $command completed\r\n"; + } + + return 0; +} + +sub NOOP_imap { + my ($args) = @_; + my @data = ( + "* 22 EXPUNGE\r\n", + "* 23 EXISTS\r\n", + "* 3 RECENT\r\n", + "* 14 FETCH (FLAGS (\\Seen \\Deleted))\r\n", + ); + + if ($args) { + sendcontrol "$cmdid BAD Command Argument\r\n"; + } + else { + for my $d (@data) { + sendcontrol $d; + } + + sendcontrol "$cmdid OK NOOP completed\r\n"; + } + + return 0; +} + +sub LOGOUT_imap { + sendcontrol "* BYE curl IMAP server signing off\r\n"; + sendcontrol "$cmdid OK LOGOUT completed\r\n"; + + return 0; +} + +################ +################ POP3 commands +################ + +# Who is attempting to log in +my $username; + +sub CAPA_pop3 { + my @list = (); + my $mechs; + + # Calculate the capability list based on the specified capabilities + # (except APOP) and any authentication mechanisms + for my $c (@capabilities) { + push @list, "$c\r\n" unless $c eq "APOP"; + } + + for my $am (@auth_mechs) { + if(!$mechs) { + $mechs = "$am"; + } + else { + $mechs .= " $am"; + } + } + + if($mechs) { + push @list, "SASL $mechs\r\n"; + } + + if(!@list) { + sendcontrol "-ERR Unrecognized command\r\n"; + } + else { + my @data = (); + + # Calculate the CAPA response + push @data, "+OK List of capabilities follows\r\n"; + + for my $l (@list) { + push @data, "$l\r\n"; + } + + push @data, "IMPLEMENTATION POP3 pingpong test server\r\n"; + + # Send the CAPA response + for my $d (@data) { + sendcontrol $d; + } + + # End with the magic 3-byte end of listing marker + sendcontrol ".\r\n"; + } + + return 0; +} + +sub APOP_pop3 { + my ($args) = @_; + my ($user, $secret) = split(/ /, $args, 2); + + if (!grep /^APOP$/, @capabilities) { + sendcontrol "-ERR Unrecognized command\r\n"; + } + elsif (($user eq "") || ($secret eq "")) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + my $digest = Digest::MD5::md5_hex($POP3_TIMESTAMP, $TEXT_PASSWORD); + + if ($secret ne $digest) { + sendcontrol "-ERR Login failure\r\n"; + } + else { + sendcontrol "+OK Login successful\r\n"; + } + } + + return 0; +} + +sub AUTH_pop3 { + if(!@auth_mechs) { + sendcontrol "-ERR Unrecognized command\r\n"; + } + else { + my @data = (); + + # Calculate the AUTH response + push @data, "+OK List of supported mechanisms follows\r\n"; + + for my $am (@auth_mechs) { + push @data, "$am\r\n"; + } + + # Send the AUTH response + for my $d (@data) { + sendcontrol $d; + } + + # End with the magic 3-byte end of listing marker + sendcontrol ".\r\n"; + } + + return 0; +} + +sub USER_pop3 { + my ($user) = @_; + + logmsg "USER_pop3 got $user\n"; + + if (!$user) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + $username = $user; + + sendcontrol "+OK\r\n"; + } + + return 0; +} + +sub PASS_pop3 { + my ($password) = @_; + + logmsg "PASS_pop3 got $password\n"; + + sendcontrol "+OK Login successful\r\n"; + + return 0; +} + +sub RETR_pop3 { + my ($msgid) = @_; + my @data; + + if($msgid =~ /^verifiedserver$/) { + # this is the secret command that verifies that this actually is + # the curl test server + my $response = "WE ROOLZ: $$\r\n"; + if($verbose) { + print STDERR "FTPD: We returned proof we are the test server\n"; + } + $data[0] = $response; + logmsg "return proof we are we\n"; + } + else { + # send mail content + logmsg "retrieve a mail\n"; + + @data = getreplydata($msgid); + } + + sendcontrol "+OK Mail transfer starts\r\n"; + + for my $d (@data) { + sendcontrol $d; + } + + # end with the magic 3-byte end of mail marker, assumes that the + # mail body ends with a CRLF! + sendcontrol ".\r\n"; + + return 0; +} + +sub LIST_pop3 { + my @data = getpart("reply", "data"); + + logmsg "retrieve a message list\n"; + + sendcontrol "+OK Listing starts\r\n"; + + for my $d (@data) { + sendcontrol $d; + } + + # End with the magic 3-byte end of listing marker + sendcontrol ".\r\n"; + + return 0; +} + +sub DELE_pop3 { + my ($msgid) = @_; + + logmsg "DELE_pop3 got $msgid\n"; + + if (!$msgid) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + push (@deleted, $msgid); + + sendcontrol "+OK\r\n"; + } + + return 0; +} + +sub STAT_pop3 { + my ($args) = @_; + + if ($args) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + # Send statistics for the built-in fake message list as + # detailed in the LIST_pop3 function above + sendcontrol "+OK 3 4294967800\r\n"; + } + + return 0; +} + +sub NOOP_pop3 { + my ($args) = @_; + + if ($args) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + sendcontrol "+OK\r\n"; + } + + return 0; +} + +sub UIDL_pop3 { + # This is a built-in fake-message UID list + my @data = ( + "1 1\r\n", + "2 2\r\n", + "3 4\r\n", # Note that UID 3 is a simulated "deleted" message + ); + + if (!grep /^UIDL$/, @capabilities) { + sendcontrol "-ERR Unrecognized command\r\n"; + } + else { + logmsg "retrieve a message UID list\n"; + + sendcontrol "+OK Listing starts\r\n"; + + for my $d (@data) { + sendcontrol $d; + } + + # End with the magic 3-byte end of listing marker + sendcontrol ".\r\n"; + } + + return 0; +} + +sub TOP_pop3 { + my ($args) = @_; + my ($msgid, $lines) = split(/ /, $args, 2); + + logmsg "TOP_pop3 got $args\n"; + + if (!grep /^TOP$/, @capabilities) { + sendcontrol "-ERR Unrecognized command\r\n"; + } + elsif (($msgid eq "") || ($lines eq "")) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + if ($lines == "0") { + logmsg "retrieve header of mail\n"; + } + else { + logmsg "retrieve top $lines lines of mail\n"; + } + + my @data = getreplydata($msgid); + + sendcontrol "+OK Mail transfer starts\r\n"; + + # Send mail content + for my $d (@data) { + sendcontrol $d; + } + + # End with the magic 3-byte end of mail marker, assumes that the + # mail body ends with a CRLF! + sendcontrol ".\r\n"; + } + + return 0; +} + +sub RSET_pop3 { + my ($args) = @_; + + if ($args) { + sendcontrol "-ERR Protocol error\r\n"; + } + else { + if (@deleted) { + logmsg "resetting @deleted message(s)\n"; + + @deleted = (); + } + + sendcontrol "+OK\r\n"; + } + + return 0; +} + +sub QUIT_pop3 { + if(@deleted) { + logmsg "deleting @deleted message(s)\n"; + + @deleted = (); + } + + sendcontrol "+OK curl POP3 server signing off\r\n"; + + return 0; +} + +################ +################ FTP commands +################ +my $rest=0; +sub REST_ftp { + $rest = $_[0]; + logmsg "Set REST position to $rest\n" +} + +sub switch_directory_goto { + my $target_dir = $_; + + if(!$ftptargetdir) { + $ftptargetdir = "/"; + } + + if($target_dir eq "") { + $ftptargetdir = "/"; + } + elsif($target_dir eq "..") { + if($ftptargetdir eq "/") { + $ftptargetdir = "/"; + } + else { + $ftptargetdir =~ s/[[:alnum:]]+\/$//; + } + } + else { + $ftptargetdir .= $target_dir . "/"; + } +} + +sub switch_directory { + my $target_dir = $_[0]; + + if($target_dir =~ /^test-(\d+)/) { + $cwd_testno = $1; + } + elsif($target_dir eq "/") { + $ftptargetdir = "/"; + } + else { + my @dirs = split("/", $target_dir); + for(@dirs) { + switch_directory_goto($_); + } + } +} + +sub CWD_ftp { + my ($folder, $fullcommand) = $_[0]; + switch_directory($folder); + if($ftptargetdir =~ /^\/fully_simulated/) { + $ftplistparserstate = "enabled"; + logmsg "enabled FTP list parser mode\n"; + } + else { + undef $ftplistparserstate; + } +} + +sub PWD_ftp { + my $mydir; + $mydir = $ftptargetdir ? $ftptargetdir : "/"; + + if($mydir ne "/") { + $mydir =~ s/\/$//; + } + sendcontrol "257 \"$mydir\" is current directory\r\n"; +} + +sub LIST_ftp { + # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n"; + + if($datasockf_conn eq 'no') { + if($nodataconn425) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "425 Can't open data connection\r\n"; + } + elsif($nodataconn421) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "421 Connection timed out\r\n"; + } + elsif($nodataconn150) { + sendcontrol "150 Opening data connection\r\n"; + # client shall timeout + } + else { + # client shall timeout + } + return 0; + } + + logmsg "pass LIST data on data connection\n"; + + if($ftplistparserstate) { + # provide a synthetic response + my @ftpdir = ftp_contentlist($ftptargetdir); + # old hard-coded style + for(@ftpdir) { + senddata $_; + } + } + else { + my @data = getpart("reply", "data"); + for(@data) { + my $send = $_; + # convert all \n to \r\n for ASCII transfer + $send =~ s/\r\n/\n/g; + $send =~ s/\n/\r\n/g; + logmsg "send $send as data\n"; + senddata $send; + } + } + close_dataconn(0); + sendcontrol "226 ASCII transfer complete\r\n"; + return 0; +} + +sub NLST_ftp { + my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README"); + + if($datasockf_conn eq 'no') { + if($nodataconn425) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "425 Can't open data connection\r\n"; + } + elsif($nodataconn421) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "421 Connection timed out\r\n"; + } + elsif($nodataconn150) { + sendcontrol "150 Opening data connection\r\n"; + # client shall timeout + } + else { + # client shall timeout + } + return 0; + } + + logmsg "pass NLST data on data connection\n"; + for(@ftpdir) { + senddata "$_\r\n"; + } + close_dataconn(0); + sendcontrol "226 ASCII transfer complete\r\n"; + return 0; +} + +sub MDTM_ftp { + my $testno = $_[0]; + my $testpart = ""; + if ($testno > 10000) { + $testpart = $testno % 10000; + $testno = int($testno / 10000); + } + + loadtest("$logdir/test$testno"); + + my @data = getpart("reply", "mdtm"); + + my $reply = $data[0]; + chomp $reply if($reply); + + if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) { + sendcontrol "550 $testno: no such file.\r\n"; + } + elsif($reply) { + sendcontrol "$reply\r\n"; + } + else { + sendcontrol "500 MDTM: no such command.\r\n"; + } + return 0; +} + +sub SIZE_ftp { + my $testno = $_[0]; + + if($ftplistparserstate) { + my $size = wildcard_filesize($ftptargetdir, $testno); + if($size == -1) { + sendcontrol "550 $testno: No such file or directory.\r\n"; + } + else { + sendcontrol "213 $size\r\n"; + } + return 0; + } + + if($testno =~ /^verifiedserver$/) { + my $response = "WE ROOLZ: $$\r\n"; + my $size = length($response); + sendcontrol "213 $size\r\n"; + return 0; + } + + if($testno =~ /(\d+)\/?$/) { + $testno = $1; + } + else { + print STDERR "SIZE_ftp: invalid test number: $testno\n"; + return 1; + } + + my $testpart = ""; + if($testno > 10000) { + $testpart = $testno % 10000; + $testno = int($testno / 10000); + } + + loadtest("$logdir/test$testno"); + my @data = getpart("reply", "size"); + + my $size = $data[0]; + + if($size) { + $size += 0; # make it a number + if($size > -1) { + sendcontrol "213 $size\r\n"; + } + else { + sendcontrol "550 $testno: No such file or directory.\r\n"; + } + } + else { + $size=0; + @data = getpart("reply", "data$testpart"); + for(@data) { + $size += length($_); + } + if($size) { + sendcontrol "213 $size\r\n"; + } + else { + sendcontrol "550 $testno: No such file or directory.\r\n"; + } + } + return 0; +} + +sub RETR_ftp { + my ($testno) = @_; + + if($datasockf_conn eq 'no') { + if($nodataconn425) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "425 Can't open data connection\r\n"; + } + elsif($nodataconn421) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "421 Connection timed out\r\n"; + } + elsif($nodataconn150) { + sendcontrol "150 Opening data connection\r\n"; + # client shall timeout + } + else { + # client shall timeout + } + return 0; + } + + if($ftplistparserstate) { + my @content = wildcard_getfile($ftptargetdir, $testno); + if($content[0] == -1) { + #file not found + } + else { + my $size = length $content[1]; + sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n", + senddata $content[1]; + close_dataconn(0); + sendcontrol "226 File transfer complete\r\n"; + } + return 0; + } + + if($testno =~ /^verifiedserver$/) { + # this is the secret command that verifies that this actually is + # the curl test server + my $response = "WE ROOLZ: $$\r\n"; + my $len = length($response); + sendcontrol "150 Binary junk ($len bytes).\r\n"; + senddata "WE ROOLZ: $$\r\n"; + close_dataconn(0); + sendcontrol "226 File transfer complete\r\n"; + if($verbose) { + print STDERR "FTPD: We returned proof we are the test server\n"; + } + return 0; + } + + $testno =~ s/^([^0-9]*)//; + my $testpart = ""; + if ($testno > 10000) { + $testpart = $testno % 10000; + $testno = int($testno / 10000); + } + + loadtest("$logdir/test$testno"); + + my @data = getpart("reply", "data$testpart"); + + my $size=0; + for(@data) { + $size += length($_); + } + + my %hash = getpartattr("reply", "data$testpart"); + + if($size || $hash{'sendzero'}) { + + if($rest) { + # move read pointer forward + $size -= $rest; + logmsg "REST $rest was removed from size, makes $size left\n"; + $rest = 0; # reset REST offset again + } + if($retrweirdo) { + sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n", + "226 File transfer complete\r\n"; + + for(@data) { + my $send = $_; + senddata $send; + } + close_dataconn(0); + $retrweirdo=0; # switch off the weirdo again! + } + else { + my $sz = "($size bytes)"; + if($retrnosize) { + $sz = "size?"; + } + elsif($retrsize > 0) { + $sz = "($retrsize bytes)"; + } + + sendcontrol "150 Binary data connection for $testno ($testpart) $sz.\r\n"; + + for(@data) { + my $send = $_; + senddata $send; + } + close_dataconn(0); + sendcontrol "226 File transfer complete\r\n"; + } + } + else { + sendcontrol "550 $testno: No such file or directory.\r\n"; + } + return 0; +} + +sub STOR_ftp { + my $testno=$_[0]; + + my $filename = "$logdir/upload.$testno"; + + if($datasockf_conn eq 'no') { + if($nodataconn425) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "425 Can't open data connection\r\n"; + } + elsif($nodataconn421) { + sendcontrol "150 Opening data connection\r\n"; + sendcontrol "421 Connection timed out\r\n"; + } + elsif($nodataconn150) { + sendcontrol "150 Opening data connection\r\n"; + # client shall timeout + } + else { + # client shall timeout + } + return 0; + } + + logmsg "STOR test number $testno in $filename\n"; + + sendcontrol "125 Gimme gimme gimme!\r\n"; + + open(my $file, ">", "$filename") || + return 0; # failed to open output + + my $line; + my $ulsize=0; + my $disc=0; + while (5 == (sysread DREAD, $line, 5)) { + if($line eq "DATA\n") { + my $i; + sysread DREAD, $i, 5; + + my $size = 0; + if($i =~ /^([0-9a-fA-F]{4})\n/) { + $size = hex($1); + } + + read_datasockf(\$line, $size); + + #print STDERR " GOT: $size bytes\n"; + + $ulsize += $size; + print $file $line if(!$nosave); + logmsg "> Appending $size bytes to file\n"; + } + elsif($line eq "DISC\n") { + # disconnect! + $disc=1; + printf DWRITE "ACKD\n"; + last; + } + else { + logmsg "No support for: $line"; + last; + } + if($storeresp) { + # abort early + last; + } + } + if($nosave) { + print $file "$ulsize bytes would've been stored here\n"; + } + close($file); + close_dataconn($disc); + logmsg "received $ulsize bytes upload\n"; + if($storeresp) { + sendcontrol "$storeresp\r\n"; + } + else { + sendcontrol "226 File transfer complete\r\n"; + } + return 0; +} + +sub PASV_ftp { + my ($arg, $cmd)=@_; + my $pasvport; + + # kill previous data connection sockfilt when alive + if($datasockf_runs eq 'yes') { + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt for $datasockf_mode data channel killed\n"; + } + datasockf_state('STOPPED'); + + logmsg "====> Passive DATA channel requested by client\n"; + + logmsg "DATA sockfilt for passive data channel starting...\n"; + + # We fire up a new sockfilt to do the data transfer for us. + my @datasockfcmd = ("./server/sockfilt".exe_ext('SRV'), + "--ipv$ipvnum", "--port", 0, + "--pidfile", $datasockf_pidfile, + "--logfile", $datasockf_logfile); + if($nodataconn) { + push(@datasockfcmd, '--bindonly'); + } + $slavepid = open2(\*DREAD, \*DWRITE, @datasockfcmd); + + if($nodataconn) { + datasockf_state('PASSIVE_NODATACONN'); + } + else { + datasockf_state('PASSIVE'); + } + + print STDERR "@datasockfcmd\n" if($verbose); + + print DWRITE "PING\n"; + my $pong; + sysread_or_die(\*DREAD, \$pong, 5); + + if($pong =~ /^FAIL/) { + logmsg "DATA sockfilt said: FAIL\n"; + logmsg "DATA sockfilt for passive data channel failed\n"; + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + sendcontrol "500 no free ports!\r\n"; + return; + } + elsif($pong !~ /^PONG/) { + logmsg "DATA sockfilt unexpected response: $pong\n"; + logmsg "DATA sockfilt for passive data channel failed\n"; + logmsg "DATA sockfilt killed now\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + sendcontrol "500 no free ports!\r\n"; + return; + } + + logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n"; + + # Find out on what port we listen on or have bound + my $i; + print DWRITE "PORT\n"; + + # READ the response code + sysread_or_die(\*DREAD, \$i, 5); + + # READ the response size + sysread_or_die(\*DREAD, \$i, 5); + + my $size = 0; + if($i =~ /^([0-9a-fA-F]{4})\n/) { + $size = hex($1); + } + + # READ the response data + read_datasockf(\$i, $size); + + # The data is in the format + # IPvX/NNN + + if($i =~ /IPv(\d)\/(\d+)/) { + # FIX: deal with IP protocol version + $pasvport = $2; + } + + if(!$pasvport) { + logmsg "DATA sockfilt unknown listener port\n"; + logmsg "DATA sockfilt for passive data channel failed\n"; + logmsg "DATA sockfilt killed now\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + sendcontrol "500 no free ports!\r\n"; + return; + } + + if($nodataconn) { + my $str = nodataconn_str(); + logmsg "DATA sockfilt for passive data channel ($str) bound on port ". + "$pasvport\n"; + } + else { + logmsg "DATA sockfilt for passive data channel listens on port ". + "$pasvport\n"; + } + + if($cmd ne "EPSV") { + # PASV reply + my $p=$listenaddr; + $p =~ s/\./,/g; + if($pasvbadip) { + $p="1,2,3,4"; + } + sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n", + int($pasvport/256), int($pasvport%256)); + } + else { + # EPSV reply + sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport); + } + + logmsg "Client has been notified that DATA conn ". + "will be accepted on port $pasvport\n"; + + if($nodataconn) { + my $str = nodataconn_str(); + logmsg "====> Client fooled ($str)\n"; + return; + } + + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + + # assume swift operations unless explicitly slow + alarm ($datadelay?20:2); + + # Wait for 'CNCT' + my $input; + + # FIX: Monitor ctrl conn for disconnect + + while(sysread(DREAD, $input, 5)) { + + if($input !~ /^CNCT/) { + # we wait for a connected client + logmsg "Odd, we got $input from client\n"; + next; + } + logmsg "Client connects to port $pasvport\n"; + last; + } + alarm 0; + }; + if ($@) { + # timed out + logmsg "$srvrname server timed out awaiting data connection ". + "on port $pasvport\n"; + logmsg "accept failed or connection not even attempted\n"; + logmsg "DATA sockfilt killed now\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + return; + } + else { + logmsg "====> Client established passive DATA connection ". + "on port $pasvport\n"; + } + + return; +} + +# +# Support both PORT and EPRT here. +# + +sub PORT_ftp { + my ($arg, $cmd) = @_; + my $port; + my $addr; + + # kill previous data connection sockfilt when alive + if($datasockf_runs eq 'yes') { + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt for $datasockf_mode data channel killed\n"; + } + datasockf_state('STOPPED'); + + logmsg "====> Active DATA channel requested by client\n"; + + # We always ignore the given IP and use localhost. + + if($cmd eq "PORT") { + if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) { + logmsg "DATA sockfilt for active data channel not started ". + "(bad PORT-line: $arg)\n"; + sendcontrol "500 silly you, go away\r\n"; + return; + } + $port = ($5<<8)+$6; + $addr = "$1.$2.$3.$4"; + } + # EPRT |2|::1|49706| + elsif($cmd eq "EPRT") { + if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) { + logmsg "DATA sockfilt for active data channel not started ". + "(bad EPRT-line: $arg)\n"; + sendcontrol "500 silly you, go away\r\n"; + return; + } + sendcontrol "200 Thanks for dropping by. We contact you later\r\n"; + $port = $3; + $addr = $2; + } + else { + logmsg "DATA sockfilt for active data channel not started ". + "(invalid command: $cmd)\n"; + sendcontrol "500 we don't like $cmd now\r\n"; + return; + } + + if(!$port || $port > 65535) { + logmsg "DATA sockfilt for active data channel not started ". + "(illegal PORT number: $port)\n"; + return; + } + + if($nodataconn) { + my $str = nodataconn_str(); + logmsg "DATA sockfilt for active data channel not started ($str)\n"; + datasockf_state('ACTIVE_NODATACONN'); + logmsg "====> Active DATA channel not established\n"; + return; + } + + logmsg "DATA sockfilt for active data channel starting...\n"; + + # We fire up a new sockfilt to do the data transfer for us. + my @datasockfcmd = ("./server/sockfilt".exe_ext('SRV'), + "--ipv$ipvnum", "--connect", $port, "--addr", $addr, + "--pidfile", $datasockf_pidfile, + "--logfile", $datasockf_logfile); + $slavepid = open2(\*DREAD, \*DWRITE, @datasockfcmd); + + datasockf_state('ACTIVE'); + + print STDERR "@datasockfcmd\n" if($verbose); + + print DWRITE "PING\n"; + my $pong; + sysread_or_die(\*DREAD, \$pong, 5); + + if($pong =~ /^FAIL/) { + logmsg "DATA sockfilt said: FAIL\n"; + logmsg "DATA sockfilt for active data channel failed\n"; + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + # client shall timeout awaiting connection from server + return; + } + elsif($pong !~ /^PONG/) { + logmsg "DATA sockfilt unexpected response: $pong\n"; + logmsg "DATA sockfilt for active data channel failed\n"; + logmsg "DATA sockfilt killed now\n"; + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt not running\n"; + datasockf_state('STOPPED'); + # client shall timeout awaiting connection from server + return; + } + + logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n"; + + logmsg "====> Active DATA channel connected to client port $port\n"; + + return; +} + +#********************************************************************** +# datasockf_state is used to change variables that keep state info +# relative to the FTP secondary or data sockfilt process as soon as +# one of the five possible stable states is reached. Variables that +# are modified by this sub may be checked independently but should +# not be changed except by calling this sub. +# +sub datasockf_state { + my $state = $_[0]; + + if($state eq 'STOPPED') { + # Data sockfilter initial state, not running, + # not connected and not used. + $datasockf_state = $state; + $datasockf_mode = 'none'; + $datasockf_runs = 'no'; + $datasockf_conn = 'no'; + } + elsif($state eq 'PASSIVE') { + # Data sockfilter accepted connection from client. + $datasockf_state = $state; + $datasockf_mode = 'passive'; + $datasockf_runs = 'yes'; + $datasockf_conn = 'yes'; + } + elsif($state eq 'ACTIVE') { + # Data sockfilter has connected to client. + $datasockf_state = $state; + $datasockf_mode = 'active'; + $datasockf_runs = 'yes'; + $datasockf_conn = 'yes'; + } + elsif($state eq 'PASSIVE_NODATACONN') { + # Data sockfilter bound port without listening, + # client won't be able to establish data connection. + $datasockf_state = $state; + $datasockf_mode = 'passive'; + $datasockf_runs = 'yes'; + $datasockf_conn = 'no'; + } + elsif($state eq 'ACTIVE_NODATACONN') { + # Data sockfilter does not even run, + # client awaits data connection from server in vain. + $datasockf_state = $state; + $datasockf_mode = 'active'; + $datasockf_runs = 'no'; + $datasockf_conn = 'no'; + } + else { + die "Internal error. Unknown datasockf state: $state!"; + } +} + +#********************************************************************** +# nodataconn_str returns string of effective nodataconn command. Notice +# that $nodataconn may be set alone or in addition to a $nodataconnXXX. +# +sub nodataconn_str { + my $str; + # order matters + $str = 'NODATACONN' if($nodataconn); + $str = 'NODATACONN425' if($nodataconn425); + $str = 'NODATACONN421' if($nodataconn421); + $str = 'NODATACONN150' if($nodataconn150); + return "$str"; +} + +#********************************************************************** +# customize configures test server operation for each curl test, reading +# configuration commands/parameters from server commands file each time +# a new client control connection is established with the test server. +# On success returns 1, otherwise zero. +# +sub customize { + my($cmdfile) = @_; + $ctrldelay = 0; # default is no throttling of the ctrl stream + $datadelay = 0; # default is no throttling of the data stream + $retrweirdo = 0; # default is no use of RETRWEIRDO + $retrnosize = 0; # default is no use of RETRNOSIZE + $retrsize = 0; # default is no use of RETRSIZE + $pasvbadip = 0; # default is no use of PASVBADIP + $nosave = 0; # default is to actually save uploaded data to file + $nodataconn = 0; # default is to establish or accept data channel + $nodataconn425 = 0; # default is to not send 425 without data channel + $nodataconn421 = 0; # default is to not send 421 without data channel + $nodataconn150 = 0; # default is to not send 150 without data channel + $storeresp = ""; # send as ultimate STOR response + $postfetch = ""; # send as header after a FETCH response + @capabilities = (); # default is to not support capability commands + @auth_mechs = (); # default is to not support authentication commands + %fulltextreply = ();# + %commandreply = (); # + %customcount = (); # + %delayreply = (); # + + open(my $custom, "<", "$logdir/$SERVERCMD") || + return 1; + + logmsg "FTPD: Getting commands from $logdir/$SERVERCMD\n"; + + while(<$custom>) { + if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) { + $fulltextreply{$1}=eval "qq{$2}"; + logmsg "FTPD: set custom reply for $1\n"; + } + elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) { + $commandreply{$2}=eval "qq{$3}"; + if($1 ne "LF") { + $commandreply{$2}.="\r\n"; + } + else { + $commandreply{$2}.="\n"; + } + if($2 eq "") { + logmsg "FTPD: set custom reply for empty command\n"; + } + else { + logmsg "FTPD: set custom reply for $2 command\n"; + } + } + elsif($_ =~ /COUNT ([A-Z]+) (.*)/) { + # we blank the custom reply for this command when having + # been used this number of times + $customcount{$1}=$2; + logmsg "FTPD: blank custom reply for $1 command after $2 uses\n"; + } + elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) { + $delayreply{$1}=$2; + logmsg "FTPD: delay reply for $1 with $2 seconds\n"; + } + elsif($_ =~ /POSTFETCH (.*)/) { + logmsg "FTPD: read POSTFETCH header data\n"; + $postfetch = $1; + } + elsif($_ =~ /SLOWDOWNDATA/) { + $ctrldelay=0; + $datadelay=0.005; + logmsg "FTPD: send response data with 5ms delay per byte\n"; + } + elsif($_ =~ /SLOWDOWN/) { + $ctrldelay=0.005; + $datadelay=0.005; + logmsg "FTPD: send response with 5ms delay between each byte\n"; + } + elsif($_ =~ /RETRWEIRDO/) { + logmsg "FTPD: instructed to use RETRWEIRDO\n"; + $retrweirdo=1; + } + elsif($_ =~ /RETRNOSIZE/) { + logmsg "FTPD: instructed to use RETRNOSIZE\n"; + $retrnosize=1; + } + elsif($_ =~ /RETRSIZE (\d+)/) { + $retrsize= $1; + logmsg "FTPD: instructed to use RETRSIZE = $1\n"; + } + elsif($_ =~ /PASVBADIP/) { + logmsg "FTPD: instructed to use PASVBADIP\n"; + $pasvbadip=1; + } + elsif($_ =~ /NODATACONN425/) { + # applies to both active and passive FTP modes + logmsg "FTPD: instructed to use NODATACONN425\n"; + $nodataconn425=1; + $nodataconn=1; + } + elsif($_ =~ /NODATACONN421/) { + # applies to both active and passive FTP modes + logmsg "FTPD: instructed to use NODATACONN421\n"; + $nodataconn421=1; + $nodataconn=1; + } + elsif($_ =~ /NODATACONN150/) { + # applies to both active and passive FTP modes + logmsg "FTPD: instructed to use NODATACONN150\n"; + $nodataconn150=1; + $nodataconn=1; + } + elsif($_ =~ /NODATACONN/) { + # applies to both active and passive FTP modes + logmsg "FTPD: instructed to use NODATACONN\n"; + $nodataconn=1; + } + elsif($_ =~ /^STOR (.*)/) { + $storeresp=$1; + logmsg "FTPD: instructed to use respond to STOR with '$storeresp'\n"; + } + elsif($_ =~ /CAPA (.*)/) { + logmsg "FTPD: instructed to support CAPABILITY command\n"; + @capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1); + foreach (@capabilities) { + $_ = $1 if /^"(.*)"$/; + } + } + elsif($_ =~ /AUTH (.*)/) { + logmsg "FTPD: instructed to support AUTHENTICATION command\n"; + @auth_mechs = split(/ /, $1); + } + elsif($_ =~ /NOSAVE/) { + # don't actually store the file we upload - to be used when + # uploading insanely huge amounts + $nosave = 1; + logmsg "FTPD: NOSAVE prevents saving of uploaded data\n"; + } + elsif($_ =~ /^Testnum (\d+)/){ + $testno = $1; + logmsg "FTPD: run test case number: $testno\n"; + } + } + close($custom); +} + +#---------------------------------------------------------------------- +#---------------------------------------------------------------------- +#--------------------------- END OF SUBS ---------------------------- +#---------------------------------------------------------------------- +#---------------------------------------------------------------------- + +#********************************************************************** +# Parse command line options +# +# Options: +# +# --verbose # verbose +# --srcdir # source directory +# --id # server instance number +# --proto # server protocol +# --pidfile # server pid file +# --portfile # server port file +# --logfile # server log file +# --logdir # server log directory +# --ipv4 # server IP version 4 +# --ipv6 # server IP version 6 +# --port # server listener port +# --addr # server address for listener port binding +# +while(@ARGV) { + if($ARGV[0] eq '--verbose') { + $verbose = 1; + } + elsif($ARGV[0] eq '--srcdir') { + if($ARGV[1]) { + $srcdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--id') { + if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) { + $idnum = $1 if($1 > 0); + shift @ARGV; + } + } + elsif($ARGV[0] eq '--proto') { + if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) { + $proto = $1; + shift @ARGV; + } + else { + die "unsupported protocol $ARGV[1]"; + } + } + elsif($ARGV[0] eq '--pidfile') { + if($ARGV[1]) { + $pidfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--portfile') { + if($ARGV[1]) { + $portfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logfile') { + if($ARGV[1]) { + $logfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logdir') { + if($ARGV[1]) { + $logdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--ipv4') { + $ipvnum = 4; + $listenaddr = '127.0.0.1' if($listenaddr eq '::1'); + } + elsif($ARGV[0] eq '--ipv6') { + $ipvnum = 6; + $listenaddr = '::1' if($listenaddr eq '127.0.0.1'); + } + elsif($ARGV[0] eq '--port') { + if($ARGV[1] =~ /^(\d+)$/) { + $port = $1; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--addr') { + if($ARGV[1]) { + my $tmpstr = $ARGV[1]; + if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) { + $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4); + } + elsif($ipvnum == 6) { + $listenaddr = $tmpstr; + $listenaddr =~ s/^\[(.*)\]$/$1/; + } + shift @ARGV; + } + } + else { + print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n"; + } + shift @ARGV; +} + +#*************************************************************************** +# Initialize command line option dependent variables +# + +if($pidfile) { + # Use our pidfile directory to store the other pidfiles + $piddir = dirname($pidfile); +} +else { + # Use the current directory to store all the pidfiles + $piddir = $path; + $pidfile = server_pidfilename($piddir, $proto, $ipvnum, $idnum); +} +if(!$portfile) { + $portfile = $piddir . "/" . $PORTFILE; +} +if(!$srcdir) { + $srcdir = $ENV{'srcdir'} || '.'; +} +if(!$logfile) { + $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum); +} + +$mainsockf_pidfile = mainsockf_pidfilename($piddir, $proto, $ipvnum, $idnum); +$mainsockf_logfile = + mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum); + +if($proto eq 'ftp') { + $datasockf_pidfile = datasockf_pidfilename($piddir, $proto, $ipvnum, $idnum); + $datasockf_logfile = + datasockf_logfilename($logdir, $proto, $ipvnum, $idnum); +} + +$srvrname = servername_str($proto, $ipvnum, $idnum); +$serverlogs_lockfile = "$logdir/$LOCKDIR/${srvrname}.lock"; + +$idstr = "$idnum" if($idnum > 1); + +protocolsetup($proto); + +$SIG{INT} = \&exit_signal_handler; +$SIG{TERM} = \&exit_signal_handler; + +startsf(); + +# actual port +if($portfile && !$port) { + my $aport; + open(my $p, "<", "$portfile"); + $aport = <$p>; + close($p); + $port = 0 + $aport; +} + +logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto)); + +open(my $pid, ">", "$pidfile"); +print $pid $$."\n"; +close($pid); + +logmsg("logged pid $$ in $pidfile\n"); + +while(1) { + + # kill previous data connection sockfilt when alive + if($datasockf_runs eq 'yes') { + killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose, 'data'); + logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n"; + } + datasockf_state('STOPPED'); + + # + # We read 'sockfilt' commands. + # + my $input; + + logmsg "Awaiting input\n"; + sysread_or_die(\*SFREAD, \$input, 5); + + if($input !~ /^CNCT/) { + # we wait for a connected client + logmsg "MAIN sockfilt said: $input"; + next; + } + logmsg "====> Client connect\n"; + + set_advisor_read_lock($serverlogs_lockfile); + $serverlogslocked = 1; + + # flush data: + $| = 1; + + &customize(); # read test control instructions + loadtest("$logdir/test$testno"); + + my $welcome = $commandreply{"welcome"}; + if(!$welcome) { + $welcome = $displaytext{"welcome"}; + } + else { + # clear it after use + $commandreply{"welcome"}=""; + if($welcome !~ /\r\n\z/) { + $welcome .= "\r\n"; + } + } + sendcontrol $welcome; + + #remove global variables from last connection + if($ftplistparserstate) { + undef $ftplistparserstate; + } + if($ftptargetdir) { + $ftptargetdir = ""; + } + + if($verbose) { + print STDERR "OUT: $welcome"; + } + + my $full = ""; + + while(1) { + my $i; + + # Now we expect to read DATA\n[hex size]\n[prot], where the [prot] + # part only is FTP lingo. + + # COMMAND + sysread_or_die(\*SFREAD, \$i, 5); + + if($i !~ /^DATA/) { + logmsg "MAIN sockfilt said $i"; + if($i =~ /^DISC/) { + # disconnect + printf SFWRITE "ACKD\n"; + last; + } + next; + } + + # SIZE of data + sysread_or_die(\*SFREAD, \$i, 5); + + my $size = 0; + if($i =~ /^([0-9a-fA-F]{4})\n/) { + $size = hex($1); + } + + # data + read_mainsockf(\$input, $size); + + ftpmsg $input; + + $full .= $input; + + # Loop until command completion + next unless($full =~ /\r\n$/); + + # Remove trailing CRLF. + $full =~ s/[\n\r]+$//; + + my $FTPCMD; + my $FTPARG; + if($proto eq "imap") { + # IMAP is different with its identifier first on the command line + if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) || + ($full =~ /^([^ ]+) ([^ ]+)/)) { + $cmdid=$1; # set the global variable + $FTPCMD=$2; + $FTPARG=$3; + } + # IMAP authentication cancellation + elsif($full =~ /^\*$/) { + # Command id has already been set + $FTPCMD="*"; + $FTPARG=""; + } + # IMAP long "commands" are base64 authentication data + elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) { + # Command id has already been set + $FTPCMD=$full; + $FTPARG=""; + } + else { + sendcontrol "$full BAD Command\r\n"; + last; + } + } + elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) { + $FTPCMD=$1; + $FTPARG=$3; + } + elsif($proto eq "pop3") { + # POP3 authentication cancellation + if($full =~ /^\*$/) { + $FTPCMD="*"; + $FTPARG=""; + } + # POP3 long "commands" are base64 authentication data + elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) { + $FTPCMD=$full; + $FTPARG=""; + } + else { + sendcontrol "-ERR Unrecognized command\r\n"; + last; + } + } + elsif($proto eq "smtp") { + # SMTP authentication cancellation + if($full =~ /^\*$/) { + $FTPCMD="*"; + $FTPARG=""; + } + # SMTP long "commands" are base64 authentication data + elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) { + $FTPCMD=$full; + $FTPARG=""; + } + else { + sendcontrol "500 Unrecognized command\r\n"; + last; + } + } + else { + sendcontrol "500 Unrecognized command\r\n"; + last; + } + + logmsg "< \"$full\"\n"; + + if($verbose) { + print STDERR "IN: $full\n"; + } + + $full = ""; + + my $delay = $delayreply{$FTPCMD}; + if($delay) { + # just go sleep this many seconds! + logmsg("Sleep for $delay seconds\n"); + my $twentieths = $delay * 20; + while($twentieths--) { + portable_sleep(0.05) unless($got_exit_signal); + } + } + + my $check = 1; # no response yet + + # See if there is a custom reply for the full text + my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD; + my $text = $fulltextreply{$fulltext}; + if($text && ($text ne "")) { + sendcontrol "$text\r\n"; + $check = 0; + } + else { + # See if there is a custom reply for the command + $text = $commandreply{$FTPCMD}; + if($text && ($text ne "")) { + if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) { + # used enough times so blank the custom command reply + $commandreply{$FTPCMD}=""; + } + + sendcontrol $text; + $check = 0; + } + else { + # See if there is any display text for the command + $text = $displaytext{$FTPCMD}; + if($text && ($text ne "")) { + if($proto eq 'imap') { + sendcontrol "$cmdid $text\r\n"; + } + else { + sendcontrol "$text\r\n"; + } + + $check = 0; + } + + # only perform this if we're not faking a reply + my $func = $commandfunc{uc($FTPCMD)}; + if($func) { + &$func($FTPARG, $FTPCMD); + $check = 0; + } + } + } + + if($check) { + logmsg "$FTPCMD wasn't handled!\n"; + if($proto eq 'pop3') { + sendcontrol "-ERR $FTPCMD is not dealt with!\r\n"; + } + elsif($proto eq 'imap') { + sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n"; + } + else { + sendcontrol "500 $FTPCMD is not dealt with!\r\n"; + } + } + + } # while(1) + logmsg "====> Client disconnected\n"; + + if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); + } +} + +killsockfilters($piddir, $proto, $ipvnum, $idnum, $verbose); +unlink($pidfile); +if($serverlogslocked) { + $serverlogslocked = 0; + clear_advisor_read_lock($serverlogs_lockfile); +} + +exit; diff --git a/local-test-curl-full-01/afc-curl/tests/getpart.pm b/local-test-curl-full-01/afc-curl/tests/getpart.pm new file mode 100644 index 0000000000000000000000000000000000000000..afc1f06214eaa27754f0ab8d863c40d268f950f5 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/getpart.pm @@ -0,0 +1,359 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +package getpart; + +use strict; +use warnings; + +BEGIN { + use base qw(Exporter); + + our @EXPORT = qw( + compareparts + fulltest + getpart + getpartattr + loadarray + loadtest + partexists + striparray + writearray + ); +} + +use Memoize; +use MIME::Base64; + +my @xml; # test data file contents +my $xmlfile; # test data file name + +my $warning=0; +my $trace=0; + +# Normalize the part function arguments for proper caching. This includes the +# file name in the arguments since that is an implied parameter that affects the +# return value. Any error messages will only be displayed the first time, but +# those are disabled by default anyway, so should never been seen outside +# development. +sub normalize_part { + push @_, $xmlfile; + return join("\t", @_); +} + +sub decode_hex { + my $s = $_; + # remove everything not hex + $s =~ s/[^A-Fa-f0-9]//g; + # encode everything + $s =~ s/([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg; + return $s; +} + +sub testcaseattr { + my %hash; + for(@xml) { + if(($_ =~ /^ *\]*)/)) { + my $attr=$1; + while($attr =~ s/ *([^=]*)= *(\"([^\"]*)\"|([^\> ]*))//) { + my ($var, $cont)=($1, $2); + $cont =~ s/^\"(.*)\"$/$1/; + $hash{$var}=$cont; + } + } + } + return %hash; +} + +sub getpartattr { + # if $part is undefined (ie only one argument) then + # return the attributes of the section + + my ($section, $part)=@_; + + my %hash; + my $inside=0; + + # print "Section: $section, part: $part\n"; + + for(@xml) { + # print "$inside: $_"; + if(!$inside && ($_ =~ /^ *\<$section/)) { + $inside++; + } + if((1 ==$inside) && ( ($_ =~ /^ *\<$part ([^>]*)/) || + !(defined($part)) ) + ) { + $inside++; + my $attr=$1; + + while($attr =~ s/ *([^=]*)= *(\"([^\"]*)\"|([^\> ]*))//) { + my ($var, $cont)=($1, $2); + $cont =~ s/^\"(.*)\"$/$1/; + $hash{$var}=$cont; + } + last; + } + # detect end of section when part wasn't found + elsif((1 ==$inside) && ($_ =~ /^ *\<\/$section\>/)) { + last; + } + elsif((2 ==$inside) && ($_ =~ /^ *\<\/$part/)) { + $inside--; + } + } + return %hash; +} +memoize('getpartattr', NORMALIZER => 'normalize_part'); # cache each result + +sub getpart { + my ($section, $part)=@_; + + my @this; + my $inside=0; + my $base64=0; + my $hex=0; + my $line; + + for(@xml) { + $line++; + if(!$inside && ($_ =~ /^ *\<$section/)) { + $inside++; + } + elsif(($inside >= 1) && ($_ =~ /^ *\<$part[ \>]/)) { + if($inside > 1) { + push @this, $_; + } + elsif($_ =~ /$part [^>]*base64=/) { + # attempt to detect our base64 encoded part + $base64=1; + } + elsif($_ =~ /$part [^>]*hex=/) { + # attempt to detect a hex-encoded part + $hex=1; + } + $inside++; + } + elsif(($inside >= 2) && ($_ =~ /^ *\<\/$part[ \>]/)) { + if($inside > 2) { + push @this, $_; + } + $inside--; + } + elsif(($inside >= 1) && ($_ =~ /^ *\<\/$section/)) { + if($inside > 1) { + print STDERR "$xmlfile:$line:1: error: missing tag before \n"; + @this = ("format error in $xmlfile"); + } + if($trace && @this) { + print STDERR "*** getpart.pm: $section/$part returned data!\n"; + } + if($warning && !@this) { + print STDERR "*** getpart.pm: $section/$part returned empty!\n"; + } + if($base64) { + # decode the whole array before returning it! + for(@this) { + my $decoded = decode_base64($_); + $_ = $decoded; + } + } + elsif($hex) { + # decode the whole array before returning it! + for(@this) { + my $decoded = decode_hex($_); + $_ = $decoded; + } + } + return @this; + } + elsif($inside >= 2) { + push @this, $_; + } + } + if($trace && @this) { + # section/part has data but end of section not detected, + # end of file implies end of section. + print STDERR "*** getpart.pm: $section/$part returned data!\n"; + } + if($warning && !@this) { + # section/part does not exist or has no data without an end of + # section; end of file implies end of section. + print STDERR "*** getpart.pm: $section/$part returned empty!\n"; + } + return @this; +} +memoize('getpart', NORMALIZER => 'normalize_part'); # cache each result + +sub partexists { + my ($section, $part)=@_; + + my $inside = 0; + + for(@xml) { + if(!$inside && ($_ =~ /^ *\<$section/)) { + $inside++; + } + elsif((1 == $inside) && ($_ =~ /^ *\<$part[ \>]/)) { + return 1; # exists + } + elsif((1 == $inside) && ($_ =~ /^ *\<\/$section/)) { + return 0; # does not exist + } + } + return 0; # does not exist +} +# The code currently never calls this more than once per part per file, so +# caching a result that will never be used again just slows things down. +# memoize('partexists', NORMALIZER => 'normalize_part'); # cache each result + +sub loadtest { + my ($file)=@_; + + if(defined $xmlfile && $file eq $xmlfile) { + # This test is already loaded + return + } + + undef @xml; + $xmlfile = ""; + + if(open(my $xmlh, "<", "$file")) { + binmode $xmlh; # for crapage systems, use binary + while(<$xmlh>) { + push @xml, $_; + } + close($xmlh); + } + else { + # failure + if($warning) { + print STDERR "file $file wouldn't open!\n"; + } + return 1; + } + $xmlfile = $file; + return 0; +} + + +# Return entire document as list of lines +sub fulltest { + return @xml; +} + +# write the test to the given file +sub savetest { + my ($file)=@_; + + if(open(my $xmlh, ">", "$file")) { + binmode $xmlh; # for crapage systems, use binary + for(@xml) { + print $xmlh $_; + } + close($xmlh); + } + else { + # failure + if($warning) { + print STDERR "file $file wouldn't open!\n"; + } + return 1; + } + return 0; +} + +# +# Strip off all lines that match the specified pattern and return +# the new array. +# + +sub striparray { + my ($pattern, $arrayref) = @_; + + my @array; + + for(@$arrayref) { + if($_ !~ /$pattern/) { + push @array, $_; + } + } + return @array; +} + +# +# pass array *REFERENCES* ! +# +sub compareparts { + my ($firstref, $secondref)=@_; + + my $first = join("", @$firstref); + my $second = join("", @$secondref); + + # we cannot compare arrays index per index since with the base64 chunks, + # they may not be "evenly" distributed + + # NOTE: this no longer strips off carriage returns from the arrays. Is that + # really necessary? It ruins the testing of newlines. I believe it was once + # added to enable tests on Windows. + + if($first ne $second) { + return 1; + } + + return 0; +} + +# +# Write a given array to the specified file +# +sub writearray { + my ($filename, $arrayref)=@_; + + open(my $temp, ">", "$filename") || die "Failure writing file"; + binmode($temp,":raw"); # Cygwin fix by Kevin Roth + for(@$arrayref) { + print $temp $_; + } + close($temp) || die "Failure writing file"; +} + +# +# Load a specified file and return it as an array +# +sub loadarray { + my ($filename)=@_; + my @array; + + if (open(my $temp, "<", "$filename")) { + while(<$temp>) { + push @array, $_; + } + close($temp); + } + return @array; +} + + +1; diff --git a/local-test-curl-full-01/afc-curl/tests/globalconfig.pm b/local-test-curl-full-01/afc-curl/tests/globalconfig.pm new file mode 100644 index 0000000000000000000000000000000000000000..08aff0ff3ee325b7eef61265f2e2a75b8fec1959 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/globalconfig.pm @@ -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 +# +########################################################################### + +# This module contains global variables used in multiple modules in the test +# harness but not really "owned" by any one. + +package globalconfig; + +use strict; +use warnings; + +BEGIN { + use base qw(Exporter); + + our @EXPORT = qw( + $anyway + $automakestyle + $CURL + $CURLVERSION + $CURLVERNUM + $DATE + $has_shared + $LIBDIR + $listonly + $LOCKDIR + $LOGDIR + $memanalyze + $MEMDUMP + $perlcmd + $perl + $PIDDIR + $proxy_address + $PROXYIN + $pwd + $randseed + $run_duphandle + $run_event_based + $SERVERCMD + $SERVERIN + $srcdir + $TESTDIR + $torture + $valgrind + $VCURL + $verbose + %feature + %keywords + @protocols + $bundle + $dev_null + ); +} +use pathhelp qw(exe_ext); +use Cwd qw(getcwd); + + +####################################################################### +# global configuration variables +# + +# config variables overridden by command-line options +our $verbose; # 1 to show verbose test output +our $torture; # 1 to enable torture testing +our $proxy_address; # external HTTP proxy address +our $listonly; # only list the tests +our $run_duphandle; # run curl with --test-duphandle to verify handle duplication +our $run_event_based; # run curl with --test-event to test the event API +our $automakestyle; # use automake-like test status output format +our $anyway; # continue anyway, even if a test fail +our $CURLVERSION=""; # curl's reported version number +our $CURLVERNUM=""; # curl's reported version number (without -DEV) +our $randseed = 0; # random number seed + +# paths +our $pwd = getcwd(); # current working directory +our $srcdir = $ENV{'srcdir'} || '.'; # root of the test source code +our $perlcmd="$^X"; +our $perl="$perlcmd -I. -I$srcdir"; # invoke perl like this +our $LOGDIR="log"; # root of the log directory; this will be different for + # each runner in multiprocess mode +our $LIBDIR="./libtest"; +our $TESTDIR="$srcdir/data"; +our $CURL="../src/curl".exe_ext('TOOL'); # what curl binary to run on the tests +our $VCURL=$CURL; # what curl binary to use to verify the servers with + # VCURL is handy to set to the system one when the one you + # just built hangs or crashes and thus prevent verification +# the path to the script that analyzes the memory debug output file +our $memanalyze="$perl $srcdir/memanalyze.pl"; +our $valgrind; # path to valgrind, or empty if disabled +our $bundle = 0; # use bundled server, libtest, unit binaries +our $dev_null = ($^O eq 'MSWin32' ? 'NUL' : '/dev/null'); + +# paths in $LOGDIR +our $LOCKDIR = "lock"; # root of the server directory with lock files +our $PIDDIR = "server"; # root of the server directory with PID files +our $SERVERIN="server.input"; # what curl sent the server +our $PROXYIN="proxy.input"; # what curl sent the proxy +our $MEMDUMP="memdump"; # file that the memory debugging creates +our $SERVERCMD="server.cmd"; # copy server instructions here + +# other config variables +our @protocols; # array of lowercase supported protocol servers +our %feature; # hash of enabled features +our $has_shared; # built as a shared library +our %keywords; # hash of keywords from the test spec + +1; diff --git a/local-test-curl-full-01/afc-curl/tests/http-server.pl b/local-test-curl-full-01/afc-curl/tests/http-server.pl new file mode 100644 index 0000000000000000000000000000000000000000..526ec319bddbeb4af99a5b7b48649ecd9e2ef6d5 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/http-server.pl @@ -0,0 +1,194 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +#*************************************************************************** + +use strict; +use warnings; + +BEGIN { + push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'}); + push(@INC, "."); +} + +use File::Basename; + +use serverhelp qw( + server_pidfilename + server_logfilename + ); + +use pathhelp qw( + exe_ext + ); + +my $verbose = 0; # set to 1 for debugging +my $port = 8990; # just a default +my $unix_socket; # location to place a listening Unix socket +my $ipvnum = 4; # default IP version of http server +my $idnum = 1; # default http server instance number +my $proto = 'http'; # protocol the http server speaks +my $pidfile; # pid file +my $portfile; # port number file +my $logfile; # log file +my $cmdfile; # command file +my $connect; # IP to connect to on CONNECT +my $keepalive_secs; # number of seconds to keep idle connections +my $srcdir; +my $gopher = 0; + +my $flags = ""; +my $path = '.'; +my $logdir = $path .'/log'; +my $piddir; + +while(@ARGV) { + if($ARGV[0] eq '--pidfile') { + if($ARGV[1]) { + $pidfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--portfile') { + if($ARGV[1]) { + $portfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--config') { + if($ARGV[1]) { + $cmdfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logfile') { + if($ARGV[1]) { + $logfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logdir') { + if($ARGV[1]) { + $logdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--srcdir') { + if($ARGV[1]) { + $srcdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--ipv4') { + $ipvnum = 4; + } + elsif($ARGV[0] eq '--ipv6') { + $ipvnum = 6; + } + elsif($ARGV[0] eq '--unix-socket') { + $ipvnum = 'unix'; + if($ARGV[1]) { + $unix_socket = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--gopher') { + $gopher = 1; + } + elsif($ARGV[0] eq '--port') { + if($ARGV[1] =~ /^(\d+)$/) { + $port = $1; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--connect') { + if($ARGV[1]) { + $connect = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--keepalive') { + if($ARGV[1]) { + $keepalive_secs = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--id') { + if($ARGV[1] =~ /^(\d+)$/) { + $idnum = $1 if($1 > 0); + shift @ARGV; + } + } + elsif($ARGV[0] eq '--verbose') { + $verbose = 1; + } + else { + print STDERR "\nWarning: http-server.pl unknown parameter: $ARGV[0]\n"; + } + shift @ARGV; +} + +#*************************************************************************** +# Initialize command line option dependent variables +# + +if($pidfile) { + # Use our pidfile directory to store the other pidfiles + $piddir = dirname($pidfile); +} +else { + # Use the current directory to store all the pidfiles + $piddir = $path; + $pidfile = server_pidfilename($piddir, $proto, $ipvnum, $idnum); +} +if(!$portfile) { + $portfile = server_portfilename($piddir, $proto, $ipvnum, $idnum); +} +if(!$srcdir) { + $srcdir = $ENV{'srcdir'} || '.'; +} +if(!$logfile) { + $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum); +} + +$flags .= "--pidfile \"$pidfile\" ". + "--cmdfile \"$cmdfile\" ". + "--logfile \"$logfile\" ". + "--logdir \"$logdir\" ". + "--portfile \"$portfile\" "; +$flags .= "--gopher " if($gopher); +$flags .= "--connect $connect " if($connect); +$flags .= "--keepalive $keepalive_secs " if($keepalive_secs); +if($ipvnum eq 'unix') { + $flags .= "--unix-socket '$unix_socket' "; +} else { + $flags .= "--ipv$ipvnum --port $port "; +} +$flags .= "--srcdir \"$srcdir\""; + +if($verbose) { + print STDERR "RUN: server/sws".exe_ext('SRV')." $flags\n"; +} + +$| = 1; +exec("exec server/sws".exe_ext('SRV')." $flags"); diff --git a/local-test-curl-full-01/afc-curl/tests/http2-server.pl b/local-test-curl-full-01/afc-curl/tests/http2-server.pl new file mode 100644 index 0000000000000000000000000000000000000000..fef17680afd632973941e62c94d753144a034ad3 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/http2-server.pl @@ -0,0 +1,121 @@ +#!/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 invokes nghttpx properly to have it serve HTTP/2 for us. +# nghttpx runs as a proxy in front of our "actual" HTTP/1 server. +use Cwd; +use Cwd 'abs_path'; +use File::Basename; + +my $logdir = "log"; +my $pidfile = "$logdir/nghttpx.pid"; +my $logfile = "$logdir/http2.log"; +my $nghttpx = "nghttpx"; +my $listenport = 9015; +my $listenport2 = 9016; +my $connect = "127.0.0.1,8990"; +my $conf = "nghttpx.conf"; +my $cert = "Server-localhost-sv"; +my $dev_null = ($^O eq 'MSWin32' ? 'NUL' : '/dev/null'); + +#*************************************************************************** +# Process command line options +# +while(@ARGV) { + if($ARGV[0] eq '--verbose') { + $verbose = 1; + } + elsif($ARGV[0] eq '--pidfile') { + if($ARGV[1]) { + $pidfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--nghttpx') { + if($ARGV[1]) { + $nghttpx = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--port') { + if($ARGV[1]) { + $listenport = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--port2') { + if($ARGV[1]) { + $listenport2 = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--connect') { + if($ARGV[1]) { + $connect = $ARGV[1]; + $connect =~ s/:/,/; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logfile') { + if($ARGV[1]) { + $logfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logdir') { + if($ARGV[1]) { + $logdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--conf') { + if($ARGV[1]) { + $conf = $ARGV[1]; + shift @ARGV; + } + } + else { + print STDERR "\nWarning: http2-server.pl unknown parameter: $ARGV[0]\n"; + } + shift @ARGV; +} + +my $srcdir = dirname(__FILE__); +$certfile = "$srcdir/certs/$cert.pem"; +$keyfile = "$srcdir/certs/$cert.key"; +$certfile = abs_path($certfile); +$keyfile = abs_path($keyfile); + +my $cmdline="$nghttpx --backend=$connect ". + "--backend-keep-alive-timeout=500ms ". + "--frontend=\"*,$listenport;no-tls\" ". + "--frontend=\"*,$listenport2\" ". + "--log-level=INFO ". + "--pid-file=$pidfile ". + "--conf=$conf ". + "--errorlog-file=$logfile ". + "$keyfile $certfile"; +print "RUN: $cmdline\n" if($verbose); +exec("exec $cmdline 2>$dev_null"); diff --git a/local-test-curl-full-01/afc-curl/tests/http3-server.pl b/local-test-curl-full-01/afc-curl/tests/http3-server.pl new file mode 100644 index 0000000000000000000000000000000000000000..489053c1937c45e11f0850dd86b0bb18931785a7 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/http3-server.pl @@ -0,0 +1,121 @@ +#!/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 invokes nghttpx properly to have it serve HTTP/3 for us. +# nghttpx runs as a proxy in front of our "actual" HTTP/1 server. + +use Cwd; +use Cwd 'abs_path'; +use File::Basename; + +my $logdir = "log"; +my $pidfile = "$logdir/nghttpx.pid"; +my $logfile = "$logdir/http3.log"; +my $nghttpx = "nghttpx"; +my $listenport = 9017; +my $connect = "127.0.0.1,8990"; +my $cert = "Server-localhost-sv"; +my $conf = "nghttpx.conf"; +my $dev_null = ($^O eq 'MSWin32' ? 'NUL' : '/dev/null'); + +#*************************************************************************** +# Process command line options +# +while(@ARGV) { + if($ARGV[0] eq '--verbose') { + $verbose = 1; + } + elsif($ARGV[0] eq '--pidfile') { + if($ARGV[1]) { + $pidfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--nghttpx') { + if($ARGV[1]) { + $nghttpx = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--port') { + if($ARGV[1]) { + $listenport = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--connect') { + if($ARGV[1]) { + $connect = $ARGV[1]; + $connect =~ s/:/,/; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--cert') { + if($ARGV[1]) { + $cert = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logfile') { + if($ARGV[1]) { + $logfile = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--logdir') { + if($ARGV[1]) { + $logdir = $ARGV[1]; + shift @ARGV; + } + } + elsif($ARGV[0] eq '--conf') { + if($ARGV[1]) { + $conf = $ARGV[1]; + shift @ARGV; + } + } + else { + print STDERR "\nWarning: http3-server.pl unknown parameter: $ARGV[0]\n"; + } + shift @ARGV; +} + +my $srcdir = dirname(__FILE__); +$certfile = "$srcdir/certs/$cert.pem"; +$keyfile = "$srcdir/certs/$cert.key"; +$certfile = abs_path($certfile); +$keyfile = abs_path($keyfile); + +my $cmdline="$nghttpx --http2-proxy --backend=$connect ". + "--backend-keep-alive-timeout=500ms ". + "--frontend=\"*,$listenport\" ". + "--frontend=\"*,$listenport;quic\" ". + "--log-level=INFO ". + "--pid-file=$pidfile ". + "--errorlog-file=$logfile ". + "--conf=$conf ". + "$keyfile $certfile"; +print "RUN: $cmdline\n" if($verbose); +exec("exec $cmdline 2>$dev_null"); diff --git a/local-test-curl-full-01/afc-curl/tests/memanalyze.pl b/local-test-curl-full-01/afc-curl/tests/memanalyze.pl new file mode 100644 index 0000000000000000000000000000000000000000..4e164fe38945c0c1c99ad0d1c9b934d17f0310f6 --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/memanalyze.pl @@ -0,0 +1,434 @@ +#!/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 +# +########################################################################### +# +# Example input: +# +# MEM mprintf.c:1094 malloc(32) = e5718 +# MEM mprintf.c:1103 realloc(e5718, 64) = e6118 +# MEM sendf.c:232 free(f6520) + +my $mallocs=0; +my $callocs=0; +my $reallocs=0; +my $strdups=0; +my $wcsdups=0; +my $showlimit; +my $sends=0; +my $recvs=0; +my $sockets=0; + +while(1) { + if($ARGV[0] eq "-v") { + $verbose=1; + shift @ARGV; + } + elsif($ARGV[0] eq "-t") { + $trace=1; + shift @ARGV; + } + elsif($ARGV[0] eq "-l") { + # only show what alloc that caused a memlimit failure + $showlimit=1; + shift @ARGV; + } + else { + last; + } +} + +my $memsum; # the total number of memory allocated over the lifetime +my $maxmem; # the high water mark + +sub newtotal { + my ($newtot)=@_; + # count a max here + + if($newtot > $maxmem) { + $maxmem= $newtot; + } +} + +my $file = $ARGV[0]; + +if(! -f $file) { + print "Usage: memanalyze.pl [options] \n", + "Options:\n", + " -l memlimit failure displayed\n", + " -v Verbose\n", + " -t Trace\n"; + exit; +} + +open(my $fileh, "<", "$file"); + +if($showlimit) { + while(<$fileh>) { + if(/^LIMIT.*memlimit$/) { + print $_; + last; + } + } + close($fileh); + exit; +} + + +my $lnum=0; +while(<$fileh>) { + chomp $_; + $line = $_; + $lnum++; + if($line =~ /^LIMIT ([^ ]*):(\d*) (.*)/) { + # new memory limit test prefix + my $i = $3; + my ($source, $linenum) = ($1, $2); + if($trace && ($i =~ /([^ ]*) reached memlimit/)) { + print "LIMIT: $1 returned error at $source:$linenum\n"; + } + } + elsif($line =~ /^MEM ([^ ]*):(\d*) (.*)/) { + # generic match for the filename+linenumber + $source = $1; + $linenum = $2; + $function = $3; + + if($function =~ /free\((\(nil\)|0x([0-9a-f]*))/) { + $addr = $2; + if($1 eq "(nil)") { + ; # do nothing when free(NULL) + } + elsif(!exists $sizeataddr{$addr}) { + print "FREE ERROR: No memory allocated: $line\n"; + } + elsif(-1 == $sizeataddr{$addr}) { + print "FREE ERROR: Memory freed twice: $line\n"; + print "FREE ERROR: Previously freed at: ".$getmem{$addr}."\n"; + } + else { + $totalmem -= $sizeataddr{$addr}; + if($trace) { + print "FREE: malloc at ".$getmem{$addr}." is freed again at $source:$linenum\n"; + printf("FREE: %d bytes freed, left allocated: $totalmem bytes\n", $sizeataddr{$addr}); + } + + newtotal($totalmem); + $frees++; + + $sizeataddr{$addr}=-1; # set -1 to mark as freed + $getmem{$addr}="$source:$linenum"; + + } + } + elsif($function =~ /malloc\((\d*)\) = 0x([0-9a-f]*)/) { + $size = $1; + $addr = $2; + + if($sizeataddr{$addr}>0) { + # this means weeeeeirdo + print "Mixed debug compile ($source:$linenum at line $lnum), rebuild curl now\n"; + print "We think $sizeataddr{$addr} bytes are already allocated at that memory address: $addr!\n"; + } + + $sizeataddr{$addr}=$size; + $totalmem += $size; + $memsum += $size; + + if($trace) { + print "MALLOC: malloc($size) at $source:$linenum", + " makes totally $totalmem bytes\n"; + } + + newtotal($totalmem); + $mallocs++; + + $getmem{$addr}="$source:$linenum"; + } + elsif($function =~ /calloc\((\d*),(\d*)\) = 0x([0-9a-f]*)/) { + $size = $1*$2; + $addr = $3; + + $arg1 = $1; + $arg2 = $2; + + if($sizeataddr{$addr}>0) { + # this means weeeeeirdo + print "Mixed debug compile, rebuild curl now\n"; + } + + $sizeataddr{$addr}=$size; + $totalmem += $size; + $memsum += $size; + + if($trace) { + print "CALLOC: calloc($arg1,$arg2) at $source:$linenum", + " makes totally $totalmem bytes\n"; + } + + newtotal($totalmem); + $callocs++; + + $getmem{$addr}="$source:$linenum"; + } + elsif($function =~ /realloc\((\(nil\)|0x([0-9a-f]*)), (\d*)\) = 0x([0-9a-f]*)/) { + my ($oldaddr, $newsize, $newaddr) = ($2, $3, $4); + + $totalmem -= $sizeataddr{$oldaddr}; + if($trace) { + printf("REALLOC: %d less bytes and ", $sizeataddr{$oldaddr}); + } + $sizeataddr{$oldaddr}=0; + + $totalmem += $newsize; + $memsum += $size; + $sizeataddr{$newaddr}=$newsize; + + if($trace) { + printf("%d more bytes ($source:$linenum)\n", $newsize); + } + + newtotal($totalmem); + $reallocs++; + + $getmem{$oldaddr}=""; + $getmem{$newaddr}="$source:$linenum"; + } + elsif($function =~ /strdup\(0x([0-9a-f]*)\) \((\d*)\) = 0x([0-9a-f]*)/) { + # strdup(a5b50) (8) = df7c0 + + $dup = $1; + $size = $2; + $addr = $3; + $getmem{$addr}="$source:$linenum"; + $sizeataddr{$addr}=$size; + + $totalmem += $size; + $memsum += $size; + + if($trace) { + printf("STRDUP: $size bytes at %s, makes totally: %d bytes\n", + $getmem{$addr}, $totalmem); + } + + newtotal($totalmem); + $strdups++; + } + elsif($function =~ /wcsdup\(0x([0-9a-f]*)\) \((\d*)\) = 0x([0-9a-f]*)/) { + # wcsdup(a5b50) (8) = df7c0 + + $dup = $1; + $size = $2; + $addr = $3; + $getmem{$addr}="$source:$linenum"; + $sizeataddr{$addr}=$size; + + $totalmem += $size; + $memsum += $size; + + if($trace) { + printf("WCSDUP: $size bytes at %s, makes totally: %d bytes\n", + $getmem{$addr}, $totalmem); + } + + newtotal($totalmem); + $wcsdups++; + } + else { + print "Not recognized input line: $function\n"; + } + } + # FD url.c:1282 socket() = 5 + elsif($_ =~ /^FD ([^ ]*):(\d*) (.*)/) { + # generic match for the filename+linenumber + $source = $1; + $linenum = $2; + $function = $3; + + if($function =~ /socket\(\) = (\d*)/) { + $filedes{$1}=1; + $getfile{$1}="$source:$linenum"; + $openfile++; + $sockets++; # number of socket() calls + } + elsif($function =~ /socketpair\(\) = (\d*) (\d*)/) { + $filedes{$1}=1; + $getfile{$1}="$source:$linenum"; + $openfile++; + $filedes{$2}=1; + $getfile{$2}="$source:$linenum"; + $openfile++; + } + elsif($function =~ /accept\(\) = (\d*)/) { + $filedes{$1}=1; + $getfile{$1}="$source:$linenum"; + $openfile++; + } + elsif($function =~ /sclose\((\d*)\)/) { + if($filedes{$1} != 1) { + print "Close without open: $line\n"; + } + else { + $filedes{$1}=0; # closed now + $openfile--; + } + } + } + # FILE url.c:1282 fopen("blabla") = 0x5ddd + elsif($_ =~ /^FILE ([^ ]*):(\d*) (.*)/) { + # generic match for the filename+linenumber + $source = $1; + $linenum = $2; + $function = $3; + + if($function =~ /f[d]*open\(\"(.*)\",\"([^\"]*)\"\) = (\(nil\)|0x([0-9a-f]*))/) { + if($3 eq "(nil)") { + ; + } + else { + $fopen{$4}=1; + $fopenfile{$4}="$source:$linenum"; + $fopens++; + } + } + # fclose(0x1026c8) + elsif($function =~ /fclose\(0x([0-9a-f]*)\)/) { + if(!$fopen{$1}) { + print "fclose() without fopen(): $line\n"; + } + else { + $fopen{$1}=0; + $fopens--; + } + } + } + # GETNAME url.c:1901 getnameinfo() + elsif($_ =~ /^GETNAME ([^ ]*):(\d*) (.*)/) { + # not much to do + } + # SEND url.c:1901 send(83) = 83 + elsif($_ =~ /^SEND ([^ ]*):(\d*) (.*)/) { + $sends++; + } + # RECV url.c:1901 recv(102400) = 256 + elsif($_ =~ /^RECV ([^ ]*):(\d*) (.*)/) { + $recvs++; + } + + # ADDR url.c:1282 getaddrinfo() = 0x5ddd + elsif($_ =~ /^ADDR ([^ ]*):(\d*) (.*)/) { + # generic match for the filename+linenumber + $source = $1; + $linenum = $2; + $function = $3; + + if($function =~ /getaddrinfo\(\) = (\(nil\)|0x([0-9a-f]*))/) { + my $add = $2; + if($add eq "(nil)") { + ; + } + else { + $addrinfo{$add}=1; + $addrinfofile{$add}="$source:$linenum"; + $addrinfos++; + } + if($trace) { + printf("GETADDRINFO ($source:$linenum)\n"); + } + } + # fclose(0x1026c8) + elsif($function =~ /freeaddrinfo\(0x([0-9a-f]*)\)/) { + if(!$addrinfo{$1}) { + print "freeaddrinfo() without getaddrinfo(): $line\n"; + } + else { + $addrinfo{$1}=0; + $addrinfos--; + } + if($trace) { + printf("FREEADDRINFO ($source:$linenum)\n"); + } + } + + } + else { + print "Not recognized prefix line: $line\n"; + } +} +close($fileh); + +if($totalmem) { + print "Leak detected: memory still allocated: $totalmem bytes\n"; + + for(keys %sizeataddr) { + $addr = $_; + $size = $sizeataddr{$addr}; + if($size > 0) { + print "At $addr, there's $size bytes.\n"; + print " allocated by ".$getmem{$addr}."\n"; + } + } +} + +if($openfile) { + for(keys %filedes) { + if($filedes{$_} == 1) { + print "Open file descriptor created at ".$getfile{$_}."\n"; + } + } +} + +if($fopens) { + print "Open FILE handles left at:\n"; + for(keys %fopen) { + if($fopen{$_} == 1) { + print "fopen() called at ".$fopenfile{$_}."\n"; + } + } +} + +if($addrinfos) { + print "IPv6-style name resolve data left at:\n"; + for(keys %addrinfofile) { + if($addrinfo{$_} == 1) { + print "getaddrinfo() called at ".$addrinfofile{$_}."\n"; + } + } +} + +if($verbose) { + print "Mallocs: $mallocs\n", + "Reallocs: $reallocs\n", + "Callocs: $callocs\n", + "Strdups: $strdups\n", + "Wcsdups: $wcsdups\n", + "Frees: $frees\n", + "Sends: $sends\n", + "Recvs: $recvs\n", + "Sockets: $sockets\n", + "Allocations: ".($mallocs + $callocs + $reallocs + $strdups + $wcsdups)."\n", + "Operations: ".($mallocs + $callocs + $reallocs + $strdups + $wcsdups + $sends + $recvs + $sockets)."\n"; + + print "Maximum allocated: $maxmem\n"; + print "Total allocated: $memsum\n"; +} diff --git a/local-test-curl-full-01/afc-curl/tests/mk-bundle-hints.sh b/local-test-curl-full-01/afc-curl/tests/mk-bundle-hints.sh new file mode 100644 index 0000000000000000000000000000000000000000..67bf9361c02c0e951d2c9c5f6ffcd762db5b666c --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/mk-bundle-hints.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Viktor Szakats +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +detect_in_reused_sources=1 + +if [ "$detect_in_reused_sources" = '1' ]; then + # Make symlinks for all re-used sources + grep -E '^(lib|unit)[0-9]+_SOURCES = ' libtest/Makefile.inc unit/Makefile.inc \ + | sed -E 's@^([a-z]+)/[a-zA-Z.]+:(lib|unit)([0-9]+)_SOURCES = (lib|unit)([0-9]+).+@\1 \2 \3 \5@g' | \ + while read -r l; do + if [[ "${l}" =~ ([a-z]+)\ ([a-z]+)\ ([0-9]+)\ ([0-9]+) ]]; then + trg="${BASH_REMATCH[3]}" + src="${BASH_REMATCH[4]}" + if [ "${trg}" != "${src}" ]; then + dir="${BASH_REMATCH[1]}" + pfx="${BASH_REMATCH[2]}" + ln -s "${pfx}${src}.c" "${dir}/${pfx}${trg}.c" + fi + fi + done +fi + +# Look for symbols possibly re-used in multiple sources. +# +# Falsely picks ups symbols in re-used sources, but guarded for a single use. +# Misses shadowed variables. +# shellcheck disable=SC2046 +grep -E '^ *(static|struct) +' $(find libtest unit -maxdepth 1 -name 'lib*.c' -o -name 'unit*.c' -o -name 'mk-*.pl') \ + | grep -E '^(libtest|unit)/' \ + | grep -E '\.(c|pl):(static|struct)( +[a-zA-Z_* ]+)? +[a-zA-Z_][a-zA-Z0-9_]+ *' | sort -u \ + | grep -o -E '[a-zA-Z_][a-zA-Z0-9_]+ *[=;[({]' | tr -d '=;[({ ' \ + | grep -v -E '^(NULL$|sizeof$|CURLE_)' \ + | sort | uniq -c | sort -k 2 | grep -v -E '^ +1 ' \ + | awk '{print " \"" $2 "\","}' + +echo '---' + +# Extract list of macros that may be re-used by multiple tests. +# +# Picks up false-positive when the macro is defined to the same value everywhere. +# shellcheck disable=SC2046 +grep -E '^ *# *define +' $(find libtest unit -maxdepth 1 -name 'lib*.c' -o -name 'unit*.c' -o -name 'mk-*.pl') \ + | grep -E '^(libtest|unit)/' \ + | grep -o -E '.+\.(c|pl): *# *define +[A-Z_][A-Z0-9_]+' | sort -u \ + | grep -o -E '[A-Z_][A-Z0-9_]+' \ + | sort | uniq -c | sort -k 2 | grep -v -E '^ +1 ' \ + | awk '{print " \"" $2 "\","}' + +if [ "$detect_in_reused_sources" = '1' ]; then + # Delete symlinks for all re-used sources + find libtest unit -type l -delete +fi diff --git a/local-test-curl-full-01/afc-curl/tests/mk-bundle.pl b/local-test-curl-full-01/afc-curl/tests/mk-bundle.pl new file mode 100644 index 0000000000000000000000000000000000000000..5ed28a0807fd7b1f4d5ac750cbd92cb27659073e --- /dev/null +++ b/local-test-curl-full-01/afc-curl/tests/mk-bundle.pl @@ -0,0 +1,162 @@ +#!/usr/bin/env perl +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) Viktor Szakats +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +# SPDX-License-Identifier: curl +# +########################################################################### + +# Bundle up individual tests into a single binary. The resulting binary can run +# individual tests by passing their name (without '.c') as the first argument. +# +# Usage: mk-bundle.pl [] + +use strict; +use warnings; + +my $src_dir = @ARGV ? $ARGV[0] : "."; + +# Read list of tests +open my $fh, "<", "$src_dir/Makefile.inc" or die "Cannot open '$src_dir/Makefile.inc': $!"; + +print <
) { + chomp $line; + if($line =~ /([a-z0-9]+)_SOURCES\ =\ ([a-z0-9]+)\.c/) { + my $name = $1; + my $namu = uc($name); + my $src = "$2.c"; + + # Make common symbols unique across test sources + foreach my $symb ("test", @reused_symbols) { + print "#undef $symb\n"; + print "#define $symb ${symb}_$name\n"; + } + + print "#define $namu\n"; + print "#include \"$src\"\n"; + print "#undef $namu\n"; + + # Reset macros re-used by multiple tests + foreach my $undef ("test", @reused_macros) { + print "#undef $undef\n"; + } + + print "\n"; + + $tlist .= " {\"$name\", test_$name},\n"; + } +} + +close $fh; + +print <