Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/setup-os400.h | #ifndef HEADER_CURL_SETUP_OS400_H
#define HEADER_CURL_SETUP_OS400_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* 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;
/* System API wrapper prototypes & definitions to support ASCII parameters. */
#include <sys/socket.h>
#include <netdb.h>
#include <gskssl.h>
#include <qsoasync.h>
#include <gssapi.h>
extern int Curl_getaddrinfo_a(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct addrinfo **res);
#define getaddrinfo Curl_getaddrinfo_a
extern int Curl_getnameinfo_a(const struct sockaddr *sa,
curl_socklen_t salen,
char *nodename, curl_socklen_t nodenamelen,
char *servname, curl_socklen_t servnamelen,
int flags);
#define getnameinfo Curl_getnameinfo_a
/* GSKit wrappers. */
extern int Curl_gsk_environment_open(gsk_handle * my_env_handle);
#define gsk_environment_open Curl_gsk_environment_open
extern int Curl_gsk_secure_soc_open(gsk_handle my_env_handle,
gsk_handle * my_session_handle);
#define gsk_secure_soc_open Curl_gsk_secure_soc_open
extern int Curl_gsk_environment_close(gsk_handle * my_env_handle);
#define gsk_environment_close Curl_gsk_environment_close
extern int Curl_gsk_secure_soc_close(gsk_handle * my_session_handle);
#define gsk_secure_soc_close Curl_gsk_secure_soc_close
extern int Curl_gsk_environment_init(gsk_handle my_env_handle);
#define gsk_environment_init Curl_gsk_environment_init
extern int Curl_gsk_secure_soc_init(gsk_handle my_session_handle);
#define gsk_secure_soc_init Curl_gsk_secure_soc_init
extern int Curl_gsk_attribute_set_buffer_a(gsk_handle my_gsk_handle,
GSK_BUF_ID bufID,
const char *buffer,
int bufSize);
#define gsk_attribute_set_buffer Curl_gsk_attribute_set_buffer_a
extern int Curl_gsk_attribute_set_enum(gsk_handle my_gsk_handle,
GSK_ENUM_ID enumID,
GSK_ENUM_VALUE enumValue);
#define gsk_attribute_set_enum Curl_gsk_attribute_set_enum
extern int Curl_gsk_attribute_set_numeric_value(gsk_handle my_gsk_handle,
GSK_NUM_ID numID,
int numValue);
#define gsk_attribute_set_numeric_value Curl_gsk_attribute_set_numeric_value
extern int Curl_gsk_attribute_set_callback(gsk_handle my_gsk_handle,
GSK_CALLBACK_ID callBackID,
void *callBackAreaPtr);
#define gsk_attribute_set_callback Curl_gsk_attribute_set_callback
extern int Curl_gsk_attribute_get_buffer_a(gsk_handle my_gsk_handle,
GSK_BUF_ID bufID,
const char **buffer,
int *bufSize);
#define gsk_attribute_get_buffer Curl_gsk_attribute_get_buffer_a
extern int Curl_gsk_attribute_get_enum(gsk_handle my_gsk_handle,
GSK_ENUM_ID enumID,
GSK_ENUM_VALUE *enumValue);
#define gsk_attribute_get_enum Curl_gsk_attribute_get_enum
extern int Curl_gsk_attribute_get_numeric_value(gsk_handle my_gsk_handle,
GSK_NUM_ID numID,
int *numValue);
#define gsk_attribute_get_numeric_value Curl_gsk_attribute_get_numeric_value
extern int Curl_gsk_attribute_get_cert_info(gsk_handle my_gsk_handle,
GSK_CERT_ID certID,
const gsk_cert_data_elem **certDataElem,
int *certDataElementCount);
#define gsk_attribute_get_cert_info Curl_gsk_attribute_get_cert_info
extern int Curl_gsk_secure_soc_misc(gsk_handle my_session_handle,
GSK_MISC_ID miscID);
#define gsk_secure_soc_misc Curl_gsk_secure_soc_misc
extern int Curl_gsk_secure_soc_read(gsk_handle my_session_handle,
char *readBuffer,
int readBufSize, int *amtRead);
#define gsk_secure_soc_read Curl_gsk_secure_soc_read
extern int Curl_gsk_secure_soc_write(gsk_handle my_session_handle,
char *writeBuffer,
int writeBufSize, int *amtWritten);
#define gsk_secure_soc_write Curl_gsk_secure_soc_write
extern const char * Curl_gsk_strerror_a(int gsk_return_value);
#define gsk_strerror Curl_gsk_strerror_a
extern int Curl_gsk_secure_soc_startInit(gsk_handle my_session_handle,
int IOCompletionPort,
Qso_OverlappedIO_t * communicationsArea);
#define gsk_secure_soc_startInit Curl_gsk_secure_soc_startInit
/* 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,
struct sockaddr *dstaddr, int addrlen);
extern int Curl_os400_recvfrom(int sd, char *buffer, int buflen, int flags,
struct sockaddr *fromaddr, int *addrlen);
extern int Curl_os400_getpeername(int sd, struct sockaddr *addr, int *addrlen);
extern int Curl_os400_getsockname(int sd, struct sockaddr *addr, int *addrlen);
#define connect Curl_os400_connect
#define bind Curl_os400_bind
#define sendto Curl_os400_sendto
#define recvfrom Curl_os400_recvfrom
#define getpeername Curl_os400_getpeername
#define getsockname Curl_os400_getsockname
#ifdef HAVE_LIBZ
#define zlibVersion Curl_os400_zlibVersion
#define inflateInit_ Curl_os400_inflateInit_
#define inflateInit2_ Curl_os400_inflateInit2_
#define inflate Curl_os400_inflate
#define inflateEnd Curl_os400_inflateEnd
#endif
#endif /* HEADER_CURL_SETUP_OS400_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/hostip4.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
/***********************************************************************
* Only for plain IPv4 builds
**********************************************************************/
#ifdef CURLRES_IPV4 /* plain IPv4 code coming up */
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#ifdef HAVE_PROCESS_H
#include <process.h>
#endif
#include "urldata.h"
#include "sendf.h"
#include "hostip.h"
#include "hash.h"
#include "share.h"
#include "url.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/*
* Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've
* been set and returns TRUE if they are OK.
*/
bool Curl_ipvalid(struct Curl_easy *data, struct connectdata *conn)
{
(void)data;
if(conn->ip_version == CURL_IPRESOLVE_V6)
/* An IPv6 address was requested and we can't get/use one */
return FALSE;
return TRUE; /* OK, proceed */
}
#ifdef CURLRES_SYNCH
/*
* Curl_getaddrinfo() - the IPv4 synchronous version.
*
* The original code to this function was from the Dancer source code, written
* by Bjorn Reese, it has since been patched and modified considerably.
*
* gethostbyname_r() is the thread-safe version of the gethostbyname()
* function. When we build for plain IPv4, we attempt to use this
* function. There are _three_ different gethostbyname_r() versions, and we
* detect which one this platform supports in the configure script and set up
* the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or
* HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME
* has the corresponding rules. This is primarily on *nix. Note that some unix
* flavours have thread-safe versions of the plain gethostbyname() etc.
*
*/
struct Curl_addrinfo *Curl_getaddrinfo(struct Curl_easy *data,
const char *hostname,
int port,
int *waitp)
{
struct Curl_addrinfo *ai = NULL;
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)data;
#endif
*waitp = 0; /* synchronous response only */
ai = Curl_ipv4_resolve_r(hostname, port);
if(!ai)
infof(data, "Curl_ipv4_resolve_r failed for %s", hostname);
return ai;
}
#endif /* CURLRES_SYNCH */
#endif /* CURLRES_IPV4 */
#if defined(CURLRES_IPV4) && !defined(CURLRES_ARES)
/*
* Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function.
*
* This is used for both synchronous and asynchronous resolver builds,
* implying that only threadsafe code and function calls may be used.
*
*/
struct Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
int port)
{
#if !defined(HAVE_GETADDRINFO_THREADSAFE) && defined(HAVE_GETHOSTBYNAME_R_3)
int res;
#endif
struct Curl_addrinfo *ai = NULL;
struct hostent *h = NULL;
struct hostent *buf = NULL;
#if defined(HAVE_GETADDRINFO_THREADSAFE)
struct addrinfo hints;
char sbuf[12];
char *sbufptr = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
if(port) {
msnprintf(sbuf, sizeof(sbuf), "%d", port);
sbufptr = sbuf;
}
(void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai);
#elif defined(HAVE_GETHOSTBYNAME_R)
/*
* gethostbyname_r() is the preferred resolve function for many platforms.
* Since there are three different versions of it, the following code is
* somewhat #ifdef-ridden.
*/
int h_errnop;
buf = calloc(1, CURL_HOSTENT_SIZE);
if(!buf)
return NULL; /* major failure */
/*
* The clearing of the buffer is a workaround for a gethostbyname_r bug in
* qnx nto and it is also _required_ for some of these functions on some
* platforms.
*/
#if defined(HAVE_GETHOSTBYNAME_R_5)
/* Solaris, IRIX and more */
h = gethostbyname_r(hostname,
(struct hostent *)buf,
(char *)buf + sizeof(struct hostent),
CURL_HOSTENT_SIZE - sizeof(struct hostent),
&h_errnop);
/* If the buffer is too small, it returns NULL and sets errno to
* ERANGE. The errno is thread safe if this is compiled with
* -D_REENTRANT as then the 'errno' variable is a macro defined to get
* used properly for threads.
*/
if(h) {
;
}
else
#elif defined(HAVE_GETHOSTBYNAME_R_6)
/* Linux */
(void)gethostbyname_r(hostname,
(struct hostent *)buf,
(char *)buf + sizeof(struct hostent),
CURL_HOSTENT_SIZE - sizeof(struct hostent),
&h, /* DIFFERENCE */
&h_errnop);
/* Redhat 8, using glibc 2.2.93 changed the behavior. Now all of a
* sudden this function returns EAGAIN if the given buffer size is too
* small. Previous versions are known to return ERANGE for the same
* problem.
*
* This wouldn't be such a big problem if older versions wouldn't
* sometimes return EAGAIN on a common failure case. Alas, we can't
* assume that EAGAIN *or* ERANGE means ERANGE for any given version of
* glibc.
*
* For now, we do that and thus we may call the function repeatedly and
* fail for older glibc versions that return EAGAIN, until we run out of
* buffer size (step_size grows beyond CURL_HOSTENT_SIZE).
*
* If anyone has a better fix, please tell us!
*
* -------------------------------------------------------------------
*
* On October 23rd 2003, Dan C dug up more details on the mysteries of
* gethostbyname_r() in glibc:
*
* In glibc 2.2.5 the interface is different (this has also been
* discovered in glibc 2.1.1-6 as shipped by Redhat 6). What I can't
* explain, is that tests performed on glibc 2.2.4-34 and 2.2.4-32
* (shipped/upgraded by Redhat 7.2) don't show this behavior!
*
* In this "buggy" version, the return code is -1 on error and 'errno'
* is set to the ERANGE or EAGAIN code. Note that 'errno' is not a
* thread-safe variable.
*/
if(!h) /* failure */
#elif defined(HAVE_GETHOSTBYNAME_R_3)
/* AIX, Digital Unix/Tru64, HPUX 10, more? */
/* For AIX 4.3 or later, we don't use gethostbyname_r() at all, because of
* the plain fact that it does not return unique full buffers on each
* call, but instead several of the pointers in the hostent structs will
* point to the same actual data! This have the unfortunate down-side that
* our caching system breaks down horribly. Luckily for us though, AIX 4.3
* and more recent versions have a "completely thread-safe"[*] libc where
* all the data is stored in thread-specific memory areas making calls to
* the plain old gethostbyname() work fine even for multi-threaded
* programs.
*
* This AIX 4.3 or later detection is all made in the configure script.
*
* Troels Walsted Hansen helped us work this out on March 3rd, 2003.
*
* [*] = much later we've found out that it isn't at all "completely
* thread-safe", but at least the gethostbyname() function is.
*/
if(CURL_HOSTENT_SIZE >=
(sizeof(struct hostent) + sizeof(struct hostent_data))) {
/* August 22nd, 2000: Albert Chin-A-Young brought an updated version
* that should work! September 20: Richard Prescott worked on the buffer
* size dilemma.
*/
res = gethostbyname_r(hostname,
(struct hostent *)buf,
(struct hostent_data *)((char *)buf +
sizeof(struct hostent)));
h_errnop = SOCKERRNO; /* we don't deal with this, but set it anyway */
}
else
res = -1; /* failure, too smallish buffer size */
if(!res) { /* success */
h = buf; /* result expected in h */
/* This is the worst kind of the different gethostbyname_r() interfaces.
* Since we don't know how big buffer this particular lookup required,
* we can't realloc down the huge alloc without doing closer analysis of
* the returned data. Thus, we always use CURL_HOSTENT_SIZE for every
* name lookup. Fixing this would require an extra malloc() and then
* calling Curl_addrinfo_copy() that subsequent realloc()s down the new
* memory area to the actually used amount.
*/
}
else
#endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */
{
h = NULL; /* set return code to NULL */
free(buf);
}
#else /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
/*
* Here is code for platforms that don't have a thread safe
* getaddrinfo() nor gethostbyname_r() function or for which
* gethostbyname() is the preferred one.
*/
h = gethostbyname((void *)hostname);
#endif /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */
if(h) {
ai = Curl_he2ai(h, port);
if(buf) /* used a *_r() function */
free(buf);
}
return ai;
}
#endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/memdebug.h | #ifndef HEADER_CURL_MEMDEBUG_H
#define HEADER_CURL_MEMDEBUG_H
#ifdef CURLDEBUG
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* CAUTION: this header is designed to work when included by the app-side
* as well as the library. Do not mix with library internals!
*/
#define CURL_MT_LOGFNAME_BUFSIZE 512
extern FILE *curl_dbg_logfile;
/* memory functions */
CURL_EXTERN void *curl_dbg_malloc(size_t size, int line, const char *source);
CURL_EXTERN void *curl_dbg_calloc(size_t elements, size_t size, int line,
const char *source);
CURL_EXTERN void *curl_dbg_realloc(void *ptr, size_t size, int line,
const char *source);
CURL_EXTERN void curl_dbg_free(void *ptr, int line, const char *source);
CURL_EXTERN char *curl_dbg_strdup(const char *str, int line, const char *src);
#if defined(WIN32) && defined(UNICODE)
CURL_EXTERN wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line,
const char *source);
#endif
CURL_EXTERN void curl_dbg_memdebug(const char *logname);
CURL_EXTERN void curl_dbg_memlimit(long limit);
CURL_EXTERN void curl_dbg_log(const char *format, ...);
/* file descriptor manipulators */
CURL_EXTERN curl_socket_t curl_dbg_socket(int domain, int type, int protocol,
int line, const char *source);
CURL_EXTERN void curl_dbg_mark_sclose(curl_socket_t sockfd,
int line, const char *source);
CURL_EXTERN int curl_dbg_sclose(curl_socket_t sockfd,
int line, const char *source);
CURL_EXTERN curl_socket_t curl_dbg_accept(curl_socket_t s, void *a, void *alen,
int line, const char *source);
#ifdef HAVE_SOCKETPAIR
CURL_EXTERN int curl_dbg_socketpair(int domain, int type, int protocol,
curl_socket_t socket_vector[2],
int line, const char *source);
#endif
/* send/receive sockets */
CURL_EXTERN SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd,
SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf,
SEND_TYPE_ARG3 len,
SEND_TYPE_ARG4 flags, int line,
const char *source);
CURL_EXTERN RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd,
RECV_TYPE_ARG2 buf,
RECV_TYPE_ARG3 len,
RECV_TYPE_ARG4 flags, int line,
const char *source);
/* FILE functions */
CURL_EXTERN FILE *curl_dbg_fopen(const char *file, const char *mode, int line,
const char *source);
CURL_EXTERN FILE *curl_dbg_fdopen(int filedes, const char *mode,
int line, const char *source);
CURL_EXTERN int curl_dbg_fclose(FILE *file, int line, const char *source);
#ifndef MEMDEBUG_NODEFINES
/* Set this symbol on the command-line, recompile all lib-sources */
#undef strdup
#define strdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__)
#define malloc(size) curl_dbg_malloc(size, __LINE__, __FILE__)
#define calloc(nbelem,size) curl_dbg_calloc(nbelem, size, __LINE__, __FILE__)
#define realloc(ptr,size) curl_dbg_realloc(ptr, size, __LINE__, __FILE__)
#define free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__)
#define send(a,b,c,d) curl_dbg_send(a,b,c,d, __LINE__, __FILE__)
#define recv(a,b,c,d) curl_dbg_recv(a,b,c,d, __LINE__, __FILE__)
#ifdef WIN32
# ifdef UNICODE
# undef wcsdup
# define wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
# undef _wcsdup
# define _wcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
# undef _tcsdup
# define _tcsdup(ptr) curl_dbg_wcsdup(ptr, __LINE__, __FILE__)
# else
# undef _tcsdup
# define _tcsdup(ptr) curl_dbg_strdup(ptr, __LINE__, __FILE__)
# endif
#endif
#undef socket
#define socket(domain,type,protocol)\
curl_dbg_socket(domain, type, protocol, __LINE__, __FILE__)
#undef accept /* for those with accept as a macro */
#define accept(sock,addr,len)\
curl_dbg_accept(sock, addr, len, __LINE__, __FILE__)
#ifdef HAVE_SOCKETPAIR
#define socketpair(domain,type,protocol,socket_vector)\
curl_dbg_socketpair(domain, type, protocol, socket_vector, __LINE__, __FILE__)
#endif
#ifdef HAVE_GETADDRINFO
#if defined(getaddrinfo) && defined(__osf__)
/* OSF/1 and Tru64 have getaddrinfo as a define already, so we cannot define
our macro as for other platforms. Instead, we redefine the new name they
define getaddrinfo to become! */
#define ogetaddrinfo(host,serv,hint,res) \
curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
#else
#undef getaddrinfo
#define getaddrinfo(host,serv,hint,res) \
curl_dbg_getaddrinfo(host, serv, hint, res, __LINE__, __FILE__)
#endif
#endif /* HAVE_GETADDRINFO */
#ifdef HAVE_FREEADDRINFO
#undef freeaddrinfo
#define freeaddrinfo(data) \
curl_dbg_freeaddrinfo(data, __LINE__, __FILE__)
#endif /* HAVE_FREEADDRINFO */
/* sclose is probably already defined, redefine it! */
#undef sclose
#define sclose(sockfd) curl_dbg_sclose(sockfd,__LINE__,__FILE__)
#define fake_sclose(sockfd) curl_dbg_mark_sclose(sockfd,__LINE__,__FILE__)
#undef fopen
#define fopen(file,mode) curl_dbg_fopen(file,mode,__LINE__,__FILE__)
#undef fdopen
#define fdopen(file,mode) curl_dbg_fdopen(file,mode,__LINE__,__FILE__)
#define fclose(file) curl_dbg_fclose(file,__LINE__,__FILE__)
#endif /* MEMDEBUG_NODEFINES */
#endif /* CURLDEBUG */
/*
** Following section applies even when CURLDEBUG is not defined.
*/
#ifndef fake_sclose
#define fake_sclose(x) Curl_nop_stmt
#endif
/*
* Curl_safefree defined as a macro to allow MemoryTracking feature
* to log free() calls at same location where Curl_safefree is used.
* This macro also assigns NULL to given pointer when free'd.
*/
#define Curl_safefree(ptr) \
do { free((ptr)); (ptr) = NULL;} while(0)
#endif /* HEADER_CURL_MEMDEBUG_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strtoofft.h | #ifndef HEADER_CURL_STRTOOFFT_H
#define HEADER_CURL_STRTOOFFT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
/*
* Determine which string to integral data type conversion function we use
* to implement string conversion to our curl_off_t integral data type.
*
* Notice that curl_off_t might be 64 or 32 bit wide, and that it might use
* an underlying data type which might be 'long', 'int64_t', 'long long' or
* '__int64' and more remotely other data types.
*
* On systems where the size of curl_off_t is greater than the size of 'long'
* the conversion function to use is strtoll() if it is available, otherwise,
* we emulate its functionality with our own clone.
*
* On systems where the size of curl_off_t is smaller or equal than the size
* of 'long' the conversion function to use is strtol().
*/
typedef enum {
CURL_OFFT_OK, /* parsed fine */
CURL_OFFT_FLOW, /* over or underflow */
CURL_OFFT_INVAL /* nothing was parsed */
} CURLofft;
CURLofft curlx_strtoofft(const char *str, char **endp, int base,
curl_off_t *num);
#endif /* HEADER_CURL_STRTOOFFT_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/inet_pton.h | #ifndef HEADER_CURL_INET_PTON_H
#define HEADER_CURL_INET_PTON_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
int Curl_inet_pton(int, const char *, void *);
#ifdef HAVE_INET_PTON
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#elif defined(HAVE_WS2TCPIP_H)
/* inet_pton() exists in Vista or later */
#include <ws2tcpip.h>
#endif
#define Curl_inet_pton(x,y,z) inet_pton(x,y,z)
#endif
#endif /* HEADER_CURL_INET_PTON_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/sha256.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2017, Florin Petriuc, <[email protected]>
* Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_CRYPTO_AUTH
#include "warnless.h"
#include "curl_sha256.h"
#include "curl_hmac.h"
#ifdef USE_WOLFSSL
#include <wolfssl/options.h>
#ifndef NO_SHA256
#define USE_OPENSSL_SHA256
#endif
#endif
#if defined(USE_OPENSSL)
#include <openssl/opensslv.h>
#if (OPENSSL_VERSION_NUMBER >= 0x0090700fL)
#define USE_OPENSSL_SHA256
#endif
#endif /* USE_OPENSSL */
#ifdef USE_MBEDTLS
#include <mbedtls/version.h>
#if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \
(MBEDTLS_VERSION_NUMBER < 0x03000000)
#define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS
#endif
#endif /* USE_MBEDTLS */
/* 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)
/* When OpenSSL is available we use the SHA256-function from OpenSSL */
#include <openssl/evp.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
struct sha256_ctx {
EVP_MD_CTX *openssl_ctx;
};
typedef struct sha256_ctx my_sha256_ctx;
static void my_sha256_init(my_sha256_ctx *ctx)
{
ctx->openssl_ctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(ctx->openssl_ctx, EVP_sha256(), NULL);
}
static void my_sha256_update(my_sha256_ctx *ctx,
const unsigned char *data,
unsigned int length)
{
EVP_DigestUpdate(ctx->openssl_ctx, data, length);
}
static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx)
{
EVP_DigestFinal_ex(ctx->openssl_ctx, digest, NULL);
EVP_MD_CTX_destroy(ctx->openssl_ctx);
}
#elif defined(USE_GNUTLS)
#include <nettle/sha.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
typedef struct sha256_ctx my_sha256_ctx;
static void my_sha256_init(my_sha256_ctx *ctx)
{
sha256_init(ctx);
}
static void my_sha256_update(my_sha256_ctx *ctx,
const unsigned char *data,
unsigned int length)
{
sha256_update(ctx, length, data);
}
static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx)
{
sha256_digest(ctx, SHA256_DIGEST_SIZE, digest);
}
#elif defined(USE_MBEDTLS)
#include <mbedtls/sha256.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
typedef mbedtls_sha256_context my_sha256_ctx;
static void my_sha256_init(my_sha256_ctx *ctx)
{
#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS)
(void) mbedtls_sha256_starts(ctx, 0);
#else
(void) mbedtls_sha256_starts_ret(ctx, 0);
#endif
}
static void my_sha256_update(my_sha256_ctx *ctx,
const unsigned char *data,
unsigned int length)
{
#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS)
(void) mbedtls_sha256_update(ctx, data, length);
#else
(void) mbedtls_sha256_update_ret(ctx, data, length);
#endif
}
static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx)
{
#if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS)
(void) mbedtls_sha256_finish(ctx, digest);
#else
(void) mbedtls_sha256_finish_ret(ctx, digest);
#endif
}
#elif (defined(__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 <CommonCrypto/CommonDigest.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
typedef CC_SHA256_CTX my_sha256_ctx;
static void my_sha256_init(my_sha256_ctx *ctx)
{
(void) CC_SHA256_Init(ctx);
}
static void my_sha256_update(my_sha256_ctx *ctx,
const unsigned char *data,
unsigned int length)
{
(void) CC_SHA256_Update(ctx, data, length);
}
static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx)
{
(void) CC_SHA256_Final(digest, ctx);
}
#elif defined(USE_WIN32_CRYPTO)
#include <wincrypt.h>
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 void my_sha256_init(my_sha256_ctx *ctx)
{
if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_AES,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
CryptCreateHash(ctx->hCryptProv, CALG_SHA_256, 0, 0, &ctx->hHash);
}
}
static void my_sha256_update(my_sha256_ctx *ctx,
const unsigned char *data,
unsigned int length)
{
CryptHashData(ctx->hHash, (unsigned char *) data, length, 0);
}
static void my_sha256_final(unsigned char *digest, my_sha256_ctx *ctx)
{
unsigned long length = 0;
CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0);
if(length == SHA256_DIGEST_LENGTH)
CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0);
if(ctx->hHash)
CryptDestroyHash(ctx->hHash);
if(ctx->hCryptProv)
CryptReleaseContext(ctx->hCryptProv, 0);
}
#else
/* When no other crypto library is available we use this code segment */
/* This is based on SHA256 implementation in LibTomCrypt that was released into
* public domain by Tom St Denis. */
#define WPA_GET_BE32(a) ((((unsigned long)(a)[0]) << 24) | \
(((unsigned long)(a)[1]) << 16) | \
(((unsigned long)(a)[2]) << 8) | \
((unsigned long)(a)[3]))
#define WPA_PUT_BE32(a, val) \
do { \
(a)[0] = (unsigned char)((((unsigned long) (val)) >> 24) & 0xff); \
(a)[1] = (unsigned char)((((unsigned long) (val)) >> 16) & 0xff); \
(a)[2] = (unsigned char)((((unsigned long) (val)) >> 8) & 0xff); \
(a)[3] = (unsigned char)(((unsigned long) (val)) & 0xff); \
} while(0)
#ifdef HAVE_LONGLONG
#define WPA_PUT_BE64(a, val) \
do { \
(a)[0] = (unsigned char)(((unsigned long long)(val)) >> 56); \
(a)[1] = (unsigned char)(((unsigned long long)(val)) >> 48); \
(a)[2] = (unsigned char)(((unsigned long long)(val)) >> 40); \
(a)[3] = (unsigned char)(((unsigned long long)(val)) >> 32); \
(a)[4] = (unsigned char)(((unsigned long long)(val)) >> 24); \
(a)[5] = (unsigned char)(((unsigned long long)(val)) >> 16); \
(a)[6] = (unsigned char)(((unsigned long long)(val)) >> 8); \
(a)[7] = (unsigned char)(((unsigned long long)(val)) & 0xff); \
} while(0)
#else
#define WPA_PUT_BE64(a, val) \
do { \
(a)[0] = (unsigned char)(((unsigned __int64)(val)) >> 56); \
(a)[1] = (unsigned char)(((unsigned __int64)(val)) >> 48); \
(a)[2] = (unsigned char)(((unsigned __int64)(val)) >> 40); \
(a)[3] = (unsigned char)(((unsigned __int64)(val)) >> 32); \
(a)[4] = (unsigned char)(((unsigned __int64)(val)) >> 24); \
(a)[5] = (unsigned char)(((unsigned __int64)(val)) >> 16); \
(a)[6] = (unsigned char)(((unsigned __int64)(val)) >> 8); \
(a)[7] = (unsigned char)(((unsigned __int64)(val)) & 0xff); \
} while(0)
#endif
struct sha256_state {
#ifdef HAVE_LONGLONG
unsigned long long length;
#else
unsigned __int64 length;
#endif
unsigned long state[8], curlen;
unsigned char buf[64];
};
typedef struct sha256_state my_sha256_ctx;
/* The K array */
static const unsigned long K[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
/* Various logical functions */
#define RORc(x, y) \
(((((unsigned long)(x) & 0xFFFFFFFFUL) >> (unsigned long)((y) & 31)) | \
((unsigned long)(x) << (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL)
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) RORc((x), (n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))
/* Compress 512-bits */
static int sha256_compress(struct sha256_state *md,
unsigned char *buf)
{
unsigned long S[8], W[64];
int i;
/* Copy state into S */
for(i = 0; i < 8; i++) {
S[i] = md->state[i];
}
/* copy the state into 512-bits into W[0..15] */
for(i = 0; i < 16; i++)
W[i] = WPA_GET_BE32(buf + (4 * i));
/* fill W[16..63] */
for(i = 16; i < 64; i++) {
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) +
W[i - 16];
}
/* Compress */
#define RND(a,b,c,d,e,f,g,h,i) \
do { \
unsigned long t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
unsigned long t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1; \
} while(0)
for(i = 0; i < 64; ++i) {
unsigned long t;
RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i);
t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
}
/* Feedback */
for(i = 0; i < 8; i++) {
md->state[i] = md->state[i] + S[i];
}
return 0;
}
/* Initialize the hash state */
static void my_sha256_init(struct sha256_state *md)
{
md->curlen = 0;
md->length = 0;
md->state[0] = 0x6A09E667UL;
md->state[1] = 0xBB67AE85UL;
md->state[2] = 0x3C6EF372UL;
md->state[3] = 0xA54FF53AUL;
md->state[4] = 0x510E527FUL;
md->state[5] = 0x9B05688CUL;
md->state[6] = 0x1F83D9ABUL;
md->state[7] = 0x5BE0CD19UL;
}
/*
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
static int my_sha256_update(struct sha256_state *md,
const unsigned char *in,
unsigned long inlen)
{
unsigned long n;
#define block_size 64
if(md->curlen > sizeof(md->buf))
return -1;
while(inlen > 0) {
if(md->curlen == 0 && inlen >= block_size) {
if(sha256_compress(md, (unsigned char *)in) < 0)
return -1;
md->length += block_size * 8;
in += block_size;
inlen -= block_size;
}
else {
n = CURLMIN(inlen, (block_size - md->curlen));
memcpy(md->buf + md->curlen, in, n);
md->curlen += n;
in += n;
inlen -= n;
if(md->curlen == block_size) {
if(sha256_compress(md, md->buf) < 0)
return -1;
md->length += 8 * block_size;
md->curlen = 0;
}
}
}
return 0;
}
/*
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (32 bytes)
@return CRYPT_OK if successful
*/
static int my_sha256_final(unsigned char *out,
struct sha256_state *md)
{
int i;
if(md->curlen >= sizeof(md->buf))
return -1;
/* Increase the length of the message */
md->length += md->curlen * 8;
/* Append the '1' bit */
md->buf[md->curlen++] = (unsigned char)0x80;
/* If the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if(md->curlen > 56) {
while(md->curlen < 64) {
md->buf[md->curlen++] = (unsigned char)0;
}
sha256_compress(md, md->buf);
md->curlen = 0;
}
/* Pad up to 56 bytes of zeroes */
while(md->curlen < 56) {
md->buf[md->curlen++] = (unsigned char)0;
}
/* Store length */
WPA_PUT_BE64(md->buf + 56, md->length);
sha256_compress(md, md->buf);
/* Copy output */
for(i = 0; i < 8; i++)
WPA_PUT_BE32(out + (4 * i), md->state[i]);
return 0;
}
#endif /* CRYPTO LIBS */
/*
* Curl_sha256it()
*
* Generates a SHA256 hash for the given input data.
*
* Parameters:
*
* output [in/out] - The output buffer.
* input [in] - The input data.
* length [in] - The input length.
*/
void Curl_sha256it(unsigned char *output, const unsigned char *input,
const size_t length)
{
my_sha256_ctx ctx;
my_sha256_init(&ctx);
my_sha256_update(&ctx, input, curlx_uztoui(length));
my_sha256_final(output, &ctx);
}
const struct HMAC_params Curl_HMAC_SHA256[] = {
{
/* Hash initialization function. */
CURLX_FUNCTION_CAST(HMAC_hinit_func, my_sha256_init),
/* Hash update function. */
CURLX_FUNCTION_CAST(HMAC_hupdate_func, my_sha256_update),
/* Hash computation end function. */
CURLX_FUNCTION_CAST(HMAC_hfinal_func, my_sha256_final),
/* Size of hash context structure. */
sizeof(my_sha256_ctx),
/* Maximum key length. */
64,
/* Result size. */
32
}
};
#endif /* CURL_DISABLE_CRYPTO_AUTH */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_ctype.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DOES_CONVERSIONS
#undef _U
#define _U (1<<0) /* upper case */
#undef _L
#define _L (1<<1) /* lower case */
#undef _N
#define _N (1<<2) /* decimal numerical digit */
#undef _S
#define _S (1<<3) /* space */
#undef _P
#define _P (1<<4) /* punctuation */
#undef _C
#define _C (1<<5) /* control */
#undef _X
#define _X (1<<6) /* hexadecimal letter */
#undef _B
#define _B (1<<7) /* blank */
static const unsigned char ascii[128] = {
_C, _C, _C, _C, _C, _C, _C, _C,
_C, _C|_S, _C|_S, _C|_S, _C|_S, _C|_S, _C, _C,
_C, _C, _C, _C, _C, _C, _C, _C,
_C, _C, _C, _C, _C, _C, _C, _C,
_S|_B, _P, _P, _P, _P, _P, _P, _P,
_P, _P, _P, _P, _P, _P, _P, _P,
_N, _N, _N, _N, _N, _N, _N, _N,
_N, _N, _P, _P, _P, _P, _P, _P,
_P, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U,
_U, _U, _U, _U, _U, _U, _U, _U,
_U, _U, _U, _U, _U, _U, _U, _U,
_U, _U, _U, _P, _P, _P, _P, _P,
_P, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L,
_L, _L, _L, _L, _L, _L, _L, _L,
_L, _L, _L, _L, _L, _L, _L, _L,
_L, _L, _L, _P, _P, _P, _P, _C
};
int Curl_isspace(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & _S);
}
int Curl_isdigit(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & _N);
}
int Curl_isalnum(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_N|_U|_L));
}
int Curl_isxdigit(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_N|_X));
}
int Curl_isgraph(int c)
{
if((c < 0) || (c >= 0x80) || (c == ' '))
return FALSE;
return (ascii[c] & (_N|_X|_U|_L|_P|_S));
}
int Curl_isprint(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_N|_X|_U|_L|_P|_S));
}
int Curl_isalpha(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_U|_L));
}
int Curl_isupper(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_U));
}
int Curl_islower(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_L));
}
int Curl_iscntrl(int c)
{
if((c < 0) || (c >= 0x80))
return FALSE;
return (ascii[c] & (_C));
}
#endif /* !CURL_DOES_CONVERSIONS */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strtok.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef HAVE_STRTOK_R
#include <stddef.h>
#include "strtok.h"
char *
Curl_strtok_r(char *ptr, const char *sep, char **end)
{
if(!ptr)
/* we got NULL input so then we get our last position instead */
ptr = *end;
/* pass all letters that are including in the separator string */
while(*ptr && strchr(sep, *ptr))
++ptr;
if(*ptr) {
/* so this is where the next piece of string starts */
char *start = ptr;
/* set the end pointer to the first byte after the start */
*end = start + 1;
/* scan through the string to find where it ends, it ends on a
null byte or a character that exists in the separator string */
while(**end && !strchr(sep, **end))
++*end;
if(**end) {
/* the end is not a null byte */
**end = '\0'; /* null-terminate it! */
++*end; /* advance the last pointer to beyond the null byte */
}
return start; /* return the position where the string starts */
}
/* we ended up on a null byte, there are no more strings to find! */
return NULL;
}
#endif /* this was only compiled if strtok_r wasn't present */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/altsvc.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* The Alt-Svc: header is defined in RFC 7838:
* https://tools.ietf.org/html/rfc7838
*/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
#include <curl/curl.h>
#include "urldata.h"
#include "altsvc.h"
#include "curl_get_line.h"
#include "strcase.h"
#include "parsedate.h"
#include "sendf.h"
#include "warnless.h"
#include "rand.h"
#include "rename.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#define MAX_ALTSVC_LINE 4095
#define MAX_ALTSVC_DATELENSTR "64"
#define MAX_ALTSVC_DATELEN 64
#define MAX_ALTSVC_HOSTLENSTR "512"
#define MAX_ALTSVC_HOSTLEN 512
#define MAX_ALTSVC_ALPNLENSTR "10"
#define MAX_ALTSVC_ALPNLEN 10
#if defined(USE_QUICHE) && !defined(UNITTESTS)
#define H3VERSION "h3-29"
#elif defined(USE_NGTCP2) && !defined(UNITTESTS)
#define H3VERSION "h3-29"
#else
#define H3VERSION "h3"
#endif
static enum alpnid alpn2alpnid(char *name)
{
if(strcasecompare(name, "h1"))
return ALPN_h1;
if(strcasecompare(name, "h2"))
return ALPN_h2;
if(strcasecompare(name, H3VERSION))
return ALPN_h3;
return ALPN_none; /* unknown, probably rubbish input */
}
/* Given the ALPN ID, return the name */
const char *Curl_alpnid2str(enum alpnid id)
{
switch(id) {
case ALPN_h1:
return "h1";
case ALPN_h2:
return "h2";
case ALPN_h3:
return H3VERSION;
default:
return ""; /* bad */
}
}
static void altsvc_free(struct altsvc *as)
{
free(as->src.host);
free(as->dst.host);
free(as);
}
static struct altsvc *altsvc_createid(const char *srchost,
const char *dsthost,
enum alpnid srcalpnid,
enum alpnid dstalpnid,
unsigned int srcport,
unsigned int dstport)
{
struct altsvc *as = calloc(sizeof(struct altsvc), 1);
if(!as)
return NULL;
as->src.host = strdup(srchost);
if(!as->src.host)
goto error;
as->dst.host = strdup(dsthost);
if(!as->dst.host)
goto error;
as->src.alpnid = srcalpnid;
as->dst.alpnid = dstalpnid;
as->src.port = curlx_ultous(srcport);
as->dst.port = curlx_ultous(dstport);
return as;
error:
altsvc_free(as);
return NULL;
}
static struct altsvc *altsvc_create(char *srchost,
char *dsthost,
char *srcalpn,
char *dstalpn,
unsigned int srcport,
unsigned int dstport)
{
enum alpnid dstalpnid = alpn2alpnid(dstalpn);
enum alpnid srcalpnid = alpn2alpnid(srcalpn);
if(!srcalpnid || !dstalpnid)
return NULL;
return altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid,
srcport, dstport);
}
/* only returns SERIOUS errors */
static CURLcode altsvc_add(struct altsvcinfo *asi, char *line)
{
/* Example line:
h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
*/
char srchost[MAX_ALTSVC_HOSTLEN + 1];
char dsthost[MAX_ALTSVC_HOSTLEN + 1];
char srcalpn[MAX_ALTSVC_ALPNLEN + 1];
char dstalpn[MAX_ALTSVC_ALPNLEN + 1];
char date[MAX_ALTSVC_DATELEN + 1];
unsigned int srcport;
unsigned int dstport;
unsigned int prio;
unsigned int persist;
int rc;
rc = sscanf(line,
"%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
"%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
"\"%" MAX_ALTSVC_DATELENSTR "[^\"]\" %u %u",
srcalpn, srchost, &srcport,
dstalpn, dsthost, &dstport,
date, &persist, &prio);
if(9 == rc) {
struct altsvc *as;
time_t expires = Curl_getdate_capped(date);
as = altsvc_create(srchost, dsthost, srcalpn, dstalpn, srcport, dstport);
if(as) {
as->expires = expires;
as->prio = prio;
as->persist = persist ? 1 : 0;
Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
}
}
return CURLE_OK;
}
/*
* Load alt-svc entries from the given file. The text based line-oriented file
* format is documented here:
* https://github.com/curl/curl/wiki/QUIC-implementation
*
* This function only returns error on major problems that prevents alt-svc
* handling to work completely. It will ignore individual syntactical errors
* etc.
*/
static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
{
CURLcode result = CURLE_OK;
char *line = NULL;
FILE *fp;
/* we need a private copy of the file name so that the altsvc cache file
name survives an easy handle reset */
free(asi->filename);
asi->filename = strdup(file);
if(!asi->filename)
return CURLE_OUT_OF_MEMORY;
fp = fopen(file, FOPEN_READTEXT);
if(fp) {
line = malloc(MAX_ALTSVC_LINE);
if(!line)
goto fail;
while(Curl_get_line(line, MAX_ALTSVC_LINE, fp)) {
char *lineptr = line;
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
if(*lineptr == '#')
/* skip commented lines */
continue;
altsvc_add(asi, lineptr);
}
free(line); /* free the line buffer */
fclose(fp);
}
return result;
fail:
Curl_safefree(asi->filename);
free(line);
fclose(fp);
return CURLE_OUT_OF_MEMORY;
}
/*
* Write this single altsvc entry to a single output line
*/
static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
{
struct tm stamp;
CURLcode result = Curl_gmtime(as->expires, &stamp);
if(result)
return result;
fprintf(fp,
"%s %s %u "
"%s %s %u "
"\"%d%02d%02d "
"%02d:%02d:%02d\" "
"%u %d\n",
Curl_alpnid2str(as->src.alpnid), as->src.host, as->src.port,
Curl_alpnid2str(as->dst.alpnid), as->dst.host, as->dst.port,
stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
as->persist, as->prio);
return CURLE_OK;
}
/* ---- library-wide functions below ---- */
/*
* Curl_altsvc_init() creates a new altsvc cache.
* It returns the new instance or NULL if something goes wrong.
*/
struct altsvcinfo *Curl_altsvc_init(void)
{
struct altsvcinfo *asi = calloc(sizeof(struct altsvcinfo), 1);
if(!asi)
return NULL;
Curl_llist_init(&asi->list, NULL);
/* set default behavior */
asi->flags = CURLALTSVC_H1
#ifdef USE_NGHTTP2
| CURLALTSVC_H2
#endif
#ifdef ENABLE_QUIC
| CURLALTSVC_H3
#endif
;
return asi;
}
/*
* Curl_altsvc_load() loads alt-svc from file.
*/
CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
{
CURLcode result;
DEBUGASSERT(asi);
result = altsvc_load(asi, file);
return result;
}
/*
* Curl_altsvc_ctrl() passes on the external bitmask.
*/
CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl)
{
DEBUGASSERT(asi);
if(!ctrl)
/* unexpected */
return CURLE_BAD_FUNCTION_ARGUMENT;
asi->flags = ctrl;
return CURLE_OK;
}
/*
* Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
* resources.
*/
void Curl_altsvc_cleanup(struct altsvcinfo **altsvcp)
{
struct Curl_llist_element *e;
struct Curl_llist_element *n;
if(*altsvcp) {
struct altsvcinfo *altsvc = *altsvcp;
for(e = altsvc->list.head; e; e = n) {
struct altsvc *as = e->ptr;
n = e->next;
altsvc_free(as);
}
free(altsvc->filename);
free(altsvc);
*altsvcp = NULL; /* clear the pointer */
}
}
/*
* Curl_altsvc_save() writes the altsvc cache to a file.
*/
CURLcode Curl_altsvc_save(struct Curl_easy *data,
struct altsvcinfo *altsvc, const char *file)
{
struct Curl_llist_element *e;
struct Curl_llist_element *n;
CURLcode result = CURLE_OK;
FILE *out;
char *tempstore;
unsigned char randsuffix[9];
if(!altsvc)
/* no cache activated */
return CURLE_OK;
/* if not new name is given, use the one we stored from the load */
if(!file && altsvc->filename)
file = altsvc->filename;
if((altsvc->flags & CURLALTSVC_READONLYFILE) || !file || !file[0])
/* marked as read-only, no file or zero length file name */
return CURLE_OK;
if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix)))
return CURLE_FAILED_INIT;
tempstore = aprintf("%s.%s.tmp", file, randsuffix);
if(!tempstore)
return CURLE_OUT_OF_MEMORY;
out = fopen(tempstore, FOPEN_WRITETEXT);
if(!out)
result = CURLE_WRITE_ERROR;
else {
fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n"
"# This file was generated by libcurl! Edit at your own risk.\n",
out);
for(e = altsvc->list.head; e; e = n) {
struct altsvc *as = e->ptr;
n = e->next;
result = altsvc_out(as, out);
if(result)
break;
}
fclose(out);
if(!result && Curl_rename(tempstore, file))
result = CURLE_WRITE_ERROR;
if(result)
unlink(tempstore);
}
free(tempstore);
return result;
}
static CURLcode getalnum(const char **ptr, char *alpnbuf, size_t buflen)
{
size_t len;
const char *protop;
const char *p = *ptr;
while(*p && ISBLANK(*p))
p++;
protop = p;
while(*p && !ISBLANK(*p) && (*p != ';') && (*p != '='))
p++;
len = p - protop;
*ptr = p;
if(!len || (len >= buflen))
return CURLE_BAD_FUNCTION_ARGUMENT;
memcpy(alpnbuf, protop, len);
alpnbuf[len] = 0;
return CURLE_OK;
}
/* altsvc_flush() removes all alternatives for this source origin from the
list */
static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid,
const char *srchost, unsigned short srcport)
{
struct Curl_llist_element *e;
struct Curl_llist_element *n;
for(e = asi->list.head; e; e = n) {
struct altsvc *as = e->ptr;
n = e->next;
if((srcalpnid == as->src.alpnid) &&
(srcport == as->src.port) &&
strcasecompare(srchost, as->src.host)) {
Curl_llist_remove(&asi->list, e, NULL);
altsvc_free(as);
}
}
}
#ifdef DEBUGBUILD
/* to play well with debug builds, we can *set* a fixed time this will
return */
static time_t debugtime(void *unused)
{
char *timestr = getenv("CURL_TIME");
(void)unused;
if(timestr) {
unsigned long val = strtol(timestr, NULL, 10);
return (time_t)val;
}
return time(NULL);
}
#define time(x) debugtime(x)
#endif
#define ISNEWLINE(x) (((x) == '\n') || (x) == '\r')
/*
* Curl_altsvc_parse() takes an incoming alt-svc response header and stores
* the data correctly in the cache.
*
* 'value' points to the header *value*. That's contents to the right of the
* header name.
*
* Currently this function rejects invalid data without returning an error.
* Invalid host name, port number will result in the specific alternative
* being rejected. Unknown protocols are skipped.
*/
CURLcode Curl_altsvc_parse(struct Curl_easy *data,
struct altsvcinfo *asi, const char *value,
enum alpnid srcalpnid, const char *srchost,
unsigned short srcport)
{
const char *p = value;
size_t len;
char namebuf[MAX_ALTSVC_HOSTLEN] = "";
char alpnbuf[MAX_ALTSVC_ALPNLEN] = "";
struct altsvc *as;
unsigned short dstport = srcport; /* the same by default */
CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)data;
#endif
if(result) {
infof(data, "Excessive alt-svc header, ignoring.");
return CURLE_OK;
}
DEBUGASSERT(asi);
/* Flush all cached alternatives for this source origin, if any */
altsvc_flush(asi, srcalpnid, srchost, srcport);
/* "clear" is a magic keyword */
if(strcasecompare(alpnbuf, "clear")) {
return CURLE_OK;
}
do {
if(*p == '=') {
/* [protocol]="[host][:port]" */
enum alpnid dstalpnid = alpn2alpnid(alpnbuf); /* the same by default */
p++;
if(*p == '\"') {
const char *dsthost = "";
const char *value_ptr;
char option[32];
unsigned long num;
char *end_ptr;
bool quoted = FALSE;
time_t maxage = 24 * 3600; /* default is 24 hours */
bool persist = FALSE;
p++;
if(*p != ':') {
/* host name starts here */
const char *hostp = p;
while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-')))
p++;
len = p - hostp;
if(!len || (len >= MAX_ALTSVC_HOSTLEN)) {
infof(data, "Excessive alt-svc host name, ignoring.");
dstalpnid = ALPN_none;
}
else {
memcpy(namebuf, hostp, len);
namebuf[len] = 0;
dsthost = namebuf;
}
}
else {
/* no destination name, use source host */
dsthost = srchost;
}
if(*p == ':') {
/* a port number */
unsigned long port = strtoul(++p, &end_ptr, 10);
if(port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') {
infof(data, "Unknown alt-svc port number, ignoring.");
dstalpnid = ALPN_none;
}
p = end_ptr;
dstport = curlx_ultous(port);
}
if(*p++ != '\"')
break;
/* Handle the optional 'ma' and 'persist' flags. Unknown flags
are skipped. */
for(;;) {
while(ISBLANK(*p))
p++;
if(*p != ';')
break;
p++; /* pass the semicolon */
if(!*p || ISNEWLINE(*p))
break;
result = getalnum(&p, option, sizeof(option));
if(result) {
/* skip option if name is too long */
option[0] = '\0';
}
while(*p && ISBLANK(*p))
p++;
if(*p != '=')
return CURLE_OK;
p++;
while(*p && ISBLANK(*p))
p++;
if(!*p)
return CURLE_OK;
if(*p == '\"') {
/* quoted value */
p++;
quoted = TRUE;
}
value_ptr = p;
if(quoted) {
while(*p && *p != '\"')
p++;
if(!*p++)
return CURLE_OK;
}
else {
while(*p && !ISBLANK(*p) && *p!= ';' && *p != ',')
p++;
}
num = strtoul(value_ptr, &end_ptr, 10);
if((end_ptr != value_ptr) && (num < ULONG_MAX)) {
if(strcasecompare("ma", option))
maxage = num;
else if(strcasecompare("persist", option) && (num == 1))
persist = TRUE;
}
}
if(dstalpnid) {
as = altsvc_createid(srchost, dsthost,
srcalpnid, dstalpnid,
srcport, dstport);
if(as) {
/* The expires time also needs to take the Age: value (if any) into
account. [See RFC 7838 section 3.1] */
as->expires = maxage + time(NULL);
as->persist = persist;
Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
infof(data, "Added alt-svc: %s:%d over %s", dsthost, dstport,
Curl_alpnid2str(dstalpnid));
}
}
else {
infof(data, "Unknown alt-svc protocol \"%s\", skipping.",
alpnbuf);
}
}
else
break;
/* after the double quote there can be a comma if there's another
string or a semicolon if no more */
if(*p == ',') {
/* comma means another alternative is presented */
p++;
result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
if(result)
break;
}
}
else
break;
} while(*p && (*p != ';') && (*p != '\n') && (*p != '\r'));
return CURLE_OK;
}
/*
* Return TRUE on a match
*/
bool Curl_altsvc_lookup(struct altsvcinfo *asi,
enum alpnid srcalpnid, const char *srchost,
int srcport,
struct altsvc **dstentry,
const int versions) /* one or more bits */
{
struct Curl_llist_element *e;
struct Curl_llist_element *n;
time_t now = time(NULL);
DEBUGASSERT(asi);
DEBUGASSERT(srchost);
DEBUGASSERT(dstentry);
for(e = asi->list.head; e; e = n) {
struct altsvc *as = e->ptr;
n = e->next;
if(as->expires < now) {
/* an expired entry, remove */
Curl_llist_remove(&asi->list, e, NULL);
altsvc_free(as);
continue;
}
if((as->src.alpnid == srcalpnid) &&
strcasecompare(as->src.host, srchost) &&
(as->src.port == srcport) &&
(versions & as->dst.alpnid)) {
/* match */
*dstentry = as;
return TRUE;
}
}
return FALSE;
}
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_sspi.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef USE_WINDOWS_SSPI
#include <curl/curl.h>
#include "curl_sspi.h"
#include "curl_multibyte.h"
#include "system_win32.h"
#include "version_win32.h"
#include "warnless.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/* We use our own typedef here since some headers might lack these */
typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID);
/* See definition of SECURITY_ENTRYPOINT in sspi.h */
#ifdef UNICODE
# ifdef _WIN32_WCE
# define SECURITYENTRYPOINT L"InitSecurityInterfaceW"
# else
# define SECURITYENTRYPOINT "InitSecurityInterfaceW"
# endif
#else
# define SECURITYENTRYPOINT "InitSecurityInterfaceA"
#endif
/* Handle of security.dll or secur32.dll, depending on Windows version */
HMODULE s_hSecDll = NULL;
/* Pointer to SSPI dispatch table */
PSecurityFunctionTable s_pSecFn = NULL;
/*
* Curl_sspi_global_init()
*
* This is used to load the Security Service Provider Interface (SSPI)
* dynamic link library portably across all Windows versions, without
* the need to directly link libcurl, nor the application using it, at
* build time.
*
* Once this function has been executed, Windows SSPI functions can be
* called through the Security Service Provider Interface dispatch table.
*
* Parameters:
*
* None.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_sspi_global_init(void)
{
INITSECURITYINTERFACE_FN pInitSecurityInterface;
/* If security interface is not yet initialized try to do this */
if(!s_hSecDll) {
/* Security Service Provider Interface (SSPI) functions are located in
* security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP
* have both these DLLs (security.dll forwards calls to secur32.dll) */
/* Load SSPI dll into the address space of the calling process */
if(curlx_verify_windows_version(4, 0, PLATFORM_WINNT, VERSION_EQUAL))
s_hSecDll = Curl_load_library(TEXT("security.dll"));
else
s_hSecDll = Curl_load_library(TEXT("secur32.dll"));
if(!s_hSecDll)
return CURLE_FAILED_INIT;
/* Get address of the InitSecurityInterfaceA function from the SSPI dll */
pInitSecurityInterface =
CURLX_FUNCTION_CAST(INITSECURITYINTERFACE_FN,
(GetProcAddress(s_hSecDll, SECURITYENTRYPOINT)));
if(!pInitSecurityInterface)
return CURLE_FAILED_INIT;
/* Get pointer to Security Service Provider Interface dispatch table */
s_pSecFn = pInitSecurityInterface();
if(!s_pSecFn)
return CURLE_FAILED_INIT;
}
return CURLE_OK;
}
/*
* Curl_sspi_global_cleanup()
*
* This deinitializes the Security Service Provider Interface from libcurl.
*
* Parameters:
*
* None.
*/
void Curl_sspi_global_cleanup(void)
{
if(s_hSecDll) {
FreeLibrary(s_hSecDll);
s_hSecDll = NULL;
s_pSecFn = NULL;
}
}
/*
* Curl_create_sspi_identity()
*
* This is used to populate a SSPI identity structure based on the supplied
* username and password.
*
* Parameters:
*
* userp [in] - The user name in the format User or Domain\User.
* passwdp [in] - The user's password.
* identity [in/out] - The identity structure.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp,
SEC_WINNT_AUTH_IDENTITY *identity)
{
xcharp_u useranddomain;
xcharp_u user, dup_user;
xcharp_u domain, dup_domain;
xcharp_u passwd, dup_passwd;
size_t domlen = 0;
domain.const_tchar_ptr = TEXT("");
/* Initialize the identity */
memset(identity, 0, sizeof(*identity));
useranddomain.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)userp);
if(!useranddomain.tchar_ptr)
return CURLE_OUT_OF_MEMORY;
user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('\\'));
if(!user.const_tchar_ptr)
user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('/'));
if(user.tchar_ptr) {
domain.tchar_ptr = useranddomain.tchar_ptr;
domlen = user.tchar_ptr - useranddomain.tchar_ptr;
user.tchar_ptr++;
}
else {
user.tchar_ptr = useranddomain.tchar_ptr;
domain.const_tchar_ptr = TEXT("");
domlen = 0;
}
/* Setup the identity's user and length */
dup_user.tchar_ptr = _tcsdup(user.tchar_ptr);
if(!dup_user.tchar_ptr) {
curlx_unicodefree(useranddomain.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
identity->User = dup_user.tbyte_ptr;
identity->UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr));
dup_user.tchar_ptr = NULL;
/* Setup the identity's domain and length */
dup_domain.tchar_ptr = malloc(sizeof(TCHAR) * (domlen + 1));
if(!dup_domain.tchar_ptr) {
curlx_unicodefree(useranddomain.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
_tcsncpy(dup_domain.tchar_ptr, domain.tchar_ptr, domlen);
*(dup_domain.tchar_ptr + domlen) = TEXT('\0');
identity->Domain = dup_domain.tbyte_ptr;
identity->DomainLength = curlx_uztoul(domlen);
dup_domain.tchar_ptr = NULL;
curlx_unicodefree(useranddomain.tchar_ptr);
/* Setup the identity's password and length */
passwd.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)passwdp);
if(!passwd.tchar_ptr)
return CURLE_OUT_OF_MEMORY;
dup_passwd.tchar_ptr = _tcsdup(passwd.tchar_ptr);
if(!dup_passwd.tchar_ptr) {
curlx_unicodefree(passwd.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
identity->Password = dup_passwd.tbyte_ptr;
identity->PasswordLength = curlx_uztoul(_tcslen(dup_passwd.tchar_ptr));
dup_passwd.tchar_ptr = NULL;
curlx_unicodefree(passwd.tchar_ptr);
/* Setup the identity's flags */
identity->Flags = SECFLAG_WINNT_AUTH_IDENTITY;
return CURLE_OK;
}
/*
* Curl_sspi_free_identity()
*
* This is used to free the contents of a SSPI identifier structure.
*
* Parameters:
*
* identity [in/out] - The identity structure.
*/
void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity)
{
if(identity) {
Curl_safefree(identity->User);
Curl_safefree(identity->Password);
Curl_safefree(identity->Domain);
}
}
#endif /* USE_WINDOWS_SSPI */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_proxy.h | #ifndef HEADER_CURL_HTTP_PROXY_H
#define HEADER_CURL_HTTP_PROXY_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
/* ftp can use this as well */
CURLcode Curl_proxyCONNECT(struct Curl_easy *data,
int tunnelsocket,
const char *hostname, int remote_port);
/* Default proxy timeout in milliseconds */
#define PROXY_TIMEOUT (3600*1000)
CURLcode Curl_proxy_connect(struct Curl_easy *data, int sockindex);
bool Curl_connect_complete(struct connectdata *conn);
bool Curl_connect_ongoing(struct connectdata *conn);
int Curl_connect_getsock(struct connectdata *conn);
#else
#define Curl_proxyCONNECT(x,y,z,w) CURLE_NOT_BUILT_IN
#define Curl_proxy_connect(x,y) CURLE_OK
#define Curl_connect_complete(x) CURLE_OK
#define Curl_connect_ongoing(x) FALSE
#define Curl_connect_getsock(x) 0
#endif
void Curl_connect_free(struct Curl_easy *data);
void Curl_connect_done(struct Curl_easy *data);
/* struct for HTTP CONNECT state data */
struct http_connect_state {
struct HTTP http_proxy;
struct HTTP *prot_save;
struct dynbuf rcvbuf;
struct dynbuf req;
size_t nsend;
enum keeponval {
KEEPON_DONE,
KEEPON_CONNECT,
KEEPON_IGNORE
} keepon;
curl_off_t cl; /* size of content to read and ignore */
enum {
TUNNEL_INIT, /* init/default/no tunnel state */
TUNNEL_CONNECT, /* CONNECT has been sent off */
TUNNEL_COMPLETE, /* CONNECT response received completely */
TUNNEL_EXIT
} tunnel_state;
BIT(chunked_encoding);
BIT(close_connection);
};
#endif /* HEADER_CURL_HTTP_PROXY_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/wildcard.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
#include "wildcard.h"
#include "llist.h"
#include "fileinfo.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
static void fileinfo_dtor(void *user, void *element)
{
(void)user;
Curl_fileinfo_cleanup(element);
}
CURLcode Curl_wildcard_init(struct WildcardData *wc)
{
Curl_llist_init(&wc->filelist, fileinfo_dtor);
wc->state = CURLWC_INIT;
return CURLE_OK;
}
void Curl_wildcard_dtor(struct WildcardData *wc)
{
if(!wc)
return;
if(wc->dtor) {
wc->dtor(wc->protdata);
wc->dtor = ZERO_NULL;
wc->protdata = NULL;
}
DEBUGASSERT(wc->protdata == NULL);
Curl_llist_destroy(&wc->filelist, NULL);
free(wc->path);
wc->path = NULL;
free(wc->pattern);
wc->pattern = NULL;
wc->customptr = NULL;
wc->state = CURLWC_INIT;
}
#endif /* if disabled */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/slist.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "slist.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/* returns last node in linked list */
static struct curl_slist *slist_get_last(struct curl_slist *list)
{
struct curl_slist *item;
/* if caller passed us a NULL, return now */
if(!list)
return NULL;
/* loop through to find the last item */
item = list;
while(item->next) {
item = item->next;
}
return item;
}
/*
* Curl_slist_append_nodup() appends a string to the linked list. Rather than
* copying the string in dynamic storage, it takes its ownership. The string
* should have been malloc()ated. Curl_slist_append_nodup always returns
* the address of the first record, so that you can use this function as an
* initialization function as well as an append function.
* If an error occurs, NULL is returned and the string argument is NOT
* released.
*/
struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data)
{
struct curl_slist *last;
struct curl_slist *new_item;
DEBUGASSERT(data);
new_item = malloc(sizeof(struct curl_slist));
if(!new_item)
return NULL;
new_item->next = NULL;
new_item->data = data;
/* if this is the first item, then new_item *is* the list */
if(!list)
return new_item;
last = slist_get_last(list);
last->next = new_item;
return list;
}
/*
* curl_slist_append() appends a string to the linked list. It always returns
* the address of the first record, so that you can use this function as an
* initialization function as well as an append function. If you find this
* bothersome, then simply create a separate _init function and call it
* appropriately from within the program.
*/
struct curl_slist *curl_slist_append(struct curl_slist *list,
const char *data)
{
char *dupdata = strdup(data);
if(!dupdata)
return NULL;
list = Curl_slist_append_nodup(list, dupdata);
if(!list)
free(dupdata);
return list;
}
/*
* Curl_slist_duplicate() duplicates a linked list. It always returns the
* address of the first record of the cloned list or NULL in case of an
* error (or if the input list was NULL).
*/
struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist)
{
struct curl_slist *outlist = NULL;
struct curl_slist *tmp;
while(inlist) {
tmp = curl_slist_append(outlist, inlist->data);
if(!tmp) {
curl_slist_free_all(outlist);
return NULL;
}
outlist = tmp;
inlist = inlist->next;
}
return outlist;
}
/* be nice and clean up resources */
void curl_slist_free_all(struct curl_slist *list)
{
struct curl_slist *next;
struct curl_slist *item;
if(!list)
return;
item = list;
do {
next = item->next;
Curl_safefree(item->data);
free(item);
item = next;
} while(next);
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_addrinfo.h | #ifndef HEADER_CURL_ADDRINFO_H
#define HEADER_CURL_ADDRINFO_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef __VMS
# include <in.h>
# include <inet.h>
# include <stdlib.h>
#endif
/*
* Curl_addrinfo is our internal struct definition that we use to allow
* consistent internal handling of this data. We use this even when the
* system provides an addrinfo structure definition. And we use this for
* all sorts of IPv4 and IPV6 builds.
*/
struct Curl_addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
curl_socklen_t ai_addrlen; /* Follow rfc3493 struct addrinfo */
char *ai_canonname;
struct sockaddr *ai_addr;
struct Curl_addrinfo *ai_next;
};
void
Curl_freeaddrinfo(struct Curl_addrinfo *cahead);
#ifdef HAVE_GETADDRINFO
int
Curl_getaddrinfo_ex(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct Curl_addrinfo **result);
#endif
struct Curl_addrinfo *
Curl_he2ai(const struct hostent *he, int port);
struct Curl_addrinfo *
Curl_ip2addr(int af, const void *inaddr, const char *hostname, int port);
struct Curl_addrinfo *Curl_str2addr(char *dotted, int port);
#ifdef USE_UNIX_SOCKETS
struct Curl_addrinfo *Curl_unix2addr(const char *path, bool *longpath,
bool abstract);
#endif
#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO) && \
defined(HAVE_FREEADDRINFO)
void
curl_dbg_freeaddrinfo(struct addrinfo *freethis, int line, const char *source);
#endif
#if defined(CURLDEBUG) && defined(HAVE_GETADDRINFO)
int
curl_dbg_getaddrinfo(const char *hostname, const char *service,
const struct addrinfo *hints, struct addrinfo **result,
int line, const char *source);
#endif
#ifdef HAVE_GETADDRINFO
#ifdef USE_RESOLVE_ON_IPS
void Curl_addrinfo_set_port(struct Curl_addrinfo *addrinfo, int port);
#else
#define Curl_addrinfo_set_port(x,y)
#endif
#endif
#endif /* HEADER_CURL_ADDRINFO_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/timeval.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "timeval.h"
#if defined(WIN32) && !defined(MSDOS)
/* set in win32_init() */
extern LARGE_INTEGER Curl_freq;
extern bool Curl_isVistaOrGreater;
/* In case of bug fix this function has a counterpart in tool_util.c */
struct curltime Curl_now(void)
{
struct curltime now;
if(Curl_isVistaOrGreater) { /* QPC timer might have issues pre-Vista */
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
now.tv_sec = (time_t)(count.QuadPart / Curl_freq.QuadPart);
now.tv_usec = (int)((count.QuadPart % Curl_freq.QuadPart) * 1000000 /
Curl_freq.QuadPart);
}
else {
/* Disable /analyze warning that GetTickCount64 is preferred */
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:28159)
#endif
DWORD milliseconds = GetTickCount();
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
now.tv_sec = milliseconds / 1000;
now.tv_usec = (milliseconds % 1000) * 1000;
}
return now;
}
#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
struct curltime Curl_now(void)
{
/*
** clock_gettime() is granted to be increased monotonically when the
** monotonic clock is queried. Time starting point is unspecified, it
** could be the system start-up time, the Epoch, or something else,
** in any case the time starting point does not change once that the
** system has started up.
*/
#ifdef HAVE_GETTIMEOFDAY
struct timeval now;
#endif
struct curltime cnow;
struct timespec tsnow;
/*
** clock_gettime() may be defined by Apple's SDK as weak symbol thus
** code compiles but fails during run-time if clock_gettime() is
** called on unsupported OS version.
*/
#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \
(HAVE_BUILTIN_AVAILABLE == 1)
bool have_clock_gettime = FALSE;
if(__builtin_available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *))
have_clock_gettime = TRUE;
#endif
if(
#if defined(__APPLE__) && defined(HAVE_BUILTIN_AVAILABLE) && \
(HAVE_BUILTIN_AVAILABLE == 1)
have_clock_gettime &&
#endif
(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow))) {
cnow.tv_sec = tsnow.tv_sec;
cnow.tv_usec = (unsigned int)(tsnow.tv_nsec / 1000);
}
/*
** Even when the configure process has truly detected monotonic clock
** availability, it might happen that it is not actually available at
** run-time. When this occurs simply fallback to other time source.
*/
#ifdef HAVE_GETTIMEOFDAY
else {
(void)gettimeofday(&now, NULL);
cnow.tv_sec = now.tv_sec;
cnow.tv_usec = (unsigned int)now.tv_usec;
}
#else
else {
cnow.tv_sec = time(NULL);
cnow.tv_usec = 0;
}
#endif
return cnow;
}
#elif defined(HAVE_MACH_ABSOLUTE_TIME)
#include <stdint.h>
#include <mach/mach_time.h>
struct curltime Curl_now(void)
{
/*
** Monotonic timer on Mac OS is provided by mach_absolute_time(), which
** returns time in Mach "absolute time units," which are platform-dependent.
** To convert to nanoseconds, one must use conversion factors specified by
** mach_timebase_info().
*/
static mach_timebase_info_data_t timebase;
struct curltime cnow;
uint64_t usecs;
if(0 == timebase.denom)
(void) mach_timebase_info(&timebase);
usecs = mach_absolute_time();
usecs *= timebase.numer;
usecs /= timebase.denom;
usecs /= 1000;
cnow.tv_sec = usecs / 1000000;
cnow.tv_usec = (int)(usecs % 1000000);
return cnow;
}
#elif defined(HAVE_GETTIMEOFDAY)
struct curltime Curl_now(void)
{
/*
** gettimeofday() is not granted to be increased monotonically, due to
** clock drifting and external source time synchronization it can jump
** forward or backward in time.
*/
struct timeval now;
struct curltime ret;
(void)gettimeofday(&now, NULL);
ret.tv_sec = now.tv_sec;
ret.tv_usec = (int)now.tv_usec;
return ret;
}
#else
struct curltime Curl_now(void)
{
/*
** time() returns the value of time in seconds since the Epoch.
*/
struct curltime now;
now.tv_sec = time(NULL);
now.tv_usec = 0;
return now;
}
#endif
/*
* Returns: time difference in number of milliseconds. For too large diffs it
* returns max value.
*
* @unittest: 1323
*/
timediff_t Curl_timediff(struct curltime newer, struct curltime older)
{
timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec;
if(diff >= (TIMEDIFF_T_MAX/1000))
return TIMEDIFF_T_MAX;
else if(diff <= (TIMEDIFF_T_MIN/1000))
return TIMEDIFF_T_MIN;
return diff * 1000 + (newer.tv_usec-older.tv_usec)/1000;
}
/*
* Returns: time difference in number of microseconds. For too large diffs it
* returns max value.
*/
timediff_t Curl_timediff_us(struct curltime newer, struct curltime older)
{
timediff_t diff = (timediff_t)newer.tv_sec-older.tv_sec;
if(diff >= (TIMEDIFF_T_MAX/1000000))
return TIMEDIFF_T_MAX;
else if(diff <= (TIMEDIFF_T_MIN/1000000))
return TIMEDIFF_T_MIN;
return diff * 1000000 + newer.tv_usec-older.tv_usec;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strcase.h | #ifndef HEADER_CURL_STRCASE_H
#define HEADER_CURL_STRCASE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <curl/curl.h>
/*
* Only "raw" case insensitive strings. This is meant to be locale independent
* and only compare strings we know are safe for this.
*
* The function is capable of comparing a-z case insensitively even for
* non-ascii.
*/
#define strcasecompare(a,b) Curl_strcasecompare(a,b)
#define strncasecompare(a,b,c) Curl_strncasecompare(a,b,c)
int Curl_strcasecompare(const char *first, const char *second);
int Curl_safe_strcasecompare(const char *first, const char *second);
int Curl_strncasecompare(const char *first, const char *second, size_t max);
char Curl_raw_toupper(char in);
/* checkprefix() is a shorter version of the above, used when the first
argument is zero-byte terminated */
#define checkprefix(a,b) curl_strnequal(a,b,strlen(a))
void Curl_strntoupper(char *dest, const char *src, size_t n);
void Curl_strntolower(char *dest, const char *src, size_t n);
#endif /* HEADER_CURL_STRCASE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/urlapi.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "urlapi-int.h"
#include "strcase.h"
#include "dotdot.h"
#include "url.h"
#include "escape.h"
#include "curl_ctype.h"
#include "inet_pton.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/* MSDOS/Windows style drive prefix, eg c: in c:foo */
#define STARTS_WITH_DRIVE_PREFIX(str) \
((('a' <= str[0] && str[0] <= 'z') || \
('A' <= str[0] && str[0] <= 'Z')) && \
(str[1] == ':'))
/* MSDOS/Windows style drive prefix, optionally with
* a '|' instead of ':', followed by a slash or NUL */
#define STARTS_WITH_URL_DRIVE_PREFIX(str) \
((('a' <= (str)[0] && (str)[0] <= 'z') || \
('A' <= (str)[0] && (str)[0] <= 'Z')) && \
((str)[1] == ':' || (str)[1] == '|') && \
((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
/* 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;
char *scratch; /* temporary scratch area */
char *temppath; /* temporary path pointer */
long portnum; /* the numerical version */
};
#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);
free(u->scratch);
free(u->temppath);
}
/* move the full contents of one handle onto another and
free the original */
static void mv_urlhandle(struct Curl_URL *from,
struct Curl_URL *to)
{
free_urlhandle(to);
*to = *from;
free(from);
}
/*
* Find the separator at the end of the host name, or the '?' in cases like
* http://www.url.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;
}
/*
* Decide in an encoding-independent manner whether a character in an
* URL must be escaped. The same criterion must be used in strlen_url()
* and strcpy_url().
*/
static bool urlchar_needs_escaping(int c)
{
return !(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c));
}
/*
* strlen_url() returns the length of the given URL if the spaces within the
* URL were properly URL encoded.
* URL encoding should be skipped for host names, otherwise IDN resolution
* will fail.
*/
static size_t strlen_url(const char *url, bool relative)
{
const unsigned char *ptr;
size_t newlen = 0;
bool left = TRUE; /* left side of the ? */
const unsigned char *host_sep = (const unsigned char *) url;
if(!relative)
host_sep = (const unsigned char *) find_host_sep(url);
for(ptr = (unsigned char *)url; *ptr; ptr++) {
if(ptr < host_sep) {
++newlen;
continue;
}
if(*ptr == ' ') {
if(left)
newlen += 3;
else
newlen++;
continue;
}
if (*ptr == '?')
left = FALSE;
if(urlchar_needs_escaping(*ptr))
newlen += 2;
newlen++;
}
return newlen;
}
/* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
* the source URL accordingly.
* URL encoding should be skipped for host names, otherwise IDN resolution
* will fail.
*/
static void strcpy_url(char *output, const char *url, bool relative)
{
/* we must add this with whitespace-replacing */
bool left = TRUE;
const unsigned char *iptr;
char *optr = output;
const unsigned char *host_sep = (const unsigned char *) url;
if(!relative)
host_sep = (const unsigned char *) find_host_sep(url);
for(iptr = (unsigned char *)url; /* read from here */
*iptr; /* until zero byte */
iptr++) {
if(iptr < host_sep) {
*optr++ = *iptr;
continue;
}
if(*iptr == ' ') {
if(left) {
*optr++='%'; /* add a '%' */
*optr++='2'; /* add a '2' */
*optr++='0'; /* add a '0' */
}
else
*optr++='+'; /* add a '+' here */
continue;
}
if(*iptr == '?')
left = FALSE;
if(urlchar_needs_escaping(*iptr)) {
msnprintf(optr, 4, "%%%02x", *iptr);
optr += 3;
}
else
*optr++ = *iptr;
}
*optr = 0; /* null-terminate output buffer */
}
/*
* Returns true if the given URL is absolute (as opposed to relative) within
* the buffer size. Returns the scheme in the buffer if TRUE and 'buf' is
* non-NULL.
*/
bool Curl_is_absolute_url(const char *url, char *buf, size_t buflen)
{
size_t i;
#ifdef WIN32
if(STARTS_WITH_DRIVE_PREFIX(url))
return FALSE;
#endif
for(i = 0; i < buflen && url[i]; ++i) {
char s = url[i];
if((s == ':') && (url[i + 1] == '/')) {
if(buf)
buf[i] = 0;
return TRUE;
}
/* RFC 3986 3.1 explains:
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
*/
else if(ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') ) {
if(buf)
buf[i] = (char)TOLOWER(s);
}
else
break;
}
return FALSE;
}
/*
* 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).
*/
static char *concat_url(const char *base, const char *relurl)
{
/***
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...
*/
char *newest;
char *protsep;
char *pathsep;
size_t newlen;
bool host_changed = FALSE;
const char *useurl = relurl;
size_t urllen;
/* we must make our own copy of the URL to play with, as it may
point to read-only data */
char *url_clone = strdup(base);
if(!url_clone)
return NULL; /* skip out of this NOW */
/* protsep points to the start of the host name */
protsep = strstr(url_clone, "//");
if(!protsep)
protsep = url_clone;
else
protsep += 2; /* pass the slashes */
if('/' != relurl[0]) {
int level = 0;
/* First we need to find out if there's a ?-letter in the URL,
and cut it and the right-side of that off */
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep = 0;
/* we have a relative path to append to the last slash if there's one
available, or if the new URL is just a query string (starts with a
'?') we append the new one at the end of the entire currently worked
out URL */
if(useurl[0] != '?') {
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep = 0;
}
/* Check if there's any slash after the host name, and if so, remember
that position instead */
pathsep = strchr(protsep, '/');
if(pathsep)
protsep = pathsep + 1;
else
protsep = NULL;
/* now deal with one "./" or any amount of "../" in the newurl
and act accordingly */
if((useurl[0] == '.') && (useurl[1] == '/'))
useurl += 2; /* just skip the "./" */
while((useurl[0] == '.') &&
(useurl[1] == '.') &&
(useurl[2] == '/')) {
level++;
useurl += 3; /* pass the "../" */
}
if(protsep) {
while(level--) {
/* cut off one more level from the right of the original URL */
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep = 0;
else {
*protsep = 0;
break;
}
}
}
}
else {
/* 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.url.com?dir=/home/daniel" we must not use the first
slash, if there's a ?-letter before it! */
char *sep = strchr(protsep, '?');
if(sep && (sep < pathsep))
pathsep = sep;
*pathsep = 0;
}
else {
/* There was no slash. Now, since we might be operating on a badly
formatted URL, such as "http://www.url.com?id=2380" which doesn't
use a slash separator as it is supposed to, we need to check for a
?-letter as well! */
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep = 0;
}
}
}
/* If the new part contains a space, this is a mighty stupid redirect
but we still make an effort to do "right". To the left of a '?'
letter we replace each space with %20 while it is replaced with '+'
on the right side of the '?' letter.
*/
newlen = strlen_url(useurl, !host_changed);
urllen = strlen(url_clone);
newest = malloc(urllen + 1 + /* possible slash */
newlen + 1 /* zero byte */);
if(!newest) {
free(url_clone); /* don't leak this */
return NULL;
}
/* copy over the root url part */
memcpy(newest, url_clone, urllen);
/* check if we need to append a slash */
if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
;
else
newest[urllen++]='/';
/* then append the new piece on the right side */
strcpy_url(&newest[urllen], useurl, !host_changed);
free(url_clone);
return newest;
}
/*
* parse_hostname_login()
*
* Parse the login details (user name, password and options) from the URL and
* strip them out of the host name
*
*/
static CURLUcode parse_hostname_login(struct Curl_URL *u,
char **hostname,
unsigned int flags)
{
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're hoping all the other special cases have
* been taken care of, so conn->host.name is at most
* [user[:password][;options]]@]hostname
*
* We need somewhere to put the embedded details, so do that first.
*/
char *ptr = strchr(*hostname, '@');
char *login = *hostname;
if(!ptr)
goto out;
/* We will now try to extract the
* possible login information in a string like:
* ftp://user:[email protected]:8021/README */
*hostname = ++ptr;
/* if this is a known scheme, get some details */
if(u->scheme)
h = Curl_builtin_scheme(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_MALFORMED_INPUT;
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;
}
u->user = userp;
}
if(passwdp)
u->password = passwdp;
if(optionsp)
u->options = optionsp;
return CURLUE_OK;
out:
free(userp);
free(passwdp);
free(optionsp);
return result;
}
UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname,
bool has_scheme)
{
char *portptr = NULL;
char endbracket;
int len;
/*
* Find the end of an IPv6 address, either on the ']' ending bracket or
* a percent-encoded zone index.
*/
if(1 == sscanf(hostname, "[%*45[0123456789abcdefABCDEF:.]%c%n",
&endbracket, &len)) {
if(']' == endbracket)
portptr = &hostname[len];
else if('%' == endbracket) {
int zonelen = len;
if(1 == sscanf(hostname + zonelen, "%*[^]]%c%n", &endbracket, &len)) {
if(']' != endbracket)
return CURLUE_MALFORMED_INPUT;
portptr = &hostname[--zonelen + len + 1];
}
else
return CURLUE_MALFORMED_INPUT;
}
else
return CURLUE_MALFORMED_INPUT;
/* this is a RFC2732-style specified IP-address */
if(portptr && *portptr) {
if(*portptr != ':')
return CURLUE_MALFORMED_INPUT;
}
else
portptr = NULL;
}
else
portptr = strchr(hostname, ':');
if(portptr) {
char *rest;
long port;
char portbuf[7];
/* Browser behavior adaptation. If there's a colon with no digits after,
just cut off the name there which makes us ignore the colon and just
use the default port. Firefox, Chrome and Safari all do that.
Don't do it if the URL has no scheme, to make something that looks like
a scheme not work!
*/
if(!portptr[1]) {
*portptr = '\0';
return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
}
if(!ISDIGIT(portptr[1]))
return CURLUE_BAD_PORT_NUMBER;
port = strtol(portptr + 1, &rest, 10); /* Port number must be decimal */
if((port <= 0) || (port > 0xffff))
/* Single unix standard says port numbers are 16 bits long, but we don't
treat port zero as OK. */
return CURLUE_BAD_PORT_NUMBER;
if(rest[0])
return CURLUE_BAD_PORT_NUMBER;
*portptr++ = '\0'; /* cut off the name there */
*rest = 0;
/* generate a new port number string to get rid of leading zeroes etc */
msnprintf(portbuf, sizeof(portbuf), "%ld", port);
u->portnum = port;
u->port = strdup(portbuf);
if(!u->port)
return CURLUE_OUT_OF_MEMORY;
}
return CURLUE_OK;
}
/* scan for byte values < 31 or 127 */
static bool junkscan(const char *part, unsigned int flags)
{
if(part) {
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(part);
size_t nfine = strcspn(part, badbytes);
if(nfine != n)
/* since we don't know which part is scanned, return a generic error
code */
return TRUE;
if(!(flags & CURLU_ALLOW_SPACE) && strchr(part, ' '))
return TRUE;
}
return FALSE;
}
static CURLUcode hostname_check(struct Curl_URL *u, char *hostname)
{
size_t len;
size_t hlen = strlen(hostname);
if(hostname[0] == '[') {
#ifdef ENABLE_IPV6
char dest[16]; /* fits a binary IPv6 address */
#endif
const char *l = "0123456789abcdefABCDEF:.";
if(hlen < 4) /* '[::]' is the shortest possible valid string */
return CURLUE_MALFORMED_INPUT;
hostname++;
hlen -= 2;
if(hostname[hlen] != ']')
return CURLUE_MALFORMED_INPUT;
/* only valid letters are ok */
len = strspn(hostname, l);
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_MALFORMED_INPUT;
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_MALFORMED_INPUT;
/* hostname is fine */
}
#ifdef ENABLE_IPV6
hostname[hlen] = 0; /* end the address there */
if(1 != Curl_inet_pton(AF_INET6, hostname, dest))
return CURLUE_MALFORMED_INPUT;
hostname[hlen] = ']'; /* restore ending bracket */
#endif
}
else {
/* letters from the second string is not ok */
len = strcspn(hostname, " \r\n");
if(hlen != len)
/* hostname with bad content */
return CURLUE_MALFORMED_INPUT;
}
if(!hostname[0])
return CURLUE_NO_HOST;
return CURLUE_OK;
}
#define HOSTNAME_END(x) (((x) == '/') || ((x) == '?') || ((x) == '#'))
/*
* 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 or any part for example is
* too big, this function returns FALSE and doesn't create any output.
*
* Output the "normalized" version of that input string in plain quad decimal
* integers and return TRUE.
*/
static bool ipv4_normalize(const char *hostname, char *outp, size_t olen)
{
bool done = FALSE;
int n = 0;
const char *c = hostname;
unsigned long parts[4] = {0, 0, 0, 0};
while(!done) {
char *endp;
unsigned long l;
if((*c < '0') || (*c > '9'))
/* most importantly this doesn't allow a leading plus or minus */
return FALSE;
l = strtoul(c, &endp, 0);
/* overflow or nothing parsed at all */
if(((l == ULONG_MAX) && (errno == ERANGE)) || (endp == c))
return FALSE;
#if SIZEOF_LONG > 4
/* a value larger than 32 bits */
if(l > UINT_MAX)
return FALSE;
#endif
parts[n] = l;
c = endp;
switch (*c) {
case '.' :
if(n == 3)
return FALSE;
n++;
c++;
break;
case '\0':
done = TRUE;
break;
default:
return FALSE;
}
}
/* this is deemed a valid IPv4 numerical address */
switch(n) {
case 0: /* a -- 32 bits */
msnprintf(outp, olen, "%u.%u.%u.%u",
parts[0] >> 24, (parts[0] >> 16) & 0xff,
(parts[0] >> 8) & 0xff, parts[0] & 0xff);
break;
case 1: /* a.b -- 8.24 bits */
if((parts[0] > 0xff) || (parts[1] > 0xffffff))
return FALSE;
msnprintf(outp, olen, "%u.%u.%u.%u",
parts[0], (parts[1] >> 16) & 0xff,
(parts[1] >> 8) & 0xff, parts[1] & 0xff);
break;
case 2: /* a.b.c -- 8.8.16 bits */
if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
return FALSE;
msnprintf(outp, olen, "%u.%u.%u.%u",
parts[0], parts[1], (parts[2] >> 8) & 0xff,
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 FALSE;
msnprintf(outp, olen, "%u.%u.%u.%u",
parts[0], parts[1], parts[2], parts[3]);
break;
}
return TRUE;
}
/* return strdup'ed version in 'outp', possibly percent decoded */
static CURLUcode decode_host(char *hostname, char **outp)
{
char *per = NULL;
if(hostname[0] != '[')
/* only decode if not an ipv6 numerical */
per = strchr(hostname, '%');
if(!per) {
*outp = strdup(hostname);
if(!*outp)
return CURLUE_OUT_OF_MEMORY;
}
else {
/* might be encoded */
size_t dlen;
CURLcode result = Curl_urldecode(NULL, hostname, 0,
outp, &dlen, REJECT_CTRL);
if(result)
return CURLUE_MALFORMED_INPUT;
}
return CURLUE_OK;
}
static CURLUcode seturl(const char *url, CURLU *u, unsigned int flags)
{
char *path;
bool path_alloced = FALSE;
bool uncpath = FALSE;
char *hostname;
char *query = NULL;
char *fragment = NULL;
CURLUcode result;
bool url_has_scheme = FALSE;
char schemebuf[MAX_SCHEME_LEN + 1];
const char *schemep = NULL;
size_t schemelen = 0;
size_t urllen;
DEBUGASSERT(url);
/*************************************************************
* Parse the URL.
************************************************************/
/* allocate scratch area */
urllen = strlen(url);
if(urllen > CURL_MAX_INPUT_LENGTH)
/* excessive input length */
return CURLUE_MALFORMED_INPUT;
path = u->scratch = malloc(urllen * 2 + 2);
if(!path)
return CURLUE_OUT_OF_MEMORY;
hostname = &path[urllen + 1];
hostname[0] = 0;
if(Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf))) {
url_has_scheme = TRUE;
schemelen = strlen(schemebuf);
}
/* handle the file: scheme */
if(url_has_scheme && strcasecompare(schemebuf, "file")) {
/* path has been allocated large enough to hold this */
strcpy(path, &url[5]);
u->scheme = strdup("file");
if(!u->scheme)
return CURLUE_OUT_OF_MEMORY;
/* Extra handling URLs with an authority component (i.e. that start with
* "file://")
*
* We allow omitted hostname (e.g. file:/<path>) -- valid according to
* RFC 8089, but not the (current) WHAT-WG URL spec.
*/
if(path[0] == '/' && path[1] == '/') {
/* swallow the two slashes */
char *ptr = &path[2];
/*
* According to RFC 8089, a file: URL can be reliably dereferenced if:
*
* o it has no/blank hostname, or
*
* o the hostname matches "localhost" (case-insensitively), or
*
* o the hostname is a FQDN that resolves to this machine, or
*
* o it is an UNC String transformed to an URI (Windows only, RFC 8089
* Appendix E.3).
*
* For brevity, we only consider URLs with empty, "localhost", or
* "127.0.0.1" hostnames as local, otherwise as an UNC String.
*
* Additionally, there is an exception for URLs with a Windows drive
* letter in the authority (which was accidentally omitted from RFC 8089
* Appendix E, but believe me, it was meant to be there. --MK)
*/
if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
/* the URL includes a host name, it must match "localhost" or
"127.0.0.1" to be valid */
if(checkprefix("localhost/", ptr) ||
checkprefix("127.0.0.1/", ptr)) {
ptr += 9; /* now points to the slash after the host */
}
else {
#if defined(WIN32)
size_t len;
/* the host name, NetBIOS computer name, can not contain disallowed
chars, and the delimiting slash character must be appended to the
host name */
path = strpbrk(ptr, "/\\:*?\"<>|");
if(!path || *path != '/')
return CURLUE_MALFORMED_INPUT;
len = path - ptr;
if(len) {
memcpy(hostname, ptr, len);
hostname[len] = 0;
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 */
return CURLUE_MALFORMED_INPUT;
#endif
}
}
path = ptr;
}
if(!uncpath)
hostname = NULL; /* no host for file: URLs by default */
#if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
/* Don't allow Windows drive letters when not in Windows.
* This catches both "file:/c:" and "file:c:" */
if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
STARTS_WITH_URL_DRIVE_PREFIX(path)) {
/* File drive letters are only accepted in MSDOS/Windows */
return CURLUE_MALFORMED_INPUT;
}
#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! */
memmove(path, &path[1], strlen(&path[1]) + 1);
}
#endif
}
else {
/* clear path */
const char *p;
const char *hostp;
size_t len;
path[0] = 0;
if(url_has_scheme) {
int i = 0;
p = &url[schemelen + 1];
while(p && (*p == '/') && (i < 4)) {
p++;
i++;
}
if((i < 1) || (i>3))
/* less than one or more than three slashes */
return CURLUE_MALFORMED_INPUT;
schemep = schemebuf;
if(!Curl_builtin_scheme(schemep) &&
!(flags & CURLU_NON_SUPPORT_SCHEME))
return CURLUE_UNSUPPORTED_SCHEME;
if(junkscan(schemep, flags))
return CURLUE_MALFORMED_INPUT;
}
else {
/* no scheme! */
if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME)))
return CURLUE_MALFORMED_INPUT;
if(flags & CURLU_DEFAULT_SCHEME)
schemep = DEFAULT_SCHEME;
/*
* The URL was badly formatted, let's try without scheme specified.
*/
p = url;
}
hostp = p; /* host name starts here */
while(*p && !HOSTNAME_END(*p)) /* find end of host name */
p++;
len = p - hostp;
if(len) {
memcpy(hostname, hostp, len);
hostname[len] = 0;
}
else {
if(!(flags & CURLU_NO_AUTHORITY))
return CURLUE_MALFORMED_INPUT;
}
len = strlen(p);
memcpy(path, p, len);
path[len] = 0;
if(schemep) {
u->scheme = strdup(schemep);
if(!u->scheme)
return CURLUE_OUT_OF_MEMORY;
}
}
if(junkscan(path, flags))
return CURLUE_MALFORMED_INPUT;
if((flags & CURLU_URLENCODE) && path[0]) {
/* worst case output length is 3x the original! */
char *newp = malloc(strlen(path) * 3);
if(!newp)
return CURLUE_OUT_OF_MEMORY;
path_alloced = TRUE;
strcpy_url(newp, path, TRUE); /* consider it relative */
u->temppath = path = newp;
}
fragment = strchr(path, '#');
if(fragment) {
*fragment++ = 0;
if(fragment[0]) {
u->fragment = strdup(fragment);
if(!u->fragment)
return CURLUE_OUT_OF_MEMORY;
}
}
query = strchr(path, '?');
if(query) {
*query++ = 0;
/* done even if the query part is a blank string */
u->query = strdup(query);
if(!u->query)
return CURLUE_OUT_OF_MEMORY;
}
if(!path[0])
/* if there's no path left set, unset */
path = NULL;
else {
if(!(flags & CURLU_PATH_AS_IS)) {
/* remove ../ and ./ sequences according to RFC3986 */
char *newp = Curl_dedotdotify(path);
if(!newp)
return CURLUE_OUT_OF_MEMORY;
if(strcmp(newp, path)) {
/* if we got a new version */
if(path_alloced)
Curl_safefree(u->temppath);
u->temppath = path = newp;
path_alloced = TRUE;
}
else
free(newp);
}
u->path = path_alloced?path:strdup(path);
if(!u->path)
return CURLUE_OUT_OF_MEMORY;
u->temppath = NULL; /* used now */
}
if(hostname) {
char normalized_ipv4[sizeof("255.255.255.255") + 1];
/*
* Parse the login details and strip them out of the host name.
*/
if(junkscan(hostname, flags))
return CURLUE_MALFORMED_INPUT;
result = parse_hostname_login(u, &hostname, flags);
if(result)
return result;
result = Curl_parse_port(u, hostname, url_has_scheme);
if(result)
return result;
if(0 == strlen(hostname) && (flags & CURLU_NO_AUTHORITY)) {
/* Skip hostname check, it's allowed to be empty. */
u->host = strdup("");
}
else {
if(ipv4_normalize(hostname, normalized_ipv4, sizeof(normalized_ipv4)))
u->host = strdup(normalized_ipv4);
else {
result = decode_host(hostname, &u->host);
if(result)
return result;
result = hostname_check(u, u->host);
if(result)
return result;
}
}
if(!u->host)
return CURLUE_OUT_OF_MEMORY;
if((flags & CURLU_GUESS_SCHEME) && !schemep) {
/* legacy curl-style guess based on host name */
if(checkprefix("ftp.", hostname))
schemep = "ftp";
else if(checkprefix("dict.", hostname))
schemep = "dict";
else if(checkprefix("ldap.", hostname))
schemep = "ldap";
else if(checkprefix("imap.", hostname))
schemep = "imap";
else if(checkprefix("smtp.", hostname))
schemep = "smtp";
else if(checkprefix("pop3.", hostname))
schemep = "pop3";
else
schemep = "http";
u->scheme = strdup(schemep);
if(!u->scheme)
return CURLUE_OUT_OF_MEMORY;
}
}
Curl_safefree(u->scratch);
Curl_safefree(u->temppath);
return CURLUE_OK;
}
/*
* Parse the URL and set the relevant members of the Curl_URL struct.
*/
static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
{
CURLUcode result = seturl(url, u, flags);
if(result) {
free_urlhandle(u);
memset(u, 0, sizeof(struct Curl_URL));
}
return result;
}
/*
*/
CURLU *curl_url(void)
{
return calloc(sizeof(struct Curl_URL), 1);
}
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(CURLU *in)
{
struct Curl_URL *u = calloc(sizeof(struct Curl_URL), 1);
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);
u->portnum = in->portnum;
}
return u;
fail:
curl_url_cleanup(u);
return NULL;
}
CURLUcode curl_url_get(CURLU *u, CURLUPart what,
char **part, unsigned int flags)
{
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 plusdecode = FALSE;
(void)flags;
if(!u)
return CURLUE_BAD_HANDLE;
if(!part)
return CURLUE_BAD_PARTPOINTER;
*part = NULL;
switch(what) {
case CURLUPART_SCHEME:
ptr = u->scheme;
ifmissing = CURLUE_NO_SCHEME;
urldecode = FALSE; /* never for schemes */
break;
case CURLUPART_USER:
ptr = u->user;
ifmissing = CURLUE_NO_USER;
break;
case CURLUPART_PASSWORD:
ptr = u->password;
ifmissing = CURLUE_NO_PASSWORD;
break;
case CURLUPART_OPTIONS:
ptr = u->options;
ifmissing = CURLUE_NO_OPTIONS;
break;
case CURLUPART_HOST:
ptr = u->host;
ifmissing = CURLUE_NO_HOST;
break;
case CURLUPART_ZONEID:
ptr = u->zoneid;
break;
case CURLUPART_PORT:
ptr = u->port;
ifmissing = CURLUE_NO_PORT;
urldecode = FALSE; /* never for port */
if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) {
/* there's no stored port number, but asked to deliver
a default one for the scheme */
const struct Curl_handler *h =
Curl_builtin_scheme(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_builtin_scheme(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 = u->path = strdup("/");
if(!u->path)
return CURLUE_OUT_OF_MEMORY;
}
break;
case CURLUPART_QUERY:
ptr = u->query;
ifmissing = CURLUE_NO_QUERY;
plusdecode = urldecode;
break;
case CURLUPART_FRAGMENT:
ptr = u->fragment;
ifmissing = CURLUE_NO_FRAGMENT;
break;
case CURLUPART_URL: {
char *url;
char *scheme;
char *options = u->options;
char *port = u->port;
char *allochost = NULL;
if(u->scheme && strcasecompare("file", u->scheme)) {
url = aprintf("file://%s%s%s",
u->path,
u->fragment? "#": "",
u->fragment? u->fragment : "");
}
else if(!u->host)
return CURLUE_NO_HOST;
else {
const struct Curl_handler *h = NULL;
if(u->scheme)
scheme = u->scheme;
else if(flags & CURLU_DEFAULT_SCHEME)
scheme = (char *) DEFAULT_SCHEME;
else
return CURLUE_NO_SCHEME;
h = Curl_builtin_scheme(scheme);
if(!port && (flags & CURLU_DEFAULT_PORT)) {
/* there's no stored port number, but asked to deliver
a default one for the scheme */
if(h) {
msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
port = portbuf;
}
}
else if(port) {
/* there is a stored port number, but asked to inhibit if it matches
the default one for the scheme */
if(h && (h->defport == u->portnum) &&
(flags & CURLU_NO_DEFAULT_PORT))
port = NULL;
}
if(h && !(h->flags & PROTOPT_URLOPTIONS))
options = NULL;
if(u->host[0] == '[') {
if(u->zoneid) {
/* make it '[ host %25 zoneid ]' */
size_t hostlen = strlen(u->host);
size_t alen = hostlen + 3 + strlen(u->zoneid) + 1;
allochost = malloc(alen);
if(!allochost)
return CURLUE_OUT_OF_MEMORY;
memcpy(allochost, u->host, hostlen - 1);
msnprintf(&allochost[hostlen - 1], alen - hostlen + 1,
"%%25%s]", u->zoneid);
}
}
else if(urlencode) {
allochost = curl_easy_escape(NULL, u->host, 0);
if(!allochost)
return CURLUE_OUT_OF_MEMORY;
}
else {
/* only encode '%' in output host name */
char *host = u->host;
size_t pcount = 0;
/* first, count number of percents present in the name */
while(*host) {
if(*host == '%')
pcount++;
host++;
}
/* if there were percents, encode the host name */
if(pcount) {
size_t hostlen = strlen(u->host);
size_t alen = hostlen + 2 * pcount + 1;
char *o = allochost = malloc(alen);
if(!allochost)
return CURLUE_OUT_OF_MEMORY;
host = u->host;
while(*host) {
if(*host == '%') {
memcpy(o, "%25", 3);
o += 3;
host++;
continue;
}
*o++ = *host++;
}
*o = '\0';
}
}
url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
scheme,
u->user ? u->user : "",
u->password ? ":": "",
u->password ? u->password : "",
options ? ";" : "",
options ? options : "",
(u->user || u->password || options) ? "@": "",
allochost ? allochost : u->host,
port ? ":": "",
port ? port : "",
(u->path && (u->path[0] != '/')) ? "/": "",
u->path ? u->path : "/",
(u->query && u->query[0]) ? "?": "",
(u->query && u->query[0]) ? u->query : "",
u->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) {
*part = strdup(ptr);
if(!*part)
return CURLUE_OUT_OF_MEMORY;
if(plusdecode) {
/* convert + to space */
char *plus;
for(plus = *part; *plus; ++plus) {
if(*plus == '+')
*plus = ' ';
}
}
if(urldecode) {
char *decoded;
size_t dlen;
/* this unconditional rejection of control bytes is documented
API behavior */
CURLcode res = Curl_urldecode(NULL, *part, 0, &decoded, &dlen,
REJECT_CTRL);
free(*part);
if(res) {
*part = NULL;
return CURLUE_URLDECODE;
}
*part = decoded;
}
return CURLUE_OK;
}
else
return ifmissing;
}
CURLUcode curl_url_set(CURLU *u, CURLUPart what,
const char *part, unsigned int flags)
{
char **storep = NULL;
long port = 0;
bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0;
bool plusencode = FALSE;
bool urlskipslash = FALSE;
bool appendquery = FALSE;
bool equalsencode = FALSE;
if(!u)
return CURLUE_BAD_HANDLE;
if(!part) {
/* setting a part to NULL clears it */
switch(what) {
case CURLUPART_URL:
break;
case CURLUPART_SCHEME:
storep = &u->scheme;
break;
case CURLUPART_USER:
storep = &u->user;
break;
case CURLUPART_PASSWORD:
storep = &u->password;
break;
case CURLUPART_OPTIONS:
storep = &u->options;
break;
case CURLUPART_HOST:
storep = &u->host;
break;
case CURLUPART_ZONEID:
storep = &u->zoneid;
break;
case CURLUPART_PORT:
u->portnum = 0;
storep = &u->port;
break;
case CURLUPART_PATH:
storep = &u->path;
break;
case CURLUPART_QUERY:
storep = &u->query;
break;
case CURLUPART_FRAGMENT:
storep = &u->fragment;
break;
default:
return CURLUE_UNKNOWN_PART;
}
if(storep && *storep) {
Curl_safefree(*storep);
}
return CURLUE_OK;
}
switch(what) {
case CURLUPART_SCHEME:
if(strlen(part) > MAX_SCHEME_LEN)
/* too long */
return CURLUE_MALFORMED_INPUT;
if(!(flags & CURLU_NON_SUPPORT_SCHEME) &&
/* verify that it is a fine scheme */
!Curl_builtin_scheme(part))
return CURLUE_UNSUPPORTED_SCHEME;
storep = &u->scheme;
urlencode = FALSE; /* never */
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: {
size_t len = strcspn(part, " \r\n");
if(strlen(part) != len)
/* hostname with bad content */
return CURLUE_MALFORMED_INPUT;
storep = &u->host;
Curl_safefree(u->zoneid);
break;
}
case CURLUPART_ZONEID:
storep = &u->zoneid;
break;
case CURLUPART_PORT:
{
char *endp;
urlencode = FALSE; /* never */
port = strtol(part, &endp, 10); /* Port number must be decimal */
if((port <= 0) || (port > 0xffff))
return CURLUE_BAD_PORT_NUMBER;
if(*endp)
/* weirdly provided number, not good! */
return CURLUE_MALFORMED_INPUT;
storep = &u->port;
}
break;
case CURLUPART_PATH:
urlskipslash = TRUE;
storep = &u->path;
break;
case CURLUPART_QUERY:
plusencode = urlencode;
appendquery = (flags & CURLU_APPENDQUERY)?1:0;
equalsencode = appendquery;
storep = &u->query;
break;
case CURLUPART_FRAGMENT:
storep = &u->fragment;
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.
*/
CURLUcode result;
char *oldurl;
char *redired_url;
CURLU *handle2;
if(Curl_is_absolute_url(part, NULL, MAX_SCHEME_LEN + 1)) {
handle2 = curl_url();
if(!handle2)
return CURLUE_OUT_OF_MEMORY;
result = parseurl(part, handle2, flags);
if(!result)
mv_urlhandle(handle2, u);
else
curl_url_cleanup(handle2);
return result;
}
/* extract the full "old" URL to do the redirect on */
result = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
if(result) {
/* couldn't get the old URL, just use the new! */
handle2 = curl_url();
if(!handle2)
return CURLUE_OUT_OF_MEMORY;
result = parseurl(part, handle2, flags);
if(!result)
mv_urlhandle(handle2, u);
else
curl_url_cleanup(handle2);
return result;
}
/* apply the relative part to create a new URL */
redired_url = concat_url(oldurl, part);
free(oldurl);
if(!redired_url)
return CURLUE_OUT_OF_MEMORY;
/* now parse the new URL */
handle2 = curl_url();
if(!handle2) {
free(redired_url);
return CURLUE_OUT_OF_MEMORY;
}
result = parseurl(redired_url, handle2, flags);
free(redired_url);
if(!result)
mv_urlhandle(handle2, u);
else
curl_url_cleanup(handle2);
return result;
}
default:
return CURLUE_UNKNOWN_PART;
}
DEBUGASSERT(storep);
{
const char *newp = part;
size_t nalloc = strlen(part);
if(nalloc > CURL_MAX_INPUT_LENGTH)
/* excessive input length */
return CURLUE_MALFORMED_INPUT;
if(urlencode) {
const unsigned char *i;
char *o;
char *enc = malloc(nalloc * 3 + 1); /* for worst case! */
if(!enc)
return CURLUE_OUT_OF_MEMORY;
for(i = (const unsigned char *)part, o = enc; *i; i++) {
if((*i == ' ') && plusencode) {
*o = '+';
o++;
}
else if(Curl_isunreserved(*i) ||
((*i == '/') && urlskipslash) ||
((*i == '=') && equalsencode)) {
if((*i == '=') && equalsencode)
/* only skip the first equals sign */
equalsencode = FALSE;
*o = *i;
o++;
}
else {
msnprintf(o, 4, "%%%02x", *i);
o += 3;
}
}
*o = 0; /* null-terminate */
newp = enc;
}
else {
char *p;
newp = strdup(part);
if(!newp)
return CURLUE_OUT_OF_MEMORY;
p = (char *)newp;
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] = (char)TOLOWER(p[1]);
p[2] = (char)TOLOWER(p[2]);
p += 3;
}
else
p++;
}
}
if(appendquery) {
/* Append the string onto the old query. Add a '&' separator if none is
present at the end of the exsting query already */
size_t querylen = u->query ? strlen(u->query) : 0;
bool addamperand = querylen && (u->query[querylen -1] != '&');
if(querylen) {
size_t newplen = strlen(newp);
char *p = malloc(querylen + addamperand + newplen + 1);
if(!p) {
free((char *)newp);
return CURLUE_OUT_OF_MEMORY;
}
strcpy(p, u->query); /* original query */
if(addamperand)
p[querylen] = '&'; /* ampersand */
strcpy(&p[querylen + addamperand], newp); /* new suffix */
free((char *)newp);
free(*storep);
*storep = p;
return CURLUE_OK;
}
}
if(what == CURLUPART_HOST) {
if(0 == strlen(newp) && (flags & CURLU_NO_AUTHORITY)) {
/* Skip hostname check, it's allowed to be empty. */
}
else {
if(hostname_check(u, (char *)newp)) {
free((char *)newp);
return CURLUE_MALFORMED_INPUT;
}
}
}
free(*storep);
*storep = (char *)newp;
}
/* set after the string, to make it not assigned if the allocation above
fails */
if(port)
u->portnum = port;
return CURLUE_OK;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/mime.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "mime.h"
#include "non-ascii.h"
#include "warnless.h"
#include "urldata.h"
#include "sendf.h"
#if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)) || \
!defined(CURL_DISABLE_SMTP) || !defined(CURL_DISABLE_IMAP)
#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
#include <libgen.h>
#endif
#include "rand.h"
#include "slist.h"
#include "strcase.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#ifdef WIN32
# ifndef R_OK
# define R_OK 4
# endif
#endif
#define READ_ERROR ((size_t) -1)
#define STOP_FILLING ((size_t) -2)
static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
void *instream, bool *hasread);
/* Encoders. */
static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part);
static curl_off_t encoder_nop_size(curl_mimepart *part);
static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part);
static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part);
static curl_off_t encoder_base64_size(curl_mimepart *part);
static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part);
static curl_off_t encoder_qp_size(curl_mimepart *part);
static const struct mime_encoder encoders[] = {
{"binary", encoder_nop_read, encoder_nop_size},
{"8bit", encoder_nop_read, encoder_nop_size},
{"7bit", encoder_7bit_read, encoder_nop_size},
{"base64", encoder_base64_read, encoder_base64_size},
{"quoted-printable", encoder_qp_read, encoder_qp_size},
{ZERO_NULL, ZERO_NULL, ZERO_NULL}
};
/* Base64 encoding table */
static const char base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* Quoted-printable character class table.
*
* We cannot rely on ctype functions since quoted-printable input data
* is assumed to be ascii-compatible, even on non-ascii platforms. */
#define QP_OK 1 /* Can be represented by itself. */
#define QP_SP 2 /* Space or tab. */
#define QP_CR 3 /* Carriage return. */
#define QP_LF 4 /* Line-feed. */
static const unsigned char qp_class[] = {
0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 07 */
0, QP_SP, QP_LF, 0, 0, QP_CR, 0, 0, /* 08 - 0F */
0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 17 */
0, 0, 0, 0, 0, 0, 0, 0, /* 18 - 1F */
QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 20 - 27 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 28 - 2F */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 30 - 37 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0 , QP_OK, QP_OK, /* 38 - 3F */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 40 - 47 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 48 - 4F */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 50 - 57 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 58 - 5F */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 60 - 67 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 68 - 6F */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 70 - 77 */
QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0, /* 78 - 7F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
};
/* Binary --> hexadecimal ASCII table. */
static const char aschex[] =
"\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46";
#ifndef __VMS
#define filesize(name, stat_data) (stat_data.st_size)
#define fopen_read fopen
#else
#include <fabdef.h>
/*
* get_vms_file_size does what it takes to get the real size of the file
*
* For fixed files, find out the size of the EOF block and adjust.
*
* For all others, have to read the entire file in, discarding the contents.
* Most posted text files will be small, and binary files like zlib archives
* and CD/DVD images should be either a STREAM_LF format or a fixed format.
*
*/
curl_off_t VmsRealFileSize(const char *name,
const struct_stat *stat_buf)
{
char buffer[8192];
curl_off_t count;
int ret_stat;
FILE * file;
file = fopen(name, FOPEN_READTEXT); /* VMS */
if(!file)
return 0;
count = 0;
ret_stat = 1;
while(ret_stat > 0) {
ret_stat = fread(buffer, 1, sizeof(buffer), file);
if(ret_stat)
count += ret_stat;
}
fclose(file);
return count;
}
/*
*
* VmsSpecialSize checks to see if the stat st_size can be trusted and
* if not to call a routine to get the correct size.
*
*/
static curl_off_t VmsSpecialSize(const char *name,
const struct_stat *stat_buf)
{
switch(stat_buf->st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
return VmsRealFileSize(name, stat_buf);
break;
default:
return stat_buf->st_size;
}
}
#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data)
/*
* vmsfopenread
*
* For upload to work as expected on VMS, different optional
* parameters must be added to the fopen command based on
* record format of the file.
*
*/
static FILE * vmsfopenread(const char *file, const char *mode)
{
struct_stat statbuf;
int result;
result = stat(file, &statbuf);
switch(statbuf.st_fab_rfm) {
case FAB$C_VAR:
case FAB$C_VFC:
case FAB$C_STMCR:
return fopen(file, FOPEN_READTEXT); /* VMS */
break;
default:
return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm");
}
}
#define fopen_read vmsfopenread
#endif
#ifndef HAVE_BASENAME
/*
(Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
Edition)
The basename() function shall take the pathname pointed to by path and
return a pointer to the final component of the pathname, deleting any
trailing '/' characters.
If the string pointed to by path consists entirely of the '/' character,
basename() shall return a pointer to the string "/". If the string pointed
to by path is exactly "//", it is implementation-defined whether '/' or "//"
is returned.
If path is a null pointer or points to an empty string, basename() shall
return a pointer to the string ".".
The basename() function may modify the string pointed to by path, and may
return a pointer to static storage that may then be overwritten by a
subsequent call to basename().
The basename() function need not be reentrant. A function that is not
required to be reentrant is not required to be thread-safe.
*/
static char *Curl_basename(char *path)
{
/* Ignore all the details above for now and make a quick and simple
implementation here */
char *s1;
char *s2;
s1 = strrchr(path, '/');
s2 = strrchr(path, '\\');
if(s1 && s2) {
path = (s1 > s2? s1 : s2) + 1;
}
else if(s1)
path = s1 + 1;
else if(s2)
path = s2 + 1;
return path;
}
#define basename(x) Curl_basename((x))
#endif
/* Set readback state. */
static void mimesetstate(struct mime_state *state,
enum mimestate tok, void *ptr)
{
state->state = tok;
state->ptr = ptr;
state->offset = 0;
}
/* Escape header string into allocated memory. */
static char *escape_string(const char *src)
{
size_t bytecount = 0;
size_t i;
char *dst;
for(i = 0; src[i]; i++)
if(src[i] == '"' || src[i] == '\\')
bytecount++;
bytecount += i;
dst = malloc(bytecount + 1);
if(!dst)
return NULL;
for(i = 0; *src; src++) {
if(*src == '"' || *src == '\\')
dst[i++] = '\\';
dst[i++] = *src;
}
dst[i] = '\0';
return dst;
}
/* Check if header matches. */
static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len)
{
char *value = NULL;
if(strncasecompare(hdr->data, lbl, len) && hdr->data[len] == ':')
for(value = hdr->data + len + 1; *value == ' '; value++)
;
return value;
}
/* Get a header from an slist. */
static char *search_header(struct curl_slist *hdrlist, const char *hdr)
{
size_t len = strlen(hdr);
char *value = NULL;
for(; !value && hdrlist; hdrlist = hdrlist->next)
value = match_header(hdrlist, hdr, len);
return value;
}
static char *strippath(const char *fullfile)
{
char *filename;
char *base;
filename = strdup(fullfile); /* duplicate since basename() may ruin the
buffer it works on */
if(!filename)
return NULL;
base = strdup(basename(filename));
free(filename); /* free temporary buffer */
return base; /* returns an allocated string or NULL ! */
}
/* Initialize data encoder state. */
static void cleanup_encoder_state(struct mime_encoder_state *p)
{
p->pos = 0;
p->bufbeg = 0;
p->bufend = 0;
}
/* Dummy encoder. This is used for 8bit and binary content encodings. */
static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
struct curl_mimepart *part)
{
struct mime_encoder_state *st = &part->encstate;
size_t insize = st->bufend - st->bufbeg;
(void) ateof;
if(!size)
return STOP_FILLING;
if(size > insize)
size = insize;
if(size)
memcpy(buffer, st->buf + st->bufbeg, size);
st->bufbeg += size;
return size;
}
static curl_off_t encoder_nop_size(curl_mimepart *part)
{
return part->datasize;
}
/* 7bit encoder: the encoder is just a data validity check. */
static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part)
{
struct mime_encoder_state *st = &part->encstate;
size_t cursize = st->bufend - st->bufbeg;
(void) ateof;
if(!size)
return STOP_FILLING;
if(size > cursize)
size = cursize;
for(cursize = 0; cursize < size; cursize++) {
*buffer = st->buf[st->bufbeg];
if(*buffer++ & 0x80)
return cursize? cursize: READ_ERROR;
st->bufbeg++;
}
return cursize;
}
/* Base64 content encoder. */
static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part)
{
struct mime_encoder_state *st = &part->encstate;
size_t cursize = 0;
int i;
char *ptr = buffer;
while(st->bufbeg < st->bufend) {
/* Line full ? */
if(st->pos > MAX_ENCODED_LINE_LENGTH - 4) {
/* Yes, we need 2 characters for CRLF. */
if(size < 2) {
if(!cursize)
return STOP_FILLING;
break;
}
*ptr++ = '\r';
*ptr++ = '\n';
st->pos = 0;
cursize += 2;
size -= 2;
}
/* Be sure there is enough space and input data for a base64 group. */
if(size < 4) {
if(!cursize)
return STOP_FILLING;
break;
}
if(st->bufend - st->bufbeg < 3)
break;
/* Encode three bytes as four characters. */
i = st->buf[st->bufbeg++] & 0xFF;
i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
*ptr++ = base64[(i >> 18) & 0x3F];
*ptr++ = base64[(i >> 12) & 0x3F];
*ptr++ = base64[(i >> 6) & 0x3F];
*ptr++ = base64[i & 0x3F];
cursize += 4;
st->pos += 4;
size -= 4;
}
/* If at eof, we have to flush the buffered data. */
if(ateof) {
if(size < 4) {
if(!cursize)
return STOP_FILLING;
}
else {
/* Buffered data size can only be 0, 1 or 2. */
ptr[2] = ptr[3] = '=';
i = 0;
/* If there is buffered data */
if(st->bufend != st->bufbeg) {
if(st->bufend - st->bufbeg == 2)
i = (st->buf[st->bufbeg + 1] & 0xFF) << 8;
i |= (st->buf[st->bufbeg] & 0xFF) << 16;
ptr[0] = base64[(i >> 18) & 0x3F];
ptr[1] = base64[(i >> 12) & 0x3F];
if(++st->bufbeg != st->bufend) {
ptr[2] = base64[(i >> 6) & 0x3F];
st->bufbeg++;
}
cursize += 4;
st->pos += 4;
}
}
}
#ifdef CURL_DOES_CONVERSIONS
/* This is now textual data, Convert character codes. */
if(part->easy && cursize) {
CURLcode result = Curl_convert_to_network(part->easy, buffer, cursize);
if(result)
return READ_ERROR;
}
#endif
return cursize;
}
static curl_off_t encoder_base64_size(curl_mimepart *part)
{
curl_off_t size = part->datasize;
if(size <= 0)
return size; /* Unknown size or no data. */
/* Compute base64 character count. */
size = 4 * (1 + (size - 1) / 3);
/* Effective character count must include CRLFs. */
return size + 2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH);
}
/* Quoted-printable lookahead.
*
* Check if a CRLF or end of data is in input buffer at current position + n.
* Return -1 if more data needed, 1 if CRLF or end of data, else 0.
*/
static int qp_lookahead_eol(struct mime_encoder_state *st, int ateof, size_t n)
{
n += st->bufbeg;
if(n >= st->bufend && ateof)
return 1;
if(n + 2 > st->bufend)
return ateof? 0: -1;
if(qp_class[st->buf[n] & 0xFF] == QP_CR &&
qp_class[st->buf[n + 1] & 0xFF] == QP_LF)
return 1;
return 0;
}
/* Quoted-printable encoder. */
static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
curl_mimepart *part)
{
struct mime_encoder_state *st = &part->encstate;
char *ptr = buffer;
size_t cursize = 0;
int softlinebreak;
char buf[4];
/* On all platforms, input is supposed to be ASCII compatible: for this
reason, we use hexadecimal ASCII codes in this function rather than
character constants that can be interpreted as non-ascii on some
platforms. Preserve ASCII encoding on output too. */
while(st->bufbeg < st->bufend) {
size_t len = 1;
size_t consumed = 1;
int i = st->buf[st->bufbeg];
buf[0] = (char) i;
buf[1] = aschex[(i >> 4) & 0xF];
buf[2] = aschex[i & 0xF];
switch(qp_class[st->buf[st->bufbeg] & 0xFF]) {
case QP_OK: /* Not a special character. */
break;
case QP_SP: /* Space or tab. */
/* Spacing must be escaped if followed by CRLF. */
switch(qp_lookahead_eol(st, ateof, 1)) {
case -1: /* More input data needed. */
return cursize;
case 0: /* No encoding needed. */
break;
default: /* CRLF after space or tab. */
buf[0] = '\x3D'; /* '=' */
len = 3;
break;
}
break;
case QP_CR: /* Carriage return. */
/* If followed by a line-feed, output the CRLF pair.
Else escape it. */
switch(qp_lookahead_eol(st, ateof, 0)) {
case -1: /* Need more data. */
return cursize;
case 1: /* CRLF found. */
buf[len++] = '\x0A'; /* Append '\n'. */
consumed = 2;
break;
default: /* Not followed by LF: escape. */
buf[0] = '\x3D'; /* '=' */
len = 3;
break;
}
break;
default: /* Character must be escaped. */
buf[0] = '\x3D'; /* '=' */
len = 3;
break;
}
/* Be sure the encoded character fits within maximum line length. */
if(buf[len - 1] != '\x0A') { /* '\n' */
softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH;
if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) {
/* We may use the current line only if end of data or followed by
a CRLF. */
switch(qp_lookahead_eol(st, ateof, consumed)) {
case -1: /* Need more data. */
return cursize;
case 0: /* Not followed by a CRLF. */
softlinebreak = 1;
break;
}
}
if(softlinebreak) {
strcpy(buf, "\x3D\x0D\x0A"); /* "=\r\n" */
len = 3;
consumed = 0;
}
}
/* If the output buffer would overflow, do not store. */
if(len > size) {
if(!cursize)
return STOP_FILLING;
break;
}
/* Append to output buffer. */
memcpy(ptr, buf, len);
cursize += len;
ptr += len;
size -= len;
st->pos += len;
if(buf[len - 1] == '\x0A') /* '\n' */
st->pos = 0;
st->bufbeg += consumed;
}
return cursize;
}
static curl_off_t encoder_qp_size(curl_mimepart *part)
{
/* Determining the size can only be done by reading the data: unless the
data size is 0, we return it as unknown (-1). */
return part->datasize? -1: 0;
}
/* In-memory data callbacks. */
/* Argument is a pointer to the mime part. */
static size_t mime_mem_read(char *buffer, size_t size, size_t nitems,
void *instream)
{
curl_mimepart *part = (curl_mimepart *) instream;
size_t sz = curlx_sotouz(part->datasize - part->state.offset);
(void) size; /* Always 1.*/
if(!nitems)
return STOP_FILLING;
if(sz > nitems)
sz = nitems;
if(sz)
memcpy(buffer, part->data + curlx_sotouz(part->state.offset), sz);
return sz;
}
static int mime_mem_seek(void *instream, curl_off_t offset, int whence)
{
curl_mimepart *part = (curl_mimepart *) instream;
switch(whence) {
case SEEK_CUR:
offset += part->state.offset;
break;
case SEEK_END:
offset += part->datasize;
break;
}
if(offset < 0 || offset > part->datasize)
return CURL_SEEKFUNC_FAIL;
part->state.offset = offset;
return CURL_SEEKFUNC_OK;
}
static void mime_mem_free(void *ptr)
{
Curl_safefree(((curl_mimepart *) ptr)->data);
}
/* Named file callbacks. */
/* Argument is a pointer to the mime part. */
static int mime_open_file(curl_mimepart *part)
{
/* Open a MIMEKIND_FILE part. */
if(part->fp)
return 0;
part->fp = fopen_read(part->data, "rb");
return part->fp? 0: -1;
}
static size_t mime_file_read(char *buffer, size_t size, size_t nitems,
void *instream)
{
curl_mimepart *part = (curl_mimepart *) instream;
if(!nitems)
return STOP_FILLING;
if(mime_open_file(part))
return READ_ERROR;
return fread(buffer, size, nitems, part->fp);
}
static int mime_file_seek(void *instream, curl_off_t offset, int whence)
{
curl_mimepart *part = (curl_mimepart *) instream;
if(whence == SEEK_SET && !offset && !part->fp)
return CURL_SEEKFUNC_OK; /* Not open: implicitly already at BOF. */
if(mime_open_file(part))
return CURL_SEEKFUNC_FAIL;
return fseek(part->fp, (long) offset, whence)?
CURL_SEEKFUNC_CANTSEEK: CURL_SEEKFUNC_OK;
}
static void mime_file_free(void *ptr)
{
curl_mimepart *part = (curl_mimepart *) ptr;
if(part->fp) {
fclose(part->fp);
part->fp = NULL;
}
Curl_safefree(part->data);
part->data = NULL;
}
/* Subparts callbacks. */
/* Argument is a pointer to the mime structure. */
/* Readback a byte string segment. */
static size_t readback_bytes(struct mime_state *state,
char *buffer, size_t bufsize,
const char *bytes, size_t numbytes,
const char *trail)
{
size_t sz;
size_t offset = curlx_sotouz(state->offset);
if(numbytes > offset) {
sz = numbytes - offset;
bytes += offset;
}
else {
size_t tsz = strlen(trail);
sz = offset - numbytes;
if(sz >= tsz)
return 0;
bytes = trail + sz;
sz = tsz - sz;
}
if(sz > bufsize)
sz = bufsize;
memcpy(buffer, bytes, sz);
state->offset += sz;
return sz;
}
/* Read a non-encoded part content. */
static size_t read_part_content(curl_mimepart *part,
char *buffer, size_t bufsize, bool *hasread)
{
size_t sz = 0;
switch(part->lastreadstatus) {
case 0:
case CURL_READFUNC_ABORT:
case CURL_READFUNC_PAUSE:
case READ_ERROR:
return part->lastreadstatus;
default:
break;
}
/* If we can determine we are at end of part data, spare a read. */
if(part->datasize != (curl_off_t) -1 &&
part->state.offset >= part->datasize) {
/* sz is already zero. */
}
else {
switch(part->kind) {
case MIMEKIND_MULTIPART:
/*
* Cannot be processed as other kinds since read function requires
* an additional parameter and is highly recursive.
*/
sz = mime_subparts_read(buffer, 1, bufsize, part->arg, hasread);
break;
case MIMEKIND_FILE:
if(part->fp && feof(part->fp))
break; /* At EOF. */
/* FALLTHROUGH */
default:
if(part->readfunc) {
if(!(part->flags & MIME_FAST_READ)) {
if(*hasread)
return STOP_FILLING;
*hasread = TRUE;
}
sz = part->readfunc(buffer, 1, bufsize, part->arg);
}
break;
}
}
switch(sz) {
case STOP_FILLING:
break;
case 0:
case CURL_READFUNC_ABORT:
case CURL_READFUNC_PAUSE:
case READ_ERROR:
part->lastreadstatus = sz;
break;
default:
part->state.offset += sz;
part->lastreadstatus = sz;
break;
}
return sz;
}
/* Read and encode part content. */
static size_t read_encoded_part_content(curl_mimepart *part, char *buffer,
size_t bufsize, bool *hasread)
{
struct mime_encoder_state *st = &part->encstate;
size_t cursize = 0;
size_t sz;
bool ateof = FALSE;
for(;;) {
if(st->bufbeg < st->bufend || ateof) {
/* Encode buffered data. */
sz = part->encoder->encodefunc(buffer, bufsize, ateof, part);
switch(sz) {
case 0:
if(ateof)
return cursize;
break;
case READ_ERROR:
case STOP_FILLING:
return cursize? cursize: sz;
default:
cursize += sz;
buffer += sz;
bufsize -= sz;
continue;
}
}
/* We need more data in input buffer. */
if(st->bufbeg) {
size_t len = st->bufend - st->bufbeg;
if(len)
memmove(st->buf, st->buf + st->bufbeg, len);
st->bufbeg = 0;
st->bufend = len;
}
if(st->bufend >= sizeof(st->buf))
return cursize? cursize: READ_ERROR; /* Buffer full. */
sz = read_part_content(part, st->buf + st->bufend,
sizeof(st->buf) - st->bufend, hasread);
switch(sz) {
case 0:
ateof = TRUE;
break;
case CURL_READFUNC_ABORT:
case CURL_READFUNC_PAUSE:
case READ_ERROR:
case STOP_FILLING:
return cursize? cursize: sz;
default:
st->bufend += sz;
break;
}
}
/* NOTREACHED */
}
/* Readback a mime part. */
static size_t readback_part(curl_mimepart *part,
char *buffer, size_t bufsize, bool *hasread)
{
size_t cursize = 0;
#ifdef CURL_DOES_CONVERSIONS
char *convbuf = buffer;
#endif
/* Readback from part. */
while(bufsize) {
size_t sz = 0;
struct curl_slist *hdr = (struct curl_slist *) part->state.ptr;
switch(part->state.state) {
case MIMESTATE_BEGIN:
mimesetstate(&part->state,
(part->flags & MIME_BODY_ONLY)?
MIMESTATE_BODY: MIMESTATE_CURLHEADERS,
part->curlheaders);
break;
case MIMESTATE_USERHEADERS:
if(!hdr) {
mimesetstate(&part->state, MIMESTATE_EOH, NULL);
break;
}
if(match_header(hdr, "Content-Type", 12)) {
mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next);
break;
}
/* FALLTHROUGH */
case MIMESTATE_CURLHEADERS:
if(!hdr)
mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders);
else {
sz = readback_bytes(&part->state, buffer, bufsize,
hdr->data, strlen(hdr->data), "\r\n");
if(!sz)
mimesetstate(&part->state, part->state.state, hdr->next);
}
break;
case MIMESTATE_EOH:
sz = readback_bytes(&part->state, buffer, bufsize, "\r\n", 2, "");
if(!sz)
mimesetstate(&part->state, MIMESTATE_BODY, NULL);
break;
case MIMESTATE_BODY:
#ifdef CURL_DOES_CONVERSIONS
if(part->easy && convbuf < buffer) {
CURLcode result = Curl_convert_to_network(part->easy, convbuf,
buffer - convbuf);
if(result)
return READ_ERROR;
convbuf = buffer;
}
#endif
cleanup_encoder_state(&part->encstate);
mimesetstate(&part->state, MIMESTATE_CONTENT, NULL);
break;
case MIMESTATE_CONTENT:
if(part->encoder)
sz = read_encoded_part_content(part, buffer, bufsize, hasread);
else
sz = read_part_content(part, buffer, bufsize, hasread);
switch(sz) {
case 0:
mimesetstate(&part->state, MIMESTATE_END, NULL);
/* Try sparing open file descriptors. */
if(part->kind == MIMEKIND_FILE && part->fp) {
fclose(part->fp);
part->fp = NULL;
}
/* FALLTHROUGH */
case CURL_READFUNC_ABORT:
case CURL_READFUNC_PAUSE:
case READ_ERROR:
case STOP_FILLING:
return cursize? cursize: sz;
}
break;
case MIMESTATE_END:
return cursize;
default:
break; /* Other values not in part state. */
}
/* Bump buffer and counters according to read size. */
cursize += sz;
buffer += sz;
bufsize -= sz;
}
#ifdef CURL_DOES_CONVERSIONS
if(part->easy && convbuf < buffer &&
part->state.state < MIMESTATE_BODY) {
CURLcode result = Curl_convert_to_network(part->easy, convbuf,
buffer - convbuf);
if(result)
return READ_ERROR;
}
#endif
return cursize;
}
/* Readback from mime. Warning: not a read callback function. */
static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
void *instream, bool *hasread)
{
curl_mime *mime = (curl_mime *) instream;
size_t cursize = 0;
#ifdef CURL_DOES_CONVERSIONS
char *convbuf = buffer;
#endif
(void) size; /* Always 1. */
while(nitems) {
size_t sz = 0;
curl_mimepart *part = mime->state.ptr;
switch(mime->state.state) {
case MIMESTATE_BEGIN:
case MIMESTATE_BODY:
#ifdef CURL_DOES_CONVERSIONS
convbuf = buffer;
#endif
mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart);
/* The first boundary always follows the header termination empty line,
so is always preceded by a CRLF. We can then spare 2 characters
by skipping the leading CRLF in boundary. */
mime->state.offset += 2;
break;
case MIMESTATE_BOUNDARY1:
sz = readback_bytes(&mime->state, buffer, nitems, "\r\n--", 4, "");
if(!sz)
mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part);
break;
case MIMESTATE_BOUNDARY2:
sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary,
strlen(mime->boundary), part? "\r\n": "--\r\n");
if(!sz) {
#ifdef CURL_DOES_CONVERSIONS
if(mime->easy && convbuf < buffer) {
CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
buffer - convbuf);
if(result)
return READ_ERROR;
convbuf = buffer;
}
#endif
mimesetstate(&mime->state, MIMESTATE_CONTENT, part);
}
break;
case MIMESTATE_CONTENT:
if(!part) {
mimesetstate(&mime->state, MIMESTATE_END, NULL);
break;
}
sz = readback_part(part, buffer, nitems, hasread);
switch(sz) {
case CURL_READFUNC_ABORT:
case CURL_READFUNC_PAUSE:
case READ_ERROR:
case STOP_FILLING:
return cursize? cursize: sz;
case 0:
#ifdef CURL_DOES_CONVERSIONS
convbuf = buffer;
#endif
mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart);
break;
}
break;
case MIMESTATE_END:
return cursize;
default:
break; /* other values not used in mime state. */
}
/* Bump buffer and counters according to read size. */
cursize += sz;
buffer += sz;
nitems -= sz;
}
#ifdef CURL_DOES_CONVERSIONS
if(mime->easy && convbuf < buffer &&
mime->state.state <= MIMESTATE_CONTENT) {
CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
buffer - convbuf);
if(result)
return READ_ERROR;
}
#endif
return cursize;
}
static int mime_part_rewind(curl_mimepart *part)
{
int res = CURL_SEEKFUNC_OK;
enum mimestate targetstate = MIMESTATE_BEGIN;
if(part->flags & MIME_BODY_ONLY)
targetstate = MIMESTATE_BODY;
cleanup_encoder_state(&part->encstate);
if(part->state.state > targetstate) {
res = CURL_SEEKFUNC_CANTSEEK;
if(part->seekfunc) {
res = part->seekfunc(part->arg, (curl_off_t) 0, SEEK_SET);
switch(res) {
case CURL_SEEKFUNC_OK:
case CURL_SEEKFUNC_FAIL:
case CURL_SEEKFUNC_CANTSEEK:
break;
case -1: /* For fseek() error. */
res = CURL_SEEKFUNC_CANTSEEK;
break;
default:
res = CURL_SEEKFUNC_FAIL;
break;
}
}
}
if(res == CURL_SEEKFUNC_OK)
mimesetstate(&part->state, targetstate, NULL);
part->lastreadstatus = 1; /* Successful read status. */
return res;
}
static int mime_subparts_seek(void *instream, curl_off_t offset, int whence)
{
curl_mime *mime = (curl_mime *) instream;
curl_mimepart *part;
int result = CURL_SEEKFUNC_OK;
if(whence != SEEK_SET || offset)
return CURL_SEEKFUNC_CANTSEEK; /* Only support full rewind. */
if(mime->state.state == MIMESTATE_BEGIN)
return CURL_SEEKFUNC_OK; /* Already rewound. */
for(part = mime->firstpart; part; part = part->nextpart) {
int res = mime_part_rewind(part);
if(res != CURL_SEEKFUNC_OK)
result = res;
}
if(result == CURL_SEEKFUNC_OK)
mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
return result;
}
/* Release part content. */
static void cleanup_part_content(curl_mimepart *part)
{
if(part->freefunc)
part->freefunc(part->arg);
part->readfunc = NULL;
part->seekfunc = NULL;
part->freefunc = NULL;
part->arg = (void *) part; /* Defaults to part itself. */
part->data = NULL;
part->fp = NULL;
part->datasize = (curl_off_t) 0; /* No size yet. */
cleanup_encoder_state(&part->encstate);
part->kind = MIMEKIND_NONE;
part->flags &= ~MIME_FAST_READ;
part->lastreadstatus = 1; /* Successful read status. */
part->state.state = MIMESTATE_BEGIN;
}
static void mime_subparts_free(void *ptr)
{
curl_mime *mime = (curl_mime *) ptr;
if(mime && mime->parent) {
mime->parent->freefunc = NULL; /* Be sure we won't be called again. */
cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */
}
curl_mime_free(mime);
}
/* Do not free subparts: unbind them. This is used for the top level only. */
static void mime_subparts_unbind(void *ptr)
{
curl_mime *mime = (curl_mime *) ptr;
if(mime && mime->parent) {
mime->parent->freefunc = NULL; /* Be sure we won't be called again. */
cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */
mime->parent = NULL;
}
}
void Curl_mime_cleanpart(curl_mimepart *part)
{
cleanup_part_content(part);
curl_slist_free_all(part->curlheaders);
if(part->flags & MIME_USERHEADERS_OWNER)
curl_slist_free_all(part->userheaders);
Curl_safefree(part->mimetype);
Curl_safefree(part->name);
Curl_safefree(part->filename);
Curl_mime_initpart(part, part->easy);
}
/* Recursively delete a mime handle and its parts. */
void curl_mime_free(curl_mime *mime)
{
curl_mimepart *part;
if(mime) {
mime_subparts_unbind(mime); /* Be sure it's not referenced anymore. */
while(mime->firstpart) {
part = mime->firstpart;
mime->firstpart = part->nextpart;
Curl_mime_cleanpart(part);
free(part);
}
free(mime);
}
}
CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src)
{
curl_mime *mime;
curl_mimepart *d;
const curl_mimepart *s;
CURLcode res = CURLE_OK;
DEBUGASSERT(dst);
/* Duplicate content. */
switch(src->kind) {
case MIMEKIND_NONE:
break;
case MIMEKIND_DATA:
res = curl_mime_data(dst, src->data, (size_t) src->datasize);
break;
case MIMEKIND_FILE:
res = curl_mime_filedata(dst, src->data);
/* Do not abort duplication if file is not readable. */
if(res == CURLE_READ_ERROR)
res = CURLE_OK;
break;
case MIMEKIND_CALLBACK:
res = curl_mime_data_cb(dst, src->datasize, src->readfunc,
src->seekfunc, src->freefunc, src->arg);
break;
case MIMEKIND_MULTIPART:
/* No one knows about the cloned subparts, thus always attach ownership
to the part. */
mime = curl_mime_init(dst->easy);
res = mime? curl_mime_subparts(dst, mime): CURLE_OUT_OF_MEMORY;
/* Duplicate subparts. */
for(s = ((curl_mime *) src->arg)->firstpart; !res && s; s = s->nextpart) {
d = curl_mime_addpart(mime);
res = d? Curl_mime_duppart(d, s): CURLE_OUT_OF_MEMORY;
}
break;
default: /* Invalid kind: should not occur. */
res = CURLE_BAD_FUNCTION_ARGUMENT; /* Internal error? */
break;
}
/* Duplicate headers. */
if(!res && src->userheaders) {
struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders);
if(!hdrs)
res = CURLE_OUT_OF_MEMORY;
else {
/* No one but this procedure knows about the new header list,
so always take ownership. */
res = curl_mime_headers(dst, hdrs, TRUE);
if(res)
curl_slist_free_all(hdrs);
}
}
if(!res) {
/* Duplicate other fields. */
dst->encoder = src->encoder;
res = curl_mime_type(dst, src->mimetype);
}
if(!res)
res = curl_mime_name(dst, src->name);
if(!res)
res = curl_mime_filename(dst, src->filename);
/* If an error occurred, rollback. */
if(res)
Curl_mime_cleanpart(dst);
return res;
}
/*
* Mime build functions.
*/
/* Create a mime handle. */
curl_mime *curl_mime_init(struct Curl_easy *easy)
{
curl_mime *mime;
mime = (curl_mime *) malloc(sizeof(*mime));
if(mime) {
mime->easy = easy;
mime->parent = NULL;
mime->firstpart = NULL;
mime->lastpart = NULL;
memset(mime->boundary, '-', 24);
if(Curl_rand_hex(easy, (unsigned char *) &mime->boundary[24],
MIME_RAND_BOUNDARY_CHARS + 1)) {
/* failed to get random separator, bail out */
free(mime);
return NULL;
}
mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
}
return mime;
}
/* Initialize a mime part. */
void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy)
{
memset((char *) part, 0, sizeof(*part));
part->easy = easy;
part->lastreadstatus = 1; /* Successful read status. */
mimesetstate(&part->state, MIMESTATE_BEGIN, NULL);
}
/* Create a mime part and append it to a mime handle's part list. */
curl_mimepart *curl_mime_addpart(curl_mime *mime)
{
curl_mimepart *part;
if(!mime)
return NULL;
part = (curl_mimepart *) malloc(sizeof(*part));
if(part) {
Curl_mime_initpart(part, mime->easy);
part->parent = mime;
if(mime->lastpart)
mime->lastpart->nextpart = part;
else
mime->firstpart = part;
mime->lastpart = part;
}
return part;
}
/* Set mime part name. */
CURLcode curl_mime_name(curl_mimepart *part, const char *name)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
Curl_safefree(part->name);
part->name = NULL;
if(name) {
part->name = strdup(name);
if(!part->name)
return CURLE_OUT_OF_MEMORY;
}
return CURLE_OK;
}
/* Set mime part remote file name. */
CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
Curl_safefree(part->filename);
part->filename = NULL;
if(filename) {
part->filename = strdup(filename);
if(!part->filename)
return CURLE_OUT_OF_MEMORY;
}
return CURLE_OK;
}
/* Set mime part content from memory data. */
CURLcode curl_mime_data(curl_mimepart *part,
const char *data, size_t datasize)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
cleanup_part_content(part);
if(data) {
if(datasize == CURL_ZERO_TERMINATED)
datasize = strlen(data);
part->data = malloc(datasize + 1);
if(!part->data)
return CURLE_OUT_OF_MEMORY;
part->datasize = datasize;
if(datasize)
memcpy(part->data, data, datasize);
part->data[datasize] = '\0'; /* Set a null terminator as sentinel. */
part->readfunc = mime_mem_read;
part->seekfunc = mime_mem_seek;
part->freefunc = mime_mem_free;
part->flags |= MIME_FAST_READ;
part->kind = MIMEKIND_DATA;
}
return CURLE_OK;
}
/* Set mime part content from named local file. */
CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
{
CURLcode result = CURLE_OK;
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
cleanup_part_content(part);
if(filename) {
char *base;
struct_stat sbuf;
if(stat(filename, &sbuf) || access(filename, R_OK))
result = CURLE_READ_ERROR;
part->data = strdup(filename);
if(!part->data)
result = CURLE_OUT_OF_MEMORY;
part->datasize = -1;
if(!result && S_ISREG(sbuf.st_mode)) {
part->datasize = filesize(filename, sbuf);
part->seekfunc = mime_file_seek;
}
part->readfunc = mime_file_read;
part->freefunc = mime_file_free;
part->kind = MIMEKIND_FILE;
/* As a side effect, set the filename to the current file's base name.
It is possible to withdraw this by explicitly calling
curl_mime_filename() with a NULL filename argument after the current
call. */
base = strippath(filename);
if(!base)
result = CURLE_OUT_OF_MEMORY;
else {
CURLcode res = curl_mime_filename(part, base);
if(res)
result = res;
free(base);
}
}
return result;
}
/* Set mime part type. */
CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
Curl_safefree(part->mimetype);
part->mimetype = NULL;
if(mimetype) {
part->mimetype = strdup(mimetype);
if(!part->mimetype)
return CURLE_OUT_OF_MEMORY;
}
return CURLE_OK;
}
/* Set mime data transfer encoder. */
CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
{
CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
const struct mime_encoder *mep;
if(!part)
return result;
part->encoder = NULL;
if(!encoding)
return CURLE_OK; /* Removing current encoder. */
for(mep = encoders; mep->name; mep++)
if(strcasecompare(encoding, mep->name)) {
part->encoder = mep;
result = CURLE_OK;
}
return result;
}
/* Set mime part headers. */
CURLcode curl_mime_headers(curl_mimepart *part,
struct curl_slist *headers, int take_ownership)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
if(part->flags & MIME_USERHEADERS_OWNER) {
if(part->userheaders != headers) /* Allow setting twice the same list. */
curl_slist_free_all(part->userheaders);
part->flags &= ~MIME_USERHEADERS_OWNER;
}
part->userheaders = headers;
if(headers && take_ownership)
part->flags |= MIME_USERHEADERS_OWNER;
return CURLE_OK;
}
/* Set mime part content from callback. */
CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize,
curl_read_callback readfunc,
curl_seek_callback seekfunc,
curl_free_callback freefunc, void *arg)
{
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
cleanup_part_content(part);
if(readfunc) {
part->readfunc = readfunc;
part->seekfunc = seekfunc;
part->freefunc = freefunc;
part->arg = arg;
part->datasize = datasize;
part->kind = MIMEKIND_CALLBACK;
}
return CURLE_OK;
}
/* Set mime part content from subparts. */
CURLcode Curl_mime_set_subparts(curl_mimepart *part,
curl_mime *subparts, int take_ownership)
{
curl_mime *root;
if(!part)
return CURLE_BAD_FUNCTION_ARGUMENT;
/* Accept setting twice the same subparts. */
if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts)
return CURLE_OK;
cleanup_part_content(part);
if(subparts) {
/* Must belong to the same data handle. */
if(part->easy && subparts->easy && part->easy != subparts->easy)
return CURLE_BAD_FUNCTION_ARGUMENT;
/* Should not have been attached already. */
if(subparts->parent)
return CURLE_BAD_FUNCTION_ARGUMENT;
/* Should not be the part's root. */
root = part->parent;
if(root) {
while(root->parent && root->parent->parent)
root = root->parent->parent;
if(subparts == root) {
if(part->easy)
failf(part->easy, "Can't add itself as a subpart!");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
}
subparts->parent = part;
/* Subparts are processed internally: no read callback. */
part->seekfunc = mime_subparts_seek;
part->freefunc = take_ownership? mime_subparts_free: mime_subparts_unbind;
part->arg = subparts;
part->datasize = -1;
part->kind = MIMEKIND_MULTIPART;
}
return CURLE_OK;
}
CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
{
return Curl_mime_set_subparts(part, subparts, TRUE);
}
/* Readback from top mime. */
/* Argument is the dummy top part. */
size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
{
curl_mimepart *part = (curl_mimepart *) instream;
size_t ret;
bool hasread;
(void) size; /* Always 1. */
do {
hasread = FALSE;
ret = readback_part(part, buffer, nitems, &hasread);
/*
* If this is not possible to get some data without calling more than
* one read callback (probably because a content encoder is not able to
* deliver a new bunch for the few data accumulated so far), force another
* read until we get enough data or a special exit code.
*/
} while(ret == STOP_FILLING);
return ret;
}
/* Rewind mime stream. */
CURLcode Curl_mime_rewind(curl_mimepart *part)
{
return mime_part_rewind(part) == CURL_SEEKFUNC_OK?
CURLE_OK: CURLE_SEND_FAIL_REWIND;
}
/* Compute header list size. */
static size_t slist_size(struct curl_slist *s,
size_t overhead, const char *skip)
{
size_t size = 0;
size_t skiplen = skip? strlen(skip): 0;
for(; s; s = s->next)
if(!skip || !match_header(s, skip, skiplen))
size += strlen(s->data) + overhead;
return size;
}
/* Get/compute multipart size. */
static curl_off_t multipart_size(curl_mime *mime)
{
curl_off_t size;
size_t boundarysize;
curl_mimepart *part;
if(!mime)
return 0; /* Not present -> empty. */
boundarysize = 4 + strlen(mime->boundary) + 2;
size = boundarysize; /* Final boundary - CRLF after headers. */
for(part = mime->firstpart; part; part = part->nextpart) {
curl_off_t sz = Curl_mime_size(part);
if(sz < 0)
size = sz;
if(size >= 0)
size += boundarysize + sz;
}
return size;
}
/* Get/compute mime size. */
curl_off_t Curl_mime_size(curl_mimepart *part)
{
curl_off_t size;
if(part->kind == MIMEKIND_MULTIPART)
part->datasize = multipart_size(part->arg);
size = part->datasize;
if(part->encoder)
size = part->encoder->sizefunc(part);
if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) {
/* Compute total part size. */
size += slist_size(part->curlheaders, 2, NULL);
size += slist_size(part->userheaders, 2, "Content-Type");
size += 2; /* CRLF after headers. */
}
return size;
}
/* Add a header. */
/* VARARGS2 */
CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
{
struct curl_slist *hdr = NULL;
char *s = NULL;
va_list ap;
va_start(ap, fmt);
s = curl_mvaprintf(fmt, ap);
va_end(ap);
if(s) {
hdr = Curl_slist_append_nodup(*slp, s);
if(hdr)
*slp = hdr;
else
free(s);
}
return hdr? CURLE_OK: CURLE_OUT_OF_MEMORY;
}
/* Add a content type header. */
static CURLcode add_content_type(struct curl_slist **slp,
const char *type, const char *boundary)
{
return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type,
boundary? "; boundary=": "",
boundary? boundary: "");
}
const char *Curl_mime_contenttype(const char *filename)
{
/*
* If no content type was specified, we scan through a few well-known
* extensions and pick the first we match!
*/
struct ContentType {
const char *extension;
const char *type;
};
static const struct ContentType ctts[] = {
{".gif", "image/gif"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".png", "image/png"},
{".svg", "image/svg+xml"},
{".txt", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".pdf", "application/pdf"},
{".xml", "application/xml"}
};
if(filename) {
size_t len1 = strlen(filename);
const char *nameend = filename + len1;
unsigned int i;
for(i = 0; i < sizeof(ctts) / sizeof(ctts[0]); i++) {
size_t len2 = strlen(ctts[i].extension);
if(len1 >= len2 && strcasecompare(nameend - len2, ctts[i].extension))
return ctts[i].type;
}
}
return NULL;
}
static bool content_type_match(const char *contenttype, const char *target)
{
size_t len = strlen(target);
if(contenttype && strncasecompare(contenttype, target, len))
switch(contenttype[len]) {
case '\0':
case '\t':
case '\r':
case '\n':
case ' ':
case ';':
return TRUE;
}
return FALSE;
}
CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
const char *contenttype,
const char *disposition,
enum mimestrategy strategy)
{
curl_mime *mime = NULL;
const char *boundary = NULL;
char *customct;
const char *cte = NULL;
CURLcode ret = CURLE_OK;
/* Get rid of previously prepared headers. */
curl_slist_free_all(part->curlheaders);
part->curlheaders = NULL;
/* Be sure we won't access old headers later. */
if(part->state.state == MIMESTATE_CURLHEADERS)
mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL);
/* Check if content type is specified. */
customct = part->mimetype;
if(!customct)
customct = search_header(part->userheaders, "Content-Type");
if(customct)
contenttype = customct;
/* If content type is not specified, try to determine it. */
if(!contenttype) {
switch(part->kind) {
case MIMEKIND_MULTIPART:
contenttype = MULTIPART_CONTENTTYPE_DEFAULT;
break;
case MIMEKIND_FILE:
contenttype = Curl_mime_contenttype(part->filename);
if(!contenttype)
contenttype = Curl_mime_contenttype(part->data);
if(!contenttype && part->filename)
contenttype = FILE_CONTENTTYPE_DEFAULT;
break;
default:
contenttype = Curl_mime_contenttype(part->filename);
break;
}
}
if(part->kind == MIMEKIND_MULTIPART) {
mime = (curl_mime *) part->arg;
if(mime)
boundary = mime->boundary;
}
else if(contenttype && !customct &&
content_type_match(contenttype, "text/plain"))
if(strategy == MIMESTRATEGY_MAIL || !part->filename)
contenttype = NULL;
/* Issue content-disposition header only if not already set by caller. */
if(!search_header(part->userheaders, "Content-Disposition")) {
if(!disposition)
if(part->filename || part->name ||
(contenttype && !strncasecompare(contenttype, "multipart/", 10)))
disposition = DISPOSITION_DEFAULT;
if(disposition && curl_strequal(disposition, "attachment") &&
!part->name && !part->filename)
disposition = NULL;
if(disposition) {
char *name = NULL;
char *filename = NULL;
if(part->name) {
name = escape_string(part->name);
if(!name)
ret = CURLE_OUT_OF_MEMORY;
}
if(!ret && part->filename) {
filename = escape_string(part->filename);
if(!filename)
ret = CURLE_OUT_OF_MEMORY;
}
if(!ret)
ret = Curl_mime_add_header(&part->curlheaders,
"Content-Disposition: %s%s%s%s%s%s%s",
disposition,
name? "; name=\"": "",
name? name: "",
name? "\"": "",
filename? "; filename=\"": "",
filename? filename: "",
filename? "\"": "");
Curl_safefree(name);
Curl_safefree(filename);
if(ret)
return ret;
}
}
/* Issue Content-Type header. */
if(contenttype) {
ret = add_content_type(&part->curlheaders, contenttype, boundary);
if(ret)
return ret;
}
/* Content-Transfer-Encoding header. */
if(!search_header(part->userheaders, "Content-Transfer-Encoding")) {
if(part->encoder)
cte = part->encoder->name;
else if(contenttype && strategy == MIMESTRATEGY_MAIL &&
part->kind != MIMEKIND_MULTIPART)
cte = "8bit";
if(cte) {
ret = Curl_mime_add_header(&part->curlheaders,
"Content-Transfer-Encoding: %s", cte);
if(ret)
return ret;
}
}
/* If we were reading curl-generated headers, restart with new ones (this
should not occur). */
if(part->state.state == MIMESTATE_CURLHEADERS)
mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders);
/* Process subparts. */
if(part->kind == MIMEKIND_MULTIPART && mime) {
curl_mimepart *subpart;
disposition = NULL;
if(content_type_match(contenttype, "multipart/form-data"))
disposition = "form-data";
for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) {
ret = Curl_mime_prepare_headers(subpart, NULL, disposition, strategy);
if(ret)
return ret;
}
}
return ret;
}
/* Recursively reset paused status in the given part. */
void Curl_mime_unpause(curl_mimepart *part)
{
if(part) {
if(part->lastreadstatus == CURL_READFUNC_PAUSE)
part->lastreadstatus = 1; /* Successful read status. */
if(part->kind == MIMEKIND_MULTIPART) {
curl_mime *mime = (curl_mime *) part->arg;
if(mime) {
curl_mimepart *subpart;
for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart)
Curl_mime_unpause(subpart);
}
}
}
}
#else /* !CURL_DISABLE_HTTP && !CURL_DISABLE_MIME ||
!CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */
/* Mime not compiled in: define stubs for externally-referenced functions. */
curl_mime *curl_mime_init(CURL *easy)
{
(void) easy;
return NULL;
}
void curl_mime_free(curl_mime *mime)
{
(void) mime;
}
curl_mimepart *curl_mime_addpart(curl_mime *mime)
{
(void) mime;
return NULL;
}
CURLcode curl_mime_name(curl_mimepart *part, const char *name)
{
(void) part;
(void) name;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
{
(void) part;
(void) filename;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
{
(void) part;
(void) mimetype;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
{
(void) part;
(void) encoding;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_data(curl_mimepart *part,
const char *data, size_t datasize)
{
(void) part;
(void) data;
(void) datasize;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
{
(void) part;
(void) filename;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_data_cb(curl_mimepart *part,
curl_off_t datasize,
curl_read_callback readfunc,
curl_seek_callback seekfunc,
curl_free_callback freefunc,
void *arg)
{
(void) part;
(void) datasize;
(void) readfunc;
(void) seekfunc;
(void) freefunc;
(void) arg;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
{
(void) part;
(void) subparts;
return CURLE_NOT_BUILT_IN;
}
CURLcode curl_mime_headers(curl_mimepart *part,
struct curl_slist *headers, int take_ownership)
{
(void) part;
(void) headers;
(void) take_ownership;
return CURLE_NOT_BUILT_IN;
}
CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
{
(void)slp;
(void)fmt;
return CURLE_NOT_BUILT_IN;
}
#endif /* if disabled */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/openldap.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2011 - 2021, Daniel Stenberg, <[email protected]>, et al.
* Copyright (C) 2010, Howard Chu, <[email protected]>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)
/*
* Notice that USE_OPENLDAP is only a source code selection switch. When
* libcurl is built with USE_OPENLDAP defined the libcurl source code that
* gets compiled is the code from openldap.c, otherwise the code that gets
* compiled is the code from ldap.c.
*
* When USE_OPENLDAP is defined a recent version of the OpenLDAP library
* might be required for compilation and runtime. In order to use ancient
* OpenLDAP library versions, USE_OPENLDAP shall not be defined.
*/
#include <ldap.h>
#include "urldata.h"
#include <curl/curl.h>
#include "sendf.h"
#include "vtls/vtls.h"
#include "transfer.h"
#include "curl_ldap.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"
/*
* Uncommenting this will enable the built-in debug logging of the openldap
* library. The debug log level can be set using the CURL_OPENLDAP_TRACE
* environment variable. The debug output is written to stderr.
*
* The library supports the following debug flags:
* LDAP_DEBUG_NONE 0x0000
* LDAP_DEBUG_TRACE 0x0001
* LDAP_DEBUG_CONSTRUCT 0x0002
* LDAP_DEBUG_DESTROY 0x0004
* LDAP_DEBUG_PARAMETER 0x0008
* LDAP_DEBUG_ANY 0xffff
*
* For example, use CURL_OPENLDAP_TRACE=0 for no debug,
* CURL_OPENLDAP_TRACE=2 for LDAP_DEBUG_CONSTRUCT messages only,
* CURL_OPENLDAP_TRACE=65535 for all debug message levels.
*/
/* #define CURL_OPENLDAP_DEBUG */
#ifndef _LDAP_PVT_H
extern int ldap_pvt_url_scheme2proto(const char *);
extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url,
LDAP **ld);
#endif
static CURLcode oldap_setup_connection(struct Curl_easy *data,
struct connectdata *conn);
static CURLcode oldap_do(struct Curl_easy *data, bool *done);
static CURLcode oldap_done(struct Curl_easy *data, CURLcode, bool);
static CURLcode oldap_connect(struct Curl_easy *data, bool *done);
static CURLcode oldap_connecting(struct Curl_easy *data, bool *done);
static CURLcode oldap_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead);
static Curl_recv oldap_recv;
/*
* LDAP protocol handler.
*/
const struct Curl_handler Curl_handler_ldap = {
"LDAP", /* scheme */
oldap_setup_connection, /* setup_connection */
oldap_do, /* do_it */
oldap_done, /* done */
ZERO_NULL, /* do_more */
oldap_connect, /* connect_it */
oldap_connecting, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
oldap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
ZERO_NULL, /* attach connection */
PORT_LDAP, /* defport */
CURLPROTO_LDAP, /* protocol */
CURLPROTO_LDAP, /* family */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* LDAPS protocol handler.
*/
const struct Curl_handler Curl_handler_ldaps = {
"LDAPS", /* scheme */
oldap_setup_connection, /* setup_connection */
oldap_do, /* do_it */
oldap_done, /* done */
ZERO_NULL, /* do_more */
oldap_connect, /* connect_it */
oldap_connecting, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
oldap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
ZERO_NULL, /* attach connection */
PORT_LDAPS, /* defport */
CURLPROTO_LDAPS, /* protocol */
CURLPROTO_LDAP, /* family */
PROTOPT_SSL /* flags */
};
#endif
static const char *url_errs[] = {
"success",
"out of memory",
"bad parameter",
"unrecognized scheme",
"unbalanced delimiter",
"bad URL",
"bad host or port",
"bad or missing attributes",
"bad or missing scope",
"bad or missing filter",
"bad or missing extensions"
};
struct ldapconninfo {
LDAP *ld;
Curl_recv *recv; /* for stacking SSL handler */
Curl_send *send;
int proto;
int msgid;
bool ssldone;
bool sslinst;
bool didbind;
};
struct ldapreqinfo {
int msgid;
int nument;
};
static CURLcode oldap_setup_connection(struct Curl_easy *data,
struct connectdata *conn)
{
struct ldapconninfo *li;
LDAPURLDesc *lud;
int rc, proto;
CURLcode status;
rc = ldap_url_parse(data->state.url, &lud);
if(rc != LDAP_URL_SUCCESS) {
const char *msg = "url parsing problem";
status = CURLE_URL_MALFORMAT;
if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
if(rc == LDAP_URL_ERR_MEM)
status = CURLE_OUT_OF_MEMORY;
msg = url_errs[rc];
}
failf(data, "LDAP local: %s", msg);
return status;
}
proto = ldap_pvt_url_scheme2proto(lud->lud_scheme);
ldap_free_urldesc(lud);
li = calloc(1, sizeof(struct ldapconninfo));
if(!li)
return CURLE_OUT_OF_MEMORY;
li->proto = proto;
conn->proto.ldapc = li;
connkeep(conn, "OpenLDAP default");
return CURLE_OK;
}
#ifdef USE_SSL
static Sockbuf_IO ldapsb_tls;
#endif
static CURLcode oldap_connect(struct Curl_easy *data, bool *done)
{
struct connectdata *conn = data->conn;
struct ldapconninfo *li = conn->proto.ldapc;
int rc, proto = LDAP_VERSION3;
char hosturl[1024];
char *ptr;
(void)done;
strcpy(hosturl, "ldap");
ptr = hosturl + 4;
if(conn->handler->flags & PROTOPT_SSL)
*ptr++ = 's';
msnprintf(ptr, sizeof(hosturl)-(ptr-hosturl), "://%s:%d",
conn->host.name, conn->remote_port);
#ifdef CURL_OPENLDAP_DEBUG
static int do_trace = 0;
const char *env = getenv("CURL_OPENLDAP_TRACE");
do_trace = (env && strtol(env, NULL, 10) > 0);
if(do_trace) {
ldap_set_option(li->ld, LDAP_OPT_DEBUG_LEVEL, &do_trace);
}
#endif
rc = ldap_init_fd(conn->sock[FIRSTSOCKET], li->proto, hosturl, &li->ld);
if(rc) {
failf(data, "LDAP local: Cannot connect to %s, %s",
hosturl, ldap_err2string(rc));
return CURLE_COULDNT_CONNECT;
}
ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
#ifdef USE_SSL
if(conn->handler->flags & PROTOPT_SSL) {
CURLcode result;
result = Curl_ssl_connect_nonblocking(data, conn, FALSE,
FIRSTSOCKET, &li->ssldone);
if(result)
return result;
}
#endif
return CURLE_OK;
}
static CURLcode oldap_connecting(struct Curl_easy *data, bool *done)
{
struct connectdata *conn = data->conn;
struct ldapconninfo *li = conn->proto.ldapc;
LDAPMessage *msg = NULL;
struct timeval tv = {0, 1}, *tvp;
int rc, err;
char *info = NULL;
#ifdef USE_SSL
if(conn->handler->flags & PROTOPT_SSL) {
/* Is the SSL handshake complete yet? */
if(!li->ssldone) {
CURLcode result = Curl_ssl_connect_nonblocking(data, conn, FALSE,
FIRSTSOCKET,
&li->ssldone);
if(result || !li->ssldone)
return result;
}
/* Have we installed the libcurl SSL handlers into the sockbuf yet? */
if(!li->sslinst) {
Sockbuf *sb;
ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb);
ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data);
li->sslinst = TRUE;
li->recv = conn->recv[FIRSTSOCKET];
li->send = conn->send[FIRSTSOCKET];
}
}
#endif
tvp = &tv;
retry:
if(!li->didbind) {
char *binddn;
struct berval passwd;
if(conn->bits.user_passwd) {
binddn = conn->user;
passwd.bv_val = conn->passwd;
passwd.bv_len = strlen(passwd.bv_val);
}
else {
binddn = NULL;
passwd.bv_val = NULL;
passwd.bv_len = 0;
}
rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd,
NULL, NULL, &li->msgid);
if(rc)
return CURLE_LDAP_CANNOT_BIND;
li->didbind = TRUE;
if(tvp)
return CURLE_OK;
}
rc = ldap_result(li->ld, li->msgid, LDAP_MSG_ONE, tvp, &msg);
if(rc < 0) {
failf(data, "LDAP local: bind ldap_result %s", ldap_err2string(rc));
return CURLE_LDAP_CANNOT_BIND;
}
if(rc == 0) {
/* timed out */
return CURLE_OK;
}
rc = ldap_parse_result(li->ld, msg, &err, NULL, &info, NULL, NULL, 1);
if(rc) {
failf(data, "LDAP local: bind ldap_parse_result %s", ldap_err2string(rc));
return CURLE_LDAP_CANNOT_BIND;
}
/* Try to fallback to LDAPv2? */
if(err == LDAP_PROTOCOL_ERROR) {
int proto;
ldap_get_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
if(proto == LDAP_VERSION3) {
if(info) {
ldap_memfree(info);
info = NULL;
}
proto = LDAP_VERSION2;
ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &proto);
li->didbind = FALSE;
goto retry;
}
}
if(err) {
failf(data, "LDAP remote: bind failed %s %s", ldap_err2string(rc),
info ? info : "");
if(info)
ldap_memfree(info);
return CURLE_LOGIN_DENIED;
}
if(info)
ldap_memfree(info);
conn->recv[FIRSTSOCKET] = oldap_recv;
*done = TRUE;
return CURLE_OK;
}
static CURLcode oldap_disconnect(struct Curl_easy *data,
struct connectdata *conn,
bool dead_connection)
{
struct ldapconninfo *li = conn->proto.ldapc;
(void) dead_connection;
if(li) {
if(li->ld) {
#ifdef USE_SSL
if(conn->ssl[FIRSTSOCKET].use) {
Sockbuf *sb;
ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb);
ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data);
}
#endif
ldap_unbind_ext(li->ld, NULL, NULL);
li->ld = NULL;
}
conn->proto.ldapc = NULL;
free(li);
}
return CURLE_OK;
}
static CURLcode oldap_do(struct Curl_easy *data, bool *done)
{
struct connectdata *conn = data->conn;
struct ldapconninfo *li = conn->proto.ldapc;
struct ldapreqinfo *lr;
CURLcode status = CURLE_OK;
int rc = 0;
LDAPURLDesc *ludp = NULL;
int msgid;
connkeep(conn, "OpenLDAP do");
infof(data, "LDAP local: %s", data->state.url);
rc = ldap_url_parse(data->state.url, &ludp);
if(rc != LDAP_URL_SUCCESS) {
const char *msg = "url parsing problem";
status = CURLE_URL_MALFORMAT;
if(rc > LDAP_URL_SUCCESS && rc <= LDAP_URL_ERR_BADEXTS) {
if(rc == LDAP_URL_ERR_MEM)
status = CURLE_OUT_OF_MEMORY;
msg = url_errs[rc];
}
failf(data, "LDAP local: %s", msg);
return status;
}
rc = ldap_search_ext(li->ld, ludp->lud_dn, ludp->lud_scope,
ludp->lud_filter, ludp->lud_attrs, 0,
NULL, NULL, NULL, 0, &msgid);
ldap_free_urldesc(ludp);
if(rc != LDAP_SUCCESS) {
failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc));
return CURLE_LDAP_SEARCH_FAILED;
}
lr = calloc(1, sizeof(struct ldapreqinfo));
if(!lr)
return CURLE_OUT_OF_MEMORY;
lr->msgid = msgid;
data->req.p.ldap = lr;
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
*done = TRUE;
return CURLE_OK;
}
static CURLcode oldap_done(struct Curl_easy *data, CURLcode res,
bool premature)
{
struct connectdata *conn = data->conn;
struct ldapreqinfo *lr = data->req.p.ldap;
(void)res;
(void)premature;
if(lr) {
/* if there was a search in progress, abandon it */
if(lr->msgid) {
struct ldapconninfo *li = conn->proto.ldapc;
ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL);
lr->msgid = 0;
}
data->req.p.ldap = NULL;
free(lr);
}
return CURLE_OK;
}
static ssize_t oldap_recv(struct Curl_easy *data, int sockindex, char *buf,
size_t len, CURLcode *err)
{
struct connectdata *conn = data->conn;
struct ldapconninfo *li = conn->proto.ldapc;
struct ldapreqinfo *lr = data->req.p.ldap;
int rc, ret;
LDAPMessage *msg = NULL;
LDAPMessage *ent;
BerElement *ber = NULL;
struct timeval tv = {0, 1};
(void)len;
(void)buf;
(void)sockindex;
rc = ldap_result(li->ld, lr->msgid, LDAP_MSG_RECEIVED, &tv, &msg);
if(rc < 0) {
failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc));
*err = CURLE_RECV_ERROR;
return -1;
}
*err = CURLE_AGAIN;
ret = -1;
/* timed out */
if(!msg)
return ret;
for(ent = ldap_first_message(li->ld, msg); ent;
ent = ldap_next_message(li->ld, ent)) {
struct berval bv, *bvals;
int binary = 0, msgtype;
CURLcode writeerr;
msgtype = ldap_msgtype(ent);
if(msgtype == LDAP_RES_SEARCH_RESULT) {
int code;
char *info = NULL;
rc = ldap_parse_result(li->ld, ent, &code, NULL, &info, NULL, NULL, 0);
if(rc) {
failf(data, "LDAP local: search ldap_parse_result %s",
ldap_err2string(rc));
*err = CURLE_LDAP_SEARCH_FAILED;
}
else if(code && code != LDAP_SIZELIMIT_EXCEEDED) {
failf(data, "LDAP remote: search failed %s %s", ldap_err2string(rc),
info ? info : "");
*err = CURLE_LDAP_SEARCH_FAILED;
}
else {
/* successful */
if(code == LDAP_SIZELIMIT_EXCEEDED)
infof(data, "There are more than %d entries", lr->nument);
data->req.size = data->req.bytecount;
*err = CURLE_OK;
ret = 0;
}
lr->msgid = 0;
ldap_memfree(info);
break;
}
else if(msgtype != LDAP_RES_SEARCH_ENTRY)
continue;
lr->nument++;
rc = ldap_get_dn_ber(li->ld, ent, &ber, &bv);
if(rc < 0) {
*err = CURLE_RECV_ERROR;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)bv.bv_val,
bv.bv_len);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount += bv.bv_len + 5;
for(rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, &bvals);
rc == LDAP_SUCCESS;
rc = ldap_get_attribute_ber(li->ld, ent, ber, &bv, &bvals)) {
int i;
if(!bv.bv_val)
break;
if(bv.bv_len > 7 && !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7))
binary = 1;
else
binary = 0;
if(!bvals) {
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)bv.bv_val,
bv.bv_len);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)":\n", 2);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount += bv.bv_len + 3;
continue;
}
for(i = 0; bvals[i].bv_val != NULL; i++) {
int binval = 0;
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)bv.bv_val,
bv.bv_len);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)":", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount += bv.bv_len + 2;
if(!binary) {
/* check for leading or trailing whitespace */
if(ISSPACE(bvals[i].bv_val[0]) ||
ISSPACE(bvals[i].bv_val[bvals[i].bv_len-1]))
binval = 1;
else {
/* check for unprintable characters */
unsigned int j;
for(j = 0; j<bvals[i].bv_len; j++)
if(!ISPRINT(bvals[i].bv_val[j])) {
binval = 1;
break;
}
}
}
if(binary || binval) {
char *val_b64 = NULL;
size_t val_b64_sz = 0;
/* Binary value, encode to base64. */
CURLcode error = Curl_base64_encode(data,
bvals[i].bv_val,
bvals[i].bv_len,
&val_b64,
&val_b64_sz);
if(error) {
ber_memfree(bvals);
ber_free(ber, 0);
ldap_msgfree(msg);
*err = error;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY,
(char *)": ", 2);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount += 2;
if(val_b64_sz > 0) {
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, val_b64,
val_b64_sz);
if(writeerr) {
*err = writeerr;
return -1;
}
free(val_b64);
data->req.bytecount += val_b64_sz;
}
}
else {
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)" ", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, bvals[i].bv_val,
bvals[i].bv_len);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount += bvals[i].bv_len + 1;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount++;
}
ber_memfree(bvals);
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount++;
}
writeerr = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
if(writeerr) {
*err = writeerr;
return -1;
}
data->req.bytecount++;
ber_free(ber, 0);
}
ldap_msgfree(msg);
return ret;
}
#ifdef USE_SSL
static int
ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg)
{
sbiod->sbiod_pvt = arg;
return 0;
}
static int
ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod)
{
sbiod->sbiod_pvt = NULL;
return 0;
}
/* We don't need to do anything because libcurl does it already */
static int
ldapsb_tls_close(Sockbuf_IO_Desc *sbiod)
{
(void)sbiod;
return 0;
}
static int
ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg)
{
(void)arg;
if(opt == LBER_SB_OPT_DATA_READY) {
struct Curl_easy *data = sbiod->sbiod_pvt;
return Curl_ssl_data_pending(data->conn, FIRSTSOCKET);
}
return 0;
}
static ber_slen_t
ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
{
struct Curl_easy *data = sbiod->sbiod_pvt;
ber_slen_t ret = 0;
if(data) {
struct connectdata *conn = data->conn;
if(conn) {
struct ldapconninfo *li = conn->proto.ldapc;
CURLcode err = CURLE_RECV_ERROR;
ret = (li->recv)(data, FIRSTSOCKET, buf, len, &err);
if(ret < 0 && err == CURLE_AGAIN) {
SET_SOCKERRNO(EWOULDBLOCK);
}
}
}
return ret;
}
static ber_slen_t
ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
{
struct Curl_easy *data = sbiod->sbiod_pvt;
ber_slen_t ret = 0;
if(data) {
struct connectdata *conn = data->conn;
if(conn) {
struct ldapconninfo *li = conn->proto.ldapc;
CURLcode err = CURLE_SEND_ERROR;
ret = (li->send)(data, FIRSTSOCKET, buf, len, &err);
if(ret < 0 && err == CURLE_AGAIN) {
SET_SOCKERRNO(EWOULDBLOCK);
}
}
}
return ret;
}
static Sockbuf_IO ldapsb_tls =
{
ldapsb_tls_setup,
ldapsb_tls_remove,
ldapsb_tls_ctrl,
ldapsb_tls_read,
ldapsb_tls_write,
ldapsb_tls_close
};
#endif /* USE_SSL */
#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/warnless.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(__INTEL_COMPILER) && defined(__unix__)
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#endif /* __INTEL_COMPILER && __unix__ */
#define BUILDING_WARNLESS_C 1
#include "warnless.h"
#define CURL_MASK_UCHAR ((unsigned char)~0)
#define CURL_MASK_SCHAR (CURL_MASK_UCHAR >> 1)
#define CURL_MASK_USHORT ((unsigned short)~0)
#define CURL_MASK_SSHORT (CURL_MASK_USHORT >> 1)
#define CURL_MASK_UINT ((unsigned int)~0)
#define CURL_MASK_SINT (CURL_MASK_UINT >> 1)
#define CURL_MASK_ULONG ((unsigned long)~0)
#define CURL_MASK_SLONG (CURL_MASK_ULONG >> 1)
#define CURL_MASK_UCOFFT ((unsigned CURL_TYPEOF_CURL_OFF_T)~0)
#define CURL_MASK_SCOFFT (CURL_MASK_UCOFFT >> 1)
#define CURL_MASK_USIZE_T ((size_t)~0)
#define CURL_MASK_SSIZE_T (CURL_MASK_USIZE_T >> 1)
/*
** unsigned long to unsigned short
*/
unsigned short curlx_ultous(unsigned long ulnum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT);
return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned long to unsigned char
*/
unsigned char curlx_ultouc(unsigned long ulnum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR);
return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned size_t to signed curl_off_t
*/
curl_off_t curlx_uztoso(size_t uznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4310) /* cast truncates constant value */
#endif
DEBUGASSERT(uznum <= (size_t) CURL_MASK_SCOFFT);
return (curl_off_t)(uznum & (size_t) CURL_MASK_SCOFFT);
#if defined(__INTEL_COMPILER) || defined(_MSC_VER)
# pragma warning(pop)
#endif
}
/*
** unsigned size_t to signed int
*/
int curlx_uztosi(size_t uznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT);
return (int)(uznum & (size_t) CURL_MASK_SINT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned size_t to unsigned long
*/
unsigned long curlx_uztoul(size_t uznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
#if ULONG_MAX < SIZE_T_MAX
DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG);
#endif
return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned size_t to unsigned int
*/
unsigned int curlx_uztoui(size_t uznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
#if UINT_MAX < SIZE_T_MAX
DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT);
#endif
return (unsigned int)(uznum & (size_t) CURL_MASK_UINT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed long to signed int
*/
int curlx_sltosi(long slnum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(slnum >= 0);
#if INT_MAX < LONG_MAX
DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT);
#endif
return (int)(slnum & (long) CURL_MASK_SINT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed long to unsigned int
*/
unsigned int curlx_sltoui(long slnum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(slnum >= 0);
#if UINT_MAX < LONG_MAX
DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT);
#endif
return (unsigned int)(slnum & (long) CURL_MASK_UINT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed long to unsigned short
*/
unsigned short curlx_sltous(long slnum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(slnum >= 0);
DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT);
return (unsigned short)(slnum & (long) CURL_MASK_USHORT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned size_t to signed ssize_t
*/
ssize_t curlx_uztosz(size_t uznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T);
return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed curl_off_t to unsigned size_t
*/
size_t curlx_sotouz(curl_off_t sonum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(sonum >= 0);
return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed ssize_t to signed int
*/
int curlx_sztosi(ssize_t sznum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(sznum >= 0);
#if INT_MAX < SSIZE_T_MAX
DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT);
#endif
return (int)(sznum & (ssize_t) CURL_MASK_SINT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** unsigned int to unsigned short
*/
unsigned short curlx_uitous(unsigned int uinum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_USHORT);
return (unsigned short) (uinum & (unsigned int) CURL_MASK_USHORT);
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
/*
** signed int to unsigned size_t
*/
size_t curlx_sitouz(int sinum)
{
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
DEBUGASSERT(sinum >= 0);
return (size_t) sinum;
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
}
#ifdef USE_WINSOCK
/*
** curl_socket_t to signed int
*/
int curlx_sktosi(curl_socket_t s)
{
return (int)((ssize_t) s);
}
/*
** signed int to curl_socket_t
*/
curl_socket_t curlx_sitosk(int i)
{
return (curl_socket_t)((ssize_t) i);
}
#endif /* USE_WINSOCK */
#if defined(WIN32) || defined(_WIN32)
ssize_t curlx_read(int fd, void *buf, size_t count)
{
return (ssize_t)read(fd, buf, curlx_uztoui(count));
}
ssize_t curlx_write(int fd, const void *buf, size_t count)
{
return (ssize_t)write(fd, buf, curlx_uztoui(count));
}
#endif /* WIN32 || _WIN32 */
#if defined(__INTEL_COMPILER) && defined(__unix__)
int curlx_FD_ISSET(int fd, fd_set *fdset)
{
#pragma warning(push)
#pragma warning(disable:1469) /* clobber ignored */
return FD_ISSET(fd, fdset);
#pragma warning(pop)
}
void curlx_FD_SET(int fd, fd_set *fdset)
{
#pragma warning(push)
#pragma warning(disable:1469) /* clobber ignored */
FD_SET(fd, fdset);
#pragma warning(pop)
}
void curlx_FD_ZERO(fd_set *fdset)
{
#pragma warning(push)
#pragma warning(disable:593) /* variable was set but never used */
FD_ZERO(fdset);
#pragma warning(pop)
}
unsigned short curlx_htons(unsigned short usnum)
{
#if (__INTEL_COMPILER == 910) && defined(__i386__)
return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
#else
#pragma warning(push)
#pragma warning(disable:810) /* conversion may lose significant bits */
return htons(usnum);
#pragma warning(pop)
#endif
}
unsigned short curlx_ntohs(unsigned short usnum)
{
#if (__INTEL_COMPILER == 910) && defined(__i386__)
return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF));
#else
#pragma warning(push)
#pragma warning(disable:810) /* conversion may lose significant bits */
return ntohs(usnum);
#pragma warning(pop)
#endif
}
#endif /* __INTEL_COMPILER && __unix__ */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_chunks.h | #ifndef HEADER_CURL_HTTP_CHUNKS_H
#define HEADER_CURL_HTTP_CHUNKS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
struct connectdata;
/*
* The longest possible hexadecimal number we support in a chunked transfer.
* Neither RFC2616 nor the later HTTP specs define a maximum chunk size.
* For 64 bit curl_off_t we support 16 digits. For 32 bit, 8 digits.
*/
#define CHUNK_MAXNUM_LEN (SIZEOF_CURL_OFF_T * 2)
typedef enum {
/* await and buffer all hexadecimal digits until we get one that isn't a
hexadecimal digit. When done, we go CHUNK_LF */
CHUNK_HEX,
/* wait for LF, ignore all else */
CHUNK_LF,
/* We eat the amount of data specified. When done, we move on to the
POST_CR state. */
CHUNK_DATA,
/* POSTLF should get a CR and then a LF and nothing else, then move back to
HEX as the CRLF combination marks the end of a chunk. A missing CR is no
big deal. */
CHUNK_POSTLF,
/* Used to mark that we're out of the game. NOTE: that there's a 'datasize'
field in the struct that will tell how many bytes that were not passed to
the client in the end of the last buffer! */
CHUNK_STOP,
/* At this point optional trailer headers can be found, unless the next line
is CRLF */
CHUNK_TRAILER,
/* A trailer CR has been found - next state is CHUNK_TRAILER_POSTCR.
Next char must be a LF */
CHUNK_TRAILER_CR,
/* A trailer LF must be found now, otherwise CHUNKE_BAD_CHUNK will be
signalled If this is an empty trailer CHUNKE_STOP will be signalled.
Otherwise the trailer will be broadcasted via Curl_client_write() and the
next state will be CHUNK_TRAILER */
CHUNK_TRAILER_POSTCR
} ChunkyState;
typedef enum {
CHUNKE_STOP = -1,
CHUNKE_OK = 0,
CHUNKE_TOO_LONG_HEX = 1,
CHUNKE_ILLEGAL_HEX,
CHUNKE_BAD_CHUNK,
CHUNKE_BAD_ENCODING,
CHUNKE_OUT_OF_MEMORY,
CHUNKE_PASSTHRU_ERROR, /* Curl_httpchunk_read() returns a CURLcode to use */
CHUNKE_LAST
} CHUNKcode;
const char *Curl_chunked_strerror(CHUNKcode code);
struct Curl_chunker {
curl_off_t datasize;
ChunkyState state;
unsigned char hexindex;
char hexbuffer[ CHUNK_MAXNUM_LEN + 1]; /* +1 for null-terminator */
};
/* The following functions are defined in http_chunks.c */
void Curl_httpchunk_init(struct Curl_easy *data);
CHUNKcode Curl_httpchunk_read(struct Curl_easy *data, char *datap,
ssize_t length, ssize_t *wrote,
CURLcode *passthru);
#endif /* HEADER_CURL_HTTP_CHUNKS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_ntlm.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
/*
* NTLM details:
*
* https://davenport.sourceforge.io/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_ntlm_wb.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 a HTTP proxy */
char **allocuserpwd;
/* point to the username, password, service and host */
const char *userp;
const char *passwdp;
const char *service = NULL;
const char *hostname = NULL;
/* point to the correct struct with this */
struct ntlmdata *ntlm;
curlntlm *state;
struct auth *authp;
struct connectdata *conn = data->conn;
DEBUGASSERT(conn);
DEBUGASSERT(data);
if(proxy) {
#ifndef CURL_DISABLE_PROXY
allocuserpwd = &data->state.aptr.proxyuserpwd;
userp = data->state.aptr.proxyuser;
passwdp = data->state.aptr.proxypasswd;
service = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP";
hostname = conn->http_proxy.host.name;
ntlm = &conn->proxyntlm;
state = &conn->proxy_ntlm_state;
authp = &data->state.authproxy;
#else
return CURLE_NOT_BUILT_IN;
#endif
}
else {
allocuserpwd = &data->state.aptr.userpwd;
userp = data->state.aptr.user;
passwdp = data->state.aptr.passwd;
service = data->set.str[STRING_SERVICE_NAME] ?
data->set.str[STRING_SERVICE_NAME] : "HTTP";
hostname = conn->host.name;
ntlm = &conn->ntlm;
state = &conn->http_ntlm_state;
authp = &data->state.authhost;
}
authp->done = FALSE;
/* not set means empty */
if(!userp)
userp = "";
if(!passwdp)
passwdp = "";
#ifdef USE_WINDOWS_SSPI
if(!s_hSecDll) {
/* not thread safe and leaks - use curl_global_init() to avoid */
CURLcode err = Curl_sspi_global_init();
if(!s_hSecDll)
return err;
}
#ifdef SECPKG_ATTR_ENDPOINT_BINDINGS
ntlm->sslContext = conn->sslContext;
#endif
#endif
Curl_bufref_init(&ntlmmsg);
/* connection is already authenticated, don't send a header in future
* requests so go directly to NTLMSTATE_LAST */
if(*state == NTLMSTATE_TYPE3)
*state = NTLMSTATE_LAST;
switch(*state) {
case NTLMSTATE_TYPE1:
default: /* for the weird cases we (re)start here */
/* Create a type-1 message */
result = Curl_auth_create_ntlm_type1_message(data, userp, passwdp,
service, hostname,
ntlm, &ntlmmsg);
if(!result) {
DEBUGASSERT(Curl_bufref_len(&ntlmmsg) != 0);
result = Curl_base64_encode(data,
(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(data,
(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);
#if defined(NTLM_WB_ENABLED)
Curl_http_auth_cleanup_ntlm_wb(conn);
#endif
}
#endif /* !CURL_DISABLE_HTTP && USE_NTLM */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/asyn.h | #ifndef HEADER_CURL_ASYN_H
#define HEADER_CURL_ASYN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_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 forth argument will point to
* memory we need to free after use. That memory *MUST* be freed with
* Curl_freeaddrinfo(), nothing else.
*
* Each resolver backend must of course make sure to return data in the
* correct format to comply with this.
*/
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data,
const char *hostname,
int port,
int *waitp);
#ifndef CURLRES_ASYNCH
/* convert these functions if an asynch resolver isn't used */
#define Curl_resolver_cancel(x) Curl_nop_stmt
#define Curl_resolver_kill(x) Curl_nop_stmt
#define Curl_resolver_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST
#define Curl_resolver_wait_resolv(x,y) CURLE_COULDNT_RESOLVE_HOST
#define Curl_resolver_duphandle(x,y,z) CURLE_OK
#define Curl_resolver_init(x,y) CURLE_OK
#define Curl_resolver_global_init() CURLE_OK
#define Curl_resolver_global_cleanup() Curl_nop_stmt
#define Curl_resolver_cleanup(x) Curl_nop_stmt
#endif
#ifdef CURLRES_ASYNCH
#define Curl_resolver_asynch() 1
#else
#define Curl_resolver_asynch() 0
#endif
/********** end of generic resolver interface functions *****************/
#endif /* HEADER_CURL_ASYN_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_fnmatch.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
#include <curl/curl.h>
#include "curl_fnmatch.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
#ifndef HAVE_FNMATCH
#define CURLFNM_CHARSET_LEN (sizeof(char) * 256)
#define CURLFNM_CHSET_SIZE (CURLFNM_CHARSET_LEN + 15)
#define CURLFNM_NEGATE CURLFNM_CHARSET_LEN
#define CURLFNM_ALNUM (CURLFNM_CHARSET_LEN + 1)
#define CURLFNM_DIGIT (CURLFNM_CHARSET_LEN + 2)
#define CURLFNM_XDIGIT (CURLFNM_CHARSET_LEN + 3)
#define CURLFNM_ALPHA (CURLFNM_CHARSET_LEN + 4)
#define CURLFNM_PRINT (CURLFNM_CHARSET_LEN + 5)
#define CURLFNM_BLANK (CURLFNM_CHARSET_LEN + 6)
#define CURLFNM_LOWER (CURLFNM_CHARSET_LEN + 7)
#define CURLFNM_GRAPH (CURLFNM_CHARSET_LEN + 8)
#define CURLFNM_SPACE (CURLFNM_CHARSET_LEN + 9)
#define CURLFNM_UPPER (CURLFNM_CHARSET_LEN + 10)
typedef enum {
CURLFNM_SCHS_DEFAULT = 0,
CURLFNM_SCHS_RIGHTBR,
CURLFNM_SCHS_RIGHTBRLEFTBR
} setcharset_state;
typedef enum {
CURLFNM_PKW_INIT = 0,
CURLFNM_PKW_DDOT
} parsekey_state;
typedef enum {
CCLASS_OTHER = 0,
CCLASS_DIGIT,
CCLASS_UPPER,
CCLASS_LOWER
} char_class;
#define SETCHARSET_OK 1
#define SETCHARSET_FAIL 0
static int parsekeyword(unsigned char **pattern, unsigned char *charset)
{
parsekey_state state = CURLFNM_PKW_INIT;
#define KEYLEN 10
char keyword[KEYLEN] = { 0 };
int found = FALSE;
int i;
unsigned char *p = *pattern;
for(i = 0; !found; i++) {
char c = *p++;
if(i >= KEYLEN)
return SETCHARSET_FAIL;
switch(state) {
case CURLFNM_PKW_INIT:
if(ISLOWER(c))
keyword[i] = c;
else if(c == ':')
state = CURLFNM_PKW_DDOT;
else
return SETCHARSET_FAIL;
break;
case CURLFNM_PKW_DDOT:
if(c == ']')
found = TRUE;
else
return SETCHARSET_FAIL;
}
}
#undef KEYLEN
*pattern = p; /* move caller's pattern pointer */
if(strcmp(keyword, "digit") == 0)
charset[CURLFNM_DIGIT] = 1;
else if(strcmp(keyword, "alnum") == 0)
charset[CURLFNM_ALNUM] = 1;
else if(strcmp(keyword, "alpha") == 0)
charset[CURLFNM_ALPHA] = 1;
else if(strcmp(keyword, "xdigit") == 0)
charset[CURLFNM_XDIGIT] = 1;
else if(strcmp(keyword, "print") == 0)
charset[CURLFNM_PRINT] = 1;
else if(strcmp(keyword, "graph") == 0)
charset[CURLFNM_GRAPH] = 1;
else if(strcmp(keyword, "space") == 0)
charset[CURLFNM_SPACE] = 1;
else if(strcmp(keyword, "blank") == 0)
charset[CURLFNM_BLANK] = 1;
else if(strcmp(keyword, "upper") == 0)
charset[CURLFNM_UPPER] = 1;
else if(strcmp(keyword, "lower") == 0)
charset[CURLFNM_LOWER] = 1;
else
return SETCHARSET_FAIL;
return SETCHARSET_OK;
}
/* Return the character class. */
static char_class charclass(unsigned char c)
{
if(ISUPPER(c))
return CCLASS_UPPER;
if(ISLOWER(c))
return CCLASS_LOWER;
if(ISDIGIT(c))
return CCLASS_DIGIT;
return CCLASS_OTHER;
}
/* Include a character or a range in set. */
static void setcharorrange(unsigned char **pp, unsigned char *charset)
{
unsigned char *p = (*pp)++;
unsigned char c = *p++;
charset[c] = 1;
if(ISALNUM(c) && *p++ == '-') {
char_class cc = charclass(c);
unsigned char endrange = *p++;
if(endrange == '\\')
endrange = *p++;
if(endrange >= c && charclass(endrange) == cc) {
while(c++ != endrange)
if(charclass(c) == cc) /* Chars in class may be not consecutive. */
charset[c] = 1;
*pp = p;
}
}
}
/* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */
static int setcharset(unsigned char **p, unsigned char *charset)
{
setcharset_state state = CURLFNM_SCHS_DEFAULT;
bool something_found = FALSE;
unsigned char c;
memset(charset, 0, CURLFNM_CHSET_SIZE);
for(;;) {
c = **p;
if(!c)
return SETCHARSET_FAIL;
switch(state) {
case CURLFNM_SCHS_DEFAULT:
if(c == ']') {
if(something_found)
return SETCHARSET_OK;
something_found = TRUE;
state = CURLFNM_SCHS_RIGHTBR;
charset[c] = 1;
(*p)++;
}
else if(c == '[') {
unsigned char *pp = *p + 1;
if(*pp++ == ':' && parsekeyword(&pp, charset))
*p = pp;
else {
charset[c] = 1;
(*p)++;
}
something_found = TRUE;
}
else if(c == '^' || c == '!') {
if(!something_found) {
if(charset[CURLFNM_NEGATE]) {
charset[c] = 1;
something_found = TRUE;
}
else
charset[CURLFNM_NEGATE] = 1; /* negate charset */
}
else
charset[c] = 1;
(*p)++;
}
else if(c == '\\') {
c = *(++(*p));
if(c)
setcharorrange(p, charset);
else
charset['\\'] = 1;
something_found = TRUE;
}
else {
setcharorrange(p, charset);
something_found = TRUE;
}
break;
case CURLFNM_SCHS_RIGHTBR:
if(c == '[') {
state = CURLFNM_SCHS_RIGHTBRLEFTBR;
charset[c] = 1;
(*p)++;
}
else if(c == ']') {
return SETCHARSET_OK;
}
else if(ISPRINT(c)) {
charset[c] = 1;
(*p)++;
state = CURLFNM_SCHS_DEFAULT;
}
else
/* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a
* nonsense warning 'statement not reached' at end of the fnc when
* compiling on Solaris */
goto fail;
break;
case CURLFNM_SCHS_RIGHTBRLEFTBR:
if(c == ']')
return SETCHARSET_OK;
state = CURLFNM_SCHS_DEFAULT;
charset[c] = 1;
(*p)++;
break;
}
}
fail:
return SETCHARSET_FAIL;
}
static int loop(const unsigned char *pattern, const unsigned char *string,
int maxstars)
{
unsigned char *p = (unsigned char *)pattern;
unsigned char *s = (unsigned char *)string;
unsigned char charset[CURLFNM_CHSET_SIZE] = { 0 };
for(;;) {
unsigned char *pp;
switch(*p) {
case '*':
if(!maxstars)
return CURL_FNMATCH_NOMATCH;
/* Regroup consecutive stars and question marks. This can be done because
'*?*?*' can be expressed as '??*'. */
for(;;) {
if(*++p == '\0')
return CURL_FNMATCH_MATCH;
if(*p == '?') {
if(!*s++)
return CURL_FNMATCH_NOMATCH;
}
else if(*p != '*')
break;
}
/* Skip string characters until we find a match with pattern suffix. */
for(maxstars--; *s; s++) {
if(loop(p, s, maxstars) == CURL_FNMATCH_MATCH)
return CURL_FNMATCH_MATCH;
}
return CURL_FNMATCH_NOMATCH;
case '?':
if(!*s)
return CURL_FNMATCH_NOMATCH;
s++;
p++;
break;
case '\0':
return *s? CURL_FNMATCH_NOMATCH: CURL_FNMATCH_MATCH;
case '\\':
if(p[1])
p++;
if(*s++ != *p++)
return CURL_FNMATCH_NOMATCH;
break;
case '[':
pp = p + 1; /* Copy in case of syntax error in set. */
if(setcharset(&pp, charset)) {
int found = FALSE;
if(!*s)
return CURL_FNMATCH_NOMATCH;
if(charset[(unsigned int)*s])
found = TRUE;
else if(charset[CURLFNM_ALNUM])
found = ISALNUM(*s);
else if(charset[CURLFNM_ALPHA])
found = ISALPHA(*s);
else if(charset[CURLFNM_DIGIT])
found = ISDIGIT(*s);
else if(charset[CURLFNM_XDIGIT])
found = ISXDIGIT(*s);
else if(charset[CURLFNM_PRINT])
found = ISPRINT(*s);
else if(charset[CURLFNM_SPACE])
found = ISSPACE(*s);
else if(charset[CURLFNM_UPPER])
found = ISUPPER(*s);
else if(charset[CURLFNM_LOWER])
found = ISLOWER(*s);
else if(charset[CURLFNM_BLANK])
found = ISBLANK(*s);
else if(charset[CURLFNM_GRAPH])
found = ISGRAPH(*s);
if(charset[CURLFNM_NEGATE])
found = !found;
if(!found)
return CURL_FNMATCH_NOMATCH;
p = pp + 1;
s++;
break;
}
/* Syntax error in set; mismatch! */
return CURL_FNMATCH_NOMATCH;
default:
if(*p++ != *s++)
return CURL_FNMATCH_NOMATCH;
break;
}
}
}
/*
* @unittest: 1307
*/
int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
{
(void)ptr; /* the argument is specified by the curl_fnmatch_callback
prototype, but not used by Curl_fnmatch() */
if(!pattern || !string) {
return CURL_FNMATCH_FAIL;
}
return loop((unsigned char *)pattern, (unsigned char *)string, 2);
}
#else
#include <fnmatch.h>
/*
* @unittest: 1307
*/
int Curl_fnmatch(void *ptr, const char *pattern, const char *string)
{
int rc;
(void)ptr; /* the argument is specified by the curl_fnmatch_callback
prototype, but not used by Curl_fnmatch() */
if(!pattern || !string) {
return CURL_FNMATCH_FAIL;
}
rc = fnmatch(pattern, string, 0);
switch(rc) {
case 0:
return CURL_FNMATCH_MATCH;
case FNM_NOMATCH:
return CURL_FNMATCH_NOMATCH;
default:
return CURL_FNMATCH_FAIL;
}
/* not reached */
}
#endif
#endif /* if FTP is disabled */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/conncache.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2012 - 2016, Linus Nielsen Feltzing, <[email protected]>
* Copyright (C) 2012 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "url.h"
#include "progress.h"
#include "multiif.h"
#include "sendf.h"
#include "conncache.h"
#include "share.h"
#include "sigpipe.h"
#include "connect.h"
#include "strcase.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#define HASHKEY_SIZE 128
static void conn_llist_dtor(void *user, void *element)
{
struct connectdata *conn = element;
(void)user;
conn->bundle = NULL;
}
static CURLcode bundle_create(struct connectbundle **bundlep)
{
DEBUGASSERT(*bundlep == NULL);
*bundlep = malloc(sizeof(struct connectbundle));
if(!*bundlep)
return CURLE_OUT_OF_MEMORY;
(*bundlep)->num_connections = 0;
(*bundlep)->multiuse = BUNDLE_UNKNOWN;
Curl_llist_init(&(*bundlep)->conn_list, (Curl_llist_dtor) conn_llist_dtor);
return CURLE_OK;
}
static void bundle_destroy(struct connectbundle *bundle)
{
if(!bundle)
return;
Curl_llist_destroy(&bundle->conn_list, NULL);
free(bundle);
}
/* Add a connection to a bundle */
static void bundle_add_conn(struct connectbundle *bundle,
struct connectdata *conn)
{
Curl_llist_insert_next(&bundle->conn_list, bundle->conn_list.tail, conn,
&conn->bundle_node);
conn->bundle = bundle;
bundle->num_connections++;
}
/* Remove a connection from a bundle */
static int bundle_remove_conn(struct connectbundle *bundle,
struct connectdata *conn)
{
struct Curl_llist_element *curr;
curr = bundle->conn_list.head;
while(curr) {
if(curr->ptr == conn) {
Curl_llist_remove(&bundle->conn_list, curr, NULL);
bundle->num_connections--;
conn->bundle = NULL;
return 1; /* we removed a handle */
}
curr = curr->next;
}
DEBUGASSERT(0);
return 0;
}
static void free_bundle_hash_entry(void *freethis)
{
struct connectbundle *b = (struct connectbundle *) freethis;
bundle_destroy(b);
}
int Curl_conncache_init(struct conncache *connc, int size)
{
int rc;
/* allocate a new easy handle to use when closing cached connections */
connc->closure_handle = curl_easy_init();
if(!connc->closure_handle)
return 1; /* bad */
rc = Curl_hash_init(&connc->hash, size, Curl_hash_str,
Curl_str_key_compare, free_bundle_hash_entry);
if(rc)
Curl_close(&connc->closure_handle);
else
connc->closure_handle->state.conn_cache = connc;
return rc;
}
void Curl_conncache_destroy(struct conncache *connc)
{
if(connc)
Curl_hash_destroy(&connc->hash);
}
/* creates a key to find a bundle for this connection */
static void hashkey(struct connectdata *conn, char *buf,
size_t len, /* something like 128 is fine */
const char **hostp)
{
const char *hostname;
long port = conn->remote_port;
#ifndef CURL_DISABLE_PROXY
if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
hostname = conn->http_proxy.host.name;
port = conn->port;
}
else
#endif
if(conn->bits.conn_to_host)
hostname = conn->conn_to_host.name;
else
hostname = conn->host.name;
if(hostp)
/* report back which name we used */
*hostp = hostname;
/* put the number first so that the hostname gets cut off if too long */
msnprintf(buf, len, "%ld%s", port, hostname);
Curl_strntolower(buf, buf, len);
}
/* Returns number of connections currently held in the connection cache.
Locks/unlocks the cache itself!
*/
size_t Curl_conncache_size(struct Curl_easy *data)
{
size_t num;
CONNCACHE_LOCK(data);
num = data->state.conn_cache->num_conn;
CONNCACHE_UNLOCK(data);
return num;
}
/* Look up the bundle with all the connections to the same host this
connectdata struct is setup to use.
**NOTE**: When it returns, it holds the connection cache lock! */
struct connectbundle *
Curl_conncache_find_bundle(struct Curl_easy *data,
struct connectdata *conn,
struct conncache *connc,
const char **hostp)
{
struct connectbundle *bundle = NULL;
CONNCACHE_LOCK(data);
if(connc) {
char key[HASHKEY_SIZE];
hashkey(conn, key, sizeof(key), hostp);
bundle = Curl_hash_pick(&connc->hash, key, strlen(key));
}
return bundle;
}
static bool conncache_add_bundle(struct conncache *connc,
char *key,
struct connectbundle *bundle)
{
void *p = Curl_hash_add(&connc->hash, key, strlen(key), bundle);
return p?TRUE:FALSE;
}
static void conncache_remove_bundle(struct conncache *connc,
struct connectbundle *bundle)
{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
if(!connc)
return;
Curl_hash_start_iterate(&connc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
if(he->ptr == bundle) {
/* The bundle is destroyed by the hash destructor function,
free_bundle_hash_entry() */
Curl_hash_delete(&connc->hash, he->key, he->key_len);
return;
}
he = Curl_hash_next_element(&iter);
}
}
CURLcode Curl_conncache_add_conn(struct Curl_easy *data)
{
CURLcode result = CURLE_OK;
struct connectbundle *bundle = NULL;
struct connectdata *conn = data->conn;
struct conncache *connc = data->state.conn_cache;
DEBUGASSERT(conn);
/* *find_bundle() locks the connection cache */
bundle = Curl_conncache_find_bundle(data, conn, data->state.conn_cache,
NULL);
if(!bundle) {
int rc;
char key[HASHKEY_SIZE];
result = bundle_create(&bundle);
if(result) {
goto unlock;
}
hashkey(conn, key, sizeof(key), NULL);
rc = conncache_add_bundle(data->state.conn_cache, key, bundle);
if(!rc) {
bundle_destroy(bundle);
result = CURLE_OUT_OF_MEMORY;
goto unlock;
}
}
bundle_add_conn(bundle, conn);
conn->connection_id = connc->next_connection_id++;
connc->num_conn++;
DEBUGF(infof(data, "Added connection %ld. "
"The cache now contains %zu members",
conn->connection_id, connc->num_conn));
unlock:
CONNCACHE_UNLOCK(data);
return result;
}
/*
* Removes the connectdata object from the connection cache, but the transfer
* still owns this connection.
*
* Pass TRUE/FALSE in the 'lock' argument depending on if the parent function
* already holds the lock or not.
*/
void Curl_conncache_remove_conn(struct Curl_easy *data,
struct connectdata *conn, bool lock)
{
struct connectbundle *bundle = conn->bundle;
struct conncache *connc = data->state.conn_cache;
/* The bundle pointer can be NULL, since this function can be called
due to a failed connection attempt, before being added to a bundle */
if(bundle) {
if(lock) {
CONNCACHE_LOCK(data);
}
bundle_remove_conn(bundle, conn);
if(bundle->num_connections == 0)
conncache_remove_bundle(connc, bundle);
conn->bundle = NULL; /* removed from it */
if(connc) {
connc->num_conn--;
DEBUGF(infof(data, "The cache now contains %zu members",
connc->num_conn));
}
if(lock) {
CONNCACHE_UNLOCK(data);
}
}
}
/* This function iterates the entire connection cache and calls the function
func() with the connection pointer as the first argument and the supplied
'param' argument as the other.
The conncache lock is still held when the callback is called. It needs it,
so that it can safely continue traversing the lists once the callback
returns.
Returns 1 if the loop was aborted due to the callback's return code.
Return 0 from func() to continue the loop, return 1 to abort it.
*/
bool Curl_conncache_foreach(struct Curl_easy *data,
struct conncache *connc,
void *param,
int (*func)(struct Curl_easy *data,
struct connectdata *conn, void *param))
{
struct Curl_hash_iterator iter;
struct Curl_llist_element *curr;
struct Curl_hash_element *he;
if(!connc)
return FALSE;
CONNCACHE_LOCK(data);
Curl_hash_start_iterate(&connc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
struct connectbundle *bundle;
bundle = he->ptr;
he = Curl_hash_next_element(&iter);
curr = bundle->conn_list.head;
while(curr) {
/* Yes, we need to update curr before calling func(), because func()
might decide to remove the connection */
struct connectdata *conn = curr->ptr;
curr = curr->next;
if(1 == func(data, conn, param)) {
CONNCACHE_UNLOCK(data);
return TRUE;
}
}
}
CONNCACHE_UNLOCK(data);
return FALSE;
}
/* Return the first connection found in the cache. Used when closing all
connections.
NOTE: no locking is done here as this is presumably only done when cleaning
up a cache!
*/
static struct connectdata *
conncache_find_first_connection(struct conncache *connc)
{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
struct connectbundle *bundle;
Curl_hash_start_iterate(&connc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
struct Curl_llist_element *curr;
bundle = he->ptr;
curr = bundle->conn_list.head;
if(curr) {
return curr->ptr;
}
he = Curl_hash_next_element(&iter);
}
return NULL;
}
/*
* Give ownership of a connection back to the connection cache. Might
* disconnect the oldest existing in there to make space.
*
* Return TRUE if stored, FALSE if closed.
*/
bool Curl_conncache_return_conn(struct Curl_easy *data,
struct connectdata *conn)
{
/* data->multi->maxconnects can be negative, deal with it. */
size_t maxconnects =
(data->multi->maxconnects < 0) ? data->multi->num_easy * 4:
data->multi->maxconnects;
struct connectdata *conn_candidate = NULL;
conn->lastused = Curl_now(); /* it was used up until now */
if(maxconnects > 0 &&
Curl_conncache_size(data) > maxconnects) {
infof(data, "Connection cache is full, closing the oldest one");
conn_candidate = Curl_conncache_extract_oldest(data);
if(conn_candidate) {
/* the winner gets the honour of being disconnected */
(void)Curl_disconnect(data, conn_candidate, /* dead_connection */ FALSE);
}
}
return (conn_candidate == conn) ? FALSE : TRUE;
}
/*
* This function finds the connection in the connection bundle that has been
* unused for the longest time.
*
* Does not lock the connection cache!
*
* Returns the pointer to the oldest idle connection, or NULL if none was
* found.
*/
struct connectdata *
Curl_conncache_extract_bundle(struct Curl_easy *data,
struct connectbundle *bundle)
{
struct Curl_llist_element *curr;
timediff_t highscore = -1;
timediff_t score;
struct curltime now;
struct connectdata *conn_candidate = NULL;
struct connectdata *conn;
(void)data;
now = Curl_now();
curr = bundle->conn_list.head;
while(curr) {
conn = curr->ptr;
if(!CONN_INUSE(conn)) {
/* Set higher score for the age passed since the connection was used */
score = Curl_timediff(now, conn->lastused);
if(score > highscore) {
highscore = score;
conn_candidate = conn;
}
}
curr = curr->next;
}
if(conn_candidate) {
/* remove it to prevent another thread from nicking it */
bundle_remove_conn(bundle, conn_candidate);
data->state.conn_cache->num_conn--;
DEBUGF(infof(data, "The cache now contains %zu members",
data->state.conn_cache->num_conn));
}
return conn_candidate;
}
/*
* This function finds the connection in the connection cache that has been
* unused for the longest time and extracts that from the bundle.
*
* Returns the pointer to the connection, or NULL if none was found.
*/
struct connectdata *
Curl_conncache_extract_oldest(struct Curl_easy *data)
{
struct conncache *connc = data->state.conn_cache;
struct Curl_hash_iterator iter;
struct Curl_llist_element *curr;
struct Curl_hash_element *he;
timediff_t highscore =- 1;
timediff_t score;
struct curltime now;
struct connectdata *conn_candidate = NULL;
struct connectbundle *bundle;
struct connectbundle *bundle_candidate = NULL;
now = Curl_now();
CONNCACHE_LOCK(data);
Curl_hash_start_iterate(&connc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
struct connectdata *conn;
bundle = he->ptr;
curr = bundle->conn_list.head;
while(curr) {
conn = curr->ptr;
if(!CONN_INUSE(conn) && !conn->bits.close &&
!conn->bits.connect_only) {
/* Set higher score for the age passed since the connection was used */
score = Curl_timediff(now, conn->lastused);
if(score > highscore) {
highscore = score;
conn_candidate = conn;
bundle_candidate = bundle;
}
}
curr = curr->next;
}
he = Curl_hash_next_element(&iter);
}
if(conn_candidate) {
/* remove it to prevent another thread from nicking it */
bundle_remove_conn(bundle_candidate, conn_candidate);
connc->num_conn--;
DEBUGF(infof(data, "The cache now contains %zu members",
connc->num_conn));
}
CONNCACHE_UNLOCK(data);
return conn_candidate;
}
void Curl_conncache_close_all_connections(struct conncache *connc)
{
struct connectdata *conn;
char buffer[READBUFFER_MIN + 1];
if(!connc->closure_handle)
return;
connc->closure_handle->state.buffer = buffer;
connc->closure_handle->set.buffer_size = READBUFFER_MIN;
conn = conncache_find_first_connection(connc);
while(conn) {
SIGPIPE_VARIABLE(pipe_st);
sigpipe_ignore(connc->closure_handle, &pipe_st);
/* This will remove the connection from the cache */
connclose(conn, "kill all");
Curl_conncache_remove_conn(connc->closure_handle, conn, TRUE);
(void)Curl_disconnect(connc->closure_handle, conn, FALSE);
sigpipe_restore(&pipe_st);
conn = conncache_find_first_connection(connc);
}
connc->closure_handle->state.buffer = NULL;
if(connc->closure_handle) {
SIGPIPE_VARIABLE(pipe_st);
sigpipe_ignore(connc->closure_handle, &pipe_st);
Curl_hostcache_clean(connc->closure_handle,
connc->closure_handle->dns.hostcache);
Curl_close(&connc->closure_handle);
sigpipe_restore(&pipe_st);
}
}
#if 0
/* Useful for debugging the connection cache */
void Curl_conncache_print(struct conncache *connc)
{
struct Curl_hash_iterator iter;
struct Curl_llist_element *curr;
struct Curl_hash_element *he;
if(!connc)
return;
fprintf(stderr, "=Bundle cache=\n");
Curl_hash_start_iterate(connc->hash, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
struct connectbundle *bundle;
struct connectdata *conn;
bundle = he->ptr;
fprintf(stderr, "%s -", he->key);
curr = bundle->conn_list->head;
while(curr) {
conn = curr->ptr;
fprintf(stderr, " [%p %d]", (void *)conn, conn->inuse);
curr = curr->next;
}
fprintf(stderr, "\n");
he = Curl_hash_next_element(&iter);
}
}
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/hash.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "hash.h"
#include "llist.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
static void
hash_element_dtor(void *user, void *element)
{
struct Curl_hash *h = (struct Curl_hash *) user;
struct Curl_hash_element *e = (struct Curl_hash_element *) element;
if(e->ptr) {
h->dtor(e->ptr);
e->ptr = NULL;
}
e->key_len = 0;
free(e);
}
/* Initializes a hash structure.
* Return 1 on error, 0 is fine.
*
* @unittest: 1602
* @unittest: 1603
*/
int
Curl_hash_init(struct Curl_hash *h,
int slots,
hash_function hfunc,
comp_function comparator,
Curl_hash_dtor dtor)
{
if(!slots || !hfunc || !comparator ||!dtor) {
return 1; /* failure */
}
h->hash_func = hfunc;
h->comp_func = comparator;
h->dtor = dtor;
h->size = 0;
h->slots = slots;
h->table = malloc(slots * sizeof(struct Curl_llist));
if(h->table) {
int i;
for(i = 0; i < slots; ++i)
Curl_llist_init(&h->table[i], (Curl_llist_dtor) hash_element_dtor);
return 0; /* fine */
}
h->slots = 0;
return 1; /* failure */
}
static struct Curl_hash_element *
mk_hash_element(const void *key, size_t key_len, const void *p)
{
/* allocate the struct plus memory after it to store the key */
struct Curl_hash_element *he = malloc(sizeof(struct Curl_hash_element) +
key_len);
if(he) {
/* copy the key */
memcpy(he->key, key, key_len);
he->key_len = key_len;
he->ptr = (void *) p;
}
return he;
}
#define FETCH_LIST(x,y,z) &x->table[x->hash_func(y, z, x->slots)]
/* Insert the data in the hash. If there already was a match in the hash,
* that data is replaced.
*
* @unittest: 1305
* @unittest: 1602
* @unittest: 1603
*/
void *
Curl_hash_add(struct Curl_hash *h, void *key, size_t key_len, void *p)
{
struct Curl_hash_element *he;
struct Curl_llist_element *le;
struct Curl_llist *l = FETCH_LIST(h, key, key_len);
for(le = l->head; le; le = le->next) {
he = (struct Curl_hash_element *) le->ptr;
if(h->comp_func(he->key, he->key_len, key, key_len)) {
Curl_llist_remove(l, le, (void *)h);
--h->size;
break;
}
}
he = mk_hash_element(key, key_len, p);
if(he) {
Curl_llist_insert_next(l, l->tail, he, &he->list);
++h->size;
return p; /* return the new entry */
}
return NULL; /* failure */
}
/* Remove the identified hash entry.
* Returns non-zero on failure.
*
* @unittest: 1603
*/
int Curl_hash_delete(struct Curl_hash *h, void *key, size_t key_len)
{
struct Curl_llist_element *le;
struct Curl_llist *l = FETCH_LIST(h, key, key_len);
for(le = l->head; le; le = le->next) {
struct Curl_hash_element *he = le->ptr;
if(h->comp_func(he->key, he->key_len, key, key_len)) {
Curl_llist_remove(l, le, (void *) h);
--h->size;
return 0;
}
}
return 1;
}
/* Retrieves a hash element.
*
* @unittest: 1603
*/
void *
Curl_hash_pick(struct Curl_hash *h, void *key, size_t key_len)
{
struct Curl_llist_element *le;
struct Curl_llist *l;
if(h) {
l = FETCH_LIST(h, key, key_len);
for(le = l->head; le; le = le->next) {
struct Curl_hash_element *he = le->ptr;
if(h->comp_func(he->key, he->key_len, key, key_len)) {
return he->ptr;
}
}
}
return NULL;
}
#if defined(DEBUGBUILD) && defined(AGGRESSIVE_TEST)
void
Curl_hash_apply(Curl_hash *h, void *user,
void (*cb)(void *user, void *ptr))
{
struct Curl_llist_element *le;
int i;
for(i = 0; i < h->slots; ++i) {
for(le = (h->table[i])->head;
le;
le = le->next) {
Curl_hash_element *el = le->ptr;
cb(user, el->ptr);
}
}
}
#endif
/* Destroys all the entries in the given hash and resets its attributes,
* prepping the given hash for [static|dynamic] deallocation.
*
* @unittest: 1305
* @unittest: 1602
* @unittest: 1603
*/
void
Curl_hash_destroy(struct Curl_hash *h)
{
int i;
for(i = 0; i < h->slots; ++i) {
Curl_llist_destroy(&h->table[i], (void *) h);
}
Curl_safefree(h->table);
h->size = 0;
h->slots = 0;
}
/* Removes all the entries in the given hash.
*
* @unittest: 1602
*/
void
Curl_hash_clean(struct Curl_hash *h)
{
Curl_hash_clean_with_criterium(h, NULL, NULL);
}
/* Cleans all entries that pass the comp function criteria. */
void
Curl_hash_clean_with_criterium(struct Curl_hash *h, void *user,
int (*comp)(void *, void *))
{
struct Curl_llist_element *le;
struct Curl_llist_element *lnext;
struct Curl_llist *list;
int i;
if(!h)
return;
for(i = 0; i < h->slots; ++i) {
list = &h->table[i];
le = list->head; /* get first list entry */
while(le) {
struct Curl_hash_element *he = le->ptr;
lnext = le->next;
/* ask the callback function if we shall remove this entry or not */
if(!comp || comp(user, he->ptr)) {
Curl_llist_remove(list, le, (void *) h);
--h->size; /* one less entry in the hash now */
}
le = lnext;
}
}
}
size_t Curl_hash_str(void *key, size_t key_length, size_t slots_num)
{
const char *key_str = (const char *) key;
const char *end = key_str + key_length;
size_t h = 5381;
while(key_str < end) {
h += h << 5;
h ^= *key_str++;
}
return (h % slots_num);
}
size_t Curl_str_key_compare(void *k1, size_t key1_len,
void *k2, size_t key2_len)
{
if((key1_len == key2_len) && !memcmp(k1, k2, key1_len))
return 1;
return 0;
}
void Curl_hash_start_iterate(struct Curl_hash *hash,
struct Curl_hash_iterator *iter)
{
iter->hash = hash;
iter->slot_index = 0;
iter->current_element = NULL;
}
struct Curl_hash_element *
Curl_hash_next_element(struct Curl_hash_iterator *iter)
{
struct Curl_hash *h = iter->hash;
/* Get the next element in the current list, if any */
if(iter->current_element)
iter->current_element = iter->current_element->next;
/* If we have reached the end of the list, find the next one */
if(!iter->current_element) {
int i;
for(i = iter->slot_index; i < h->slots; i++) {
if(h->table[i].head) {
iter->current_element = h->table[i].head;
iter->slot_index = i + 1;
break;
}
}
}
if(iter->current_element) {
struct Curl_hash_element *he = iter->current_element->ptr;
return he;
}
iter->current_element = NULL;
return NULL;
}
#if 0 /* useful function for debugging hashes and their contents */
void Curl_hash_print(struct Curl_hash *h,
void (*func)(void *))
{
struct Curl_hash_iterator iter;
struct Curl_hash_element *he;
int last_index = -1;
if(!h)
return;
fprintf(stderr, "=Hash dump=\n");
Curl_hash_start_iterate(h, &iter);
he = Curl_hash_next_element(&iter);
while(he) {
if(iter.slot_index != last_index) {
fprintf(stderr, "index %d:", iter.slot_index);
if(last_index >= 0) {
fprintf(stderr, "\n");
}
last_index = iter.slot_index;
}
if(func)
func(he->ptr);
else
fprintf(stderr, " [%p]", (void *)he->ptr);
he = Curl_hash_next_element(&iter);
}
fprintf(stderr, "\n");
}
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/transfer.h | #ifndef HEADER_CURL_TRANSFER_H
#define HEADER_CURL_TRANSFER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#define Curl_headersep(x) ((((x)==':') || ((x)==';')))
char *Curl_checkheaders(const struct Curl_easy *data,
const char *thisheader);
void Curl_init_CONNECT(struct Curl_easy *data);
CURLcode Curl_pretransfer(struct Curl_easy *data);
CURLcode Curl_posttransfer(struct Curl_easy *data);
typedef enum {
FOLLOW_NONE, /* not used within the function, just a placeholder to
allow initing to this */
FOLLOW_FAKE, /* only records stuff, not actually following */
FOLLOW_RETRY, /* set if this is a request retry as opposed to a real
redirect following */
FOLLOW_REDIR /* a full true redirect */
} followtype;
CURLcode Curl_follow(struct Curl_easy *data, char *newurl,
followtype type);
CURLcode Curl_readwrite(struct connectdata *conn,
struct Curl_easy *data, bool *done,
bool *comeback);
int Curl_single_getsock(struct Curl_easy *data,
struct connectdata *conn, curl_socket_t *socks);
CURLcode Curl_readrewind(struct Curl_easy *data);
CURLcode Curl_fillreadbuffer(struct Curl_easy *data, size_t bytes,
size_t *nreadp);
CURLcode Curl_retry_request(struct Curl_easy *data, char **url);
bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc);
CURLcode Curl_get_upload_buffer(struct Curl_easy *data);
CURLcode Curl_done_sending(struct Curl_easy *data,
struct SingleRequest *k);
/* This sets up a forthcoming transfer */
void
Curl_setup_transfer (struct Curl_easy *data,
int sockindex, /* socket index to read from or -1 */
curl_off_t size, /* -1 if unknown at this point */
bool getheader, /* TRUE if header parsing is wanted */
int writesockindex /* socket index to write to. May be
the same we read from. -1
disables */
);
#endif /* HEADER_CURL_TRANSFER_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/share.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "share.h"
#include "psl.h"
#include "vtls/vtls.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
struct Curl_share *
curl_share_init(void)
{
struct Curl_share *share = calloc(1, sizeof(struct Curl_share));
if(share) {
share->magic = CURL_GOOD_SHARE;
share->specifier |= (1<<CURL_LOCK_DATA_SHARE);
if(Curl_mk_dnscache(&share->hostcache)) {
free(share);
return NULL;
}
}
return share;
}
#undef curl_share_setopt
CURLSHcode
curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)
{
va_list param;
int type;
curl_lock_function lockfunc;
curl_unlock_function unlockfunc;
void *ptr;
CURLSHcode res = CURLSHE_OK;
if(!GOOD_SHARE_HANDLE(share))
return CURLSHE_INVALID;
if(share->dirty)
/* don't allow setting options while one or more handles are already
using this share */
return CURLSHE_IN_USE;
va_start(param, option);
switch(option) {
case CURLSHOPT_SHARE:
/* this is a type this share will share */
type = va_arg(param, int);
switch(type) {
case CURL_LOCK_DATA_DNS:
break;
case CURL_LOCK_DATA_COOKIE:
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
if(!share->cookies) {
share->cookies = Curl_cookie_init(NULL, NULL, NULL, TRUE);
if(!share->cookies)
res = CURLSHE_NOMEM;
}
#else /* CURL_DISABLE_HTTP */
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
case CURL_LOCK_DATA_SSL_SESSION:
#ifdef USE_SSL
if(!share->sslsession) {
share->max_ssl_sessions = 8;
share->sslsession = calloc(share->max_ssl_sessions,
sizeof(struct Curl_ssl_session));
share->sessionage = 0;
if(!share->sslsession)
res = CURLSHE_NOMEM;
}
#else
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
case CURL_LOCK_DATA_CONNECT:
if(Curl_conncache_init(&share->conn_cache, 103))
res = CURLSHE_NOMEM;
break;
case CURL_LOCK_DATA_PSL:
#ifndef USE_LIBPSL
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
default:
res = CURLSHE_BAD_OPTION;
}
if(!res)
share->specifier |= (1<<type);
break;
case CURLSHOPT_UNSHARE:
/* this is a type this share will no longer share */
type = va_arg(param, int);
share->specifier &= ~(1<<type);
switch(type) {
case CURL_LOCK_DATA_DNS:
break;
case CURL_LOCK_DATA_COOKIE:
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
if(share->cookies) {
Curl_cookie_cleanup(share->cookies);
share->cookies = NULL;
}
#else /* CURL_DISABLE_HTTP */
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
case CURL_LOCK_DATA_SSL_SESSION:
#ifdef USE_SSL
Curl_safefree(share->sslsession);
#else
res = CURLSHE_NOT_BUILT_IN;
#endif
break;
case CURL_LOCK_DATA_CONNECT:
break;
default:
res = CURLSHE_BAD_OPTION;
break;
}
break;
case CURLSHOPT_LOCKFUNC:
lockfunc = va_arg(param, curl_lock_function);
share->lockfunc = lockfunc;
break;
case CURLSHOPT_UNLOCKFUNC:
unlockfunc = va_arg(param, curl_unlock_function);
share->unlockfunc = unlockfunc;
break;
case CURLSHOPT_USERDATA:
ptr = va_arg(param, void *);
share->clientdata = ptr;
break;
default:
res = CURLSHE_BAD_OPTION;
break;
}
va_end(param);
return res;
}
CURLSHcode
curl_share_cleanup(struct Curl_share *share)
{
if(!GOOD_SHARE_HANDLE(share))
return CURLSHE_INVALID;
if(share->lockfunc)
share->lockfunc(NULL, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE,
share->clientdata);
if(share->dirty) {
if(share->unlockfunc)
share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
return CURLSHE_IN_USE;
}
Curl_conncache_close_all_connections(&share->conn_cache);
Curl_conncache_destroy(&share->conn_cache);
Curl_hash_destroy(&share->hostcache);
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
Curl_cookie_cleanup(share->cookies);
#endif
#ifdef USE_SSL
if(share->sslsession) {
size_t i;
for(i = 0; i < share->max_ssl_sessions; i++)
Curl_ssl_kill_session(&(share->sslsession[i]));
free(share->sslsession);
}
#endif
Curl_psl_destroy(&share->psl);
if(share->unlockfunc)
share->unlockfunc(NULL, CURL_LOCK_DATA_SHARE, share->clientdata);
share->magic = 0;
free(share);
return CURLSHE_OK;
}
CURLSHcode
Curl_share_lock(struct Curl_easy *data, curl_lock_data type,
curl_lock_access accesstype)
{
struct Curl_share *share = data->share;
if(!share)
return CURLSHE_INVALID;
if(share->specifier & (1<<type)) {
if(share->lockfunc) /* only call this if set! */
share->lockfunc(data, type, accesstype, share->clientdata);
}
/* else if we don't share this, pretend successful lock */
return CURLSHE_OK;
}
CURLSHcode
Curl_share_unlock(struct Curl_easy *data, curl_lock_data type)
{
struct Curl_share *share = data->share;
if(!share)
return CURLSHE_INVALID;
if(share->specifier & (1<<type)) {
if(share->unlockfunc) /* only call this if set! */
share->unlockfunc (data, type, share->clientdata);
}
return CURLSHE_OK;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/dynbuf.h | #ifndef HEADER_CURL_DYNBUF_H
#define HEADER_CURL_DYNBUF_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2020, 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifndef BUILDING_LIBCURL
/* this renames the functions so that the tool code can use the same code
without getting symbol collisions */
#define Curl_dyn_init(a,b) curlx_dyn_init(a,b)
#define Curl_dyn_add(a,b) curlx_dyn_add(a,b)
#define Curl_dyn_addn(a,b,c) curlx_dyn_addn(a,b,c)
#define Curl_dyn_addf curlx_dyn_addf
#define Curl_dyn_vaddf curlx_dyn_vaddf
#define Curl_dyn_free(a) curlx_dyn_free(a)
#define Curl_dyn_ptr(a) curlx_dyn_ptr(a)
#define Curl_dyn_uptr(a) curlx_dyn_uptr(a)
#define Curl_dyn_len(a) curlx_dyn_len(a)
#define Curl_dyn_reset(a) curlx_dyn_reset(a)
#define Curl_dyn_tail(a,b) curlx_dyn_tail(a,b)
#define curlx_dynbuf dynbuf /* for the struct name */
#endif
struct dynbuf {
char *bufr; /* point to a null-terminated allocated buffer */
size_t leng; /* number of bytes *EXCLUDING* the zero terminator */
size_t allc; /* size of the current allocation */
size_t toobig; /* size limit for the buffer */
#ifdef DEBUGBUILD
int init; /* detect API usage mistakes */
#endif
};
void Curl_dyn_init(struct dynbuf *s, size_t toobig);
void Curl_dyn_free(struct dynbuf *s);
CURLcode Curl_dyn_addn(struct dynbuf *s, const void *mem, size_t len)
WARN_UNUSED_RESULT;
CURLcode Curl_dyn_add(struct dynbuf *s, const char *str)
WARN_UNUSED_RESULT;
CURLcode Curl_dyn_addf(struct dynbuf *s, const char *fmt, ...)
WARN_UNUSED_RESULT;
CURLcode Curl_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap)
WARN_UNUSED_RESULT;
void Curl_dyn_reset(struct dynbuf *s);
CURLcode Curl_dyn_tail(struct dynbuf *s, size_t trail);
char *Curl_dyn_ptr(const struct dynbuf *s);
unsigned char *Curl_dyn_uptr(const struct dynbuf *s);
size_t Curl_dyn_len(const struct dynbuf *s);
/* returns 0 on success, -1 on error */
/* The implementation of this function exists in mprintf.c */
int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save);
/* Dynamic buffer max sizes */
#define DYN_DOH_RESPONSE 3000
#define DYN_DOH_CNAME 256
#define DYN_PAUSE_BUFFER (64 * 1024 * 1024)
#define DYN_HAXPROXY 2048
#define DYN_HTTP_REQUEST (1024*1024)
#define DYN_H2_HEADERS (128*1024)
#define DYN_H2_TRAILERS (128*1024)
#define DYN_APRINTF 8000000
#define DYN_RTSP_REQ_HEADER (64*1024)
#define DYN_TRAILERS (64*1024)
#define DYN_PROXY_CONNECT_HEADERS 16384
#define DYN_QLOG_NAME 1024
#define DYN_H1_TRAILER 4096
#define DYN_PINGPPONG_CMD (64*1024)
#define DYN_IMAP_CMD (64*1024)
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strdup.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#ifdef WIN32
#include <wchar.h>
#endif
#include "strdup.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
#ifndef HAVE_STRDUP
char *curlx_strdup(const char *str)
{
size_t len;
char *newstr;
if(!str)
return (char *)NULL;
len = strlen(str) + 1;
newstr = malloc(len);
if(!newstr)
return (char *)NULL;
memcpy(newstr, str, len);
return newstr;
}
#endif
#ifdef WIN32
/***************************************************************************
*
* Curl_wcsdup(source)
*
* Copies the 'source' wchar string to a newly allocated buffer (that is
* returned).
*
* Returns the new pointer or NULL on failure.
*
***************************************************************************/
wchar_t *Curl_wcsdup(const wchar_t *src)
{
size_t length = wcslen(src);
if(length > (SIZE_T_MAX / sizeof(wchar_t)) - 1)
return (wchar_t *)NULL; /* integer overflow */
return (wchar_t *)Curl_memdup(src, (length + 1) * sizeof(wchar_t));
}
#endif
/***************************************************************************
*
* Curl_memdup(source, length)
*
* Copies the 'source' data to a newly allocated buffer (that is
* returned). Copies 'length' bytes.
*
* Returns the new pointer or NULL on failure.
*
***************************************************************************/
void *Curl_memdup(const void *src, size_t length)
{
void *buffer = malloc(length);
if(!buffer)
return NULL; /* fail */
memcpy(buffer, src, length);
return buffer;
}
/***************************************************************************
*
* Curl_saferealloc(ptr, size)
*
* Does a normal realloc(), but will free the data pointer if the realloc
* fails. If 'size' is non-zero, it will free the data and return a failure.
*
* This convenience function is provided and used to help us avoid a common
* mistake pattern when we could pass in a zero, catch the NULL return and end
* up free'ing the memory twice.
*
* Returns the new pointer or NULL on failure.
*
***************************************************************************/
void *Curl_saferealloc(void *ptr, size_t size)
{
void *datap = realloc(ptr, size);
if(size && !datap)
/* only free 'ptr' if size was non-zero */
free(ptr);
return datap;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/inet_pton.c | /* This is from the BIND 4.9.4 release, modified to compile by itself */
/* Copyright (c) 1996 - 2020 by 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.
*/
#include "curl_setup.h"
#ifndef HAVE_INET_PTON
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "inet_pton.h"
#define IN6ADDRSZ 16
#define INADDRSZ 4
#define INT16SZ 2
/*
* WARNING: Don't even consider trying to compile this on a system where
* sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
*/
static int inet_pton4(const char *src, unsigned char *dst);
#ifdef ENABLE_IPV6
static int inet_pton6(const char *src, unsigned char *dst);
#endif
/* int
* inet_pton(af, src, dst)
* convert from presentation format (which usually means ASCII printable)
* to network format (which is usually some kind of binary format).
* return:
* 1 if the address was valid for the specified address family
* 0 if the address wasn't valid (`dst' is untouched in this case)
* -1 if some other error occurred (`dst' is untouched in this case, too)
* notice:
* On Windows we store the error in the thread errno, not
* in the winsock error code. This is to avoid losing the
* actual last winsock error. So when this function returns
* -1, check errno not SOCKERRNO.
* author:
* Paul Vixie, 1996.
*/
int
Curl_inet_pton(int af, const char *src, void *dst)
{
switch(af) {
case AF_INET:
return (inet_pton4(src, (unsigned char *)dst));
#ifdef ENABLE_IPV6
case AF_INET6:
return (inet_pton6(src, (unsigned char *)dst));
#endif
default:
errno = EAFNOSUPPORT;
return (-1);
}
/* NOTREACHED */
}
/* int
* inet_pton4(src, dst)
* like inet_aton() but without all the hexadecimal and shorthand.
* return:
* 1 if `src' is a valid dotted quad, else 0.
* notice:
* does not touch `dst' unless it's returning 1.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton4(const char *src, unsigned char *dst)
{
static const char digits[] = "0123456789";
int saw_digit, octets, ch;
unsigned char tmp[INADDRSZ], *tp;
saw_digit = 0;
octets = 0;
tp = tmp;
*tp = 0;
while((ch = *src++) != '\0') {
const char *pch;
pch = strchr(digits, ch);
if(pch) {
unsigned int val = *tp * 10 + (unsigned int)(pch - digits);
if(saw_digit && *tp == 0)
return (0);
if(val > 255)
return (0);
*tp = (unsigned char)val;
if(!saw_digit) {
if(++octets > 4)
return (0);
saw_digit = 1;
}
}
else if(ch == '.' && saw_digit) {
if(octets == 4)
return (0);
*++tp = 0;
saw_digit = 0;
}
else
return (0);
}
if(octets < 4)
return (0);
memcpy(dst, tmp, INADDRSZ);
return (1);
}
#ifdef ENABLE_IPV6
/* int
* inet_pton6(src, dst)
* convert presentation level address to network order binary form.
* return:
* 1 if `src' is a valid [RFC1884 2.2] address, else 0.
* notice:
* (1) does not touch `dst' unless it's returning 1.
* (2) :: in a full address is silently ignored.
* credit:
* inspired by Mark Andrews.
* author:
* Paul Vixie, 1996.
*/
static int
inet_pton6(const char *src, unsigned char *dst)
{
static const char xdigits_l[] = "0123456789abcdef",
xdigits_u[] = "0123456789ABCDEF";
unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp;
const char *curtok;
int ch, saw_xdigit;
size_t val;
memset((tp = tmp), 0, IN6ADDRSZ);
endp = tp + IN6ADDRSZ;
colonp = NULL;
/* Leading :: requires some special handling. */
if(*src == ':')
if(*++src != ':')
return (0);
curtok = src;
saw_xdigit = 0;
val = 0;
while((ch = *src++) != '\0') {
const char *xdigits;
const char *pch;
pch = strchr((xdigits = xdigits_l), ch);
if(!pch)
pch = strchr((xdigits = xdigits_u), ch);
if(pch != NULL) {
val <<= 4;
val |= (pch - xdigits);
if(++saw_xdigit > 4)
return (0);
continue;
}
if(ch == ':') {
curtok = src;
if(!saw_xdigit) {
if(colonp)
return (0);
colonp = tp;
continue;
}
if(tp + INT16SZ > endp)
return (0);
*tp++ = (unsigned char) ((val >> 8) & 0xff);
*tp++ = (unsigned char) (val & 0xff);
saw_xdigit = 0;
val = 0;
continue;
}
if(ch == '.' && ((tp + INADDRSZ) <= endp) &&
inet_pton4(curtok, tp) > 0) {
tp += INADDRSZ;
saw_xdigit = 0;
break; /* '\0' was seen by inet_pton4(). */
}
return (0);
}
if(saw_xdigit) {
if(tp + INT16SZ > endp)
return (0);
*tp++ = (unsigned char) ((val >> 8) & 0xff);
*tp++ = (unsigned char) (val & 0xff);
}
if(colonp != NULL) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
const ssize_t n = tp - colonp;
ssize_t i;
if(tp == endp)
return (0);
for(i = 1; i <= n; i++) {
*(endp - i) = *(colonp + n - i);
*(colonp + n - i) = 0;
}
tp = endp;
}
if(tp != endp)
return (0);
memcpy(dst, tmp, IN6ADDRSZ);
return (1);
}
#endif /* ENABLE_IPV6 */
#endif /* HAVE_INET_PTON */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_ntlm_wb.h | #ifndef HEADER_CURL_NTLM_WB_H
#define HEADER_CURL_NTLM_WB_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
/* this is for ntlm header input */
CURLcode Curl_input_ntlm_wb(struct Curl_easy *data,
struct connectdata *conn, bool proxy,
const char *header);
/* this is for creating ntlm header output */
CURLcode Curl_output_ntlm_wb(struct Curl_easy *data, struct connectdata *conn,
bool proxy);
void Curl_http_auth_cleanup_ntlm_wb(struct connectdata *conn);
#endif /* !CURL_DISABLE_HTTP && USE_NTLM && NTLM_WB_ENABLED */
#endif /* HEADER_CURL_NTLM_WB_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/altsvc.h | #ifndef HEADER_CURL_ALTSVC_H
#define HEADER_CURL_ALTSVC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
#include <curl/curl.h>
#include "llist.h"
enum alpnid {
ALPN_none = 0,
ALPN_h1 = CURLALTSVC_H1,
ALPN_h2 = CURLALTSVC_H2,
ALPN_h3 = CURLALTSVC_H3
};
struct althost {
char *host;
unsigned short port;
enum alpnid alpnid;
};
struct altsvc {
struct althost src;
struct althost dst;
time_t expires;
bool persist;
int prio;
struct Curl_llist_element node;
};
struct altsvcinfo {
char *filename;
struct Curl_llist list; /* list of entries */
long flags; /* the publicly set bitmask */
};
const char *Curl_alpnid2str(enum alpnid id);
struct altsvcinfo *Curl_altsvc_init(void);
CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file);
CURLcode Curl_altsvc_save(struct Curl_easy *data,
struct altsvcinfo *asi, const char *file);
CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl);
void Curl_altsvc_cleanup(struct altsvcinfo **altsvc);
CURLcode Curl_altsvc_parse(struct Curl_easy *data,
struct altsvcinfo *altsvc, const char *value,
enum alpnid srcalpn, const char *srchost,
unsigned short srcport);
bool Curl_altsvc_lookup(struct altsvcinfo *asi,
enum alpnid srcalpnid, const char *srchost,
int srcport,
struct altsvc **dstentry,
const int versions); /* CURLALTSVC_H* bits */
#else
/* disabled */
#define Curl_altsvc_save(a,b,c)
#define Curl_altsvc_cleanup(x)
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */
#endif /* HEADER_CURL_ALTSVC_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/imap.h | #ifndef HEADER_CURL_IMAP_H
#define HEADER_CURL_IMAP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2009 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "pingpong.h"
#include "curl_sasl.h"
/****************************************************************************
* IMAP unique setup
***************************************************************************/
typedef enum {
IMAP_STOP, /* do nothing state, stops the state machine */
IMAP_SERVERGREET, /* waiting for the initial greeting immediately after
a connect */
IMAP_CAPABILITY,
IMAP_STARTTLS,
IMAP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS
(multi mode only) */
IMAP_AUTHENTICATE,
IMAP_LOGIN,
IMAP_LIST,
IMAP_SELECT,
IMAP_FETCH,
IMAP_FETCH_FINAL,
IMAP_APPEND,
IMAP_APPEND_FINAL,
IMAP_SEARCH,
IMAP_LOGOUT,
IMAP_LAST /* never used */
} imapstate;
/* This IMAP struct is used in the Curl_easy. All IMAP data that is
connection-oriented must be in imap_conn to properly deal with the fact that
perhaps the Curl_easy is changed between the times the connection is
used. */
struct IMAP {
curl_pp_transfer transfer;
char *mailbox; /* Mailbox to select */
char *uidvalidity; /* UIDVALIDITY to check in select */
char *uid; /* Message UID to fetch */
char *mindex; /* Index in mail box of mail to fetch */
char *section; /* Message SECTION to fetch */
char *partial; /* Message PARTIAL to fetch */
char *query; /* Query to search for */
char *custom; /* Custom request */
char *custom_params; /* Parameters for the custom request */
};
/* imap_conn is used for struct connection-oriented data in the connectdata
struct */
struct imap_conn {
struct pingpong pp;
imapstate state; /* Always use imap.c:state() to change state! */
bool ssldone; /* Is connect() over SSL done? */
bool preauth; /* Is this connection PREAUTH? */
struct SASL sasl; /* SASL-related parameters */
unsigned int preftype; /* Preferred authentication type */
unsigned int cmdid; /* Last used command ID */
char resptag[5]; /* Response tag to wait for */
bool tls_supported; /* StartTLS capability supported by server */
bool login_disabled; /* LOGIN command disabled by server */
bool ir_supported; /* Initial response supported by server */
char *mailbox; /* The last selected mailbox */
char *mailbox_uidvalidity; /* UIDVALIDITY parsed from select response */
struct dynbuf dyn; /* for the IMAP commands */
};
extern const struct Curl_handler Curl_handler_imap;
extern const struct Curl_handler Curl_handler_imaps;
/* Authentication type flags */
#define IMAP_TYPE_CLEARTEXT (1 << 0)
#define IMAP_TYPE_SASL (1 << 1)
/* Authentication type values */
#define IMAP_TYPE_NONE 0
#define IMAP_TYPE_ANY ~0U
#endif /* HEADER_CURL_IMAP_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/memdebug.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef CURLDEBUG
#include <curl/curl.h>
#include "urldata.h"
#define MEMDEBUG_NODEFINES /* don't redefine the standard functions */
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
struct memdebug {
size_t size;
union {
curl_off_t o;
double d;
void *p;
} mem[1];
/* I'm hoping this is the thing with the strictest alignment
* requirements. That also means we waste some space :-( */
};
/*
* Note that these debug functions are very simple and they are meant to
* remain so. For advanced analysis, record a log file and write perl scripts
* to analyze them!
*
* Don't use these with multithreaded test programs!
*/
FILE *curl_dbg_logfile = NULL;
static bool registered_cleanup = FALSE; /* atexit registered cleanup */
static bool memlimit = FALSE; /* enable memory limit */
static long memsize = 0; /* set number of mallocs allowed */
/* LeakSantizier (LSAN) calls _exit() instead of exit() when a leak is detected
on exit so the logfile must be closed explicitly or data could be lost.
Though _exit() does not call atexit handlers such as this, LSAN's call to
_exit() comes after the atexit handlers are called. curl/curl#6620 */
static void curl_dbg_cleanup(void)
{
if(curl_dbg_logfile &&
curl_dbg_logfile != stderr &&
curl_dbg_logfile != stdout) {
fclose(curl_dbg_logfile);
}
curl_dbg_logfile = NULL;
}
/* this sets the log file name */
void curl_dbg_memdebug(const char *logname)
{
if(!curl_dbg_logfile) {
if(logname && *logname)
curl_dbg_logfile = fopen(logname, FOPEN_WRITETEXT);
else
curl_dbg_logfile = stderr;
#ifdef MEMDEBUG_LOG_SYNC
/* Flush the log file after every line so the log isn't lost in a crash */
if(curl_dbg_logfile)
setbuf(curl_dbg_logfile, (char *)NULL);
#endif
}
if(!registered_cleanup)
registered_cleanup = !atexit(curl_dbg_cleanup);
}
/* This function sets the number of malloc() calls that should return
successfully! */
void curl_dbg_memlimit(long limit)
{
if(!memlimit) {
memlimit = TRUE;
memsize = limit;
}
}
/* returns TRUE if this isn't allowed! */
static bool countcheck(const char *func, int line, const char *source)
{
/* if source is NULL, then the call is made internally and this check
should not be made */
if(memlimit && source) {
if(!memsize) {
/* log to file */
curl_dbg_log("LIMIT %s:%d %s reached memlimit\n",
source, line, func);
/* log to stderr also */
fprintf(stderr, "LIMIT %s:%d %s reached memlimit\n",
source, line, func);
fflush(curl_dbg_logfile); /* because it might crash now */
errno = ENOMEM;
return TRUE; /* RETURN ERROR! */
}
else
memsize--; /* countdown */
}
return FALSE; /* allow this */
}
void *curl_dbg_malloc(size_t wantedsize, int line, const char *source)
{
struct memdebug *mem;
size_t size;
DEBUGASSERT(wantedsize != 0);
if(countcheck("malloc", line, source))
return NULL;
/* alloc at least 64 bytes */
size = sizeof(struct memdebug) + wantedsize;
mem = (Curl_cmalloc)(size);
if(mem) {
mem->size = wantedsize;
}
if(source)
curl_dbg_log("MEM %s:%d malloc(%zu) = %p\n",
source, line, wantedsize,
mem ? (void *)mem->mem : (void *)0);
return (mem ? mem->mem : NULL);
}
void *curl_dbg_calloc(size_t wanted_elements, size_t wanted_size,
int line, const char *source)
{
struct memdebug *mem;
size_t size, user_size;
DEBUGASSERT(wanted_elements != 0);
DEBUGASSERT(wanted_size != 0);
if(countcheck("calloc", line, source))
return NULL;
/* alloc at least 64 bytes */
user_size = wanted_size * wanted_elements;
size = sizeof(struct memdebug) + user_size;
mem = (Curl_ccalloc)(1, size);
if(mem)
mem->size = user_size;
if(source)
curl_dbg_log("MEM %s:%d calloc(%zu,%zu) = %p\n",
source, line, wanted_elements, wanted_size,
mem ? (void *)mem->mem : (void *)0);
return (mem ? mem->mem : NULL);
}
char *curl_dbg_strdup(const char *str, int line, const char *source)
{
char *mem;
size_t len;
DEBUGASSERT(str != NULL);
if(countcheck("strdup", line, source))
return NULL;
len = strlen(str) + 1;
mem = curl_dbg_malloc(len, 0, NULL); /* NULL prevents logging */
if(mem)
memcpy(mem, str, len);
if(source)
curl_dbg_log("MEM %s:%d strdup(%p) (%zu) = %p\n",
source, line, (const void *)str, len, (const void *)mem);
return mem;
}
#if defined(WIN32) && defined(UNICODE)
wchar_t *curl_dbg_wcsdup(const wchar_t *str, int line, const char *source)
{
wchar_t *mem;
size_t wsiz, bsiz;
DEBUGASSERT(str != NULL);
if(countcheck("wcsdup", line, source))
return NULL;
wsiz = wcslen(str) + 1;
bsiz = wsiz * sizeof(wchar_t);
mem = curl_dbg_malloc(bsiz, 0, NULL); /* NULL prevents logging */
if(mem)
memcpy(mem, str, bsiz);
if(source)
curl_dbg_log("MEM %s:%d wcsdup(%p) (%zu) = %p\n",
source, line, (void *)str, bsiz, (void *)mem);
return mem;
}
#endif
/* We provide a realloc() that accepts a NULL as pointer, which then
performs a malloc(). In order to work with ares. */
void *curl_dbg_realloc(void *ptr, size_t wantedsize,
int line, const char *source)
{
struct memdebug *mem = NULL;
size_t size = sizeof(struct memdebug) + wantedsize;
DEBUGASSERT(wantedsize != 0);
if(countcheck("realloc", line, source))
return NULL;
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:1684)
/* 1684: conversion from pointer to same-sized integral type */
#endif
if(ptr)
mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
mem = (Curl_crealloc)(mem, size);
if(source)
curl_dbg_log("MEM %s:%d realloc(%p, %zu) = %p\n",
source, line, (void *)ptr, wantedsize,
mem ? (void *)mem->mem : (void *)0);
if(mem) {
mem->size = wantedsize;
return mem->mem;
}
return NULL;
}
void curl_dbg_free(void *ptr, int line, const char *source)
{
if(ptr) {
struct memdebug *mem;
#ifdef __INTEL_COMPILER
# pragma warning(push)
# pragma warning(disable:1684)
/* 1684: conversion from pointer to same-sized integral type */
#endif
mem = (void *)((char *)ptr - offsetof(struct memdebug, mem));
#ifdef __INTEL_COMPILER
# pragma warning(pop)
#endif
/* free for real */
(Curl_cfree)(mem);
}
if(source && ptr)
curl_dbg_log("MEM %s:%d free(%p)\n", source, line, (void *)ptr);
}
curl_socket_t curl_dbg_socket(int domain, int type, int protocol,
int line, const char *source)
{
const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d socket() = %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d socket() = %ld\n" :
"FD %s:%d socket() = %zd\n";
curl_socket_t sockfd;
if(countcheck("socket", line, source))
return CURL_SOCKET_BAD;
sockfd = socket(domain, type, protocol);
if(source && (sockfd != CURL_SOCKET_BAD))
curl_dbg_log(fmt, source, line, sockfd);
return sockfd;
}
SEND_TYPE_RETV curl_dbg_send(SEND_TYPE_ARG1 sockfd,
SEND_QUAL_ARG2 SEND_TYPE_ARG2 buf,
SEND_TYPE_ARG3 len, SEND_TYPE_ARG4 flags, int line,
const char *source)
{
SEND_TYPE_RETV rc;
if(countcheck("send", line, source))
return -1;
rc = send(sockfd, buf, len, flags);
if(source)
curl_dbg_log("SEND %s:%d send(%lu) = %ld\n",
source, line, (unsigned long)len, (long)rc);
return rc;
}
RECV_TYPE_RETV curl_dbg_recv(RECV_TYPE_ARG1 sockfd, RECV_TYPE_ARG2 buf,
RECV_TYPE_ARG3 len, RECV_TYPE_ARG4 flags, int line,
const char *source)
{
RECV_TYPE_RETV rc;
if(countcheck("recv", line, source))
return -1;
rc = recv(sockfd, buf, len, flags);
if(source)
curl_dbg_log("RECV %s:%d recv(%lu) = %ld\n",
source, line, (unsigned long)len, (long)rc);
return rc;
}
#ifdef HAVE_SOCKETPAIR
int curl_dbg_socketpair(int domain, int type, int protocol,
curl_socket_t socket_vector[2],
int line, const char *source)
{
const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d socketpair() = %d %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d socketpair() = %ld %ld\n" :
"FD %s:%d socketpair() = %zd %zd\n";
int res = socketpair(domain, type, protocol, socket_vector);
if(source && (0 == res))
curl_dbg_log(fmt, source, line, socket_vector[0], socket_vector[1]);
return res;
}
#endif
curl_socket_t curl_dbg_accept(curl_socket_t s, void *saddr, void *saddrlen,
int line, const char *source)
{
const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d accept() = %d\n" :
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d accept() = %ld\n" :
"FD %s:%d accept() = %zd\n";
struct sockaddr *addr = (struct sockaddr *)saddr;
curl_socklen_t *addrlen = (curl_socklen_t *)saddrlen;
curl_socket_t sockfd = accept(s, addr, addrlen);
if(source && (sockfd != CURL_SOCKET_BAD))
curl_dbg_log(fmt, source, line, sockfd);
return sockfd;
}
/* separate function to allow libcurl to mark a "faked" close */
void curl_dbg_mark_sclose(curl_socket_t sockfd, int line, const char *source)
{
const char *fmt = (sizeof(curl_socket_t) == sizeof(int)) ?
"FD %s:%d sclose(%d)\n":
(sizeof(curl_socket_t) == sizeof(long)) ?
"FD %s:%d sclose(%ld)\n":
"FD %s:%d sclose(%zd)\n";
if(source)
curl_dbg_log(fmt, source, line, sockfd);
}
/* this is our own defined way to close sockets on *ALL* platforms */
int curl_dbg_sclose(curl_socket_t sockfd, int line, const char *source)
{
int res = sclose(sockfd);
curl_dbg_mark_sclose(sockfd, line, source);
return res;
}
FILE *curl_dbg_fopen(const char *file, const char *mode,
int line, const char *source)
{
FILE *res = fopen(file, mode);
if(source)
curl_dbg_log("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n",
source, line, file, mode, (void *)res);
return res;
}
FILE *curl_dbg_fdopen(int filedes, const char *mode,
int line, const char *source)
{
FILE *res = fdopen(filedes, mode);
if(source)
curl_dbg_log("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n",
source, line, filedes, mode, (void *)res);
return res;
}
int curl_dbg_fclose(FILE *file, int line, const char *source)
{
int res;
DEBUGASSERT(file != NULL);
if(source)
curl_dbg_log("FILE %s:%d fclose(%p)\n",
source, line, (void *)file);
res = fclose(file);
return res;
}
#define LOGLINE_BUFSIZE 1024
/* this does the writing to the memory tracking log file */
void curl_dbg_log(const char *format, ...)
{
char *buf;
int nchars;
va_list ap;
if(!curl_dbg_logfile)
return;
buf = (Curl_cmalloc)(LOGLINE_BUFSIZE);
if(!buf)
return;
va_start(ap, format);
nchars = mvsnprintf(buf, LOGLINE_BUFSIZE, format, ap);
va_end(ap);
if(nchars > LOGLINE_BUFSIZE - 1)
nchars = LOGLINE_BUFSIZE - 1;
if(nchars > 0)
fwrite(buf, 1, (size_t)nchars, curl_dbg_logfile);
(Curl_cfree)(buf);
}
#endif /* CURLDEBUG */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/rename.h | #ifndef HEADER_CURL_RENAME_H
#define HEADER_CURL_RENAME_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
int Curl_rename(const char *oldpath, const char *newpath);
#endif /* HEADER_CURL_RENAME_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/if2ip.h | #ifndef HEADER_CURL_IF2IP_H
#define HEADER_CURL_IF2IP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
/* IPv6 address scopes. */
#define IPV6_SCOPE_GLOBAL 0 /* Global scope. */
#define IPV6_SCOPE_LINKLOCAL 1 /* Link-local scope. */
#define IPV6_SCOPE_SITELOCAL 2 /* Site-local scope (deprecated). */
#define IPV6_SCOPE_UNIQUELOCAL 3 /* Unique local */
#define IPV6_SCOPE_NODELOCAL 4 /* Loopback. */
unsigned int Curl_ipv6_scope(const struct sockaddr *sa);
typedef enum {
IF2IP_NOT_FOUND = 0, /* Interface not found */
IF2IP_AF_NOT_SUPPORTED = 1, /* Int. exists but has no address for this af */
IF2IP_FOUND = 2 /* The address has been stored in "buf" */
} if2ip_result_t;
if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
unsigned int local_scope_id, const char *interf,
char *buf, int buf_size);
#ifdef __INTERIX
/* Nedelcho Stanev's work-around for SFU 3.0 */
struct ifreq {
#define IFNAMSIZ 16
#define IFHWADDRLEN 6
union {
char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */
} ifr_ifrn;
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_metric;
int ifru_mtu;
} ifr_ifru;
};
/* This define was added by Daniel to avoid an extra #ifdef INTERIX in the
C code. */
#define ifr_name ifr_ifrn.ifrn_name /* interface name */
#define ifr_addr ifr_ifru.ifru_addr /* address */
#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */
#define ifr_flags ifr_ifru.ifru_flags /* flags */
#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */
#define ifr_metric ifr_ifru.ifru_metric /* metric */
#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */
#define SIOCGIFADDR _IOW('s', 102, struct ifreq) /* Get if addr */
#endif /* __INTERIX */
#endif /* HEADER_CURL_IF2IP_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/getinfo.h | #ifndef HEADER_CURL_GETINFO_H
#define HEADER_CURL_GETINFO_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...);
CURLcode Curl_initinfo(struct Curl_easy *data);
#endif /* HEADER_CURL_GETINFO_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/arpa_telnet.h | #ifndef HEADER_CURL_ARPA_TELNET_H
#define HEADER_CURL_ARPA_TELNET_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifndef CURL_DISABLE_TELNET
/*
* Telnet option defines. Add more here if in need.
*/
#define CURL_TELOPT_BINARY 0 /* binary 8bit data */
#define CURL_TELOPT_ECHO 1 /* just echo! */
#define CURL_TELOPT_SGA 3 /* Suppress Go Ahead */
#define CURL_TELOPT_EXOPL 255 /* EXtended OPtions List */
#define CURL_TELOPT_TTYPE 24 /* Terminal TYPE */
#define CURL_TELOPT_NAWS 31 /* Negotiate About Window Size */
#define CURL_TELOPT_XDISPLOC 35 /* X DISPlay LOCation */
#define CURL_TELOPT_NEW_ENVIRON 39 /* NEW ENVIRONment variables */
#define CURL_NEW_ENV_VAR 0
#define CURL_NEW_ENV_VALUE 1
#ifndef CURL_DISABLE_VERBOSE_STRINGS
/*
* The telnet options represented as strings
*/
static const char * const telnetoptions[]=
{
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD",
"NAME", "STATUS", "TIMING MARK", "RCTE",
"NAOL", "NAOP", "NAOCRD", "NAOHTS",
"NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD",
"NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
"DE TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION",
"TERM TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING",
"TTYLOC", "3270 REGIME", "X3 PAD", "NAWS",
"TERM SPEED", "LFLOW", "LINEMODE", "XDISPLOC",
"OLD-ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW-ENVIRON"
};
#endif
#define CURL_TELOPT_MAXIMUM CURL_TELOPT_NEW_ENVIRON
#define CURL_TELOPT_OK(x) ((x) <= CURL_TELOPT_MAXIMUM)
#define CURL_TELOPT(x) telnetoptions[x]
#define CURL_NTELOPTS 40
/*
* First some defines
*/
#define CURL_xEOF 236 /* End Of File */
#define CURL_SE 240 /* Sub negotiation End */
#define CURL_NOP 241 /* No OPeration */
#define CURL_DM 242 /* Data Mark */
#define CURL_GA 249 /* Go Ahead, reverse the line */
#define CURL_SB 250 /* SuBnegotiation */
#define CURL_WILL 251 /* Our side WILL use this option */
#define CURL_WONT 252 /* Our side WON'T use this option */
#define CURL_DO 253 /* DO use this option! */
#define CURL_DONT 254 /* DON'T use this option! */
#define CURL_IAC 255 /* Interpret As Command */
#ifndef CURL_DISABLE_VERBOSE_STRINGS
/*
* Then those numbers represented as strings:
*/
static const char * const telnetcmds[]=
{
"EOF", "SUSP", "ABORT", "EOR", "SE",
"NOP", "DMARK", "BRK", "IP", "AO",
"AYT", "EC", "EL", "GA", "SB",
"WILL", "WONT", "DO", "DONT", "IAC"
};
#endif
#define CURL_TELCMD_MINIMUM CURL_xEOF /* the first one */
#define CURL_TELCMD_MAXIMUM CURL_IAC /* surprise, 255 is the last one! ;-) */
#define CURL_TELQUAL_IS 0
#define CURL_TELQUAL_SEND 1
#define CURL_TELQUAL_INFO 2
#define CURL_TELQUAL_NAME 3
#define CURL_TELCMD_OK(x) ( ((unsigned int)(x) >= CURL_TELCMD_MINIMUM) && \
((unsigned int)(x) <= CURL_TELCMD_MAXIMUM) )
#define CURL_TELCMD(x) telnetcmds[(x)-CURL_TELCMD_MINIMUM]
#endif /* CURL_DISABLE_TELNET */
#endif /* HEADER_CURL_ARPA_TELNET_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/mime.h | #ifndef HEADER_CURL_MIME_H
#define HEADER_CURL_MIME_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#define MIME_RAND_BOUNDARY_CHARS 16 /* 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. */
};
/* minimum buffer size for the boundary string */
#define MIME_BOUNDARY_LEN (24 + MIME_RAND_BOUNDARY_CHARS + 1)
/* A mime multipart. */
struct curl_mime {
struct Curl_easy *easy; /* The associated easy handle. */
curl_mimepart *parent; /* Parent part. */
curl_mimepart *firstpart; /* First part. */
curl_mimepart *lastpart; /* Last part. */
char boundary[MIME_BOUNDARY_LEN]; /* The part boundary. */
struct mime_state state; /* Current readback state. */
};
/* A mime part. */
struct curl_mimepart {
struct Curl_easy *easy; /* The associated easy handle. */
curl_mime *parent; /* Parent mime structure. */
curl_mimepart *nextpart; /* Forward linked list. */
enum mimekind kind; /* The part kind. */
unsigned int flags; /* Flags. */
char *data; /* Memory data or file name. */
curl_read_callback readfunc; /* Read function. */
curl_seek_callback seekfunc; /* Seek function. */
curl_free_callback freefunc; /* Argument free function. */
void *arg; /* Argument to callback functions. */
FILE *fp; /* File pointer. */
struct curl_slist *curlheaders; /* Part headers. */
struct curl_slist *userheaders; /* Part headers. */
char *mimetype; /* Part mime type. */
char *filename; /* Remote file name. */
char *name; /* Data name. */
curl_off_t datasize; /* Expected data size. */
struct mime_state state; /* Current readback state. */
const struct mime_encoder *encoder; /* Content data encoder. */
struct mime_encoder_state encstate; /* Data encoder state. */
size_t lastreadstatus; /* Last read callback returned status. */
};
CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...);
#if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)) || \
!defined(CURL_DISABLE_SMTP) || !defined(CURL_DISABLE_IMAP)
/* Prototypes. */
void Curl_mime_initpart(struct curl_mimepart *part, struct Curl_easy *easy);
void Curl_mime_cleanpart(struct curl_mimepart *part);
CURLcode Curl_mime_duppart(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_mimepart *part,
const char *contenttype,
const char *disposition,
enum mimestrategy strategy);
curl_off_t Curl_mime_size(struct curl_mimepart *part);
size_t Curl_mime_read(char *buffer, size_t size, size_t nitems,
void *instream);
CURLcode Curl_mime_rewind(struct curl_mimepart *part);
const char *Curl_mime_contenttype(const char *filename);
void Curl_mime_unpause(struct curl_mimepart *part);
#else
/* if disabled */
#define Curl_mime_initpart(x,y)
#define Curl_mime_cleanpart(x)
#define Curl_mime_duppart(x,y) 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) CURLE_NOT_BUILT_IN
#define Curl_mime_size(x) (curl_off_t) -1
#define Curl_mime_read NULL
#define Curl_mime_rewind(x) ((void)x, CURLE_NOT_BUILT_IN)
#define Curl_mime_unpause(x)
#endif
#endif /* HEADER_CURL_MIME_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_chunks.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_HTTP
#include "urldata.h" /* it includes http_chunks.h */
#include "sendf.h" /* for the client write stuff */
#include "dynbuf.h"
#include "content_encoding.h"
#include "http.h"
#include "non-ascii.h" /* for Curl_convert_to_network prototype */
#include "strtoofft.h"
#include "warnless.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/*
* Chunk format (simplified):
*
* <HEX SIZE>[ chunk extension ] CRLF
* <DATA> CRLF
*
* Highlights from RFC2616 section 3.6 say:
The chunked encoding modifies the body of a message in order to
transfer it as a series of chunks, each with its own size indicator,
followed by an OPTIONAL trailer containing entity-header fields. This
allows dynamically produced content to be transferred along with the
information necessary for the recipient to verify that it has
received the full message.
Chunked-Body = *chunk
last-chunk
trailer
CRLF
chunk = chunk-size [ chunk-extension ] CRLF
chunk-data CRLF
chunk-size = 1*HEX
last-chunk = 1*("0") [ chunk-extension ] CRLF
chunk-extension= *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
chunk-ext-name = token
chunk-ext-val = token | quoted-string
chunk-data = chunk-size(OCTET)
trailer = *(entity-header CRLF)
The chunk-size field is a string of hex digits indicating the size of
the chunk. The chunked encoding is ended by any chunk whose size is
zero, followed by the trailer, which is terminated by an empty line.
*/
#ifdef CURL_DOES_CONVERSIONS
/* Check for an ASCII hex digit.
We avoid the use of ISXDIGIT to accommodate non-ASCII hosts. */
static bool isxdigit_ascii(char digit)
{
return (digit >= 0x30 && digit <= 0x39) /* 0-9 */
|| (digit >= 0x41 && digit <= 0x46) /* A-F */
|| (digit >= 0x61 && digit <= 0x66); /* a-f */
}
#else
#define isxdigit_ascii(x) Curl_isxdigit(x)
#endif
void Curl_httpchunk_init(struct Curl_easy *data)
{
struct connectdata *conn = data->conn;
struct Curl_chunker *chunk = &conn->chunk;
chunk->hexindex = 0; /* start at 0 */
chunk->state = CHUNK_HEX; /* we get hex first! */
Curl_dyn_init(&conn->trailer, DYN_H1_TRAILER);
}
/*
* chunk_read() returns a OK for normal operations, or a positive return code
* for errors. STOP means this sequence of chunks is complete. The 'wrote'
* argument is set to tell the caller how many bytes we actually passed to the
* client (for byte-counting and whatever).
*
* The states and the state-machine is further explained in the header file.
*
* This function always uses ASCII hex values to accommodate non-ASCII hosts.
* For example, 0x0d and 0x0a are used instead of '\r' and '\n'.
*/
CHUNKcode Curl_httpchunk_read(struct Curl_easy *data,
char *datap,
ssize_t datalen,
ssize_t *wrotep,
CURLcode *extrap)
{
CURLcode result = CURLE_OK;
struct connectdata *conn = data->conn;
struct Curl_chunker *ch = &conn->chunk;
struct SingleRequest *k = &data->req;
size_t piece;
curl_off_t length = (curl_off_t)datalen;
size_t *wrote = (size_t *)wrotep;
*wrote = 0; /* nothing's written yet */
/* the original data is written to the client, but we go on with the
chunk read process, to properly calculate the content length*/
if(data->set.http_te_skip && !k->ignorebody) {
result = Curl_client_write(data, CLIENTWRITE_BODY, datap, datalen);
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
}
while(length) {
switch(ch->state) {
case CHUNK_HEX:
if(isxdigit_ascii(*datap)) {
if(ch->hexindex < CHUNK_MAXNUM_LEN) {
ch->hexbuffer[ch->hexindex] = *datap;
datap++;
length--;
ch->hexindex++;
}
else {
return CHUNKE_TOO_LONG_HEX; /* longer hex than we support */
}
}
else {
char *endptr;
if(0 == ch->hexindex)
/* This is illegal data, we received junk where we expected
a hexadecimal digit. */
return CHUNKE_ILLEGAL_HEX;
/* length and datap are unmodified */
ch->hexbuffer[ch->hexindex] = 0;
/* convert to host encoding before calling strtoul */
result = Curl_convert_from_network(data, ch->hexbuffer, ch->hexindex);
if(result) {
/* Curl_convert_from_network calls failf if unsuccessful */
/* Treat it as a bad hex character */
return CHUNKE_ILLEGAL_HEX;
}
if(curlx_strtoofft(ch->hexbuffer, &endptr, 16, &ch->datasize))
return CHUNKE_ILLEGAL_HEX;
ch->state = CHUNK_LF; /* now wait for the CRLF */
}
break;
case CHUNK_LF:
/* waiting for the LF after a chunk size */
if(*datap == 0x0a) {
/* we're now expecting data to come, unless size was zero! */
if(0 == ch->datasize) {
ch->state = CHUNK_TRAILER; /* now check for trailers */
}
else
ch->state = CHUNK_DATA;
}
datap++;
length--;
break;
case CHUNK_DATA:
/* We expect 'datasize' of data. We have 'length' right now, it can be
more or less than 'datasize'. Get the smallest piece.
*/
piece = curlx_sotouz((ch->datasize >= length)?length:ch->datasize);
/* Write the data portion available */
if(!data->set.http_te_skip && !k->ignorebody) {
if(!data->set.http_ce_skip && k->writer_stack)
result = Curl_unencode_write(data, k->writer_stack, datap, piece);
else
result = Curl_client_write(data, CLIENTWRITE_BODY, datap, piece);
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
}
*wrote += piece;
ch->datasize -= piece; /* decrease amount left to expect */
datap += piece; /* move read pointer forward */
length -= piece; /* decrease space left in this round */
if(0 == ch->datasize)
/* end of data this round, we now expect a trailing CRLF */
ch->state = CHUNK_POSTLF;
break;
case CHUNK_POSTLF:
if(*datap == 0x0a) {
/* The last one before we go back to hex state and start all over. */
Curl_httpchunk_init(data); /* sets state back to CHUNK_HEX */
}
else if(*datap != 0x0d)
return CHUNKE_BAD_CHUNK;
datap++;
length--;
break;
case CHUNK_TRAILER:
if((*datap == 0x0d) || (*datap == 0x0a)) {
char *tr = Curl_dyn_ptr(&conn->trailer);
/* this is the end of a trailer, but if the trailer was zero bytes
there was no trailer and we move on */
if(tr) {
size_t trlen;
result = Curl_dyn_add(&conn->trailer, (char *)"\x0d\x0a");
if(result)
return CHUNKE_OUT_OF_MEMORY;
tr = Curl_dyn_ptr(&conn->trailer);
trlen = Curl_dyn_len(&conn->trailer);
/* Convert to host encoding before calling Curl_client_write */
result = Curl_convert_from_network(data, tr, trlen);
if(result)
/* Curl_convert_from_network calls failf if unsuccessful */
/* Treat it as a bad chunk */
return CHUNKE_BAD_CHUNK;
if(!data->set.http_te_skip) {
result = Curl_client_write(data, CLIENTWRITE_HEADER, tr, trlen);
if(result) {
*extrap = result;
return CHUNKE_PASSTHRU_ERROR;
}
}
Curl_dyn_reset(&conn->trailer);
ch->state = CHUNK_TRAILER_CR;
if(*datap == 0x0a)
/* already on the LF */
break;
}
else {
/* no trailer, we're on the final CRLF pair */
ch->state = CHUNK_TRAILER_POSTCR;
break; /* don't advance the pointer */
}
}
else {
result = Curl_dyn_addn(&conn->trailer, datap, 1);
if(result)
return CHUNKE_OUT_OF_MEMORY;
}
datap++;
length--;
break;
case CHUNK_TRAILER_CR:
if(*datap == 0x0a) {
ch->state = CHUNK_TRAILER_POSTCR;
datap++;
length--;
}
else
return CHUNKE_BAD_CHUNK;
break;
case CHUNK_TRAILER_POSTCR:
/* We enter this state when a CR should arrive so we expect to
have to first pass a CR before we wait for LF */
if((*datap != 0x0d) && (*datap != 0x0a)) {
/* not a CR then it must be another header in the trailer */
ch->state = CHUNK_TRAILER;
break;
}
if(*datap == 0x0d) {
/* skip if CR */
datap++;
length--;
}
/* now wait for the final LF */
ch->state = CHUNK_STOP;
break;
case CHUNK_STOP:
if(*datap == 0x0a) {
length--;
/* Record the length of any data left in the end of the buffer
even if there's no more chunks to read */
ch->datasize = curlx_sotouz(length);
return CHUNKE_STOP; /* return stop */
}
else
return CHUNKE_BAD_CHUNK;
}
}
return CHUNKE_OK;
}
const char *Curl_chunked_strerror(CHUNKcode code)
{
switch(code) {
default:
return "OK";
case CHUNKE_TOO_LONG_HEX:
return "Too long hexadecimal number";
case CHUNKE_ILLEGAL_HEX:
return "Illegal or missing hexadecimal sequence";
case CHUNKE_BAD_CHUNK:
return "Malformed encoding found";
case CHUNKE_PASSTHRU_ERROR:
DEBUGASSERT(0); /* never used */
return "";
case CHUNKE_BAD_ENCODING:
return "Bad content-encoding found";
case CHUNKE_OUT_OF_MEMORY:
return "Out of memory";
}
}
#endif /* CURL_DISABLE_HTTP */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/pingpong.h | #ifndef HEADER_CURL_PINGPONG_H
#define HEADER_CURL_PINGPONG_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_FTP) || \
!defined(CURL_DISABLE_POP3) || !defined(CURL_DISABLE_SMTP)
#define USE_PINGPONG
#endif
/* forward-declaration, this is defined in urldata.h */
struct connectdata;
typedef enum {
PPTRANSFER_BODY, /* yes do transfer a body */
PPTRANSFER_INFO, /* do still go through to get info/headers */
PPTRANSFER_NONE /* don't get anything and don't get info */
} curl_pp_transfer;
/*
* 'pingpong' is the generic struct used for protocols doing server<->client
* conversations in a back-and-forth style such as FTP, IMAP, POP3, SMTP etc.
*
* It holds response cache and non-blocking sending data.
*/
struct pingpong {
char *cache; /* data cache between getresponse()-calls */
size_t cache_size; /* size of cache in bytes */
size_t nread_resp; /* number of bytes currently read of a server response */
char *linestart_resp; /* line start pointer for the server response
reader function */
bool pending_resp; /* set TRUE when a server response is pending or in
progress, and is cleared once the last response is
read */
char *sendthis; /* allocated pointer to a buffer that is to be sent to the
server */
size_t sendleft; /* number of bytes left to send from the sendthis buffer */
size_t sendsize; /* total size of the sendthis buffer */
struct curltime response; /* set to Curl_now() when a command has been sent
off, used to time-out response reading */
timediff_t response_time; /* When no timeout is given, this is the amount of
milliseconds we await for a server response. */
struct dynbuf sendbuf;
/* Function pointers the protocols MUST implement and provide for the
pingpong layer to function */
CURLcode (*statemachine)(struct Curl_easy *data, struct connectdata *conn);
bool (*endofresp)(struct Curl_easy *data, struct connectdata *conn,
char *ptr, size_t len, int *code);
};
#define PINGPONG_SETUP(pp,s,e) \
do { \
pp->response_time = RESP_TIMEOUT; \
pp->statemachine = s; \
pp->endofresp = e; \
} while(0)
/*
* Curl_pp_statemach()
*
* called repeatedly until done. Set 'wait' to make it wait a while on the
* socket if there's no traffic.
*/
CURLcode Curl_pp_statemach(struct Curl_easy *data, struct pingpong *pp,
bool block, bool disconnecting);
/* initialize stuff to prepare for reading a fresh new response */
void Curl_pp_init(struct Curl_easy *data, struct pingpong *pp);
/* setup for the transfer */
void Curl_pp_setup(struct pingpong *pp);
/* Returns timeout in ms. 0 or negative number means the timeout has already
triggered */
timediff_t Curl_pp_state_timeout(struct Curl_easy *data,
struct pingpong *pp, bool disconnecting);
/***********************************************************************
*
* Curl_pp_sendf()
*
* Send the formatted string as a command to a pingpong server. Note that
* the string should not have any CRLF appended, as this function will
* append the necessary things itself.
*
* made to never block
*/
CURLcode Curl_pp_sendf(struct Curl_easy *data,
struct pingpong *pp,
const char *fmt, ...);
/***********************************************************************
*
* Curl_pp_vsendf()
*
* Send the formatted string as a command to a pingpong server. Note that
* the string should not have any CRLF appended, as this function will
* append the necessary things itself.
*
* made to never block
*/
CURLcode Curl_pp_vsendf(struct Curl_easy *data,
struct pingpong *pp,
const char *fmt,
va_list args);
/*
* Curl_pp_readresp()
*
* Reads a piece of a server response.
*/
CURLcode Curl_pp_readresp(struct Curl_easy *data,
curl_socket_t sockfd,
struct pingpong *pp,
int *code, /* return the server code if done */
size_t *size); /* size of the response */
CURLcode Curl_pp_flushsend(struct Curl_easy *data,
struct pingpong *pp);
/* call this when a pingpong connection is disconnected */
CURLcode Curl_pp_disconnect(struct pingpong *pp);
int Curl_pp_getsock(struct Curl_easy *data, struct pingpong *pp,
curl_socket_t *socks);
/***********************************************************************
*
* Curl_pp_moredata()
*
* Returns whether there are still more data in the cache and so a call
* to Curl_pp_readresp() will not block.
*/
bool Curl_pp_moredata(struct pingpong *pp);
#endif /* HEADER_CURL_PINGPONG_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/dynbuf.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "dynbuf.h"
#include "curl_printf.h"
#ifdef BUILDING_LIBCURL
#include "curl_memory.h"
#endif
#include "memdebug.h"
#define MIN_FIRST_ALLOC 32
#define DYNINIT 0xbee51da /* random pattern */
/*
* Init a dynbuf struct.
*/
void Curl_dyn_init(struct dynbuf *s, size_t toobig)
{
DEBUGASSERT(s);
DEBUGASSERT(toobig);
s->bufr = NULL;
s->leng = 0;
s->allc = 0;
s->toobig = toobig;
#ifdef DEBUGBUILD
s->init = DYNINIT;
#endif
}
/*
* free the buffer and re-init the necessary fields. It doesn't touch the
* 'init' field and thus this buffer can be reused to add data to again.
*/
void Curl_dyn_free(struct dynbuf *s)
{
DEBUGASSERT(s);
Curl_safefree(s->bufr);
s->leng = s->allc = 0;
}
/*
* Store/append an chunk of memory to the dynbuf.
*/
static CURLcode dyn_nappend(struct dynbuf *s,
const unsigned char *mem, size_t len)
{
size_t indx = s->leng;
size_t a = s->allc;
size_t fit = len + indx + 1; /* new string + old string + zero byte */
/* try to detect if there's rubbish in the struct */
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(s->toobig);
DEBUGASSERT(indx < s->toobig);
DEBUGASSERT(!s->leng || s->bufr);
if(fit > s->toobig) {
Curl_dyn_free(s);
return CURLE_OUT_OF_MEMORY;
}
else if(!a) {
DEBUGASSERT(!indx);
/* first invoke */
if(fit < MIN_FIRST_ALLOC)
a = MIN_FIRST_ALLOC;
else
a = fit;
}
else {
while(a < fit)
a *= 2;
}
if(a != s->allc) {
/* this logic is not using Curl_saferealloc() to make the tool not have to
include that as well when it uses this code */
void *p = realloc(s->bufr, a);
if(!p) {
Curl_safefree(s->bufr);
s->leng = s->allc = 0;
return CURLE_OUT_OF_MEMORY;
}
s->bufr = p;
s->allc = a;
}
if(len)
memcpy(&s->bufr[indx], mem, len);
s->leng = indx + len;
s->bufr[s->leng] = 0;
return CURLE_OK;
}
/*
* Clears the string, keeps the allocation. This can also be called on a
* buffer that already was freed.
*/
void Curl_dyn_reset(struct dynbuf *s)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
if(s->leng)
s->bufr[0] = 0;
s->leng = 0;
}
#ifdef USE_NGTCP2
/*
* Specify the size of the tail to keep (number of bytes from the end of the
* buffer). The rest will be dropped.
*/
CURLcode Curl_dyn_tail(struct dynbuf *s, size_t trail)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
if(trail > s->leng)
return CURLE_BAD_FUNCTION_ARGUMENT;
else if(trail == s->leng)
return CURLE_OK;
else if(!trail) {
Curl_dyn_reset(s);
}
else {
memmove(&s->bufr[0], &s->bufr[s->leng - trail], trail);
s->leng = trail;
s->bufr[s->leng] = 0;
}
return CURLE_OK;
}
#endif
/*
* Appends a buffer with length.
*/
CURLcode Curl_dyn_addn(struct dynbuf *s, const void *mem, size_t len)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
return dyn_nappend(s, mem, len);
}
/*
* Append a null-terminated string at the end.
*/
CURLcode Curl_dyn_add(struct dynbuf *s, const char *str)
{
size_t n = strlen(str);
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
return dyn_nappend(s, (unsigned char *)str, n);
}
/*
* Append a string vprintf()-style
*/
CURLcode Curl_dyn_vaddf(struct dynbuf *s, const char *fmt, va_list ap)
{
#ifdef BUILDING_LIBCURL
int rc;
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
rc = Curl_dyn_vprintf(s, fmt, ap);
if(!rc)
return CURLE_OK;
#else
char *str;
str = vaprintf(fmt, ap); /* this allocs a new string to append */
if(str) {
CURLcode result = dyn_nappend(s, (unsigned char *)str, strlen(str));
free(str);
return result;
}
/* If we failed, we cleanup the whole buffer and return error */
Curl_dyn_free(s);
#endif
return CURLE_OUT_OF_MEMORY;
}
/*
* Append a string printf()-style
*/
CURLcode Curl_dyn_addf(struct dynbuf *s, const char *fmt, ...)
{
CURLcode result;
va_list ap;
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
va_start(ap, fmt);
result = Curl_dyn_vaddf(s, fmt, ap);
va_end(ap);
return result;
}
/*
* Returns a pointer to the buffer.
*/
char *Curl_dyn_ptr(const struct dynbuf *s)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
return s->bufr;
}
/*
* Returns an unsigned pointer to the buffer.
*/
unsigned char *Curl_dyn_uptr(const struct dynbuf *s)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
return (unsigned char *)s->bufr;
}
/*
* Returns the length of the buffer.
*/
size_t Curl_dyn_len(const struct dynbuf *s)
{
DEBUGASSERT(s);
DEBUGASSERT(s->init == DYNINIT);
DEBUGASSERT(!s->leng || s->bufr);
return s->leng;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/libcurl.plist | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="0.9">
<dict>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>curl</string>
<key>CFBundleIdentifier</key>
<string>se.curl.libcurl</string>
<key>CFBundleVersion</key>
<string>7.12.3</string>
<key>CFBundleName</key>
<string>libcurl</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleShortVersionString</key>
<string>libcurl 7.12.3</string>
<key>CFBundleGetInfoString</key>
<string>libcurl.plist 7.12.3</string>
</dict>
</plist>
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/socks_sspi.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2012 - 2021, Daniel Stenberg, <[email protected]>, et al.
* Copyright (C) 2009, 2011, Markus Moeller, <[email protected]>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_PROXY)
#include "urldata.h"
#include "sendf.h"
#include "connect.h"
#include "strerror.h"
#include "timeval.h"
#include "socks.h"
#include "curl_sspi.h"
#include "curl_multibyte.h"
#include "warnless.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/*
* Helper sspi error functions.
*/
static int check_sspi_err(struct Curl_easy *data,
SECURITY_STATUS status,
const char *function)
{
if(status != SEC_E_OK &&
status != SEC_I_COMPLETE_AND_CONTINUE &&
status != SEC_I_COMPLETE_NEEDED &&
status != SEC_I_CONTINUE_NEEDED) {
char buffer[STRERROR_LEN];
failf(data, "SSPI error: %s failed: %s", function,
Curl_sspi_strerror(status, buffer, sizeof(buffer)));
return 1;
}
return 0;
}
/* This is the SSPI-using version of this function */
CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
struct Curl_easy *data)
{
struct connectdata *conn = data->conn;
curl_socket_t sock = conn->sock[sockindex];
CURLcode code;
ssize_t actualread;
ssize_t written;
int result;
/* Needs GSS-API authentication */
SECURITY_STATUS status;
unsigned long sspi_ret_flags = 0;
unsigned char gss_enc;
SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3];
SecBufferDesc input_desc, output_desc, wrap_desc;
SecPkgContext_Sizes sspi_sizes;
CredHandle cred_handle;
CtxtHandle sspi_context;
PCtxtHandle context_handle = NULL;
SecPkgCredentials_Names names;
TimeStamp expiry;
char *service_name = NULL;
unsigned short us_length;
unsigned long qop;
unsigned char socksreq[4]; /* room for GSS-API exchange header only */
const char *service = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd";
const size_t service_length = strlen(service);
/* GSS-API request looks like
* +----+------+-----+----------------+
* |VER | MTYP | LEN | TOKEN |
* +----+------+----------------------+
* | 1 | 1 | 2 | up to 2^16 - 1 |
* +----+------+-----+----------------+
*/
/* prepare service name */
if(strchr(service, '/')) {
service_name = strdup(service);
if(!service_name)
return CURLE_OUT_OF_MEMORY;
}
else {
service_name = malloc(service_length +
strlen(conn->socks_proxy.host.name) + 2);
if(!service_name)
return CURLE_OUT_OF_MEMORY;
msnprintf(service_name, service_length +
strlen(conn->socks_proxy.host.name) + 2, "%s/%s",
service, conn->socks_proxy.host.name);
}
input_desc.cBuffers = 1;
input_desc.pBuffers = &sspi_recv_token;
input_desc.ulVersion = SECBUFFER_VERSION;
sspi_recv_token.BufferType = SECBUFFER_TOKEN;
sspi_recv_token.cbBuffer = 0;
sspi_recv_token.pvBuffer = NULL;
output_desc.cBuffers = 1;
output_desc.pBuffers = &sspi_send_token;
output_desc.ulVersion = SECBUFFER_VERSION;
sspi_send_token.BufferType = SECBUFFER_TOKEN;
sspi_send_token.cbBuffer = 0;
sspi_send_token.pvBuffer = NULL;
wrap_desc.cBuffers = 3;
wrap_desc.pBuffers = sspi_w_token;
wrap_desc.ulVersion = SECBUFFER_VERSION;
cred_handle.dwLower = 0;
cred_handle.dwUpper = 0;
status = s_pSecFn->AcquireCredentialsHandle(NULL,
(TCHAR *) TEXT("Kerberos"),
SECPKG_CRED_OUTBOUND,
NULL,
NULL,
NULL,
NULL,
&cred_handle,
&expiry);
if(check_sspi_err(data, status, "AcquireCredentialsHandle")) {
failf(data, "Failed to acquire credentials.");
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
return CURLE_COULDNT_CONNECT;
}
(void)curlx_nonblock(sock, FALSE);
/* As long as we need to keep sending some context info, and there's no */
/* errors, keep sending it... */
for(;;) {
TCHAR *sname;
sname = curlx_convert_UTF8_to_tchar(service_name);
if(!sname)
return CURLE_OUT_OF_MEMORY;
status = s_pSecFn->InitializeSecurityContext(&cred_handle,
context_handle,
sname,
ISC_REQ_MUTUAL_AUTH |
ISC_REQ_ALLOCATE_MEMORY |
ISC_REQ_CONFIDENTIALITY |
ISC_REQ_REPLAY_DETECT,
0,
SECURITY_NATIVE_DREP,
&input_desc,
0,
&sspi_context,
&output_desc,
&sspi_ret_flags,
&expiry);
curlx_unicodefree(sname);
if(sspi_recv_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
sspi_recv_token.pvBuffer = NULL;
sspi_recv_token.cbBuffer = 0;
}
if(check_sspi_err(data, status, "InitializeSecurityContext")) {
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
failf(data, "Failed to initialise security context.");
return CURLE_COULDNT_CONNECT;
}
if(sspi_send_token.cbBuffer) {
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 1; /* authentication message type */
us_length = htons((short)sspi_send_token.cbBuffer);
memcpy(socksreq + 2, &us_length, sizeof(short));
code = Curl_write_plain(data, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send SSPI authentication request.");
free(service_name);
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
code = Curl_write_plain(data, sock, (char *)sspi_send_token.pvBuffer,
sspi_send_token.cbBuffer, &written);
if(code || (sspi_send_token.cbBuffer != (size_t)written)) {
failf(data, "Failed to send SSPI authentication token.");
free(service_name);
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
}
if(sspi_send_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
sspi_send_token.pvBuffer = NULL;
}
sspi_send_token.cbBuffer = 0;
if(sspi_recv_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
sspi_recv_token.pvBuffer = NULL;
}
sspi_recv_token.cbBuffer = 0;
if(status != SEC_I_CONTINUE_NEEDED)
break;
/* analyse response */
/* GSS-API response looks like
* +----+------+-----+----------------+
* |VER | MTYP | LEN | TOKEN |
* +----+------+----------------------+
* | 1 | 1 | 2 | up to 2^16 - 1 |
* +----+------+-----+----------------+
*/
result = Curl_blockread_all(data, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive SSPI authentication response.");
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
/* ignore the first (VER) byte */
if(socksreq[1] == 255) { /* status / message type */
failf(data, "User was rejected by the SOCKS5 server (%u %u).",
(unsigned int)socksreq[0], (unsigned int)socksreq[1]);
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
if(socksreq[1] != 1) { /* status / message type */
failf(data, "Invalid SSPI authentication response type (%u %u).",
(unsigned int)socksreq[0], (unsigned int)socksreq[1]);
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
sspi_recv_token.cbBuffer = us_length;
sspi_recv_token.pvBuffer = malloc(us_length);
if(!sspi_recv_token.pvBuffer) {
free(service_name);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
result = Curl_blockread_all(data, sock, (char *)sspi_recv_token.pvBuffer,
sspi_recv_token.cbBuffer, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive SSPI authentication token.");
free(service_name);
if(sspi_recv_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
context_handle = &sspi_context;
}
free(service_name);
/* Everything is good so far, user was authenticated! */
status = s_pSecFn->QueryCredentialsAttributes(&cred_handle,
SECPKG_CRED_ATTR_NAMES,
&names);
s_pSecFn->FreeCredentialsHandle(&cred_handle);
if(check_sspi_err(data, status, "QueryCredentialAttributes")) {
s_pSecFn->DeleteSecurityContext(&sspi_context);
s_pSecFn->FreeContextBuffer(names.sUserName);
failf(data, "Failed to determine user name.");
return CURLE_COULDNT_CONNECT;
}
infof(data, "SOCKS5 server authenticated user %s with GSS-API.",
names.sUserName);
s_pSecFn->FreeContextBuffer(names.sUserName);
/* Do encryption */
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 2; /* encryption message type */
gss_enc = 0; /* no data protection */
/* do confidentiality protection if supported */
if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY)
gss_enc = 2;
/* else do integrity protection */
else if(sspi_ret_flags & ISC_REQ_INTEGRITY)
gss_enc = 1;
infof(data, "SOCKS5 server supports GSS-API %s data protection.",
(gss_enc == 0)?"no":((gss_enc == 1)?"integrity":"confidentiality") );
/* force to no data protection, avoid encryption/decryption for now */
gss_enc = 0;
/*
* Sending the encryption type in clear seems wrong. It should be
* protected with gss_seal()/gss_wrap(). See RFC1961 extract below
* The NEC reference implementations on which this is based is
* therefore at fault
*
* +------+------+------+.......................+
* + ver | mtyp | len | token |
* +------+------+------+.......................+
* + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
* +------+------+------+.......................+
*
* Where:
*
* - "ver" is the protocol version number, here 1 to represent the
* first version of the SOCKS/GSS-API protocol
*
* - "mtyp" is the message type, here 2 to represent a protection
* -level negotiation message
*
* - "len" is the length of the "token" field in octets
*
* - "token" is the GSS-API encapsulated protection level
*
* The token is produced by encapsulating an octet containing the
* required protection level using gss_seal()/gss_wrap() with conf_req
* set to FALSE. The token is verified using gss_unseal()/
* gss_unwrap().
*
*/
if(data->set.socks5_gssapi_nec) {
us_length = htons((short)1);
memcpy(socksreq + 2, &us_length, sizeof(short));
}
else {
status = s_pSecFn->QueryContextAttributes(&sspi_context,
SECPKG_ATTR_SIZES,
&sspi_sizes);
if(check_sspi_err(data, status, "QueryContextAttributes")) {
s_pSecFn->DeleteSecurityContext(&sspi_context);
failf(data, "Failed to query security context attributes.");
return CURLE_COULDNT_CONNECT;
}
sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer;
sspi_w_token[0].BufferType = SECBUFFER_TOKEN;
sspi_w_token[0].pvBuffer = malloc(sspi_sizes.cbSecurityTrailer);
if(!sspi_w_token[0].pvBuffer) {
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
sspi_w_token[1].cbBuffer = 1;
sspi_w_token[1].pvBuffer = malloc(1);
if(!sspi_w_token[1].pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
memcpy(sspi_w_token[1].pvBuffer, &gss_enc, 1);
sspi_w_token[2].BufferType = SECBUFFER_PADDING;
sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize;
sspi_w_token[2].pvBuffer = malloc(sspi_sizes.cbBlockSize);
if(!sspi_w_token[2].pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
status = s_pSecFn->EncryptMessage(&sspi_context,
KERB_WRAP_NO_ENCRYPT,
&wrap_desc,
0);
if(check_sspi_err(data, status, "EncryptMessage")) {
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
failf(data, "Failed to query security context attributes.");
return CURLE_COULDNT_CONNECT;
}
sspi_send_token.cbBuffer = sspi_w_token[0].cbBuffer
+ sspi_w_token[1].cbBuffer
+ sspi_w_token[2].cbBuffer;
sspi_send_token.pvBuffer = malloc(sspi_send_token.cbBuffer);
if(!sspi_send_token.pvBuffer) {
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
memcpy(sspi_send_token.pvBuffer, sspi_w_token[0].pvBuffer,
sspi_w_token[0].cbBuffer);
memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer,
sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
memcpy((PUCHAR) sspi_send_token.pvBuffer
+ sspi_w_token[0].cbBuffer
+ sspi_w_token[1].cbBuffer,
sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
sspi_w_token[0].pvBuffer = NULL;
sspi_w_token[0].cbBuffer = 0;
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
sspi_w_token[1].pvBuffer = NULL;
sspi_w_token[1].cbBuffer = 0;
s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer);
sspi_w_token[2].pvBuffer = NULL;
sspi_w_token[2].cbBuffer = 0;
us_length = htons((short)sspi_send_token.cbBuffer);
memcpy(socksreq + 2, &us_length, sizeof(short));
}
code = Curl_write_plain(data, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send SSPI encryption request.");
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
if(data->set.socks5_gssapi_nec) {
memcpy(socksreq, &gss_enc, 1);
code = Curl_write_plain(data, sock, (char *)socksreq, 1, &written);
if(code || (1 != written)) {
failf(data, "Failed to send SSPI encryption type.");
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
}
else {
code = Curl_write_plain(data, sock, (char *)sspi_send_token.pvBuffer,
sspi_send_token.cbBuffer, &written);
if(code || (sspi_send_token.cbBuffer != (size_t)written)) {
failf(data, "Failed to send SSPI encryption type.");
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
if(sspi_send_token.pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer);
}
result = Curl_blockread_all(data, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive SSPI encryption response.");
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
/* ignore the first (VER) byte */
if(socksreq[1] == 255) { /* status / message type */
failf(data, "User was rejected by the SOCKS5 server (%u %u).",
(unsigned int)socksreq[0], (unsigned int)socksreq[1]);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
if(socksreq[1] != 2) { /* status / message type */
failf(data, "Invalid SSPI encryption response type (%u %u).",
(unsigned int)socksreq[0], (unsigned int)socksreq[1]);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
sspi_w_token[0].cbBuffer = us_length;
sspi_w_token[0].pvBuffer = malloc(us_length);
if(!sspi_w_token[0].pvBuffer) {
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_OUT_OF_MEMORY;
}
result = Curl_blockread_all(data, sock, (char *)sspi_w_token[0].pvBuffer,
sspi_w_token[0].cbBuffer, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive SSPI encryption type.");
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
if(!data->set.socks5_gssapi_nec) {
wrap_desc.cBuffers = 2;
sspi_w_token[0].BufferType = SECBUFFER_STREAM;
sspi_w_token[1].BufferType = SECBUFFER_DATA;
sspi_w_token[1].cbBuffer = 0;
sspi_w_token[1].pvBuffer = NULL;
status = s_pSecFn->DecryptMessage(&sspi_context,
&wrap_desc,
0,
&qop);
if(check_sspi_err(data, status, "DecryptMessage")) {
if(sspi_w_token[0].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
if(sspi_w_token[1].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
failf(data, "Failed to query security context attributes.");
return CURLE_COULDNT_CONNECT;
}
if(sspi_w_token[1].cbBuffer != 1) {
failf(data, "Invalid SSPI encryption response length (%lu).",
(unsigned long)sspi_w_token[1].cbBuffer);
if(sspi_w_token[0].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
if(sspi_w_token[1].pvBuffer)
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
memcpy(socksreq, sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer);
}
else {
if(sspi_w_token[0].cbBuffer != 1) {
failf(data, "Invalid SSPI encryption response length (%lu).",
(unsigned long)sspi_w_token[0].cbBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
s_pSecFn->DeleteSecurityContext(&sspi_context);
return CURLE_COULDNT_CONNECT;
}
memcpy(socksreq, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
}
(void)curlx_nonblock(sock, TRUE);
infof(data, "SOCKS5 access with%s protection granted.",
(socksreq[0] == 0)?"out GSS-API data":
((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
/* For later use if encryption is required
conn->socks5_gssapi_enctype = socksreq[0];
if(socksreq[0] != 0)
conn->socks5_sspi_context = sspi_context;
else {
s_pSecFn->DeleteSecurityContext(&sspi_context);
conn->socks5_sspi_context = sspi_context;
}
*/
return CURLE_OK;
}
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/inet_ntop.c | /*
* Copyright (C) 1996-2021 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.
*/
/*
* Original code by Paul Vixie. "curlified" by Gisle Vanem.
*/
#include "curl_setup.h"
#ifndef HAVE_INET_NTOP
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "inet_ntop.h"
#include "curl_printf.h"
#define IN6ADDRSZ 16
#define INADDRSZ 4
#define INT16SZ 2
/*
* 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;
}
#ifdef ENABLE_IPV6
/*
* 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 {
long base;
long len;
} best, cur;
unsigned long 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] |= (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, "%lx", words[i]);
}
/* Was it a trailing run of 0x00's?
*/
if(best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ))
*tp++ = ':';
*tp++ = '\0';
/* Check for overflow, copy, and we're done.
*/
if((size_t)(tp - tmp) > size) {
errno = ENOSPC;
return (NULL);
}
strcpy(dst, tmp);
return dst;
}
#endif /* ENABLE_IPV6 */
/*
* Convert a network format address to presentation format.
*
* Returns pointer to presentation format address (`buf').
* Returns NULL on error and errno set with the specific
* error, EAFNOSUPPORT or ENOSPC.
*
* On Windows we store the error in the thread errno, not
* in the winsock error code. This is to avoid losing the
* actual last winsock error. So when this function returns
* NULL, check errno not SOCKERRNO.
*/
char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size)
{
switch(af) {
case AF_INET:
return inet_ntop4((const unsigned char *)src, buf, size);
#ifdef ENABLE_IPV6
case AF_INET6:
return inet_ntop6((const unsigned char *)src, buf, size);
#endif
default:
errno = EAFNOSUPPORT;
return NULL;
}
}
#endif /* HAVE_INET_NTOP */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/asyn-ares.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
/***********************************************************************
* Only for ares-enabled builds
* And only for functions that fulfill the asynch resolver backend API
* as defined in asyn.h, nothing else belongs in this file!
**********************************************************************/
#ifdef CURLRES_ARES
#include <limits.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#ifdef HAVE_PROCESS_H
#include <process.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include "urldata.h"
#include "sendf.h"
#include "hostip.h"
#include "hash.h"
#include "share.h"
#include "url.h"
#include "multiif.h"
#include "inet_pton.h"
#include "connect.h"
#include "select.h"
#include "progress.h"
# if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \
defined(WIN32)
# define CARES_STATICLIB
# endif
# include <ares.h>
# include <ares_version.h> /* really old c-ares didn't include this by
itself */
#if ARES_VERSION >= 0x010500
/* c-ares 1.5.0 or later, the callback proto is modified */
#define HAVE_CARES_CALLBACK_TIMEOUTS 1
#endif
#if ARES_VERSION >= 0x010601
/* IPv6 supported since 1.6.1 */
#define HAVE_CARES_IPV6 1
#endif
#if ARES_VERSION >= 0x010704
#define HAVE_CARES_SERVERS_CSV 1
#define HAVE_CARES_LOCAL_DEV 1
#define HAVE_CARES_SET_LOCAL 1
#endif
#if ARES_VERSION >= 0x010b00
#define HAVE_CARES_PORTS_CSV 1
#endif
#if ARES_VERSION >= 0x011000
/* 1.16.0 or later has ares_getaddrinfo */
#define HAVE_CARES_GETADDRINFO 1
#endif
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
struct thread_data {
int num_pending; /* number of outstanding c-ares requests */
struct Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares
parts */
int last_status;
struct curltime happy_eyeballs_dns_time; /* when this timer started, or 0 */
};
/* How long we are willing to wait for additional parallel responses after
obtaining a "definitive" one.
This is intended to equal the c-ares default timeout. cURL always uses that
default value. Unfortunately, c-ares doesn't expose its default timeout in
its API, but it is officially documented as 5 seconds.
See query_completed_cb() for an explanation of how this is used.
*/
#define HAPPY_EYEBALLS_DNS_TIMEOUT 5000
/*
* Curl_resolver_global_init() - the generic low-level asynchronous name
* resolve API. Called from curl_global_init() to initialize global resolver
* environment. Initializes ares library.
*/
int Curl_resolver_global_init(void)
{
#ifdef CARES_HAVE_ARES_LIBRARY_INIT
if(ares_library_init(ARES_LIB_INIT_ALL)) {
return CURLE_FAILED_INIT;
}
#endif
return CURLE_OK;
}
/*
* Curl_resolver_global_cleanup()
*
* Called from curl_global_cleanup() to destroy global resolver environment.
* Deinitializes ares library.
*/
void Curl_resolver_global_cleanup(void)
{
#ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP
ares_library_cleanup();
#endif
}
static void sock_state_cb(void *data, ares_socket_t socket_fd,
int readable, int writable)
{
struct Curl_easy *easy = data;
if(!readable && !writable) {
DEBUGASSERT(easy);
Curl_multi_closed(easy, socket_fd);
}
}
/*
* Curl_resolver_init()
*
* Called from curl_easy_init() -> Curl_open() to initialize resolver
* URL-state specific environment ('resolver' member of the UrlState
* structure). Fills the passed pointer by the initialized ares_channel.
*/
CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver)
{
int status;
struct ares_options options;
int optmask = ARES_OPT_SOCK_STATE_CB;
options.sock_state_cb = sock_state_cb;
options.sock_state_cb_data = easy;
status = ares_init_options((ares_channel*)resolver, &options, optmask);
if(status != ARES_SUCCESS) {
if(status == ARES_ENOMEM)
return CURLE_OUT_OF_MEMORY;
else
return CURLE_FAILED_INIT;
}
return CURLE_OK;
/* make sure that all other returns from this function should destroy the
ares channel before returning error! */
}
/*
* Curl_resolver_cleanup()
*
* Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
* URL-state specific environment ('resolver' member of the UrlState
* structure). Destroys the ares channel.
*/
void Curl_resolver_cleanup(void *resolver)
{
ares_destroy((ares_channel)resolver);
}
/*
* Curl_resolver_duphandle()
*
* Called from curl_easy_duphandle() to duplicate resolver URL-state specific
* environment ('resolver' member of the UrlState structure). Duplicates the
* 'from' ares channel and passes the resulting channel to the 'to' pointer.
*/
CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from)
{
(void)from;
/*
* it would be better to call ares_dup instead, but right now
* it is not possible to set 'sock_state_cb_data' outside of
* ares_init_options
*/
return Curl_resolver_init(easy, to);
}
static void destroy_async_data(struct Curl_async *async);
/*
* Cancel all possibly still on-going resolves for this connection.
*/
void Curl_resolver_cancel(struct Curl_easy *data)
{
DEBUGASSERT(data);
if(data->state.async.resolver)
ares_cancel((ares_channel)data->state.async.resolver);
destroy_async_data(&data->state.async);
}
/*
* We're equivalent to Curl_resolver_cancel() for the c-ares resolver. We
* never block.
*/
void Curl_resolver_kill(struct Curl_easy *data)
{
/* We don't need to check the resolver state because we can be called safely
at any time and we always do the same thing. */
Curl_resolver_cancel(data);
}
/*
* destroy_async_data() cleans up async resolver data.
*/
static void destroy_async_data(struct Curl_async *async)
{
free(async->hostname);
if(async->tdata) {
struct thread_data *res = async->tdata;
if(res) {
if(res->temp_ai) {
Curl_freeaddrinfo(res->temp_ai);
res->temp_ai = NULL;
}
free(res);
}
async->tdata = NULL;
}
async->hostname = NULL;
}
/*
* Curl_resolver_getsock() is called when someone from the outside world
* (using curl_multi_fdset()) wants to get our fd_set setup and we're talking
* with ares. The caller must make sure that this function is only called when
* we have a working ares channel.
*
* Returns: sockets-in-use-bitmap
*/
int Curl_resolver_getsock(struct Curl_easy *data,
curl_socket_t *socks)
{
struct timeval maxtime;
struct timeval timebuf;
struct timeval *timeout;
long milli;
int max = ares_getsock((ares_channel)data->state.async.resolver,
(ares_socket_t *)socks, MAX_SOCKSPEREASYHANDLE);
maxtime.tv_sec = CURL_TIMEOUT_RESOLVE;
maxtime.tv_usec = 0;
timeout = ares_timeout((ares_channel)data->state.async.resolver, &maxtime,
&timebuf);
milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000);
if(milli == 0)
milli += 10;
Curl_expire(data, milli, EXPIRE_ASYNC_NAME);
return max;
}
/*
* waitperform()
*
* 1) Ask ares what sockets it currently plays with, then
* 2) wait for the timeout period to check for action on ares' sockets.
* 3) tell ares to act on all the sockets marked as "with action"
*
* return number of sockets it worked on
*/
static int waitperform(struct Curl_easy *data, timediff_t timeout_ms)
{
int nfds;
int bitmask;
ares_socket_t socks[ARES_GETSOCK_MAXNUM];
struct pollfd pfd[ARES_GETSOCK_MAXNUM];
int i;
int num = 0;
bitmask = ares_getsock((ares_channel)data->state.async.resolver, socks,
ARES_GETSOCK_MAXNUM);
for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) {
pfd[i].events = 0;
pfd[i].revents = 0;
if(ARES_GETSOCK_READABLE(bitmask, i)) {
pfd[i].fd = socks[i];
pfd[i].events |= POLLRDNORM|POLLIN;
}
if(ARES_GETSOCK_WRITABLE(bitmask, i)) {
pfd[i].fd = socks[i];
pfd[i].events |= POLLWRNORM|POLLOUT;
}
if(pfd[i].events)
num++;
else
break;
}
if(num)
nfds = Curl_poll(pfd, num, timeout_ms);
else
nfds = 0;
if(!nfds)
/* Call ares_process() unconditionally here, even if we simply timed out
above, as otherwise the ares name resolve won't timeout! */
ares_process_fd((ares_channel)data->state.async.resolver, ARES_SOCKET_BAD,
ARES_SOCKET_BAD);
else {
/* move through the descriptors and ask for processing on them */
for(i = 0; i < num; i++)
ares_process_fd((ares_channel)data->state.async.resolver,
(pfd[i].revents & (POLLRDNORM|POLLIN))?
pfd[i].fd:ARES_SOCKET_BAD,
(pfd[i].revents & (POLLWRNORM|POLLOUT))?
pfd[i].fd:ARES_SOCKET_BAD);
}
return nfds;
}
/*
* Curl_resolver_is_resolved() is called repeatedly to check if a previous
* name resolve request has completed. It should also make sure to time-out if
* the operation seems to take too long.
*
* Returns normal CURLcode errors.
*/
CURLcode Curl_resolver_is_resolved(struct Curl_easy *data,
struct Curl_dns_entry **dns)
{
struct thread_data *res = data->state.async.tdata;
CURLcode result = CURLE_OK;
DEBUGASSERT(dns);
*dns = NULL;
waitperform(data, 0);
/* Now that we've checked for any last minute results above, see if there are
any responses still pending when the EXPIRE_HAPPY_EYEBALLS_DNS timer
expires. */
if(res
&& res->num_pending
/* This is only set to non-zero if the timer was started. */
&& (res->happy_eyeballs_dns_time.tv_sec
|| res->happy_eyeballs_dns_time.tv_usec)
&& (Curl_timediff(Curl_now(), res->happy_eyeballs_dns_time)
>= HAPPY_EYEBALLS_DNS_TIMEOUT)) {
/* Remember that the EXPIRE_HAPPY_EYEBALLS_DNS timer is no longer
running. */
memset(
&res->happy_eyeballs_dns_time, 0, sizeof(res->happy_eyeballs_dns_time));
/* Cancel the raw c-ares request, which will fire query_completed_cb() with
ARES_ECANCELLED synchronously for all pending responses. This will
leave us with res->num_pending == 0, which is perfect for the next
block. */
ares_cancel((ares_channel)data->state.async.resolver);
DEBUGASSERT(res->num_pending == 0);
}
if(res && !res->num_pending) {
(void)Curl_addrinfo_callback(data, res->last_status, res->temp_ai);
/* temp_ai ownership is moved to the connection, so we need not free-up
them */
res->temp_ai = NULL;
if(!data->state.async.dns)
result = Curl_resolver_error(data);
else
*dns = data->state.async.dns;
destroy_async_data(&data->state.async);
}
return result;
}
/*
* Curl_resolver_wait_resolv()
*
* Waits for a resolve to finish. This function should be avoided since using
* this risk getting the multi interface to "hang".
*
* 'entry' MUST be non-NULL.
*
* Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved,
* CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors.
*/
CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data,
struct Curl_dns_entry **entry)
{
CURLcode result = CURLE_OK;
timediff_t timeout;
struct curltime now = Curl_now();
DEBUGASSERT(entry);
*entry = NULL; /* clear on entry */
timeout = Curl_timeleft(data, &now, TRUE);
if(timeout < 0) {
/* already expired! */
connclose(data->conn, "Timed out before name resolve started");
return CURLE_OPERATION_TIMEDOUT;
}
if(!timeout)
timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */
/* Wait for the name resolve query to complete. */
while(!result) {
struct timeval *tvp, tv, store;
int itimeout;
timediff_t timeout_ms;
#if TIMEDIFF_T_MAX > INT_MAX
itimeout = (timeout > INT_MAX) ? INT_MAX : (int)timeout;
#else
itimeout = (int)timeout;
#endif
store.tv_sec = itimeout/1000;
store.tv_usec = (itimeout%1000)*1000;
tvp = ares_timeout((ares_channel)data->state.async.resolver, &store, &tv);
/* use the timeout period ares returned to us above if less than one
second is left, otherwise just use 1000ms to make sure the progress
callback gets called frequent enough */
if(!tvp->tv_sec)
timeout_ms = (timediff_t)(tvp->tv_usec/1000);
else
timeout_ms = 1000;
waitperform(data, timeout_ms);
result = Curl_resolver_is_resolved(data, entry);
if(result || data->state.async.done)
break;
if(Curl_pgrsUpdate(data))
result = CURLE_ABORTED_BY_CALLBACK;
else {
struct curltime now2 = Curl_now();
timediff_t timediff = Curl_timediff(now2, now); /* spent time */
if(timediff <= 0)
timeout -= 1; /* always deduct at least 1 */
else if(timediff > timeout)
timeout = -1;
else
timeout -= timediff;
now = now2; /* for next loop */
}
if(timeout < 0)
result = CURLE_OPERATION_TIMEDOUT;
}
if(result)
/* failure, so we cancel the ares operation */
ares_cancel((ares_channel)data->state.async.resolver);
/* Operation complete, if the lookup was successful we now have the entry
in the cache. */
if(entry)
*entry = data->state.async.dns;
if(result)
/* close the connection, since we can't return failure here without
cleaning up this connection properly. */
connclose(data->conn, "c-ares resolve failed");
return result;
}
#ifndef HAVE_CARES_GETADDRINFO
/* Connects results to the list */
static void compound_results(struct thread_data *res,
struct Curl_addrinfo *ai)
{
if(!ai)
return;
#ifdef ENABLE_IPV6 /* CURLRES_IPV6 */
if(res->temp_ai && res->temp_ai->ai_family == PF_INET6) {
/* We have results already, put the new IPv6 entries at the head of the
list. */
struct Curl_addrinfo *temp_ai_tail = res->temp_ai;
while(temp_ai_tail->ai_next)
temp_ai_tail = temp_ai_tail->ai_next;
temp_ai_tail->ai_next = ai;
}
else
#endif /* CURLRES_IPV6 */
{
/* Add the new results to the list of old results. */
struct Curl_addrinfo *ai_tail = ai;
while(ai_tail->ai_next)
ai_tail = ai_tail->ai_next;
ai_tail->ai_next = res->temp_ai;
res->temp_ai = ai;
}
}
/*
* ares_query_completed_cb() is the callback that ares will call when
* the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(),
* when using ares, is completed either successfully or with failure.
*/
static void query_completed_cb(void *arg, /* (struct connectdata *) */
int status,
#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
int timeouts,
#endif
struct hostent *hostent)
{
struct Curl_easy *data = (struct Curl_easy *)arg;
struct thread_data *res;
#ifdef HAVE_CARES_CALLBACK_TIMEOUTS
(void)timeouts; /* ignored */
#endif
if(ARES_EDESTRUCTION == status)
/* when this ares handle is getting destroyed, the 'arg' pointer may not
be valid so only defer it when we know the 'status' says its fine! */
return;
res = data->state.async.tdata;
if(res) {
res->num_pending--;
if(CURL_ASYNC_SUCCESS == status) {
struct Curl_addrinfo *ai = Curl_he2ai(hostent, data->state.async.port);
if(ai) {
compound_results(res, ai);
}
}
/* A successful result overwrites any previous error */
if(res->last_status != ARES_SUCCESS)
res->last_status = status;
/* If there are responses still pending, we presume they must be the
complementary IPv4 or IPv6 lookups that we started in parallel in
Curl_resolver_getaddrinfo() (for Happy Eyeballs). If we've got a
"definitive" response from one of a set of parallel queries, we need to
think about how long we're willing to wait for more responses. */
if(res->num_pending
/* Only these c-ares status values count as "definitive" for these
purposes. For example, ARES_ENODATA is what we expect when there is
no IPv6 entry for a domain name, and that's not a reason to get more
aggressive in our timeouts for the other response. Other errors are
either a result of bad input (which should affect all parallel
requests), local or network conditions, non-definitive server
responses, or us cancelling the request. */
&& (status == ARES_SUCCESS || status == ARES_ENOTFOUND)) {
/* Right now, there can only be up to two parallel queries, so don't
bother handling any other cases. */
DEBUGASSERT(res->num_pending == 1);
/* It's possible that one of these parallel queries could succeed
quickly, but the other could always fail or timeout (when we're
talking to a pool of DNS servers that can only successfully resolve
IPv4 address, for example).
It's also possible that the other request could always just take
longer because it needs more time or only the second DNS server can
fulfill it successfully. But, to align with the philosophy of Happy
Eyeballs, we don't want to wait _too_ long or users will think
requests are slow when IPv6 lookups don't actually work (but IPv4 ones
do).
So, now that we have a usable answer (some IPv4 addresses, some IPv6
addresses, or "no such domain"), we start a timeout for the remaining
pending responses. Even though it is typical that this resolved
request came back quickly, that needn't be the case. It might be that
this completing request didn't get a result from the first DNS server
or even the first round of the whole DNS server pool. So it could
already be quite some time after we issued the DNS queries in the
first place. Without modifying c-ares, we can't know exactly where in
its retry cycle we are. We could guess based on how much time has
gone by, but it doesn't really matter. Happy Eyeballs tells us that,
given usable information in hand, we simply don't want to wait "too
much longer" after we get a result.
We simply wait an additional amount of time equal to the default
c-ares query timeout. That is enough time for a typical parallel
response to arrive without being "too long". Even on a network
where one of the two types of queries is failing or timing out
constantly, this will usually mean we wait a total of the default
c-ares timeout (5 seconds) plus the round trip time for the successful
request, which seems bearable. The downside is that c-ares might race
with us to issue one more retry just before we give up, but it seems
better to "waste" that request instead of trying to guess the perfect
timeout to prevent it. After all, we don't even know where in the
c-ares retry cycle each request is.
*/
res->happy_eyeballs_dns_time = Curl_now();
Curl_expire(data, HAPPY_EYEBALLS_DNS_TIMEOUT,
EXPIRE_HAPPY_EYEBALLS_DNS);
}
}
}
#else
/* c-ares 1.16.0 or later */
/*
* ares2addr() converts an address list provided by c-ares to an internal
* libcurl compatible list
*/
static struct Curl_addrinfo *ares2addr(struct ares_addrinfo_node *node)
{
/* traverse the ares_addrinfo_node list */
struct ares_addrinfo_node *ai;
struct Curl_addrinfo *cafirst = NULL;
struct Curl_addrinfo *calast = NULL;
int error = 0;
for(ai = node; ai != NULL; ai = ai->ai_next) {
size_t ss_size;
struct Curl_addrinfo *ca;
/* ignore elements with unsupported address family, */
/* settle family-specific sockaddr structure size. */
if(ai->ai_family == AF_INET)
ss_size = sizeof(struct sockaddr_in);
#ifdef ENABLE_IPV6
else if(ai->ai_family == AF_INET6)
ss_size = sizeof(struct sockaddr_in6);
#endif
else
continue;
/* ignore elements without required address info */
if(!ai->ai_addr || !(ai->ai_addrlen > 0))
continue;
/* ignore elements with bogus address size */
if((size_t)ai->ai_addrlen < ss_size)
continue;
ca = malloc(sizeof(struct Curl_addrinfo) + ss_size);
if(!ca) {
error = EAI_MEMORY;
break;
}
/* copy each structure member individually, member ordering, */
/* size, or padding might be different for each platform. */
ca->ai_flags = ai->ai_flags;
ca->ai_family = ai->ai_family;
ca->ai_socktype = ai->ai_socktype;
ca->ai_protocol = ai->ai_protocol;
ca->ai_addrlen = (curl_socklen_t)ss_size;
ca->ai_addr = NULL;
ca->ai_canonname = NULL;
ca->ai_next = NULL;
ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
memcpy(ca->ai_addr, ai->ai_addr, ss_size);
/* if the return list is empty, this becomes the first element */
if(!cafirst)
cafirst = ca;
/* add this element last in the return list */
if(calast)
calast->ai_next = ca;
calast = ca;
}
/* if we failed, destroy the Curl_addrinfo list */
if(error) {
Curl_freeaddrinfo(cafirst);
cafirst = NULL;
}
return cafirst;
}
static void addrinfo_cb(void *arg, int status, int timeouts,
struct ares_addrinfo *result)
{
struct Curl_easy *data = (struct Curl_easy *)arg;
struct thread_data *res = data->state.async.tdata;
(void)timeouts;
if(ARES_SUCCESS == status) {
res->temp_ai = ares2addr(result->nodes);
res->last_status = CURL_ASYNC_SUCCESS;
ares_freeaddrinfo(result);
}
res->num_pending--;
}
#endif
/*
* Curl_resolver_getaddrinfo() - when using ares
*
* Returns name information about the given hostname and port number. If
* successful, the 'hostent' is returned and the forth argument will point to
* memory we need to free after use. That memory *MUST* be freed with
* Curl_freeaddrinfo(), nothing else.
*/
struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data,
const char *hostname,
int port,
int *waitp)
{
char *bufp;
*waitp = 0; /* default to synchronous response */
bufp = strdup(hostname);
if(bufp) {
struct thread_data *res = NULL;
free(data->state.async.hostname);
data->state.async.hostname = bufp;
data->state.async.port = port;
data->state.async.done = FALSE; /* not done */
data->state.async.status = 0; /* clear */
data->state.async.dns = NULL; /* clear */
res = calloc(sizeof(struct thread_data), 1);
if(!res) {
free(data->state.async.hostname);
data->state.async.hostname = NULL;
return NULL;
}
data->state.async.tdata = res;
/* initial status - failed */
res->last_status = ARES_ENOTFOUND;
#ifdef HAVE_CARES_GETADDRINFO
{
struct ares_addrinfo_hints hints;
char service[12];
int pf = PF_INET;
memset(&hints, 0, sizeof(hints));
#ifdef CURLRES_IPV6
if(Curl_ipv6works(data))
/* The stack seems to be IPv6-enabled */
pf = PF_UNSPEC;
#endif /* CURLRES_IPV6 */
hints.ai_family = pf;
hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP)?
SOCK_STREAM : SOCK_DGRAM;
msnprintf(service, sizeof(service), "%d", port);
res->num_pending = 1;
ares_getaddrinfo((ares_channel)data->state.async.resolver, hostname,
service, &hints, addrinfo_cb, data);
}
#else
#ifdef HAVE_CARES_IPV6
if(Curl_ipv6works(data)) {
/* The stack seems to be IPv6-enabled */
res->num_pending = 2;
/* areschannel is already setup in the Curl_open() function */
ares_gethostbyname((ares_channel)data->state.async.resolver, hostname,
PF_INET, query_completed_cb, data);
ares_gethostbyname((ares_channel)data->state.async.resolver, hostname,
PF_INET6, query_completed_cb, data);
}
else
#endif
{
res->num_pending = 1;
/* areschannel is already setup in the Curl_open() function */
ares_gethostbyname((ares_channel)data->state.async.resolver,
hostname, PF_INET,
query_completed_cb, data);
}
#endif
*waitp = 1; /* expect asynchronous response */
}
return NULL; /* no struct yet */
}
CURLcode Curl_set_dns_servers(struct Curl_easy *data,
char *servers)
{
CURLcode result = CURLE_NOT_BUILT_IN;
int ares_result;
/* If server is NULL or empty, this would purge all DNS servers
* from ares library, which will cause any and all queries to fail.
* So, just return OK if none are configured and don't actually make
* any changes to c-ares. This lets c-ares use it's defaults, which
* it gets from the OS (for instance from /etc/resolv.conf on Linux).
*/
if(!(servers && servers[0]))
return CURLE_OK;
#ifdef HAVE_CARES_SERVERS_CSV
#ifdef HAVE_CARES_PORTS_CSV
ares_result = ares_set_servers_ports_csv(data->state.async.resolver,
servers);
#else
ares_result = ares_set_servers_csv(data->state.async.resolver, servers);
#endif
switch(ares_result) {
case ARES_SUCCESS:
result = CURLE_OK;
break;
case ARES_ENOMEM:
result = CURLE_OUT_OF_MEMORY;
break;
case ARES_ENOTINITIALIZED:
case ARES_ENODATA:
case ARES_EBADSTR:
default:
result = CURLE_BAD_FUNCTION_ARGUMENT;
break;
}
#else /* too old c-ares version! */
(void)data;
(void)(ares_result);
#endif
return result;
}
CURLcode Curl_set_dns_interface(struct Curl_easy *data,
const char *interf)
{
#ifdef HAVE_CARES_LOCAL_DEV
if(!interf)
interf = "";
ares_set_local_dev((ares_channel)data->state.async.resolver, interf);
return CURLE_OK;
#else /* c-ares version too old! */
(void)data;
(void)interf;
return CURLE_NOT_BUILT_IN;
#endif
}
CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data,
const char *local_ip4)
{
#ifdef HAVE_CARES_SET_LOCAL
struct in_addr a4;
if((!local_ip4) || (local_ip4[0] == 0)) {
a4.s_addr = 0; /* disabled: do not bind to a specific address */
}
else {
if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) {
return CURLE_BAD_FUNCTION_ARGUMENT;
}
}
ares_set_local_ip4((ares_channel)data->state.async.resolver,
ntohl(a4.s_addr));
return CURLE_OK;
#else /* c-ares version too old! */
(void)data;
(void)local_ip4;
return CURLE_NOT_BUILT_IN;
#endif
}
CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data,
const char *local_ip6)
{
#if defined(HAVE_CARES_SET_LOCAL) && defined(ENABLE_IPV6)
unsigned char a6[INET6_ADDRSTRLEN];
if((!local_ip6) || (local_ip6[0] == 0)) {
/* disabled: do not bind to a specific address */
memset(a6, 0, sizeof(a6));
}
else {
if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) {
return CURLE_BAD_FUNCTION_ARGUMENT;
}
}
ares_set_local_ip6((ares_channel)data->state.async.resolver, a6);
return CURLE_OK;
#else /* c-ares version too old! */
(void)data;
(void)local_ip6;
return CURLE_NOT_BUILT_IN;
#endif
}
#endif /* CURLRES_ARES */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/parsedate.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
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 <limits.h>
#include <curl/curl.h>
#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;
bool found = FALSE;
if(len > 3)
what = &weekday[0];
else
what = &Curl_wkday[0];
for(i = 0; i<7; i++) {
if(strcasecompare(check, what[0])) {
found = TRUE;
break;
}
what++;
}
return found?i:-1;
}
static int checkmonth(const char *check)
{
int i;
const char * const *what;
bool found = FALSE;
what = &Curl_month[0];
for(i = 0; i<12; i++) {
if(strcasecompare(check, what[0])) {
found = TRUE;
break;
}
what++;
}
return found?i:-1; /* return the offset or -1, no real offset is -1 */
}
/* return the time zone offset between GMT and the input one, in number
of seconds or -1 if the timezone wasn't found/legal */
static int checktz(const char *check)
{
unsigned int i;
const struct tzinfo *what;
bool found = FALSE;
what = tz;
for(i = 0; i< sizeof(tz)/sizeof(tz[0]); i++) {
if(strcasecompare(check, what->name)) {
found = TRUE;
break;
}
what++;
}
return found?what->offset*60:-1;
}
static void skip(const char **date)
{
/* skip everything that aren't letters or digits */
while(**date && !ISALNUM(**date))
(*date)++;
}
enum assume {
DATE_MDAY,
DATE_YEAR,
DATE_TIME
};
/*
* time2epoch: time stamp to seconds since epoch in GMT time zone. Similar to
* mktime but for GMT only.
*/
static time_t time2epoch(int sec, int min, int hour,
int mday, int mon, int year)
{
static const int month_days_cumulative [12] =
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
int leap_days = year - (mon <= 1);
leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400)
- (1969 / 4) + (1969 / 100) - (1969 / 400));
return ((((time_t) (year - 1970) * 365
+ leap_days + month_days_cumulative[mon] + mday - 1) * 24
+ hour) * 60 + min) * 60 + sec;
}
/*
* 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)
{
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 */
char buf[32]="";
size_t len;
if(sscanf(date, "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz]", buf))
len = strlen(buf);
else
len = 0;
if(wdaynum == -1) {
wdaynum = checkday(buf, len);
if(wdaynum != -1)
found = TRUE;
}
if(!found && (monnum == -1)) {
monnum = checkmonth(buf);
if(monnum != -1)
found = TRUE;
}
if(!found && (tzoff == -1)) {
/* this just must be a time zone string */
tzoff = checktz(buf);
if(tzoff != -1)
found = TRUE;
}
if(!found)
return PARSEDATE_FAIL; /* bad string */
date += len;
}
else if(ISDIGIT(*date)) {
/* a digit */
int val;
char *end;
int len = 0;
if((secnum == -1) &&
(3 == sscanf(date, "%02d:%02d:%02d%n",
&hournum, &minnum, &secnum, &len))) {
/* time stamp! */
date += len;
}
else if((secnum == -1) &&
(2 == sscanf(date, "%02d:%02d%n", &hournum, &minnum, &len))) {
/* time stamp without seconds */
date += len;
secnum = 0;
}
else {
long lval;
int error;
int old_errno;
old_errno = errno;
errno = 0;
lval = strtol(date, &end, 10);
error = errno;
if(errno != old_errno)
errno = old_errno;
if(error)
return PARSEDATE_FAIL;
#if LONG_MAX != INT_MAX
if((lval > (long)INT_MAX) || (lval < (long)INT_MIN))
return PARSEDATE_FAIL;
#endif
val = curlx_sltosi(lval);
if((tzoff == -1) &&
((end - date) == 4) &&
(val <= 1400) &&
(indate< date) &&
((date[-1] == '+' || date[-1] == '-'))) {
/* four digits and a value less than or equal to 1400 (to take into
account all sorts of funny time zone diffs) and it is preceded
with a plus or minus. This is a time zone indication. 1400 is
picked since +1300 is frequently used and +1400 is mentioned as
an edge number in the document "ISO C 200X Proposal: Timezone
Functions" at http://david.tribble.com/text/c0xtimezone.html If
anyone has a more authoritative source for the exact maximum time
zone offsets, please speak up! */
found = TRUE;
tzoff = (val/100 * 60 + val%100)*60;
/* the + and - prefix indicates the local time compared to GMT,
this we need their reversed math to get what we want */
tzoff = date[-1]=='+'?-tzoff:tzoff;
}
if(((end - date) == 8) &&
(yearnum == -1) &&
(monnum == -1) &&
(mdaynum == -1)) {
/* 8 digits, no year, month or day yet. This is YYYYMMDD */
found = TRUE;
yearnum = val/10000;
monnum = (val%10000)/100-1; /* month is 0 - 11 */
mdaynum = val%100;
}
if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) {
if((val > 0) && (val<32)) {
mdaynum = val;
found = TRUE;
}
dignext = DATE_YEAR;
}
if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) {
yearnum = val;
found = TRUE;
if(yearnum < 100) {
if(yearnum > 70)
yearnum += 1900;
else
yearnum += 2000;
}
if(mdaynum == -1)
dignext = DATE_MDAY;
}
if(!found)
return PARSEDATE_FAIL;
date = end;
}
}
part++;
}
if(-1 == secnum)
secnum = minnum = hournum = 0; /* no time, make it zero */
if((-1 == mdaynum) ||
(-1 == monnum) ||
(-1 == yearnum))
/* lacks vital info, fail */
return PARSEDATE_FAIL;
#ifdef HAVE_TIME_T_UNSIGNED
if(yearnum < 1970) {
/* only positive numbers cannot return earlier */
*output = TIME_T_MIN;
return PARSEDATE_SOONER;
}
#endif
#if (SIZEOF_TIME_T < 5)
#ifdef HAVE_TIME_T_UNSIGNED
/* an unsigned 32 bit time_t can only hold dates to 2106 */
if(yearnum > 2105) {
*output = TIME_T_MAX;
return PARSEDATE_LATER;
}
#else
/* a signed 32 bit time_t can only hold dates to the beginning of 2038 */
if(yearnum > 2037) {
*output = TIME_T_MAX;
return PARSEDATE_LATER;
}
if(yearnum < 1903) {
*output = TIME_T_MIN;
return PARSEDATE_SOONER;
}
#endif
#else
/* The Gregorian calendar was introduced 1582 */
if(yearnum < 1583)
return PARSEDATE_FAIL;
#endif
if((mdaynum > 31) || (monnum > 11) ||
(hournum > 23) || (minnum > 59) || (secnum > 60))
return PARSEDATE_FAIL; /* clearly an illegal date */
/* time2epoch() returns a time_t. time_t is often 32 bits, sometimes even on
architectures that feature 64 bit 'long' but ultimately time_t is the
correct data type to use.
*/
t = time2epoch(secnum, minnum, hournum, mdaynum, monnum, yearnum);
/* Add the time zone diff between local time zone and GMT. */
if(tzoff == -1)
tzoff = 0;
if((tzoff > 0) && (t > TIME_T_MAX - tzoff)) {
*output = TIME_T_MAX;
return PARSEDATE_LATER; /* time_t overflow */
}
t += tzoff;
*output = t;
return PARSEDATE_OK;
}
#else
/* disabled */
static int parsedate(const char *date, time_t *output)
{
(void)date;
*output = 0;
return PARSEDATE_OK; /* a lie */
}
#endif
time_t curl_getdate(const char *p, const time_t *now)
{
time_t parsed = -1;
int rc = parsedate(p, &parsed);
(void)now; /* legacy argument from the past that we ignore */
if(rc == PARSEDATE_OK) {
if(parsed == -1)
/* avoid returning -1 for a working scenario */
parsed++;
return parsed;
}
/* everything else is fail */
return -1;
}
/* Curl_getdate_capped() differs from curl_getdate() in that this will return
TIME_T_MAX in case the parsed time value was too big, instead of an
error. */
time_t Curl_getdate_capped(const char *p)
{
time_t parsed = -1;
int rc = parsedate(p, &parsed);
switch(rc) {
case PARSEDATE_OK:
if(parsed == -1)
/* avoid returning -1 for a working scenario */
parsed++;
return parsed;
case PARSEDATE_LATER:
/* this returns the maximum time value */
return parsed;
default:
return -1; /* everything else is fail */
}
/* UNREACHABLE */
}
/*
* Curl_gmtime() is a gmtime() replacement for portability. Do not use the
* gmtime_r() or gmtime() functions anywhere else but here.
*
*/
CURLcode Curl_gmtime(time_t intime, struct tm *store)
{
const struct tm *tm;
#ifdef HAVE_GMTIME_R
/* thread-safe version */
tm = (struct tm *)gmtime_r(&intime, store);
#else
/* !checksrc! disable BANNEDFUNC 1 */
tm = gmtime(&intime);
if(tm)
*store = *tm; /* copy the pointed struct to the local copy */
#endif
if(!tm)
return CURLE_BAD_FUNCTION_ARGUMENT;
return CURLE_OK;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/rtsp.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_RTSP) && !defined(USE_HYPER)
#include "urldata.h"
#include <curl/curl.h>
#include "transfer.h"
#include "sendf.h"
#include "multiif.h"
#include "http.h"
#include "url.h"
#include "progress.h"
#include "rtsp.h"
#include "strcase.h"
#include "select.h"
#include "connect.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#define RTP_PKT_CHANNEL(p) ((int)((unsigned char)((p)[1])))
#define RTP_PKT_LENGTH(p) ((((int)((unsigned char)((p)[2]))) << 8) | \
((int)((unsigned char)((p)[3]))))
/* protocol-specific functions set up to be called by the main engine */
static CURLcode rtsp_do(struct Curl_easy *data, bool *done);
static CURLcode rtsp_done(struct Curl_easy *data, CURLcode, bool premature);
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done);
static CURLcode rtsp_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead);
static int rtsp_getsock_do(struct Curl_easy *data,
struct connectdata *conn, curl_socket_t *socks);
/*
* Parse and write out any available RTP data.
*
* nread: amount of data left after k->str. will be modified if RTP
* data is parsed and k->str is moved up
* readmore: whether or not the RTP parser needs more data right away
*/
static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
struct connectdata *conn,
ssize_t *nread,
bool *readmore);
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
struct connectdata *conn);
static unsigned int rtsp_conncheck(struct Curl_easy *data,
struct connectdata *check,
unsigned int checks_to_perform);
/* this returns the socket to wait for in the DO and DOING state for the multi
interface and then we're always _sending_ a request and thus we wait for
the single socket to become writable only */
static int rtsp_getsock_do(struct Curl_easy *data, struct connectdata *conn,
curl_socket_t *socks)
{
/* write mode */
(void)data;
socks[0] = conn->sock[FIRSTSOCKET];
return GETSOCK_WRITESOCK(0);
}
static
CURLcode rtp_client_write(struct Curl_easy *data, char *ptr, size_t len);
/*
* RTSP handler interface.
*/
const struct Curl_handler Curl_handler_rtsp = {
"RTSP", /* scheme */
rtsp_setup_connection, /* setup_connection */
rtsp_do, /* do_it */
rtsp_done, /* done */
ZERO_NULL, /* do_more */
rtsp_connect, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
rtsp_getsock_do, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
rtsp_disconnect, /* disconnect */
rtsp_rtp_readwrite, /* readwrite */
rtsp_conncheck, /* connection_check */
ZERO_NULL, /* attach connection */
PORT_RTSP, /* defport */
CURLPROTO_RTSP, /* protocol */
CURLPROTO_RTSP, /* family */
PROTOPT_NONE /* flags */
};
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
struct connectdata *conn)
{
struct RTSP *rtsp;
(void)conn;
data->req.p.rtsp = rtsp = calloc(1, sizeof(struct RTSP));
if(!rtsp)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
/*
* The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
* want to block the application forever while receiving a stream. Therefore,
* we cannot assume that an RTSP socket is dead just because it is readable.
*
* Instead, if it is readable, run Curl_connalive() to peek at the socket
* and distinguish between closed and data.
*/
static bool rtsp_connisdead(struct connectdata *check)
{
int sval;
bool ret_val = TRUE;
sval = SOCKET_READABLE(check->sock[FIRSTSOCKET], 0);
if(sval == 0) {
/* timeout */
ret_val = FALSE;
}
else if(sval & CURL_CSELECT_ERR) {
/* socket is in an error state */
ret_val = TRUE;
}
else if(sval & CURL_CSELECT_IN) {
/* readable with no error. could still be closed */
ret_val = !Curl_connalive(check);
}
return ret_val;
}
/*
* Function to check on various aspects of a connection.
*/
static unsigned int rtsp_conncheck(struct Curl_easy *data,
struct connectdata *conn,
unsigned int checks_to_perform)
{
unsigned int ret_val = CONNRESULT_NONE;
(void)data;
if(checks_to_perform & CONNCHECK_ISDEAD) {
if(rtsp_connisdead(conn))
ret_val |= CONNRESULT_DEAD;
}
return ret_val;
}
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done)
{
CURLcode httpStatus;
httpStatus = Curl_http_connect(data, done);
/* Initialize the CSeq if not already done */
if(data->state.rtsp_next_client_CSeq == 0)
data->state.rtsp_next_client_CSeq = 1;
if(data->state.rtsp_next_server_CSeq == 0)
data->state.rtsp_next_server_CSeq = 1;
data->conn->proto.rtspc.rtp_channel = -1;
return httpStatus;
}
static CURLcode rtsp_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead)
{
(void) dead;
(void) data;
Curl_safefree(conn->proto.rtspc.rtp_buf);
return CURLE_OK;
}
static CURLcode rtsp_done(struct Curl_easy *data,
CURLcode status, bool premature)
{
struct RTSP *rtsp = data->req.p.rtsp;
CURLcode httpStatus;
/* Bypass HTTP empty-reply checks on receive */
if(data->set.rtspreq == RTSPREQ_RECEIVE)
premature = TRUE;
httpStatus = Curl_http_done(data, status, premature);
if(rtsp) {
/* Check the sequence numbers */
long CSeq_sent = rtsp->CSeq_sent;
long CSeq_recv = rtsp->CSeq_recv;
if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
failf(data,
"The CSeq of this request %ld did not match the response %ld",
CSeq_sent, CSeq_recv);
return CURLE_RTSP_CSEQ_ERROR;
}
if(data->set.rtspreq == RTSPREQ_RECEIVE &&
(data->conn->proto.rtspc.rtp_channel == -1)) {
infof(data, "Got an RTP Receive with a CSeq of %ld", CSeq_recv);
}
}
return httpStatus;
}
static CURLcode rtsp_do(struct Curl_easy *data, bool *done)
{
struct connectdata *conn = data->conn;
CURLcode result = CURLE_OK;
Curl_RtspReq rtspreq = data->set.rtspreq;
struct RTSP *rtsp = data->req.p.rtsp;
struct dynbuf req_buffer;
curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
const char *p_request = NULL;
const char *p_session_id = NULL;
const char *p_accept = NULL;
const char *p_accept_encoding = NULL;
const char *p_range = NULL;
const char *p_referrer = NULL;
const char *p_stream_uri = NULL;
const char *p_transport = NULL;
const char *p_uagent = NULL;
const char *p_proxyuserpwd = NULL;
const char *p_userpwd = NULL;
*done = TRUE;
rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
rtsp->CSeq_recv = 0;
/* Setup the 'p_request' pointer to the proper p_request string
* Since all RTSP requests are included here, there is no need to
* support custom requests like HTTP.
**/
data->set.opt_no_body = TRUE; /* most requests don't contain a body */
switch(rtspreq) {
default:
failf(data, "Got invalid RTSP request");
return CURLE_BAD_FUNCTION_ARGUMENT;
case RTSPREQ_OPTIONS:
p_request = "OPTIONS";
break;
case RTSPREQ_DESCRIBE:
p_request = "DESCRIBE";
data->set.opt_no_body = FALSE;
break;
case RTSPREQ_ANNOUNCE:
p_request = "ANNOUNCE";
break;
case RTSPREQ_SETUP:
p_request = "SETUP";
break;
case RTSPREQ_PLAY:
p_request = "PLAY";
break;
case RTSPREQ_PAUSE:
p_request = "PAUSE";
break;
case RTSPREQ_TEARDOWN:
p_request = "TEARDOWN";
break;
case RTSPREQ_GET_PARAMETER:
/* GET_PARAMETER's no_body status is determined later */
p_request = "GET_PARAMETER";
data->set.opt_no_body = FALSE;
break;
case RTSPREQ_SET_PARAMETER:
p_request = "SET_PARAMETER";
break;
case RTSPREQ_RECORD:
p_request = "RECORD";
break;
case RTSPREQ_RECEIVE:
p_request = "";
/* Treat interleaved RTP as body*/
data->set.opt_no_body = FALSE;
break;
case RTSPREQ_LAST:
failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
if(rtspreq == RTSPREQ_RECEIVE) {
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
return result;
}
p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
if(!p_session_id &&
(rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
p_request);
return CURLE_BAD_FUNCTION_ARGUMENT;
}
/* Stream URI. Default to server '*' if not specified */
if(data->set.str[STRING_RTSP_STREAM_URI]) {
p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
}
else {
p_stream_uri = "*";
}
/* Transport Header for SETUP requests */
p_transport = Curl_checkheaders(data, "Transport");
if(rtspreq == RTSPREQ_SETUP && !p_transport) {
/* New Transport: setting? */
if(data->set.str[STRING_RTSP_TRANSPORT]) {
Curl_safefree(data->state.aptr.rtsp_transport);
data->state.aptr.rtsp_transport =
aprintf("Transport: %s\r\n",
data->set.str[STRING_RTSP_TRANSPORT]);
if(!data->state.aptr.rtsp_transport)
return CURLE_OUT_OF_MEMORY;
}
else {
failf(data,
"Refusing to issue an RTSP SETUP without a Transport: header.");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
p_transport = data->state.aptr.rtsp_transport;
}
/* Accept Headers for DESCRIBE requests */
if(rtspreq == RTSPREQ_DESCRIBE) {
/* Accept Header */
p_accept = Curl_checkheaders(data, "Accept")?
NULL:"Accept: application/sdp\r\n";
/* Accept-Encoding header */
if(!Curl_checkheaders(data, "Accept-Encoding") &&
data->set.str[STRING_ENCODING]) {
Curl_safefree(data->state.aptr.accept_encoding);
data->state.aptr.accept_encoding =
aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
if(!data->state.aptr.accept_encoding)
return CURLE_OUT_OF_MEMORY;
p_accept_encoding = data->state.aptr.accept_encoding;
}
}
/* The User-Agent string might have been allocated in url.c already, because
it might have been used in the proxy connect, but if we have got a header
with the user-agent string specified, we erase the previously made string
here. */
if(Curl_checkheaders(data, "User-Agent") && data->state.aptr.uagent) {
Curl_safefree(data->state.aptr.uagent);
data->state.aptr.uagent = NULL;
}
else if(!Curl_checkheaders(data, "User-Agent") &&
data->set.str[STRING_USERAGENT]) {
p_uagent = data->state.aptr.uagent;
}
/* setup the authentication headers */
result = Curl_http_output_auth(data, conn, p_request, HTTPREQ_GET,
p_stream_uri, FALSE);
if(result)
return result;
p_proxyuserpwd = data->state.aptr.proxyuserpwd;
p_userpwd = data->state.aptr.userpwd;
/* Referrer */
Curl_safefree(data->state.aptr.ref);
if(data->state.referer && !Curl_checkheaders(data, "Referer"))
data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer);
else
data->state.aptr.ref = NULL;
p_referrer = data->state.aptr.ref;
/*
* Range Header
* Only applies to PLAY, PAUSE, RECORD
*
* Go ahead and use the Range stuff supplied for HTTP
*/
if(data->state.use_range &&
(rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
/* Check to see if there is a range set in the custom headers */
if(!Curl_checkheaders(data, "Range") && data->state.range) {
Curl_safefree(data->state.aptr.rangeline);
data->state.aptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
p_range = data->state.aptr.rangeline;
}
}
/*
* Sanity check the custom headers
*/
if(Curl_checkheaders(data, "CSeq")) {
failf(data, "CSeq cannot be set as a custom header.");
return CURLE_RTSP_CSEQ_ERROR;
}
if(Curl_checkheaders(data, "Session")) {
failf(data, "Session ID cannot be set as a custom header.");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
/* Initialize a dynamic send buffer */
Curl_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
result =
Curl_dyn_addf(&req_buffer,
"%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
"CSeq: %ld\r\n", /* CSeq */
p_request, p_stream_uri, rtsp->CSeq_sent);
if(result)
return result;
/*
* Rather than do a normal alloc line, keep the session_id unformatted
* to make comparison easier
*/
if(p_session_id) {
result = Curl_dyn_addf(&req_buffer, "Session: %s\r\n", p_session_id);
if(result)
return result;
}
/*
* Shared HTTP-like options
*/
result = Curl_dyn_addf(&req_buffer,
"%s" /* transport */
"%s" /* accept */
"%s" /* accept-encoding */
"%s" /* range */
"%s" /* referrer */
"%s" /* user-agent */
"%s" /* proxyuserpwd */
"%s" /* userpwd */
,
p_transport ? p_transport : "",
p_accept ? p_accept : "",
p_accept_encoding ? p_accept_encoding : "",
p_range ? p_range : "",
p_referrer ? p_referrer : "",
p_uagent ? p_uagent : "",
p_proxyuserpwd ? p_proxyuserpwd : "",
p_userpwd ? p_userpwd : "");
/*
* Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM
* with basic and digest, it will be freed anyway by the next request
*/
Curl_safefree(data->state.aptr.userpwd);
data->state.aptr.userpwd = NULL;
if(result)
return result;
if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
result = Curl_add_timecondition(data, &req_buffer);
if(result)
return result;
}
result = Curl_add_custom_headers(data, FALSE, &req_buffer);
if(result)
return result;
if(rtspreq == RTSPREQ_ANNOUNCE ||
rtspreq == RTSPREQ_SET_PARAMETER ||
rtspreq == RTSPREQ_GET_PARAMETER) {
if(data->set.upload) {
putsize = data->state.infilesize;
data->state.httpreq = HTTPREQ_PUT;
}
else {
postsize = (data->state.infilesize != -1)?
data->state.infilesize:
(data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
data->state.httpreq = HTTPREQ_POST;
}
if(putsize > 0 || postsize > 0) {
/* As stated in the http comments, it is probably not wise to
* actually set a custom Content-Length in the headers */
if(!Curl_checkheaders(data, "Content-Length")) {
result =
Curl_dyn_addf(&req_buffer,
"Content-Length: %" CURL_FORMAT_CURL_OFF_T"\r\n",
(data->set.upload ? putsize : postsize));
if(result)
return result;
}
if(rtspreq == RTSPREQ_SET_PARAMETER ||
rtspreq == RTSPREQ_GET_PARAMETER) {
if(!Curl_checkheaders(data, "Content-Type")) {
result = Curl_dyn_addf(&req_buffer,
"Content-Type: text/parameters\r\n");
if(result)
return result;
}
}
if(rtspreq == RTSPREQ_ANNOUNCE) {
if(!Curl_checkheaders(data, "Content-Type")) {
result = Curl_dyn_addf(&req_buffer,
"Content-Type: application/sdp\r\n");
if(result)
return result;
}
}
data->state.expect100header = FALSE; /* RTSP posts are simple/small */
}
else if(rtspreq == RTSPREQ_GET_PARAMETER) {
/* Check for an empty GET_PARAMETER (heartbeat) request */
data->state.httpreq = HTTPREQ_HEAD;
data->set.opt_no_body = TRUE;
}
}
/* RTSP never allows chunked transfer */
data->req.forbidchunk = TRUE;
/* Finish the request buffer */
result = Curl_dyn_add(&req_buffer, "\r\n");
if(result)
return result;
if(postsize > 0) {
result = Curl_dyn_addn(&req_buffer, data->set.postfields,
(size_t)postsize);
if(result)
return result;
}
/* issue the request */
result = Curl_buffer_send(&req_buffer, data,
&data->info.request_size, 0, FIRSTSOCKET);
if(result) {
failf(data, "Failed sending RTSP request");
return result;
}
Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, putsize?FIRSTSOCKET:-1);
/* Increment the CSeq on success */
data->state.rtsp_next_client_CSeq++;
if(data->req.writebytecount) {
/* if a request-body has been sent off, we make sure this progress is
noted properly */
Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
if(Curl_pgrsUpdate(data))
result = CURLE_ABORTED_BY_CALLBACK;
}
return result;
}
static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
struct connectdata *conn,
ssize_t *nread,
bool *readmore) {
struct SingleRequest *k = &data->req;
struct rtsp_conn *rtspc = &(conn->proto.rtspc);
char *rtp; /* moving pointer to rtp data */
ssize_t rtp_dataleft; /* how much data left to parse in this round */
char *scratch;
CURLcode result;
if(rtspc->rtp_buf) {
/* There was some leftover data the last time. Merge buffers */
char *newptr = Curl_saferealloc(rtspc->rtp_buf,
rtspc->rtp_bufsize + *nread);
if(!newptr) {
rtspc->rtp_buf = NULL;
rtspc->rtp_bufsize = 0;
return CURLE_OUT_OF_MEMORY;
}
rtspc->rtp_buf = newptr;
memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
rtspc->rtp_bufsize += *nread;
rtp = rtspc->rtp_buf;
rtp_dataleft = rtspc->rtp_bufsize;
}
else {
/* Just parse the request buffer directly */
rtp = k->str;
rtp_dataleft = *nread;
}
while((rtp_dataleft > 0) &&
(rtp[0] == '$')) {
if(rtp_dataleft > 4) {
int rtp_length;
/* Parse the header */
/* The channel identifier immediately follows and is 1 byte */
rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
/* The length is two bytes */
rtp_length = RTP_PKT_LENGTH(rtp);
if(rtp_dataleft < rtp_length + 4) {
/* Need more - incomplete payload*/
*readmore = TRUE;
break;
}
/* We have the full RTP interleaved packet
* Write out the header including the leading '$' */
DEBUGF(infof(data, "RTP write channel %d rtp_length %d",
rtspc->rtp_channel, rtp_length));
result = rtp_client_write(data, &rtp[0], rtp_length + 4);
if(result) {
failf(data, "Got an error writing an RTP packet");
*readmore = FALSE;
Curl_safefree(rtspc->rtp_buf);
rtspc->rtp_buf = NULL;
rtspc->rtp_bufsize = 0;
return result;
}
/* Move forward in the buffer */
rtp_dataleft -= rtp_length + 4;
rtp += rtp_length + 4;
if(data->set.rtspreq == RTSPREQ_RECEIVE) {
/* If we are in a passive receive, give control back
* to the app as often as we can.
*/
k->keepon &= ~KEEP_RECV;
}
}
else {
/* Need more - incomplete header */
*readmore = TRUE;
break;
}
}
if(rtp_dataleft && rtp[0] == '$') {
DEBUGF(infof(data, "RTP Rewinding %zd %s", rtp_dataleft,
*readmore ? "(READMORE)" : ""));
/* Store the incomplete RTP packet for a "rewind" */
scratch = malloc(rtp_dataleft);
if(!scratch) {
Curl_safefree(rtspc->rtp_buf);
rtspc->rtp_buf = NULL;
rtspc->rtp_bufsize = 0;
return CURLE_OUT_OF_MEMORY;
}
memcpy(scratch, rtp, rtp_dataleft);
Curl_safefree(rtspc->rtp_buf);
rtspc->rtp_buf = scratch;
rtspc->rtp_bufsize = rtp_dataleft;
/* As far as the transfer is concerned, this data is consumed */
*nread = 0;
return CURLE_OK;
}
/* Fix up k->str to point just after the last RTP packet */
k->str += *nread - rtp_dataleft;
/* either all of the data has been read or...
* rtp now points at the next byte to parse
*/
if(rtp_dataleft > 0)
DEBUGASSERT(k->str[0] == rtp[0]);
DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
*nread = rtp_dataleft;
/* If we get here, we have finished with the leftover/merge buffer */
Curl_safefree(rtspc->rtp_buf);
rtspc->rtp_buf = NULL;
rtspc->rtp_bufsize = 0;
return CURLE_OK;
}
static
CURLcode rtp_client_write(struct Curl_easy *data, char *ptr, size_t len)
{
size_t wrote;
curl_write_callback writeit;
void *user_ptr;
if(len == 0) {
failf(data, "Cannot write a 0 size RTP packet.");
return CURLE_WRITE_ERROR;
}
/* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that
function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP
data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA
pointer to write out the RTP data. */
if(data->set.fwrite_rtp) {
writeit = data->set.fwrite_rtp;
user_ptr = data->set.rtp_out;
}
else {
writeit = data->set.fwrite_func;
user_ptr = data->set.out;
}
Curl_set_in_callback(data, true);
wrote = writeit(ptr, 1, len, user_ptr);
Curl_set_in_callback(data, false);
if(CURL_WRITEFUNC_PAUSE == wrote) {
failf(data, "Cannot pause RTP");
return CURLE_WRITE_ERROR;
}
if(wrote != len) {
failf(data, "Failed writing RTP data");
return CURLE_WRITE_ERROR;
}
return CURLE_OK;
}
CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, char *header)
{
long CSeq = 0;
if(checkprefix("CSeq:", header)) {
/* Store the received CSeq. Match is verified in rtsp_done */
int nc = sscanf(&header[4], ": %ld", &CSeq);
if(nc == 1) {
struct RTSP *rtsp = data->req.p.rtsp;
rtsp->CSeq_recv = CSeq; /* mark the request */
data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
}
else {
failf(data, "Unable to read the CSeq header: [%s]", header);
return CURLE_RTSP_CSEQ_ERROR;
}
}
else if(checkprefix("Session:", header)) {
char *start;
char *end;
size_t idlen;
/* Find the first non-space letter */
start = header + 8;
while(*start && ISSPACE(*start))
start++;
if(!*start) {
failf(data, "Got a blank Session ID");
return CURLE_RTSP_SESSION_ERROR;
}
/* Find the end of Session ID
*
* Allow any non whitespace content, up to the field separator or end of
* line. RFC 2326 isn't 100% clear on the session ID and for example
* gstreamer does url-encoded session ID's not covered by the standard.
*/
end = start;
while(*end && *end != ';' && !ISSPACE(*end))
end++;
idlen = end - start;
if(data->set.str[STRING_RTSP_SESSION_ID]) {
/* If the Session ID is set, then compare */
if(strlen(data->set.str[STRING_RTSP_SESSION_ID]) != idlen ||
strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], idlen) != 0) {
failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
start, data->set.str[STRING_RTSP_SESSION_ID]);
return CURLE_RTSP_SESSION_ERROR;
}
}
else {
/* If the Session ID is not set, and we find it in a response, then set
* it.
*/
/* Copy the id substring into a new buffer */
data->set.str[STRING_RTSP_SESSION_ID] = malloc(idlen + 1);
if(!data->set.str[STRING_RTSP_SESSION_ID])
return CURLE_OUT_OF_MEMORY;
memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, idlen);
(data->set.str[STRING_RTSP_SESSION_ID])[idlen] = '\0';
}
}
return CURLE_OK;
}
#endif /* CURL_DISABLE_RTSP or using Hyper */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_multibyte.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* This 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);
free(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;
free(filename_w);
free(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
free(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
}
int curlx_win32_access(const char *path, int mode)
{
#if defined(_UNICODE)
int result = -1;
wchar_t *path_w = curlx_convert_UTF8_to_wchar(path);
if(path_w) {
result = _waccess(path_w, mode);
free(path_w);
}
else
errno = EINVAL;
return result;
#else
return _access(path, mode);
#endif
}
#endif /* USE_WIN32_LARGE_FILES || USE_WIN32_SMALL_FILES */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/gopher.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_GOPHER
#include "urldata.h"
#include <curl/curl.h>
#include "transfer.h"
#include "sendf.h"
#include "connect.h"
#include "progress.h"
#include "gopher.h"
#include "select.h"
#include "strdup.h"
#include "vtls/vtls.h"
#include "url.h"
#include "escape.h"
#include "warnless.h"
#include "curl_printf.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/*
* Forward declarations.
*/
static CURLcode gopher_do(struct Curl_easy *data, bool *done);
#ifdef USE_SSL
static CURLcode gopher_connect(struct Curl_easy *data, bool *done);
static CURLcode gopher_connecting(struct Curl_easy *data, bool *done);
#endif
/*
* Gopher protocol handler.
* This is also a nice simple template to build off for simple
* connect-command-download protocols.
*/
const struct Curl_handler Curl_handler_gopher = {
"GOPHER", /* scheme */
ZERO_NULL, /* setup_connection */
gopher_do, /* do_it */
ZERO_NULL, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
ZERO_NULL, /* attach connection */
PORT_GOPHER, /* defport */
CURLPROTO_GOPHER, /* protocol */
CURLPROTO_GOPHER, /* family */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
const struct Curl_handler Curl_handler_gophers = {
"GOPHERS", /* scheme */
ZERO_NULL, /* setup_connection */
gopher_do, /* do_it */
ZERO_NULL, /* done */
ZERO_NULL, /* do_more */
gopher_connect, /* connect_it */
gopher_connecting, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
ZERO_NULL, /* attach connection */
PORT_GOPHER, /* defport */
CURLPROTO_GOPHERS, /* protocol */
CURLPROTO_GOPHER, /* family */
PROTOPT_SSL /* flags */
};
static CURLcode gopher_connect(struct Curl_easy *data, bool *done)
{
(void)data;
(void)done;
return CURLE_OK;
}
static CURLcode gopher_connecting(struct Curl_easy *data, bool *done)
{
struct connectdata *conn = data->conn;
CURLcode result = Curl_ssl_connect(data, conn, FIRSTSOCKET);
if(result)
connclose(conn, "Failed TLS connection");
*done = TRUE;
return result;
}
#endif
static CURLcode gopher_do(struct Curl_easy *data, bool *done)
{
CURLcode result = CURLE_OK;
struct connectdata *conn = data->conn;
curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
char *gopherpath;
char *path = data->state.up.path;
char *query = data->state.up.query;
char *sel = NULL;
char *sel_org = NULL;
timediff_t timeout_ms;
ssize_t amount, k;
size_t len;
int what;
*done = TRUE; /* unconditionally */
/* path is guaranteed non-NULL */
DEBUGASSERT(path);
if(query)
gopherpath = aprintf("%s?%s", path, query);
else
gopherpath = strdup(path);
if(!gopherpath)
return CURLE_OUT_OF_MEMORY;
/* Create selector. Degenerate cases: / and /1 => convert to "" */
if(strlen(gopherpath) <= 2) {
sel = (char *)"";
len = strlen(sel);
free(gopherpath);
}
else {
char *newp;
/* Otherwise, drop / and the first character (i.e., item type) ... */
newp = gopherpath;
newp += 2;
/* ... and finally unescape */
result = Curl_urldecode(data, newp, 0, &sel, &len, REJECT_ZERO);
free(gopherpath);
if(result)
return result;
sel_org = sel;
}
k = curlx_uztosz(len);
for(;;) {
/* Break out of the loop if the selector is empty because OpenSSL and/or
LibreSSL fail with errno 0 if this is the case. */
if(strlen(sel) < 1)
break;
result = Curl_write(data, sockfd, sel, k, &amount);
if(!result) { /* Which may not have written it all! */
result = Curl_client_write(data, CLIENTWRITE_HEADER, sel, amount);
if(result)
break;
k -= amount;
sel += amount;
if(k < 1)
break; /* but it did write it all */
}
else
break;
timeout_ms = Curl_timeleft(data, NULL, FALSE);
if(timeout_ms < 0) {
result = CURLE_OPERATION_TIMEDOUT;
break;
}
if(!timeout_ms)
timeout_ms = TIMEDIFF_T_MAX;
/* Don't busyloop. The entire loop thing is a work-around as it causes a
BLOCKING behavior which is a NO-NO. This function should rather be
split up in a do and a doing piece where the pieces that aren't
possible to send now will be sent in the doing function repeatedly
until the entire request is sent.
*/
what = SOCKET_WRITABLE(sockfd, timeout_ms);
if(what < 0) {
result = CURLE_SEND_ERROR;
break;
}
else if(!what) {
result = CURLE_OPERATION_TIMEDOUT;
break;
}
}
free(sel_org);
if(!result)
result = Curl_write(data, sockfd, "\r\n", 2, &amount);
if(result) {
failf(data, "Failed sending Gopher request");
return result;
}
result = Curl_client_write(data, CLIENTWRITE_HEADER, (char *)"\r\n", 2);
if(result)
return result;
Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1);
return CURLE_OK;
}
#endif /*CURL_DISABLE_GOPHER*/
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_endian.h | #ifndef HEADER_CURL_ENDIAN_H
#define HEADER_CURL_ENDIAN_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* Converts a 16-bit integer from little endian */
unsigned short Curl_read16_le(const unsigned char *buf);
/* Converts a 32-bit integer from little endian */
unsigned int Curl_read32_le(const unsigned char *buf);
/* Converts a 16-bit integer from big endian */
unsigned short Curl_read16_be(const unsigned char *buf);
#if (SIZEOF_CURL_OFF_T > 4)
/* Converts a 64-bit integer to little endian */
#if defined(HAVE_LONGLONG)
void Curl_write64_le(const long long value, unsigned char *buffer);
#else
void Curl_write64_le(const __int64 value, unsigned char *buffer);
#endif
#endif
#endif /* HEADER_CURL_ENDIAN_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strtok.h | #ifndef HEADER_CURL_STRTOK_H
#define HEADER_CURL_STRTOK_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <stddef.h>
#ifndef HAVE_STRTOK_R
char *Curl_strtok_r(char *s, const char *delim, char **last);
#define strtok_r Curl_strtok_r
#else
#include <string.h>
#endif
#endif /* HEADER_CURL_STRTOK_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/easyoptions.h | #ifndef HEADER_CURL_EASYOPTIONS_H
#define HEADER_CURL_EASYOPTIONS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* should probably go into the public header */
#include <curl/curl.h>
/* generated table with all easy options */
extern struct curl_easyoption Curl_easyopts[];
#ifdef DEBUGBUILD
int Curl_easyopts_check(void);
#endif
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-amigaos.h | #ifndef HEADER_CURL_CONFIG_AMIGAOS_H
#define HEADER_CURL_CONFIG_AMIGAOS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* Hand crafted config file for AmigaOS */
/* ================================================================ */
#ifdef __AMIGA__ /* Any AmigaOS flavour */
#define HAVE_ARPA_INET_H 1
#define HAVE_CLOSESOCKET_CAMEL 1
#define HAVE_ERRNO_H 1
#define HAVE_INET_ADDR 1
#define HAVE_INTTYPES_H 1
#define HAVE_IOCTLSOCKET_CAMEL 1
#define HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1
#define HAVE_LIBZ 1
#define HAVE_LONGLONG 1
#define HAVE_MALLOC_H 1
#define HAVE_MEMORY_H 1
#define HAVE_NETDB_H 1
#define HAVE_NETINET_IN_H 1
#define HAVE_NET_IF_H 1
#define HAVE_OPENSSL_CRYPTO_H 1
#define HAVE_OPENSSL_ERR_H 1
#define HAVE_OPENSSL_PEM_H 1
#define HAVE_OPENSSL_RSA_H 1
#define HAVE_OPENSSL_SSL_H 1
#define HAVE_OPENSSL_X509_H 1
#define HAVE_PWD_H 1
#define HAVE_RAND_EGD 1
#define HAVE_RAND_STATUS 1
#define HAVE_SELECT 1
#define HAVE_SETJMP_H 1
#define HAVE_SIGNAL 1
#define HAVE_SIGNAL_H 1
#define HAVE_SOCKET 1
#define HAVE_STRCASECMP 1
#define HAVE_STRDUP 1
#define HAVE_STRFTIME 1
#define HAVE_STRICMP 1
#define HAVE_STRINGS_H 1
#define HAVE_STRING_H 1
#define HAVE_STRSTR 1
#define HAVE_STRUCT_TIMEVAL 1
#define HAVE_SYS_PARAM_H 1
#define HAVE_SYS_SOCKET_H 1
#define HAVE_SYS_SOCKIO_H 1
#define HAVE_SYS_STAT_H 1
#define HAVE_SYS_TIME_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_TIME_H 1
#define HAVE_UNAME 1
#define HAVE_UNISTD_H 1
#define HAVE_UTIME 1
#define HAVE_UTIME_H 1
#define HAVE_WRITABLE_ARGV 1
#define HAVE_ZLIB_H 1
#define HAVE_SYS_IOCTL_H 1
#define NEED_MALLOC_H 1
#define SIZEOF_INT 4
#define SIZEOF_SHORT 2
#define SIZEOF_SIZE_T 4
#define USE_MANUAL 1
#define USE_OPENSSL 1
#define CURL_DISABLE_LDAP 1
#define OS "AmigaOS"
#define PACKAGE "curl"
#define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/"
#define PACKAGE_NAME "curl"
#define PACKAGE_STRING "curl -"
#define PACKAGE_TARNAME "curl"
#define PACKAGE_VERSION "-"
#define CURL_CA_BUNDLE "s:curl-ca-bundle.crt"
#define SELECT_TYPE_ARG1 int
#define SELECT_TYPE_ARG234 (fd_set *)
#define SELECT_TYPE_ARG5 (struct timeval *)
#define STDC_HEADERS 1
#define TIME_WITH_SYS_TIME 1
#define in_addr_t int
#ifndef F_OK
# define F_OK 0
#endif
#ifndef O_RDONLY
# define O_RDONLY 0x0000
#endif
#ifndef LONG_MAX
# define LONG_MAX 0x7fffffffL
#endif
#ifndef LONG_MIN
# define LONG_MIN (-0x7fffffffL-1)
#endif
#define HAVE_RECV 1
#define RECV_TYPE_ARG1 long
#define RECV_TYPE_ARG2 char *
#define RECV_TYPE_ARG3 long
#define RECV_TYPE_ARG4 long
#define RECV_TYPE_RETV long
#define HAVE_RECVFROM 1
#define RECVFROM_TYPE_ARG1 long
#define RECVFROM_TYPE_ARG2 char
#define RECVFROM_TYPE_ARG3 long
#define RECVFROM_TYPE_ARG4 long
#define RECVFROM_TYPE_ARG5 struct sockaddr
#define RECVFROM_TYPE_ARG6 long
#define RECVFROM_TYPE_RETV long
#define HAVE_SEND 1
#define SEND_TYPE_ARG1 int
#define SEND_QUAL_ARG2 const
#define SEND_TYPE_ARG2 char *
#define SEND_TYPE_ARG3 int
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV int
#endif /* __AMIGA__ */
#endif /* HEADER_CURL_CONFIG_AMIGAOS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_ntlm_core.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(USE_CURL_NTLM_CORE)
/*
* NTLM details:
*
* https://davenport.sourceforge.io/ntlm.html
* https://www.innovation.ch/java/ntlm.html
*/
/* Please keep the SSL backend-specific #if branches in this order:
1. USE_OPENSSL
2. USE_GNUTLS
3. USE_NSS
4. USE_MBEDTLS
5. USE_SECTRANSP
6. USE_OS400CRYPTO
7. USE_WIN32_CRYPTO
This ensures that:
- the same SSL branch gets activated throughout this source
file even if multiple backends are enabled at the same time.
- OpenSSL and NSS have higher priority than Windows Crypt, due
to issues with the latter supporting NTLM2Session responses
in NTLM type-3 messages.
*/
#if defined(USE_OPENSSL)
#include <openssl/opensslconf.h>
#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0)
#define USE_OPENSSL_DES
#endif
#endif
#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
#ifdef USE_WOLFSSL
#include <wolfssl/options.h>
#endif
# include <openssl/des.h>
# include <openssl/md5.h>
# include <openssl/ssl.h>
# include <openssl/rand.h>
# if (defined(OPENSSL_VERSION_NUMBER) && \
(OPENSSL_VERSION_NUMBER < 0x00907001L)) && !defined(USE_WOLFSSL)
# define DES_key_schedule des_key_schedule
# define DES_cblock des_cblock
# define DES_set_odd_parity des_set_odd_parity
# define DES_set_key des_set_key
# define DES_ecb_encrypt des_ecb_encrypt
# define DESKEY(x) x
# define DESKEYARG(x) x
# else
# define DESKEYARG(x) *x
# define DESKEY(x) &x
# endif
#elif defined(USE_GNUTLS)
# include <nettle/des.h>
#elif defined(USE_NSS)
# include <nss.h>
# include <pk11pub.h>
# include <hasht.h>
#elif defined(USE_MBEDTLS)
# include <mbedtls/des.h>
#elif defined(USE_SECTRANSP)
# include <CommonCrypto/CommonCryptor.h>
# include <CommonCrypto/CommonDigest.h>
#elif defined(USE_OS400CRYPTO)
# include "cipher.mih" /* mih/cipher */
#elif defined(USE_WIN32_CRYPTO)
# include <wincrypt.h>
#else
# error "Can't compile NTLM support without a crypto library with DES."
#endif
#include "urldata.h"
#include "non-ascii.h"
#include "strcase.h"
#include "curl_ntlm_core.h"
#include "curl_md5.h"
#include "curl_hmac.h"
#include "warnless.h"
#include "curl_endian.h"
#include "curl_des.h"
#include "curl_md4.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#define NTLMv2_BLOB_SIGNATURE "\x01\x01\x00\x00"
#define NTLMv2_BLOB_LEN (44 -16 + ntlm->target_info_len + 4)
/*
* Turns a 56-bit key into being 64-bit wide.
*/
static void extend_key_56_to_64(const unsigned char *key_56, char *key)
{
key[0] = key_56[0];
key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1));
key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2));
key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3));
key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4));
key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5));
key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6));
key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF);
}
#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
/*
* Turns a 56 bit key into the 64 bit, odd parity key and sets the key. The
* key schedule ks is also set.
*/
static void setup_des_key(const unsigned char *key_56,
DES_key_schedule DESKEYARG(ks))
{
DES_cblock key;
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, (char *) &key);
/* Set the key parity to odd */
DES_set_odd_parity(&key);
/* Set the key */
DES_set_key_unchecked(&key, ks);
}
#elif defined(USE_GNUTLS)
static void setup_des_key(const unsigned char *key_56,
struct des_ctx *des)
{
char key[8];
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Set the key */
des_set_key(des, (const uint8_t *) key);
}
#elif defined(USE_NSS)
/*
* Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using
* the expanded key. The caller is responsible for giving 64 bit of valid
* data is IN and (at least) 64 bit large buffer as OUT.
*/
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */
char key[8]; /* expanded 64 bit key */
SECItem key_item;
PK11SymKey *symkey = NULL;
SECItem *param = NULL;
PK11Context *ctx = NULL;
int out_len; /* not used, required by NSS */
bool rv = FALSE;
/* use internal slot for DES encryption (requires NSS to be initialized) */
PK11SlotInfo *slot = PK11_GetInternalKeySlot();
if(!slot)
return FALSE;
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Import the key */
key_item.data = (unsigned char *)key;
key_item.len = sizeof(key);
symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT,
&key_item, NULL);
if(!symkey)
goto fail;
/* Create the DES encryption context */
param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL);
if(!param)
goto fail;
ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param);
if(!ctx)
goto fail;
/* Perform the encryption */
if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8,
(unsigned char *)in, /* inbuflen */ 8)
&& SECSuccess == PK11_Finalize(ctx))
rv = /* all OK */ TRUE;
fail:
/* cleanup */
if(ctx)
PK11_DestroyContext(ctx, PR_TRUE);
if(symkey)
PK11_FreeSymKey(symkey);
if(param)
SECITEM_FreeItem(param, PR_TRUE);
PK11_FreeSlot(slot);
return rv;
}
#elif defined(USE_MBEDTLS)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
mbedtls_des_context ctx;
char key[8];
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
mbedtls_des_key_set_parity((unsigned char *) key);
/* Perform the encryption */
mbedtls_des_init(&ctx);
mbedtls_des_setkey_enc(&ctx, (unsigned char *) key);
return mbedtls_des_crypt_ecb(&ctx, in, out) == 0;
}
#elif defined(USE_SECTRANSP)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
char key[8];
size_t out_len;
CCCryptorStatus err;
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) key, sizeof(key));
/* Perform the encryption */
err = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, key,
kCCKeySizeDES, NULL, in, 8 /* inbuflen */, out,
8 /* outbuflen */, &out_len);
return err == kCCSuccess;
}
#elif defined(USE_OS400CRYPTO)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
char key[8];
_CIPHER_Control_T ctl;
/* Setup the cipher control structure */
ctl.Func_ID = ENCRYPT_ONLY;
ctl.Data_Len = sizeof(key);
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, ctl.Crypto_Key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) ctl.Crypto_Key, ctl.Data_Len);
/* Perform the encryption */
_CIPHER((_SPCPTR *) &out, &ctl, (_SPCPTR *) &in);
return TRUE;
}
#elif defined(USE_WIN32_CRYPTO)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
const unsigned char *key_56)
{
HCRYPTPROV hprov;
HCRYPTKEY hkey;
struct {
BLOBHEADER hdr;
unsigned int len;
char key[8];
} blob;
DWORD len = 8;
/* Acquire the crypto provider */
if(!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
return FALSE;
/* Setup the key blob structure */
memset(&blob, 0, sizeof(blob));
blob.hdr.bType = PLAINTEXTKEYBLOB;
blob.hdr.bVersion = 2;
blob.hdr.aiKeyAlg = CALG_DES;
blob.len = sizeof(blob.key);
/* Expand the 56-bit key to 64-bits */
extend_key_56_to_64(key_56, blob.key);
/* Set the key parity to odd */
Curl_des_set_odd_parity((unsigned char *) blob.key, sizeof(blob.key));
/* Import the key */
if(!CryptImportKey(hprov, (BYTE *) &blob, sizeof(blob), 0, 0, &hkey)) {
CryptReleaseContext(hprov, 0);
return FALSE;
}
memcpy(out, in, 8);
/* Perform the encryption */
CryptEncrypt(hkey, 0, FALSE, 0, out, &len, len);
CryptDestroyKey(hkey);
CryptReleaseContext(hprov, 0);
return TRUE;
}
#endif /* defined(USE_WIN32_CRYPTO) */
/*
* takes a 21 byte array and treats it as 3 56-bit DES keys. The
* 8 byte plaintext is encrypted with each key and the resulting 24
* bytes are stored in the results array.
*/
void Curl_ntlm_core_lm_resp(const unsigned char *keys,
const unsigned char *plaintext,
unsigned char *results)
{
#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
DES_key_schedule ks;
setup_des_key(keys, DESKEY(ks));
DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results,
DESKEY(ks), DES_ENCRYPT);
setup_des_key(keys + 7, DESKEY(ks));
DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8),
DESKEY(ks), DES_ENCRYPT);
setup_des_key(keys + 14, DESKEY(ks));
DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16),
DESKEY(ks), DES_ENCRYPT);
#elif defined(USE_GNUTLS)
struct des_ctx des;
setup_des_key(keys, &des);
des_encrypt(&des, 8, results, plaintext);
setup_des_key(keys + 7, &des);
des_encrypt(&des, 8, results + 8, plaintext);
setup_des_key(keys + 14, &des);
des_encrypt(&des, 8, results + 16, plaintext);
#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
encrypt_des(plaintext, results, keys);
encrypt_des(plaintext, results + 8, keys + 7);
encrypt_des(plaintext, results + 16, keys + 14);
#endif
}
/*
* Set up lanmanager hashed password
*/
CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data,
const char *password,
unsigned char *lmbuffer /* 21 bytes */)
{
CURLcode result;
unsigned char pw[14];
static const unsigned char magic[] = {
0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */
};
size_t len = CURLMIN(strlen(password), 14);
Curl_strntoupper((char *)pw, password, len);
memset(&pw[len], 0, 14 - len);
/*
* The LanManager hashed password needs to be created using the
* password in the network encoding not the host encoding.
*/
result = Curl_convert_to_network(data, (char *)pw, 14);
if(result)
return result;
{
/* Create LanManager hashed password. */
#if defined(USE_OPENSSL_DES) || defined(USE_WOLFSSL)
DES_key_schedule ks;
setup_des_key(pw, DESKEY(ks));
DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer,
DESKEY(ks), DES_ENCRYPT);
setup_des_key(pw + 7, DESKEY(ks));
DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8),
DESKEY(ks), DES_ENCRYPT);
#elif defined(USE_GNUTLS)
struct des_ctx des;
setup_des_key(pw, &des);
des_encrypt(&des, 8, lmbuffer, magic);
setup_des_key(pw + 7, &des);
des_encrypt(&des, 8, lmbuffer + 8, magic);
#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_SECTRANSP) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
encrypt_des(magic, lmbuffer, pw);
encrypt_des(magic, lmbuffer + 8, pw + 7);
#endif
memset(lmbuffer + 16, 0, 21 - 16);
}
return CURLE_OK;
}
#ifdef USE_NTRESPONSES
static void ascii_to_unicode_le(unsigned char *dest, const char *src,
size_t srclen)
{
size_t i;
for(i = 0; i < srclen; i++) {
dest[2 * i] = (unsigned char)src[i];
dest[2 * i + 1] = '\0';
}
}
#if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI)
static void ascii_uppercase_to_unicode_le(unsigned char *dest,
const char *src, size_t srclen)
{
size_t i;
for(i = 0; i < srclen; i++) {
dest[2 * i] = (unsigned char)(Curl_raw_toupper(src[i]));
dest[2 * i + 1] = '\0';
}
}
#endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */
/*
* Set up nt hashed passwords
* @unittest: 1600
*/
CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
const char *password,
unsigned char *ntbuffer /* 21 bytes */)
{
size_t len = strlen(password);
unsigned char *pw;
CURLcode result;
if(len > SIZE_T_MAX/2) /* avoid integer overflow */
return CURLE_OUT_OF_MEMORY;
pw = len ? malloc(len * 2) : (unsigned char *)strdup("");
if(!pw)
return CURLE_OUT_OF_MEMORY;
ascii_to_unicode_le(pw, password, len);
/*
* The NT hashed password needs to be created using the password in the
* network encoding not the host encoding.
*/
result = Curl_convert_to_network(data, (char *)pw, len * 2);
if(!result) {
/* Create NT hashed password. */
Curl_md4it(ntbuffer, pw, 2 * len);
memset(ntbuffer + 16, 0, 21 - 16);
}
free(pw);
return result;
}
#if defined(USE_NTLM_V2) && !defined(USE_WINDOWS_SSPI)
/* Timestamp in tenths of a microsecond since January 1, 1601 00:00:00 UTC. */
struct ms_filetime {
unsigned int dwLowDateTime;
unsigned int dwHighDateTime;
};
/* Convert a time_t to an MS FILETIME (MS-DTYP section 2.3.3). */
static void time2filetime(struct ms_filetime *ft, time_t t)
{
#if SIZEOF_TIME_T > 4
t = (t + CURL_OFF_T_C(11644473600)) * 10000000;
ft->dwLowDateTime = (unsigned int) (t & 0xFFFFFFFF);
ft->dwHighDateTime = (unsigned int) (t >> 32);
#else
unsigned int r, s;
unsigned int i;
ft->dwLowDateTime = t & 0xFFFFFFFF;
ft->dwHighDateTime = 0;
# ifndef HAVE_TIME_T_UNSIGNED
/* Extend sign if needed. */
if(ft->dwLowDateTime & 0x80000000)
ft->dwHighDateTime = ~0;
# endif
/* Bias seconds to Jan 1, 1601.
134774 days = 11644473600 seconds = 0x2B6109100 */
r = ft->dwLowDateTime;
ft->dwLowDateTime = (ft->dwLowDateTime + 0xB6109100U) & 0xFFFFFFFF;
ft->dwHighDateTime += ft->dwLowDateTime < r? 0x03: 0x02;
/* Convert to tenths of microseconds. */
ft->dwHighDateTime *= 10000000;
i = 32;
do {
i -= 8;
s = ((ft->dwLowDateTime >> i) & 0xFF) * (10000000 - 1);
r = (s << i) & 0xFFFFFFFF;
s >>= 1; /* Split shift to avoid width overflow. */
s >>= 31 - i;
ft->dwLowDateTime = (ft->dwLowDateTime + r) & 0xFFFFFFFF;
if(ft->dwLowDateTime < r)
s++;
ft->dwHighDateTime += s;
} while(i);
ft->dwHighDateTime &= 0xFFFFFFFF;
#endif
}
/* This creates the NTLMv2 hash by using NTLM hash as the key and Unicode
* (uppercase UserName + Domain) as the data
*/
CURLcode Curl_ntlm_core_mk_ntlmv2_hash(const char *user, size_t userlen,
const char *domain, size_t domlen,
unsigned char *ntlmhash,
unsigned char *ntlmv2hash)
{
/* Unicode representation */
size_t identity_len;
unsigned char *identity;
CURLcode result = CURLE_OK;
if((userlen > CURL_MAX_INPUT_LENGTH) || (domlen > CURL_MAX_INPUT_LENGTH))
return CURLE_OUT_OF_MEMORY;
identity_len = (userlen + domlen) * 2;
identity = malloc(identity_len + 1);
if(!identity)
return CURLE_OUT_OF_MEMORY;
ascii_uppercase_to_unicode_le(identity, user, userlen);
ascii_to_unicode_le(identity + (userlen << 1), domain, domlen);
result = Curl_hmacit(Curl_HMAC_MD5, ntlmhash, 16, identity, identity_len,
ntlmv2hash);
free(identity);
return result;
}
/*
* Curl_ntlm_core_mk_ntlmv2_resp()
*
* This creates the NTLMv2 response as set in the ntlm type-3 message.
*
* Parameters:
*
* ntlmv2hash [in] - The ntlmv2 hash (16 bytes)
* challenge_client [in] - The client nonce (8 bytes)
* ntlm [in] - The ntlm data struct being used to read TargetInfo
and Server challenge received in the type-2 message
* ntresp [out] - The address where a pointer to newly allocated
* memory holding the NTLMv2 response.
* ntresp_len [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_ntlm_core_mk_ntlmv2_resp(unsigned char *ntlmv2hash,
unsigned char *challenge_client,
struct ntlmdata *ntlm,
unsigned char **ntresp,
unsigned int *ntresp_len)
{
/* NTLMv2 response structure :
------------------------------------------------------------------------------
0 HMAC MD5 16 bytes
------BLOB--------------------------------------------------------------------
16 Signature 0x01010000
20 Reserved long (0x00000000)
24 Timestamp LE, 64-bit signed value representing the number of
tenths of a microsecond since January 1, 1601.
32 Client Nonce 8 bytes
40 Unknown 4 bytes
44 Target Info N bytes (from the type-2 message)
44+N Unknown 4 bytes
------------------------------------------------------------------------------
*/
unsigned int len = 0;
unsigned char *ptr = NULL;
unsigned char hmac_output[HMAC_MD5_LENGTH];
struct ms_filetime tw;
CURLcode result = CURLE_OK;
/* Calculate the timestamp */
#ifdef DEBUGBUILD
char *force_timestamp = getenv("CURL_FORCETIME");
if(force_timestamp)
time2filetime(&tw, (time_t) 0);
else
#endif
time2filetime(&tw, time(NULL));
/* Calculate the response len */
len = HMAC_MD5_LENGTH + NTLMv2_BLOB_LEN;
/* Allocate the response */
ptr = calloc(1, len);
if(!ptr)
return CURLE_OUT_OF_MEMORY;
/* Create the BLOB structure */
msnprintf((char *)ptr + HMAC_MD5_LENGTH, NTLMv2_BLOB_LEN,
"%c%c%c%c" /* NTLMv2_BLOB_SIGNATURE */
"%c%c%c%c" /* Reserved = 0 */
"%c%c%c%c%c%c%c%c", /* Timestamp */
NTLMv2_BLOB_SIGNATURE[0], NTLMv2_BLOB_SIGNATURE[1],
NTLMv2_BLOB_SIGNATURE[2], NTLMv2_BLOB_SIGNATURE[3],
0, 0, 0, 0,
LONGQUARTET(tw.dwLowDateTime), LONGQUARTET(tw.dwHighDateTime));
memcpy(ptr + 32, challenge_client, 8);
memcpy(ptr + 44, ntlm->target_info, ntlm->target_info_len);
/* Concatenate the Type 2 challenge with the BLOB and do HMAC MD5 */
memcpy(ptr + 8, &ntlm->nonce[0], 8);
result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, HMAC_MD5_LENGTH, ptr + 8,
NTLMv2_BLOB_LEN + 8, hmac_output);
if(result) {
free(ptr);
return result;
}
/* Concatenate the HMAC MD5 output with the BLOB */
memcpy(ptr, hmac_output, HMAC_MD5_LENGTH);
/* Return the response */
*ntresp = ptr;
*ntresp_len = len;
return result;
}
/*
* Curl_ntlm_core_mk_lmv2_resp()
*
* This creates the LMv2 response as used in the ntlm type-3 message.
*
* Parameters:
*
* ntlmv2hash [in] - The ntlmv2 hash (16 bytes)
* challenge_client [in] - The client nonce (8 bytes)
* challenge_client [in] - The server challenge (8 bytes)
* lmresp [out] - The LMv2 response (24 bytes)
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash,
unsigned char *challenge_client,
unsigned char *challenge_server,
unsigned char *lmresp)
{
unsigned char data[16];
unsigned char hmac_output[16];
CURLcode result = CURLE_OK;
memcpy(&data[0], challenge_server, 8);
memcpy(&data[8], challenge_client, 8);
result = Curl_hmacit(Curl_HMAC_MD5, ntlmv2hash, 16, &data[0], 16,
hmac_output);
if(result)
return result;
/* Concatenate the HMAC MD5 output with the client nonce */
memcpy(lmresp, hmac_output, 16);
memcpy(lmresp + 16, challenge_client, 8);
return result;
}
#endif /* USE_NTLM_V2 && !USE_WINDOWS_SSPI */
#endif /* USE_NTRESPONSES */
#endif /* USE_CURL_NTLM_CORE */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/libcurl.vers.in | HIDDEN
{
local:
__*;
_rest*;
_save*;
};
CURL_@CURL_LT_SHLIB_VERSIONED_FLAVOUR@4
{
global: curl_*;
local: *;
};
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/easyoptions.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ | |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* ___|___/|_| ______|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* This source code is generated by optiontable.pl - DO NOT EDIT BY HAND */
#include "curl_setup.h"
#include "easyoptions.h"
/* all easy setopt options listed in alphabetical order */
struct curl_easyoption Curl_easyopts[] = {
{"ABSTRACT_UNIX_SOCKET", CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOT_STRING, 0},
{"ACCEPTTIMEOUT_MS", CURLOPT_ACCEPTTIMEOUT_MS, CURLOT_LONG, 0},
{"ACCEPT_ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, 0},
{"ADDRESS_SCOPE", CURLOPT_ADDRESS_SCOPE, CURLOT_LONG, 0},
{"ALTSVC", CURLOPT_ALTSVC, CURLOT_STRING, 0},
{"ALTSVC_CTRL", CURLOPT_ALTSVC_CTRL, CURLOT_LONG, 0},
{"APPEND", CURLOPT_APPEND, CURLOT_LONG, 0},
{"AUTOREFERER", CURLOPT_AUTOREFERER, CURLOT_LONG, 0},
{"AWS_SIGV4", CURLOPT_AWS_SIGV4, CURLOT_STRING, 0},
{"BUFFERSIZE", CURLOPT_BUFFERSIZE, CURLOT_LONG, 0},
{"CAINFO", CURLOPT_CAINFO, CURLOT_STRING, 0},
{"CAINFO_BLOB", CURLOPT_CAINFO_BLOB, CURLOT_BLOB, 0},
{"CAPATH", CURLOPT_CAPATH, CURLOT_STRING, 0},
{"CERTINFO", CURLOPT_CERTINFO, CURLOT_LONG, 0},
{"CHUNK_BGN_FUNCTION", CURLOPT_CHUNK_BGN_FUNCTION, CURLOT_FUNCTION, 0},
{"CHUNK_DATA", CURLOPT_CHUNK_DATA, CURLOT_CBPTR, 0},
{"CHUNK_END_FUNCTION", CURLOPT_CHUNK_END_FUNCTION, CURLOT_FUNCTION, 0},
{"CLOSESOCKETDATA", CURLOPT_CLOSESOCKETDATA, CURLOT_CBPTR, 0},
{"CLOSESOCKETFUNCTION", CURLOPT_CLOSESOCKETFUNCTION, CURLOT_FUNCTION, 0},
{"CONNECTTIMEOUT", CURLOPT_CONNECTTIMEOUT, CURLOT_LONG, 0},
{"CONNECTTIMEOUT_MS", CURLOPT_CONNECTTIMEOUT_MS, CURLOT_LONG, 0},
{"CONNECT_ONLY", CURLOPT_CONNECT_ONLY, CURLOT_LONG, 0},
{"CONNECT_TO", CURLOPT_CONNECT_TO, CURLOT_SLIST, 0},
{"CONV_FROM_NETWORK_FUNCTION", CURLOPT_CONV_FROM_NETWORK_FUNCTION,
CURLOT_FUNCTION, 0},
{"CONV_FROM_UTF8_FUNCTION", CURLOPT_CONV_FROM_UTF8_FUNCTION,
CURLOT_FUNCTION, 0},
{"CONV_TO_NETWORK_FUNCTION", CURLOPT_CONV_TO_NETWORK_FUNCTION,
CURLOT_FUNCTION, 0},
{"COOKIE", CURLOPT_COOKIE, CURLOT_STRING, 0},
{"COOKIEFILE", CURLOPT_COOKIEFILE, CURLOT_STRING, 0},
{"COOKIEJAR", CURLOPT_COOKIEJAR, CURLOT_STRING, 0},
{"COOKIELIST", CURLOPT_COOKIELIST, CURLOT_STRING, 0},
{"COOKIESESSION", CURLOPT_COOKIESESSION, CURLOT_LONG, 0},
{"COPYPOSTFIELDS", CURLOPT_COPYPOSTFIELDS, CURLOT_OBJECT, 0},
{"CRLF", CURLOPT_CRLF, CURLOT_LONG, 0},
{"CRLFILE", CURLOPT_CRLFILE, CURLOT_STRING, 0},
{"CURLU", CURLOPT_CURLU, CURLOT_OBJECT, 0},
{"CUSTOMREQUEST", CURLOPT_CUSTOMREQUEST, CURLOT_STRING, 0},
{"DEBUGDATA", CURLOPT_DEBUGDATA, CURLOT_CBPTR, 0},
{"DEBUGFUNCTION", CURLOPT_DEBUGFUNCTION, CURLOT_FUNCTION, 0},
{"DEFAULT_PROTOCOL", CURLOPT_DEFAULT_PROTOCOL, CURLOT_STRING, 0},
{"DIRLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, 0},
{"DISALLOW_USERNAME_IN_URL", CURLOPT_DISALLOW_USERNAME_IN_URL,
CURLOT_LONG, 0},
{"DNS_CACHE_TIMEOUT", CURLOPT_DNS_CACHE_TIMEOUT, CURLOT_LONG, 0},
{"DNS_INTERFACE", CURLOPT_DNS_INTERFACE, CURLOT_STRING, 0},
{"DNS_LOCAL_IP4", CURLOPT_DNS_LOCAL_IP4, CURLOT_STRING, 0},
{"DNS_LOCAL_IP6", CURLOPT_DNS_LOCAL_IP6, CURLOT_STRING, 0},
{"DNS_SERVERS", CURLOPT_DNS_SERVERS, CURLOT_STRING, 0},
{"DNS_SHUFFLE_ADDRESSES", CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOT_LONG, 0},
{"DNS_USE_GLOBAL_CACHE", CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOT_LONG, 0},
{"DOH_SSL_VERIFYHOST", CURLOPT_DOH_SSL_VERIFYHOST, CURLOT_LONG, 0},
{"DOH_SSL_VERIFYPEER", CURLOPT_DOH_SSL_VERIFYPEER, CURLOT_LONG, 0},
{"DOH_SSL_VERIFYSTATUS", CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOT_LONG, 0},
{"DOH_URL", CURLOPT_DOH_URL, CURLOT_STRING, 0},
{"EGDSOCKET", CURLOPT_EGDSOCKET, CURLOT_STRING, 0},
{"ENCODING", CURLOPT_ACCEPT_ENCODING, CURLOT_STRING, CURLOT_FLAG_ALIAS},
{"ERRORBUFFER", CURLOPT_ERRORBUFFER, CURLOT_OBJECT, 0},
{"EXPECT_100_TIMEOUT_MS", CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOT_LONG, 0},
{"FAILONERROR", CURLOPT_FAILONERROR, CURLOT_LONG, 0},
{"FILE", CURLOPT_WRITEDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS},
{"FILETIME", CURLOPT_FILETIME, CURLOT_LONG, 0},
{"FNMATCH_DATA", CURLOPT_FNMATCH_DATA, CURLOT_CBPTR, 0},
{"FNMATCH_FUNCTION", CURLOPT_FNMATCH_FUNCTION, CURLOT_FUNCTION, 0},
{"FOLLOWLOCATION", CURLOPT_FOLLOWLOCATION, CURLOT_LONG, 0},
{"FORBID_REUSE", CURLOPT_FORBID_REUSE, CURLOT_LONG, 0},
{"FRESH_CONNECT", CURLOPT_FRESH_CONNECT, CURLOT_LONG, 0},
{"FTPAPPEND", CURLOPT_APPEND, CURLOT_LONG, CURLOT_FLAG_ALIAS},
{"FTPLISTONLY", CURLOPT_DIRLISTONLY, CURLOT_LONG, CURLOT_FLAG_ALIAS},
{"FTPPORT", CURLOPT_FTPPORT, CURLOT_STRING, 0},
{"FTPSSLAUTH", CURLOPT_FTPSSLAUTH, CURLOT_VALUES, 0},
{"FTP_ACCOUNT", CURLOPT_FTP_ACCOUNT, CURLOT_STRING, 0},
{"FTP_ALTERNATIVE_TO_USER", CURLOPT_FTP_ALTERNATIVE_TO_USER,
CURLOT_STRING, 0},
{"FTP_CREATE_MISSING_DIRS", CURLOPT_FTP_CREATE_MISSING_DIRS,
CURLOT_LONG, 0},
{"FTP_FILEMETHOD", CURLOPT_FTP_FILEMETHOD, CURLOT_VALUES, 0},
{"FTP_RESPONSE_TIMEOUT", CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOT_LONG, 0},
{"FTP_SKIP_PASV_IP", CURLOPT_FTP_SKIP_PASV_IP, CURLOT_LONG, 0},
{"FTP_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, CURLOT_FLAG_ALIAS},
{"FTP_SSL_CCC", CURLOPT_FTP_SSL_CCC, CURLOT_LONG, 0},
{"FTP_USE_EPRT", CURLOPT_FTP_USE_EPRT, CURLOT_LONG, 0},
{"FTP_USE_EPSV", CURLOPT_FTP_USE_EPSV, CURLOT_LONG, 0},
{"FTP_USE_PRET", CURLOPT_FTP_USE_PRET, CURLOT_LONG, 0},
{"GSSAPI_DELEGATION", CURLOPT_GSSAPI_DELEGATION, CURLOT_VALUES, 0},
{"HAPPY_EYEBALLS_TIMEOUT_MS", CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS,
CURLOT_LONG, 0},
{"HAPROXYPROTOCOL", CURLOPT_HAPROXYPROTOCOL, CURLOT_LONG, 0},
{"HEADER", CURLOPT_HEADER, CURLOT_LONG, 0},
{"HEADERDATA", CURLOPT_HEADERDATA, CURLOT_CBPTR, 0},
{"HEADERFUNCTION", CURLOPT_HEADERFUNCTION, CURLOT_FUNCTION, 0},
{"HEADEROPT", CURLOPT_HEADEROPT, CURLOT_VALUES, 0},
{"HSTS", CURLOPT_HSTS, CURLOT_STRING, 0},
{"HSTSREADDATA", CURLOPT_HSTSREADDATA, CURLOT_CBPTR, 0},
{"HSTSREADFUNCTION", CURLOPT_HSTSREADFUNCTION, CURLOT_FUNCTION, 0},
{"HSTSWRITEDATA", CURLOPT_HSTSWRITEDATA, CURLOT_CBPTR, 0},
{"HSTSWRITEFUNCTION", CURLOPT_HSTSWRITEFUNCTION, CURLOT_FUNCTION, 0},
{"HSTS_CTRL", CURLOPT_HSTS_CTRL, CURLOT_LONG, 0},
{"HTTP09_ALLOWED", CURLOPT_HTTP09_ALLOWED, CURLOT_LONG, 0},
{"HTTP200ALIASES", CURLOPT_HTTP200ALIASES, CURLOT_SLIST, 0},
{"HTTPAUTH", CURLOPT_HTTPAUTH, CURLOT_VALUES, 0},
{"HTTPGET", CURLOPT_HTTPGET, CURLOT_LONG, 0},
{"HTTPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, 0},
{"HTTPPOST", CURLOPT_HTTPPOST, CURLOT_OBJECT, 0},
{"HTTPPROXYTUNNEL", CURLOPT_HTTPPROXYTUNNEL, CURLOT_LONG, 0},
{"HTTP_CONTENT_DECODING", CURLOPT_HTTP_CONTENT_DECODING, CURLOT_LONG, 0},
{"HTTP_TRANSFER_DECODING", CURLOPT_HTTP_TRANSFER_DECODING, CURLOT_LONG, 0},
{"HTTP_VERSION", CURLOPT_HTTP_VERSION, CURLOT_VALUES, 0},
{"IGNORE_CONTENT_LENGTH", CURLOPT_IGNORE_CONTENT_LENGTH, CURLOT_LONG, 0},
{"INFILE", CURLOPT_READDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS},
{"INFILESIZE", CURLOPT_INFILESIZE, CURLOT_LONG, 0},
{"INFILESIZE_LARGE", CURLOPT_INFILESIZE_LARGE, CURLOT_OFF_T, 0},
{"INTERFACE", CURLOPT_INTERFACE, CURLOT_STRING, 0},
{"INTERLEAVEDATA", CURLOPT_INTERLEAVEDATA, CURLOT_CBPTR, 0},
{"INTERLEAVEFUNCTION", CURLOPT_INTERLEAVEFUNCTION, CURLOT_FUNCTION, 0},
{"IOCTLDATA", CURLOPT_IOCTLDATA, CURLOT_CBPTR, 0},
{"IOCTLFUNCTION", CURLOPT_IOCTLFUNCTION, CURLOT_FUNCTION, 0},
{"IPRESOLVE", CURLOPT_IPRESOLVE, CURLOT_VALUES, 0},
{"ISSUERCERT", CURLOPT_ISSUERCERT, CURLOT_STRING, 0},
{"ISSUERCERT_BLOB", CURLOPT_ISSUERCERT_BLOB, CURLOT_BLOB, 0},
{"KEEP_SENDING_ON_ERROR", CURLOPT_KEEP_SENDING_ON_ERROR, CURLOT_LONG, 0},
{"KEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, 0},
{"KRB4LEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, CURLOT_FLAG_ALIAS},
{"KRBLEVEL", CURLOPT_KRBLEVEL, CURLOT_STRING, 0},
{"LOCALPORT", CURLOPT_LOCALPORT, CURLOT_LONG, 0},
{"LOCALPORTRANGE", CURLOPT_LOCALPORTRANGE, CURLOT_LONG, 0},
{"LOGIN_OPTIONS", CURLOPT_LOGIN_OPTIONS, CURLOT_STRING, 0},
{"LOW_SPEED_LIMIT", CURLOPT_LOW_SPEED_LIMIT, CURLOT_LONG, 0},
{"LOW_SPEED_TIME", CURLOPT_LOW_SPEED_TIME, CURLOT_LONG, 0},
{"MAIL_AUTH", CURLOPT_MAIL_AUTH, CURLOT_STRING, 0},
{"MAIL_FROM", CURLOPT_MAIL_FROM, CURLOT_STRING, 0},
{"MAIL_RCPT", CURLOPT_MAIL_RCPT, CURLOT_SLIST, 0},
{"MAIL_RCPT_ALLLOWFAILS", CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOT_LONG, 0},
{"MAXAGE_CONN", CURLOPT_MAXAGE_CONN, CURLOT_LONG, 0},
{"MAXCONNECTS", CURLOPT_MAXCONNECTS, CURLOT_LONG, 0},
{"MAXFILESIZE", CURLOPT_MAXFILESIZE, CURLOT_LONG, 0},
{"MAXFILESIZE_LARGE", CURLOPT_MAXFILESIZE_LARGE, CURLOT_OFF_T, 0},
{"MAXLIFETIME_CONN", CURLOPT_MAXLIFETIME_CONN, CURLOT_LONG, 0},
{"MAXREDIRS", CURLOPT_MAXREDIRS, CURLOT_LONG, 0},
{"MAX_RECV_SPEED_LARGE", CURLOPT_MAX_RECV_SPEED_LARGE, CURLOT_OFF_T, 0},
{"MAX_SEND_SPEED_LARGE", CURLOPT_MAX_SEND_SPEED_LARGE, CURLOT_OFF_T, 0},
{"MIMEPOST", CURLOPT_MIMEPOST, CURLOT_OBJECT, 0},
{"NETRC", CURLOPT_NETRC, CURLOT_VALUES, 0},
{"NETRC_FILE", CURLOPT_NETRC_FILE, CURLOT_STRING, 0},
{"NEW_DIRECTORY_PERMS", CURLOPT_NEW_DIRECTORY_PERMS, CURLOT_LONG, 0},
{"NEW_FILE_PERMS", CURLOPT_NEW_FILE_PERMS, CURLOT_LONG, 0},
{"NOBODY", CURLOPT_NOBODY, CURLOT_LONG, 0},
{"NOPROGRESS", CURLOPT_NOPROGRESS, CURLOT_LONG, 0},
{"NOPROXY", CURLOPT_NOPROXY, CURLOT_STRING, 0},
{"NOSIGNAL", CURLOPT_NOSIGNAL, CURLOT_LONG, 0},
{"OPENSOCKETDATA", CURLOPT_OPENSOCKETDATA, CURLOT_CBPTR, 0},
{"OPENSOCKETFUNCTION", CURLOPT_OPENSOCKETFUNCTION, CURLOT_FUNCTION, 0},
{"PASSWORD", CURLOPT_PASSWORD, CURLOT_STRING, 0},
{"PATH_AS_IS", CURLOPT_PATH_AS_IS, CURLOT_LONG, 0},
{"PINNEDPUBLICKEY", CURLOPT_PINNEDPUBLICKEY, CURLOT_STRING, 0},
{"PIPEWAIT", CURLOPT_PIPEWAIT, CURLOT_LONG, 0},
{"PORT", CURLOPT_PORT, CURLOT_LONG, 0},
{"POST", CURLOPT_POST, CURLOT_LONG, 0},
{"POST301", CURLOPT_POSTREDIR, CURLOT_VALUES, CURLOT_FLAG_ALIAS},
{"POSTFIELDS", CURLOPT_POSTFIELDS, CURLOT_OBJECT, 0},
{"POSTFIELDSIZE", CURLOPT_POSTFIELDSIZE, CURLOT_LONG, 0},
{"POSTFIELDSIZE_LARGE", CURLOPT_POSTFIELDSIZE_LARGE, CURLOT_OFF_T, 0},
{"POSTQUOTE", CURLOPT_POSTQUOTE, CURLOT_SLIST, 0},
{"POSTREDIR", CURLOPT_POSTREDIR, CURLOT_VALUES, 0},
{"PREQUOTE", CURLOPT_PREQUOTE, CURLOT_SLIST, 0},
{"PREREQDATA", CURLOPT_PREREQDATA, CURLOT_CBPTR, 0},
{"PREREQFUNCTION", CURLOPT_PREREQFUNCTION, CURLOT_FUNCTION, 0},
{"PRE_PROXY", CURLOPT_PRE_PROXY, CURLOT_STRING, 0},
{"PRIVATE", CURLOPT_PRIVATE, CURLOT_OBJECT, 0},
{"PROGRESSDATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS},
{"PROGRESSFUNCTION", CURLOPT_PROGRESSFUNCTION, CURLOT_FUNCTION, 0},
{"PROTOCOLS", CURLOPT_PROTOCOLS, CURLOT_LONG, 0},
{"PROXY", CURLOPT_PROXY, CURLOT_STRING, 0},
{"PROXYAUTH", CURLOPT_PROXYAUTH, CURLOT_VALUES, 0},
{"PROXYHEADER", CURLOPT_PROXYHEADER, CURLOT_SLIST, 0},
{"PROXYPASSWORD", CURLOPT_PROXYPASSWORD, CURLOT_STRING, 0},
{"PROXYPORT", CURLOPT_PROXYPORT, CURLOT_LONG, 0},
{"PROXYTYPE", CURLOPT_PROXYTYPE, CURLOT_VALUES, 0},
{"PROXYUSERNAME", CURLOPT_PROXYUSERNAME, CURLOT_STRING, 0},
{"PROXYUSERPWD", CURLOPT_PROXYUSERPWD, CURLOT_STRING, 0},
{"PROXY_CAINFO", CURLOPT_PROXY_CAINFO, CURLOT_STRING, 0},
{"PROXY_CAINFO_BLOB", CURLOPT_PROXY_CAINFO_BLOB, CURLOT_BLOB, 0},
{"PROXY_CAPATH", CURLOPT_PROXY_CAPATH, CURLOT_STRING, 0},
{"PROXY_CRLFILE", CURLOPT_PROXY_CRLFILE, CURLOT_STRING, 0},
{"PROXY_ISSUERCERT", CURLOPT_PROXY_ISSUERCERT, CURLOT_STRING, 0},
{"PROXY_ISSUERCERT_BLOB", CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOT_BLOB, 0},
{"PROXY_KEYPASSWD", CURLOPT_PROXY_KEYPASSWD, CURLOT_STRING, 0},
{"PROXY_PINNEDPUBLICKEY", CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOT_STRING, 0},
{"PROXY_SERVICE_NAME", CURLOPT_PROXY_SERVICE_NAME, CURLOT_STRING, 0},
{"PROXY_SSLCERT", CURLOPT_PROXY_SSLCERT, CURLOT_STRING, 0},
{"PROXY_SSLCERTTYPE", CURLOPT_PROXY_SSLCERTTYPE, CURLOT_STRING, 0},
{"PROXY_SSLCERT_BLOB", CURLOPT_PROXY_SSLCERT_BLOB, CURLOT_BLOB, 0},
{"PROXY_SSLKEY", CURLOPT_PROXY_SSLKEY, CURLOT_STRING, 0},
{"PROXY_SSLKEYTYPE", CURLOPT_PROXY_SSLKEYTYPE, CURLOT_STRING, 0},
{"PROXY_SSLKEY_BLOB", CURLOPT_PROXY_SSLKEY_BLOB, CURLOT_BLOB, 0},
{"PROXY_SSLVERSION", CURLOPT_PROXY_SSLVERSION, CURLOT_VALUES, 0},
{"PROXY_SSL_CIPHER_LIST", CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOT_STRING, 0},
{"PROXY_SSL_OPTIONS", CURLOPT_PROXY_SSL_OPTIONS, CURLOT_LONG, 0},
{"PROXY_SSL_VERIFYHOST", CURLOPT_PROXY_SSL_VERIFYHOST, CURLOT_LONG, 0},
{"PROXY_SSL_VERIFYPEER", CURLOPT_PROXY_SSL_VERIFYPEER, CURLOT_LONG, 0},
{"PROXY_TLS13_CIPHERS", CURLOPT_PROXY_TLS13_CIPHERS, CURLOT_STRING, 0},
{"PROXY_TLSAUTH_PASSWORD", CURLOPT_PROXY_TLSAUTH_PASSWORD,
CURLOT_STRING, 0},
{"PROXY_TLSAUTH_TYPE", CURLOPT_PROXY_TLSAUTH_TYPE, CURLOT_STRING, 0},
{"PROXY_TLSAUTH_USERNAME", CURLOPT_PROXY_TLSAUTH_USERNAME,
CURLOT_STRING, 0},
{"PROXY_TRANSFER_MODE", CURLOPT_PROXY_TRANSFER_MODE, CURLOT_LONG, 0},
{"PUT", CURLOPT_PUT, CURLOT_LONG, 0},
{"QUOTE", CURLOPT_QUOTE, CURLOT_SLIST, 0},
{"RANDOM_FILE", CURLOPT_RANDOM_FILE, CURLOT_STRING, 0},
{"RANGE", CURLOPT_RANGE, CURLOT_STRING, 0},
{"READDATA", CURLOPT_READDATA, CURLOT_CBPTR, 0},
{"READFUNCTION", CURLOPT_READFUNCTION, CURLOT_FUNCTION, 0},
{"REDIR_PROTOCOLS", CURLOPT_REDIR_PROTOCOLS, CURLOT_LONG, 0},
{"REFERER", CURLOPT_REFERER, CURLOT_STRING, 0},
{"REQUEST_TARGET", CURLOPT_REQUEST_TARGET, CURLOT_STRING, 0},
{"RESOLVE", CURLOPT_RESOLVE, CURLOT_SLIST, 0},
{"RESOLVER_START_DATA", CURLOPT_RESOLVER_START_DATA, CURLOT_CBPTR, 0},
{"RESOLVER_START_FUNCTION", CURLOPT_RESOLVER_START_FUNCTION,
CURLOT_FUNCTION, 0},
{"RESUME_FROM", CURLOPT_RESUME_FROM, CURLOT_LONG, 0},
{"RESUME_FROM_LARGE", CURLOPT_RESUME_FROM_LARGE, CURLOT_OFF_T, 0},
{"RTSPHEADER", CURLOPT_HTTPHEADER, CURLOT_SLIST, CURLOT_FLAG_ALIAS},
{"RTSP_CLIENT_CSEQ", CURLOPT_RTSP_CLIENT_CSEQ, CURLOT_LONG, 0},
{"RTSP_REQUEST", CURLOPT_RTSP_REQUEST, CURLOT_VALUES, 0},
{"RTSP_SERVER_CSEQ", CURLOPT_RTSP_SERVER_CSEQ, CURLOT_LONG, 0},
{"RTSP_SESSION_ID", CURLOPT_RTSP_SESSION_ID, CURLOT_STRING, 0},
{"RTSP_STREAM_URI", CURLOPT_RTSP_STREAM_URI, CURLOT_STRING, 0},
{"RTSP_TRANSPORT", CURLOPT_RTSP_TRANSPORT, CURLOT_STRING, 0},
{"SASL_AUTHZID", CURLOPT_SASL_AUTHZID, CURLOT_STRING, 0},
{"SASL_IR", CURLOPT_SASL_IR, CURLOT_LONG, 0},
{"SEEKDATA", CURLOPT_SEEKDATA, CURLOT_CBPTR, 0},
{"SEEKFUNCTION", CURLOPT_SEEKFUNCTION, CURLOT_FUNCTION, 0},
{"SERVER_RESPONSE_TIMEOUT", CURLOPT_FTP_RESPONSE_TIMEOUT,
CURLOT_LONG, CURLOT_FLAG_ALIAS},
{"SERVICE_NAME", CURLOPT_SERVICE_NAME, CURLOT_STRING, 0},
{"SHARE", CURLOPT_SHARE, CURLOT_OBJECT, 0},
{"SOCKOPTDATA", CURLOPT_SOCKOPTDATA, CURLOT_CBPTR, 0},
{"SOCKOPTFUNCTION", CURLOPT_SOCKOPTFUNCTION, CURLOT_FUNCTION, 0},
{"SOCKS5_AUTH", CURLOPT_SOCKS5_AUTH, CURLOT_LONG, 0},
{"SOCKS5_GSSAPI_NEC", CURLOPT_SOCKS5_GSSAPI_NEC, CURLOT_LONG, 0},
{"SOCKS5_GSSAPI_SERVICE", CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOT_STRING, 0},
{"SSH_AUTH_TYPES", CURLOPT_SSH_AUTH_TYPES, CURLOT_VALUES, 0},
{"SSH_COMPRESSION", CURLOPT_SSH_COMPRESSION, CURLOT_LONG, 0},
{"SSH_HOST_PUBLIC_KEY_MD5", CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
CURLOT_STRING, 0},
{"SSH_HOST_PUBLIC_KEY_SHA256", CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256,
CURLOT_STRING, 0},
{"SSH_KEYDATA", CURLOPT_SSH_KEYDATA, CURLOT_CBPTR, 0},
{"SSH_KEYFUNCTION", CURLOPT_SSH_KEYFUNCTION, CURLOT_FUNCTION, 0},
{"SSH_KNOWNHOSTS", CURLOPT_SSH_KNOWNHOSTS, CURLOT_STRING, 0},
{"SSH_PRIVATE_KEYFILE", CURLOPT_SSH_PRIVATE_KEYFILE, CURLOT_STRING, 0},
{"SSH_PUBLIC_KEYFILE", CURLOPT_SSH_PUBLIC_KEYFILE, CURLOT_STRING, 0},
{"SSLCERT", CURLOPT_SSLCERT, CURLOT_STRING, 0},
{"SSLCERTPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS},
{"SSLCERTTYPE", CURLOPT_SSLCERTTYPE, CURLOT_STRING, 0},
{"SSLCERT_BLOB", CURLOPT_SSLCERT_BLOB, CURLOT_BLOB, 0},
{"SSLENGINE", CURLOPT_SSLENGINE, CURLOT_STRING, 0},
{"SSLENGINE_DEFAULT", CURLOPT_SSLENGINE_DEFAULT, CURLOT_LONG, 0},
{"SSLKEY", CURLOPT_SSLKEY, CURLOT_STRING, 0},
{"SSLKEYPASSWD", CURLOPT_KEYPASSWD, CURLOT_STRING, CURLOT_FLAG_ALIAS},
{"SSLKEYTYPE", CURLOPT_SSLKEYTYPE, CURLOT_STRING, 0},
{"SSLKEY_BLOB", CURLOPT_SSLKEY_BLOB, CURLOT_BLOB, 0},
{"SSLVERSION", CURLOPT_SSLVERSION, CURLOT_VALUES, 0},
{"SSL_CIPHER_LIST", CURLOPT_SSL_CIPHER_LIST, CURLOT_STRING, 0},
{"SSL_CTX_DATA", CURLOPT_SSL_CTX_DATA, CURLOT_CBPTR, 0},
{"SSL_CTX_FUNCTION", CURLOPT_SSL_CTX_FUNCTION, CURLOT_FUNCTION, 0},
{"SSL_EC_CURVES", CURLOPT_SSL_EC_CURVES, CURLOT_STRING, 0},
{"SSL_ENABLE_ALPN", CURLOPT_SSL_ENABLE_ALPN, CURLOT_LONG, 0},
{"SSL_ENABLE_NPN", CURLOPT_SSL_ENABLE_NPN, CURLOT_LONG, 0},
{"SSL_FALSESTART", CURLOPT_SSL_FALSESTART, CURLOT_LONG, 0},
{"SSL_OPTIONS", CURLOPT_SSL_OPTIONS, CURLOT_VALUES, 0},
{"SSL_SESSIONID_CACHE", CURLOPT_SSL_SESSIONID_CACHE, CURLOT_LONG, 0},
{"SSL_VERIFYHOST", CURLOPT_SSL_VERIFYHOST, CURLOT_LONG, 0},
{"SSL_VERIFYPEER", CURLOPT_SSL_VERIFYPEER, CURLOT_LONG, 0},
{"SSL_VERIFYSTATUS", CURLOPT_SSL_VERIFYSTATUS, CURLOT_LONG, 0},
{"STDERR", CURLOPT_STDERR, CURLOT_OBJECT, 0},
{"STREAM_DEPENDS", CURLOPT_STREAM_DEPENDS, CURLOT_OBJECT, 0},
{"STREAM_DEPENDS_E", CURLOPT_STREAM_DEPENDS_E, CURLOT_OBJECT, 0},
{"STREAM_WEIGHT", CURLOPT_STREAM_WEIGHT, CURLOT_LONG, 0},
{"SUPPRESS_CONNECT_HEADERS", CURLOPT_SUPPRESS_CONNECT_HEADERS,
CURLOT_LONG, 0},
{"TCP_FASTOPEN", CURLOPT_TCP_FASTOPEN, CURLOT_LONG, 0},
{"TCP_KEEPALIVE", CURLOPT_TCP_KEEPALIVE, CURLOT_LONG, 0},
{"TCP_KEEPIDLE", CURLOPT_TCP_KEEPIDLE, CURLOT_LONG, 0},
{"TCP_KEEPINTVL", CURLOPT_TCP_KEEPINTVL, CURLOT_LONG, 0},
{"TCP_NODELAY", CURLOPT_TCP_NODELAY, CURLOT_LONG, 0},
{"TELNETOPTIONS", CURLOPT_TELNETOPTIONS, CURLOT_SLIST, 0},
{"TFTP_BLKSIZE", CURLOPT_TFTP_BLKSIZE, CURLOT_LONG, 0},
{"TFTP_NO_OPTIONS", CURLOPT_TFTP_NO_OPTIONS, CURLOT_LONG, 0},
{"TIMECONDITION", CURLOPT_TIMECONDITION, CURLOT_VALUES, 0},
{"TIMEOUT", CURLOPT_TIMEOUT, CURLOT_LONG, 0},
{"TIMEOUT_MS", CURLOPT_TIMEOUT_MS, CURLOT_LONG, 0},
{"TIMEVALUE", CURLOPT_TIMEVALUE, CURLOT_LONG, 0},
{"TIMEVALUE_LARGE", CURLOPT_TIMEVALUE_LARGE, CURLOT_OFF_T, 0},
{"TLS13_CIPHERS", CURLOPT_TLS13_CIPHERS, CURLOT_STRING, 0},
{"TLSAUTH_PASSWORD", CURLOPT_TLSAUTH_PASSWORD, CURLOT_STRING, 0},
{"TLSAUTH_TYPE", CURLOPT_TLSAUTH_TYPE, CURLOT_STRING, 0},
{"TLSAUTH_USERNAME", CURLOPT_TLSAUTH_USERNAME, CURLOT_STRING, 0},
{"TRAILERDATA", CURLOPT_TRAILERDATA, CURLOT_CBPTR, 0},
{"TRAILERFUNCTION", CURLOPT_TRAILERFUNCTION, CURLOT_FUNCTION, 0},
{"TRANSFERTEXT", CURLOPT_TRANSFERTEXT, CURLOT_LONG, 0},
{"TRANSFER_ENCODING", CURLOPT_TRANSFER_ENCODING, CURLOT_LONG, 0},
{"UNIX_SOCKET_PATH", CURLOPT_UNIX_SOCKET_PATH, CURLOT_STRING, 0},
{"UNRESTRICTED_AUTH", CURLOPT_UNRESTRICTED_AUTH, CURLOT_LONG, 0},
{"UPKEEP_INTERVAL_MS", CURLOPT_UPKEEP_INTERVAL_MS, CURLOT_LONG, 0},
{"UPLOAD", CURLOPT_UPLOAD, CURLOT_LONG, 0},
{"UPLOAD_BUFFERSIZE", CURLOPT_UPLOAD_BUFFERSIZE, CURLOT_LONG, 0},
{"URL", CURLOPT_URL, CURLOT_STRING, 0},
{"USERAGENT", CURLOPT_USERAGENT, CURLOT_STRING, 0},
{"USERNAME", CURLOPT_USERNAME, CURLOT_STRING, 0},
{"USERPWD", CURLOPT_USERPWD, CURLOT_STRING, 0},
{"USE_SSL", CURLOPT_USE_SSL, CURLOT_VALUES, 0},
{"VERBOSE", CURLOPT_VERBOSE, CURLOT_LONG, 0},
{"WILDCARDMATCH", CURLOPT_WILDCARDMATCH, CURLOT_LONG, 0},
{"WRITEDATA", CURLOPT_WRITEDATA, CURLOT_CBPTR, 0},
{"WRITEFUNCTION", CURLOPT_WRITEFUNCTION, CURLOT_FUNCTION, 0},
{"WRITEHEADER", CURLOPT_HEADERDATA, CURLOT_CBPTR, CURLOT_FLAG_ALIAS},
{"XFERINFODATA", CURLOPT_XFERINFODATA, CURLOT_CBPTR, 0},
{"XFERINFOFUNCTION", CURLOPT_XFERINFOFUNCTION, CURLOT_FUNCTION, 0},
{"XOAUTH2_BEARER", CURLOPT_XOAUTH2_BEARER, CURLOT_STRING, 0},
{NULL, CURLOPT_LASTENTRY, 0, 0} /* end of table */
};
#ifdef DEBUGBUILD
/*
* Curl_easyopts_check() is a debug-only function that returns non-zero
* if this source file is not in sync with the options listed in curl/curl.h
*/
int Curl_easyopts_check(void)
{
return ((CURLOPT_LASTENTRY%10000) != (314 + 1));
}
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_path.h | #ifndef HEADER_CURL_PATH_H
#define HEADER_CURL_PATH_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#ifdef WIN32
# undef PATH_MAX
# define PATH_MAX MAX_PATH
# ifndef R_OK
# define R_OK 4
# endif
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024 /* just an extra precaution since there are systems that
have their definition hidden well */
#endif
CURLcode Curl_getworkingpath(struct Curl_easy *data,
char *homedir,
char **path);
CURLcode Curl_get_pathname(const char **cpp, char **path, char *homedir);
#endif /* HEADER_CURL_PATH_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_proxy.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "http_proxy.h"
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
#include <curl/curl.h>
#ifdef USE_HYPER
#include <hyper.h>
#endif
#include "sendf.h"
#include "http.h"
#include "url.h"
#include "select.h"
#include "progress.h"
#include "non-ascii.h"
#include "connect.h"
#include "curlx.h"
#include "vtls/vtls.h"
#include "transfer.h"
#include "multiif.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/*
* Perform SSL initialization for HTTPS proxy. Sets
* proxy_ssl_connected connection bit when complete. Can be
* called multiple times.
*/
static CURLcode https_proxy_connect(struct Curl_easy *data, int sockindex)
{
#ifdef USE_SSL
struct connectdata *conn = data->conn;
CURLcode result = CURLE_OK;
DEBUGASSERT(conn->http_proxy.proxytype == CURLPROXY_HTTPS);
if(!conn->bits.proxy_ssl_connected[sockindex]) {
/* perform SSL initialization for this socket */
result =
Curl_ssl_connect_nonblocking(data, conn, TRUE, sockindex,
&conn->bits.proxy_ssl_connected[sockindex]);
if(result)
/* a failed connection is marked for closure to prevent (bad) re-use or
similar */
connclose(conn, "TLS handshake failed");
}
return result;
#else
(void) data;
(void) sockindex;
return CURLE_NOT_BUILT_IN;
#endif
}
CURLcode Curl_proxy_connect(struct Curl_easy *data, int sockindex)
{
struct connectdata *conn = data->conn;
if(conn->http_proxy.proxytype == CURLPROXY_HTTPS) {
const CURLcode result = https_proxy_connect(data, sockindex);
if(result)
return result;
if(!conn->bits.proxy_ssl_connected[sockindex])
return result; /* wait for HTTPS proxy SSL initialization to complete */
}
if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
#ifndef CURL_DISABLE_PROXY
/* for [protocol] tunneled through HTTP proxy */
const char *hostname;
int remote_port;
CURLcode result;
/* We want "seamless" operations through HTTP proxy tunnel */
/* for the secondary socket (FTP), use the "connect to host"
* but ignore the "connect to port" (use the secondary port)
*/
if(conn->bits.conn_to_host)
hostname = conn->conn_to_host.name;
else if(sockindex == SECONDARYSOCKET)
hostname = conn->secondaryhostname;
else
hostname = conn->host.name;
if(sockindex == SECONDARYSOCKET)
remote_port = conn->secondary_port;
else if(conn->bits.conn_to_port)
remote_port = conn->conn_to_port;
else
remote_port = conn->remote_port;
result = Curl_proxyCONNECT(data, sockindex, hostname, remote_port);
if(CURLE_OK != result)
return result;
Curl_safefree(data->state.aptr.proxyuserpwd);
#else
return CURLE_NOT_BUILT_IN;
#endif
}
/* no HTTP tunnel proxy, just return */
return CURLE_OK;
}
bool Curl_connect_complete(struct connectdata *conn)
{
return !conn->connect_state ||
(conn->connect_state->tunnel_state >= TUNNEL_COMPLETE);
}
bool Curl_connect_ongoing(struct connectdata *conn)
{
return conn->connect_state &&
(conn->connect_state->tunnel_state <= TUNNEL_COMPLETE);
}
/* when we've sent a CONNECT to a proxy, we should rather either wait for the
socket to become readable to be able to get the response headers or if
we're still sending the request, wait for write. */
int Curl_connect_getsock(struct connectdata *conn)
{
struct HTTP *http;
DEBUGASSERT(conn);
DEBUGASSERT(conn->connect_state);
http = &conn->connect_state->http_proxy;
if(http->sending == HTTPSEND_REQUEST)
return GETSOCK_WRITESOCK(0);
return GETSOCK_READSOCK(0);
}
static CURLcode connect_init(struct Curl_easy *data, bool reinit)
{
struct http_connect_state *s;
struct connectdata *conn = data->conn;
if(!reinit) {
CURLcode result;
DEBUGASSERT(!conn->connect_state);
/* we might need the upload buffer for streaming a partial request */
result = Curl_get_upload_buffer(data);
if(result)
return result;
s = calloc(1, sizeof(struct http_connect_state));
if(!s)
return CURLE_OUT_OF_MEMORY;
infof(data, "allocate connect buffer!");
conn->connect_state = s;
Curl_dyn_init(&s->rcvbuf, DYN_PROXY_CONNECT_HEADERS);
/* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the
* member conn->proto.http; we want [protocol] through HTTP and we have
* to change the member temporarily for connecting to the HTTP
* proxy. After Curl_proxyCONNECT we have to set back the member to the
* original pointer
*
* This function might be called several times in the multi interface case
* if the proxy's CONNECT response is not instant.
*/
s->prot_save = data->req.p.http;
data->req.p.http = &s->http_proxy;
connkeep(conn, "HTTP proxy CONNECT");
}
else {
DEBUGASSERT(conn->connect_state);
s = conn->connect_state;
Curl_dyn_reset(&s->rcvbuf);
}
s->tunnel_state = TUNNEL_INIT;
s->keepon = KEEPON_CONNECT;
s->cl = 0;
s->close_connection = FALSE;
return CURLE_OK;
}
static void connect_done(struct Curl_easy *data)
{
struct connectdata *conn = data->conn;
struct http_connect_state *s = conn->connect_state;
if(s->tunnel_state != TUNNEL_EXIT) {
s->tunnel_state = TUNNEL_EXIT;
Curl_dyn_free(&s->rcvbuf);
Curl_dyn_free(&s->req);
/* restore the protocol pointer */
data->req.p.http = s->prot_save;
s->prot_save = NULL;
data->info.httpcode = 0; /* clear it as it might've been used for the
proxy */
data->req.ignorebody = FALSE;
#ifdef USE_HYPER
data->state.hconnect = FALSE;
#endif
infof(data, "CONNECT phase completed!");
}
}
static CURLcode CONNECT_host(struct Curl_easy *data,
struct connectdata *conn,
const char *hostname,
int remote_port,
char **connecthostp,
char **hostp)
{
char *hostheader; /* for CONNECT */
char *host = NULL; /* Host: */
bool ipv6_ip = conn->bits.ipv6_ip;
/* the hostname may be different */
if(hostname != conn->host.name)
ipv6_ip = (strchr(hostname, ':') != NULL);
hostheader = /* host:port with IPv6 support */
aprintf("%s%s%s:%d", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"",
remote_port);
if(!hostheader)
return CURLE_OUT_OF_MEMORY;
if(!Curl_checkProxyheaders(data, conn, "Host")) {
host = aprintf("Host: %s\r\n", hostheader);
if(!host) {
free(hostheader);
return CURLE_OUT_OF_MEMORY;
}
}
*connecthostp = hostheader;
*hostp = host;
return CURLE_OK;
}
#ifndef USE_HYPER
static CURLcode CONNECT(struct Curl_easy *data,
int sockindex,
const char *hostname,
int remote_port)
{
int subversion = 0;
struct SingleRequest *k = &data->req;
CURLcode result;
struct connectdata *conn = data->conn;
curl_socket_t tunnelsocket = conn->sock[sockindex];
struct http_connect_state *s = conn->connect_state;
struct HTTP *http = data->req.p.http;
char *linep;
size_t perline;
#define SELECT_OK 0
#define SELECT_ERROR 1
if(Curl_connect_complete(conn))
return CURLE_OK; /* CONNECT is already completed */
conn->bits.proxy_connect_closed = FALSE;
do {
timediff_t check;
if(TUNNEL_INIT == s->tunnel_state) {
/* BEGIN CONNECT PHASE */
struct dynbuf *req = &s->req;
char *hostheader = NULL;
char *host = NULL;
infof(data, "Establish HTTP proxy tunnel to %s:%d",
hostname, remote_port);
/* This only happens if we've looped here due to authentication
reasons, and we don't really use the newly cloned URL here
then. Just free() it. */
Curl_safefree(data->req.newurl);
/* initialize send-buffer */
Curl_dyn_init(req, DYN_HTTP_REQUEST);
result = CONNECT_host(data, conn,
hostname, remote_port, &hostheader, &host);
if(result)
return result;
/* Setup the proxy-authorization header, if any */
result = Curl_http_output_auth(data, conn, "CONNECT", HTTPREQ_GET,
hostheader, TRUE);
if(!result) {
const char *httpv =
(conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) ? "1.0" : "1.1";
result =
Curl_dyn_addf(req,
"CONNECT %s HTTP/%s\r\n"
"%s" /* Host: */
"%s", /* Proxy-Authorization */
hostheader,
httpv,
host?host:"",
data->state.aptr.proxyuserpwd?
data->state.aptr.proxyuserpwd:"");
if(!result && !Curl_checkProxyheaders(data, conn, "User-Agent") &&
data->set.str[STRING_USERAGENT])
result = Curl_dyn_addf(req, "User-Agent: %s\r\n",
data->set.str[STRING_USERAGENT]);
if(!result && !Curl_checkProxyheaders(data, conn, "Proxy-Connection"))
result = Curl_dyn_add(req, "Proxy-Connection: Keep-Alive\r\n");
if(!result)
result = Curl_add_custom_headers(data, TRUE, req);
if(!result)
/* CRLF terminate the request */
result = Curl_dyn_add(req, "\r\n");
if(!result) {
/* Send the connect request to the proxy */
result = Curl_buffer_send(req, data, &data->info.request_size, 0,
sockindex);
}
if(result)
failf(data, "Failed sending CONNECT to proxy");
}
free(host);
free(hostheader);
if(result)
return result;
s->tunnel_state = TUNNEL_CONNECT;
} /* END CONNECT PHASE */
check = Curl_timeleft(data, NULL, TRUE);
if(check <= 0) {
failf(data, "Proxy CONNECT aborted due to timeout");
return CURLE_OPERATION_TIMEDOUT;
}
if(!Curl_conn_data_pending(conn, sockindex) && !http->sending)
/* return so we'll be called again polling-style */
return CURLE_OK;
/* at this point, the tunnel_connecting phase is over. */
if(http->sending == HTTPSEND_REQUEST) {
if(!s->nsend) {
size_t fillcount;
k->upload_fromhere = data->state.ulbuf;
result = Curl_fillreadbuffer(data, data->set.upload_buffer_size,
&fillcount);
if(result)
return result;
s->nsend = fillcount;
}
if(s->nsend) {
ssize_t bytes_written;
/* write to socket (send away data) */
result = Curl_write(data,
conn->writesockfd, /* socket to send to */
k->upload_fromhere, /* buffer pointer */
s->nsend, /* buffer size */
&bytes_written); /* actually sent */
if(!result)
/* send to debug callback! */
result = Curl_debug(data, CURLINFO_HEADER_OUT,
k->upload_fromhere, bytes_written);
s->nsend -= bytes_written;
k->upload_fromhere += bytes_written;
return result;
}
http->sending = HTTPSEND_NADA;
/* if nothing left to send, continue */
}
{ /* READING RESPONSE PHASE */
int error = SELECT_OK;
while(s->keepon) {
ssize_t gotbytes;
char byte;
/* Read one byte at a time to avoid a race condition. Wait at most one
second before looping to ensure continuous pgrsUpdates. */
result = Curl_read(data, tunnelsocket, &byte, 1, &gotbytes);
if(result == CURLE_AGAIN)
/* socket buffer drained, return */
return CURLE_OK;
if(Curl_pgrsUpdate(data))
return CURLE_ABORTED_BY_CALLBACK;
if(result) {
s->keepon = KEEPON_DONE;
break;
}
else if(gotbytes <= 0) {
if(data->set.proxyauth && data->state.authproxy.avail &&
data->state.aptr.proxyuserpwd) {
/* proxy auth was requested and there was proxy auth available,
then deem this as "mere" proxy disconnect */
conn->bits.proxy_connect_closed = TRUE;
infof(data, "Proxy CONNECT connection closed");
}
else {
error = SELECT_ERROR;
failf(data, "Proxy CONNECT aborted");
}
s->keepon = KEEPON_DONE;
break;
}
if(s->keepon == KEEPON_IGNORE) {
/* This means we are currently ignoring a response-body */
if(s->cl) {
/* A Content-Length based body: simply count down the counter
and make sure to break out of the loop when we're done! */
s->cl--;
if(s->cl <= 0) {
s->keepon = KEEPON_DONE;
s->tunnel_state = TUNNEL_COMPLETE;
break;
}
}
else {
/* chunked-encoded body, so we need to do the chunked dance
properly to know when the end of the body is reached */
CHUNKcode r;
CURLcode extra;
ssize_t tookcareof = 0;
/* now parse the chunked piece of data so that we can
properly tell when the stream ends */
r = Curl_httpchunk_read(data, &byte, 1, &tookcareof, &extra);
if(r == CHUNKE_STOP) {
/* we're done reading chunks! */
infof(data, "chunk reading DONE");
s->keepon = KEEPON_DONE;
/* we did the full CONNECT treatment, go COMPLETE */
s->tunnel_state = TUNNEL_COMPLETE;
}
}
continue;
}
if(Curl_dyn_addn(&s->rcvbuf, &byte, 1)) {
failf(data, "CONNECT response too large!");
return CURLE_RECV_ERROR;
}
/* if this is not the end of a header line then continue */
if(byte != 0x0a)
continue;
linep = Curl_dyn_ptr(&s->rcvbuf);
perline = Curl_dyn_len(&s->rcvbuf); /* amount of bytes in this line */
/* convert from the network encoding */
result = Curl_convert_from_network(data, linep, perline);
/* Curl_convert_from_network calls failf if unsuccessful */
if(result)
return result;
/* output debug if that is requested */
Curl_debug(data, CURLINFO_HEADER_IN, linep, perline);
if(!data->set.suppress_connect_headers) {
/* send the header to the callback */
int writetype = CLIENTWRITE_HEADER;
if(data->set.include_header)
writetype |= CLIENTWRITE_BODY;
result = Curl_client_write(data, writetype, linep, perline);
if(result)
return result;
}
data->info.header_size += (long)perline;
/* Newlines are CRLF, so the CR is ignored as the line isn't
really terminated until the LF comes. Treat a following CR
as end-of-headers as well.*/
if(('\r' == linep[0]) ||
('\n' == linep[0])) {
/* end of response-headers from the proxy */
if((407 == k->httpcode) && !data->state.authproblem) {
/* If we get a 407 response code with content length
when we have no auth problem, we must ignore the
whole response-body */
s->keepon = KEEPON_IGNORE;
if(s->cl) {
infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T
" bytes of response-body", s->cl);
}
else if(s->chunked_encoding) {
CHUNKcode r;
CURLcode extra;
infof(data, "Ignore chunked response-body");
/* We set ignorebody true here since the chunked decoder
function will acknowledge that. Pay attention so that this is
cleared again when this function returns! */
k->ignorebody = TRUE;
if(linep[1] == '\n')
/* this can only be a LF if the letter at index 0 was a CR */
linep++;
/* now parse the chunked piece of data so that we can properly
tell when the stream ends */
r = Curl_httpchunk_read(data, linep + 1, 1, &gotbytes,
&extra);
if(r == CHUNKE_STOP) {
/* we're done reading chunks! */
infof(data, "chunk reading DONE");
s->keepon = KEEPON_DONE;
/* we did the full CONNECT treatment, go to COMPLETE */
s->tunnel_state = TUNNEL_COMPLETE;
}
}
else {
/* without content-length or chunked encoding, we
can't keep the connection alive since the close is
the end signal so we bail out at once instead */
s->keepon = KEEPON_DONE;
}
}
else
s->keepon = KEEPON_DONE;
if(s->keepon == KEEPON_DONE && !s->cl)
/* we did the full CONNECT treatment, go to COMPLETE */
s->tunnel_state = TUNNEL_COMPLETE;
DEBUGASSERT(s->keepon == KEEPON_IGNORE || s->keepon == KEEPON_DONE);
continue;
}
if((checkprefix("WWW-Authenticate:", linep) &&
(401 == k->httpcode)) ||
(checkprefix("Proxy-authenticate:", linep) &&
(407 == k->httpcode))) {
bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
char *auth = Curl_copy_header_value(linep);
if(!auth)
return CURLE_OUT_OF_MEMORY;
result = Curl_http_input_auth(data, proxy, auth);
free(auth);
if(result)
return result;
}
else if(checkprefix("Content-Length:", linep)) {
if(k->httpcode/100 == 2) {
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
"Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */
infof(data, "Ignoring Content-Length in CONNECT %03d response",
k->httpcode);
}
else {
(void)curlx_strtoofft(linep +
strlen("Content-Length:"), NULL, 10, &s->cl);
}
}
else if(Curl_compareheader(linep, "Connection:", "close"))
s->close_connection = TRUE;
else if(checkprefix("Transfer-Encoding:", linep)) {
if(k->httpcode/100 == 2) {
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
"Successful" described as: 2xx (Successful). RFC 7231 4.3.6 */
infof(data, "Ignoring Transfer-Encoding in "
"CONNECT %03d response", k->httpcode);
}
else if(Curl_compareheader(linep,
"Transfer-Encoding:", "chunked")) {
infof(data, "CONNECT responded chunked");
s->chunked_encoding = TRUE;
/* init our chunky engine */
Curl_httpchunk_init(data);
}
}
else if(Curl_compareheader(linep, "Proxy-Connection:", "close"))
s->close_connection = TRUE;
else if(2 == sscanf(linep, "HTTP/1.%d %d",
&subversion,
&k->httpcode)) {
/* store the HTTP code from the proxy */
data->info.httpproxycode = k->httpcode;
}
Curl_dyn_reset(&s->rcvbuf);
} /* while there's buffer left and loop is requested */
if(Curl_pgrsUpdate(data))
return CURLE_ABORTED_BY_CALLBACK;
if(error)
return CURLE_RECV_ERROR;
if(data->info.httpproxycode/100 != 2) {
/* Deal with the possibly already received authenticate
headers. 'newurl' is set to a new URL if we must loop. */
result = Curl_http_auth_act(data);
if(result)
return result;
if(conn->bits.close)
/* the connection has been marked for closure, most likely in the
Curl_http_auth_act() function and thus we can kill it at once
below */
s->close_connection = TRUE;
}
if(s->close_connection && data->req.newurl) {
/* Connection closed by server. Don't use it anymore */
Curl_closesocket(data, conn, conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
break;
}
} /* END READING RESPONSE PHASE */
/* If we are supposed to continue and request a new URL, which basically
* means the HTTP authentication is still going on so if the tunnel
* is complete we start over in INIT state */
if(data->req.newurl && (TUNNEL_COMPLETE == s->tunnel_state)) {
connect_init(data, TRUE); /* reinit */
}
} while(data->req.newurl);
if(data->info.httpproxycode/100 != 2) {
if(s->close_connection && data->req.newurl) {
conn->bits.proxy_connect_closed = TRUE;
infof(data, "Connect me again please");
connect_done(data);
}
else {
free(data->req.newurl);
data->req.newurl = NULL;
/* failure, close this connection to avoid re-use */
streamclose(conn, "proxy CONNECT failure");
Curl_closesocket(data, conn, conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
}
/* to back to init state */
s->tunnel_state = TUNNEL_INIT;
if(conn->bits.proxy_connect_closed)
/* this is not an error, just part of the connection negotiation */
return CURLE_OK;
Curl_dyn_free(&s->rcvbuf);
failf(data, "Received HTTP code %d from proxy after CONNECT",
data->req.httpcode);
return CURLE_RECV_ERROR;
}
s->tunnel_state = TUNNEL_COMPLETE;
/* If a proxy-authorization header was used for the proxy, then we should
make sure that it isn't accidentally used for the document request
after we've connected. So let's free and clear it here. */
Curl_safefree(data->state.aptr.proxyuserpwd);
data->state.aptr.proxyuserpwd = NULL;
data->state.authproxy.done = TRUE;
data->state.authproxy.multipass = FALSE;
infof(data, "Proxy replied %d to CONNECT request",
data->info.httpproxycode);
data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the
document request */
Curl_dyn_free(&s->rcvbuf);
return CURLE_OK;
}
#else
/* The Hyper version of CONNECT */
static CURLcode CONNECT(struct Curl_easy *data,
int sockindex,
const char *hostname,
int remote_port)
{
struct connectdata *conn = data->conn;
struct hyptransfer *h = &data->hyp;
curl_socket_t tunnelsocket = conn->sock[sockindex];
struct http_connect_state *s = conn->connect_state;
CURLcode result = CURLE_OUT_OF_MEMORY;
hyper_io *io = NULL;
hyper_request *req = NULL;
hyper_headers *headers = NULL;
hyper_clientconn_options *options = NULL;
hyper_task *handshake = NULL;
hyper_task *task = NULL; /* for the handshake */
hyper_task *sendtask = NULL; /* for the send */
hyper_clientconn *client = NULL;
hyper_error *hypererr = NULL;
char *hostheader = NULL; /* for CONNECT */
char *host = NULL; /* Host: */
if(Curl_connect_complete(conn))
return CURLE_OK; /* CONNECT is already completed */
conn->bits.proxy_connect_closed = FALSE;
do {
switch(s->tunnel_state) {
case TUNNEL_INIT:
/* BEGIN CONNECT PHASE */
io = hyper_io_new();
if(!io) {
failf(data, "Couldn't create hyper IO");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
/* tell Hyper how to read/write network data */
hyper_io_set_userdata(io, data);
hyper_io_set_read(io, Curl_hyper_recv);
hyper_io_set_write(io, Curl_hyper_send);
conn->sockfd = tunnelsocket;
data->state.hconnect = TRUE;
/* create an executor to poll futures */
if(!h->exec) {
h->exec = hyper_executor_new();
if(!h->exec) {
failf(data, "Couldn't create hyper executor");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
}
options = hyper_clientconn_options_new();
if(!options) {
failf(data, "Couldn't create hyper client options");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
hyper_clientconn_options_exec(options, h->exec);
/* "Both the `io` and the `options` are consumed in this function
call" */
handshake = hyper_clientconn_handshake(io, options);
if(!handshake) {
failf(data, "Couldn't create hyper client handshake");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
io = NULL;
options = NULL;
if(HYPERE_OK != hyper_executor_push(h->exec, handshake)) {
failf(data, "Couldn't hyper_executor_push the handshake");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
handshake = NULL; /* ownership passed on */
task = hyper_executor_poll(h->exec);
if(!task) {
failf(data, "Couldn't hyper_executor_poll the handshake");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
client = hyper_task_value(task);
hyper_task_free(task);
req = hyper_request_new();
if(!req) {
failf(data, "Couldn't hyper_request_new");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
if(hyper_request_set_method(req, (uint8_t *)"CONNECT",
strlen("CONNECT"))) {
failf(data, "error setting method");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
infof(data, "Establish HTTP proxy tunnel to %s:%d",
hostname, remote_port);
/* This only happens if we've looped here due to authentication
reasons, and we don't really use the newly cloned URL here
then. Just free() it. */
Curl_safefree(data->req.newurl);
result = CONNECT_host(data, conn, hostname, remote_port,
&hostheader, &host);
if(result)
goto error;
if(hyper_request_set_uri(req, (uint8_t *)hostheader,
strlen(hostheader))) {
failf(data, "error setting path");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
if(data->set.verbose) {
char *se = aprintf("CONNECT %s HTTP/1.1\r\n", hostheader);
if(!se) {
result = CURLE_OUT_OF_MEMORY;
goto error;
}
Curl_debug(data, CURLINFO_HEADER_OUT, se, strlen(se));
free(se);
}
/* Setup the proxy-authorization header, if any */
result = Curl_http_output_auth(data, conn, "CONNECT", HTTPREQ_GET,
hostheader, TRUE);
if(result)
goto error;
Curl_safefree(hostheader);
/* default is 1.1 */
if((conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) &&
(HYPERE_OK != hyper_request_set_version(req,
HYPER_HTTP_VERSION_1_0))) {
failf(data, "error setting HTTP version");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
headers = hyper_request_headers(req);
if(!headers) {
failf(data, "hyper_request_headers");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
if(host) {
result = Curl_hyper_header(data, headers, host);
if(result)
goto error;
Curl_safefree(host);
}
if(data->state.aptr.proxyuserpwd) {
result = Curl_hyper_header(data, headers,
data->state.aptr.proxyuserpwd);
if(result)
goto error;
}
if(!Curl_checkProxyheaders(data, conn, "User-Agent") &&
data->set.str[STRING_USERAGENT]) {
struct dynbuf ua;
Curl_dyn_init(&ua, DYN_HTTP_REQUEST);
result = Curl_dyn_addf(&ua, "User-Agent: %s\r\n",
data->set.str[STRING_USERAGENT]);
if(result)
goto error;
result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&ua));
if(result)
goto error;
Curl_dyn_free(&ua);
}
if(!Curl_checkProxyheaders(data, conn, "Proxy-Connection")) {
result = Curl_hyper_header(data, headers,
"Proxy-Connection: Keep-Alive");
if(result)
goto error;
}
result = Curl_add_custom_headers(data, TRUE, headers);
if(result)
goto error;
sendtask = hyper_clientconn_send(client, req);
if(!sendtask) {
failf(data, "hyper_clientconn_send");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
if(HYPERE_OK != hyper_executor_push(h->exec, sendtask)) {
failf(data, "Couldn't hyper_executor_push the send");
result = CURLE_OUT_OF_MEMORY;
goto error;
}
hyper_clientconn_free(client);
do {
task = hyper_executor_poll(h->exec);
if(task) {
bool error = hyper_task_type(task) == HYPER_TASK_ERROR;
if(error)
hypererr = hyper_task_value(task);
hyper_task_free(task);
if(error) {
/* this could probably use a better error code? */
result = CURLE_OUT_OF_MEMORY;
goto error;
}
}
} while(task);
s->tunnel_state = TUNNEL_CONNECT;
/* FALLTHROUGH */
case TUNNEL_CONNECT: {
int didwhat;
bool done = FALSE;
result = Curl_hyper_stream(data, conn, &didwhat, &done,
CURL_CSELECT_IN | CURL_CSELECT_OUT);
if(result)
goto error;
if(!done)
break;
s->tunnel_state = TUNNEL_COMPLETE;
if(h->exec) {
hyper_executor_free(h->exec);
h->exec = NULL;
}
if(h->read_waker) {
hyper_waker_free(h->read_waker);
h->read_waker = NULL;
}
if(h->write_waker) {
hyper_waker_free(h->write_waker);
h->write_waker = NULL;
}
}
break;
default:
break;
}
/* If we are supposed to continue and request a new URL, which basically
* means the HTTP authentication is still going on so if the tunnel
* is complete we start over in INIT state */
if(data->req.newurl && (TUNNEL_COMPLETE == s->tunnel_state)) {
infof(data, "CONNECT request done, loop to make another");
connect_init(data, TRUE); /* reinit */
}
} while(data->req.newurl);
result = CURLE_OK;
if(s->tunnel_state == TUNNEL_COMPLETE) {
if(data->info.httpproxycode/100 != 2) {
if(conn->bits.close && data->req.newurl) {
conn->bits.proxy_connect_closed = TRUE;
infof(data, "Connect me again please");
connect_done(data);
}
else {
free(data->req.newurl);
data->req.newurl = NULL;
/* failure, close this connection to avoid re-use */
streamclose(conn, "proxy CONNECT failure");
Curl_closesocket(data, conn, conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
}
/* to back to init state */
s->tunnel_state = TUNNEL_INIT;
if(!conn->bits.proxy_connect_closed) {
failf(data, "Received HTTP code %d from proxy after CONNECT",
data->req.httpcode);
result = CURLE_RECV_ERROR;
}
}
}
error:
free(host);
free(hostheader);
if(io)
hyper_io_free(io);
if(options)
hyper_clientconn_options_free(options);
if(handshake)
hyper_task_free(handshake);
if(hypererr) {
uint8_t errbuf[256];
size_t errlen = hyper_error_print(hypererr, errbuf, sizeof(errbuf));
failf(data, "Hyper: %.*s", (int)errlen, errbuf);
hyper_error_free(hypererr);
}
return result;
}
#endif
void Curl_connect_free(struct Curl_easy *data)
{
struct connectdata *conn = data->conn;
struct http_connect_state *s = conn->connect_state;
if(s) {
free(s);
conn->connect_state = NULL;
}
}
/*
* Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This
* function will issue the necessary commands to get a seamless tunnel through
* this proxy. After that, the socket can be used just as a normal socket.
*/
CURLcode Curl_proxyCONNECT(struct Curl_easy *data,
int sockindex,
const char *hostname,
int remote_port)
{
CURLcode result;
struct connectdata *conn = data->conn;
if(!conn->connect_state) {
result = connect_init(data, FALSE);
if(result)
return result;
}
result = CONNECT(data, sockindex, hostname, remote_port);
if(result || Curl_connect_complete(conn))
connect_done(data);
return result;
}
#else
void Curl_connect_free(struct Curl_easy *data)
{
(void)data;
}
#endif /* CURL_DISABLE_PROXY */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/ftplistparser.h | #ifndef HEADER_CURL_FTPLISTPARSER_H
#define HEADER_CURL_FTPLISTPARSER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_FTP
/* WRITEFUNCTION callback for parsing LIST responses */
size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
void *connptr);
struct ftp_parselist_data; /* defined inside ftplibparser.c */
CURLcode Curl_ftp_parselist_geterror(struct ftp_parselist_data *pl_data);
struct ftp_parselist_data *Curl_ftp_parselist_data_alloc(void);
void Curl_ftp_parselist_data_free(struct ftp_parselist_data **pl_data);
#endif /* CURL_DISABLE_FTP */
#endif /* HEADER_CURL_FTPLISTPARSER_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/setup-vms.h | #ifndef HEADER_CURL_SETUP_VMS_H
#define HEADER_CURL_SETUP_VMS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* */
/* JEM, 12/30/12, VMS now generates config.h, so only define wrappers for */
/* getenv(), getpwuid() and provide is_vms_shell() */
/* Also need upper case symbols for system services, and */
/* OpenSSL, and some Kerberos image */
#ifdef __DECC
#pragma message save
#pragma message disable dollarid
#endif
/* Hide the stuff we are overriding */
#define getenv decc_getenv
#ifdef __DECC
# if __INITIAL_POINTER_SIZE != 64
# define getpwuid decc_getpwuid
# endif
#endif
#include <stdlib.h>
char *decc$getenv(const char *__name);
#include <pwd.h>
#include <string.h>
#include <unixlib.h>
#undef getenv
#undef getpwuid
#define getenv vms_getenv
#define getpwuid vms_getpwuid
/* VAX needs these in upper case when compiling exact case */
#define sys$assign SYS$ASSIGN
#define sys$dassgn SYS$DASSGN
#define sys$qiow SYS$QIOW
#ifdef __DECC
# if __INITIAL_POINTER_SIZE
# pragma __pointer_size __save
# endif
#endif
#if __USE_LONG_GID_T
# define decc_getpwuid DECC$__LONG_GID_GETPWUID
#else
# if __INITIAL_POINTER_SIZE
# define decc_getpwuid decc$__32_getpwuid
# else
# define decc_getpwuid decc$getpwuid
# endif
#endif
struct passwd *decc_getpwuid(uid_t uid);
#ifdef __DECC
# if __INITIAL_POINTER_SIZE == 32
/* Translate the path, but only if the path is a VMS file specification */
/* The translation is usually only needed for older versions of VMS */
static char *vms_translate_path(const char *path)
{
char *unix_path;
char *test_str;
/* See if the result is in VMS format, if not, we are done */
/* Assume that this is a PATH, not just some data */
test_str = strpbrk(path, ":[<^");
if(!test_str) {
return (char *)path;
}
unix_path = decc$translate_vms(path);
if((int)unix_path <= 0) {
/* We can not translate it, so return the original string */
return (char *)path;
}
}
# else
/* VMS translate path is actually not needed on the current 64 bit */
/* VMS platforms, so instead of figuring out the pointer settings */
/* Change it to a noop */
# define vms_translate_path(__path) __path
# endif
#endif
#ifdef __DECC
# if __INITIAL_POINTER_SIZE
# pragma __pointer_size __restore
# endif
#endif
static char *vms_getenv(const char *envvar)
{
char *result;
char *vms_path;
/* first use the DECC getenv() function */
result = decc$getenv(envvar);
if(!result) {
return result;
}
vms_path = result;
result = vms_translate_path(vms_path);
/* note that if you backport this to use VAX C RTL, that the VAX C RTL */
/* may do a malloc(2048) for each call to getenv(), so you will need */
/* to add a free(vms_path) */
/* Do not do a free() for DEC C RTL builds, which should be used for */
/* VMS 5.5-2 and later, even if using GCC */
return result;
}
static struct passwd vms_passwd_cache;
static struct passwd *vms_getpwuid(uid_t uid)
{
struct passwd *my_passwd;
/* Hack needed to support 64 bit builds, decc_getpwnam is 32 bit only */
#ifdef __DECC
# if __INITIAL_POINTER_SIZE
__char_ptr32 unix_path;
# else
char *unix_path;
# endif
#else
char *unix_path;
#endif
my_passwd = decc_getpwuid(uid);
if(!my_passwd) {
return my_passwd;
}
unix_path = vms_translate_path(my_passwd->pw_dir);
if((long)unix_path <= 0) {
/* We can not translate it, so return the original string */
return my_passwd;
}
/* If no changes needed just return it */
if(unix_path == my_passwd->pw_dir) {
return my_passwd;
}
/* Need to copy the structure returned */
/* Since curl is only using pw_dir, no need to fix up */
/* the pw_shell when running under Bash */
vms_passwd_cache.pw_name = my_passwd->pw_name;
vms_passwd_cache.pw_uid = my_passwd->pw_uid;
vms_passwd_cache.pw_gid = my_passwd->pw_uid;
vms_passwd_cache.pw_dir = unix_path;
vms_passwd_cache.pw_shell = my_passwd->pw_shell;
return &vms_passwd_cache;
}
#ifdef __DECC
#pragma message restore
#endif
/* Bug - VMS OpenSSL and Kerberos universal symbols are in uppercase only */
/* VMS libraries should have universal symbols in exact and uppercase */
#define ASN1_INTEGER_get ASN1_INTEGER_GET
#define ASN1_STRING_data ASN1_STRING_DATA
#define ASN1_STRING_length ASN1_STRING_LENGTH
#define ASN1_STRING_print ASN1_STRING_PRINT
#define ASN1_STRING_to_UTF8 ASN1_STRING_TO_UTF8
#define ASN1_STRING_type ASN1_STRING_TYPE
#define BIO_ctrl BIO_CTRL
#define BIO_free BIO_FREE
#define BIO_new BIO_NEW
#define BIO_s_mem BIO_S_MEM
#define BN_bn2bin BN_BN2BIN
#define BN_num_bits BN_NUM_BITS
#define CRYPTO_cleanup_all_ex_data CRYPTO_CLEANUP_ALL_EX_DATA
#define CRYPTO_free CRYPTO_FREE
#define CRYPTO_malloc CRYPTO_MALLOC
#define CONF_modules_load_file CONF_MODULES_LOAD_FILE
#ifdef __VAX
# ifdef VMS_OLD_SSL
/* Ancient OpenSSL on VAX/VMS missing this constant */
# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
# undef CONF_modules_load_file
static int CONF_modules_load_file(const char *filename,
const char *appname,
unsigned long flags) {
return 1;
}
# endif
#endif
#define DES_ecb_encrypt DES_ECB_ENCRYPT
#define DES_set_key DES_SET_KEY
#define DES_set_odd_parity DES_SET_ODD_PARITY
#define ENGINE_ctrl ENGINE_CTRL
#define ENGINE_ctrl_cmd ENGINE_CTRL_CMD
#define ENGINE_finish ENGINE_FINISH
#define ENGINE_free ENGINE_FREE
#define ENGINE_get_first ENGINE_GET_FIRST
#define ENGINE_get_id ENGINE_GET_ID
#define ENGINE_get_next ENGINE_GET_NEXT
#define ENGINE_init ENGINE_INIT
#define ENGINE_load_builtin_engines ENGINE_LOAD_BUILTIN_ENGINES
#define ENGINE_load_private_key ENGINE_LOAD_PRIVATE_KEY
#define ENGINE_set_default ENGINE_SET_DEFAULT
#define ERR_clear_error ERR_CLEAR_ERROR
#define ERR_error_string ERR_ERROR_STRING
#define ERR_error_string_n ERR_ERROR_STRING_N
#define ERR_free_strings ERR_FREE_STRINGS
#define ERR_get_error ERR_GET_ERROR
#define ERR_peek_error ERR_PEEK_ERROR
#define ERR_remove_state ERR_REMOVE_STATE
#define EVP_PKEY_copy_parameters EVP_PKEY_COPY_PARAMETERS
#define EVP_PKEY_free EVP_PKEY_FREE
#define EVP_cleanup EVP_CLEANUP
#define GENERAL_NAMES_free GENERAL_NAMES_FREE
#define i2d_X509_PUBKEY I2D_X509_PUBKEY
#define MD4_Final MD4_FINAL
#define MD4_Init MD4_INIT
#define MD4_Update MD4_UPDATE
#define MD5_Final MD5_FINAL
#define MD5_Init MD5_INIT
#define MD5_Update MD5_UPDATE
#define OPENSSL_add_all_algo_noconf OPENSSL_ADD_ALL_ALGO_NOCONF
#ifndef __VAX
#define OPENSSL_load_builtin_modules OPENSSL_LOAD_BUILTIN_MODULES
#endif
#define PEM_read_X509 PEM_READ_X509
#define PEM_write_bio_X509 PEM_WRITE_BIO_X509
#define PKCS12_PBE_add PKCS12_PBE_ADD
#define PKCS12_free PKCS12_FREE
#define PKCS12_parse PKCS12_PARSE
#define RAND_add RAND_ADD
#define RAND_bytes RAND_BYTES
#define RAND_egd RAND_EGD
#define RAND_file_name RAND_FILE_NAME
#define RAND_load_file RAND_LOAD_FILE
#define RAND_status RAND_STATUS
#define SSL_CIPHER_get_name SSL_CIPHER_GET_NAME
#define SSL_CTX_add_client_CA SSL_CTX_ADD_CLIENT_CA
#define SSL_CTX_callback_ctrl SSL_CTX_CALLBACK_CTRL
#define SSL_CTX_check_private_key SSL_CTX_CHECK_PRIVATE_KEY
#define SSL_CTX_ctrl SSL_CTX_CTRL
#define SSL_CTX_free SSL_CTX_FREE
#define SSL_CTX_get_cert_store SSL_CTX_GET_CERT_STORE
#define SSL_CTX_load_verify_locations SSL_CTX_LOAD_VERIFY_LOCATIONS
#define SSL_CTX_new SSL_CTX_NEW
#define SSL_CTX_set_cipher_list SSL_CTX_SET_CIPHER_LIST
#define SSL_CTX_set_def_passwd_cb_ud SSL_CTX_SET_DEF_PASSWD_CB_UD
#define SSL_CTX_set_default_passwd_cb SSL_CTX_SET_DEFAULT_PASSWD_CB
#define SSL_CTX_set_msg_callback SSL_CTX_SET_MSG_CALLBACK
#define SSL_CTX_set_verify SSL_CTX_SET_VERIFY
#define SSL_CTX_use_PrivateKey SSL_CTX_USE_PRIVATEKEY
#define SSL_CTX_use_PrivateKey_file SSL_CTX_USE_PRIVATEKEY_FILE
#define SSL_CTX_use_cert_chain_file SSL_CTX_USE_CERT_CHAIN_FILE
#define SSL_CTX_use_certificate SSL_CTX_USE_CERTIFICATE
#define SSL_CTX_use_certificate_file SSL_CTX_USE_CERTIFICATE_FILE
#define SSL_SESSION_free SSL_SESSION_FREE
#define SSL_connect SSL_CONNECT
#define SSL_free SSL_FREE
#define SSL_get1_session SSL_GET1_SESSION
#define SSL_get_certificate SSL_GET_CERTIFICATE
#define SSL_get_current_cipher SSL_GET_CURRENT_CIPHER
#define SSL_get_error SSL_GET_ERROR
#define SSL_get_peer_cert_chain SSL_GET_PEER_CERT_CHAIN
#define SSL_get_peer_certificate SSL_GET_PEER_CERTIFICATE
#define SSL_get_privatekey SSL_GET_PRIVATEKEY
#define SSL_get_session SSL_GET_SESSION
#define SSL_get_shutdown SSL_GET_SHUTDOWN
#define SSL_get_verify_result SSL_GET_VERIFY_RESULT
#define SSL_library_init SSL_LIBRARY_INIT
#define SSL_load_error_strings SSL_LOAD_ERROR_STRINGS
#define SSL_new SSL_NEW
#define SSL_peek SSL_PEEK
#define SSL_pending SSL_PENDING
#define SSL_read SSL_READ
#define SSL_set_connect_state SSL_SET_CONNECT_STATE
#define SSL_set_fd SSL_SET_FD
#define SSL_set_session SSL_SET_SESSION
#define SSL_shutdown SSL_SHUTDOWN
#define SSL_version SSL_VERSION
#define SSL_write SSL_WRITE
#define SSLeay SSLEAY
#define SSLv23_client_method SSLV23_CLIENT_METHOD
#define SSLv3_client_method SSLV3_CLIENT_METHOD
#define TLSv1_client_method TLSV1_CLIENT_METHOD
#define UI_create_method UI_CREATE_METHOD
#define UI_destroy_method UI_DESTROY_METHOD
#define UI_get0_user_data UI_GET0_USER_DATA
#define UI_get_input_flags UI_GET_INPUT_FLAGS
#define UI_get_string_type UI_GET_STRING_TYPE
#define UI_create_method UI_CREATE_METHOD
#define UI_destroy_method UI_DESTROY_METHOD
#define UI_method_get_closer UI_METHOD_GET_CLOSER
#define UI_method_get_opener UI_METHOD_GET_OPENER
#define UI_method_get_reader UI_METHOD_GET_READER
#define UI_method_get_writer UI_METHOD_GET_WRITER
#define UI_method_set_closer UI_METHOD_SET_CLOSER
#define UI_method_set_opener UI_METHOD_SET_OPENER
#define UI_method_set_reader UI_METHOD_SET_READER
#define UI_method_set_writer UI_METHOD_SET_WRITER
#define UI_OpenSSL UI_OPENSSL
#define UI_set_result UI_SET_RESULT
#define X509V3_EXT_print X509V3_EXT_PRINT
#define X509_EXTENSION_get_critical X509_EXTENSION_GET_CRITICAL
#define X509_EXTENSION_get_data X509_EXTENSION_GET_DATA
#define X509_EXTENSION_get_object X509_EXTENSION_GET_OBJECT
#define X509_LOOKUP_file X509_LOOKUP_FILE
#define X509_NAME_ENTRY_get_data X509_NAME_ENTRY_GET_DATA
#define X509_NAME_get_entry X509_NAME_GET_ENTRY
#define X509_NAME_get_index_by_NID X509_NAME_GET_INDEX_BY_NID
#define X509_NAME_print_ex X509_NAME_PRINT_EX
#define X509_STORE_CTX_get_current_cert X509_STORE_CTX_GET_CURRENT_CERT
#define X509_STORE_add_lookup X509_STORE_ADD_LOOKUP
#define X509_STORE_set_flags X509_STORE_SET_FLAGS
#define X509_check_issued X509_CHECK_ISSUED
#define X509_free X509_FREE
#define X509_get_ext_d2i X509_GET_EXT_D2I
#define X509_get_issuer_name X509_GET_ISSUER_NAME
#define X509_get_pubkey X509_GET_PUBKEY
#define X509_get_serialNumber X509_GET_SERIALNUMBER
#define X509_get_subject_name X509_GET_SUBJECT_NAME
#define X509_load_crl_file X509_LOAD_CRL_FILE
#define X509_verify_cert_error_string X509_VERIFY_CERT_ERROR_STRING
#define d2i_PKCS12_fp D2I_PKCS12_FP
#define i2t_ASN1_OBJECT I2T_ASN1_OBJECT
#define sk_num SK_NUM
#define sk_pop SK_POP
#define sk_pop_free SK_POP_FREE
#define sk_value SK_VALUE
#ifdef __VAX
#define OPENSSL_NO_SHA256
#endif
#define SHA256_Final SHA256_FINAL
#define SHA256_Init SHA256_INIT
#define SHA256_Update SHA256_UPDATE
#define USE_UPPERCASE_GSSAPI 1
#define gss_seal GSS_SEAL
#define gss_unseal GSS_UNSEAL
#define USE_UPPERCASE_KRBAPI 1
/* AI_NUMERICHOST needed for IP V6 support in Curl */
#ifdef HAVE_NETDB_H
#include <netdb.h>
#ifndef AI_NUMERICHOST
#ifdef ENABLE_IPV6
#undef ENABLE_IPV6
#endif
#endif
#endif
/* VAX symbols are always in uppercase */
#ifdef __VAX
#define inflate INFLATE
#define inflateEnd INFLATEEND
#define inflateInit2_ INFLATEINIT2_
#define inflateInit_ INFLATEINIT_
#define zlibVersion ZLIBVERSION
#endif
/* Older VAX OpenSSL port defines these as Macros */
/* Need to include the headers first and then redefine */
/* that way a newer port will also work if some one has one */
#ifdef __VAX
# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
# define des_set_odd_parity DES_SET_ODD_PARITY
# define des_set_key DES_SET_KEY
# define des_ecb_encrypt DES_ECB_ENCRYPT
# endif
# include <openssl/evp.h>
# ifndef OpenSSL_add_all_algorithms
# define OpenSSL_add_all_algorithms OPENSSL_ADD_ALL_ALGORITHMS
void OPENSSL_ADD_ALL_ALGORITHMS(void);
# endif
/* Curl defines these to lower case and VAX needs them in upper case */
/* So we need static routines */
# if (OPENSSL_VERSION_NUMBER < 0x00907001L)
# undef des_set_odd_parity
# undef DES_set_odd_parity
# undef des_set_key
# undef DES_set_key
# undef des_ecb_encrypt
# undef DES_ecb_encrypt
static void des_set_odd_parity(des_cblock *key) {
DES_SET_ODD_PARITY(key);
}
static int des_set_key(const_des_cblock *key,
des_key_schedule schedule) {
return DES_SET_KEY(key, schedule);
}
static void des_ecb_encrypt(const_des_cblock *input,
des_cblock *output,
des_key_schedule ks, int enc) {
DES_ECB_ENCRYPT(input, output, ks, enc);
}
#endif
/* Need this to stop a macro redefinition error */
#if OPENSSL_VERSION_NUMBER < 0x00907000L
# ifdef X509_STORE_set_flags
# undef X509_STORE_set_flags
# define X509_STORE_set_flags(x,y) Curl_nop_stmt
# endif
#endif
#endif
#endif /* HEADER_CURL_SETUP_VMS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-mac.h | #ifndef HEADER_CURL_CONFIG_MAC_H
#define HEADER_CURL_CONFIG_MAC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* =================================================================== */
/* Hand crafted config file for Mac OS 9 */
/* =================================================================== */
/* On Mac OS X you must run configure to generate curl_config.h file */
/* =================================================================== */
#define OS "mac"
/* Define if you want the built-in manual */
#define USE_MANUAL 1
#define HAVE_ERRNO_H 1
#define HAVE_NETINET_IN_H 1
#define HAVE_SYS_SOCKET_H 1
#define HAVE_SYS_SELECT_H 1
#define HAVE_NETDB_H 1
#define HAVE_ARPA_INET_H 1
#define HAVE_UNISTD_H 1
#define HAVE_NET_IF_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_GETTIMEOFDAY 1
#define HAVE_FCNTL_H 1
#define HAVE_SYS_STAT_H 1
#define HAVE_ALLOCA_H 1
#define HAVE_STDLIB_H 1
#define HAVE_TIME_H 1
#define HAVE_UTIME_H 1
#define HAVE_SYS_TIME_H 1
#define HAVE_SYS_UTIME_H 1
#define TIME_WITH_SYS_TIME 1
#define HAVE_ALARM 1
#define HAVE_FTRUNCATE 1
#define HAVE_UTIME 1
#define HAVE_SETVBUF 1
#define HAVE_STRFTIME 1
#define HAVE_INET_ADDR 1
#define HAVE_MEMCPY 1
#define HAVE_SELECT 1
#define HAVE_SOCKET 1
#define HAVE_STRUCT_TIMEVAL 1
#define HAVE_SIGACTION 1
#define HAVE_SIGNAL_H 1
#ifdef MACOS_SSL_SUPPORT
# define USE_OPENSSL 1
#endif
#define CURL_DISABLE_LDAP 1
#define HAVE_RAND_STATUS 1
#define HAVE_RAND_EGD 1
#define HAVE_IOCTL 1
#define HAVE_IOCTL_FIONBIO 1
#define SIZEOF_INT 4
#define SIZEOF_SHORT 2
#define SIZEOF_SIZE_T 4
#define HAVE_RECV 1
#define RECV_TYPE_ARG1 int
#define RECV_TYPE_ARG2 void *
#define RECV_TYPE_ARG3 size_t
#define RECV_TYPE_ARG4 int
#define RECV_TYPE_RETV ssize_t
#define HAVE_RECVFROM 1
#define RECVFROM_TYPE_ARG1 int
#define RECVFROM_TYPE_ARG2 void
#define RECVFROM_TYPE_ARG3 size_t
#define RECVFROM_TYPE_ARG4 int
#define RECVFROM_TYPE_ARG5 struct sockaddr
#define RECVFROM_TYPE_ARG6 int
#define RECVFROM_TYPE_RETV ssize_t
#define RECVFROM_TYPE_ARG2_IS_VOID 1
#define HAVE_SEND 1
#define SEND_TYPE_ARG1 int
#define SEND_QUAL_ARG2 const
#define SEND_TYPE_ARG2 void *
#define SEND_TYPE_ARG3 size_T
#define SEND_TYPE_ARG4 int
#define SEND_TYPE_RETV ssize_t
#define HAVE_EXTRA_STRICMP_H 1
#define HAVE_EXTRA_STRDUP_H 1
#endif /* HEADER_CURL_CONFIG_MAC_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_get_line.h | #ifndef HEADER_CURL_GET_LINE_H
#define HEADER_CURL_GET_LINE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* get_line() makes sure to only return complete whole lines that fit in 'len'
* bytes and end with a newline. */
char *Curl_get_line(char *buf, int len, FILE *input);
#endif /* HEADER_CURL_GET_LINE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-os400.h | #ifndef HEADER_CURL_CONFIG_OS400_H
#define HEADER_CURL_CONFIG_OS400_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* Hand crafted config file for OS/400 */
/* ================================================================ */
#pragma enum(int)
#undef PACKAGE
/* Version number of this archive. */
#undef VERSION
/* Define if you have the getpass function. */
#undef HAVE_GETPASS
/* Define cpu-machine-OS */
#define OS "OS/400"
/* 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 have the Kerberos4 libraries (including -ldes) */
#undef HAVE_KRB4
/* Define if you want to enable IPv6 support */
#define ENABLE_IPV6
/* Define if struct sockaddr_in6 has the sin6_scope_id member */
#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/* Define this to 'int' if ssize_t is not an available typedefed type */
#undef ssize_t
/* Define this as a suitable file to read random data from */
#undef RANDOM_FILE
/* Define this to your Entropy Gathering Daemon socket pathname */
#undef EGD_SOCKET
/* Define to 1 if you have the alarm function. */
#define HAVE_ALARM 1
/* Define if you have the <alloca.h> header file. */
#undef HAVE_ALLOCA_H
/* Define if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H
/* Define if you have the `closesocket' function. */
#undef HAVE_CLOSESOCKET
/* Define if you have the <errno.h> header file. */
#define HAVE_ERRNO_H
/* Define if you have the <fcntl.h> 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 <getopt.h> header file. */
#undef HAVE_GETOPT_H
/* 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 if you have the `getservbyname' function. */
#define HAVE_GETSERVBYNAME
/* 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 `inet_addr' function. */
#define HAVE_INET_ADDR
/* Define if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H
/* Define if you have the <io.h> header file. */
#undef HAVE_IO_H
/* Define if you have the `krb_get_our_ip_for_realm' function. */
#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
/* Define if you have the <krb.h> header file. */
#undef HAVE_KRB_H
/* Define if you have the `nsl' library (-lnsl). */
#undef HAVE_LIBNSL
/* Define if you have the `resolv' library (-lresolv). */
#undef HAVE_LIBRESOLV
/* Define if you have the `resolve' library (-lresolve). */
#undef HAVE_LIBRESOLVE
/* Define if you have the `socket' library (-lsocket). */
#undef HAVE_LIBSOCKET
/* Define if you have GSS API. */
#define HAVE_GSSAPI
/* Define if you have the GNU gssapi libraries */
#undef HAVE_GSSGNU
/* Define if you have the Heimdal gssapi libraries */
#define HAVE_GSSHEIMDAL
/* Define if you have the MIT gssapi libraries */
#undef HAVE_GSSMIT
/* Define if you have the `ucb' library (-lucb). */
#undef HAVE_LIBUCB
/* Define if you have the `localtime_r' function. */
#define HAVE_LOCALTIME_R
/* Define if you have the <malloc.h> header file. */
#define HAVE_MALLOC_H
/* Define if you need the malloc.h header file even with stdlib.h */
/* #define NEED_MALLOC_H 1 */
/* Define if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define if you have the <netdb.h> header file. */
#define HAVE_NETDB_H
/* Define if you have the <netinet/if_ether.h> header file. */
#undef HAVE_NETINET_IF_ETHER_H
/* Define if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H
/* Define if you have the <net/if.h> header file. */
#define HAVE_NET_IF_H
/* Define if you have the <openssl/crypto.h> header file. */
#undef HAVE_OPENSSL_CRYPTO_H
/* Define if you have the <openssl/err.h> header file. */
#undef HAVE_OPENSSL_ERR_H
/* Define if you have the <openssl/pem.h> header file. */
#undef HAVE_OPENSSL_PEM_H
/* Define if you have the <openssl/rsa.h> header file. */
#undef HAVE_OPENSSL_RSA_H
/* Define if you have the <openssl/ssl.h> header file. */
#undef HAVE_OPENSSL_SSL_H
/* Define if you have the <openssl/x509.h> header file. */
#undef HAVE_OPENSSL_X509_H
/* Define if you have the <pem.h> header file. */
#undef HAVE_PEM_H
/* Define if you have the <pwd.h> header file. */
#define HAVE_PWD_H
/* Define if you have the `RAND_egd' function. */
#undef HAVE_RAND_EGD
/* Define if you have the `RAND_screen' function. */
#undef HAVE_RAND_SCREEN
/* Define if you have the `RAND_status' function. */
#undef HAVE_RAND_STATUS
/* Define if you have the `select' function. */
#define HAVE_SELECT
/* Define if you have the `setvbuf' function. */
#define HAVE_SETVBUF
/* 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 <signal.h> header file. */
#define HAVE_SIGNAL_H
/* Define if you have the `socket' function. */
#define HAVE_SOCKET
/* Define if you have the <ssl.h> header file. */
#undef HAVE_SSL_H
/* Define if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H
/* 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 `strftime' function. */
#define HAVE_STRFTIME
/* Define if you have the <strings.h> header file. */
#define HAVE_STRINGS_H
/* Define if you have the <string.h> header file. */
#define HAVE_STRING_H
/* Define if you have the <stropts.h> header file. */
#undef HAVE_STROPTS_H
/* Define if you have the `strstr' function. */
#define HAVE_STRSTR
/* 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 <sys/param.h> header file. */
#define HAVE_SYS_PARAM_H
/* Define if you have the <sys/select.h> header file. */
#undef HAVE_SYS_SELECT_H
/* Define if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H
/* Define if you have the <sys/sockio.h> header file. */
#undef HAVE_SYS_SOCKIO_H
/* Define if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H
/* Define if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H
/* Define if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H
/* Define if you have the <sys/un.h> header file. */
#define HAVE_SYS_UN_H
/* Define if you have the <sys/ioctl.h> header file. */
#define HAVE_SYS_IOCTL_H
/* Define if you have the <termios.h> header file. */
#undef HAVE_TERMIOS_H
/* Define if you have the <termio.h> header file. */
#undef HAVE_TERMIO_H
/* Define if you have the <time.h> header file. */
#define HAVE_TIME_H
/* Define if you have the `uname' function. */
#undef HAVE_UNAME
/* Define if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H
/* Define if you have the <x509.h> header file. */
#undef HAVE_X509_H
/* Name of package */
#undef PACKAGE
/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT 4
/* The size of a `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE 8
/* 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 `short', as computed by sizeof. */
#define SIZEOF_SHORT 2
/* 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
/* Whether long long constants must be suffixed by LL. */
#define HAVE_LL
/* 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 if you can safely include both <sys/time.h> and <time.h>. */
#define TIME_WITH_SYS_TIME
/* Define to enable HTTP3 support (experimental, requires NGTCP2 or QUICHE) */
#undef ENABLE_QUIC
/* 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 <sys/types.h> does not define. */
#undef size_t
/* Define if you have the ioctl function. */
#define HAVE_IOCTL
/* 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 recvfrom function. */
#define HAVE_RECVFROM
/* Define to the type of arg 1 for recvfrom. */
#define RECVFROM_TYPE_ARG1 int
/* Define to the type pointed by arg 2 for recvfrom. */
#define RECVFROM_TYPE_ARG2 char
/* Define to the type of arg 3 for recvfrom. */
#define RECVFROM_TYPE_ARG3 int
/* Define to the type of arg 4 for recvfrom. */
#define RECVFROM_TYPE_ARG4 int
/* Define to the type pointed by arg 5 for recvfrom. */
#define RECVFROM_TYPE_ARG5 struct sockaddr
/* Define to the type pointed by arg 6 for recvfrom. */
#define RECVFROM_TYPE_ARG6 int
/* Define to the function return type for recvfrom. */
#define RECVFROM_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 GSKit package. */
#define USE_GSKIT
/* 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 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/gopher.h | #ifndef HEADER_CURL_GOPHER_H
#define HEADER_CURL_GOPHER_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#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 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_sasl.h | #ifndef HEADER_CURL_SASL_H
#define HEADER_CURL_SASL_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2012 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <curl/curl.h>
#include "bufref.h"
struct Curl_easy;
struct connectdata;
/* Authentication mechanism flags */
#define SASL_MECH_LOGIN (1 << 0)
#define SASL_MECH_PLAIN (1 << 1)
#define SASL_MECH_CRAM_MD5 (1 << 2)
#define SASL_MECH_DIGEST_MD5 (1 << 3)
#define SASL_MECH_GSSAPI (1 << 4)
#define SASL_MECH_EXTERNAL (1 << 5)
#define SASL_MECH_NTLM (1 << 6)
#define SASL_MECH_XOAUTH2 (1 << 7)
#define SASL_MECH_OAUTHBEARER (1 << 8)
#define SASL_MECH_SCRAM_SHA_1 (1 << 9)
#define SASL_MECH_SCRAM_SHA_256 (1 << 10)
/* Authentication mechanism values */
#define SASL_AUTH_NONE 0
#define SASL_AUTH_ANY 0xffff
#define SASL_AUTH_DEFAULT (SASL_AUTH_ANY & ~SASL_MECH_EXTERNAL)
/* Authentication mechanism strings */
#define SASL_MECH_STRING_LOGIN "LOGIN"
#define SASL_MECH_STRING_PLAIN "PLAIN"
#define SASL_MECH_STRING_CRAM_MD5 "CRAM-MD5"
#define SASL_MECH_STRING_DIGEST_MD5 "DIGEST-MD5"
#define SASL_MECH_STRING_GSSAPI "GSSAPI"
#define SASL_MECH_STRING_EXTERNAL "EXTERNAL"
#define SASL_MECH_STRING_NTLM "NTLM"
#define SASL_MECH_STRING_XOAUTH2 "XOAUTH2"
#define SASL_MECH_STRING_OAUTHBEARER "OAUTHBEARER"
#define SASL_MECH_STRING_SCRAM_SHA_1 "SCRAM-SHA-1"
#define SASL_MECH_STRING_SCRAM_SHA_256 "SCRAM-SHA-256"
/* SASL flags */
#define SASL_FLAG_BASE64 0x0001 /* Messages are base64-encoded */
/* SASL machine states */
typedef enum {
SASL_STOP,
SASL_PLAIN,
SASL_LOGIN,
SASL_LOGIN_PASSWD,
SASL_EXTERNAL,
SASL_CRAMMD5,
SASL_DIGESTMD5,
SASL_DIGESTMD5_RESP,
SASL_NTLM,
SASL_NTLM_TYPE2MSG,
SASL_GSSAPI,
SASL_GSSAPI_TOKEN,
SASL_GSSAPI_NO_DATA,
SASL_OAUTH2,
SASL_OAUTH2_RESP,
SASL_GSASL,
SASL_CANCEL,
SASL_FINAL
} saslstate;
/* Progress indicator */
typedef enum {
SASL_IDLE,
SASL_INPROGRESS,
SASL_DONE
} saslprogress;
/* Protocol dependent SASL parameters */
struct SASLproto {
const char *service; /* The service name */
CURLcode (*sendauth)(struct Curl_easy *data, const char *mech,
const struct bufref *ir);
/* Send authentication command */
CURLcode (*contauth)(struct Curl_easy *data, const char *mech,
const struct bufref *contauth);
/* Send authentication continuation */
CURLcode (*cancelauth)(struct Curl_easy *data, const char *mech);
/* Cancel authentication. */
CURLcode (*getmessage)(struct Curl_easy *data, struct bufref *out);
/* Get SASL response message */
size_t maxirlen; /* Maximum initial response + mechanism length,
or zero if no max. This is normally the max
command length - other characters count.
This has to be zero for non-base64 protocols. */
int contcode; /* Code to receive when continuation is expected */
int finalcode; /* Code to receive upon authentication success */
unsigned short defmechs; /* Mechanisms enabled by default */
unsigned short flags; /* Configuration flags. */
};
/* Per-connection parameters */
struct SASL {
const struct SASLproto *params; /* Protocol dependent parameters */
saslstate state; /* Current machine state */
const char *curmech; /* Current mechanism id. */
unsigned short authmechs; /* Accepted authentication mechanisms */
unsigned short prefmech; /* Preferred authentication mechanism */
unsigned short authused; /* Auth mechanism used for the connection */
bool resetprefs; /* For URL auth option parsing. */
bool mutual_auth; /* Mutual authentication enabled (GSSAPI only) */
bool force_ir; /* Protocol always supports initial response */
};
/* This is used to test whether the line starts with the given mechanism */
#define sasl_mech_equal(line, wordlen, mech) \
(wordlen == (sizeof(mech) - 1) / sizeof(char) && \
!memcmp(line, mech, wordlen))
/* This is used to cleanup any libraries or curl modules used by the sasl
functions */
void Curl_sasl_cleanup(struct connectdata *conn, unsigned short authused);
/* Convert a mechanism name to a token */
unsigned short Curl_sasl_decode_mech(const char *ptr,
size_t maxlen, size_t *len);
/* Parse the URL login options */
CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl,
const char *value, size_t len);
/* Initializes an SASL structure */
void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data,
const struct SASLproto *params);
/* Check if we have enough auth data and capabilities to authenticate */
bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn);
/* Calculate the required login details for SASL authentication */
CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data,
bool force_ir, saslprogress *progress);
/* Continue an SASL authentication */
CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data,
int code, saslprogress *progress);
#endif /* HEADER_CURL_SASL_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_setup.h | #ifndef HEADER_CURL_SETUP_H
#define HEADER_CURL_SETUP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES)
#define CURL_NO_OLDIES
#endif
/*
* Disable Visual Studio warnings:
* 4127 "conditional expression is constant"
*/
#ifdef _MSC_VER
#pragma warning(disable:4127)
#endif
/*
* Define WIN32 when build target is Win32 API
*/
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
#define WIN32
#endif
#ifdef WIN32
/*
* Don't include unneeded stuff in Windows headers to avoid compiler
* warnings and macro clashes.
* Make sure to define this macro before including any Windows headers.
*/
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef NOGDI
# define NOGDI
# endif
/* Detect Windows App environment which has a restricted access
* to the Win32 APIs. */
# if (defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602)) || \
defined(WINAPI_FAMILY)
# include <winapifamily.h>
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
# define CURL_WINDOWS_APP
# endif
# endif
#endif
/*
* Include configuration script results or hand-crafted
* configuration file for platforms which lack config tool.
*/
#ifdef HAVE_CONFIG_H
#include "curl_config.h"
#else /* HAVE_CONFIG_H */
#ifdef _WIN32_WCE
# include "config-win32ce.h"
#else
# ifdef WIN32
# include "config-win32.h"
# endif
#endif
#if defined(macintosh) && defined(__MRC__)
# include "config-mac.h"
#endif
#ifdef __riscos__
# include "config-riscos.h"
#endif
#ifdef __AMIGA__
# include "config-amigaos.h"
#endif
#ifdef __OS400__
# include "config-os400.h"
#endif
#ifdef TPF
# include "config-tpf.h"
#endif
#ifdef __VXWORKS__
# include "config-vxworks.h"
#endif
#ifdef __PLAN9__
# include "config-plan9.h"
#endif
#endif /* HAVE_CONFIG_H */
/* ================================================================ */
/* Definition of preprocessor macros/symbols which modify compiler */
/* behavior or generated code characteristics must be done here, */
/* as appropriate, before any system header file is included. It is */
/* also possible to have them defined in the config file included */
/* before this point. As a result of all this we frown inclusion of */
/* system header files in our config files, avoid this at any cost. */
/* ================================================================ */
/*
* AIX 4.3 and newer needs _THREAD_SAFE defined to build
* proper reentrant code. Others may also need it.
*/
#ifdef NEED_THREAD_SAFE
# ifndef _THREAD_SAFE
# define _THREAD_SAFE
# endif
#endif
/*
* Tru64 needs _REENTRANT set for a few function prototypes and
* things to appear in the system header files. Unixware needs it
* to build proper reentrant code. Others may also need it.
*/
#ifdef NEED_REENTRANT
# ifndef _REENTRANT
# define _REENTRANT
# endif
#endif
/* Solaris needs this to get a POSIX-conformant getpwuid_r */
#if defined(sun) || defined(__sun)
# ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
# endif
#endif
/* ================================================================ */
/* If you need to include a system header file for your platform, */
/* please, do it beyond the point further indicated in this file. */
/* ================================================================ */
#include <curl/curl.h>
/*
* Disable other protocols when http is the only one desired.
*/
#ifdef HTTP_ONLY
# ifndef CURL_DISABLE_DICT
# define CURL_DISABLE_DICT
# endif
# ifndef CURL_DISABLE_FILE
# define CURL_DISABLE_FILE
# endif
# ifndef CURL_DISABLE_FTP
# define CURL_DISABLE_FTP
# endif
# ifndef CURL_DISABLE_GOPHER
# define CURL_DISABLE_GOPHER
# endif
# ifndef CURL_DISABLE_IMAP
# define CURL_DISABLE_IMAP
# endif
# ifndef CURL_DISABLE_LDAP
# define CURL_DISABLE_LDAP
# endif
# ifndef CURL_DISABLE_LDAPS
# define CURL_DISABLE_LDAPS
# endif
# ifndef CURL_DISABLE_MQTT
# define CURL_DISABLE_MQTT
# endif
# ifndef CURL_DISABLE_POP3
# define CURL_DISABLE_POP3
# endif
# ifndef CURL_DISABLE_RTSP
# define CURL_DISABLE_RTSP
# endif
# ifndef CURL_DISABLE_SMB
# define CURL_DISABLE_SMB
# endif
# ifndef CURL_DISABLE_SMTP
# define CURL_DISABLE_SMTP
# endif
# ifndef CURL_DISABLE_TELNET
# define CURL_DISABLE_TELNET
# endif
# ifndef CURL_DISABLE_TFTP
# define CURL_DISABLE_TFTP
# endif
#endif
/*
* When http is disabled rtsp is not supported.
*/
#if defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_RTSP)
# define CURL_DISABLE_RTSP
#endif
/* ================================================================ */
/* No system header file shall be included in this file before this */
/* point. The only allowed ones are those included from curl/system.h */
/* ================================================================ */
/*
* OS/400 setup file includes some system headers.
*/
#ifdef __OS400__
# include "setup-os400.h"
#endif
/*
* VMS setup file includes some system headers.
*/
#ifdef __VMS
# include "setup-vms.h"
#endif
/*
* Windows setup file includes some system headers.
*/
#ifdef HAVE_WINDOWS_H
# include "setup-win32.h"
#endif
/*
* Use getaddrinfo to resolve the IPv4 address literal. If the current network
* interface doesn't support IPv4, but supports IPv6, NAT64, and DNS64,
* performing this task will result in a synthesized IPv6 address.
*/
#if defined(__APPLE__) && !defined(USE_ARES)
#include <TargetConditionals.h>
#define USE_RESOLVE_ON_IPS 1
# if defined(TARGET_OS_OSX) && TARGET_OS_OSX
# define CURL_OSX_CALL_COPYPROXIES 1
# endif
#endif
#ifdef USE_LWIPSOCK
# include <lwip/init.h>
# include <lwip/sockets.h>
# include <lwip/netdb.h>
#endif
#ifdef HAVE_EXTRA_STRICMP_H
# include <extra/stricmp.h>
#endif
#ifdef HAVE_EXTRA_STRDUP_H
# include <extra/strdup.h>
#endif
#ifdef TPF
# include <strings.h> /* for bzero, strcasecmp, and strncasecmp */
# include <string.h> /* for strcpy and strlen */
# include <stdlib.h> /* for rand and srand */
# include <sys/socket.h> /* for select and ioctl*/
# include <netdb.h> /* for in_addr_t definition */
# include <tpf/sysapi.h> /* for tpf_process_signals */
/* change which select is used for libcurl */
# define select(a,b,c,d,e) tpf_select_libcurl(a,b,c,d,e)
#endif
#ifdef __VXWORKS__
# include <sockLib.h> /* for generic BSD socket functions */
# include <ioLib.h> /* for basic I/O interface functions */
#endif
#ifdef __AMIGA__
# include <exec/types.h>
# include <exec/execbase.h>
# include <proto/exec.h>
# include <proto/dos.h>
# include <unistd.h>
# ifdef HAVE_PROTO_BSDSOCKET_H
# include <proto/bsdsocket.h> /* ensure bsdsocket.library use */
# define select(a,b,c,d,e) WaitSelect(a,b,c,d,e,0)
# endif
/*
* In clib2 arpa/inet.h warns that some prototypes may clash
* with bsdsocket.library. This avoids the definition of those.
*/
# define __NO_NET_API
#endif
#include <stdio.h>
#ifdef HAVE_ASSERT_H
#include <assert.h>
#endif
#ifdef __TANDEM /* for nsr-tandem-nsk systems */
#include <floss.h>
#endif
#ifndef STDC_HEADERS /* no standard C headers! */
#include <curl/stdcheaders.h>
#endif
#ifdef __POCC__
# include <sys/types.h>
# include <unistd.h>
# define sys_nerr EILSEQ
#endif
/*
* Salford-C kludge section (mostly borrowed from wxWidgets).
*/
#ifdef __SALFORDC__
#pragma suppress 353 /* Possible nested comments */
#pragma suppress 593 /* Define not used */
#pragma suppress 61 /* enum has no name */
#pragma suppress 106 /* unnamed, unused parameter */
#include <clib.h>
#endif
/*
* Large file (>2Gb) support using WIN32 functions.
*/
#ifdef USE_WIN32_LARGE_FILES
# include <io.h>
# include <sys/types.h>
# include <sys/stat.h>
# undef lseek
# define lseek(fdes,offset,whence) _lseeki64(fdes, offset, whence)
# undef fstat
# define fstat(fdes,stp) _fstati64(fdes, stp)
# undef stat
# define stat(fname,stp) curlx_win32_stat(fname, stp)
# define struct_stat struct _stati64
# define LSEEK_ERROR (__int64)-1
# define open curlx_win32_open
# define fopen(fname,mode) curlx_win32_fopen(fname, mode)
# define access(fname,mode) curlx_win32_access(fname, mode)
int curlx_win32_open(const char *filename, int oflag, ...);
int curlx_win32_stat(const char *path, struct_stat *buffer);
FILE *curlx_win32_fopen(const char *filename, const char *mode);
int curlx_win32_access(const char *path, int mode);
#endif
/*
* Small file (<2Gb) support using WIN32 functions.
*/
#ifdef USE_WIN32_SMALL_FILES
# include <io.h>
# include <sys/types.h>
# include <sys/stat.h>
# ifndef _WIN32_WCE
# undef lseek
# define lseek(fdes,offset,whence) _lseek(fdes, (long)offset, whence)
# define fstat(fdes,stp) _fstat(fdes, stp)
# define stat(fname,stp) curlx_win32_stat(fname, stp)
# define struct_stat struct _stat
# define open curlx_win32_open
# define fopen(fname,mode) curlx_win32_fopen(fname, mode)
# define access(fname,mode) curlx_win32_access(fname, mode)
int curlx_win32_stat(const char *path, struct_stat *buffer);
int curlx_win32_open(const char *filename, int oflag, ...);
FILE *curlx_win32_fopen(const char *filename, const char *mode);
int curlx_win32_access(const char *path, int mode);
# endif
# define LSEEK_ERROR (long)-1
#endif
#ifndef struct_stat
# define struct_stat struct stat
#endif
#ifndef LSEEK_ERROR
# define LSEEK_ERROR (off_t)-1
#endif
#ifndef SIZEOF_TIME_T
/* assume default size of time_t to be 32 bit */
#define SIZEOF_TIME_T 4
#endif
/*
* Default sizeof(off_t) in case it hasn't been defined in config file.
*/
#ifndef SIZEOF_OFF_T
# if defined(__VMS) && !defined(__VAX)
# if defined(_LARGEFILE)
# define SIZEOF_OFF_T 8
# endif
# elif defined(__OS400__) && defined(__ILEC400__)
# if defined(_LARGE_FILES)
# define SIZEOF_OFF_T 8
# endif
# elif defined(__MVS__) && defined(__IBMC__)
# if defined(_LP64) || defined(_LARGE_FILES)
# define SIZEOF_OFF_T 8
# endif
# elif defined(__370__) && defined(__IBMC__)
# if defined(_LP64) || defined(_LARGE_FILES)
# define SIZEOF_OFF_T 8
# endif
# endif
# ifndef SIZEOF_OFF_T
# define SIZEOF_OFF_T 4
# endif
#endif
#if (SIZEOF_CURL_OFF_T == 4)
# define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFF)
#else
/* assume SIZEOF_CURL_OFF_T == 8 */
# define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF)
#endif
#define CURL_OFF_T_MIN (-CURL_OFF_T_MAX - CURL_OFF_T_C(1))
#if (SIZEOF_TIME_T == 4)
# ifdef HAVE_TIME_T_UNSIGNED
# define TIME_T_MAX UINT_MAX
# define TIME_T_MIN 0
# else
# define TIME_T_MAX INT_MAX
# define TIME_T_MIN INT_MIN
# endif
#else
# ifdef HAVE_TIME_T_UNSIGNED
# define TIME_T_MAX 0xFFFFFFFFFFFFFFFF
# define TIME_T_MIN 0
# else
# define TIME_T_MAX 0x7FFFFFFFFFFFFFFF
# define TIME_T_MIN (-TIME_T_MAX - 1)
# endif
#endif
#ifndef SIZE_T_MAX
/* some limits.h headers have this defined, some don't */
#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4)
#define SIZE_T_MAX 18446744073709551615U
#else
#define SIZE_T_MAX 4294967295U
#endif
#endif
#ifndef SSIZE_T_MAX
/* some limits.h headers have this defined, some don't */
#if defined(SIZEOF_SIZE_T) && (SIZEOF_SIZE_T > 4)
#define SSIZE_T_MAX 9223372036854775807
#else
#define SSIZE_T_MAX 2147483647
#endif
#endif
/*
* Arg 2 type for gethostname in case it hasn't been defined in config file.
*/
#ifndef GETHOSTNAME_TYPE_ARG2
# ifdef USE_WINSOCK
# define GETHOSTNAME_TYPE_ARG2 int
# else
# define GETHOSTNAME_TYPE_ARG2 size_t
# endif
#endif
/* Below we define some functions. They should
4. set the SIGALRM signal timeout
5. set dir/file naming defines
*/
#ifdef WIN32
# define DIR_CHAR "\\"
#else /* WIN32 */
# ifdef MSDOS /* Watt-32 */
# include <sys/ioctl.h>
# define select(n,r,w,x,t) select_s(n,r,w,x,t)
# define ioctl(x,y,z) ioctlsocket(x,y,(char *)(z))
# include <tcp.h>
# ifdef word
# undef word
# endif
# ifdef byte
# undef byte
# endif
# endif /* MSDOS */
# ifdef __minix
/* Minix 3 versions up to at least 3.1.3 are missing these prototypes */
extern char *strtok_r(char *s, const char *delim, char **last);
extern struct tm *gmtime_r(const time_t * const timep, struct tm *tmp);
# endif
# define DIR_CHAR "/"
# ifndef fileno /* sunos 4 have this as a macro! */
int fileno(FILE *stream);
# endif
#endif /* WIN32 */
/*
* msvc 6.0 requires PSDK in order to have INET6_ADDRSTRLEN
* defined in ws2tcpip.h as well as to provide IPv6 support.
* Does not apply if lwIP is used.
*/
#if defined(_MSC_VER) && !defined(__POCC__) && !defined(USE_LWIPSOCK)
# if !defined(HAVE_WS2TCPIP_H) || \
((_MSC_VER < 1300) && !defined(INET6_ADDRSTRLEN))
# undef HAVE_GETADDRINFO_THREADSAFE
# undef HAVE_FREEADDRINFO
# undef HAVE_GETADDRINFO
# undef ENABLE_IPV6
# endif
#endif
/* ---------------------------------------------------------------- */
/* resolver specialty compile-time defines */
/* CURLRES_* defines to use in the host*.c sources */
/* ---------------------------------------------------------------- */
/*
* lcc-win32 doesn't have _beginthreadex(), lacks threads support.
*/
#if defined(__LCC__) && defined(WIN32)
# undef USE_THREADS_POSIX
# undef USE_THREADS_WIN32
#endif
/*
* MSVC threads support requires a multi-threaded runtime library.
* _beginthreadex() is not available in single-threaded ones.
*/
#if defined(_MSC_VER) && !defined(__POCC__) && !defined(_MT)
# undef USE_THREADS_POSIX
# undef USE_THREADS_WIN32
#endif
/*
* Mutually exclusive CURLRES_* definitions.
*/
#if defined(ENABLE_IPV6) && defined(HAVE_GETADDRINFO)
# define CURLRES_IPV6
#else
# define CURLRES_IPV4
#endif
#ifdef USE_ARES
# define CURLRES_ASYNCH
# define CURLRES_ARES
/* now undef the stock libc functions just to avoid them being used */
# undef HAVE_GETADDRINFO
# undef HAVE_FREEADDRINFO
# undef HAVE_GETHOSTBYNAME
#elif defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
# define CURLRES_ASYNCH
# define CURLRES_THREADED
#else
# define CURLRES_SYNCH
#endif
/* ---------------------------------------------------------------- */
/*
* msvc 6.0 does not have struct sockaddr_storage and
* does not define IPPROTO_ESP in winsock2.h. But both
* are available if PSDK is properly installed.
*/
#if defined(_MSC_VER) && !defined(__POCC__)
# if !defined(HAVE_WINSOCK2_H) || ((_MSC_VER < 1300) && !defined(IPPROTO_ESP))
# undef HAVE_STRUCT_SOCKADDR_STORAGE
# endif
#endif
/*
* Intentionally fail to build when using msvc 6.0 without PSDK installed.
* The brave of heart can circumvent this, defining ALLOW_MSVC6_WITHOUT_PSDK
* in lib/config-win32.h although absolutely discouraged and unsupported.
*/
#if defined(_MSC_VER) && !defined(__POCC__)
# if !defined(HAVE_WINDOWS_H) || ((_MSC_VER < 1300) && !defined(_FILETIME_))
# if !defined(ALLOW_MSVC6_WITHOUT_PSDK)
# error MSVC 6.0 requires "February 2003 Platform SDK" a.k.a. \
"Windows Server 2003 PSDK"
# else
# define CURL_DISABLE_LDAP 1
# endif
# endif
#endif
#ifdef NETWARE
int netware_init(void);
#ifndef __NOVELL_LIBC__
#include <sys/bsdskt.h>
#include <sys/timeval.h>
#endif
#endif
#if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H) && !defined(USE_WIN32_IDN)
/* The lib and header are present */
#define USE_LIBIDN2
#endif
#if defined(USE_LIBIDN2) && defined(USE_WIN32_IDN)
#error "Both libidn2 and WinIDN are enabled, choose one."
#endif
#define LIBIDN_REQUIRED_VERSION "0.4.1"
#if defined(USE_GNUTLS) || defined(USE_OPENSSL) || defined(USE_NSS) || \
defined(USE_MBEDTLS) || \
defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || \
defined(USE_SECTRANSP) || defined(USE_GSKIT) || defined(USE_MESALINK) || \
defined(USE_BEARSSL) || defined(USE_RUSTLS)
#define USE_SSL /* SSL support has been enabled */
#endif
/* Single point where USE_SPNEGO definition might be defined */
#if !defined(CURL_DISABLE_CRYPTO_AUTH) && \
(defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI))
#define USE_SPNEGO
#endif
/* Single point where USE_KERBEROS5 definition might be defined */
#if !defined(CURL_DISABLE_CRYPTO_AUTH) && \
(defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI))
#define USE_KERBEROS5
#endif
/* Single point where USE_NTLM definition might be defined */
#if !defined(CURL_DISABLE_CRYPTO_AUTH) && !defined(CURL_DISABLE_NTLM)
# if defined(USE_OPENSSL) || defined(USE_MBEDTLS) || \
defined(USE_GNUTLS) || defined(USE_NSS) || defined(USE_SECTRANSP) || \
defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO) || \
(defined(USE_WOLFSSL) && defined(HAVE_WOLFSSL_DES_ECB_ENCRYPT))
# define USE_CURL_NTLM_CORE
# endif
# if defined(USE_CURL_NTLM_CORE) || defined(USE_WINDOWS_SSPI)
# define USE_NTLM
# endif
#endif
#ifdef CURL_WANTS_CA_BUNDLE_ENV
#error "No longer supported. Set CURLOPT_CAINFO at runtime instead."
#endif
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH) || defined(USE_WOLFSSH)
#define USE_SSH
#endif
/*
* Provide a mechanism to silence picky compilers, such as gcc 4.6+.
* Parameters should of course normally not be unused, but for example when
* we have multiple implementations of the same interface it may happen.
*/
#if defined(__GNUC__) && ((__GNUC__ >= 3) || \
((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7)))
# define UNUSED_PARAM __attribute__((__unused__))
# define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define UNUSED_PARAM /*NOTHING*/
# define WARN_UNUSED_RESULT
#endif
/*
* Include macros and defines that should only be processed once.
*/
#ifndef HEADER_CURL_SETUP_ONCE_H
#include "curl_setup_once.h"
#endif
/*
* Definition of our NOP statement Object-like macro
*/
#ifndef Curl_nop_stmt
# define Curl_nop_stmt do { } while(0)
#endif
/*
* Ensure that Winsock and lwIP TCP/IP stacks are not mixed.
*/
#if defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)
# if defined(SOCKET) || \
defined(USE_WINSOCK) || \
defined(HAVE_WINSOCK2_H) || \
defined(HAVE_WS2TCPIP_H)
# error "WinSock and lwIP TCP/IP stack definitions shall not coexist!"
# endif
#endif
/*
* shutdown() flags for systems that don't define them
*/
#ifndef SHUT_RD
#define SHUT_RD 0x00
#endif
#ifndef SHUT_WR
#define SHUT_WR 0x01
#endif
#ifndef SHUT_RDWR
#define SHUT_RDWR 0x02
#endif
/* Define S_ISREG if not defined by system headers, f.e. MSVC */
#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif
/* Define S_ISDIR if not defined by system headers, f.e. MSVC */
#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif
/* In Windows the default file mode is text but an application can override it.
Therefore we specify it explicitly. https://github.com/curl/curl/pull/258
*/
#if defined(WIN32) || defined(MSDOS)
#define FOPEN_READTEXT "rt"
#define FOPEN_WRITETEXT "wt"
#define FOPEN_APPENDTEXT "at"
#elif defined(__CYGWIN__)
/* Cygwin has specific behavior we need to address when WIN32 is not defined.
https://cygwin.com/cygwin-ug-net/using-textbinary.html
For write we want our output to have line endings of LF and be compatible with
other Cygwin utilities. For read we want to handle input that may have line
endings either CRLF or LF so 't' is appropriate.
*/
#define FOPEN_READTEXT "rt"
#define FOPEN_WRITETEXT "w"
#define FOPEN_APPENDTEXT "a"
#else
#define FOPEN_READTEXT "r"
#define FOPEN_WRITETEXT "w"
#define FOPEN_APPENDTEXT "a"
#endif
/* WinSock destroys recv() buffer when send() failed.
* Enabled automatically for Windows and for Cygwin as Cygwin sockets are
* wrappers for WinSock sockets. https://github.com/curl/curl/issues/657
* Define DONT_USE_RECV_BEFORE_SEND_WORKAROUND to force disable workaround.
*/
#if !defined(DONT_USE_RECV_BEFORE_SEND_WORKAROUND)
# if defined(WIN32) || defined(__CYGWIN__)
# define USE_RECV_BEFORE_SEND_WORKAROUND
# endif
#else /* DONT_USE_RECV_BEFORE_SEND_WORKAROUND */
# ifdef USE_RECV_BEFORE_SEND_WORKAROUND
# undef USE_RECV_BEFORE_SEND_WORKAROUND
# endif
#endif /* DONT_USE_RECV_BEFORE_SEND_WORKAROUND */
/* for systems that don't detect this in configure */
#ifndef CURL_SA_FAMILY_T
# if defined(HAVE_SA_FAMILY_T)
# define CURL_SA_FAMILY_T sa_family_t
# elif defined(HAVE_ADDRESS_FAMILY)
# define CURL_SA_FAMILY_T ADDRESS_FAMILY
# else
/* use a sensible default */
# define CURL_SA_FAMILY_T unsigned short
# endif
#endif
/* Some convenience macros to get the larger/smaller value out of two given.
We prefix with CURL to prevent name collisions. */
#define CURLMAX(x,y) ((x)>(y)?(x):(y))
#define CURLMIN(x,y) ((x)<(y)?(x):(y))
/* Some versions of the Android SDK is missing the declaration */
#if defined(HAVE_GETPWUID_R) && defined(HAVE_DECL_GETPWUID_R_MISSING)
struct passwd;
int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf,
size_t buflen, struct passwd **result);
#endif
#ifdef DEBUGBUILD
#define UNITTEST
#else
#define UNITTEST static
#endif
#if defined(USE_NGHTTP2) || defined(USE_HYPER)
#define USE_HTTP2
#endif
#if defined(USE_NGTCP2) || defined(USE_QUICHE)
#define ENABLE_QUIC
#endif
#if defined(USE_UNIX_SOCKETS) && defined(WIN32)
# if defined(__MINGW32__) && !defined(LUP_SECURE)
typedef u_short ADDRESS_FAMILY; /* Classic mingw, 11y+ old mingw-w64 */
# endif
# if !defined(UNIX_PATH_MAX)
/* Replicating logic present in afunix.h
(distributed with newer Windows 10 SDK versions only) */
# define UNIX_PATH_MAX 108
/* !checksrc! disable TYPEDEFSTRUCT 1 */
typedef struct sockaddr_un {
ADDRESS_FAMILY sun_family;
char sun_path[UNIX_PATH_MAX];
} SOCKADDR_UN, *PSOCKADDR_UN;
# define WIN32_SOCKADDR_UN
# endif
#endif
#endif /* HEADER_CURL_SETUP_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/quic.h | #ifndef HEADER_CURL_QUIC_H
#define HEADER_CURL_QUIC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef ENABLE_QUIC
#ifdef USE_NGTCP2
#include "vquic/ngtcp2.h"
#endif
#ifdef USE_QUICHE
#include "vquic/quiche.h"
#endif
#include "urldata.h"
/* functions provided by the specific backends */
CURLcode Curl_quic_connect(struct Curl_easy *data,
struct connectdata *conn,
curl_socket_t sockfd,
int sockindex,
const struct sockaddr *addr,
socklen_t addrlen);
CURLcode Curl_quic_is_connected(struct Curl_easy *data,
struct connectdata *conn,
int sockindex,
bool *connected);
void Curl_quic_ver(char *p, size_t len);
CURLcode Curl_quic_done_sending(struct Curl_easy *data);
void Curl_quic_done(struct Curl_easy *data, bool premature);
bool Curl_quic_data_pending(const struct Curl_easy *data);
void Curl_quic_disconnect(struct Curl_easy *data,
struct connectdata *conn, int tempindex);
#else /* ENABLE_QUIC */
#define Curl_quic_done_sending(x)
#define Curl_quic_done(x,y)
#define Curl_quic_data_pending(x)
#define Curl_quic_disconnect(x,y,z)
#endif /* !ENABLE_QUIC */
#endif /* HEADER_CURL_QUIC_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/smb.h | #ifndef HEADER_CURL_SMB_H
#define HEADER_CURL_SMB_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2014, Bill Nagel <[email protected]>, Exacq Technologies
* Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
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;
size_t upload_size;
size_t send_size;
size_t sent;
size_t got;
};
/*
* Definitions for SMB protocol data structures
*/
#ifdef BUILDING_CURL_SMB_C
#if defined(_MSC_VER) || defined(__ILEC400__)
# define PACK
# pragma pack(push)
# pragma pack(1)
#elif defined(__GNUC__)
# define PACK __attribute__((packed))
#else
# define PACK
#endif
#define SMB_COM_CLOSE 0x04
#define SMB_COM_READ_ANDX 0x2e
#define SMB_COM_WRITE_ANDX 0x2f
#define SMB_COM_TREE_DISCONNECT 0x71
#define SMB_COM_NEGOTIATE 0x72
#define SMB_COM_SETUP_ANDX 0x73
#define SMB_COM_TREE_CONNECT_ANDX 0x75
#define SMB_COM_NT_CREATE_ANDX 0xa2
#define SMB_COM_NO_ANDX_COMMAND 0xff
#define SMB_WC_CLOSE 0x03
#define SMB_WC_READ_ANDX 0x0c
#define SMB_WC_WRITE_ANDX 0x0e
#define SMB_WC_SETUP_ANDX 0x0d
#define SMB_WC_TREE_CONNECT_ANDX 0x04
#define SMB_WC_NT_CREATE_ANDX 0x18
#define SMB_FLAGS_CANONICAL_PATHNAMES 0x10
#define SMB_FLAGS_CASELESS_PATHNAMES 0x08
#define SMB_FLAGS2_UNICODE_STRINGS 0x8000
#define SMB_FLAGS2_IS_LONG_NAME 0x0040
#define SMB_FLAGS2_KNOWS_LONG_NAME 0x0001
#define SMB_CAP_LARGE_FILES 0x08
#define SMB_GENERIC_WRITE 0x40000000
#define SMB_GENERIC_READ 0x80000000
#define SMB_FILE_SHARE_ALL 0x07
#define SMB_FILE_OPEN 0x01
#define SMB_FILE_OVERWRITE_IF 0x05
#define SMB_ERR_NOACCESS 0x00050001
struct smb_header {
unsigned char nbt_type;
unsigned char nbt_flags;
unsigned short nbt_length;
unsigned char magic[4];
unsigned char command;
unsigned int status;
unsigned char flags;
unsigned short flags2;
unsigned short pid_high;
unsigned char signature[8];
unsigned short pad;
unsigned short tid;
unsigned short pid;
unsigned short uid;
unsigned short mid;
} PACK;
struct smb_negotiate_response {
struct smb_header h;
unsigned char word_count;
unsigned short dialect_index;
unsigned char security_mode;
unsigned short max_mpx_count;
unsigned short max_number_vcs;
unsigned int max_buffer_size;
unsigned int max_raw_size;
unsigned int session_key;
unsigned int capabilities;
unsigned int system_time_low;
unsigned int system_time_high;
unsigned short server_time_zone;
unsigned char encryption_key_length;
unsigned short byte_count;
char bytes[1];
} PACK;
struct andx {
unsigned char command;
unsigned char pad;
unsigned short offset;
} PACK;
struct smb_setup {
unsigned char word_count;
struct andx andx;
unsigned short max_buffer_size;
unsigned short max_mpx_count;
unsigned short vc_number;
unsigned int session_key;
unsigned short lengths[2];
unsigned int pad;
unsigned int capabilities;
unsigned short byte_count;
char bytes[1024];
} PACK;
struct smb_tree_connect {
unsigned char word_count;
struct andx andx;
unsigned short flags;
unsigned short pw_len;
unsigned short byte_count;
char bytes[1024];
} PACK;
struct smb_nt_create {
unsigned char word_count;
struct andx andx;
unsigned char pad;
unsigned short name_length;
unsigned int flags;
unsigned int root_fid;
unsigned int access;
curl_off_t allocation_size;
unsigned int ext_file_attributes;
unsigned int share_access;
unsigned int create_disposition;
unsigned int create_options;
unsigned int impersonation_level;
unsigned char security_flags;
unsigned short byte_count;
char bytes[1024];
} PACK;
struct smb_nt_create_response {
struct smb_header h;
unsigned char word_count;
struct andx andx;
unsigned char op_lock_level;
unsigned short fid;
unsigned int create_disposition;
curl_off_t create_time;
curl_off_t last_access_time;
curl_off_t last_write_time;
curl_off_t last_change_time;
unsigned int ext_file_attributes;
curl_off_t allocation_size;
curl_off_t end_of_file;
} PACK;
struct smb_read {
unsigned char word_count;
struct andx andx;
unsigned short fid;
unsigned int offset;
unsigned short max_bytes;
unsigned short min_bytes;
unsigned int timeout;
unsigned short remaining;
unsigned int offset_high;
unsigned short byte_count;
} PACK;
struct smb_write {
struct smb_header h;
unsigned char word_count;
struct andx andx;
unsigned short fid;
unsigned int offset;
unsigned int timeout;
unsigned short write_mode;
unsigned short remaining;
unsigned short pad;
unsigned short data_length;
unsigned short data_offset;
unsigned int offset_high;
unsigned short byte_count;
unsigned char pad2;
} PACK;
struct smb_close {
unsigned char word_count;
unsigned short fid;
unsigned int last_mtime;
unsigned short byte_count;
} PACK;
struct smb_tree_disconnect {
unsigned char word_count;
unsigned short byte_count;
} PACK;
#if defined(_MSC_VER) || defined(__ILEC400__)
# pragma pack(pop)
#endif
#endif /* BUILDING_CURL_SMB_C */
#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 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/rand.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <curl/curl.h>
#include "vtls/vtls.h"
#include "sendf.h"
#include "rand.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
static CURLcode randit(struct Curl_easy *data, unsigned int *rnd)
{
unsigned int r;
CURLcode result = CURLE_OK;
static unsigned int randseed;
static bool seeded = FALSE;
#ifdef CURLDEBUG
char *force_entropy = getenv("CURL_ENTROPY");
if(force_entropy) {
if(!seeded) {
unsigned int seed = 0;
size_t elen = strlen(force_entropy);
size_t clen = sizeof(seed);
size_t min = elen < clen ? elen : clen;
memcpy((char *)&seed, force_entropy, min);
randseed = ntohl(seed);
seeded = TRUE;
}
else
randseed++;
*rnd = randseed;
return CURLE_OK;
}
#endif
/* data may be NULL! */
result = Curl_ssl_random(data, (unsigned char *)rnd, sizeof(*rnd));
if(result != CURLE_NOT_BUILT_IN)
/* only if there is no random function in the TLS backend do the non crypto
version, otherwise return result */
return result;
/* ---- non-cryptographic version following ---- */
#ifdef RANDOM_FILE
if(!seeded) {
/* if there's a random file to read a seed from, use it */
int fd = open(RANDOM_FILE, O_RDONLY);
if(fd > -1) {
/* read random data into the randseed variable */
ssize_t nread = read(fd, &randseed, sizeof(randseed));
if(nread == sizeof(randseed))
seeded = TRUE;
close(fd);
}
}
#endif
if(!seeded) {
struct curltime now = Curl_now();
infof(data, "WARNING: Using weak random seed");
randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
randseed = randseed * 1103515245 + 12345;
randseed = randseed * 1103515245 + 12345;
randseed = randseed * 1103515245 + 12345;
seeded = TRUE;
}
/* Return an unsigned 32-bit pseudo-random number. */
r = randseed = randseed * 1103515245 + 12345;
*rnd = (r << 16) | ((r >> 16) & 0xFFFF);
return CURLE_OK;
}
/*
* Curl_rand() stores 'num' number of random unsigned integers in the buffer
* 'rndptr' points to.
*
* If libcurl is built without TLS support or with a TLS backend that lacks a
* proper random API (Gskit or mbedTLS), this function will use "weak" random.
*
* When built *with* TLS support and a backend that offers strong random, it
* will return error if it cannot provide strong random values.
*
* NOTE: 'data' may be passed in as NULL when coming from external API without
* easy handle!
*
*/
CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num)
{
CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
DEBUGASSERT(num > 0);
while(num) {
unsigned int r;
size_t left = num < sizeof(unsigned int) ? num : sizeof(unsigned int);
result = randit(data, &r);
if(result)
return result;
while(left) {
*rnd++ = (unsigned char)(r & 0xFF);
r >>= 8;
--num;
--left;
}
}
return result;
}
/*
* Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random
* hexadecimal digits PLUS a zero terminating byte. It must be an odd number
* size.
*/
CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd,
size_t num)
{
CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
const char *hex = "0123456789abcdef";
unsigned char buffer[128];
unsigned char *bufp = buffer;
DEBUGASSERT(num > 1);
#ifdef __clang_analyzer__
/* This silences a scan-build warning about accessing this buffer with
uninitialized memory. */
memset(buffer, 0, sizeof(buffer));
#endif
if((num/2 >= sizeof(buffer)) || !(num&1))
/* make sure it fits in the local buffer and that it is an odd number! */
return CURLE_BAD_FUNCTION_ARGUMENT;
num--; /* save one for zero termination */
result = Curl_rand(data, buffer, num/2);
if(result)
return result;
while(num) {
/* clang-tidy warns on this line without this comment: */
/* NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult) */
*rnd++ = hex[(*bufp & 0xF0)>>4];
*rnd++ = hex[*bufp & 0x0F];
bufp++;
num -= 2;
}
*rnd = 0;
return result;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/cookie.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/***
RECEIVING COOKIE INFORMATION
============================
struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
const char *file, struct CookieInfo *inc, bool newsession);
Inits a cookie struct to store data in a local file. This is always
called before any cookies are set.
struct Cookie *Curl_cookie_add(struct Curl_easy *data,
struct CookieInfo *c, bool httpheader, char *lineptr,
const char *domain, const char *path);
The 'lineptr' parameter is a full "Set-cookie:" line as
received from a server.
The function need to replace previously stored lines that this new
line supersedes.
It may remove lines that are expired.
It should return an indication of success/error.
SENDING COOKIE INFORMATION
==========================
struct Cookies *Curl_cookie_getlist(struct CookieInfo *cookie,
char *host, char *path, bool secure);
For a given host and path, return a linked list of cookies that
the client should send to the server if used now. The secure
boolean informs the cookie if a secure connection is achieved or
not.
It shall only return cookies that haven't expired.
Example set of cookies:
Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure
Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
domain=.fidelity.com; path=/ftgw; secure
Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
domain=.fidelity.com; path=/; secure
Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
domain=.fidelity.com; path=/; secure
Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
domain=.fidelity.com; path=/; secure
Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT;
domain=.fidelity.com; path=/; secure
Set-cookie:
Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday,
13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure
****/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
#include "urldata.h"
#include "cookie.h"
#include "psl.h"
#include "strtok.h"
#include "sendf.h"
#include "slist.h"
#include "share.h"
#include "strtoofft.h"
#include "strcase.h"
#include "curl_get_line.h"
#include "curl_memrchr.h"
#include "parsedate.h"
#include "rand.h"
#include "rename.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
static void strstore(char **str, const char *newstr);
static void freecookie(struct Cookie *co)
{
free(co->expirestr);
free(co->domain);
free(co->path);
free(co->spath);
free(co->name);
free(co->value);
free(co->maxage);
free(co->version);
free(co);
}
static bool tailmatch(const char *cooke_domain, const char *hostname)
{
size_t cookie_domain_len = strlen(cooke_domain);
size_t hostname_len = strlen(hostname);
if(hostname_len < cookie_domain_len)
return FALSE;
if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len))
return FALSE;
/*
* A lead char of cookie_domain is not '.'.
* RFC6265 4.1.2.3. The Domain Attribute says:
* For example, if the value of the Domain attribute is
* "example.com", the user agent will include the cookie in the Cookie
* header when making HTTP requests to example.com, www.example.com, and
* www.corp.example.com.
*/
if(hostname_len == cookie_domain_len)
return TRUE;
if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
return TRUE;
return FALSE;
}
/*
* matching cookie path and url path
* RFC6265 5.1.4 Paths and Path-Match
*/
static bool pathmatch(const char *cookie_path, const char *request_uri)
{
size_t cookie_path_len;
size_t uri_path_len;
char *uri_path = NULL;
char *pos;
bool ret = FALSE;
/* cookie_path must not have last '/' separator. ex: /sample */
cookie_path_len = strlen(cookie_path);
if(1 == cookie_path_len) {
/* cookie_path must be '/' */
return TRUE;
}
uri_path = strdup(request_uri);
if(!uri_path)
return FALSE;
pos = strchr(uri_path, '?');
if(pos)
*pos = 0x0;
/* #-fragments are already cut off! */
if(0 == strlen(uri_path) || uri_path[0] != '/') {
strstore(&uri_path, "/");
if(!uri_path)
return FALSE;
}
/*
* here, RFC6265 5.1.4 says
* 4. Output the characters of the uri-path from the first character up
* to, but not including, the right-most %x2F ("/").
* but URL path /hoge?fuga=xxx means /hoge/index.cgi?fuga=xxx in some site
* without redirect.
* Ignore this algorithm because /hoge is uri path for this case
* (uri path is not /).
*/
uri_path_len = strlen(uri_path);
if(uri_path_len < cookie_path_len) {
ret = FALSE;
goto pathmatched;
}
/* not using checkprefix() because matching should be case-sensitive */
if(strncmp(cookie_path, uri_path, cookie_path_len)) {
ret = FALSE;
goto pathmatched;
}
/* The cookie-path and the uri-path are identical. */
if(cookie_path_len == uri_path_len) {
ret = TRUE;
goto pathmatched;
}
/* here, cookie_path_len < uri_path_len */
if(uri_path[cookie_path_len] == '/') {
ret = TRUE;
goto pathmatched;
}
ret = FALSE;
pathmatched:
free(uri_path);
return ret;
}
/*
* Return the top-level domain, for optimal hashing.
*/
static const char *get_top_domain(const char * const domain, size_t *outlen)
{
size_t len = 0;
const char *first = NULL, *last;
if(domain) {
len = strlen(domain);
last = memrchr(domain, '.', len);
if(last) {
first = memrchr(domain, '.', (last - domain));
if(first)
len -= (++first - domain);
}
}
if(outlen)
*outlen = len;
return first? first: domain;
}
/* Avoid C1001, an "internal error" with MSVC14 */
#if defined(_MSC_VER) && (_MSC_VER == 1900)
#pragma optimize("", off)
#endif
/*
* A case-insensitive hash for the cookie domains.
*/
static size_t cookie_hash_domain(const char *domain, const size_t len)
{
const char *end = domain + len;
size_t h = 5381;
while(domain < end) {
h += h << 5;
h ^= Curl_raw_toupper(*domain++);
}
return (h % COOKIE_HASH_SIZE);
}
#if defined(_MSC_VER) && (_MSC_VER == 1900)
#pragma optimize("", on)
#endif
/*
* Hash this domain.
*/
static size_t cookiehash(const char * const domain)
{
const char *top;
size_t len;
if(!domain || Curl_host_is_ipnum(domain))
return 0;
top = get_top_domain(domain, &len);
return cookie_hash_domain(top, len);
}
/*
* cookie path sanitize
*/
static char *sanitize_cookie_path(const char *cookie_path)
{
size_t len;
char *new_path = strdup(cookie_path);
if(!new_path)
return NULL;
/* some stupid site sends path attribute with '"'. */
len = strlen(new_path);
if(new_path[0] == '\"') {
memmove((void *)new_path, (const void *)(new_path + 1), len);
len--;
}
if(len && (new_path[len - 1] == '\"')) {
new_path[len - 1] = 0x0;
len--;
}
/* RFC6265 5.2.4 The Path Attribute */
if(new_path[0] != '/') {
/* Let cookie-path be the default-path. */
strstore(&new_path, "/");
return new_path;
}
/* convert /hoge/ to /hoge */
if(len && new_path[len - 1] == '/') {
new_path[len - 1] = 0x0;
}
return new_path;
}
/*
* Load cookies from all given cookie files (CURLOPT_COOKIEFILE).
*
* NOTE: OOM or cookie parsing failures are ignored.
*/
void Curl_cookie_loadfiles(struct Curl_easy *data)
{
struct curl_slist *list = data->state.cookielist;
if(list) {
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
while(list) {
struct CookieInfo *newcookies = Curl_cookie_init(data,
list->data,
data->cookies,
data->set.cookiesession);
if(!newcookies)
/*
* Failure may be due to OOM or a bad cookie; both are ignored
* but only the first should be
*/
infof(data, "ignoring failed cookie_init for %s", list->data);
else
data->cookies = newcookies;
list = list->next;
}
curl_slist_free_all(data->state.cookielist); /* clean up list */
data->state.cookielist = NULL; /* don't do this again! */
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
}
}
/*
* strstore
*
* A thin wrapper around strdup which ensures that any memory allocated at
* *str will be freed before the string allocated by strdup is stored there.
* The intended usecase is repeated assignments to the same variable during
* parsing in a last-wins scenario. The caller is responsible for checking
* for OOM errors.
*/
static void strstore(char **str, const char *newstr)
{
free(*str);
*str = strdup(newstr);
}
/*
* remove_expired
*
* Remove expired cookies from the hash by inspecting the expires timestamp on
* each cookie in the hash, freeing and deleting any where the timestamp is in
* the past. If the cookiejar has recorded the next timestamp at which one or
* more cookies expire, then processing will exit early in case this timestamp
* is in the future.
*/
static void remove_expired(struct CookieInfo *cookies)
{
struct Cookie *co, *nx;
curl_off_t now = (curl_off_t)time(NULL);
unsigned int i;
/*
* If the earliest expiration timestamp in the jar is in the future we can
* skip scanning the whole jar and instead exit early as there won't be any
* cookies to evict. If we need to evict however, reset the next_expiration
* counter in order to track the next one. In case the recorded first
* expiration is the max offset, then perform the safe fallback of checking
* all cookies.
*/
if(now < cookies->next_expiration &&
cookies->next_expiration != CURL_OFF_T_MAX)
return;
else
cookies->next_expiration = CURL_OFF_T_MAX;
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
struct Cookie *pv = NULL;
co = cookies->cookies[i];
while(co) {
nx = co->next;
if(co->expires && co->expires < now) {
if(!pv) {
cookies->cookies[i] = co->next;
}
else {
pv->next = co->next;
}
cookies->numcookies--;
freecookie(co);
}
else {
/*
* If this cookie has an expiration timestamp earlier than what we've
* seen so far then record it for the next round of expirations.
*/
if(co->expires && co->expires < cookies->next_expiration)
cookies->next_expiration = co->expires;
pv = co;
}
co = nx;
}
}
}
/* Make sure domain contains a dot or is localhost. */
static bool bad_domain(const char *domain)
{
return !strchr(domain, '.') && !strcasecompare(domain, "localhost");
}
/*
* Curl_cookie_add
*
* Add a single cookie line to the cookie keeping object. Be aware that
* sometimes we get an IP-only host name, and that might also be a numerical
* IPv6 address.
*
* Returns NULL on out of memory or invalid cookie. This is suboptimal,
* as they should be treated separately.
*/
struct Cookie *
Curl_cookie_add(struct Curl_easy *data,
/*
* The 'data' pointer here may be NULL at times, and thus
* must only be used very carefully for things that can deal
* with data being NULL. Such as infof() and similar
*/
struct CookieInfo *c,
bool httpheader, /* TRUE if HTTP header-style line */
bool noexpire, /* if TRUE, skip remove_expired() */
char *lineptr, /* first character of the line */
const char *domain, /* default domain */
const char *path, /* full path used when this cookie is set,
used to get default path for the cookie
unless set */
bool secure) /* TRUE if connection is over secure origin */
{
struct Cookie *clist;
struct Cookie *co;
struct Cookie *lastc = NULL;
time_t now = time(NULL);
bool replace_old = FALSE;
bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
size_t myhash;
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)data;
#endif
/* First, alloc and init a new struct for it */
co = calloc(1, sizeof(struct Cookie));
if(!co)
return NULL; /* bail out if we're this low on memory */
if(httpheader) {
/* This line was read off a HTTP-header */
char name[MAX_NAME];
char what[MAX_NAME];
const char *ptr;
const char *semiptr;
size_t linelength = strlen(lineptr);
if(linelength > MAX_COOKIE_LINE) {
/* discard overly long lines at once */
free(co);
return NULL;
}
semiptr = strchr(lineptr, ';'); /* first, find a semicolon */
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
ptr = lineptr;
do {
/* we have a <what>=<this> pair or a stand-alone word here */
name[0] = what[0] = 0; /* init the buffers */
if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
MAX_NAME_TXT "[^;\r\n]",
name, what)) {
/*
* Use strstore() below to properly deal with received cookie
* headers that have the same string property set more than once,
* and then we use the last one.
*/
const char *whatptr;
bool done = FALSE;
bool sep;
size_t len = strlen(what);
size_t nlen = strlen(name);
const char *endofn = &ptr[ nlen ];
/*
* Check for too long individual name or contents, or too long
* combination of name + contents. Chrome and Firefox support 4095 or
* 4096 bytes combo
*/
if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
((nlen + len) > MAX_NAME)) {
freecookie(co);
infof(data, "oversized cookie dropped, name/val %zu + %zu bytes",
nlen, len);
return NULL;
}
/* name ends with a '=' ? */
sep = (*endofn == '=')?TRUE:FALSE;
if(nlen) {
endofn--; /* move to the last character */
if(ISBLANK(*endofn)) {
/* skip trailing spaces in name */
while(*endofn && ISBLANK(*endofn) && nlen) {
endofn--;
nlen--;
}
name[nlen] = 0; /* new end of name */
}
}
/* Strip off trailing whitespace from the 'what' */
while(len && ISBLANK(what[len-1])) {
what[len-1] = 0;
len--;
}
/* Skip leading whitespace from the 'what' */
whatptr = what;
while(*whatptr && ISBLANK(*whatptr))
whatptr++;
/*
* Check if we have a reserved prefix set before anything else, as we
* otherwise have to test for the prefix in both the cookie name and
* "the rest". Prefixes must start with '__' and end with a '-', so
* only test for names where that can possibly be true.
*/
if(nlen > 3 && name[0] == '_' && name[1] == '_') {
if(!strncmp("__Secure-", name, 9))
co->prefix |= COOKIE_PREFIX__SECURE;
else if(!strncmp("__Host-", name, 7))
co->prefix |= COOKIE_PREFIX__HOST;
}
if(!co->name) {
/* The very first name/value pair is the actual cookie name */
if(!sep) {
/* Bad name/value pair. */
badcookie = TRUE;
break;
}
co->name = strdup(name);
co->value = strdup(whatptr);
done = TRUE;
if(!co->name || !co->value) {
badcookie = TRUE;
break;
}
}
else if(!len) {
/*
* this was a "<name>=" with no content, and we must allow
* 'secure' and 'httponly' specified this weirdly
*/
done = TRUE;
/*
* secure cookies are only allowed to be set when the connection is
* using a secure protocol, or when the cookie is being set by
* reading from file
*/
if(strcasecompare("secure", name)) {
if(secure || !c->running) {
co->secure = TRUE;
}
else {
badcookie = TRUE;
break;
}
}
else if(strcasecompare("httponly", name))
co->httponly = TRUE;
else if(sep)
/* there was a '=' so we're not done parsing this field */
done = FALSE;
}
if(done)
;
else if(strcasecompare("path", name)) {
strstore(&co->path, whatptr);
if(!co->path) {
badcookie = TRUE; /* out of memory bad */
break;
}
free(co->spath); /* if this is set again */
co->spath = sanitize_cookie_path(co->path);
if(!co->spath) {
badcookie = TRUE; /* out of memory bad */
break;
}
}
else if(strcasecompare("domain", name)) {
bool is_ip;
/*
* Now, we make sure that our host is within the given domain, or
* the given domain is not valid and thus cannot be set.
*/
if('.' == whatptr[0])
whatptr++; /* ignore preceding dot */
#ifndef USE_LIBPSL
/*
* Without PSL we don't know when the incoming cookie is set on a
* TLD or otherwise "protected" suffix. To reduce risk, we require a
* dot OR the exact host name being "localhost".
*/
if(bad_domain(whatptr))
domain = ":";
#endif
is_ip = Curl_host_is_ipnum(domain ? domain : whatptr);
if(!domain
|| (is_ip && !strcmp(whatptr, domain))
|| (!is_ip && tailmatch(whatptr, domain))) {
strstore(&co->domain, whatptr);
if(!co->domain) {
badcookie = TRUE;
break;
}
if(!is_ip)
co->tailmatch = TRUE; /* we always do that if the domain name was
given */
}
else {
/*
* We did not get a tailmatch and then the attempted set domain is
* not a domain to which the current host belongs. Mark as bad.
*/
badcookie = TRUE;
infof(data, "skipped cookie with bad tailmatch domain: %s",
whatptr);
}
}
else if(strcasecompare("version", name)) {
strstore(&co->version, whatptr);
if(!co->version) {
badcookie = TRUE;
break;
}
}
else if(strcasecompare("max-age", name)) {
/*
* Defined in RFC2109:
*
* Optional. The Max-Age attribute defines the lifetime of the
* cookie, in seconds. The delta-seconds value is a decimal non-
* negative integer. After delta-seconds seconds elapse, the
* client should discard the cookie. A value of zero means the
* cookie should be discarded immediately.
*/
strstore(&co->maxage, whatptr);
if(!co->maxage) {
badcookie = TRUE;
break;
}
}
else if(strcasecompare("expires", name)) {
strstore(&co->expirestr, whatptr);
if(!co->expirestr) {
badcookie = TRUE;
break;
}
}
/*
* Else, this is the second (or more) name we don't know about!
*/
}
else {
/* this is an "illegal" <what>=<this> pair */
}
if(!semiptr || !*semiptr) {
/* we already know there are no more cookies */
semiptr = NULL;
continue;
}
ptr = semiptr + 1;
while(*ptr && ISBLANK(*ptr))
ptr++;
semiptr = strchr(ptr, ';'); /* now, find the next semicolon */
if(!semiptr && *ptr)
/*
* There are no more semicolons, but there's a final name=value pair
* coming up
*/
semiptr = strchr(ptr, '\0');
} while(semiptr);
if(co->maxage) {
CURLofft offt;
offt = curlx_strtoofft((*co->maxage == '\"')?
&co->maxage[1]:&co->maxage[0], NULL, 10,
&co->expires);
if(offt == CURL_OFFT_FLOW)
/* overflow, used max value */
co->expires = CURL_OFF_T_MAX;
else if(!offt) {
if(!co->expires)
/* already expired */
co->expires = 1;
else if(CURL_OFF_T_MAX - now < co->expires)
/* would overflow */
co->expires = CURL_OFF_T_MAX;
else
co->expires += now;
}
}
else if(co->expirestr) {
/*
* Note that if the date couldn't get parsed for whatever reason, the
* cookie will be treated as a session cookie
*/
co->expires = Curl_getdate_capped(co->expirestr);
/*
* Session cookies have expires set to 0 so if we get that back from the
* date parser let's add a second to make it a non-session cookie
*/
if(co->expires == 0)
co->expires = 1;
else if(co->expires < 0)
co->expires = 0;
}
if(!badcookie && !co->domain) {
if(domain) {
/* no domain was given in the header line, set the default */
co->domain = strdup(domain);
if(!co->domain)
badcookie = TRUE;
}
}
if(!badcookie && !co->path && path) {
/*
* No path was given in the header line, set the default. Note that the
* passed-in path to this function MAY have a '?' and following part that
* MUST NOT be stored as part of the path.
*/
char *queryp = strchr(path, '?');
/*
* queryp is where the interesting part of the path ends, so now we
* want to the find the last
*/
char *endslash;
if(!queryp)
endslash = strrchr(path, '/');
else
endslash = memrchr(path, '/', (queryp - path));
if(endslash) {
size_t pathlen = (endslash-path + 1); /* include end slash */
co->path = malloc(pathlen + 1); /* one extra for the zero byte */
if(co->path) {
memcpy(co->path, path, pathlen);
co->path[pathlen] = 0; /* null-terminate */
co->spath = sanitize_cookie_path(co->path);
if(!co->spath)
badcookie = TRUE; /* out of memory bad */
}
else
badcookie = TRUE;
}
}
/*
* If we didn't get a cookie name, or a bad one, the this is an illegal
* line so bail out.
*/
if(badcookie || !co->name) {
freecookie(co);
return NULL;
}
}
else {
/*
* This line is NOT a HTTP header style line, we do offer support for
* reading the odd netscape cookies-file format here
*/
char *ptr;
char *firstptr;
char *tok_buf = NULL;
int fields;
/*
* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked
* with httpOnly after the domain name are not accessible from javascripts,
* but since curl does not operate at javascript level, we include them
* anyway. In Firefox's cookie files, these lines are preceded with
* #HttpOnly_ and then everything is as usual, so we skip 10 characters of
* the line..
*/
if(strncmp(lineptr, "#HttpOnly_", 10) == 0) {
lineptr += 10;
co->httponly = TRUE;
}
if(lineptr[0]=='#') {
/* don't even try the comments */
free(co);
return NULL;
}
/* strip off the possible end-of-line characters */
ptr = strchr(lineptr, '\r');
if(ptr)
*ptr = 0; /* clear it */
ptr = strchr(lineptr, '\n');
if(ptr)
*ptr = 0; /* clear it */
firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
/*
* Now loop through the fields and init the struct we already have
* allocated
*/
for(ptr = firstptr, fields = 0; ptr && !badcookie;
ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
switch(fields) {
case 0:
if(ptr[0]=='.') /* skip preceding dots */
ptr++;
co->domain = strdup(ptr);
if(!co->domain)
badcookie = TRUE;
break;
case 1:
/*
* flag: A TRUE/FALSE value indicating if all machines within a given
* domain can access the variable. Set TRUE when the cookie says
* .domain.com and to false when the domain is complete www.domain.com
*/
co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
break;
case 2:
/* The file format allows the path field to remain not filled in */
if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
/* only if the path doesn't look like a boolean option! */
co->path = strdup(ptr);
if(!co->path)
badcookie = TRUE;
else {
co->spath = sanitize_cookie_path(co->path);
if(!co->spath) {
badcookie = TRUE; /* out of memory bad */
}
}
break;
}
/* this doesn't look like a path, make one up! */
co->path = strdup("/");
if(!co->path)
badcookie = TRUE;
co->spath = strdup("/");
if(!co->spath)
badcookie = TRUE;
fields++; /* add a field and fall down to secure */
/* FALLTHROUGH */
case 3:
co->secure = FALSE;
if(strcasecompare(ptr, "TRUE")) {
if(secure || c->running)
co->secure = TRUE;
else
badcookie = TRUE;
}
break;
case 4:
if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
badcookie = TRUE;
break;
case 5:
co->name = strdup(ptr);
if(!co->name)
badcookie = TRUE;
else {
/* For Netscape file format cookies we check prefix on the name */
if(strncasecompare("__Secure-", co->name, 9))
co->prefix |= COOKIE_PREFIX__SECURE;
else if(strncasecompare("__Host-", co->name, 7))
co->prefix |= COOKIE_PREFIX__HOST;
}
break;
case 6:
co->value = strdup(ptr);
if(!co->value)
badcookie = TRUE;
break;
}
}
if(6 == fields) {
/* we got a cookie with blank contents, fix it */
co->value = strdup("");
if(!co->value)
badcookie = TRUE;
else
fields++;
}
if(!badcookie && (7 != fields))
/* we did not find the sufficient number of fields */
badcookie = TRUE;
if(badcookie) {
freecookie(co);
return NULL;
}
}
if(co->prefix & COOKIE_PREFIX__SECURE) {
/* The __Secure- prefix only requires that the cookie be set secure */
if(!co->secure) {
freecookie(co);
return NULL;
}
}
if(co->prefix & COOKIE_PREFIX__HOST) {
/*
* The __Host- prefix requires the cookie to be secure, have a "/" path
* and not have a domain set.
*/
if(co->secure && co->path && strcmp(co->path, "/") == 0 && !co->tailmatch)
;
else {
freecookie(co);
return NULL;
}
}
if(!c->running && /* read from a file */
c->newsession && /* clean session cookies */
!co->expires) { /* this is a session cookie since it doesn't expire! */
freecookie(co);
return NULL;
}
co->livecookie = c->running;
co->creationtime = ++c->lastct;
/*
* Now we have parsed the incoming line, we must now check if this supersedes
* an already existing cookie, which it may if the previous have the same
* domain and path as this.
*/
/* at first, remove expired cookies */
if(!noexpire)
remove_expired(c);
#ifdef USE_LIBPSL
/*
* Check if the domain is a Public Suffix and if yes, ignore the cookie. We
* must also check that the data handle isn't NULL since the psl code will
* dereference it.
*/
if(data && (domain && co->domain && !Curl_host_is_ipnum(co->domain))) {
const psl_ctx_t *psl = Curl_psl_use(data);
int acceptable;
if(psl) {
acceptable = psl_is_cookie_domain_acceptable(psl, domain, co->domain);
Curl_psl_release(data);
}
else
acceptable = !bad_domain(domain);
if(!acceptable) {
infof(data, "cookie '%s' dropped, domain '%s' must not "
"set cookies for '%s'", co->name, domain, co->domain);
freecookie(co);
return NULL;
}
}
#endif
myhash = cookiehash(co->domain);
clist = c->cookies[myhash];
replace_old = FALSE;
while(clist) {
if(strcasecompare(clist->name, co->name)) {
/* the names are identical */
if(clist->domain && co->domain) {
if(strcasecompare(clist->domain, co->domain) &&
(clist->tailmatch == co->tailmatch))
/* The domains are identical */
replace_old = TRUE;
}
else if(!clist->domain && !co->domain)
replace_old = TRUE;
if(replace_old) {
/* the domains were identical */
if(clist->spath && co->spath) {
if(clist->secure && !co->secure && !secure) {
size_t cllen;
const char *sep;
/*
* A non-secure cookie may not overlay an existing secure cookie.
* For an existing cookie "a" with path "/login", refuse a new
* cookie "a" with for example path "/login/en", while the path
* "/loginhelper" is ok.
*/
sep = strchr(clist->spath + 1, '/');
if(sep)
cllen = sep - clist->spath;
else
cllen = strlen(clist->spath);
if(strncasecompare(clist->spath, co->spath, cllen)) {
freecookie(co);
return NULL;
}
}
else if(strcasecompare(clist->spath, co->spath))
replace_old = TRUE;
else
replace_old = FALSE;
}
else if(!clist->spath && !co->spath)
replace_old = TRUE;
else
replace_old = FALSE;
}
if(replace_old && !co->livecookie && clist->livecookie) {
/*
* Both cookies matched fine, except that the already present cookie is
* "live", which means it was set from a header, while the new one was
* read from a file and thus isn't "live". "live" cookies are preferred
* so the new cookie is freed.
*/
freecookie(co);
return NULL;
}
if(replace_old) {
co->next = clist->next; /* get the next-pointer first */
/* when replacing, creationtime is kept from old */
co->creationtime = clist->creationtime;
/* then free all the old pointers */
free(clist->name);
free(clist->value);
free(clist->domain);
free(clist->path);
free(clist->spath);
free(clist->expirestr);
free(clist->version);
free(clist->maxage);
*clist = *co; /* then store all the new data */
free(co); /* free the newly allocated memory */
co = clist; /* point to the previous struct instead */
/*
* We have replaced a cookie, now skip the rest of the list but make
* sure the 'lastc' pointer is properly set
*/
do {
lastc = clist;
clist = clist->next;
} while(clist);
break;
}
}
lastc = clist;
clist = clist->next;
}
if(c->running)
/* Only show this when NOT reading the cookies from a file */
infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, "
"expire %" CURL_FORMAT_CURL_OFF_T,
replace_old?"Replaced":"Added", co->name, co->value,
co->domain, co->path, co->expires);
if(!replace_old) {
/* then make the last item point on this new one */
if(lastc)
lastc->next = co;
else
c->cookies[myhash] = co;
c->numcookies++; /* one more cookie in the jar */
}
/*
* Now that we've added a new cookie to the jar, update the expiration
* tracker in case it is the next one to expire.
*/
if(co->expires && (co->expires < c->next_expiration))
c->next_expiration = co->expires;
return co;
}
/*
* Curl_cookie_init()
*
* Inits a cookie struct to read data from a local file. This is always
* called before any cookies are set. File may be NULL in which case only the
* struct is initialized. Is file is "-" then STDIN is read.
*
* If 'newsession' is TRUE, discard all "session cookies" on read from file.
*
* Note that 'data' might be called as NULL pointer.
*
* Returns NULL on out of memory. Invalid cookies are ignored.
*/
struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
const char *file,
struct CookieInfo *inc,
bool newsession)
{
struct CookieInfo *c;
FILE *fp = NULL;
bool fromfile = TRUE;
char *line = NULL;
if(NULL == inc) {
/* we didn't get a struct, create one */
c = calloc(1, sizeof(struct CookieInfo));
if(!c)
return NULL; /* failed to get memory */
c->filename = strdup(file?file:"none"); /* copy the name just in case */
if(!c->filename)
goto fail; /* failed to get memory */
/*
* Initialize the next_expiration time to signal that we don't have enough
* information yet.
*/
c->next_expiration = CURL_OFF_T_MAX;
}
else {
/* we got an already existing one, use that */
c = inc;
}
c->running = FALSE; /* this is not running, this is init */
if(file && !strcmp(file, "-")) {
fp = stdin;
fromfile = FALSE;
}
else if(file && !*file) {
/* points to a "" string */
fp = NULL;
}
else
fp = file?fopen(file, FOPEN_READTEXT):NULL;
c->newsession = newsession; /* new session? */
if(fp) {
char *lineptr;
bool headerline;
line = malloc(MAX_COOKIE_LINE);
if(!line)
goto fail;
while(Curl_get_line(line, MAX_COOKIE_LINE, fp)) {
if(checkprefix("Set-Cookie:", line)) {
/* This is a cookie line, get it! */
lineptr = &line[11];
headerline = TRUE;
}
else {
lineptr = line;
headerline = FALSE;
}
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
Curl_cookie_add(data, c, headerline, TRUE, lineptr, NULL, NULL, TRUE);
}
free(line); /* free the line buffer */
/*
* Remove expired cookies from the hash. We must make sure to run this
* after reading the file, and not on every cookie.
*/
remove_expired(c);
if(fromfile)
fclose(fp);
}
c->running = TRUE; /* now, we're running */
if(data)
data->state.cookie_engine = TRUE;
return c;
fail:
free(line);
/*
* Only clean up if we allocated it here, as the original could still be in
* use by a share handle.
*/
if(!inc)
Curl_cookie_cleanup(c);
if(fromfile && fp)
fclose(fp);
return NULL; /* out of memory */
}
/*
* cookie_sort
*
* Helper function to sort cookies such that the longest path gets before the
* shorter path. Path, domain and name lengths are considered in that order,
* with the creationtime as the tiebreaker. The creationtime is guaranteed to
* be unique per cookie, so we know we will get an ordering at that point.
*/
static int cookie_sort(const void *p1, const void *p2)
{
struct Cookie *c1 = *(struct Cookie **)p1;
struct Cookie *c2 = *(struct Cookie **)p2;
size_t l1, l2;
/* 1 - compare cookie path lengths */
l1 = c1->path ? strlen(c1->path) : 0;
l2 = c2->path ? strlen(c2->path) : 0;
if(l1 != l2)
return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
/* 2 - compare cookie domain lengths */
l1 = c1->domain ? strlen(c1->domain) : 0;
l2 = c2->domain ? strlen(c2->domain) : 0;
if(l1 != l2)
return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */
/* 3 - compare cookie name lengths */
l1 = c1->name ? strlen(c1->name) : 0;
l2 = c2->name ? strlen(c2->name) : 0;
if(l1 != l2)
return (l2 > l1) ? 1 : -1;
/* 4 - compare cookie creation time */
return (c2->creationtime > c1->creationtime) ? 1 : -1;
}
/*
* cookie_sort_ct
*
* Helper function to sort cookies according to creation time.
*/
static int cookie_sort_ct(const void *p1, const void *p2)
{
struct Cookie *c1 = *(struct Cookie **)p1;
struct Cookie *c2 = *(struct Cookie **)p2;
return (c2->creationtime > c1->creationtime) ? 1 : -1;
}
#define CLONE(field) \
do { \
if(src->field) { \
d->field = strdup(src->field); \
if(!d->field) \
goto fail; \
} \
} while(0)
static struct Cookie *dup_cookie(struct Cookie *src)
{
struct Cookie *d = calloc(sizeof(struct Cookie), 1);
if(d) {
CLONE(expirestr);
CLONE(domain);
CLONE(path);
CLONE(spath);
CLONE(name);
CLONE(value);
CLONE(maxage);
CLONE(version);
d->expires = src->expires;
d->tailmatch = src->tailmatch;
d->secure = src->secure;
d->livecookie = src->livecookie;
d->httponly = src->httponly;
d->creationtime = src->creationtime;
}
return d;
fail:
freecookie(d);
return NULL;
}
/*
* Curl_cookie_getlist
*
* For a given host and path, return a linked list of cookies that the client
* should send to the server if used now. The secure boolean informs the cookie
* if a secure connection is achieved or not.
*
* It shall only return cookies that haven't expired.
*/
struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
const char *host, const char *path,
bool secure)
{
struct Cookie *newco;
struct Cookie *co;
struct Cookie *mainco = NULL;
size_t matches = 0;
bool is_ip;
const size_t myhash = cookiehash(host);
if(!c || !c->cookies[myhash])
return NULL; /* no cookie struct or no cookies in the struct */
/* at first, remove expired cookies */
remove_expired(c);
/* check if host is an IP(v4|v6) address */
is_ip = Curl_host_is_ipnum(host);
co = c->cookies[myhash];
while(co) {
/* if the cookie requires we're secure we must only continue if we are! */
if(co->secure?secure:TRUE) {
/* now check if the domain is correct */
if(!co->domain ||
(co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
/*
* the right part of the host matches the domain stuff in the
* cookie data
*/
/*
* now check the left part of the path with the cookies path
* requirement
*/
if(!co->spath || pathmatch(co->spath, path) ) {
/*
* and now, we know this is a match and we should create an
* entry for the return-linked-list
*/
newco = dup_cookie(co);
if(newco) {
/* then modify our next */
newco->next = mainco;
/* point the main to us */
mainco = newco;
matches++;
}
else
goto fail;
}
}
}
co = co->next;
}
if(matches) {
/*
* Now we need to make sure that if there is a name appearing more than
* once, the longest specified path version comes first. To make this
* the swiftest way, we just sort them all based on path length.
*/
struct Cookie **array;
size_t i;
/* alloc an array and store all cookie pointers */
array = malloc(sizeof(struct Cookie *) * matches);
if(!array)
goto fail;
co = mainco;
for(i = 0; co; co = co->next)
array[i++] = co;
/* now sort the cookie pointers in path length order */
qsort(array, matches, sizeof(struct Cookie *), cookie_sort);
/* remake the linked list order according to the new order */
mainco = array[0]; /* start here */
for(i = 0; i<matches-1; i++)
array[i]->next = array[i + 1];
array[matches-1]->next = NULL; /* terminate the list */
free(array); /* remove the temporary data again */
}
return mainco; /* return the new list */
fail:
/* failure, clear up the allocated chain and return NULL */
Curl_cookie_freelist(mainco);
return NULL;
}
/*
* Curl_cookie_clearall
*
* Clear all existing cookies and reset the counter.
*/
void Curl_cookie_clearall(struct CookieInfo *cookies)
{
if(cookies) {
unsigned int i;
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
Curl_cookie_freelist(cookies->cookies[i]);
cookies->cookies[i] = NULL;
}
cookies->numcookies = 0;
}
}
/*
* Curl_cookie_freelist
*
* Free a list of cookies previously returned by Curl_cookie_getlist();
*/
void Curl_cookie_freelist(struct Cookie *co)
{
struct Cookie *next;
while(co) {
next = co->next;
freecookie(co);
co = next;
}
}
/*
* Curl_cookie_clearsess
*
* Free all session cookies in the cookies list.
*/
void Curl_cookie_clearsess(struct CookieInfo *cookies)
{
struct Cookie *first, *curr, *next, *prev = NULL;
unsigned int i;
if(!cookies)
return;
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
if(!cookies->cookies[i])
continue;
first = curr = prev = cookies->cookies[i];
for(; curr; curr = next) {
next = curr->next;
if(!curr->expires) {
if(first == curr)
first = next;
if(prev == curr)
prev = next;
else
prev->next = next;
freecookie(curr);
cookies->numcookies--;
}
else
prev = curr;
}
cookies->cookies[i] = first;
}
}
/*
* Curl_cookie_cleanup()
*
* Free a "cookie object" previous created with Curl_cookie_init().
*/
void Curl_cookie_cleanup(struct CookieInfo *c)
{
if(c) {
unsigned int i;
free(c->filename);
for(i = 0; i < COOKIE_HASH_SIZE; i++)
Curl_cookie_freelist(c->cookies[i]);
free(c); /* free the base struct as well */
}
}
/*
* get_netscape_format()
*
* Formats a string for Netscape output file, w/o a newline at the end.
* Function returns a char * to a formatted line. The caller is responsible
* for freeing the returned pointer.
*/
static char *get_netscape_format(const struct Cookie *co)
{
return aprintf(
"%s" /* httponly preamble */
"%s%s\t" /* domain */
"%s\t" /* tailmatch */
"%s\t" /* path */
"%s\t" /* secure */
"%" CURL_FORMAT_CURL_OFF_T "\t" /* expires */
"%s\t" /* name */
"%s", /* value */
co->httponly?"#HttpOnly_":"",
/*
* Make sure all domains are prefixed with a dot if they allow
* tailmatching. This is Mozilla-style.
*/
(co->tailmatch && co->domain && co->domain[0] != '.')? ".":"",
co->domain?co->domain:"unknown",
co->tailmatch?"TRUE":"FALSE",
co->path?co->path:"/",
co->secure?"TRUE":"FALSE",
co->expires,
co->name,
co->value?co->value:"");
}
/*
* cookie_output()
*
* Writes all internally known cookies to the specified file. Specify
* "-" as file name to write to stdout.
*
* The function returns non-zero on write failure.
*/
static CURLcode cookie_output(struct Curl_easy *data,
struct CookieInfo *c, const char *filename)
{
struct Cookie *co;
FILE *out = NULL;
bool use_stdout = FALSE;
char *tempstore = NULL;
CURLcode error = CURLE_OK;
if(!c)
/* no cookie engine alive */
return CURLE_OK;
/* at first, remove expired cookies */
remove_expired(c);
if(!strcmp("-", filename)) {
/* use stdout */
out = stdout;
use_stdout = TRUE;
}
else {
unsigned char randsuffix[9];
if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix)))
return 2;
tempstore = aprintf("%s.%s.tmp", filename, randsuffix);
if(!tempstore)
return CURLE_OUT_OF_MEMORY;
out = fopen(tempstore, FOPEN_WRITETEXT);
if(!out) {
error = CURLE_WRITE_ERROR;
goto error;
}
}
fputs("# Netscape HTTP Cookie File\n"
"# https://curl.se/docs/http-cookies.html\n"
"# This file was generated by libcurl! Edit at your own risk.\n\n",
out);
if(c->numcookies) {
unsigned int i;
size_t nvalid = 0;
struct Cookie **array;
array = calloc(1, sizeof(struct Cookie *) * c->numcookies);
if(!array) {
error = CURLE_OUT_OF_MEMORY;
goto error;
}
/* only sort the cookies with a domain property */
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
for(co = c->cookies[i]; co; co = co->next) {
if(!co->domain)
continue;
array[nvalid++] = co;
}
}
qsort(array, nvalid, sizeof(struct Cookie *), cookie_sort_ct);
for(i = 0; i < nvalid; i++) {
char *format_ptr = get_netscape_format(array[i]);
if(!format_ptr) {
free(array);
error = CURLE_OUT_OF_MEMORY;
goto error;
}
fprintf(out, "%s\n", format_ptr);
free(format_ptr);
}
free(array);
}
if(!use_stdout) {
fclose(out);
out = NULL;
if(Curl_rename(tempstore, filename)) {
unlink(tempstore);
error = CURLE_WRITE_ERROR;
goto error;
}
}
/*
* If we reach here we have successfully written a cookie file so theree is
* no need to inspect the error, any error case should have jumped into the
* error block below.
*/
free(tempstore);
return CURLE_OK;
error:
if(out && !use_stdout)
fclose(out);
free(tempstore);
return error;
}
static struct curl_slist *cookie_list(struct Curl_easy *data)
{
struct curl_slist *list = NULL;
struct curl_slist *beg;
struct Cookie *c;
char *line;
unsigned int i;
if(!data->cookies || (data->cookies->numcookies == 0))
return NULL;
for(i = 0; i < COOKIE_HASH_SIZE; i++) {
for(c = data->cookies->cookies[i]; c; c = c->next) {
if(!c->domain)
continue;
line = get_netscape_format(c);
if(!line) {
curl_slist_free_all(list);
return NULL;
}
beg = Curl_slist_append_nodup(list, line);
if(!beg) {
free(line);
curl_slist_free_all(list);
return NULL;
}
list = beg;
}
}
return list;
}
struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
{
struct curl_slist *list;
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
list = cookie_list(data);
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
return list;
}
void Curl_flush_cookies(struct Curl_easy *data, bool cleanup)
{
CURLcode res;
if(data->set.str[STRING_COOKIEJAR]) {
if(data->state.cookielist) {
/* If there is a list of cookie files to read, do it first so that
we have all the told files read before we write the new jar.
Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
Curl_cookie_loadfiles(data);
}
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
/* if we have a destination file for all the cookies to get dumped to */
res = cookie_output(data, data->cookies, data->set.str[STRING_COOKIEJAR]);
if(res)
infof(data, "WARNING: failed to save cookies in %s: %s",
data->set.str[STRING_COOKIEJAR], curl_easy_strerror(res));
}
else {
if(cleanup && data->state.cookielist) {
/* since nothing is written, we can just free the list of cookie file
names */
curl_slist_free_all(data->state.cookielist); /* clean up list */
data->state.cookielist = NULL;
}
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
}
if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
Curl_cookie_cleanup(data->cookies);
data->cookies = NULL;
}
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
}
#endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/socks_gssapi.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2012 - 2021, Daniel Stenberg, <[email protected]>, et al.
* Copyright (C) 2009, Markus Moeller, <[email protected]>
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_PROXY)
#include "curl_gssapi.h"
#include "urldata.h"
#include "sendf.h"
#include "connect.h"
#include "timeval.h"
#include "socks.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"
static gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT;
/*
* Helper GSS-API error functions.
*/
static int check_gss_err(struct Curl_easy *data,
OM_uint32 major_status,
OM_uint32 minor_status,
const char *function)
{
if(GSS_ERROR(major_status)) {
OM_uint32 maj_stat, min_stat;
OM_uint32 msg_ctx = 0;
gss_buffer_desc status_string;
char buf[1024];
size_t len;
len = 0;
msg_ctx = 0;
while(!msg_ctx) {
/* convert major status code (GSS-API error) to text */
maj_stat = gss_display_status(&min_stat, major_status,
GSS_C_GSS_CODE,
GSS_C_NULL_OID,
&msg_ctx, &status_string);
if(maj_stat == GSS_S_COMPLETE) {
if(sizeof(buf) > len + status_string.length + 1) {
strcpy(buf + len, (char *) status_string.value);
len += status_string.length;
}
gss_release_buffer(&min_stat, &status_string);
break;
}
gss_release_buffer(&min_stat, &status_string);
}
if(sizeof(buf) > len + 3) {
strcpy(buf + len, ".\n");
len += 2;
}
msg_ctx = 0;
while(!msg_ctx) {
/* convert minor status code (underlying routine error) to text */
maj_stat = gss_display_status(&min_stat, minor_status,
GSS_C_MECH_CODE,
GSS_C_NULL_OID,
&msg_ctx, &status_string);
if(maj_stat == GSS_S_COMPLETE) {
if(sizeof(buf) > len + status_string.length)
strcpy(buf + len, (char *) status_string.value);
gss_release_buffer(&min_stat, &status_string);
break;
}
gss_release_buffer(&min_stat, &status_string);
}
failf(data, "GSS-API error: %s failed: %s", function, buf);
return 1;
}
return 0;
}
CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
struct Curl_easy *data)
{
struct connectdata *conn = data->conn;
curl_socket_t sock = conn->sock[sockindex];
CURLcode code;
ssize_t actualread;
ssize_t written;
int result;
OM_uint32 gss_major_status, gss_minor_status, gss_status;
OM_uint32 gss_ret_flags;
int gss_conf_state, gss_enc;
gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
gss_buffer_desc gss_send_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc gss_recv_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc gss_w_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc *gss_token = GSS_C_NO_BUFFER;
gss_name_t server = GSS_C_NO_NAME;
gss_name_t gss_client_name = GSS_C_NO_NAME;
unsigned short us_length;
char *user = NULL;
unsigned char socksreq[4]; /* room for GSS-API exchange header only */
const char *serviceptr = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd";
const size_t serviceptr_length = strlen(serviceptr);
/* GSS-API request looks like
* +----+------+-----+----------------+
* |VER | MTYP | LEN | TOKEN |
* +----+------+----------------------+
* | 1 | 1 | 2 | up to 2^16 - 1 |
* +----+------+-----+----------------+
*/
/* prepare service name */
if(strchr(serviceptr, '/')) {
service.length = serviceptr_length;
service.value = malloc(service.length);
if(!service.value)
return CURLE_OUT_OF_MEMORY;
memcpy(service.value, serviceptr, service.length);
gss_major_status = gss_import_name(&gss_minor_status, &service,
(gss_OID) GSS_C_NULL_OID, &server);
}
else {
service.value = malloc(serviceptr_length +
strlen(conn->socks_proxy.host.name) + 2);
if(!service.value)
return CURLE_OUT_OF_MEMORY;
service.length = serviceptr_length +
strlen(conn->socks_proxy.host.name) + 1;
msnprintf(service.value, service.length + 1, "%s@%s",
serviceptr, conn->socks_proxy.host.name);
gss_major_status = gss_import_name(&gss_minor_status, &service,
GSS_C_NT_HOSTBASED_SERVICE, &server);
}
gss_release_buffer(&gss_status, &service); /* clear allocated memory */
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_import_name()")) {
failf(data, "Failed to create service name.");
gss_release_name(&gss_status, &server);
return CURLE_COULDNT_CONNECT;
}
(void)curlx_nonblock(sock, FALSE);
/* As long as we need to keep sending some context info, and there's no */
/* errors, keep sending it... */
for(;;) {
gss_major_status = Curl_gss_init_sec_context(data,
&gss_minor_status,
&gss_context,
server,
&Curl_krb5_mech_oid,
NULL,
gss_token,
&gss_send_token,
TRUE,
&gss_ret_flags);
if(gss_token != GSS_C_NO_BUFFER)
gss_release_buffer(&gss_status, &gss_recv_token);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_init_sec_context")) {
gss_release_name(&gss_status, &server);
gss_release_buffer(&gss_status, &gss_recv_token);
gss_release_buffer(&gss_status, &gss_send_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to initial GSS-API token.");
return CURLE_COULDNT_CONNECT;
}
if(gss_send_token.length) {
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 1; /* authentication message type */
us_length = htons((short)gss_send_token.length);
memcpy(socksreq + 2, &us_length, sizeof(short));
code = Curl_write_plain(data, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send GSS-API authentication request.");
gss_release_name(&gss_status, &server);
gss_release_buffer(&gss_status, &gss_recv_token);
gss_release_buffer(&gss_status, &gss_send_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
code = Curl_write_plain(data, sock, (char *)gss_send_token.value,
gss_send_token.length, &written);
if(code || ((ssize_t)gss_send_token.length != written)) {
failf(data, "Failed to send GSS-API authentication token.");
gss_release_name(&gss_status, &server);
gss_release_buffer(&gss_status, &gss_recv_token);
gss_release_buffer(&gss_status, &gss_send_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
}
gss_release_buffer(&gss_status, &gss_send_token);
gss_release_buffer(&gss_status, &gss_recv_token);
if(gss_major_status != GSS_S_CONTINUE_NEEDED)
break;
/* analyse response */
/* GSS-API response looks like
* +----+------+-----+----------------+
* |VER | MTYP | LEN | TOKEN |
* +----+------+----------------------+
* | 1 | 1 | 2 | up to 2^16 - 1 |
* +----+------+-----+----------------+
*/
result = Curl_blockread_all(data, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API authentication response.");
gss_release_name(&gss_status, &server);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
/* ignore the first (VER) byte */
if(socksreq[1] == 255) { /* status / message type */
failf(data, "User was rejected by the SOCKS5 server (%d %d).",
socksreq[0], socksreq[1]);
gss_release_name(&gss_status, &server);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
if(socksreq[1] != 1) { /* status / message type */
failf(data, "Invalid GSS-API authentication response type (%d %d).",
socksreq[0], socksreq[1]);
gss_release_name(&gss_status, &server);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
gss_recv_token.length = us_length;
gss_recv_token.value = malloc(us_length);
if(!gss_recv_token.value) {
failf(data,
"Could not allocate memory for GSS-API authentication "
"response token.");
gss_release_name(&gss_status, &server);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_OUT_OF_MEMORY;
}
result = Curl_blockread_all(data, sock, (char *)gss_recv_token.value,
gss_recv_token.length, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API authentication token.");
gss_release_name(&gss_status, &server);
gss_release_buffer(&gss_status, &gss_recv_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
gss_token = &gss_recv_token;
}
gss_release_name(&gss_status, &server);
/* Everything is good so far, user was authenticated! */
gss_major_status = gss_inquire_context(&gss_minor_status, gss_context,
&gss_client_name, NULL, NULL, NULL,
NULL, NULL, NULL);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_inquire_context")) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
gss_release_name(&gss_status, &gss_client_name);
failf(data, "Failed to determine user name.");
return CURLE_COULDNT_CONNECT;
}
gss_major_status = gss_display_name(&gss_minor_status, gss_client_name,
&gss_send_token, NULL);
if(check_gss_err(data, gss_major_status,
gss_minor_status, "gss_display_name")) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
gss_release_name(&gss_status, &gss_client_name);
gss_release_buffer(&gss_status, &gss_send_token);
failf(data, "Failed to determine user name.");
return CURLE_COULDNT_CONNECT;
}
user = malloc(gss_send_token.length + 1);
if(!user) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
gss_release_name(&gss_status, &gss_client_name);
gss_release_buffer(&gss_status, &gss_send_token);
return CURLE_OUT_OF_MEMORY;
}
memcpy(user, gss_send_token.value, gss_send_token.length);
user[gss_send_token.length] = '\0';
gss_release_name(&gss_status, &gss_client_name);
gss_release_buffer(&gss_status, &gss_send_token);
infof(data, "SOCKS5 server authenticated user %s with GSS-API.",user);
free(user);
user = NULL;
/* Do encryption */
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 2; /* encryption message type */
gss_enc = 0; /* no data protection */
/* do confidentiality protection if supported */
if(gss_ret_flags & GSS_C_CONF_FLAG)
gss_enc = 2;
/* else do integrity protection */
else if(gss_ret_flags & GSS_C_INTEG_FLAG)
gss_enc = 1;
infof(data, "SOCKS5 server supports GSS-API %s data protection.",
(gss_enc == 0)?"no":((gss_enc==1)?"integrity":"confidentiality"));
/* force for the moment to no data protection */
gss_enc = 0;
/*
* Sending the encryption type in clear seems wrong. It should be
* protected with gss_seal()/gss_wrap(). See RFC1961 extract below
* The NEC reference implementations on which this is based is
* therefore at fault
*
* +------+------+------+.......................+
* + ver | mtyp | len | token |
* +------+------+------+.......................+
* + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets |
* +------+------+------+.......................+
*
* Where:
*
* - "ver" is the protocol version number, here 1 to represent the
* first version of the SOCKS/GSS-API protocol
*
* - "mtyp" is the message type, here 2 to represent a protection
* -level negotiation message
*
* - "len" is the length of the "token" field in octets
*
* - "token" is the GSS-API encapsulated protection level
*
* The token is produced by encapsulating an octet containing the
* required protection level using gss_seal()/gss_wrap() with conf_req
* set to FALSE. The token is verified using gss_unseal()/
* gss_unwrap().
*
*/
if(data->set.socks5_gssapi_nec) {
us_length = htons((short)1);
memcpy(socksreq + 2, &us_length, sizeof(short));
}
else {
gss_send_token.length = 1;
gss_send_token.value = malloc(1);
if(!gss_send_token.value) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_OUT_OF_MEMORY;
}
memcpy(gss_send_token.value, &gss_enc, 1);
gss_major_status = gss_wrap(&gss_minor_status, gss_context, 0,
GSS_C_QOP_DEFAULT, &gss_send_token,
&gss_conf_state, &gss_w_token);
if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_wrap")) {
gss_release_buffer(&gss_status, &gss_send_token);
gss_release_buffer(&gss_status, &gss_w_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to wrap GSS-API encryption value into token.");
return CURLE_COULDNT_CONNECT;
}
gss_release_buffer(&gss_status, &gss_send_token);
us_length = htons((short)gss_w_token.length);
memcpy(socksreq + 2, &us_length, sizeof(short));
}
code = Curl_write_plain(data, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
failf(data, "Failed to send GSS-API encryption request.");
gss_release_buffer(&gss_status, &gss_w_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
if(data->set.socks5_gssapi_nec) {
memcpy(socksreq, &gss_enc, 1);
code = Curl_write_plain(data, sock, socksreq, 1, &written);
if(code || ( 1 != written)) {
failf(data, "Failed to send GSS-API encryption type.");
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
}
else {
code = Curl_write_plain(data, sock, (char *)gss_w_token.value,
gss_w_token.length, &written);
if(code || ((ssize_t)gss_w_token.length != written)) {
failf(data, "Failed to send GSS-API encryption type.");
gss_release_buffer(&gss_status, &gss_w_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
gss_release_buffer(&gss_status, &gss_w_token);
}
result = Curl_blockread_all(data, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API encryption response.");
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
/* ignore the first (VER) byte */
if(socksreq[1] == 255) { /* status / message type */
failf(data, "User was rejected by the SOCKS5 server (%d %d).",
socksreq[0], socksreq[1]);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
if(socksreq[1] != 2) { /* status / message type */
failf(data, "Invalid GSS-API encryption response type (%d %d).",
socksreq[0], socksreq[1]);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
gss_recv_token.length = us_length;
gss_recv_token.value = malloc(gss_recv_token.length);
if(!gss_recv_token.value) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_OUT_OF_MEMORY;
}
result = Curl_blockread_all(data, sock, (char *)gss_recv_token.value,
gss_recv_token.length, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API encryptrion type.");
gss_release_buffer(&gss_status, &gss_recv_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
if(!data->set.socks5_gssapi_nec) {
gss_major_status = gss_unwrap(&gss_minor_status, gss_context,
&gss_recv_token, &gss_w_token,
0, GSS_C_QOP_DEFAULT);
if(check_gss_err(data, gss_major_status, gss_minor_status, "gss_unwrap")) {
gss_release_buffer(&gss_status, &gss_recv_token);
gss_release_buffer(&gss_status, &gss_w_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
failf(data, "Failed to unwrap GSS-API encryption value into token.");
return CURLE_COULDNT_CONNECT;
}
gss_release_buffer(&gss_status, &gss_recv_token);
if(gss_w_token.length != 1) {
failf(data, "Invalid GSS-API encryption response length (%zu).",
gss_w_token.length);
gss_release_buffer(&gss_status, &gss_w_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
memcpy(socksreq, gss_w_token.value, gss_w_token.length);
gss_release_buffer(&gss_status, &gss_w_token);
}
else {
if(gss_recv_token.length != 1) {
failf(data, "Invalid GSS-API encryption response length (%zu).",
gss_recv_token.length);
gss_release_buffer(&gss_status, &gss_recv_token);
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_COULDNT_CONNECT;
}
memcpy(socksreq, gss_recv_token.value, gss_recv_token.length);
gss_release_buffer(&gss_status, &gss_recv_token);
}
(void)curlx_nonblock(sock, TRUE);
infof(data, "SOCKS5 access with%s protection granted.",
(socksreq[0] == 0)?"out GSS-API data":
((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
conn->socks5_gssapi_enctype = socksreq[0];
if(socksreq[0] == 0)
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_OK;
}
#endif /* HAVE_GSSAPI && !CURL_DISABLE_PROXY */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/bufref.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "urldata.h"
#include "bufref.h"
#include "curl_memory.h"
#include "memdebug.h"
#define SIGNATURE 0x5c48e9b2 /* Random pattern. */
/*
* Init a bufref struct.
*/
void Curl_bufref_init(struct bufref *br)
{
DEBUGASSERT(br);
br->dtor = NULL;
br->ptr = NULL;
br->len = 0;
#ifdef DEBUGBUILD
br->signature = SIGNATURE;
#endif
}
/*
* Free the buffer and re-init the necessary fields. It doesn't touch the
* 'signature' field and thus this buffer reference can be reused.
*/
void Curl_bufref_free(struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
if(br->ptr && br->dtor)
br->dtor((void *) br->ptr);
br->dtor = NULL;
br->ptr = NULL;
br->len = 0;
}
/*
* Set the buffer reference to new values. The previously referenced buffer
* is released before assignment.
*/
void Curl_bufref_set(struct bufref *br, const void *ptr, size_t len,
void (*dtor)(void *))
{
DEBUGASSERT(ptr || !len);
DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
Curl_bufref_free(br);
br->ptr = (const unsigned char *) ptr;
br->len = len;
br->dtor = dtor;
}
/*
* Get a pointer to the referenced buffer.
*/
const unsigned char *Curl_bufref_ptr(const struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
return br->ptr;
}
/*
* Get the length of the referenced buffer data.
*/
size_t Curl_bufref_len(const struct bufref *br)
{
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
return br->len;
}
CURLcode Curl_bufref_memdup(struct bufref *br, const void *ptr, size_t len)
{
unsigned char *cpy = NULL;
DEBUGASSERT(br);
DEBUGASSERT(br->signature == SIGNATURE);
DEBUGASSERT(br->ptr || !br->len);
DEBUGASSERT(ptr || !len);
DEBUGASSERT(len <= CURL_MAX_INPUT_LENGTH);
if(ptr) {
cpy = malloc(len + 1);
if(!cpy)
return CURLE_OUT_OF_MEMORY;
if(len)
memcpy(cpy, ptr, len);
cpy[len] = '\0';
}
Curl_bufref_set(br, cpy, len, curl_free);
return CURLE_OK;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/non-ascii.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef CURL_DOES_CONVERSIONS
#include <curl/curl.h>
#include "non-ascii.h"
#include "formdata.h"
#include "sendf.h"
#include "urldata.h"
#include "multiif.h"
#include "strerror.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
#ifdef HAVE_ICONV
#include <iconv.h>
/* set default codesets for iconv */
#ifndef CURL_ICONV_CODESET_OF_NETWORK
#define CURL_ICONV_CODESET_OF_NETWORK "ISO8859-1"
#endif
#ifndef CURL_ICONV_CODESET_FOR_UTF8
#define CURL_ICONV_CODESET_FOR_UTF8 "UTF-8"
#endif
#define ICONV_ERROR (size_t)-1
#endif /* HAVE_ICONV */
/*
* Curl_convert_clone() returns a malloced copy of the source string (if
* returning CURLE_OK), with the data converted to network format.
*/
CURLcode Curl_convert_clone(struct Curl_easy *data,
const char *indata,
size_t insize,
char **outbuf)
{
char *convbuf;
CURLcode result;
convbuf = malloc(insize);
if(!convbuf)
return CURLE_OUT_OF_MEMORY;
memcpy(convbuf, indata, insize);
result = Curl_convert_to_network(data, convbuf, insize);
if(result) {
free(convbuf);
return result;
}
*outbuf = convbuf; /* return the converted buffer */
return CURLE_OK;
}
/*
* Curl_convert_to_network() is an internal function for performing ASCII
* conversions on non-ASCII platforms. It converts the buffer _in place_.
*/
CURLcode Curl_convert_to_network(struct Curl_easy *data,
char *buffer, size_t length)
{
if(data && data->set.convtonetwork) {
/* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convtonetwork(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
failf(data,
"CURLOPT_CONV_TO_NETWORK_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
}
return result;
}
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
char *input_ptr, *output_ptr;
size_t in_bytes, out_bytes, rc;
char ebuffer[STRERROR_LEN];
/* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->outbound_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
CURL_ICONV_CODESET_OF_HOST);
if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_NETWORK,
CURL_ICONV_CODESET_OF_HOST,
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes)) {
failf(data,
"The Curl_convert_to_network iconv call failed with errno %i: %s",
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
#else
failf(data, "CURLOPT_CONV_TO_NETWORK_FUNCTION callback required");
return CURLE_CONV_REQD;
#endif /* HAVE_ICONV */
}
return CURLE_OK;
}
/*
* Curl_convert_from_network() is an internal function for performing ASCII
* conversions on non-ASCII platforms. It converts the buffer _in place_.
*/
CURLcode Curl_convert_from_network(struct Curl_easy *data,
char *buffer, size_t length)
{
if(data && data->set.convfromnetwork) {
/* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convfromnetwork(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
failf(data,
"CURLOPT_CONV_FROM_NETWORK_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
}
return result;
}
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
char *input_ptr, *output_ptr;
size_t in_bytes, out_bytes, rc;
char ebuffer[STRERROR_LEN];
/* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->inbound_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_OF_NETWORK);
if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_OF_NETWORK,
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes)) {
failf(data,
"Curl_convert_from_network iconv call failed with errno %i: %s",
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
#else
failf(data, "CURLOPT_CONV_FROM_NETWORK_FUNCTION callback required");
return CURLE_CONV_REQD;
#endif /* HAVE_ICONV */
}
return CURLE_OK;
}
/*
* Curl_convert_from_utf8() is an internal function for performing UTF-8
* conversions on non-ASCII platforms.
*/
CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
char *buffer, size_t length)
{
if(data && data->set.convfromutf8) {
/* use translation callback */
CURLcode result;
Curl_set_in_callback(data, true);
result = data->set.convfromutf8(buffer, length);
Curl_set_in_callback(data, false);
if(result) {
failf(data,
"CURLOPT_CONV_FROM_UTF8_FUNCTION callback returned %d: %s",
(int)result, curl_easy_strerror(result));
}
return result;
}
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
iconv_t tmpcd = (iconv_t) -1;
iconv_t *cd = &tmpcd;
char *input_ptr;
char *output_ptr;
size_t in_bytes, out_bytes, rc;
char ebuffer[STRERROR_LEN];
/* open an iconv conversion descriptor if necessary */
if(data)
cd = &data->utf8_cd;
if(*cd == (iconv_t)-1) {
*cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_FOR_UTF8);
if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_FOR_UTF8,
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
if(!data)
iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes)) {
failf(data,
"The Curl_convert_from_utf8 iconv call failed with errno %i: %s",
errno, Curl_strerror(errno, ebuffer, sizeof(ebuffer)));
return CURLE_CONV_FAILED;
}
if(output_ptr < input_ptr) {
/* null terminate the now shorter output string */
*output_ptr = 0x00;
}
#else
failf(data, "CURLOPT_CONV_FROM_UTF8_FUNCTION callback required");
return CURLE_CONV_REQD;
#endif /* HAVE_ICONV */
}
return CURLE_OK;
}
/*
* Init conversion stuff for a Curl_easy
*/
void Curl_convert_init(struct Curl_easy *data)
{
#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
/* conversion descriptors for iconv calls */
data->outbound_cd = (iconv_t)-1;
data->inbound_cd = (iconv_t)-1;
data->utf8_cd = (iconv_t)-1;
#else
(void)data;
#endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
}
/*
* Setup conversion stuff for a Curl_easy
*/
void Curl_convert_setup(struct Curl_easy *data)
{
data->inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_OF_NETWORK);
data->outbound_cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
CURL_ICONV_CODESET_OF_HOST);
data->utf8_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_FOR_UTF8);
}
/*
* Close conversion stuff for a Curl_easy
*/
void Curl_convert_close(struct Curl_easy *data)
{
#ifdef HAVE_ICONV
/* close iconv conversion descriptors */
if(data->inbound_cd != (iconv_t)-1) {
iconv_close(data->inbound_cd);
}
if(data->outbound_cd != (iconv_t)-1) {
iconv_close(data->outbound_cd);
}
if(data->utf8_cd != (iconv_t)-1) {
iconv_close(data->utf8_cd);
}
#else
(void)data;
#endif /* HAVE_ICONV */
}
#endif /* CURL_DOES_CONVERSIONS */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_ldap.h | #ifndef HEADER_CURL_LDAP_H
#define HEADER_CURL_LDAP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#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 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/socks.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if !defined(CURL_DISABLE_PROXY)
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "urldata.h"
#include "sendf.h"
#include "select.h"
#include "connect.h"
#include "timeval.h"
#include "socks.h"
#include "multiif.h" /* for getsock macros */
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
/*
* Helper read-from-socket functions. Does the same as Curl_read() but it
* blocks until all bytes amount of buffersize will be read. No more, no less.
*
* This is STUPID BLOCKING behavior. Only used by the SOCKS GSSAPI functions.
*/
int Curl_blockread_all(struct Curl_easy *data, /* transfer */
curl_socket_t sockfd, /* read from this socket */
char *buf, /* store read data here */
ssize_t buffersize, /* max amount to read */
ssize_t *n) /* amount bytes read */
{
ssize_t nread = 0;
ssize_t allread = 0;
int result;
*n = 0;
for(;;) {
timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
if(timeout_ms < 0) {
/* we already got the timeout */
result = CURLE_OPERATION_TIMEDOUT;
break;
}
if(!timeout_ms)
timeout_ms = TIMEDIFF_T_MAX;
if(SOCKET_READABLE(sockfd, timeout_ms) <= 0) {
result = ~CURLE_OK;
break;
}
result = Curl_read_plain(sockfd, buf, buffersize, &nread);
if(CURLE_AGAIN == result)
continue;
if(result)
break;
if(buffersize == nread) {
allread += nread;
*n = allread;
result = CURLE_OK;
break;
}
if(!nread) {
result = ~CURLE_OK;
break;
}
buffersize -= nread;
buf += nread;
allread += nread;
}
return result;
}
#endif
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
#define DEBUG_AND_VERBOSE
#define sxstate(x,y) socksstate(x,y, __LINE__)
#else
#define sxstate(x,y) socksstate(x,y)
#endif
/* always use this function to change state, to make debugging easier */
static void socksstate(struct Curl_easy *data,
enum connect_t state
#ifdef DEBUG_AND_VERBOSE
, int lineno
#endif
)
{
struct connectdata *conn = data->conn;
enum connect_t oldstate = conn->cnnct.state;
#ifdef DEBUG_AND_VERBOSE
/* synced with the state list in urldata.h */
static const char * const statename[] = {
"INIT",
"SOCKS_INIT",
"SOCKS_SEND",
"SOCKS_READ_INIT",
"SOCKS_READ",
"GSSAPI_INIT",
"AUTH_INIT",
"AUTH_SEND",
"AUTH_READ",
"REQ_INIT",
"RESOLVING",
"RESOLVED",
"RESOLVE_REMOTE",
"REQ_SEND",
"REQ_SENDING",
"REQ_READ",
"REQ_READ_MORE",
"DONE"
};
#endif
if(oldstate == state)
/* don't bother when the new state is the same as the old state */
return;
conn->cnnct.state = state;
#ifdef DEBUG_AND_VERBOSE
infof(data,
"SXSTATE: %s => %s conn %p; line %d",
statename[oldstate], statename[conn->cnnct.state], conn,
lineno);
#endif
}
int Curl_SOCKS_getsock(struct connectdata *conn, curl_socket_t *sock,
int sockindex)
{
int rc = 0;
sock[0] = conn->sock[sockindex];
switch(conn->cnnct.state) {
case CONNECT_RESOLVING:
case CONNECT_SOCKS_READ:
case CONNECT_AUTH_READ:
case CONNECT_REQ_READ:
case CONNECT_REQ_READ_MORE:
rc = GETSOCK_READSOCK(0);
break;
default:
rc = GETSOCK_WRITESOCK(0);
break;
}
return rc;
}
/*
* This function logs in to a SOCKS4 proxy and sends the specifics to the final
* destination server.
*
* Reference :
* https://www.openssh.com/txt/socks4.protocol
*
* Note :
* Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
* Nonsupport "Identification Protocol (RFC1413)"
*/
CURLproxycode Curl_SOCKS4(const char *proxy_user,
const char *hostname,
int remote_port,
int sockindex,
struct Curl_easy *data,
bool *done)
{
struct connectdata *conn = data->conn;
const bool protocol4a =
(conn->socks_proxy.proxytype == CURLPROXY_SOCKS4A) ? TRUE : FALSE;
unsigned char *socksreq = (unsigned char *)data->state.buffer;
CURLcode result;
curl_socket_t sockfd = conn->sock[sockindex];
struct connstate *sx = &conn->cnnct;
struct Curl_dns_entry *dns = NULL;
ssize_t actualread;
ssize_t written;
/* make sure that the buffer is at least 600 bytes */
DEBUGASSERT(READBUFFER_MIN >= 600);
if(!SOCKS_STATE(sx->state) && !*done)
sxstate(data, CONNECT_SOCKS_INIT);
switch(sx->state) {
case CONNECT_SOCKS_INIT:
/* SOCKS4 can only do IPv4, insist! */
conn->ip_version = CURL_IPRESOLVE_V4;
if(conn->bits.httpproxy)
infof(data, "SOCKS4%s: connecting to HTTP proxy %s port %d",
protocol4a ? "a" : "", hostname, remote_port);
infof(data, "SOCKS4 communication to %s:%d", hostname, remote_port);
/*
* Compose socks4 request
*
* Request format
*
* +----+----+----+----+----+----+----+----+----+----+....+----+
* | VN | CD | DSTPORT | DSTIP | USERID |NULL|
* +----+----+----+----+----+----+----+----+----+----+....+----+
* # of bytes: 1 1 2 4 variable 1
*/
socksreq[0] = 4; /* version (SOCKS4) */
socksreq[1] = 1; /* connect */
socksreq[2] = (unsigned char)((remote_port >> 8) & 0xff); /* PORT MSB */
socksreq[3] = (unsigned char)(remote_port & 0xff); /* PORT LSB */
/* DNS resolve only for SOCKS4, not SOCKS4a */
if(!protocol4a) {
enum resolve_t rc =
Curl_resolv(data, hostname, remote_port, FALSE, &dns);
if(rc == CURLRESOLV_ERROR)
return CURLPX_RESOLVE_HOST;
else if(rc == CURLRESOLV_PENDING) {
sxstate(data, CONNECT_RESOLVING);
infof(data, "SOCKS4 non-blocking resolve of %s", hostname);
return CURLPX_OK;
}
sxstate(data, CONNECT_RESOLVED);
goto CONNECT_RESOLVED;
}
/* socks4a doesn't resolve anything locally */
sxstate(data, CONNECT_REQ_INIT);
goto CONNECT_REQ_INIT;
case CONNECT_RESOLVING:
/* check if we have the name resolved by now */
dns = Curl_fetch_addr(data, hostname, (int)conn->port);
if(dns) {
#ifdef CURLRES_ASYNCH
data->state.async.dns = dns;
data->state.async.done = TRUE;
#endif
infof(data, "Hostname '%s' was found", hostname);
sxstate(data, CONNECT_RESOLVED);
}
else {
result = Curl_resolv_check(data, &dns);
if(!dns) {
if(result)
return CURLPX_RESOLVE_HOST;
return CURLPX_OK;
}
}
/* FALLTHROUGH */
CONNECT_RESOLVED:
case CONNECT_RESOLVED: {
struct Curl_addrinfo *hp = NULL;
/*
* We cannot use 'hostent' as a struct that Curl_resolv() returns. It
* returns a Curl_addrinfo pointer that may not always look the same.
*/
if(dns) {
hp = dns->addr;
/* scan for the first IPv4 address */
while(hp && (hp->ai_family != AF_INET))
hp = hp->ai_next;
if(hp) {
struct sockaddr_in *saddr_in;
char buf[64];
Curl_printable_address(hp, buf, sizeof(buf));
saddr_in = (struct sockaddr_in *)(void *)hp->ai_addr;
socksreq[4] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[0];
socksreq[5] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[1];
socksreq[6] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[2];
socksreq[7] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[3];
infof(data, "SOCKS4 connect to IPv4 %s (locally resolved)", buf);
Curl_resolv_unlock(data, dns); /* not used anymore from now on */
}
else
failf(data, "SOCKS4 connection to %s not supported", hostname);
}
else
failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
hostname);
if(!hp)
return CURLPX_RESOLVE_HOST;
}
/* FALLTHROUGH */
CONNECT_REQ_INIT:
case CONNECT_REQ_INIT:
/*
* This is currently not supporting "Identification Protocol (RFC1413)".
*/
socksreq[8] = 0; /* ensure empty userid is NUL-terminated */
if(proxy_user) {
size_t plen = strlen(proxy_user);
if(plen >= (size_t)data->set.buffer_size - 8) {
failf(data, "Too long SOCKS proxy user name, can't use!");
return CURLPX_LONG_USER;
}
/* copy the proxy name WITH trailing zero */
memcpy(socksreq + 8, proxy_user, plen + 1);
}
/*
* Make connection
*/
{
size_t packetsize = 9 +
strlen((char *)socksreq + 8); /* size including NUL */
/* If SOCKS4a, set special invalid IP address 0.0.0.x */
if(protocol4a) {
size_t hostnamelen = 0;
socksreq[4] = 0;
socksreq[5] = 0;
socksreq[6] = 0;
socksreq[7] = 1;
/* append hostname */
hostnamelen = strlen(hostname) + 1; /* length including NUL */
if(hostnamelen <= 255)
strcpy((char *)socksreq + packetsize, hostname);
else {
failf(data, "SOCKS4: too long host name");
return CURLPX_LONG_HOSTNAME;
}
packetsize += hostnamelen;
}
sx->outp = socksreq;
sx->outstanding = packetsize;
sxstate(data, CONNECT_REQ_SENDING);
}
/* FALLTHROUGH */
case CONNECT_REQ_SENDING:
/* Send request */
result = Curl_write_plain(data, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Failed to send SOCKS4 connect request.");
return CURLPX_SEND_CONNECT;
}
if(written != sx->outstanding) {
/* not done, remain in state */
sx->outstanding -= written;
sx->outp += written;
return CURLPX_OK;
}
/* done sending! */
sx->outstanding = 8; /* receive data size */
sx->outp = socksreq;
sxstate(data, CONNECT_SOCKS_READ);
/* FALLTHROUGH */
case CONNECT_SOCKS_READ:
/* Receive response */
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "SOCKS4: Failed receiving connect request ack: %s",
curl_easy_strerror(result));
return CURLPX_RECV_CONNECT;
}
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
return CURLPX_CLOSED;
}
else if(actualread != sx->outstanding) {
/* remain in reading state */
sx->outstanding -= actualread;
sx->outp += actualread;
return CURLPX_OK;
}
sxstate(data, CONNECT_DONE);
break;
default: /* lots of unused states in SOCKS4 */
break;
}
/*
* Response format
*
* +----+----+----+----+----+----+----+----+
* | VN | CD | DSTPORT | DSTIP |
* +----+----+----+----+----+----+----+----+
* # of bytes: 1 1 2 4
*
* VN is the version of the reply code and should be 0. CD is the result
* code with one of the following values:
*
* 90: request granted
* 91: request rejected or failed
* 92: request rejected because SOCKS server cannot connect to
* identd on the client
* 93: request rejected because the client program and identd
* report different user-ids
*/
/* wrong version ? */
if(socksreq[0]) {
failf(data,
"SOCKS4 reply has wrong version, version should be 0.");
return CURLPX_BAD_VERSION;
}
/* Result */
switch(socksreq[1]) {
case 90:
infof(data, "SOCKS4%s request granted.", protocol4a?"a":"");
break;
case 91:
failf(data,
"Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
", request rejected or failed.",
socksreq[4], socksreq[5], socksreq[6], socksreq[7],
(((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLPX_REQUEST_FAILED;
case 92:
failf(data,
"Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
", request rejected because SOCKS server cannot connect to "
"identd on the client.",
socksreq[4], socksreq[5], socksreq[6], socksreq[7],
(((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLPX_IDENTD;
case 93:
failf(data,
"Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
", request rejected because the client program and identd "
"report different user-ids.",
socksreq[4], socksreq[5], socksreq[6], socksreq[7],
(((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLPX_IDENTD_DIFFER;
default:
failf(data,
"Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
", Unknown.",
socksreq[4], socksreq[5], socksreq[6], socksreq[7],
(((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLPX_UNKNOWN_FAIL;
}
*done = TRUE;
return CURLPX_OK; /* Proxy was successful! */
}
/*
* This function logs in to a SOCKS5 proxy and sends the specifics to the final
* destination server.
*/
CURLproxycode Curl_SOCKS5(const char *proxy_user,
const char *proxy_password,
const char *hostname,
int remote_port,
int sockindex,
struct Curl_easy *data,
bool *done)
{
/*
According to the RFC1928, section "6. Replies". This is what a SOCK5
replies:
+----+-----+-------+------+----------+----------+
|VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
Where:
o VER protocol version: X'05'
o REP Reply field:
o X'00' succeeded
*/
struct connectdata *conn = data->conn;
unsigned char *socksreq = (unsigned char *)data->state.buffer;
char dest[256] = "unknown"; /* printable hostname:port */
int idx;
ssize_t actualread;
ssize_t written;
CURLcode result;
curl_socket_t sockfd = conn->sock[sockindex];
bool socks5_resolve_local =
(conn->socks_proxy.proxytype == CURLPROXY_SOCKS5) ? TRUE : FALSE;
const size_t hostname_len = strlen(hostname);
ssize_t len = 0;
const unsigned long auth = data->set.socks5auth;
bool allow_gssapi = FALSE;
struct connstate *sx = &conn->cnnct;
struct Curl_dns_entry *dns = NULL;
if(!SOCKS_STATE(sx->state) && !*done)
sxstate(data, CONNECT_SOCKS_INIT);
switch(sx->state) {
case CONNECT_SOCKS_INIT:
if(conn->bits.httpproxy)
infof(data, "SOCKS5: connecting to HTTP proxy %s port %d",
hostname, remote_port);
/* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */
if(!socks5_resolve_local && hostname_len > 255) {
infof(data, "SOCKS5: server resolving disabled for hostnames of "
"length > 255 [actual len=%zu]", hostname_len);
socks5_resolve_local = TRUE;
}
if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI))
infof(data,
"warning: unsupported value passed to CURLOPT_SOCKS5_AUTH: %lu",
auth);
if(!(auth & CURLAUTH_BASIC))
/* disable username/password auth */
proxy_user = NULL;
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(auth & CURLAUTH_GSSAPI)
allow_gssapi = TRUE;
#endif
idx = 0;
socksreq[idx++] = 5; /* version */
idx++; /* number of authentication methods */
socksreq[idx++] = 0; /* no authentication */
if(allow_gssapi)
socksreq[idx++] = 1; /* GSS-API */
if(proxy_user)
socksreq[idx++] = 2; /* username/password */
/* write the number of authentication methods */
socksreq[1] = (unsigned char) (idx - 2);
result = Curl_write_plain(data, sockfd, (char *)socksreq, idx, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Unable to send initial SOCKS5 request.");
return CURLPX_SEND_CONNECT;
}
if(written != idx) {
sxstate(data, CONNECT_SOCKS_SEND);
sx->outstanding = idx - written;
sx->outp = &socksreq[written];
return CURLPX_OK;
}
sxstate(data, CONNECT_SOCKS_READ);
goto CONNECT_SOCKS_READ_INIT;
case CONNECT_SOCKS_SEND:
result = Curl_write_plain(data, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Unable to send initial SOCKS5 request.");
return CURLPX_SEND_CONNECT;
}
if(written != sx->outstanding) {
/* not done, remain in state */
sx->outstanding -= written;
sx->outp += written;
return CURLPX_OK;
}
/* FALLTHROUGH */
CONNECT_SOCKS_READ_INIT:
case CONNECT_SOCKS_READ_INIT:
sx->outstanding = 2; /* expect two bytes */
sx->outp = socksreq; /* store it here */
/* FALLTHROUGH */
case CONNECT_SOCKS_READ:
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Unable to receive initial SOCKS5 response.");
return CURLPX_RECV_CONNECT;
}
else if(!result && !actualread) {
/* connection closed */
failf(data, "Connection to proxy closed");
return CURLPX_CLOSED;
}
else if(actualread != sx->outstanding) {
/* remain in reading state */
sx->outstanding -= actualread;
sx->outp += actualread;
return CURLPX_OK;
}
else if(socksreq[0] != 5) {
failf(data, "Received invalid version in initial SOCKS5 response.");
return CURLPX_BAD_VERSION;
}
else if(socksreq[1] == 0) {
/* DONE! No authentication needed. Send request. */
sxstate(data, CONNECT_REQ_INIT);
goto CONNECT_REQ_INIT;
}
else if(socksreq[1] == 2) {
/* regular name + password authentication */
sxstate(data, CONNECT_AUTH_INIT);
goto CONNECT_AUTH_INIT;
}
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
else if(allow_gssapi && (socksreq[1] == 1)) {
sxstate(data, CONNECT_GSSAPI_INIT);
result = Curl_SOCKS5_gssapi_negotiate(sockindex, data);
if(result) {
failf(data, "Unable to negotiate SOCKS5 GSS-API context.");
return CURLPX_GSSAPI;
}
}
#endif
else {
/* error */
if(!allow_gssapi && (socksreq[1] == 1)) {
failf(data,
"SOCKS5 GSSAPI per-message authentication is not supported.");
return CURLPX_GSSAPI_PERMSG;
}
else if(socksreq[1] == 255) {
failf(data, "No authentication method was acceptable.");
return CURLPX_NO_AUTH;
}
}
failf(data,
"Undocumented SOCKS5 mode attempted to be used by server.");
return CURLPX_UNKNOWN_MODE;
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
case CONNECT_GSSAPI_INIT:
/* GSSAPI stuff done non-blocking */
break;
#endif
default: /* do nothing! */
break;
CONNECT_AUTH_INIT:
case CONNECT_AUTH_INIT: {
/* Needs user name and password */
size_t proxy_user_len, proxy_password_len;
if(proxy_user && proxy_password) {
proxy_user_len = strlen(proxy_user);
proxy_password_len = strlen(proxy_password);
}
else {
proxy_user_len = 0;
proxy_password_len = 0;
}
/* username/password request looks like
* +----+------+----------+------+----------+
* |VER | ULEN | UNAME | PLEN | PASSWD |
* +----+------+----------+------+----------+
* | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
* +----+------+----------+------+----------+
*/
len = 0;
socksreq[len++] = 1; /* username/pw subnegotiation version */
socksreq[len++] = (unsigned char) proxy_user_len;
if(proxy_user && proxy_user_len) {
/* the length must fit in a single byte */
if(proxy_user_len >= 255) {
failf(data, "Excessive user name length for proxy auth");
return CURLPX_LONG_USER;
}
memcpy(socksreq + len, proxy_user, proxy_user_len);
}
len += proxy_user_len;
socksreq[len++] = (unsigned char) proxy_password_len;
if(proxy_password && proxy_password_len) {
/* the length must fit in a single byte */
if(proxy_password_len > 255) {
failf(data, "Excessive password length for proxy auth");
return CURLPX_LONG_PASSWD;
}
memcpy(socksreq + len, proxy_password, proxy_password_len);
}
len += proxy_password_len;
sxstate(data, CONNECT_AUTH_SEND);
sx->outstanding = len;
sx->outp = socksreq;
}
/* FALLTHROUGH */
case CONNECT_AUTH_SEND:
result = Curl_write_plain(data, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Failed to send SOCKS5 sub-negotiation request.");
return CURLPX_SEND_AUTH;
}
if(sx->outstanding != written) {
/* remain in state */
sx->outstanding -= written;
sx->outp += written;
return CURLPX_OK;
}
sx->outp = socksreq;
sx->outstanding = 2;
sxstate(data, CONNECT_AUTH_READ);
/* FALLTHROUGH */
case CONNECT_AUTH_READ:
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
return CURLPX_RECV_AUTH;
}
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
return CURLPX_CLOSED;
}
else if(actualread != sx->outstanding) {
/* remain in state */
sx->outstanding -= actualread;
sx->outp += actualread;
return CURLPX_OK;
}
/* ignore the first (VER) byte */
else if(socksreq[1]) { /* status */
failf(data, "User was rejected by the SOCKS5 server (%d %d).",
socksreq[0], socksreq[1]);
return CURLPX_USER_REJECTED;
}
/* Everything is good so far, user was authenticated! */
sxstate(data, CONNECT_REQ_INIT);
/* FALLTHROUGH */
CONNECT_REQ_INIT:
case CONNECT_REQ_INIT:
if(socks5_resolve_local) {
enum resolve_t rc = Curl_resolv(data, hostname, remote_port,
FALSE, &dns);
if(rc == CURLRESOLV_ERROR)
return CURLPX_RESOLVE_HOST;
if(rc == CURLRESOLV_PENDING) {
sxstate(data, CONNECT_RESOLVING);
return CURLPX_OK;
}
sxstate(data, CONNECT_RESOLVED);
goto CONNECT_RESOLVED;
}
goto CONNECT_RESOLVE_REMOTE;
case CONNECT_RESOLVING:
/* check if we have the name resolved by now */
dns = Curl_fetch_addr(data, hostname, remote_port);
if(dns) {
#ifdef CURLRES_ASYNCH
data->state.async.dns = dns;
data->state.async.done = TRUE;
#endif
infof(data, "SOCKS5: hostname '%s' found", hostname);
}
if(!dns) {
result = Curl_resolv_check(data, &dns);
if(!dns) {
if(result)
return CURLPX_RESOLVE_HOST;
return CURLPX_OK;
}
}
/* FALLTHROUGH */
CONNECT_RESOLVED:
case CONNECT_RESOLVED: {
struct Curl_addrinfo *hp = NULL;
size_t destlen;
if(dns)
hp = dns->addr;
if(!hp) {
failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
hostname);
return CURLPX_RESOLVE_HOST;
}
Curl_printable_address(hp, dest, sizeof(dest));
destlen = strlen(dest);
msnprintf(dest + destlen, sizeof(dest) - destlen, ":%d", remote_port);
len = 0;
socksreq[len++] = 5; /* version (SOCKS5) */
socksreq[len++] = 1; /* connect */
socksreq[len++] = 0; /* must be zero */
if(hp->ai_family == AF_INET) {
int i;
struct sockaddr_in *saddr_in;
socksreq[len++] = 1; /* ATYP: IPv4 = 1 */
saddr_in = (struct sockaddr_in *)(void *)hp->ai_addr;
for(i = 0; i < 4; i++) {
socksreq[len++] = ((unsigned char *)&saddr_in->sin_addr.s_addr)[i];
}
infof(data, "SOCKS5 connect to IPv4 %s (locally resolved)", dest);
}
#ifdef ENABLE_IPV6
else if(hp->ai_family == AF_INET6) {
int i;
struct sockaddr_in6 *saddr_in6;
socksreq[len++] = 4; /* ATYP: IPv6 = 4 */
saddr_in6 = (struct sockaddr_in6 *)(void *)hp->ai_addr;
for(i = 0; i < 16; i++) {
socksreq[len++] =
((unsigned char *)&saddr_in6->sin6_addr.s6_addr)[i];
}
infof(data, "SOCKS5 connect to IPv6 %s (locally resolved)", dest);
}
#endif
else {
hp = NULL; /* fail! */
failf(data, "SOCKS5 connection to %s not supported", dest);
}
Curl_resolv_unlock(data, dns); /* not used anymore from now on */
goto CONNECT_REQ_SEND;
}
CONNECT_RESOLVE_REMOTE:
case CONNECT_RESOLVE_REMOTE:
/* Authentication is complete, now specify destination to the proxy */
len = 0;
socksreq[len++] = 5; /* version (SOCKS5) */
socksreq[len++] = 1; /* connect */
socksreq[len++] = 0; /* must be zero */
if(!socks5_resolve_local) {
socksreq[len++] = 3; /* ATYP: domain name = 3 */
socksreq[len++] = (char) hostname_len; /* one byte address length */
memcpy(&socksreq[len], hostname, hostname_len); /* address w/o NULL */
len += hostname_len;
infof(data, "SOCKS5 connect to %s:%d (remotely resolved)",
hostname, remote_port);
}
/* FALLTHROUGH */
CONNECT_REQ_SEND:
case CONNECT_REQ_SEND:
/* PORT MSB */
socksreq[len++] = (unsigned char)((remote_port >> 8) & 0xff);
/* PORT LSB */
socksreq[len++] = (unsigned char)(remote_port & 0xff);
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(conn->socks5_gssapi_enctype) {
failf(data, "SOCKS5 GSS-API protection not yet implemented.");
return CURLPX_GSSAPI_PROTECTION;
}
#endif
sx->outp = socksreq;
sx->outstanding = len;
sxstate(data, CONNECT_REQ_SENDING);
/* FALLTHROUGH */
case CONNECT_REQ_SENDING:
result = Curl_write_plain(data, sockfd, (char *)sx->outp,
sx->outstanding, &written);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Failed to send SOCKS5 connect request.");
return CURLPX_SEND_REQUEST;
}
if(sx->outstanding != written) {
/* remain in state */
sx->outstanding -= written;
sx->outp += written;
return CURLPX_OK;
}
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(conn->socks5_gssapi_enctype) {
failf(data, "SOCKS5 GSS-API protection not yet implemented.");
return CURLPX_GSSAPI_PROTECTION;
}
#endif
sx->outstanding = 10; /* minimum packet size is 10 */
sx->outp = socksreq;
sxstate(data, CONNECT_REQ_READ);
/* FALLTHROUGH */
case CONNECT_REQ_READ:
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Failed to receive SOCKS5 connect request ack.");
return CURLPX_RECV_REQACK;
}
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
return CURLPX_CLOSED;
}
else if(actualread != sx->outstanding) {
/* remain in state */
sx->outstanding -= actualread;
sx->outp += actualread;
return CURLPX_OK;
}
if(socksreq[0] != 5) { /* version */
failf(data,
"SOCKS5 reply has wrong version, version should be 5.");
return CURLPX_BAD_VERSION;
}
else if(socksreq[1]) { /* Anything besides 0 is an error */
CURLproxycode rc = CURLPX_REPLY_UNASSIGNED;
int code = socksreq[1];
failf(data, "Can't complete SOCKS5 connection to %s. (%d)",
hostname, (unsigned char)socksreq[1]);
if(code < 9) {
/* RFC 1928 section 6 lists: */
static const CURLproxycode lookup[] = {
CURLPX_OK,
CURLPX_REPLY_GENERAL_SERVER_FAILURE,
CURLPX_REPLY_NOT_ALLOWED,
CURLPX_REPLY_NETWORK_UNREACHABLE,
CURLPX_REPLY_HOST_UNREACHABLE,
CURLPX_REPLY_CONNECTION_REFUSED,
CURLPX_REPLY_TTL_EXPIRED,
CURLPX_REPLY_COMMAND_NOT_SUPPORTED,
CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED,
};
rc = lookup[code];
}
return rc;
}
/* Fix: in general, returned BND.ADDR is variable length parameter by RFC
1928, so the reply packet should be read until the end to avoid errors
at subsequent protocol level.
+----+-----+-------+------+----------+----------+
|VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
ATYP:
o IP v4 address: X'01', BND.ADDR = 4 byte
o domain name: X'03', BND.ADDR = [ 1 byte length, string ]
o IP v6 address: X'04', BND.ADDR = 16 byte
*/
/* Calculate real packet size */
if(socksreq[3] == 3) {
/* domain name */
int addrlen = (int) socksreq[4];
len = 5 + addrlen + 2;
}
else if(socksreq[3] == 4) {
/* IPv6 */
len = 4 + 16 + 2;
}
else if(socksreq[3] == 1) {
len = 4 + 4 + 2;
}
else {
failf(data, "SOCKS5 reply has wrong address type.");
return CURLPX_BAD_ADDRESS_TYPE;
}
/* At this point we already read first 10 bytes */
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
if(!conn->socks5_gssapi_enctype) {
/* decrypt_gssapi_blockread already read the whole packet */
#endif
if(len > 10) {
sx->outstanding = len - 10; /* get the rest */
sx->outp = &socksreq[10];
sxstate(data, CONNECT_REQ_READ_MORE);
}
else {
sxstate(data, CONNECT_DONE);
break;
}
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
}
#endif
/* FALLTHROUGH */
case CONNECT_REQ_READ_MORE:
result = Curl_read_plain(sockfd, (char *)sx->outp,
sx->outstanding, &actualread);
if(result && (CURLE_AGAIN != result)) {
failf(data, "Failed to receive SOCKS5 connect request ack.");
return CURLPX_RECV_ADDRESS;
}
else if(!result && !actualread) {
/* connection closed */
failf(data, "connection to proxy closed");
return CURLPX_CLOSED;
}
else if(actualread != sx->outstanding) {
/* remain in state */
sx->outstanding -= actualread;
sx->outp += actualread;
return CURLPX_OK;
}
sxstate(data, CONNECT_DONE);
}
infof(data, "SOCKS5 request granted.");
*done = TRUE;
return CURLPX_OK; /* Proxy was successful! */
}
#endif /* CURL_DISABLE_PROXY */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/urlapi-int.h | #ifndef HEADER_CURL_URLAPI_INT_H
#define HEADER_CURL_URLAPI_INT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
/* scheme is not URL encoded, the longest libcurl supported ones are... */
#define MAX_SCHEME_LEN 40
bool Curl_is_absolute_url(const char *url, char *scheme, size_t buflen);
#ifdef DEBUGBUILD
CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname, bool);
#endif
#endif /* HEADER_CURL_URLAPI_INT_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/system_win32.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2016 - 2021, Steve Holme, <[email protected]>.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(WIN32)
#include <curl/curl.h>
#include "system_win32.h"
#include "version_win32.h"
#include "curl_sspi.h"
#include "warnless.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
LARGE_INTEGER Curl_freq;
bool Curl_isVistaOrGreater;
/* Handle of iphlpapp.dll */
static HMODULE s_hIpHlpApiDll = NULL;
/* Pointer to the if_nametoindex function */
IF_NAMETOINDEX_FN Curl_if_nametoindex = NULL;
/* Curl_win32_init() performs win32 global initialization */
CURLcode Curl_win32_init(long flags)
{
/* CURL_GLOBAL_WIN32 controls the *optional* part of the initialization which
is just for Winsock at the moment. Any required win32 initialization
should take place after this block. */
if(flags & CURL_GLOBAL_WIN32) {
#ifdef USE_WINSOCK
WORD wVersionRequested;
WSADATA wsaData;
int res;
wVersionRequested = MAKEWORD(2, 2);
res = WSAStartup(wVersionRequested, &wsaData);
if(res)
/* Tell the user that we couldn't find a usable */
/* winsock.dll. */
return CURLE_FAILED_INIT;
/* Confirm that the Windows Sockets DLL supports what we need.*/
/* Note that if the DLL supports versions greater */
/* than wVersionRequested, it will still return */
/* wVersionRequested in wVersion. wHighVersion contains the */
/* highest supported version. */
if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) ||
HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) {
/* Tell the user that we couldn't find a usable */
/* winsock.dll. */
WSACleanup();
return CURLE_FAILED_INIT;
}
/* The Windows Sockets DLL is acceptable. Proceed. */
#elif defined(USE_LWIPSOCK)
lwip_init();
#endif
} /* CURL_GLOBAL_WIN32 */
#ifdef USE_WINDOWS_SSPI
{
CURLcode result = Curl_sspi_global_init();
if(result)
return result;
}
#endif
s_hIpHlpApiDll = Curl_load_library(TEXT("iphlpapi.dll"));
if(s_hIpHlpApiDll) {
/* Get the address of the if_nametoindex function */
IF_NAMETOINDEX_FN pIfNameToIndex =
CURLX_FUNCTION_CAST(IF_NAMETOINDEX_FN,
(GetProcAddress(s_hIpHlpApiDll, "if_nametoindex")));
if(pIfNameToIndex)
Curl_if_nametoindex = pIfNameToIndex;
}
/* curlx_verify_windows_version must be called during init at least once
because it has its own initialization routine. */
if(curlx_verify_windows_version(6, 0, PLATFORM_WINNT,
VERSION_GREATER_THAN_EQUAL)) {
Curl_isVistaOrGreater = TRUE;
}
else
Curl_isVistaOrGreater = FALSE;
QueryPerformanceFrequency(&Curl_freq);
return CURLE_OK;
}
/* Curl_win32_cleanup() is the opposite of Curl_win32_init() */
void Curl_win32_cleanup(long init_flags)
{
if(s_hIpHlpApiDll) {
FreeLibrary(s_hIpHlpApiDll);
s_hIpHlpApiDll = NULL;
Curl_if_nametoindex = NULL;
}
#ifdef USE_WINDOWS_SSPI
Curl_sspi_global_cleanup();
#endif
if(init_flags & CURL_GLOBAL_WIN32) {
#ifdef USE_WINSOCK
WSACleanup();
#endif
}
}
#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH)
#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
#endif
#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
/* We use our own typedef here since some headers might lack these */
typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD);
/* See function definitions in winbase.h */
#ifdef UNICODE
# ifdef _WIN32_WCE
# define LOADLIBARYEX L"LoadLibraryExW"
# else
# define LOADLIBARYEX "LoadLibraryExW"
# endif
#else
# define LOADLIBARYEX "LoadLibraryExA"
#endif
/*
* Curl_load_library()
*
* This is used to dynamically load DLLs using the most secure method available
* for the version of Windows that we are running on.
*
* Parameters:
*
* filename [in] - The filename or full path of the DLL to load. If only the
* filename is passed then the DLL will be loaded from the
* Windows system directory.
*
* Returns the handle of the module on success; otherwise NULL.
*/
HMODULE Curl_load_library(LPCTSTR filename)
{
#ifndef CURL_WINDOWS_APP
HMODULE hModule = NULL;
LOADLIBRARYEX_FN pLoadLibraryEx = NULL;
/* Get a handle to kernel32 so we can access it's functions at runtime */
HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32"));
if(!hKernel32)
return NULL;
/* Attempt to find LoadLibraryEx() which is only available on Windows 2000
and above */
pLoadLibraryEx =
CURLX_FUNCTION_CAST(LOADLIBRARYEX_FN,
(GetProcAddress(hKernel32, LOADLIBARYEX)));
/* Detect if there's already a path in the filename and load the library if
there is. Note: Both back slashes and forward slashes have been supported
since the earlier days of DOS at an API level although they are not
supported by command prompt */
if(_tcspbrk(filename, TEXT("\\/"))) {
/** !checksrc! disable BANNEDFUNC 1 **/
hModule = pLoadLibraryEx ?
pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
LoadLibrary(filename);
}
/* Detect if KB2533623 is installed, as LOAD_LIBRARY_SEARCH_SYSTEM32 is only
supported on Windows Vista, Windows Server 2008, Windows 7 and Windows
Server 2008 R2 with this patch or natively on Windows 8 and above */
else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) {
/* Load the DLL from the Windows system directory */
hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
}
else {
/* Attempt to get the Windows system path */
UINT systemdirlen = GetSystemDirectory(NULL, 0);
if(systemdirlen) {
/* Allocate space for the full DLL path (Room for the null terminator
is included in systemdirlen) */
size_t filenamelen = _tcslen(filename);
TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen));
if(path && GetSystemDirectory(path, systemdirlen)) {
/* Calculate the full DLL path */
_tcscpy(path + _tcslen(path), TEXT("\\"));
_tcscpy(path + _tcslen(path), filename);
/* Load the DLL from the Windows system directory */
/** !checksrc! disable BANNEDFUNC 1 **/
hModule = pLoadLibraryEx ?
pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
LoadLibrary(path);
}
free(path);
}
}
return hModule;
#else
/* the Universal Windows Platform (UWP) can't do this */
(void)filename;
return NULL;
#endif
}
#endif /* WIN32 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/mprintf.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1999 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
*
* Purpose:
* A merge of Bjorn Reese's format() function and Daniel's dsprintf()
* 1.0. A full blooded printf() clone with full support for <num>$
* everywhere (parameters, widths and precisions) including variabled
* sized parameters (like doubles, long longs, long doubles and even
* void * in 64-bit architectures).
*
* Current restrictions:
* - Max 128 parameters
* - No 'long double' support.
*
* If you ever want truly portable and good *printf() clones, the project that
* took on from here is named 'Trio' and you find more details on the trio web
* page at https://daniel.haxx.se/projects/trio/
*/
#include "curl_setup.h"
#include "dynbuf.h"
#include <curl/mprintf.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
/*
* Non-ANSI integer extensions
*/
#if (defined(__BORLANDC__) && (__BORLANDC__ >= 0x520)) || \
(defined(__WATCOMC__) && defined(__386__)) || \
(defined(__POCC__) && defined(_MSC_VER)) || \
(defined(_WIN32_WCE)) || \
(defined(__MINGW32__)) || \
(defined(_MSC_VER) && (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64))
# define MP_HAVE_INT_EXTENSIONS
#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 /* lame static limit */
#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), (FILE *)data) != -1) \
done++; \
else \
return done; /* return immediately on failure */ \
} while(0)
/* Data type to read from the arglist */
typedef enum {
FORMAT_UNKNOWN = 0,
FORMAT_STRING,
FORMAT_PTR,
FORMAT_INT,
FORMAT_INTPTR,
FORMAT_LONG,
FORMAT_LONGLONG,
FORMAT_DOUBLE,
FORMAT_LONGDOUBLE,
FORMAT_WIDTH /* For internal use */
} FormatType;
/* conversion and display flags */
enum {
FLAGS_NEW = 0,
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 '*<num>$' 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 */
};
struct va_stack {
FormatType type;
int flags;
long width; /* width OR width parameter number */
long precision; /* precision OR precision parameter number */
union {
char *str;
void *ptr;
union {
mp_intmax_t as_signed;
mp_uintmax_t as_unsigned;
} num;
double dnum;
} data;
};
struct nsprintf {
char *buffer;
size_t length;
size_t max;
};
struct asprintf {
struct dynbuf *b;
bool fail; /* if an alloc has failed and thus the output is not the complete
data */
};
static long dprintf_DollarString(char *input, char **end)
{
int number = 0;
while(ISDIGIT(*input)) {
if(number < MAX_PARAMETERS) {
number *= 10;
number += *input - '0';
}
input++;
}
if(number <= MAX_PARAMETERS && ('$' == *input)) {
*end = ++input;
return number;
}
return 0;
}
static bool dprintf_IsQualifierNoDollar(const char *fmt)
{
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3) || !strncmp(fmt, "I64", 3)) {
return TRUE;
}
#endif
switch(*fmt) {
case '-': case '+': case ' ': case '#': case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'h': case 'l': case 'L': case 'z': case 'q':
case '*': case 'O':
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#endif
return TRUE;
default:
return FALSE;
}
}
/******************************************************************
*
* Pass 1:
* Create an index with the type of each parameter entry and its
* value (may vary in size)
*
* Returns zero on success.
*
******************************************************************/
static int dprintf_Pass1(const char *format, struct va_stack *vto,
char **endpos, va_list arglist)
{
char *fmt = (char *)format;
int param_num = 0;
long this_param;
long width;
long precision;
int flags;
long max_param = 0;
long i;
while(*fmt) {
if(*fmt++ == '%') {
if(*fmt == '%') {
fmt++;
continue; /* while */
}
flags = FLAGS_NEW;
/* Handle the positional case (N$) */
param_num++;
this_param = dprintf_DollarString(fmt, &fmt);
if(0 == this_param)
/* we got no positional, get the next counter */
this_param = param_num;
if(this_param > max_param)
max_param = this_param;
/*
* The parameter with number 'i' should be used. Next, we need
* to get SIZE and TYPE of the parameter. Add the information
* to our array.
*/
width = 0;
precision = 0;
/* Handle the flags */
while(dprintf_IsQualifierNoDollar(fmt)) {
#if defined(MP_HAVE_INT_EXTENSIONS)
if(!strncmp(fmt, "I32", 3)) {
flags |= FLAGS_LONG;
fmt += 3;
}
else if(!strncmp(fmt, "I64", 3)) {
flags |= FLAGS_LONGLONG;
fmt += 3;
}
else
#endif
switch(*fmt++) {
case ' ':
flags |= FLAGS_SPACE;
break;
case '+':
flags |= FLAGS_SHOWSIGN;
break;
case '-':
flags |= FLAGS_LEFT;
flags &= ~FLAGS_PAD_NIL;
break;
case '#':
flags |= FLAGS_ALT;
break;
case '.':
if('*' == *fmt) {
/* The precision is picked from a specified parameter */
flags |= FLAGS_PRECPARAM;
fmt++;
param_num++;
i = dprintf_DollarString(fmt, &fmt);
if(i)
precision = i;
else
precision = param_num;
if(precision > max_param)
max_param = precision;
}
else {
flags |= FLAGS_PREC;
precision = strtol(fmt, &fmt, 10);
}
break;
case 'h':
flags |= FLAGS_SHORT;
break;
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
#endif
break;
#endif
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 = strtol(fmt-1, &fmt, 10);
break;
case '*': /* Special case */
flags |= FLAGS_WIDTHPARAM;
param_num++;
i = dprintf_DollarString(fmt, &fmt);
if(i)
width = i;
else
width = param_num;
if(width > max_param)
max_param = width;
break;
case '\0':
fmt--;
default:
break;
}
} /* switch */
/* Handle the specifier */
i = this_param - 1;
if((i < 0) || (i >= MAX_PARAMETERS))
/* out of allowed range */
return 1;
switch (*fmt) {
case 'S':
flags |= FLAGS_ALT;
/* FALLTHROUGH */
case 's':
vto[i].type = FORMAT_STRING;
break;
case 'n':
vto[i].type = FORMAT_INTPTR;
break;
case 'p':
vto[i].type = FORMAT_PTR;
break;
case 'd': case 'i':
vto[i].type = FORMAT_INT;
break;
case 'u':
vto[i].type = FORMAT_INT;
flags |= FLAGS_UNSIGNED;
break;
case 'o':
vto[i].type = FORMAT_INT;
flags |= FLAGS_OCTAL;
break;
case 'x':
vto[i].type = FORMAT_INT;
flags |= FLAGS_HEX|FLAGS_UNSIGNED;
break;
case 'X':
vto[i].type = FORMAT_INT;
flags |= FLAGS_HEX|FLAGS_UPPER|FLAGS_UNSIGNED;
break;
case 'c':
vto[i].type = FORMAT_INT;
flags |= FLAGS_CHAR;
break;
case 'f':
vto[i].type = FORMAT_DOUBLE;
break;
case 'e':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATE;
break;
case 'E':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATE|FLAGS_UPPER;
break;
case 'g':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATG;
break;
case 'G':
vto[i].type = FORMAT_DOUBLE;
flags |= FLAGS_FLOATG|FLAGS_UPPER;
break;
default:
vto[i].type = FORMAT_UNKNOWN;
break;
} /* switch */
vto[i].flags = flags;
vto[i].width = width;
vto[i].precision = precision;
if(flags & FLAGS_WIDTHPARAM) {
/* we have the width specified from a parameter, so we make that
parameter's info setup properly */
long k = width - 1;
if((k < 0) || (k >= MAX_PARAMETERS))
/* out of allowed range */
return 1;
vto[i].width = k;
vto[k].type = FORMAT_WIDTH;
vto[k].flags = FLAGS_NEW;
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
}
if(flags & FLAGS_PRECPARAM) {
/* we have the precision specified from a parameter, so we make that
parameter's info setup properly */
long k = precision - 1;
if((k < 0) || (k >= MAX_PARAMETERS))
/* out of allowed range */
return 1;
vto[i].precision = k;
vto[k].type = FORMAT_WIDTH;
vto[k].flags = FLAGS_NEW;
/* can't use width or precision of width! */
vto[k].width = 0;
vto[k].precision = 0;
}
*endpos++ = fmt + ((*fmt == '\0') ? 0 : 1); /* end of this sequence */
}
}
/* Read the arg list parameters into our data list */
for(i = 0; i<max_param; i++) {
/* Width/precision arguments must be read before the main argument
they are attached to */
if(vto[i].flags & FLAGS_WIDTHPARAM) {
vto[vto[i].width].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
if(vto[i].flags & FLAGS_PRECPARAM) {
vto[vto[i].precision].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
switch(vto[i].type) {
case FORMAT_STRING:
vto[i].data.str = va_arg(arglist, char *);
break;
case FORMAT_INTPTR:
case FORMAT_UNKNOWN:
case FORMAT_PTR:
vto[i].data.ptr = va_arg(arglist, void *);
break;
case FORMAT_INT:
#ifdef HAVE_LONG_LONG_TYPE
if((vto[i].flags & FLAGS_LONGLONG) && (vto[i].flags & FLAGS_UNSIGNED))
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, mp_uintmax_t);
else if(vto[i].flags & FLAGS_LONGLONG)
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, mp_intmax_t);
else
#endif
{
if((vto[i].flags & FLAGS_LONG) && (vto[i].flags & FLAGS_UNSIGNED))
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, unsigned long);
else if(vto[i].flags & FLAGS_LONG)
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, long);
else if(vto[i].flags & FLAGS_UNSIGNED)
vto[i].data.num.as_unsigned =
(mp_uintmax_t)va_arg(arglist, unsigned int);
else
vto[i].data.num.as_signed =
(mp_intmax_t)va_arg(arglist, int);
}
break;
case FORMAT_DOUBLE:
vto[i].data.dnum = va_arg(arglist, double);
break;
case FORMAT_WIDTH:
/* Argument has been read. Silently convert it into an integer
* for later use
*/
vto[i].type = FORMAT_INT;
break;
default:
break;
}
}
return 0;
}
static int dprintf_formatf(
void *data, /* untouched by format(), just sent to the stream() function in
the second argument */
/* function pointer called for each output character */
int (*stream)(int, FILE *),
const char *format, /* %-formatted string */
va_list ap_save) /* list of parameters */
{
/* Base-36 digits for numbers. */
const char *digits = lower_digits;
/* Pointer into the format string. */
char *f;
/* Number of characters written. */
int done = 0;
long param; /* current parameter to read */
long param_num = 0; /* parameter counter */
struct va_stack vto[MAX_PARAMETERS];
char *endpos[MAX_PARAMETERS];
char **end;
char work[BUFFSIZE];
struct va_stack *p;
/* '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];
/* Do the actual %-code parsing */
if(dprintf_Pass1(format, vto, endpos, ap_save))
return -1;
end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
created for us */
f = (char *)format;
while(*f != '\0') {
/* Format spec modifiers. */
int is_alt;
/* Width of a field. */
long width;
/* Precision of a field. */
long prec;
/* Decimal integer is negative. */
int is_neg;
/* Base of a number to be written. */
unsigned long base;
/* Integral values to be written. */
mp_uintmax_t num;
/* Used to convert negative in positive. */
mp_intmax_t signed_num;
char *w;
if(*f != '%') {
/* This isn't a format spec, so write everything out until the next one
OR end of string is reached. */
do {
OUTCHAR(*f);
} while(*++f && ('%' != *f));
continue;
}
++f;
/* Check for "%%". Note that although the ANSI standard lists
'%' as a conversion specifier, it says "The complete format
specification shall be `%%'," so we can avoid all the width
and precision processing. */
if(*f == '%') {
++f;
OUTCHAR('%');
continue;
}
/* If this is a positional parameter, the position must follow immediately
after the %, thus create a %<num>$ sequence */
param = dprintf_DollarString(f, &f);
if(!param)
param = param_num;
else
--param;
param_num++; /* increase this always to allow "%2$s %1$s %s" and then the
third %s will pick the 3rd argument */
p = &vto[param];
/* pick up the specified width */
if(p->flags & FLAGS_WIDTHPARAM) {
width = (long)vto[p->width].data.num.as_signed;
param_num++; /* since the width is extracted from a parameter, we
must skip that to get to the next one properly */
if(width < 0) {
/* "A negative field width is taken as a '-' flag followed by a
positive field width." */
width = -width;
p->flags |= FLAGS_LEFT;
p->flags &= ~FLAGS_PAD_NIL;
}
}
else
width = p->width;
/* pick up the specified precision */
if(p->flags & FLAGS_PRECPARAM) {
prec = (long)vto[p->precision].data.num.as_signed;
param_num++; /* since the precision is extracted from a parameter, we
must skip that to get to the next one properly */
if(prec < 0)
/* "A negative precision is taken as if the precision were
omitted." */
prec = -1;
}
else if(p->flags & FLAGS_PREC)
prec = p->precision;
else
prec = -1;
is_alt = (p->flags & FLAGS_ALT) ? 1 : 0;
switch(p->type) {
case FORMAT_INT:
num = p->data.num.as_unsigned;
if(p->flags & FLAGS_CHAR) {
/* Character. */
if(!(p->flags & FLAGS_LEFT))
while(--width > 0)
OUTCHAR(' ');
OUTCHAR((char) num);
if(p->flags & FLAGS_LEFT)
while(--width > 0)
OUTCHAR(' ');
break;
}
if(p->flags & FLAGS_OCTAL) {
/* Octal unsigned integer. */
base = 8;
goto unsigned_number;
}
else if(p->flags & FLAGS_HEX) {
/* Hexadecimal unsigned integer. */
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
base = 16;
goto unsigned_number;
}
else if(p->flags & FLAGS_UNSIGNED) {
/* Decimal unsigned integer. */
base = 10;
goto unsigned_number;
}
/* Decimal integer. */
base = 10;
is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0;
if(is_neg) {
/* signed_num might fail to hold absolute negative minimum by 1 */
signed_num = p->data.num.as_signed + (mp_intmax_t)1;
signed_num = -signed_num;
num = (mp_uintmax_t)signed_num;
num += (mp_uintmax_t)1;
}
goto number;
unsigned_number:
/* Unsigned number of base BASE. */
is_neg = 0;
number:
/* Number of base BASE. */
/* Supply a default precision if none was given. */
if(prec == -1)
prec = 1;
/* Put the number in WORK. */
w = workend;
while(num > 0) {
*w-- = digits[num % base];
num /= base;
}
width -= (long)(workend - w);
prec -= (long)(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 || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE))
--width;
if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR(' ');
if(is_neg)
OUTCHAR('-');
else if(p->flags & FLAGS_SHOWSIGN)
OUTCHAR('+');
else if(p->flags & FLAGS_SPACE)
OUTCHAR(' ');
if(is_alt && base == 16) {
OUTCHAR('0');
if(p->flags & FLAGS_UPPER)
OUTCHAR('X');
else
OUTCHAR('x');
}
if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL))
while(width-- > 0)
OUTCHAR('0');
/* Write the number. */
while(++w <= workend) {
OUTCHAR(*w);
}
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
break;
case FORMAT_STRING:
/* String. */
{
static const char null[] = "(nil)";
const char *str;
size_t len;
str = (char *) p->data.str;
if(!str) {
/* Write null[] if there's space. */
if(prec == -1 || prec >= (long) sizeof(null) - 1) {
str = null;
len = sizeof(null) - 1;
/* Disable quotes around (nil) */
p->flags &= (~FLAGS_ALT);
}
else {
str = "";
len = 0;
}
}
else if(prec != -1)
len = (size_t)prec;
else
len = strlen(str);
width -= (len > LONG_MAX) ? LONG_MAX : (long)len;
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
if(!(p->flags&FLAGS_LEFT))
while(width-- > 0)
OUTCHAR(' ');
for(; len && *str; len--)
OUTCHAR(*str++);
if(p->flags&FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
if(p->flags & FLAGS_ALT)
OUTCHAR('"');
}
break;
case FORMAT_PTR:
/* Generic pointer. */
{
void *ptr;
ptr = (void *) p->data.ptr;
if(ptr != NULL) {
/* If the pointer is not NULL, write it as a %#x spec. */
base = 16;
digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits;
is_alt = 1;
num = (size_t) ptr;
is_neg = 0;
goto number;
}
else {
/* Write "(nil)" for a nil pointer. */
static const char strnil[] = "(nil)";
const char *point;
width -= (long)(sizeof(strnil) - 1);
if(p->flags & FLAGS_LEFT)
while(width-- > 0)
OUTCHAR(' ');
for(point = strnil; *point != '\0'; ++point)
OUTCHAR(*point);
if(!(p->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;
width = -1;
if(p->flags & FLAGS_WIDTH)
width = p->width;
else if(p->flags & FLAGS_WIDTHPARAM)
width = (long)vto[p->width].data.num.as_signed;
prec = -1;
if(p->flags & FLAGS_PREC)
prec = p->precision;
else if(p->flags & FLAGS_PRECPARAM)
prec = (long)vto[p->precision].data.num.as_signed;
if(p->flags & FLAGS_LEFT)
*fptr++ = '-';
if(p->flags & FLAGS_SHOWSIGN)
*fptr++ = '+';
if(p->flags & FLAGS_SPACE)
*fptr++ = ' ';
if(p->flags & FLAGS_ALT)
*fptr++ = '#';
*fptr = 0;
if(width >= 0) {
if(width >= (long)sizeof(work))
width = sizeof(work)-1;
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, "%ld", width);
fptr += len;
left -= len;
}
if(prec >= 0) {
/* for each digit in the integer part, we can have one less
precision */
size_t maxprec = sizeof(work) - 2;
double val = p->data.dnum;
if(width > 0 && prec <= width)
maxprec -= width;
while(val >= 10.0) {
val /= 10;
maxprec--;
}
if(prec > (long)maxprec)
prec = (long)maxprec-1;
if(prec < 0)
prec = 0;
/* RECURSIVE USAGE */
len = curl_msnprintf(fptr, left, ".%ld", prec);
fptr += len;
}
if(p->flags & FLAGS_LONG)
*fptr++ = 'l';
if(p->flags & FLAGS_FLOATE)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e');
else if(p->flags & FLAGS_FLOATG)
*fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g');
else
*fptr++ = 'f';
*fptr = 0; /* and a final zero termination */
/* NOTE NOTE NOTE!! Not all sprintf implementations return number of
output characters */
(sprintf)(work, formatbuf, p->data.dnum);
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(p->flags & FLAGS_LONGLONG)
*(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done;
else
#endif
if(p->flags & FLAGS_LONG)
*(long *) p->data.ptr = (long)done;
else if(!(p->flags & FLAGS_SHORT))
*(int *) p->data.ptr = (int)done;
else
*(short *) p->data.ptr = (short)done;
break;
default:
break;
}
f = *end++; /* goto end of %-code */
}
return done;
}
/* fputc() look-alike */
static int addbyter(int output, FILE *data)
{
struct nsprintf *infop = (struct nsprintf *)data;
unsigned char outc = (unsigned char)output;
if(infop->length < infop->max) {
/* only do this if we haven't reached max length yet */
infop->buffer[0] = outc; /* store */
infop->buffer++; /* increase pointer */
infop->length++; /* we are now one byte larger */
return outc; /* 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 = dprintf_formatf(&info, addbyter, format, ap_save);
if((retcode != -1) && info.max) {
/* we terminate this with a zero byte */
if(info.max == info.length) {
/* we're at maximum, scrap the last letter */
info.buffer[-1] = 0;
retcode--; /* don't count the nul byte */
}
else
info.buffer[0] = 0;
}
return retcode;
}
int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
{
int retcode;
va_list ap_save; /* argument pointer */
va_start(ap_save, format);
retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save);
va_end(ap_save);
return retcode;
}
/* fputc() look-alike */
static int alloc_addbyter(int output, FILE *data)
{
struct asprintf *infop = (struct asprintf *)data;
unsigned char outc = (unsigned char)output;
if(Curl_dyn_addn(infop->b, &outc, 1)) {
infop->fail = 1;
return -1; /* fail */
}
return outc; /* fputc() returns like this on success */
}
extern int Curl_dyn_vprintf(struct dynbuf *dyn,
const char *format, va_list ap_save);
/* appends the formatted string, returns 0 on success, 1 on error */
int Curl_dyn_vprintf(struct dynbuf *dyn, const char *format, va_list ap_save)
{
int retcode;
struct asprintf info;
info.b = dyn;
info.fail = 0;
retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
if((-1 == retcode) || info.fail) {
Curl_dyn_free(info.b);
return 1;
}
return 0;
}
char *curl_mvaprintf(const char *format, va_list ap_save)
{
int retcode;
struct asprintf info;
struct dynbuf dyn;
info.b = &dyn;
Curl_dyn_init(info.b, DYN_APRINTF);
info.fail = 0;
retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save);
if((-1 == retcode) || info.fail) {
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(int output, FILE *data)
{
char **buffer = (char **)data;
unsigned char outc = (unsigned char)output;
**buffer = outc;
(*buffer)++;
return outc; /* act like fputc() ! */
}
int curl_msprintf(char *buffer, const char *format, ...)
{
va_list ap_save; /* argument pointer */
int retcode;
va_start(ap_save, format);
retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
va_end(ap_save);
*buffer = 0; /* we terminate this with a zero byte */
return retcode;
}
int curl_mprintf(const char *format, ...)
{
int retcode;
va_list ap_save; /* argument pointer */
va_start(ap_save, format);
retcode = dprintf_formatf(stdout, fputc, 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 = dprintf_formatf(whereto, fputc, format, ap_save);
va_end(ap_save);
return retcode;
}
int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
{
int retcode;
retcode = dprintf_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 dprintf_formatf(stdout, fputc, format, ap_save);
}
int curl_mvfprintf(FILE *whereto, const char *format, va_list ap_save)
{
return dprintf_formatf(whereto, fputc, format, ap_save);
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/x509asn1.h | #ifndef HEADER_CURL_X509ASN1_H
#define HEADER_CURL_X509ASN1_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \
defined(USE_WOLFSSL) || defined(USE_SCHANNEL) || defined(USE_SECTRANSP)
#include "urldata.h"
/*
* Constants.
*/
/* Largest supported ASN.1 structure. */
#define CURL_ASN1_MAX ((size_t) 0x40000) /* 256K */
/* ASN.1 classes. */
#define CURL_ASN1_UNIVERSAL 0
#define CURL_ASN1_APPLICATION 1
#define CURL_ASN1_CONTEXT_SPECIFIC 2
#define CURL_ASN1_PRIVATE 3
/* ASN.1 types. */
#define CURL_ASN1_BOOLEAN 1
#define CURL_ASN1_INTEGER 2
#define CURL_ASN1_BIT_STRING 3
#define CURL_ASN1_OCTET_STRING 4
#define CURL_ASN1_NULL 5
#define CURL_ASN1_OBJECT_IDENTIFIER 6
#define CURL_ASN1_OBJECT_DESCRIPTOR 7
#define CURL_ASN1_INSTANCE_OF 8
#define CURL_ASN1_REAL 9
#define CURL_ASN1_ENUMERATED 10
#define CURL_ASN1_EMBEDDED 11
#define CURL_ASN1_UTF8_STRING 12
#define CURL_ASN1_RELATIVE_OID 13
#define CURL_ASN1_SEQUENCE 16
#define CURL_ASN1_SET 17
#define CURL_ASN1_NUMERIC_STRING 18
#define CURL_ASN1_PRINTABLE_STRING 19
#define CURL_ASN1_TELETEX_STRING 20
#define CURL_ASN1_VIDEOTEX_STRING 21
#define CURL_ASN1_IA5_STRING 22
#define CURL_ASN1_UTC_TIME 23
#define CURL_ASN1_GENERALIZED_TIME 24
#define CURL_ASN1_GRAPHIC_STRING 25
#define CURL_ASN1_VISIBLE_STRING 26
#define CURL_ASN1_GENERAL_STRING 27
#define CURL_ASN1_UNIVERSAL_STRING 28
#define CURL_ASN1_CHARACTER_STRING 29
#define CURL_ASN1_BMP_STRING 30
/*
* Types.
*/
/* ASN.1 parsed element. */
struct Curl_asn1Element {
const char *header; /* Pointer to header byte. */
const char *beg; /* Pointer to element data. */
const char *end; /* Pointer to 1st byte after element. */
unsigned char class; /* ASN.1 element class. */
unsigned char tag; /* ASN.1 element tag. */
bool constructed; /* Element is constructed. */
};
/* ASN.1 OID table entry. */
struct Curl_OID {
const char *numoid; /* Dotted-numeric OID. */
const char *textoid; /* OID name. */
};
/* X509 certificate: RFC 5280. */
struct Curl_X509certificate {
struct Curl_asn1Element certificate;
struct Curl_asn1Element version;
struct Curl_asn1Element serialNumber;
struct Curl_asn1Element signatureAlgorithm;
struct Curl_asn1Element signature;
struct Curl_asn1Element issuer;
struct Curl_asn1Element notBefore;
struct Curl_asn1Element notAfter;
struct Curl_asn1Element subject;
struct Curl_asn1Element subjectPublicKeyInfo;
struct Curl_asn1Element subjectPublicKeyAlgorithm;
struct Curl_asn1Element subjectPublicKey;
struct Curl_asn1Element issuerUniqueID;
struct Curl_asn1Element subjectUniqueID;
struct Curl_asn1Element extensions;
};
/*
* Prototypes.
*/
const char *Curl_getASN1Element(struct Curl_asn1Element *elem,
const char *beg, const char *end);
const char *Curl_ASN1tostr(struct Curl_asn1Element *elem, int type);
const char *Curl_DNtostr(struct Curl_asn1Element *dn);
int Curl_parseX509(struct Curl_X509certificate *cert,
const char *beg, const char *end);
CURLcode Curl_extract_certinfo(struct Curl_easy *data, int certnum,
const char *beg, const char *end);
CURLcode Curl_verifyhost(struct Curl_easy *data, struct connectdata *conn,
const char *beg, const char *end);
#endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_WOLFSSL or USE_SCHANNEL
* or USE_SECTRANSP */
#endif /* HEADER_CURL_X509ASN1_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/ftp.h | #ifndef HEADER_CURL_FTP_H
#define HEADER_CURL_FTP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "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
***************************************************************************/
typedef enum {
FTP_STOP, /* do nothing state, stops the state machine */
FTP_WAIT220, /* waiting for the initial 220 response immediately after
a connect */
FTP_AUTH,
FTP_USER,
FTP_PASS,
FTP_ACCT,
FTP_PBSZ,
FTP_PROT,
FTP_CCC,
FTP_PWD,
FTP_SYST,
FTP_NAMEFMT,
FTP_QUOTE, /* waiting for a response to a command sent in a quote list */
FTP_RETR_PREQUOTE,
FTP_STOR_PREQUOTE,
FTP_POSTQUOTE,
FTP_CWD, /* change dir */
FTP_MKD, /* if the dir didn't exist */
FTP_MDTM, /* to figure out the datestamp */
FTP_TYPE, /* to set type when doing a head-like request */
FTP_LIST_TYPE, /* set type when about to do a dir list */
FTP_RETR_TYPE, /* set type when about to RETR a file */
FTP_STOR_TYPE, /* set type when about to STOR a file */
FTP_SIZE, /* get the remote file's size for head-like request */
FTP_RETR_SIZE, /* get the remote file's size for RETR */
FTP_STOR_SIZE, /* get the size for STOR */
FTP_REST, /* when used to check if the server supports it in head-like */
FTP_RETR_REST, /* when asking for "resume" in for RETR */
FTP_PORT, /* generic state for PORT, LPRT and EPRT, check count1 */
FTP_PRET, /* generic state for PRET RETR, PRET STOR and PRET LIST/NLST */
FTP_PASV, /* generic state for PASV and EPSV, check count1 */
FTP_LIST, /* generic state for LIST, NLST or a custom list command */
FTP_RETR,
FTP_STOR, /* generic state for STOR and APPE */
FTP_QUIT,
FTP_LAST /* never used */
} ftpstate;
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 *entrypath; /* the PWD reply when we logged on */
char *file; /* url-decoded file name (or path) */
char **dirs; /* realloc()ed array for path components */
int dirdepth; /* number of entries used in the 'dirs' array */
bool 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. */
bool 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() */
bool cwddone; /* if it has been determined that the proper CWD combo
already has been done */
int cwdcount; /* number of CWD commands issued */
bool cwdfail; /* set TRUE if a CWD command fails, as then we must prevent
caching the current directory */
bool wait_data_conn; /* this is set TRUE if data connection is waited */
/* newhost is the (allocated) IP addr or host name to connect the data
connection to */
unsigned short newport;
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) */
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 */
ftpstate state; /* always use ftp.c:state() to change state! */
ftpstate state_saved; /* transfer type saved to be reloaded after
data connection is established */
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 */
};
#define DEFAULT_ACCEPT_TIMEOUT 60000 /* milliseconds == one minute */
#endif /* HEADER_CURL_FTP_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_config.h.cmake | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* lib/curl_config.h.in. Generated somehow by cmake. */
/* when building libcurl itself */
#cmakedefine BUILDING_LIBCURL 1
/* Location of default ca bundle */
#cmakedefine CURL_CA_BUNDLE "${CURL_CA_BUNDLE}"
/* define "1" to use built-in ca store of TLS backend */
#cmakedefine CURL_CA_FALLBACK 1
/* Location of default ca path */
#cmakedefine CURL_CA_PATH "${CURL_CA_PATH}"
/* disables alt-svc */
#cmakedefine CURL_DISABLE_ALTSVC 1
/* disables cookies support */
#cmakedefine CURL_DISABLE_COOKIES 1
/* disables cryptographic authentication */
#cmakedefine CURL_DISABLE_CRYPTO_AUTH 1
/* disables DICT */
#cmakedefine CURL_DISABLE_DICT 1
/* disables DNS-over-HTTPS */
#cmakedefine CURL_DISABLE_DOH 1
/* disables FILE */
#cmakedefine CURL_DISABLE_FILE 1
/* disables FTP */
#cmakedefine CURL_DISABLE_FTP 1
/* disables GOPHER */
#cmakedefine CURL_DISABLE_GOPHER 1
/* disables HSTS support */
#cmakedefine CURL_DISABLE_HSTS 1
/* disables HTTP */
#cmakedefine CURL_DISABLE_HTTP 1
/* disables IMAP */
#cmakedefine CURL_DISABLE_IMAP 1
/* disables LDAP */
#cmakedefine CURL_DISABLE_LDAP 1
/* disables LDAPS */
#cmakedefine CURL_DISABLE_LDAPS 1
/* disables --libcurl option from the curl tool */
#cmakedefine CURL_DISABLE_LIBCURL_OPTION 1
/* disables MIME support */
#cmakedefine CURL_DISABLE_MIME 1
/* disables MQTT */
#cmakedefine CURL_DISABLE_MQTT 1
/* disables netrc parser */
#cmakedefine CURL_DISABLE_NETRC 1
/* disables NTLM support */
#cmakedefine CURL_DISABLE_NTLM 1
/* disables date parsing */
#cmakedefine CURL_DISABLE_PARSEDATE 1
/* disables POP3 */
#cmakedefine CURL_DISABLE_POP3 1
/* disables built-in progress meter */
#cmakedefine CURL_DISABLE_PROGRESS_METER 1
/* disables proxies */
#cmakedefine CURL_DISABLE_PROXY 1
/* disables RTSP */
#cmakedefine CURL_DISABLE_RTSP 1
/* disables SMB */
#cmakedefine CURL_DISABLE_SMB 1
/* disables SMTP */
#cmakedefine CURL_DISABLE_SMTP 1
/* disables use of socketpair for curl_multi_poll */
#cmakedefine CURL_DISABLE_SOCKETPAIR 1
/* disables TELNET */
#cmakedefine CURL_DISABLE_TELNET 1
/* disables TFTP */
#cmakedefine CURL_DISABLE_TFTP 1
/* disables verbose strings */
#cmakedefine CURL_DISABLE_VERBOSE_STRINGS 1
/* to make a symbol visible */
#cmakedefine CURL_EXTERN_SYMBOL ${CURL_EXTERN_SYMBOL}
/* Ensure using CURL_EXTERN_SYMBOL is possible */
#ifndef CURL_EXTERN_SYMBOL
#define CURL_EXTERN_SYMBOL
#endif
/* Allow SMB to work on Windows */
#cmakedefine USE_WIN32_CRYPTO 1
/* Use Windows LDAP implementation */
#cmakedefine USE_WIN32_LDAP 1
/* when not building a shared library */
#cmakedefine CURL_STATICLIB 1
/* your Entropy Gathering Daemon socket pathname */
#cmakedefine EGD_SOCKET ${EGD_SOCKET}
/* Define if you want to enable IPv6 support */
#cmakedefine ENABLE_IPV6 1
/* Define to 1 if you have the alarm function. */
#cmakedefine HAVE_ALARM 1
/* Define to 1 if you have the <alloca.h> header file. */
#cmakedefine HAVE_ALLOCA_H 1
/* Define to 1 if you have the <arpa/inet.h> header file. */
#cmakedefine HAVE_ARPA_INET_H 1
/* Define to 1 if you have the <arpa/tftp.h> header file. */
#cmakedefine HAVE_ARPA_TFTP_H 1
/* Define to 1 if you have the <assert.h> header file. */
#cmakedefine HAVE_ASSERT_H 1
/* Define to 1 if you have the `basename' function. */
#cmakedefine HAVE_BASENAME 1
/* Define to 1 if bool is an available type. */
#cmakedefine HAVE_BOOL_T 1
/* Define to 1 if you have the __builtin_available function. */
#cmakedefine HAVE_BUILTIN_AVAILABLE 1
/* Define to 1 if you have the clock_gettime function and monotonic timer. */
#cmakedefine HAVE_CLOCK_GETTIME_MONOTONIC 1
/* Define to 1 if you have the `closesocket' function. */
#cmakedefine HAVE_CLOSESOCKET 1
/* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */
#cmakedefine HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H 1
/* Define to 1 if you have the <errno.h> header file. */
#cmakedefine HAVE_ERRNO_H 1
/* Define to 1 if you have the fcntl function. */
#cmakedefine HAVE_FCNTL 1
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine HAVE_FCNTL_H 1
/* Define to 1 if you have a working fcntl O_NONBLOCK function. */
#cmakedefine HAVE_FCNTL_O_NONBLOCK 1
/* Define to 1 if you have the freeaddrinfo function. */
#cmakedefine HAVE_FREEADDRINFO 1
/* Define to 1 if you have the ftruncate function. */
#cmakedefine HAVE_FTRUNCATE 1
/* Define to 1 if you have a working getaddrinfo function. */
#cmakedefine HAVE_GETADDRINFO 1
/* Define to 1 if you have the `geteuid' function. */
#cmakedefine HAVE_GETEUID 1
/* Define to 1 if you have the `getppid' function. */
#cmakedefine HAVE_GETPPID 1
/* Define to 1 if you have the gethostbyname function. */
#cmakedefine HAVE_GETHOSTBYNAME 1
/* Define to 1 if you have the gethostbyname_r function. */
#cmakedefine HAVE_GETHOSTBYNAME_R 1
/* gethostbyname_r() takes 3 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_3 1
/* gethostbyname_r() takes 5 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_5 1
/* gethostbyname_r() takes 6 args */
#cmakedefine HAVE_GETHOSTBYNAME_R_6 1
/* Define to 1 if you have the gethostname function. */
#cmakedefine HAVE_GETHOSTNAME 1
/* Define to 1 if you have a working getifaddrs function. */
#cmakedefine HAVE_GETIFADDRS 1
/* Define to 1 if you have the `getpass_r' function. */
#cmakedefine HAVE_GETPASS_R 1
/* Define to 1 if you have the `getppid' function. */
#cmakedefine HAVE_GETPPID 1
/* Define to 1 if you have the `getprotobyname' function. */
#cmakedefine HAVE_GETPROTOBYNAME 1
/* Define to 1 if you have the `getpeername' function. */
#cmakedefine HAVE_GETPEERNAME 1
/* Define to 1 if you have the `getsockname' function. */
#cmakedefine HAVE_GETSOCKNAME 1
/* Define to 1 if you have the `if_nametoindex' function. */
#cmakedefine HAVE_IF_NAMETOINDEX 1
/* Define to 1 if you have the `getpwuid' function. */
#cmakedefine HAVE_GETPWUID 1
/* Define to 1 if you have the `getpwuid_r' function. */
#cmakedefine HAVE_GETPWUID_R 1
/* Define to 1 if you have the `getrlimit' function. */
#cmakedefine HAVE_GETRLIMIT 1
/* Define to 1 if you have the `gettimeofday' function. */
#cmakedefine HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have a working glibc-style strerror_r function. */
#cmakedefine HAVE_GLIBC_STRERROR_R 1
/* Define to 1 if you have a working gmtime_r function. */
#cmakedefine HAVE_GMTIME_R 1
/* if you have the gssapi libraries */
#cmakedefine HAVE_GSSAPI 1
/* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */
#cmakedefine HAVE_GSSAPI_GSSAPI_GENERIC_H 1
/* Define to 1 if you have the <gssapi/gssapi.h> header file. */
#cmakedefine HAVE_GSSAPI_GSSAPI_H 1
/* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */
#cmakedefine HAVE_GSSAPI_GSSAPI_KRB5_H 1
/* if you have the GNU gssapi libraries */
#cmakedefine HAVE_GSSGNU 1
/* if you have the Heimdal gssapi libraries */
#cmakedefine HAVE_GSSHEIMDAL 1
/* if you have the MIT gssapi libraries */
#cmakedefine HAVE_GSSMIT 1
/* Define to 1 if you have the `idna_strerror' function. */
#cmakedefine HAVE_IDNA_STRERROR 1
/* Define to 1 if you have the `idn_free' function. */
#cmakedefine HAVE_IDN_FREE 1
/* Define to 1 if you have the <idn-free.h> header file. */
#cmakedefine HAVE_IDN_FREE_H 1
/* Define to 1 if you have the <ifaddrs.h> header file. */
#cmakedefine HAVE_IFADDRS_H 1
/* Define to 1 if you have the `inet_addr' function. */
#cmakedefine HAVE_INET_ADDR 1
/* Define to 1 if you have a IPv6 capable working inet_ntop function. */
#cmakedefine HAVE_INET_NTOP 1
/* Define to 1 if you have a IPv6 capable working inet_pton function. */
#cmakedefine HAVE_INET_PTON 1
/* Define to 1 if symbol `sa_family_t' exists */
#cmakedefine HAVE_SA_FAMILY_T 1
/* Define to 1 if symbol `ADDRESS_FAMILY' exists */
#cmakedefine HAVE_ADDRESS_FAMILY 1
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine HAVE_INTTYPES_H 1
/* Define to 1 if you have the ioctl function. */
#cmakedefine HAVE_IOCTL 1
/* Define to 1 if you have the ioctlsocket function. */
#cmakedefine HAVE_IOCTLSOCKET 1
/* Define to 1 if you have the IoctlSocket camel case function. */
#cmakedefine HAVE_IOCTLSOCKET_CAMEL 1
/* Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
*/
#cmakedefine HAVE_IOCTLSOCKET_CAMEL_FIONBIO 1
/* Define to 1 if you have a working ioctlsocket FIONBIO function. */
#cmakedefine HAVE_IOCTLSOCKET_FIONBIO 1
/* Define to 1 if you have a working ioctl FIONBIO function. */
#cmakedefine HAVE_IOCTL_FIONBIO 1
/* Define to 1 if you have a working ioctl SIOCGIFADDR function. */
#cmakedefine HAVE_IOCTL_SIOCGIFADDR 1
/* Define to 1 if you have the <io.h> header file. */
#cmakedefine HAVE_IO_H 1
/* if you have the Kerberos4 libraries (including -ldes) */
#cmakedefine HAVE_KRB4 1
/* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */
#cmakedefine HAVE_KRB_GET_OUR_IP_FOR_REALM 1
/* Define to 1 if you have the <krb.h> header file. */
#cmakedefine HAVE_KRB_H 1
/* Define to 1 if you have the lber.h header file. */
#cmakedefine HAVE_LBER_H 1
/* Define to 1 if you have the ldapssl.h header file. */
#cmakedefine HAVE_LDAPSSL_H 1
/* Define to 1 if you have the ldap.h header file. */
#cmakedefine HAVE_LDAP_H 1
/* Use LDAPS implementation */
#cmakedefine HAVE_LDAP_SSL 1
/* Define to 1 if you have the ldap_ssl.h header file. */
#cmakedefine HAVE_LDAP_SSL_H 1
/* Define to 1 if you have the `ldap_url_parse' function. */
#cmakedefine HAVE_LDAP_URL_PARSE 1
/* Define to 1 if you have the <libgen.h> header file. */
#cmakedefine HAVE_LIBGEN_H 1
/* Define to 1 if you have the `idn2' library (-lidn2). */
#cmakedefine HAVE_LIBIDN2 1
/* Define to 1 if you have the idn2.h header file. */
#cmakedefine HAVE_IDN2_H 1
/* Define to 1 if you have the `resolv' library (-lresolv). */
#cmakedefine HAVE_LIBRESOLV 1
/* Define to 1 if you have the `resolve' library (-lresolve). */
#cmakedefine HAVE_LIBRESOLVE 1
/* Define to 1 if you have the `socket' library (-lsocket). */
#cmakedefine HAVE_LIBSOCKET 1
/* Define to 1 if you have the `ssh2' library (-lssh2). */
#cmakedefine HAVE_LIBSSH2 1
/* Define to 1 if you have the <libssh2.h> header file. */
#cmakedefine HAVE_LIBSSH2_H 1
/* Define to 1 if you have the <libssh/libssh.h> header file. */
#cmakedefine HAVE_LIBSSH_LIBSSH_H 1
/* if zlib is available */
#cmakedefine HAVE_LIBZ 1
/* if brotli is available */
#cmakedefine HAVE_BROTLI 1
/* if zstd is available */
#cmakedefine HAVE_ZSTD 1
/* if your compiler supports LL */
#cmakedefine HAVE_LL 1
/* Define to 1 if you have the <locale.h> header file. */
#cmakedefine HAVE_LOCALE_H 1
/* Define to 1 if you have a working localtime_r function. */
#cmakedefine HAVE_LOCALTIME_R 1
/* Define to 1 if the compiler supports the 'long long' data type. */
#cmakedefine HAVE_LONGLONG 1
/* Define to 1 if you have the malloc.h header file. */
#cmakedefine HAVE_MALLOC_H 1
/* Define to 1 if you have the <memory.h> header file. */
#cmakedefine HAVE_MEMORY_H 1
/* Define to 1 if you have the MSG_NOSIGNAL flag. */
#cmakedefine HAVE_MSG_NOSIGNAL 1
/* Define to 1 if you have the <netdb.h> header file. */
#cmakedefine HAVE_NETDB_H 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#cmakedefine HAVE_NETINET_IN_H 1
/* Define to 1 if you have the <netinet/tcp.h> header file. */
#cmakedefine HAVE_NETINET_TCP_H 1
/* Define to 1 if you have the <linux/tcp.h> header file. */
#cmakedefine HAVE_LINUX_TCP_H 1
/* Define to 1 if you have the <net/if.h> header file. */
#cmakedefine HAVE_NET_IF_H 1
/* Define to 1 if NI_WITHSCOPEID exists and works. */
#cmakedefine HAVE_NI_WITHSCOPEID 1
/* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE */
#cmakedefine HAVE_OLD_GSSMIT 1
/* Define to 1 if you have the <openssl/crypto.h> header file. */
#cmakedefine HAVE_OPENSSL_CRYPTO_H 1
/* Define to 1 if you have the <openssl/err.h> header file. */
#cmakedefine HAVE_OPENSSL_ERR_H 1
/* Define to 1 if you have the <openssl/pem.h> header file. */
#cmakedefine HAVE_OPENSSL_PEM_H 1
/* Define to 1 if you have the <openssl/pkcs12.h> header file. */
#cmakedefine HAVE_OPENSSL_PKCS12_H 1
/* Define to 1 if you have the <openssl/rsa.h> header file. */
#cmakedefine HAVE_OPENSSL_RSA_H 1
/* Define to 1 if you have the <openssl/ssl.h> header file. */
#cmakedefine HAVE_OPENSSL_SSL_H 1
/* Define to 1 if you have the <openssl/x509.h> header file. */
#cmakedefine HAVE_OPENSSL_X509_H 1
/* Define to 1 if you have the <pem.h> header file. */
#cmakedefine HAVE_PEM_H 1
/* Define to 1 if you have the `pipe' function. */
#cmakedefine HAVE_PIPE 1
/* Define to 1 if you have a working poll function. */
#cmakedefine HAVE_POLL 1
/* If you have a fine poll */
#cmakedefine HAVE_POLL_FINE 1
/* Define to 1 if you have the <poll.h> header file. */
#cmakedefine HAVE_POLL_H 1
/* Define to 1 if you have a working POSIX-style strerror_r function. */
#cmakedefine HAVE_POSIX_STRERROR_R 1
/* Define to 1 if you have the <pthread.h> header file */
#cmakedefine HAVE_PTHREAD_H 1
/* Define to 1 if you have the <pwd.h> header file. */
#cmakedefine HAVE_PWD_H 1
/* Define to 1 if you have the `RAND_egd' function. */
#cmakedefine HAVE_RAND_EGD 1
/* Define to 1 if you have the `RAND_screen' function. */
#cmakedefine HAVE_RAND_SCREEN 1
/* Define to 1 if you have the `RAND_status' function. */
#cmakedefine HAVE_RAND_STATUS 1
/* Define to 1 if you have the recv function. */
#cmakedefine HAVE_RECV 1
/* Define to 1 if you have the recvfrom function. */
#cmakedefine HAVE_RECVFROM 1
/* Define to 1 if you have the select function. */
#cmakedefine HAVE_SELECT 1
/* Define to 1 if you have the send function. */
#cmakedefine HAVE_SEND 1
/* Define to 1 if you have the 'fsetxattr' function. */
#cmakedefine HAVE_FSETXATTR 1
/* fsetxattr() takes 5 args */
#cmakedefine HAVE_FSETXATTR_5 1
/* fsetxattr() takes 6 args */
#cmakedefine HAVE_FSETXATTR_6 1
/* Define to 1 if you have the <setjmp.h> header file. */
#cmakedefine HAVE_SETJMP_H 1
/* Define to 1 if you have the `setlocale' function. */
#cmakedefine HAVE_SETLOCALE 1
/* Define to 1 if you have the `setmode' function. */
#cmakedefine HAVE_SETMODE 1
/* Define to 1 if you have the `setrlimit' function. */
#cmakedefine HAVE_SETRLIMIT 1
/* Define to 1 if you have the setsockopt function. */
#cmakedefine HAVE_SETSOCKOPT 1
/* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */
#cmakedefine HAVE_SETSOCKOPT_SO_NONBLOCK 1
/* Define to 1 if you have the sigaction function. */
#cmakedefine HAVE_SIGACTION 1
/* Define to 1 if you have the siginterrupt function. */
#cmakedefine HAVE_SIGINTERRUPT 1
/* Define to 1 if you have the signal function. */
#cmakedefine HAVE_SIGNAL 1
/* Define to 1 if you have the <signal.h> header file. */
#cmakedefine HAVE_SIGNAL_H 1
/* Define to 1 if you have the sigsetjmp function or macro. */
#cmakedefine HAVE_SIGSETJMP 1
/* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */
#cmakedefine HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/* Define to 1 if you have the `socket' function. */
#cmakedefine HAVE_SOCKET 1
/* Define to 1 if you have the <ssl.h> header file. */
#cmakedefine HAVE_SSL_H 1
/* Define to 1 if you have the <stdbool.h> header file. */
#cmakedefine HAVE_STDBOOL_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H 1
/* Define to 1 if you have the <stdio.h> header file. */
#cmakedefine HAVE_STDIO_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#cmakedefine HAVE_STDLIB_H 1
/* Define to 1 if you have the strcasecmp function. */
#cmakedefine HAVE_STRCASECMP 1
/* Define to 1 if you have the strcasestr function. */
#cmakedefine HAVE_STRCASESTR 1
/* Define to 1 if you have the strcmpi function. */
#cmakedefine HAVE_STRCMPI 1
/* Define to 1 if you have the strdup function. */
#cmakedefine HAVE_STRDUP 1
/* Define to 1 if you have the strerror_r function. */
#cmakedefine HAVE_STRERROR_R 1
/* Define to 1 if you have the stricmp function. */
#cmakedefine HAVE_STRICMP 1
/* Define to 1 if you have the <strings.h> header file. */
#cmakedefine HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#cmakedefine HAVE_STRING_H 1
/* Define to 1 if you have the strncmpi function. */
#cmakedefine HAVE_STRNCMPI 1
/* Define to 1 if you have the strnicmp function. */
#cmakedefine HAVE_STRNICMP 1
/* Define to 1 if you have the <stropts.h> header file. */
#cmakedefine HAVE_STROPTS_H 1
/* Define to 1 if you have the strstr function. */
#cmakedefine HAVE_STRSTR 1
/* Define to 1 if you have the strtok_r function. */
#cmakedefine HAVE_STRTOK_R 1
/* Define to 1 if you have the strtoll function. */
#cmakedefine HAVE_STRTOLL 1
/* if struct sockaddr_storage is defined */
#cmakedefine HAVE_STRUCT_SOCKADDR_STORAGE 1
/* Define to 1 if you have the timeval struct. */
#cmakedefine HAVE_STRUCT_TIMEVAL 1
/* Define to 1 if you have the <sys/filio.h> header file. */
#cmakedefine HAVE_SYS_FILIO_H 1
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/poll.h> header file. */
#cmakedefine HAVE_SYS_POLL_H 1
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H 1
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/socket.h> header file. */
#cmakedefine HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/sockio.h> header file. */
#cmakedefine HAVE_SYS_SOCKIO_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/uio.h> header file. */
#cmakedefine HAVE_SYS_UIO_H 1
/* Define to 1 if you have the <sys/un.h> header file. */
#cmakedefine HAVE_SYS_UN_H 1
/* Define to 1 if you have the <sys/utime.h> header file. */
#cmakedefine HAVE_SYS_UTIME_H 1
/* Define to 1 if you have the <termios.h> header file. */
#cmakedefine HAVE_TERMIOS_H 1
/* Define to 1 if you have the <termio.h> header file. */
#cmakedefine HAVE_TERMIO_H 1
/* Define to 1 if you have the <time.h> header file. */
#cmakedefine HAVE_TIME_H 1
/* Define to 1 if you have the <tld.h> header file. */
#cmakedefine HAVE_TLD_H 1
/* Define to 1 if you have the `tld_strerror' function. */
#cmakedefine HAVE_TLD_STRERROR 1
/* Define to 1 if you have the `uname' function. */
#cmakedefine HAVE_UNAME 1
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H 1
/* Define to 1 if you have the `utime' function. */
#cmakedefine HAVE_UTIME 1
/* Define to 1 if you have the `utimes' function. */
#cmakedefine HAVE_UTIMES 1
/* Define to 1 if you have the <utime.h> header file. */
#cmakedefine HAVE_UTIME_H 1
/* Define to 1 if compiler supports C99 variadic macro style. */
#cmakedefine HAVE_VARIADIC_MACROS_C99 1
/* Define to 1 if compiler supports old gcc variadic macro style. */
#cmakedefine HAVE_VARIADIC_MACROS_GCC 1
/* Define to 1 if you have the winber.h header file. */
#cmakedefine HAVE_WINBER_H 1
/* Define to 1 if you have the windows.h header file. */
#cmakedefine HAVE_WINDOWS_H 1
/* Define to 1 if you have the winldap.h header file. */
#cmakedefine HAVE_WINLDAP_H 1
/* Define to 1 if you have the winsock2.h header file. */
#cmakedefine HAVE_WINSOCK2_H 1
/* Define this symbol if your OS supports changing the contents of argv */
#cmakedefine HAVE_WRITABLE_ARGV 1
/* Define to 1 if you have the writev function. */
#cmakedefine HAVE_WRITEV 1
/* Define to 1 if you have the ws2tcpip.h header file. */
#cmakedefine HAVE_WS2TCPIP_H 1
/* Define to 1 if you have the <x509.h> header file. */
#cmakedefine HAVE_X509_H 1
/* Define if you have the <process.h> header file. */
#cmakedefine HAVE_PROCESS_H 1
/* if you have the zlib.h header file */
#cmakedefine HAVE_ZLIB_H 1
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#cmakedefine LT_OBJDIR ${LT_OBJDIR}
/* If you lack a fine basename() prototype */
#cmakedefine NEED_BASENAME_PROTO 1
/* Define to 1 if you need the lber.h header file even with ldap.h */
#cmakedefine NEED_LBER_H 1
/* Define to 1 if you need the malloc.h header file even with stdlib.h */
#cmakedefine NEED_MALLOC_H 1
/* Define to 1 if _REENTRANT preprocessor symbol must be defined. */
#cmakedefine NEED_REENTRANT 1
/* cpu-machine-OS */
#cmakedefine OS ${OS}
/* Name of package */
#cmakedefine PACKAGE ${PACKAGE}
/* Define to the address where bug reports for this package should be sent. */
#cmakedefine PACKAGE_BUGREPORT ${PACKAGE_BUGREPORT}
/* Define to the full name of this package. */
#cmakedefine PACKAGE_NAME ${PACKAGE_NAME}
/* Define to the full name and version of this package. */
#cmakedefine PACKAGE_STRING ${PACKAGE_STRING}
/* Define to the one symbol short name of this package. */
#cmakedefine PACKAGE_TARNAME ${PACKAGE_TARNAME}
/* Define to the version of this package. */
#cmakedefine PACKAGE_VERSION ${PACKAGE_VERSION}
/* a suitable file to read random data from */
#cmakedefine RANDOM_FILE "${RANDOM_FILE}"
/* Define to the type of arg 1 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG1 ${RECVFROM_TYPE_ARG1}
/* Define to the type pointed by arg 2 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG2 ${RECVFROM_TYPE_ARG2}
/* Define to 1 if the type pointed by arg 2 for recvfrom is void. */
#cmakedefine RECVFROM_TYPE_ARG2_IS_VOID 1
/* Define to the type of arg 3 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG3 ${RECVFROM_TYPE_ARG3}
/* Define to the type of arg 4 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG4 ${RECVFROM_TYPE_ARG4}
/* Define to the type pointed by arg 5 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG5 ${RECVFROM_TYPE_ARG5}
/* Define to 1 if the type pointed by arg 5 for recvfrom is void. */
#cmakedefine RECVFROM_TYPE_ARG5_IS_VOID 1
/* Define to the type pointed by arg 6 for recvfrom. */
#cmakedefine RECVFROM_TYPE_ARG6 ${RECVFROM_TYPE_ARG6}
/* Define to 1 if the type pointed by arg 6 for recvfrom is void. */
#cmakedefine RECVFROM_TYPE_ARG6_IS_VOID 1
/* Define to the function return type for recvfrom. */
#cmakedefine RECVFROM_TYPE_RETV ${RECVFROM_TYPE_RETV}
/* Define to the type of arg 1 for recv. */
#cmakedefine RECV_TYPE_ARG1 ${RECV_TYPE_ARG1}
/* Define to the type of arg 2 for recv. */
#cmakedefine RECV_TYPE_ARG2 ${RECV_TYPE_ARG2}
/* Define to the type of arg 3 for recv. */
#cmakedefine RECV_TYPE_ARG3 ${RECV_TYPE_ARG3}
/* Define to the type of arg 4 for recv. */
#cmakedefine RECV_TYPE_ARG4 ${RECV_TYPE_ARG4}
/* Define to the function return type for recv. */
#cmakedefine RECV_TYPE_RETV ${RECV_TYPE_RETV}
/* Define to the type qualifier of arg 5 for select. */
#cmakedefine SELECT_QUAL_ARG5 ${SELECT_QUAL_ARG5}
/* Define to the type of arg 1 for select. */
#cmakedefine SELECT_TYPE_ARG1 ${SELECT_TYPE_ARG1}
/* Define to the type of args 2, 3 and 4 for select. */
#cmakedefine SELECT_TYPE_ARG234 ${SELECT_TYPE_ARG234}
/* Define to the type of arg 5 for select. */
#cmakedefine SELECT_TYPE_ARG5 ${SELECT_TYPE_ARG5}
/* Define to the function return type for select. */
#cmakedefine SELECT_TYPE_RETV ${SELECT_TYPE_RETV}
/* Define to the type qualifier of arg 2 for send. */
#cmakedefine SEND_QUAL_ARG2 ${SEND_QUAL_ARG2}
/* Define to the type of arg 1 for send. */
#cmakedefine SEND_TYPE_ARG1 ${SEND_TYPE_ARG1}
/* Define to the type of arg 2 for send. */
#cmakedefine SEND_TYPE_ARG2 ${SEND_TYPE_ARG2}
/* Define to the type of arg 3 for send. */
#cmakedefine SEND_TYPE_ARG3 ${SEND_TYPE_ARG3}
/* Define to the type of arg 4 for send. */
#cmakedefine SEND_TYPE_ARG4 ${SEND_TYPE_ARG4}
/* Define to the function return type for send. */
#cmakedefine SEND_TYPE_RETV ${SEND_TYPE_RETV}
/*
Note: SIZEOF_* variables are fetched with CMake through check_type_size().
As per CMake documentation on CheckTypeSize, C preprocessor code is
generated by CMake into SIZEOF_*_CODE. This is what we use in the
following statements.
Reference: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html
*/
/* The size of `int', as computed by sizeof. */
${SIZEOF_INT_CODE}
/* The size of `short', as computed by sizeof. */
${SIZEOF_SHORT_CODE}
/* The size of `long', as computed by sizeof. */
${SIZEOF_LONG_CODE}
/* The size of `off_t', as computed by sizeof. */
${SIZEOF_OFF_T_CODE}
/* The size of `curl_off_t', as computed by sizeof. */
${SIZEOF_CURL_OFF_T_CODE}
/* The size of `size_t', as computed by sizeof. */
${SIZEOF_SIZE_T_CODE}
/* The size of `time_t', as computed by sizeof. */
${SIZEOF_TIME_T_CODE}
/* Define to 1 if you have the ANSI C header files. */
#cmakedefine STDC_HEADERS 1
/* Define to the type of arg 3 for strerror_r. */
#cmakedefine STRERROR_R_TYPE_ARG3 ${STRERROR_R_TYPE_ARG3}
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#cmakedefine TIME_WITH_SYS_TIME 1
/* Define if you want to enable c-ares support */
#cmakedefine USE_ARES 1
/* Define if you want to enable POSIX threaded DNS lookup */
#cmakedefine USE_THREADS_POSIX 1
/* Define if you want to enable WIN32 threaded DNS lookup */
#cmakedefine USE_THREADS_WIN32 1
/* if GnuTLS is enabled */
#cmakedefine USE_GNUTLS 1
/* if Secure Transport is enabled */
#cmakedefine USE_SECTRANSP 1
/* if mbedTLS is enabled */
#cmakedefine USE_MBEDTLS 1
/* if BearSSL is enabled */
#cmakedefine USE_BEARSSL 1
/* if WolfSSL is enabled */
#cmakedefine USE_WOLFSSL 1
/* if libSSH is in use */
#cmakedefine USE_LIBSSH 1
/* if libSSH2 is in use */
#cmakedefine USE_LIBSSH2 1
/* If you want to build curl with the built-in manual */
#cmakedefine USE_MANUAL 1
/* if NSS is enabled */
#cmakedefine USE_NSS 1
/* if you have the PK11_CreateManagedGenericObject function */
#cmakedefine HAVE_PK11_CREATEMANAGEDGENERICOBJECT 1
/* if you want to use OpenLDAP code instead of legacy ldap implementation */
#cmakedefine USE_OPENLDAP 1
/* if OpenSSL is in use */
#cmakedefine USE_OPENSSL 1
/* Define to 1 if you don't want the OpenSSL configuration to be loaded
automatically */
#cmakedefine CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1
/* to enable NGHTTP2 */
#cmakedefine USE_NGHTTP2 1
/* to enable NGTCP2 */
#cmakedefine USE_NGTCP2 1
/* to enable NGHTTP3 */
#cmakedefine USE_NGHTTP3 1
/* to enable quiche */
#cmakedefine USE_QUICHE 1
/* Define to 1 if you have the quiche_conn_set_qlog_fd function. */
#cmakedefine HAVE_QUICHE_CONN_SET_QLOG_FD 1
/* if Unix domain sockets are enabled */
#cmakedefine USE_UNIX_SOCKETS
/* Define to 1 if you are building a Windows target with large file support. */
#cmakedefine USE_WIN32_LARGE_FILES 1
/* to enable SSPI support */
#cmakedefine USE_WINDOWS_SSPI 1
/* to enable Windows SSL */
#cmakedefine USE_SCHANNEL 1
/* enable multiple SSL backends */
#cmakedefine CURL_WITH_MULTI_SSL 1
/* Define to 1 if using yaSSL in OpenSSL compatibility mode. */
#cmakedefine USE_YASSLEMUL 1
/* Version number of package */
#cmakedefine VERSION ${VERSION}
/* Define to 1 if OS is AIX. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
#cmakedefine _FILE_OFFSET_BITS ${_FILE_OFFSET_BITS}
/* Define for large files, on AIX-style hosts. */
#cmakedefine _LARGE_FILES ${_LARGE_FILES}
/* define this if you need it to compile thread-safe code */
#cmakedefine _THREAD_SAFE ${_THREAD_SAFE}
/* Define to empty if `const' does not conform to ANSI C. */
#cmakedefine const ${const}
/* Type to use in place of in_addr_t when system does not provide it. */
#cmakedefine in_addr_t ${in_addr_t}
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
#undef inline
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
#cmakedefine size_t ${size_t}
/* the signed version of size_t */
#cmakedefine ssize_t ${ssize_t}
/* Define to 1 if you have the mach_absolute_time function. */
#cmakedefine HAVE_MACH_ABSOLUTE_TIME 1
/* to enable Windows IDN */
#cmakedefine USE_WIN32_IDN 1
/* to make the compiler know the prototypes of Windows IDN APIs */
#cmakedefine WANT_IDN_PROTOTYPES 1
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/doh.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_DOH
#include "urldata.h"
#include "curl_addrinfo.h"
#include "doh.h"
#include "sendf.h"
#include "multiif.h"
#include "url.h"
#include "share.h"
#include "curl_base64.h"
#include "connect.h"
#include "strdup.h"
#include "dynbuf.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#define DNS_CLASS_IN 0x01
#ifndef CURL_DISABLE_VERBOSE_STRINGS
static const char * const errors[]={
"",
"Bad label",
"Out of range",
"Label loop",
"Too small",
"Out of memory",
"RDATA length",
"Malformat",
"Bad RCODE",
"Unexpected TYPE",
"Unexpected CLASS",
"No content",
"Bad ID",
"Name too long"
};
static const char *doh_strerror(DOHcode code)
{
if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG))
return errors[code];
return "bad error code";
}
#endif
#ifdef DEBUGBUILD
#define UNITTEST
#else
#define UNITTEST static
#endif
/* @unittest 1655
*/
UNITTEST DOHcode doh_encode(const char *host,
DNStype dnstype,
unsigned char *dnsp, /* buffer */
size_t len, /* buffer size */
size_t *olen) /* output length */
{
const size_t hostlen = strlen(host);
unsigned char *orig = dnsp;
const char *hostp = host;
/* The expected output length is 16 bytes more than the length of
* the QNAME-encoding of the host name.
*
* A valid DNS name may not contain a zero-length label, except at
* the end. For this reason, a name beginning with a dot, or
* containing a sequence of two or more consecutive dots, is invalid
* and cannot be encoded as a QNAME.
*
* If the host name ends with a trailing dot, the corresponding
* QNAME-encoding is one byte longer than the host name. If (as is
* also valid) the hostname is shortened by the omission of the
* trailing dot, then its QNAME-encoding will be two bytes longer
* than the host name.
*
* Each [ label, dot ] pair is encoded as [ length, label ],
* preserving overall length. A final [ label ] without a dot is
* also encoded as [ length, label ], increasing overall length
* by one. The encoding is completed by appending a zero byte,
* representing the zero-length root label, again increasing
* the overall length by one.
*/
size_t expected_len;
DEBUGASSERT(hostlen);
expected_len = 12 + 1 + hostlen + 4;
if(host[hostlen-1]!='.')
expected_len++;
if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
return DOH_DNS_NAME_TOO_LONG;
if(len < expected_len)
return DOH_TOO_SMALL_BUFFER;
*dnsp++ = 0; /* 16 bit id */
*dnsp++ = 0;
*dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
*dnsp++ = '\0'; /* |RA| Z | RCODE | */
*dnsp++ = '\0';
*dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
*dnsp++ = '\0';
*dnsp++ = '\0'; /* ANCOUNT */
*dnsp++ = '\0';
*dnsp++ = '\0'; /* NSCOUNT */
*dnsp++ = '\0';
*dnsp++ = '\0'; /* ARCOUNT */
/* encode each label and store it in the QNAME */
while(*hostp) {
size_t labellen;
char *dot = strchr(hostp, '.');
if(dot)
labellen = dot - hostp;
else
labellen = strlen(hostp);
if((labellen > 63) || (!labellen)) {
/* label is too long or too short, error out */
*olen = 0;
return DOH_DNS_BAD_LABEL;
}
/* label is non-empty, process it */
*dnsp++ = (unsigned char)labellen;
memcpy(dnsp, hostp, labellen);
dnsp += labellen;
hostp += labellen;
/* advance past dot, but only if there is one */
if(dot)
hostp++;
} /* next label */
*dnsp++ = 0; /* append zero-length label for root */
/* There are assigned TYPE codes beyond 255: use range [1..65535] */
*dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */
*dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
*dnsp++ = '\0'; /* upper 8 bit CLASS */
*dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
*olen = dnsp - orig;
/* verify that our estimation of length is valid, since
* this has led to buffer overflows in this function */
DEBUGASSERT(*olen == expected_len);
return DOH_OK;
}
static size_t
doh_write_cb(const void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct dynbuf *mem = (struct dynbuf *)userp;
if(Curl_dyn_addn(mem, contents, realsize))
return 0;
return realsize;
}
/* called from multi.c when this DoH transfer is complete */
static int doh_done(struct Curl_easy *doh, CURLcode result)
{
struct Curl_easy *data = doh->set.dohfor;
struct dohdata *dohp = data->req.doh;
/* so one of the DoH request done for the 'data' transfer is now complete! */
dohp->pending--;
infof(data, "a DoH request is completed, %u to go", dohp->pending);
if(result)
infof(data, "DoH request %s", curl_easy_strerror(result));
if(!dohp->pending) {
/* DoH completed */
curl_slist_free_all(dohp->headers);
dohp->headers = NULL;
Curl_expire(data, 0, EXPIRE_RUN_NOW);
}
return 0;
}
#define ERROR_CHECK_SETOPT(x,y) \
do { \
result = curl_easy_setopt(doh, x, y); \
if(result && \
result != CURLE_NOT_BUILT_IN && \
result != CURLE_UNKNOWN_OPTION) \
goto error; \
} while(0)
static CURLcode dohprobe(struct Curl_easy *data,
struct dnsprobe *p, DNStype dnstype,
const char *host,
const char *url, CURLM *multi,
struct curl_slist *headers)
{
struct Curl_easy *doh = NULL;
char *nurl = NULL;
CURLcode result = CURLE_OK;
timediff_t timeout_ms;
DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
&p->dohlen);
if(d) {
failf(data, "Failed to encode DoH packet [%d]", d);
return CURLE_OUT_OF_MEMORY;
}
p->dnstype = dnstype;
Curl_dyn_init(&p->serverdoh, DYN_DOH_RESPONSE);
timeout_ms = Curl_timeleft(data, NULL, TRUE);
if(timeout_ms <= 0) {
result = CURLE_OPERATION_TIMEDOUT;
goto error;
}
/* Curl_open() is the internal version of curl_easy_init() */
result = Curl_open(&doh);
if(!result) {
/* pass in the struct pointer via a local variable to please coverity and
the gcc typecheck helpers */
struct dynbuf *resp = &p->serverdoh;
ERROR_CHECK_SETOPT(CURLOPT_URL, url);
ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
#ifdef USE_NGHTTP2
ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
#endif
#ifndef CURLDEBUG
/* enforce HTTPS if not debug */
ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#else
/* in debug mode, also allow http */
ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
#endif
ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
ERROR_CHECK_SETOPT(CURLOPT_SHARE, data->share);
if(data->set.err && data->set.err != stderr)
ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err);
if(data->set.verbose)
ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
if(data->set.no_signal)
ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST,
data->set.doh_verifyhost ? 2L : 0L);
ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER,
data->set.doh_verifypeer ? 1L : 0L);
ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS,
data->set.doh_verifystatus ? 1L : 0L);
/* Inherit *some* SSL options from the user's transfer. This is a
best-guess as to which options are needed for compatibility. #3661
Note DoH does not inherit the user's proxy server so proxy SSL settings
have no effect and are not inherited. If that changes then two new
options should be added to check doh proxy insecure separately,
CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER.
*/
if(data->set.ssl.falsestart)
ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
if(data->set.str[STRING_SSL_CAFILE]) {
ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
data->set.str[STRING_SSL_CAFILE]);
}
if(data->set.blobs[BLOB_CAINFO]) {
ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB,
data->set.blobs[BLOB_CAINFO]);
}
if(data->set.str[STRING_SSL_CAPATH]) {
ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
data->set.str[STRING_SSL_CAPATH]);
}
if(data->set.str[STRING_SSL_CRLFILE]) {
ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
data->set.str[STRING_SSL_CRLFILE]);
}
if(data->set.ssl.certinfo)
ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
if(data->set.str[STRING_SSL_RANDOM_FILE]) {
ERROR_CHECK_SETOPT(CURLOPT_RANDOM_FILE,
data->set.str[STRING_SSL_RANDOM_FILE]);
}
if(data->set.str[STRING_SSL_EGDSOCKET]) {
ERROR_CHECK_SETOPT(CURLOPT_EGDSOCKET,
data->set.str[STRING_SSL_EGDSOCKET]);
}
if(data->set.ssl.fsslctx)
ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
if(data->set.ssl.fsslctxp)
ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
if(data->set.str[STRING_SSL_EC_CURVES]) {
ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
data->set.str[STRING_SSL_EC_CURVES]);
}
{
long mask =
(data->set.ssl.enable_beast ?
CURLSSLOPT_ALLOW_BEAST : 0) |
(data->set.ssl.no_revoke ?
CURLSSLOPT_NO_REVOKE : 0) |
(data->set.ssl.no_partialchain ?
CURLSSLOPT_NO_PARTIALCHAIN : 0) |
(data->set.ssl.revoke_best_effort ?
CURLSSLOPT_REVOKE_BEST_EFFORT : 0) |
(data->set.ssl.native_ca_store ?
CURLSSLOPT_NATIVE_CA : 0) |
(data->set.ssl.auto_client_cert ?
CURLSSLOPT_AUTO_CLIENT_CERT : 0);
(void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, mask);
}
doh->set.fmultidone = doh_done;
doh->set.dohfor = data; /* identify for which transfer this is done */
p->easy = doh;
/* DoH private_data must be null because the user must have a way to
distinguish their transfer's handle from DoH handles in user
callbacks (ie SSL CTX callback). */
DEBUGASSERT(!doh->set.private_data);
if(curl_multi_add_handle(multi, doh))
goto error;
}
else
goto error;
free(nurl);
return CURLE_OK;
error:
free(nurl);
Curl_close(&doh);
return result;
}
/*
* Curl_doh() resolves a name using DoH. It resolves a name and returns a
* 'Curl_addrinfo *' with the address information.
*/
struct Curl_addrinfo *Curl_doh(struct Curl_easy *data,
const char *hostname,
int port,
int *waitp)
{
CURLcode result = CURLE_OK;
int slot;
struct dohdata *dohp;
struct connectdata *conn = data->conn;
*waitp = TRUE; /* this never returns synchronously */
(void)hostname;
(void)port;
DEBUGASSERT(!data->req.doh);
DEBUGASSERT(conn);
/* start clean, consider allocating this struct on demand */
dohp = data->req.doh = calloc(sizeof(struct dohdata), 1);
if(!dohp)
return NULL;
conn->bits.doh = TRUE;
dohp->host = hostname;
dohp->port = port;
dohp->headers =
curl_slist_append(NULL,
"Content-Type: application/dns-message");
if(!dohp->headers)
goto error;
/* create IPv4 DoH request */
result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V4],
DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
data->multi, dohp->headers);
if(result)
goto error;
dohp->pending++;
if(Curl_ipv6works(data)) {
/* create IPv6 DoH request */
result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V6],
DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
data->multi, dohp->headers);
if(result)
goto error;
dohp->pending++;
}
return NULL;
error:
curl_slist_free_all(dohp->headers);
data->req.doh->headers = NULL;
for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
Curl_close(&dohp->probe[slot].easy);
}
Curl_safefree(data->req.doh);
return NULL;
}
static DOHcode skipqname(const unsigned char *doh, size_t dohlen,
unsigned int *indexp)
{
unsigned char length;
do {
if(dohlen < (*indexp + 1))
return DOH_DNS_OUT_OF_RANGE;
length = doh[*indexp];
if((length & 0xc0) == 0xc0) {
/* name pointer, advance over it and be done */
if(dohlen < (*indexp + 2))
return DOH_DNS_OUT_OF_RANGE;
*indexp += 2;
break;
}
if(length & 0xc0)
return DOH_DNS_BAD_LABEL;
if(dohlen < (*indexp + 1 + length))
return DOH_DNS_OUT_OF_RANGE;
*indexp += 1 + length;
} while(length);
return DOH_OK;
}
static unsigned short get16bit(const unsigned char *doh, int index)
{
return (unsigned short)((doh[index] << 8) | doh[index + 1]);
}
static unsigned int get32bit(const unsigned char *doh, int index)
{
/* make clang and gcc optimize this to bswap by incrementing
the pointer first. */
doh += index;
/* avoid undefined behavior by casting to unsigned before shifting
24 bits, possibly into the sign bit. codegen is same, but
ub sanitizer won't be upset */
return ( (unsigned)doh[0] << 24) | (doh[1] << 16) |(doh[2] << 8) | doh[3];
}
static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d)
{
/* silently ignore addresses over the limit */
if(d->numaddr < DOH_MAX_ADDR) {
struct dohaddr *a = &d->addr[d->numaddr];
a->type = DNS_TYPE_A;
memcpy(&a->ip.v4, &doh[index], 4);
d->numaddr++;
}
return DOH_OK;
}
static DOHcode store_aaaa(const unsigned char *doh,
int index,
struct dohentry *d)
{
/* silently ignore addresses over the limit */
if(d->numaddr < DOH_MAX_ADDR) {
struct dohaddr *a = &d->addr[d->numaddr];
a->type = DNS_TYPE_AAAA;
memcpy(&a->ip.v6, &doh[index], 16);
d->numaddr++;
}
return DOH_OK;
}
static DOHcode store_cname(const unsigned char *doh,
size_t dohlen,
unsigned int index,
struct dohentry *d)
{
struct dynbuf *c;
unsigned int loop = 128; /* a valid DNS name can never loop this much */
unsigned char length;
if(d->numcname == DOH_MAX_CNAME)
return DOH_OK; /* skip! */
c = &d->cname[d->numcname++];
do {
if(index >= dohlen)
return DOH_DNS_OUT_OF_RANGE;
length = doh[index];
if((length & 0xc0) == 0xc0) {
int newpos;
/* name pointer, get the new offset (14 bits) */
if((index + 1) >= dohlen)
return DOH_DNS_OUT_OF_RANGE;
/* move to the new index */
newpos = (length & 0x3f) << 8 | doh[index + 1];
index = newpos;
continue;
}
else if(length & 0xc0)
return DOH_DNS_BAD_LABEL; /* bad input */
else
index++;
if(length) {
if(Curl_dyn_len(c)) {
if(Curl_dyn_add(c, "."))
return DOH_OUT_OF_MEM;
}
if((index + length) > dohlen)
return DOH_DNS_BAD_LABEL;
if(Curl_dyn_addn(c, &doh[index], length))
return DOH_OUT_OF_MEM;
index += length;
}
} while(length && --loop);
if(!loop)
return DOH_DNS_LABEL_LOOP;
return DOH_OK;
}
static DOHcode rdata(const unsigned char *doh,
size_t dohlen,
unsigned short rdlength,
unsigned short type,
int index,
struct dohentry *d)
{
/* RDATA
- A (TYPE 1): 4 bytes
- AAAA (TYPE 28): 16 bytes
- NS (TYPE 2): N bytes */
DOHcode rc;
switch(type) {
case DNS_TYPE_A:
if(rdlength != 4)
return DOH_DNS_RDATA_LEN;
rc = store_a(doh, index, d);
if(rc)
return rc;
break;
case DNS_TYPE_AAAA:
if(rdlength != 16)
return DOH_DNS_RDATA_LEN;
rc = store_aaaa(doh, index, d);
if(rc)
return rc;
break;
case DNS_TYPE_CNAME:
rc = store_cname(doh, dohlen, index, d);
if(rc)
return rc;
break;
case DNS_TYPE_DNAME:
/* explicit for clarity; just skip; rely on synthesized CNAME */
break;
default:
/* unsupported type, just skip it */
break;
}
return DOH_OK;
}
UNITTEST void de_init(struct dohentry *de)
{
int i;
memset(de, 0, sizeof(*de));
de->ttl = INT_MAX;
for(i = 0; i < DOH_MAX_CNAME; i++)
Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
}
UNITTEST DOHcode doh_decode(const unsigned char *doh,
size_t dohlen,
DNStype dnstype,
struct dohentry *d)
{
unsigned char rcode;
unsigned short qdcount;
unsigned short ancount;
unsigned short type = 0;
unsigned short rdlength;
unsigned short nscount;
unsigned short arcount;
unsigned int index = 12;
DOHcode rc;
if(dohlen < 12)
return DOH_TOO_SMALL_BUFFER; /* too small */
if(!doh || doh[0] || doh[1])
return DOH_DNS_BAD_ID; /* bad ID */
rcode = doh[3] & 0x0f;
if(rcode)
return DOH_DNS_BAD_RCODE; /* bad rcode */
qdcount = get16bit(doh, 4);
while(qdcount) {
rc = skipqname(doh, dohlen, &index);
if(rc)
return rc; /* bad qname */
if(dohlen < (index + 4))
return DOH_DNS_OUT_OF_RANGE;
index += 4; /* skip question's type and class */
qdcount--;
}
ancount = get16bit(doh, 6);
while(ancount) {
unsigned short class;
unsigned int ttl;
rc = skipqname(doh, dohlen, &index);
if(rc)
return rc; /* bad qname */
if(dohlen < (index + 2))
return DOH_DNS_OUT_OF_RANGE;
type = get16bit(doh, index);
if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
&& (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
&& (type != dnstype))
/* Not the same type as was asked for nor CNAME nor DNAME */
return DOH_DNS_UNEXPECTED_TYPE;
index += 2;
if(dohlen < (index + 2))
return DOH_DNS_OUT_OF_RANGE;
class = get16bit(doh, index);
if(DNS_CLASS_IN != class)
return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
index += 2;
if(dohlen < (index + 4))
return DOH_DNS_OUT_OF_RANGE;
ttl = get32bit(doh, index);
if(ttl < d->ttl)
d->ttl = ttl;
index += 4;
if(dohlen < (index + 2))
return DOH_DNS_OUT_OF_RANGE;
rdlength = get16bit(doh, index);
index += 2;
if(dohlen < (index + rdlength))
return DOH_DNS_OUT_OF_RANGE;
rc = rdata(doh, dohlen, rdlength, type, index, d);
if(rc)
return rc; /* bad rdata */
index += rdlength;
ancount--;
}
nscount = get16bit(doh, 8);
while(nscount) {
rc = skipqname(doh, dohlen, &index);
if(rc)
return rc; /* bad qname */
if(dohlen < (index + 8))
return DOH_DNS_OUT_OF_RANGE;
index += 2 + 2 + 4; /* type, class and ttl */
if(dohlen < (index + 2))
return DOH_DNS_OUT_OF_RANGE;
rdlength = get16bit(doh, index);
index += 2;
if(dohlen < (index + rdlength))
return DOH_DNS_OUT_OF_RANGE;
index += rdlength;
nscount--;
}
arcount = get16bit(doh, 10);
while(arcount) {
rc = skipqname(doh, dohlen, &index);
if(rc)
return rc; /* bad qname */
if(dohlen < (index + 8))
return DOH_DNS_OUT_OF_RANGE;
index += 2 + 2 + 4; /* type, class and ttl */
if(dohlen < (index + 2))
return DOH_DNS_OUT_OF_RANGE;
rdlength = get16bit(doh, index);
index += 2;
if(dohlen < (index + rdlength))
return DOH_DNS_OUT_OF_RANGE;
index += rdlength;
arcount--;
}
if(index != dohlen)
return DOH_DNS_MALFORMAT; /* something is wrong */
if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
/* nothing stored! */
return DOH_NO_CONTENT;
return DOH_OK; /* ok */
}
#ifndef CURL_DISABLE_VERBOSE_STRINGS
static void showdoh(struct Curl_easy *data,
const struct dohentry *d)
{
int i;
infof(data, "TTL: %u seconds", d->ttl);
for(i = 0; i < d->numaddr; i++) {
const struct dohaddr *a = &d->addr[i];
if(a->type == DNS_TYPE_A) {
infof(data, "DoH A: %u.%u.%u.%u",
a->ip.v4[0], a->ip.v4[1],
a->ip.v4[2], a->ip.v4[3]);
}
else if(a->type == DNS_TYPE_AAAA) {
int j;
char buffer[128];
char *ptr;
size_t len;
msnprintf(buffer, 128, "DoH AAAA: ");
ptr = &buffer[10];
len = 118;
for(j = 0; j < 16; j += 2) {
size_t l;
msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
d->addr[i].ip.v6[j + 1]);
l = strlen(ptr);
len -= l;
ptr += l;
}
infof(data, "%s", buffer);
}
}
for(i = 0; i < d->numcname; i++) {
infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i]));
}
}
#else
#define showdoh(x,y)
#endif
/*
* doh2ai()
*
* This function returns a pointer to the first element of a newly allocated
* Curl_addrinfo struct linked list filled with the data from a set of DoH
* lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
* a IPv6 stack, but usable also for IPv4, all hosts and environments.
*
* The memory allocated by this function *MUST* be free'd later on calling
* Curl_freeaddrinfo(). For each successful call to this function there
* must be an associated call later to Curl_freeaddrinfo().
*/
static struct Curl_addrinfo *
doh2ai(const struct dohentry *de, const char *hostname, int port)
{
struct Curl_addrinfo *ai;
struct Curl_addrinfo *prevai = NULL;
struct Curl_addrinfo *firstai = NULL;
struct sockaddr_in *addr;
#ifdef ENABLE_IPV6
struct sockaddr_in6 *addr6;
#endif
CURLcode result = CURLE_OK;
int i;
size_t hostlen = strlen(hostname) + 1; /* include zero terminator */
if(!de)
/* no input == no output! */
return NULL;
for(i = 0; i < de->numaddr; i++) {
size_t ss_size;
CURL_SA_FAMILY_T addrtype;
if(de->addr[i].type == DNS_TYPE_AAAA) {
#ifndef ENABLE_IPV6
/* we can't handle IPv6 addresses */
continue;
#else
ss_size = sizeof(struct sockaddr_in6);
addrtype = AF_INET6;
#endif
}
else {
ss_size = sizeof(struct sockaddr_in);
addrtype = AF_INET;
}
ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
if(!ai) {
result = CURLE_OUT_OF_MEMORY;
break;
}
ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
memcpy(ai->ai_canonname, hostname, hostlen);
if(!firstai)
/* store the pointer we want to return from this function */
firstai = ai;
if(prevai)
/* make the previous entry point to this */
prevai->ai_next = ai;
ai->ai_family = addrtype;
/* we return all names as STREAM, so when using this address for TFTP
the type must be ignored and conn->socktype be used instead! */
ai->ai_socktype = SOCK_STREAM;
ai->ai_addrlen = (curl_socklen_t)ss_size;
/* leave the rest of the struct filled with zero */
switch(ai->ai_family) {
case AF_INET:
addr = (void *)ai->ai_addr; /* storage area for this info */
DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
addr->sin_family = addrtype;
addr->sin_port = htons((unsigned short)port);
break;
#ifdef ENABLE_IPV6
case AF_INET6:
addr6 = (void *)ai->ai_addr; /* storage area for this info */
DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
addr6->sin6_family = addrtype;
addr6->sin6_port = htons((unsigned short)port);
break;
#endif
}
prevai = ai;
}
if(result) {
Curl_freeaddrinfo(firstai);
firstai = NULL;
}
return firstai;
}
#ifndef CURL_DISABLE_VERBOSE_STRINGS
static const char *type2name(DNStype dnstype)
{
return (dnstype == DNS_TYPE_A)?"A":"AAAA";
}
#endif
UNITTEST void de_cleanup(struct dohentry *d)
{
int i = 0;
for(i = 0; i < d->numcname; i++) {
Curl_dyn_free(&d->cname[i]);
}
}
CURLcode Curl_doh_is_resolved(struct Curl_easy *data,
struct Curl_dns_entry **dnsp)
{
CURLcode result;
struct dohdata *dohp = data->req.doh;
*dnsp = NULL; /* defaults to no response */
if(!dohp)
return CURLE_OUT_OF_MEMORY;
if(!dohp->probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
!dohp->probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
failf(data, "Could not DoH-resolve: %s", data->state.async.hostname);
return data->conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY:
CURLE_COULDNT_RESOLVE_HOST;
}
else if(!dohp->pending) {
DOHcode rc[DOH_PROBE_SLOTS] = {
DOH_OK, DOH_OK
};
struct dohentry de;
int slot;
/* remove DoH handles from multi handle and close them */
for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
curl_multi_remove_handle(data->multi, dohp->probe[slot].easy);
Curl_close(&dohp->probe[slot].easy);
}
/* parse the responses, create the struct and return it! */
de_init(&de);
for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
struct dnsprobe *p = &dohp->probe[slot];
if(!p->dnstype)
continue;
rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh),
Curl_dyn_len(&p->serverdoh),
p->dnstype,
&de);
Curl_dyn_free(&p->serverdoh);
if(rc[slot]) {
infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]),
type2name(p->dnstype), dohp->host);
}
} /* next slot */
result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
/* we have an address, of one kind or other */
struct Curl_dns_entry *dns;
struct Curl_addrinfo *ai;
infof(data, "DoH Host name: %s", dohp->host);
showdoh(data, &de);
ai = doh2ai(&de, dohp->host, dohp->port);
if(!ai) {
de_cleanup(&de);
return CURLE_OUT_OF_MEMORY;
}
if(data->share)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
/* we got a response, store it in the cache */
dns = Curl_cache_addr(data, ai, dohp->host, dohp->port);
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
if(!dns) {
/* returned failure, bail out nicely */
Curl_freeaddrinfo(ai);
}
else {
data->state.async.dns = dns;
*dnsp = dns;
result = CURLE_OK; /* address resolution OK */
}
} /* address processing done */
/* Now process any build-specific attributes retrieved from DNS */
/* All done */
de_cleanup(&de);
Curl_safefree(data->req.doh);
return result;
} /* !dohp->pending */
/* else wait for pending DoH transactions to complete */
return CURLE_OK;
}
#endif /* CURL_DISABLE_DOH */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-riscos.h | #ifndef HEADER_CURL_CONFIG_RISCOS_H
#define HEADER_CURL_CONFIG_RISCOS_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* ================================================================ */
/* Hand crafted config file for RISC OS */
/* ================================================================ */
/* Name of this package! */
#undef PACKAGE
/* Version number of this archive. */
#undef VERSION
/* Define if you have the getpass function. */
#undef HAVE_GETPASS
/* Define cpu-machine-OS */
#define OS "ARM-RISC OS"
/* Define if you want the built-in manual */
#define USE_MANUAL
/* Define if you have the gethostbyname_r() function with 3 arguments */
#undef HAVE_GETHOSTBYNAME_R_3
/* Define if you have the gethostbyname_r() function with 5 arguments */
#undef HAVE_GETHOSTBYNAME_R_5
/* Define if you have the gethostbyname_r() function with 6 arguments */
#undef HAVE_GETHOSTBYNAME_R_6
/* Define if you need the _REENTRANT define for some functions */
#undef NEED_REENTRANT
/* Define if you have the Kerberos4 libraries (including -ldes) */
#undef HAVE_KRB4
/* Define if you want to enable IPv6 support */
#undef ENABLE_IPV6
/* Define if struct sockaddr_in6 has the sin6_scope_id member */
#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1
/* Define this to 'int' if ssize_t is not an available typedefed type */
#undef ssize_t
/* Define this as a suitable file to read random data from */
#undef RANDOM_FILE
/* Define this to your Entropy Gathering Daemon socket pathname */
#undef EGD_SOCKET
/* Define if you want to enable IPv6 support */
#undef ENABLE_IPV6
/* Define if you have the alarm function. */
#define HAVE_ALARM
/* Define if you have the <alloca.h> header file. */
#define HAVE_ALLOCA_H
/* Define if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H
/* Define if you have the `closesocket' function. */
#undef HAVE_CLOSESOCKET
/* Define if you have the <errno.h> header file. */
#define HAVE_ERRNO_H
/* Define if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H
/* Define if you have the `ftruncate' function. */
#define HAVE_FTRUNCATE
/* Define if getaddrinfo exists and works */
#define HAVE_GETADDRINFO
/* Define if you have the `geteuid' function. */
#undef HAVE_GETEUID
/* Define if you have the `gethostbyname_r' function. */
#undef HAVE_GETHOSTBYNAME_R
/* Define if you have the `gethostname' function. */
#define HAVE_GETHOSTNAME
/* Define if you have the <getopt.h> header file. */
#define HAVE_GETOPT_H
/* Define if you have the `getpass_r' function. */
#undef HAVE_GETPASS_R
/* Define if you have the `getpwuid' function. */
#undef HAVE_GETPWUID
/* Define if you have the `getservbyname' function. */
#undef HAVE_GETSERVBYNAME
/* 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 `inet_addr' function. */
#undef HAVE_INET_ADDR
/* Define if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H
/* Define if you have the <io.h> header file. */
#undef HAVE_IO_H
/* Define if you have the `krb_get_our_ip_for_realm' function. */
#undef HAVE_KRB_GET_OUR_IP_FOR_REALM
/* Define if you have the <krb.h> header file. */
#undef HAVE_KRB_H
/* Define if you have the `nsl' library (-lnsl). */
#undef HAVE_LIBNSL
/* Define if you have the `resolv' library (-lresolv). */
#undef HAVE_LIBRESOLV
/* Define if you have the `resolve' library (-lresolve). */
#undef HAVE_LIBRESOLVE
/* Define if you have the `socket' library (-lsocket). */
#undef HAVE_LIBSOCKET
/* Define if you have the `ucb' library (-lucb). */
#undef HAVE_LIBUCB
/* Define if you have the `localtime_r' function. */
#undef HAVE_LOCALTIME_R
/* Define if you have the <malloc.h> header file. */
#define HAVE_MALLOC_H
/* Define if you need the malloc.h header file even with stdlib.h */
/* #define NEED_MALLOC_H 1 */
/* Define if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define if you have the <netdb.h> header file. */
#define HAVE_NETDB_H
/* Define if you have the <netinet/if_ether.h> header file. */
#undef HAVE_NETINET_IF_ETHER_H
/* Define if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H
/* Define if you have the <net/if.h> header file. */
#define HAVE_NET_IF_H
/* Define if you have the <openssl/crypto.h> header file. */
#undef HAVE_OPENSSL_CRYPTO_H
/* Define if you have the <openssl/err.h> header file. */
#undef HAVE_OPENSSL_ERR_H
/* Define if you have the <openssl/pem.h> header file. */
#undef HAVE_OPENSSL_PEM_H
/* Define if you have the <openssl/rsa.h> header file. */
#undef HAVE_OPENSSL_RSA_H
/* Define if you have the <openssl/ssl.h> header file. */
#undef HAVE_OPENSSL_SSL_H
/* Define if you have the <openssl/x509.h> header file. */
#undef HAVE_OPENSSL_X509_H
/* Define if you have the <pem.h> header file. */
#undef HAVE_PEM_H
/* Define if you have the <pwd.h> header file. */
#undef HAVE_PWD_H
/* Define if you have the `RAND_egd' function. */
#undef HAVE_RAND_EGD
/* Define if you have the `RAND_screen' function. */
#undef HAVE_RAND_SCREEN
/* Define if you have the `RAND_status' function. */
#undef HAVE_RAND_STATUS
/* Define if you have the `select' function. */
#define HAVE_SELECT
/* Define if you have the `setvbuf' function. */
#undef HAVE_SETVBUF
/* Define if you have the `sigaction' function. */
#undef HAVE_SIGACTION
/* Define if you have the `signal' function. */
#define HAVE_SIGNAL
/* Define if you have the <signal.h> header file. */
#define HAVE_SIGNAL_H
/* Define if you have the `socket' function. */
#define HAVE_SOCKET
/* Define if you have the <ssl.h> header file. */
#undef HAVE_SSL_H
/* Define if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H
/* Define if you have the `strcasecmp' function. */
#undef HAVE_STRCASECMP
/* Define if you have the `strcmpi' function. */
#undef HAVE_STRCMPI
/* Define if you have the `strdup' function. */
#define HAVE_STRDUP
/* Define if you have the `strftime' function. */
#define HAVE_STRFTIME
/* Define if you have the `stricmp' function. */
#define HAVE_STRICMP
/* Define if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define if you have the <string.h> header file. */
#define HAVE_STRING_H
/* Define if you have the `strstr' function. */
#define HAVE_STRSTR
/* Define if you have the `strtok_r' function. */
#undef HAVE_STRTOK_R
/* Define if you have the `strtoll' function. */
#undef HAVE_STRTOLL
/* Define if you have the <sys/param.h> header file. */
#undef HAVE_SYS_PARAM_H
/* Define if you have the <sys/select.h> header file. */
#undef HAVE_SYS_SELECT_H
/* Define if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H
/* Define if you have the <sys/sockio.h> header file. */
#undef HAVE_SYS_SOCKIO_H
/* Define if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H
/* Define if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H
/* Define if you have the <termios.h> header file. */
#define HAVE_TERMIOS_H
/* Define if you have the <termio.h> header file. */
#undef HAVE_TERMIO_H
/* Define if you have the <time.h> header file. */
#undef HAVE_TIME_H
/* Define if you have the `uname' function. */
#define HAVE_UNAME
/* Define if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H
/* Define if you have the <x509.h> header file. */
#undef HAVE_X509_H
/* Name of package */
#undef PACKAGE
/* The size of `int', as computed by sizeof. */
#define SIZEOF_INT 4
/* The size of `long double', as computed by sizeof. */
#undef SIZEOF_LONG_DOUBLE
/* The size of `long long', as computed by sizeof. */
#undef SIZEOF_LONG_LONG
/* The size of `short', as computed by sizeof. */
#define SIZEOF_SHORT 2
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 4
/* Define if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Version number of package */
#undef VERSION
/* Define if on AIX 3.
System headers sometimes define this.
We just want to avoid a redefinition error message. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
#undef _FILE_OFFSET_BITS
/* Define for large files, on AIX-style hosts. */
#undef _LARGE_FILES
/* Define to empty if `const' does not conform to ANSI C. */
#undef const
/* Define to `unsigned' if <sys/types.h> does not define. */
#undef size_t
/* Define to `int' if <sys/types.h> does not define. */
#undef ssize_t
/* Define if you have the ioctl function. */
#define HAVE_IOCTL
/* Define if you have a working ioctl FIONBIO function. */
#define HAVE_IOCTL_FIONBIO
/* to disable LDAP */
#define CURL_DISABLE_LDAP
/* Define if you have the recv function. */
#define HAVE_RECV 1
/* Define to the type of arg 1 for recv. */
#define RECV_TYPE_ARG1 int
/* Define to the type of arg 2 for recv. */
#define RECV_TYPE_ARG2 void *
/* Define to the type of arg 3 for recv. */
#define RECV_TYPE_ARG3 size_t
/* Define to the type of arg 4 for recv. */
#define RECV_TYPE_ARG4 int
/* Define to the function return type for recv. */
#define RECV_TYPE_RETV ssize_t
/* Define 1 if you have the recvfrom function. */
#define HAVE_RECVFROM 1
/* Define to the type of arg 1 for recvfrom. */
#define RECVFROM_TYPE_ARG1 int
/* Define to the type pointed by arg 2 for recvfrom. */
#define RECVFROM_TYPE_ARG2 void
/* Define if the type pointed by arg 2 for recvfrom is void. */
#define RECVFROM_TYPE_ARG2_IS_VOID
/* Define to the type of arg 3 for recvfrom. */
#define RECVFROM_TYPE_ARG3 size_t
/* Define to the type of arg 4 for recvfrom. */
#define RECVFROM_TYPE_ARG4 int
/* Define to the type pointed by arg 5 for recvfrom. */
#define RECVFROM_TYPE_ARG5 struct sockaddr
/* Define to the type pointed by arg 6 for recvfrom. */
#define RECVFROM_TYPE_ARG6 int
/* Define to the function return type for recvfrom. */
#define RECVFROM_TYPE_RETV ssize_t
/* Define if you have the send function. */
#define HAVE_SEND 1
/* Define to the type of arg 1 for send. */
#define SEND_TYPE_ARG1 int
/* Define to the type qualifier of arg 2 for send. */
#define SEND_QUAL_ARG2 const
/* Define to the type of arg 2 for send. */
#define SEND_TYPE_ARG2 void *
/* Define to the type of arg 3 for send. */
#define SEND_TYPE_ARG3 size_t
/* Define to the type of arg 4 for send. */
#define SEND_TYPE_ARG4 int
/* Define to the function return type for send. */
#define SEND_TYPE_RETV ssize_t
#endif /* HEADER_CURL_CONFIG_RISCOS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/escape.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* Escape and unescape URL encoding in strings. The functions return a new
* allocated string or NULL if an error occurred. */
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "warnless.h"
#include "non-ascii.h"
#include "escape.h"
#include "strdup.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/* Portable character check (remember EBCDIC). Do not use isalnum() because
its behavior is altered by the current locale.
See https://tools.ietf.org/html/rfc3986#section-2.3
*/
bool Curl_isunreserved(unsigned char in)
{
switch(in) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '-': case '.': case '_': case '~':
return TRUE;
default:
break;
}
return FALSE;
}
/* for ABI-compatibility with previous versions */
char *curl_escape(const char *string, int inlength)
{
return curl_easy_escape(NULL, string, inlength);
}
/* for ABI-compatibility with previous versions */
char *curl_unescape(const char *string, int length)
{
return curl_easy_unescape(NULL, string, length, NULL);
}
char *curl_easy_escape(struct Curl_easy *data, const char *string,
int inlength)
{
size_t length;
CURLcode result;
struct dynbuf d;
if(inlength < 0)
return NULL;
Curl_dyn_init(&d, CURL_MAX_INPUT_LENGTH * 3);
length = (inlength?(size_t)inlength:strlen(string));
if(!length)
return strdup("");
while(length--) {
unsigned char in = *string; /* we need to treat the characters unsigned */
if(Curl_isunreserved(in)) {
/* append this */
if(Curl_dyn_addn(&d, &in, 1))
return NULL;
}
else {
/* encode it */
char encoded[4];
result = Curl_convert_to_network(data, (char *)&in, 1);
if(result) {
/* Curl_convert_to_network calls failf if unsuccessful */
Curl_dyn_free(&d);
return NULL;
}
msnprintf(encoded, sizeof(encoded), "%%%02X", in);
if(Curl_dyn_add(&d, encoded))
return NULL;
}
string++;
}
return Curl_dyn_ptr(&d);
}
/*
* Curl_urldecode() URL decodes the given string.
*
* Returns a pointer to a malloced string in *ostring with length given in
* *olen. If length == 0, the length is assumed to be strlen(string).
*
* 'data' can be set to NULL but then this function can't convert network
* data to host for non-ascii.
*
* ctrl options:
* - REJECT_NADA: accept everything
* - REJECT_CTRL: rejects control characters (byte codes lower than 32) in
* the data
* - REJECT_ZERO: rejects decoded zero bytes
*
* The values for the enum starts at 2, to make the assert detect legacy
* invokes that used TRUE/FALSE (0 and 1).
*/
CURLcode Curl_urldecode(struct Curl_easy *data,
const char *string, size_t length,
char **ostring, size_t *olen,
enum urlreject ctrl)
{
size_t alloc;
char *ns;
size_t strindex = 0;
unsigned long hex;
CURLcode result = CURLE_OK;
DEBUGASSERT(string);
DEBUGASSERT(ctrl >= REJECT_NADA); /* crash on TRUE/FALSE */
alloc = (length?length:strlen(string)) + 1;
ns = malloc(alloc);
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
unsigned char in = *string;
if(('%' == in) && (alloc > 2) &&
ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
if(data) {
result = Curl_convert_from_network(data, (char *)&in, 1);
if(result) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return result;
}
}
string += 2;
alloc -= 2;
}
if(((ctrl == REJECT_CTRL) && (in < 0x20)) ||
((ctrl == REJECT_ZERO) && (in == 0))) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex] = 0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
/* store output string */
*ostring = ns;
return CURLE_OK;
}
/*
* Unescapes the given URL escaped string of given length. Returns a
* pointer to a malloced string with length given in *olen.
* If length == 0, the length is assumed to be strlen(string).
* If olen == NULL, no output length is stored.
*/
char *curl_easy_unescape(struct Curl_easy *data, const char *string,
int length, int *olen)
{
char *str = NULL;
if(length >= 0) {
size_t inputlen = length;
size_t outputlen;
CURLcode res = Curl_urldecode(data, string, inputlen, &str, &outputlen,
REJECT_NADA);
if(res)
return NULL;
if(olen) {
if(outputlen <= (size_t) INT_MAX)
*olen = curlx_uztosi(outputlen);
else
/* too large to return in an int, fail! */
Curl_safefree(str);
}
}
return str;
}
/* For operating systems/environments that use different malloc/free
systems for the app and for this library, we provide a free that uses
the library's memory system */
void curl_free(void *p)
{
free(p);
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/multihandle.h | #ifndef HEADER_CURL_MULTIHANDLE_H
#define HEADER_CURL_MULTIHANDLE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "llist.h"
#include "hash.h"
#include "conncache.h"
#include "psl.h"
#include "socketpair.h"
struct connectdata;
struct Curl_message {
struct Curl_llist_element list;
/* the 'CURLMsg' is the part that is visible to the external user */
struct CURLMsg extmsg;
};
/* NOTE: if you add a state here, add the name to the statename[] array as
well!
*/
typedef enum {
MSTATE_INIT, /* 0 - start in this state */
MSTATE_PENDING, /* 1 - no connections, waiting for one */
MSTATE_CONNECT, /* 2 - resolve/connect has been sent off */
MSTATE_RESOLVING, /* 3 - awaiting the resolve to finalize */
MSTATE_CONNECTING, /* 4 - awaiting the TCP connect to finalize */
MSTATE_TUNNELING, /* 5 - awaiting HTTPS proxy SSL initialization to
complete and/or proxy CONNECT to finalize */
MSTATE_PROTOCONNECT, /* 6 - initiate protocol connect procedure */
MSTATE_PROTOCONNECTING, /* 7 - completing the protocol-specific connect
phase */
MSTATE_DO, /* 8 - start send off the request (part 1) */
MSTATE_DOING, /* 9 - sending off the request (part 1) */
MSTATE_DOING_MORE, /* 10 - send off the request (part 2) */
MSTATE_DID, /* 11 - done sending off request */
MSTATE_PERFORMING, /* 12 - transfer data */
MSTATE_RATELIMITING, /* 13 - wait because limit-rate exceeded */
MSTATE_DONE, /* 14 - post data transfer operation */
MSTATE_COMPLETED, /* 15 - operation complete */
MSTATE_MSGSENT, /* 16 - the operation complete message is sent */
MSTATE_LAST /* 17 - not a true state, never use this */
} CURLMstate;
/* we support N sockets per easy handle. Set the corresponding bit to what
action we should wait for */
#define MAX_SOCKSPEREASYHANDLE 5
#define GETSOCK_READABLE (0x00ff)
#define GETSOCK_WRITABLE (0xff00)
#define CURLPIPE_ANY (CURLPIPE_MULTIPLEX)
#if !defined(CURL_DISABLE_SOCKETPAIR)
#define ENABLE_WAKEUP
#endif
/* value for MAXIMUM CONCURRENT STREAMS upper limit */
#define INITIAL_MAX_CONCURRENT_STREAMS ((1U << 31) - 1)
/* This is the struct known as CURLM on the outside */
struct Curl_multi {
/* First a simple identifier to easier detect if a user mix up
this multi handle with an easy handle. Set this to CURL_MULTI_HANDLE. */
unsigned int magic;
/* We have a doubly-linked list with easy handles */
struct Curl_easy *easyp;
struct Curl_easy *easylp; /* last node */
int num_easy; /* amount of entries in the linked list above. */
int num_alive; /* amount of easy handles that are added but have not yet
reached COMPLETE state */
struct Curl_llist msglist; /* a list of messages from completed transfers */
struct Curl_llist pending; /* Curl_easys that are in the
MSTATE_PENDING state */
/* callback function and user data pointer for the *socket() API */
curl_socket_callback socket_cb;
void *socket_userp;
/* callback function and user data pointer for server push */
curl_push_callback push_cb;
void *push_userp;
/* Hostname cache */
struct Curl_hash hostcache;
#ifdef USE_LIBPSL
/* PSL cache. */
struct PslCache psl;
#endif
/* timetree points to the splay-tree of time nodes to figure out expire
times of all currently set timers */
struct Curl_tree *timetree;
/* 'sockhash' is the lookup hash for socket descriptor => easy handles (note
the pluralis form, there can be more than one easy handle waiting on the
same actual socket) */
struct Curl_hash sockhash;
/* Shared connection cache (bundles)*/
struct conncache conn_cache;
long maxconnects; /* if >0, a fixed limit of the maximum number of entries
we're allowed to grow the connection cache to */
long max_host_connections; /* if >0, a fixed limit of the maximum number
of connections per host */
long max_total_connections; /* if >0, a fixed limit of the maximum number
of connections in total */
/* timer callback and user data pointer for the *socket() API */
curl_multi_timer_callback timer_cb;
void *timer_userp;
struct curltime timer_lastcall; /* the fixed time for the timeout for the
previous callback */
unsigned int max_concurrent_streams;
#ifdef USE_WINSOCK
WSAEVENT wsa_event; /* winsock event used for waits */
#else
#ifdef ENABLE_WAKEUP
curl_socket_t wakeup_pair[2]; /* socketpair() used for wakeup
0 is used for read, 1 is used for write */
#endif
#endif
/* multiplexing wanted */
bool multiplexing;
bool recheckstate; /* see Curl_multi_connchanged */
bool in_callback; /* true while executing a callback */
bool ipv6_works;
#ifdef USE_OPENSSL
bool ssl_seeded;
#endif
};
#endif /* HEADER_CURL_MULTIHANDLE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/hmac.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC2104 Keyed-Hashing for Message Authentication
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_CRYPTO_AUTH
#include <curl/curl.h>
#include "curl_hmac.h"
#include "curl_memory.h"
#include "warnless.h"
/* The last #include file should be: */
#include "memdebug.h"
/*
* Generic HMAC algorithm.
*
* This module computes HMAC digests based on any hash function. Parameters
* and computing procedures are set-up dynamically at HMAC computation
* context initialisation.
*/
static const unsigned char hmac_ipad = 0x36;
static const unsigned char hmac_opad = 0x5C;
struct HMAC_context *
Curl_HMAC_init(const struct HMAC_params *hashparams,
const unsigned char *key,
unsigned int keylen)
{
size_t i;
struct HMAC_context *ctxt;
unsigned char *hkey;
unsigned char b;
/* Create HMAC context. */
i = sizeof(*ctxt) + 2 * hashparams->hmac_ctxtsize +
hashparams->hmac_resultlen;
ctxt = malloc(i);
if(!ctxt)
return ctxt;
ctxt->hmac_hash = hashparams;
ctxt->hmac_hashctxt1 = (void *) (ctxt + 1);
ctxt->hmac_hashctxt2 = (void *) ((char *) ctxt->hmac_hashctxt1 +
hashparams->hmac_ctxtsize);
/* If the key is too long, replace it by its hash digest. */
if(keylen > hashparams->hmac_maxkeylen) {
(*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, key, keylen);
hkey = (unsigned char *) ctxt->hmac_hashctxt2 + hashparams->hmac_ctxtsize;
(*hashparams->hmac_hfinal)(hkey, ctxt->hmac_hashctxt1);
key = hkey;
keylen = hashparams->hmac_resultlen;
}
/* Prime the two hash contexts with the modified key. */
(*hashparams->hmac_hinit)(ctxt->hmac_hashctxt1);
(*hashparams->hmac_hinit)(ctxt->hmac_hashctxt2);
for(i = 0; i < keylen; i++) {
b = (unsigned char)(*key ^ hmac_ipad);
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &b, 1);
b = (unsigned char)(*key++ ^ hmac_opad);
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &b, 1);
}
for(; i < hashparams->hmac_maxkeylen; i++) {
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt1, &hmac_ipad, 1);
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2, &hmac_opad, 1);
}
/* Done, return pointer to HMAC context. */
return ctxt;
}
int Curl_HMAC_update(struct HMAC_context *ctxt,
const unsigned char *data,
unsigned int len)
{
/* Update first hash calculation. */
(*ctxt->hmac_hash->hmac_hupdate)(ctxt->hmac_hashctxt1, data, len);
return 0;
}
int Curl_HMAC_final(struct HMAC_context *ctxt, unsigned char *result)
{
const struct HMAC_params *hashparams = ctxt->hmac_hash;
/* Do not get result if called with a null parameter: only release
storage. */
if(!result)
result = (unsigned char *) ctxt->hmac_hashctxt2 +
ctxt->hmac_hash->hmac_ctxtsize;
(*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt1);
(*hashparams->hmac_hupdate)(ctxt->hmac_hashctxt2,
result, hashparams->hmac_resultlen);
(*hashparams->hmac_hfinal)(result, ctxt->hmac_hashctxt2);
free((char *) ctxt);
return 0;
}
/*
* Curl_hmacit()
*
* This is used to generate a HMAC hash, for the specified input data, given
* the specified hash function and key.
*
* Parameters:
*
* hashparams [in] - The hash function (Curl_HMAC_MD5).
* key [in] - The key to use.
* keylen [in] - The length of the key.
* data [in] - The data to encrypt.
* datalen [in] - The length of the data.
* output [in/out] - The output buffer.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_hmacit(const struct HMAC_params *hashparams,
const unsigned char *key, const size_t keylen,
const unsigned char *data, const size_t datalen,
unsigned char *output)
{
struct HMAC_context *ctxt =
Curl_HMAC_init(hashparams, key, curlx_uztoui(keylen));
if(!ctxt)
return CURLE_OUT_OF_MEMORY;
/* Update the digest with the given challenge */
Curl_HMAC_update(ctxt, data, curlx_uztoui(datalen));
/* Finalise the digest */
Curl_HMAC_final(ctxt, output);
return CURLE_OK;
}
#endif /* CURL_DISABLE_CRYPTO_AUTH */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/setup-win32.h | #ifndef HEADER_CURL_SETUP_WIN32_H
#define HEADER_CURL_SETUP_WIN32_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Include header files for windows builds before redefining anything.
* Use this preprocessor block only to include or exclude windows.h,
* winsock2.h or ws2tcpip.h. Any other windows thing belongs
* to any other further and independent block. Under Cygwin things work
* just as under linux (e.g. <sys/socket.h>) and the winsock headers should
* never be included when __CYGWIN__ is defined. configure script takes
* care of this, not defining HAVE_WINDOWS_H, HAVE_WINSOCK2_H,
* neither HAVE_WS2TCPIP_H when __CYGWIN__ is defined.
*/
#ifdef HAVE_WINDOWS_H
# if defined(UNICODE) && !defined(_UNICODE)
# define _UNICODE
# endif
# if defined(_UNICODE) && !defined(UNICODE)
# define UNICODE
# endif
# include <winerror.h>
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# ifdef HAVE_WS2TCPIP_H
# include <ws2tcpip.h>
# endif
# endif
# include <tchar.h>
# ifdef UNICODE
typedef wchar_t *(*curl_wcsdup_callback)(const wchar_t *str);
# endif
#endif
/*
* Define USE_WINSOCK to 2 if we have and use WINSOCK2 API, else
* undefine USE_WINSOCK.
*/
#undef USE_WINSOCK
#ifdef HAVE_WINSOCK2_H
# define USE_WINSOCK 2
#endif
/*
* Define _WIN32_WINNT_[OS] symbols because not all Windows build systems have
* those symbols to compare against, and even those that do may be missing
* newer symbols.
*/
#ifndef _WIN32_WINNT_NT4
#define _WIN32_WINNT_NT4 0x0400 /* Windows NT 4.0 */
#endif
#ifndef _WIN32_WINNT_WIN2K
#define _WIN32_WINNT_WIN2K 0x0500 /* Windows 2000 */
#endif
#ifndef _WIN32_WINNT_WINXP
#define _WIN32_WINNT_WINXP 0x0501 /* Windows XP */
#endif
#ifndef _WIN32_WINNT_WS03
#define _WIN32_WINNT_WS03 0x0502 /* Windows Server 2003 */
#endif
#ifndef _WIN32_WINNT_WIN6
#define _WIN32_WINNT_WIN6 0x0600 /* Windows Vista */
#endif
#ifndef _WIN32_WINNT_VISTA
#define _WIN32_WINNT_VISTA 0x0600 /* Windows Vista */
#endif
#ifndef _WIN32_WINNT_WS08
#define _WIN32_WINNT_WS08 0x0600 /* Windows Server 2008 */
#endif
#ifndef _WIN32_WINNT_LONGHORN
#define _WIN32_WINNT_LONGHORN 0x0600 /* Windows Vista */
#endif
#ifndef _WIN32_WINNT_WIN7
#define _WIN32_WINNT_WIN7 0x0601 /* Windows 7 */
#endif
#ifndef _WIN32_WINNT_WIN8
#define _WIN32_WINNT_WIN8 0x0602 /* Windows 8 */
#endif
#ifndef _WIN32_WINNT_WINBLUE
#define _WIN32_WINNT_WINBLUE 0x0603 /* Windows 8.1 */
#endif
#ifndef _WIN32_WINNT_WINTHRESHOLD
#define _WIN32_WINNT_WINTHRESHOLD 0x0A00 /* Windows 10 */
#endif
#ifndef _WIN32_WINNT_WIN10
#define _WIN32_WINNT_WIN10 0x0A00 /* Windows 10 */
#endif
#endif /* HEADER_CURL_SETUP_WIN32_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/netrc.h | #ifndef HEADER_CURL_NETRC_H
#define HEADER_CURL_NETRC_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_NETRC
/* returns -1 on failure, 0 if the host is found, 1 is the host isn't found */
int Curl_parsenetrc(const char *host,
char **loginp,
char **passwordp,
bool *login_changed,
bool *password_changed,
char *filename);
/* Assume: (*passwordp)[0]=0, host[0] != 0.
* If (*loginp)[0] = 0, search for login and password within a machine
* section in the netrc.
* If (*loginp)[0] != 0, search for password within machine and login.
*/
#else
/* disabled */
#define Curl_parsenetrc(a,b,c,d,e,f) 1
#endif
#endif /* HEADER_CURL_NETRC_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_ctype.h | #ifndef HEADER_CURL_CTYPE_H
#define HEADER_CURL_CTYPE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef CURL_DOES_CONVERSIONS
/*
* Uppercase macro versions of ANSI/ISO is*() functions/macros which
* avoid negative number inputs with argument byte codes > 127.
*
* For non-ASCII platforms the C library character classification routines
* are used despite being locale-dependent, because this is better than
* not to work at all.
*/
#include <ctype.h>
#define ISSPACE(x) (isspace((int) ((unsigned char)x)))
#define ISDIGIT(x) (isdigit((int) ((unsigned char)x)))
#define ISALNUM(x) (isalnum((int) ((unsigned char)x)))
#define ISXDIGIT(x) (isxdigit((int) ((unsigned char)x)))
#define ISGRAPH(x) (isgraph((int) ((unsigned char)x)))
#define ISALPHA(x) (isalpha((int) ((unsigned char)x)))
#define ISPRINT(x) (isprint((int) ((unsigned char)x)))
#define ISUPPER(x) (isupper((int) ((unsigned char)x)))
#define ISLOWER(x) (islower((int) ((unsigned char)x)))
#define ISCNTRL(x) (iscntrl((int) ((unsigned char)x)))
#define ISASCII(x) (isascii((int) ((unsigned char)x)))
#else
int Curl_isspace(int c);
int Curl_isdigit(int c);
int Curl_isalnum(int c);
int Curl_isxdigit(int c);
int Curl_isgraph(int c);
int Curl_isprint(int c);
int Curl_isalpha(int c);
int Curl_isupper(int c);
int Curl_islower(int c);
int Curl_iscntrl(int c);
#define ISSPACE(x) (Curl_isspace((int) ((unsigned char)x)))
#define ISDIGIT(x) (Curl_isdigit((int) ((unsigned char)x)))
#define ISALNUM(x) (Curl_isalnum((int) ((unsigned char)x)))
#define ISXDIGIT(x) (Curl_isxdigit((int) ((unsigned char)x)))
#define ISGRAPH(x) (Curl_isgraph((int) ((unsigned char)x)))
#define ISALPHA(x) (Curl_isalpha((int) ((unsigned char)x)))
#define ISPRINT(x) (Curl_isprint((int) ((unsigned char)x)))
#define ISUPPER(x) (Curl_isupper((int) ((unsigned char)x)))
#define ISLOWER(x) (Curl_islower((int) ((unsigned char)x)))
#define ISCNTRL(x) (Curl_iscntrl((int) ((unsigned char)x)))
#define ISASCII(x) (((x) >= 0) && ((x) <= 0x80))
#endif
#define ISBLANK(x) (int)((((unsigned char)x) == ' ') || \
(((unsigned char)x) == '\t'))
#endif /* HEADER_CURL_CTYPE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/socketpair.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include "socketpair.h"
#if !defined(HAVE_SOCKETPAIR) && !defined(CURL_DISABLE_SOCKETPAIR)
#ifdef WIN32
/*
* This is a socketpair() implementation for Windows.
*/
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <io.h>
#else
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h> /* IPPROTO_TCP */
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001
#endif /* !INADDR_LOOPBACK */
#endif /* !WIN32 */
#include "nonblock.h" /* for curlx_nonblock */
#include "timeval.h" /* needed before select.h */
#include "select.h" /* for Curl_poll */
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
int Curl_socketpair(int domain, int type, int protocol,
curl_socket_t socks[2])
{
union {
struct sockaddr_in inaddr;
struct sockaddr addr;
} a, a2;
curl_socket_t listener;
curl_socklen_t addrlen = sizeof(a.inaddr);
int reuse = 1;
struct pollfd pfd[1];
(void)domain;
(void)type;
(void)protocol;
listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(listener == CURL_SOCKET_BAD)
return -1;
memset(&a, 0, sizeof(a));
a.inaddr.sin_family = AF_INET;
a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
a.inaddr.sin_port = 0;
socks[0] = socks[1] = CURL_SOCKET_BAD;
if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,
(char *)&reuse, (curl_socklen_t)sizeof(reuse)) == -1)
goto error;
if(bind(listener, &a.addr, sizeof(a.inaddr)) == -1)
goto error;
if(getsockname(listener, &a.addr, &addrlen) == -1 ||
addrlen < (int)sizeof(a.inaddr))
goto error;
if(listen(listener, 1) == -1)
goto error;
socks[0] = socket(AF_INET, SOCK_STREAM, 0);
if(socks[0] == CURL_SOCKET_BAD)
goto error;
if(connect(socks[0], &a.addr, sizeof(a.inaddr)) == -1)
goto error;
/* use non-blocking accept to make sure we don't block forever */
if(curlx_nonblock(listener, TRUE) < 0)
goto error;
pfd[0].fd = listener;
pfd[0].events = POLLIN;
pfd[0].revents = 0;
(void)Curl_poll(pfd, 1, 10*1000); /* 10 seconds */
socks[1] = accept(listener, NULL, NULL);
if(socks[1] == CURL_SOCKET_BAD)
goto error;
/* verify that nothing else connected */
addrlen = sizeof(a.inaddr);
if(getsockname(socks[0], &a.addr, &addrlen) == -1 ||
addrlen < (int)sizeof(a.inaddr))
goto error;
addrlen = sizeof(a2.inaddr);
if(getpeername(socks[1], &a2.addr, &addrlen) == -1 ||
addrlen < (int)sizeof(a2.inaddr))
goto error;
if(a.inaddr.sin_family != a2.inaddr.sin_family ||
a.inaddr.sin_addr.s_addr != a2.inaddr.sin_addr.s_addr ||
a.inaddr.sin_port != a2.inaddr.sin_port)
goto error;
sclose(listener);
return 0;
error:
sclose(listener);
sclose(socks[0]);
sclose(socks[1]);
return -1;
}
#endif /* ! HAVE_SOCKETPAIR */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/sendf.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_LINUX_TCP_H
#include <linux/tcp.h>
#elif defined(HAVE_NETINET_TCP_H)
#include <netinet/tcp.h>
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "connect.h"
#include "vtls/vtls.h"
#include "vssh/ssh.h"
#include "easyif.h"
#include "multiif.h"
#include "non-ascii.h"
#include "strerror.h"
#include "select.h"
#include "strdup.h"
#include "http2.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#ifdef CURL_DO_LINEEND_CONV
/*
* convert_lineends() changes CRLF (\r\n) end-of-line markers to a single LF
* (\n), with special processing for CRLF sequences that are split between two
* blocks of data. Remaining, bare CRs are changed to LFs. The possibly new
* size of the data is returned.
*/
static size_t convert_lineends(struct Curl_easy *data,
char *startPtr, size_t size)
{
char *inPtr, *outPtr;
/* sanity check */
if(!startPtr || (size < 1)) {
return size;
}
if(data->state.prev_block_had_trailing_cr) {
/* The previous block of incoming data
had a trailing CR, which was turned into a LF. */
if(*startPtr == '\n') {
/* This block of incoming data starts with the
previous block's LF so get rid of it */
memmove(startPtr, startPtr + 1, size-1);
size--;
/* and it wasn't a bare CR but a CRLF conversion instead */
data->state.crlf_conversions++;
}
data->state.prev_block_had_trailing_cr = FALSE; /* reset the flag */
}
/* find 1st CR, if any */
inPtr = outPtr = memchr(startPtr, '\r', size);
if(inPtr) {
/* at least one CR, now look for CRLF */
while(inPtr < (startPtr + size-1)) {
/* note that it's size-1, so we'll never look past the last byte */
if(memcmp(inPtr, "\r\n", 2) == 0) {
/* CRLF found, bump past the CR and copy the NL */
inPtr++;
*outPtr = *inPtr;
/* keep track of how many CRLFs we converted */
data->state.crlf_conversions++;
}
else {
if(*inPtr == '\r') {
/* lone CR, move LF instead */
*outPtr = '\n';
}
else {
/* not a CRLF nor a CR, just copy whatever it is */
*outPtr = *inPtr;
}
}
outPtr++;
inPtr++;
} /* end of while loop */
if(inPtr < startPtr + size) {
/* handle last byte */
if(*inPtr == '\r') {
/* deal with a CR at the end of the buffer */
*outPtr = '\n'; /* copy a NL instead */
/* note that a CRLF might be split across two blocks */
data->state.prev_block_had_trailing_cr = TRUE;
}
else {
/* copy last byte */
*outPtr = *inPtr;
}
outPtr++;
}
if(outPtr < startPtr + size)
/* tidy up by null terminating the now shorter data */
*outPtr = '\0';
return (outPtr - startPtr);
}
return size;
}
#endif /* CURL_DO_LINEEND_CONV */
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
{
struct postponed_data * const psnd = &(conn->postponed[sockindex]);
return psnd->buffer && psnd->allocated_size &&
psnd->recv_size > psnd->recv_processed;
}
static CURLcode pre_receive_plain(struct Curl_easy *data,
struct connectdata *conn, int num)
{
const curl_socket_t sockfd = conn->sock[num];
struct postponed_data * const psnd = &(conn->postponed[num]);
size_t bytestorecv = psnd->allocated_size - psnd->recv_size;
/* WinSock will destroy unread received data if send() is
failed.
To avoid lossage of received data, recv() must be
performed before every send() if any incoming data is
available. However, skip this, if buffer is already full. */
if((conn->handler->protocol&PROTO_FAMILY_HTTP) != 0 &&
conn->recv[num] == Curl_recv_plain &&
(!psnd->buffer || bytestorecv)) {
const int readymask = Curl_socket_check(sockfd, CURL_SOCKET_BAD,
CURL_SOCKET_BAD, 0);
if(readymask != -1 && (readymask & CURL_CSELECT_IN) != 0) {
/* Have some incoming data */
if(!psnd->buffer) {
/* Use buffer double default size for intermediate buffer */
psnd->allocated_size = 2 * data->set.buffer_size;
psnd->buffer = malloc(psnd->allocated_size);
if(!psnd->buffer)
return CURLE_OUT_OF_MEMORY;
psnd->recv_size = 0;
psnd->recv_processed = 0;
#ifdef DEBUGBUILD
psnd->bindsock = sockfd; /* Used only for DEBUGASSERT */
#endif /* DEBUGBUILD */
bytestorecv = psnd->allocated_size;
}
if(psnd->buffer) {
ssize_t recvedbytes;
DEBUGASSERT(psnd->bindsock == sockfd);
recvedbytes = sread(sockfd, psnd->buffer + psnd->recv_size,
bytestorecv);
if(recvedbytes > 0)
psnd->recv_size += recvedbytes;
}
else
psnd->allocated_size = 0;
}
}
return CURLE_OK;
}
static ssize_t get_pre_recved(struct connectdata *conn, int num, char *buf,
size_t len)
{
struct postponed_data * const psnd = &(conn->postponed[num]);
size_t copysize;
if(!psnd->buffer)
return 0;
DEBUGASSERT(psnd->allocated_size > 0);
DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
DEBUGASSERT(psnd->recv_processed <= psnd->recv_size);
/* Check and process data that already received and storied in internal
intermediate buffer */
if(psnd->recv_size > psnd->recv_processed) {
DEBUGASSERT(psnd->bindsock == conn->sock[num]);
copysize = CURLMIN(len, psnd->recv_size - psnd->recv_processed);
memcpy(buf, psnd->buffer + psnd->recv_processed, copysize);
psnd->recv_processed += copysize;
}
else
copysize = 0; /* buffer was allocated, but nothing was received */
/* Free intermediate buffer if it has no unprocessed data */
if(psnd->recv_processed == psnd->recv_size) {
free(psnd->buffer);
psnd->buffer = NULL;
psnd->allocated_size = 0;
psnd->recv_size = 0;
psnd->recv_processed = 0;
#ifdef DEBUGBUILD
psnd->bindsock = CURL_SOCKET_BAD;
#endif /* DEBUGBUILD */
}
return (ssize_t)copysize;
}
#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
/* Use "do-nothing" macros instead of functions when workaround not used */
bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex)
{
(void)conn;
(void)sockindex;
return false;
}
#define pre_receive_plain(d,c,n) CURLE_OK
#define get_pre_recved(c,n,b,l) 0
#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
/* Curl_infof() is for info message along the way */
#define MAXINFO 2048
void Curl_infof(struct Curl_easy *data, const char *fmt, ...)
{
DEBUGASSERT(!strchr(fmt, '\n'));
if(data && data->set.verbose) {
va_list ap;
size_t len;
char buffer[MAXINFO + 2];
va_start(ap, fmt);
len = mvsnprintf(buffer, MAXINFO, fmt, ap);
va_end(ap);
buffer[len++] = '\n';
buffer[len] = '\0';
Curl_debug(data, CURLINFO_TEXT, buffer, len);
}
}
/* Curl_failf() is for messages stating why we failed.
* The message SHALL NOT include any LF or CR.
*/
void Curl_failf(struct Curl_easy *data, const char *fmt, ...)
{
DEBUGASSERT(!strchr(fmt, '\n'));
if(data->set.verbose || data->set.errorbuffer) {
va_list ap;
size_t len;
char error[CURL_ERROR_SIZE + 2];
va_start(ap, fmt);
len = mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap);
if(data->set.errorbuffer && !data->state.errorbuf) {
strcpy(data->set.errorbuffer, error);
data->state.errorbuf = TRUE; /* wrote error string */
}
error[len++] = '\n';
error[len] = '\0';
Curl_debug(data, CURLINFO_TEXT, error, len);
va_end(ap);
}
}
/*
* Curl_write() is an internal write function that sends data to the
* server. Works with plain sockets, SCP, SSL or kerberos.
*
* If the write would block (CURLE_AGAIN), we return CURLE_OK and
* (*written == 0). Otherwise we return regular CURLcode value.
*/
CURLcode Curl_write(struct Curl_easy *data,
curl_socket_t sockfd,
const void *mem,
size_t len,
ssize_t *written)
{
ssize_t bytes_written;
CURLcode result = CURLE_OK;
struct connectdata *conn;
int num;
DEBUGASSERT(data);
DEBUGASSERT(data->conn);
conn = data->conn;
num = (sockfd == conn->sock[SECONDARYSOCKET]);
#ifdef CURLDEBUG
{
/* Allow debug builds to override this logic to force short sends
*/
char *p = getenv("CURL_SMALLSENDS");
if(p) {
size_t altsize = (size_t)strtoul(p, NULL, 10);
if(altsize)
len = CURLMIN(len, altsize);
}
}
#endif
bytes_written = conn->send[num](data, num, mem, len, &result);
*written = bytes_written;
if(bytes_written >= 0)
/* we completely ignore the curlcode value when subzero is not returned */
return CURLE_OK;
/* handle CURLE_AGAIN or a send failure */
switch(result) {
case CURLE_AGAIN:
*written = 0;
return CURLE_OK;
case CURLE_OK:
/* general send failure */
return CURLE_SEND_ERROR;
default:
/* we got a specific curlcode, forward it */
return result;
}
}
ssize_t Curl_send_plain(struct Curl_easy *data, int num,
const void *mem, size_t len, CURLcode *code)
{
struct connectdata *conn;
curl_socket_t sockfd;
ssize_t bytes_written;
DEBUGASSERT(data);
DEBUGASSERT(data->conn);
conn = data->conn;
sockfd = conn->sock[num];
/* WinSock will destroy unread received data if send() is
failed.
To avoid lossage of received data, recv() must be
performed before every send() if any incoming data is
available. */
if(pre_receive_plain(data, conn, num)) {
*code = CURLE_OUT_OF_MEMORY;
return -1;
}
#if defined(MSG_FASTOPEN) && !defined(TCP_FASTOPEN_CONNECT) /* Linux */
if(conn->bits.tcp_fastopen) {
bytes_written = sendto(sockfd, mem, len, MSG_FASTOPEN,
conn->ip_addr->ai_addr, conn->ip_addr->ai_addrlen);
conn->bits.tcp_fastopen = FALSE;
}
else
#endif
bytes_written = swrite(sockfd, mem, len);
*code = CURLE_OK;
if(-1 == bytes_written) {
int err = SOCKERRNO;
if(
#ifdef WSAEWOULDBLOCK
/* This is how Windows does it */
(WSAEWOULDBLOCK == err)
#else
/* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
due to its inability to send off data without blocking. We therefore
treat both error codes the same here */
(EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err) ||
(EINPROGRESS == err)
#endif
) {
/* this is just a case of EWOULDBLOCK */
bytes_written = 0;
*code = CURLE_AGAIN;
}
else {
char buffer[STRERROR_LEN];
failf(data, "Send failure: %s",
Curl_strerror(err, buffer, sizeof(buffer)));
data->state.os_errno = err;
*code = CURLE_SEND_ERROR;
}
}
return bytes_written;
}
/*
* Curl_write_plain() is an internal write function that sends data to the
* server using plain sockets only. Otherwise meant to have the exact same
* proto as Curl_write()
*/
CURLcode Curl_write_plain(struct Curl_easy *data,
curl_socket_t sockfd,
const void *mem,
size_t len,
ssize_t *written)
{
CURLcode result;
struct connectdata *conn = data->conn;
int num;
DEBUGASSERT(conn);
num = (sockfd == conn->sock[SECONDARYSOCKET]);
*written = Curl_send_plain(data, num, mem, len, &result);
return result;
}
ssize_t Curl_recv_plain(struct Curl_easy *data, int num, char *buf,
size_t len, CURLcode *code)
{
struct connectdata *conn;
curl_socket_t sockfd;
ssize_t nread;
DEBUGASSERT(data);
DEBUGASSERT(data->conn);
conn = data->conn;
sockfd = conn->sock[num];
/* Check and return data that already received and storied in internal
intermediate buffer */
nread = get_pre_recved(conn, num, buf, len);
if(nread > 0) {
*code = CURLE_OK;
return nread;
}
nread = sread(sockfd, buf, len);
*code = CURLE_OK;
if(-1 == nread) {
int err = SOCKERRNO;
if(
#ifdef WSAEWOULDBLOCK
/* This is how Windows does it */
(WSAEWOULDBLOCK == err)
#else
/* errno may be EWOULDBLOCK or on some systems EAGAIN when it returned
due to its inability to send off data without blocking. We therefore
treat both error codes the same here */
(EWOULDBLOCK == err) || (EAGAIN == err) || (EINTR == err)
#endif
) {
/* this is just a case of EWOULDBLOCK */
*code = CURLE_AGAIN;
}
else {
char buffer[STRERROR_LEN];
failf(data, "Recv failure: %s",
Curl_strerror(err, buffer, sizeof(buffer)));
data->state.os_errno = err;
*code = CURLE_RECV_ERROR;
}
}
return nread;
}
static CURLcode pausewrite(struct Curl_easy *data,
int type, /* what type of data */
const char *ptr,
size_t len)
{
/* signalled to pause sending on this connection, but since we have data
we want to send we need to dup it to save a copy for when the sending
is again enabled */
struct SingleRequest *k = &data->req;
struct UrlState *s = &data->state;
unsigned int i;
bool newtype = TRUE;
/* If this transfers over HTTP/2, pause the stream! */
Curl_http2_stream_pause(data, TRUE);
if(s->tempcount) {
for(i = 0; i< s->tempcount; i++) {
if(s->tempwrite[i].type == type) {
/* data for this type exists */
newtype = FALSE;
break;
}
}
DEBUGASSERT(i < 3);
}
else
i = 0;
if(newtype) {
/* store this information in the state struct for later use */
Curl_dyn_init(&s->tempwrite[i].b, DYN_PAUSE_BUFFER);
s->tempwrite[i].type = type;
s->tempcount++;
}
if(Curl_dyn_addn(&s->tempwrite[i].b, (unsigned char *)ptr, len))
return CURLE_OUT_OF_MEMORY;
/* mark the connection as RECV paused */
k->keepon |= KEEP_RECV_PAUSE;
return CURLE_OK;
}
/* chop_write() writes chunks of data not larger than CURL_MAX_WRITE_SIZE via
* client write callback(s) and takes care of pause requests from the
* callbacks.
*/
static CURLcode chop_write(struct Curl_easy *data,
int type,
char *optr,
size_t olen)
{
struct connectdata *conn = data->conn;
curl_write_callback writeheader = NULL;
curl_write_callback writebody = NULL;
char *ptr = optr;
size_t len = olen;
if(!len)
return CURLE_OK;
/* If reading is paused, append this data to the already held data for this
type. */
if(data->req.keepon & KEEP_RECV_PAUSE)
return pausewrite(data, type, ptr, len);
/* Determine the callback(s) to use. */
if(type & CLIENTWRITE_BODY)
writebody = data->set.fwrite_func;
if((type & CLIENTWRITE_HEADER) &&
(data->set.fwrite_header || data->set.writeheader)) {
/*
* Write headers to the same callback or to the especially setup
* header callback function (added after version 7.7.1).
*/
writeheader =
data->set.fwrite_header? data->set.fwrite_header: data->set.fwrite_func;
}
/* Chop data, write chunks. */
while(len) {
size_t chunklen = len <= CURL_MAX_WRITE_SIZE? len: CURL_MAX_WRITE_SIZE;
if(writebody) {
size_t wrote;
Curl_set_in_callback(data, true);
wrote = writebody(ptr, 1, chunklen, data->set.out);
Curl_set_in_callback(data, false);
if(CURL_WRITEFUNC_PAUSE == wrote) {
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* Protocols that work without network cannot be paused. This is
actually only FILE:// just now, and it can't pause since the
transfer isn't done using the "normal" procedure. */
failf(data, "Write callback asked for PAUSE when not supported!");
return CURLE_WRITE_ERROR;
}
return pausewrite(data, type, ptr, len);
}
if(wrote != chunklen) {
failf(data, "Failure writing output to destination");
return CURLE_WRITE_ERROR;
}
}
ptr += chunklen;
len -= chunklen;
}
if(writeheader) {
size_t wrote;
ptr = optr;
len = olen;
Curl_set_in_callback(data, true);
wrote = writeheader(ptr, 1, len, data->set.writeheader);
Curl_set_in_callback(data, false);
if(CURL_WRITEFUNC_PAUSE == wrote)
/* here we pass in the HEADER bit only since if this was body as well
then it was passed already and clearly that didn't trigger the
pause, so this is saved for later with the HEADER bit only */
return pausewrite(data, CLIENTWRITE_HEADER, ptr, len);
if(wrote != len) {
failf(data, "Failed writing header");
return CURLE_WRITE_ERROR;
}
}
return CURLE_OK;
}
/* Curl_client_write() sends data to the write callback(s)
The bit pattern defines to what "streams" to write to. Body and/or header.
The defines are in sendf.h of course.
If CURL_DO_LINEEND_CONV is enabled, data is converted IN PLACE to the
local character encoding. This is a problem and should be changed in
the future to leave the original data alone.
*/
CURLcode Curl_client_write(struct Curl_easy *data,
int type,
char *ptr,
size_t len)
{
struct connectdata *conn = data->conn;
DEBUGASSERT(!(type & ~CLIENTWRITE_BOTH));
if(!len)
return CURLE_OK;
/* FTP data may need conversion. */
if((type & CLIENTWRITE_BODY) &&
(conn->handler->protocol & PROTO_FAMILY_FTP) &&
conn->proto.ftpc.transfertype == 'A') {
/* convert from the network encoding */
CURLcode result = Curl_convert_from_network(data, ptr, len);
/* Curl_convert_from_network calls failf if unsuccessful */
if(result)
return result;
#ifdef CURL_DO_LINEEND_CONV
/* convert end-of-line markers */
len = convert_lineends(data, ptr, len);
#endif /* CURL_DO_LINEEND_CONV */
}
return chop_write(data, type, ptr, len);
}
CURLcode Curl_read_plain(curl_socket_t sockfd,
char *buf,
size_t bytesfromsocket,
ssize_t *n)
{
ssize_t nread = sread(sockfd, buf, bytesfromsocket);
if(-1 == nread) {
const int err = SOCKERRNO;
const bool return_error =
#ifdef USE_WINSOCK
WSAEWOULDBLOCK == err
#else
EWOULDBLOCK == err || EAGAIN == err || EINTR == err
#endif
;
*n = 0; /* no data returned */
if(return_error)
return CURLE_AGAIN;
return CURLE_RECV_ERROR;
}
*n = nread;
return CURLE_OK;
}
/*
* Internal read-from-socket function. This is meant to deal with plain
* sockets, SSL sockets and kerberos sockets.
*
* Returns a regular CURLcode value.
*/
CURLcode Curl_read(struct Curl_easy *data, /* transfer */
curl_socket_t sockfd, /* read from this socket */
char *buf, /* store read data here */
size_t sizerequested, /* max amount to read */
ssize_t *n) /* amount bytes read */
{
CURLcode result = CURLE_RECV_ERROR;
ssize_t nread = 0;
size_t bytesfromsocket = 0;
char *buffertofill = NULL;
struct connectdata *conn = data->conn;
/* Set 'num' to 0 or 1, depending on which socket that has been sent here.
If it is the second socket, we set num to 1. Otherwise to 0. This lets
us use the correct ssl handle. */
int num = (sockfd == conn->sock[SECONDARYSOCKET]);
*n = 0; /* reset amount to zero */
bytesfromsocket = CURLMIN(sizerequested, (size_t)data->set.buffer_size);
buffertofill = buf;
nread = conn->recv[num](data, num, buffertofill, bytesfromsocket, &result);
if(nread < 0)
return result;
*n += nread;
return CURLE_OK;
}
/* return 0 on success */
int Curl_debug(struct Curl_easy *data, curl_infotype type,
char *ptr, size_t size)
{
int rc = 0;
if(data->set.verbose) {
static const char s_infotype[CURLINFO_END][3] = {
"* ", "< ", "> ", "{ ", "} ", "{ ", "} " };
#ifdef CURL_DOES_CONVERSIONS
char *buf = NULL;
size_t conv_size = 0;
switch(type) {
case CURLINFO_HEADER_OUT:
buf = Curl_memdup(ptr, size);
if(!buf)
return 1;
conv_size = size;
/* Special processing is needed for this block if it
* contains both headers and data (separated by CRLFCRLF).
* We want to convert just the headers, leaving the data as-is.
*/
if(size > 4) {
size_t i;
for(i = 0; i < size-4; i++) {
if(memcmp(&buf[i], "\x0d\x0a\x0d\x0a", 4) == 0) {
/* convert everything through this CRLFCRLF but no further */
conv_size = i + 4;
break;
}
}
}
Curl_convert_from_network(data, buf, conv_size);
/* Curl_convert_from_network calls failf if unsuccessful */
/* we might as well continue even if it fails... */
ptr = buf; /* switch pointer to use my buffer instead */
break;
default:
/* leave everything else as-is */
break;
}
#endif /* CURL_DOES_CONVERSIONS */
if(data->set.fdebug) {
Curl_set_in_callback(data, true);
rc = (*data->set.fdebug)(data, type, ptr, size, data->set.debugdata);
Curl_set_in_callback(data, false);
}
else {
switch(type) {
case CURLINFO_TEXT:
case CURLINFO_HEADER_OUT:
case CURLINFO_HEADER_IN:
fwrite(s_infotype[type], 2, 1, data->set.err);
fwrite(ptr, size, 1, data->set.err);
#ifdef CURL_DOES_CONVERSIONS
if(size != conv_size) {
/* we had untranslated data so we need an explicit newline */
fwrite("\n", 1, 1, data->set.err);
}
#endif
break;
default: /* nada */
break;
}
}
#ifdef CURL_DOES_CONVERSIONS
free(buf);
#endif
}
return rc;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strtoofft.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include <errno.h>
#include "curl_setup.h"
#include "strtoofft.h"
/*
* NOTE:
*
* In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we
* could use in case strtoll() doesn't exist... See
* https://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html
*/
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
# ifdef HAVE_STRTOLL
# define strtooff strtoll
# else
# if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_INTEGRAL_MAX_BITS >= 64)
# if defined(_SAL_VERSION)
_Check_return_ _CRTIMP __int64 __cdecl _strtoi64(
_In_z_ const char *_String,
_Out_opt_ _Deref_post_z_ char **_EndPtr, _In_ int _Radix);
# else
_CRTIMP __int64 __cdecl _strtoi64(const char *_String,
char **_EndPtr, int _Radix);
# endif
# define strtooff _strtoi64
# else
# define PRIVATE_STRTOOFF 1
# endif
# endif
#else
# define strtooff strtol
#endif
#ifdef PRIVATE_STRTOOFF
/* Range tests can be used for alphanum decoding if characters are consecutive,
like in ASCII. Else an array is scanned. Determine this condition now. */
#if('9' - '0') != 9 || ('Z' - 'A') != 25 || ('z' - 'a') != 25
#define NO_RANGE_TEST
static const char valchars[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#endif
static int get_char(char c, int base);
/**
* Custom version of the strtooff function. This extracts a curl_off_t
* value from the given input string and returns it.
*/
static curl_off_t strtooff(const char *nptr, char **endptr, int base)
{
char *end;
int is_negative = 0;
int overflow;
int i;
curl_off_t value = 0;
curl_off_t newval;
/* Skip leading whitespace. */
end = (char *)nptr;
while(ISSPACE(end[0])) {
end++;
}
/* Handle the sign, if any. */
if(end[0] == '-') {
is_negative = 1;
end++;
}
else if(end[0] == '+') {
end++;
}
else if(end[0] == '\0') {
/* We had nothing but perhaps some whitespace -- there was no number. */
if(endptr) {
*endptr = end;
}
return 0;
}
/* Handle special beginnings, if present and allowed. */
if(end[0] == '0' && end[1] == 'x') {
if(base == 16 || base == 0) {
end += 2;
base = 16;
}
}
else if(end[0] == '0') {
if(base == 8 || base == 0) {
end++;
base = 8;
}
}
/* Matching strtol, if the base is 0 and it doesn't look like
* the number is octal or hex, we assume it's base 10.
*/
if(base == 0) {
base = 10;
}
/* Loop handling digits. */
value = 0;
overflow = 0;
for(i = get_char(end[0], base);
i != -1;
end++, i = get_char(end[0], base)) {
newval = base * value + i;
if(newval < value) {
/* We've overflowed. */
overflow = 1;
break;
}
else
value = newval;
}
if(!overflow) {
if(is_negative) {
/* Fix the sign. */
value *= -1;
}
}
else {
if(is_negative)
value = CURL_OFF_T_MIN;
else
value = CURL_OFF_T_MAX;
errno = ERANGE;
}
if(endptr)
*endptr = end;
return value;
}
/**
* Returns the value of c in the given base, or -1 if c cannot
* be interpreted properly in that base (i.e., is out of range,
* is a null, etc.).
*
* @param c the character to interpret according to base
* @param base the base in which to interpret c
*
* @return the value of c in base, or -1 if c isn't in range
*/
static int get_char(char c, int base)
{
#ifndef NO_RANGE_TEST
int value = -1;
if(c <= '9' && c >= '0') {
value = c - '0';
}
else if(c <= 'Z' && c >= 'A') {
value = c - 'A' + 10;
}
else if(c <= 'z' && c >= 'a') {
value = c - 'a' + 10;
}
#else
const char *cp;
int value;
cp = memchr(valchars, c, 10 + 26 + 26);
if(!cp)
return -1;
value = cp - valchars;
if(value >= 10 + 26)
value -= 26; /* Lowercase. */
#endif
if(value >= base) {
value = -1;
}
return value;
}
#endif /* Only present if we need strtoll, but don't have it. */
/*
* Parse a *positive* up to 64 bit number written in ascii.
*/
CURLofft curlx_strtoofft(const char *str, char **endp, int base,
curl_off_t *num)
{
char *end;
curl_off_t number;
errno = 0;
*num = 0; /* clear by default */
while(*str && ISSPACE(*str))
str++;
if('-' == *str) {
if(endp)
*endp = (char *)str; /* didn't actually move */
return CURL_OFFT_INVAL; /* nothing parsed */
}
number = strtooff(str, &end, base);
if(endp)
*endp = end;
if(errno == ERANGE)
/* overflow/underflow */
return CURL_OFFT_FLOW;
else if(str == end)
/* nothing parsed */
return CURL_OFFT_INVAL;
*num = number;
return CURL_OFFT_OK;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/CMakeLists.txt | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
set(LIB_NAME libcurl)
set(LIBCURL_OUTPUT_NAME libcurl CACHE STRING "Basename of the curl library")
if(BUILD_SHARED_LIBS)
set(CURL_STATICLIB NO)
else()
set(CURL_STATICLIB YES)
endif()
# Use:
# * CURL_STATICLIB
configure_file(curl_config.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/curl_config.h)
transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake)
list(APPEND HHEADERS
${CMAKE_CURRENT_BINARY_DIR}/curl_config.h
)
if(WIN32)
list(APPEND CSOURCES libcurl.rc)
endif()
# SET(CSOURCES
# # memdebug.c -not used
# # nwlib.c - Not used
# # strtok.c - specify later
# # strtoofft.c - specify later
# )
# #OPTION(CURL_MALLOC_DEBUG "Debug mallocs in Curl" OFF)
# MARK_AS_ADVANCED(CURL_MALLOC_DEBUG)
# IF(CURL_MALLOC_DEBUG)
# SET(CSOURCES ${CSOURCES}
# memdebug.c
# )
# ENDIF(CURL_MALLOC_DEBUG)
# # only build compat strtoofft if we need to
# IF(NOT HAVE_STRTOLL AND NOT HAVE__STRTOI64)
# SET(CSOURCES ${CSOURCES}
# strtoofft.c
# )
# ENDIF(NOT HAVE_STRTOLL AND NOT HAVE__STRTOI64)
# The rest of the build
include_directories(${CMAKE_CURRENT_BINARY_DIR}/../include)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/..)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
if(USE_ARES)
include_directories(${CARES_INCLUDE_DIR})
endif()
add_library(
${LIB_NAME}
${HHEADERS} ${CSOURCES}
)
add_library(
${PROJECT_NAME}::${LIB_NAME}
ALIAS ${LIB_NAME}
)
if(NOT BUILD_SHARED_LIBS)
set_target_properties(${LIB_NAME} PROPERTIES INTERFACE_COMPILE_DEFINITIONS CURL_STATICLIB)
endif()
target_link_libraries(${LIB_NAME} ${CURL_LIBS})
if(WIN32)
add_definitions(-D_USRDLL)
endif()
set_target_properties(${LIB_NAME} PROPERTIES
COMPILE_DEFINITIONS BUILDING_LIBCURL
OUTPUT_NAME ${LIBCURL_OUTPUT_NAME}
)
if(HIDES_CURL_PRIVATE_SYMBOLS)
set_property(TARGET ${LIB_NAME} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS")
set_property(TARGET ${LIB_NAME} APPEND PROPERTY COMPILE_FLAGS ${CURL_CFLAG_SYMBOLS_HIDE})
endif()
# Remove the "lib" prefix since the library is already named "libcurl".
set_target_properties(${LIB_NAME} PROPERTIES PREFIX "")
set_target_properties(${LIB_NAME} PROPERTIES IMPORT_PREFIX "")
if(CURL_HAS_LTO)
set_target_properties(${LIB_NAME} PROPERTIES
INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE
INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO TRUE)
endif()
if(WIN32)
if(BUILD_SHARED_LIBS)
if(MSVC)
# Add "_imp" as a suffix before the extension to avoid conflicting with
# the statically linked "libcurl.lib"
set_target_properties(${LIB_NAME} PROPERTIES IMPORT_SUFFIX "_imp.lib")
endif()
endif()
endif()
target_include_directories(${LIB_NAME} INTERFACE
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
$<BUILD_INTERFACE:${CURL_SOURCE_DIR}/include>)
install(TARGETS ${LIB_NAME}
EXPORT ${TARGETS_EXPORT_NAME}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
export(TARGETS ${LIB_NAME}
APPEND FILE ${PROJECT_BINARY_DIR}/libcurl-target.cmake
NAMESPACE ${PROJECT_NAME}::
)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/dict.h | #ifndef HEADER_CURL_DICT_H
#define HEADER_CURL_DICT_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifndef CURL_DISABLE_DICT
extern const struct Curl_handler Curl_handler_dict;
#endif
#endif /* HEADER_CURL_DICT_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/doh.h | #ifndef HEADER_CURL_DOH_H
#define HEADER_CURL_DOH_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "urldata.h"
#include "curl_addrinfo.h"
#ifndef CURL_DISABLE_DOH
/*
* 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);
int Curl_doh_getsock(struct connectdata *conn, curl_socket_t *socks);
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 */
} DNStype;
#define DOH_MAX_ADDR 24
#define DOH_MAX_CNAME 4
struct dohaddr {
int type;
union {
unsigned char v4[4]; /* network byte order */
unsigned char v6[16];
} ip;
};
struct dohentry {
struct dynbuf cname[DOH_MAX_CNAME];
struct dohaddr addr[DOH_MAX_ADDR];
int numaddr;
unsigned int ttl;
int numcname;
};
#ifdef DEBUGBUILD
DOHcode doh_encode(const char *host,
DNStype dnstype,
unsigned char *dnsp, /* buffer */
size_t len, /* buffer size */
size_t *olen); /* output length */
DOHcode doh_decode(const unsigned char *doh,
size_t dohlen,
DNStype dnstype,
struct dohentry *d);
void de_init(struct dohentry *d);
void de_cleanup(struct dohentry *d);
#endif
#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 */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_negotiate.h | #ifndef HEADER_CURL_HTTP_NEGOTIATE_H
#define HEADER_CURL_HTTP_NEGOTIATE_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO)
/* this is for Negotiate header input */
CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn,
bool proxy, const char *header);
/* this is for creating Negotiate header output */
CURLcode Curl_output_negotiate(struct Curl_easy *data,
struct connectdata *conn, bool proxy);
void Curl_http_auth_cleanup_negotiate(struct connectdata *conn);
#else /* !CURL_DISABLE_HTTP && USE_SPNEGO */
#define Curl_http_auth_cleanup_negotiate(x)
#endif
#endif /* HEADER_CURL_HTTP_NEGOTIATE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/Makefile.inc | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
LIB_VAUTH_CFILES = \
vauth/cleartext.c \
vauth/cram.c \
vauth/digest.c \
vauth/digest_sspi.c \
vauth/gsasl.c \
vauth/krb5_gssapi.c \
vauth/krb5_sspi.c \
vauth/ntlm.c \
vauth/ntlm_sspi.c \
vauth/oauth2.c \
vauth/spnego_gssapi.c \
vauth/spnego_sspi.c \
vauth/vauth.c
LIB_VAUTH_HFILES = \
vauth/digest.h \
vauth/ntlm.h \
vauth/vauth.h
LIB_VTLS_CFILES = \
vtls/bearssl.c \
vtls/gskit.c \
vtls/gtls.c \
vtls/keylog.c \
vtls/mbedtls.c \
vtls/mbedtls_threadlock.c \
vtls/mesalink.c \
vtls/nss.c \
vtls/openssl.c \
vtls/rustls.c \
vtls/schannel.c \
vtls/schannel_verify.c \
vtls/sectransp.c \
vtls/vtls.c \
vtls/wolfssl.c
LIB_VTLS_HFILES = \
vtls/bearssl.h \
vtls/gskit.h \
vtls/gtls.h \
vtls/keylog.h \
vtls/mbedtls.h \
vtls/mbedtls_threadlock.h \
vtls/mesalink.h \
vtls/nssg.h \
vtls/openssl.h \
vtls/rustls.h \
vtls/schannel.h \
vtls/sectransp.h \
vtls/vtls.h \
vtls/wolfssl.h
LIB_VQUIC_CFILES = \
vquic/ngtcp2.c \
vquic/quiche.c \
vquic/vquic.c
LIB_VQUIC_HFILES = \
vquic/ngtcp2.h \
vquic/quiche.h \
vquic/vquic.h
LIB_VSSH_CFILES = \
vssh/libssh.c \
vssh/libssh2.c \
vssh/wolfssh.c
LIB_VSSH_HFILES = \
vssh/ssh.h
LIB_CFILES = \
altsvc.c \
amigaos.c \
asyn-ares.c \
asyn-thread.c \
base64.c \
bufref.c \
c-hyper.c \
conncache.c \
connect.c \
content_encoding.c \
cookie.c \
curl_addrinfo.c \
curl_ctype.c \
curl_des.c \
curl_endian.c \
curl_fnmatch.c \
curl_get_line.c \
curl_gethostname.c \
curl_gssapi.c \
curl_memrchr.c \
curl_multibyte.c \
curl_ntlm_core.c \
curl_ntlm_wb.c \
curl_path.c \
curl_range.c \
curl_rtmp.c \
curl_sasl.c \
curl_sspi.c \
curl_threads.c \
dict.c \
doh.c \
dotdot.c \
dynbuf.c \
easy.c \
easygetopt.c \
easyoptions.c \
escape.c \
file.c \
fileinfo.c \
formdata.c \
ftp.c \
ftplistparser.c \
getenv.c \
getinfo.c \
gopher.c \
hash.c \
hmac.c \
hostasyn.c \
hostcheck.c \
hostip.c \
hostip4.c \
hostip6.c \
hostsyn.c \
hsts.c \
http.c \
http2.c \
http_chunks.c \
http_digest.c \
http_negotiate.c \
http_ntlm.c \
http_proxy.c \
http_aws_sigv4.c \
idn_win32.c \
if2ip.c \
imap.c \
inet_ntop.c \
inet_pton.c \
krb5.c \
ldap.c \
llist.c \
md4.c \
md5.c \
memdebug.c \
mime.c \
mprintf.c \
mqtt.c \
multi.c \
netrc.c \
non-ascii.c \
nonblock.c \
openldap.c \
parsedate.c \
pingpong.c \
pop3.c \
progress.c \
psl.c \
rand.c \
rename.c \
rtsp.c \
select.c \
sendf.c \
setopt.c \
sha256.c \
share.c \
slist.c \
smb.c \
smtp.c \
socketpair.c \
socks.c \
socks_gssapi.c \
socks_sspi.c \
speedcheck.c \
splay.c \
strcase.c \
strdup.c \
strerror.c \
strtok.c \
strtoofft.c \
system_win32.c \
telnet.c \
tftp.c \
timeval.c \
transfer.c \
url.c \
urlapi.c \
version.c \
version_win32.c \
warnless.c \
wildcard.c \
x509asn1.c
LIB_HFILES = \
altsvc.h \
amigaos.h \
arpa_telnet.h \
asyn.h \
bufref.h \
c-hyper.h \
conncache.h \
connect.h \
content_encoding.h \
cookie.h \
curl_addrinfo.h \
curl_base64.h \
curl_ctype.h \
curl_des.h \
curl_endian.h \
curl_fnmatch.h \
curl_get_line.h \
curl_gethostname.h \
curl_gssapi.h \
curl_hmac.h \
curl_krb5.h \
curl_ldap.h \
curl_md4.h \
curl_md5.h \
curl_memory.h \
curl_memrchr.h \
curl_multibyte.h \
curl_ntlm_core.h \
curl_ntlm_wb.h \
curl_path.h \
curl_printf.h \
curl_range.h \
curl_rtmp.h \
curl_sasl.h \
curl_setup.h \
curl_setup_once.h \
curl_sha256.h \
curl_sspi.h \
curl_threads.h \
curlx.h \
dict.h \
doh.h \
dotdot.h \
dynbuf.h \
easyif.h \
easyoptions.h \
escape.h \
file.h \
fileinfo.h \
formdata.h \
ftp.h \
ftplistparser.h \
getinfo.h \
gopher.h \
hash.h \
hostcheck.h \
hostip.h \
hsts.h \
http.h \
http2.h \
http_chunks.h \
http_digest.h \
http_negotiate.h \
http_ntlm.h \
http_proxy.h \
http_aws_sigv4.h \
if2ip.h \
imap.h \
inet_ntop.h \
inet_pton.h \
llist.h \
memdebug.h \
mime.h \
mqtt.h \
multihandle.h \
multiif.h \
netrc.h \
non-ascii.h \
nonblock.h \
parsedate.h \
pingpong.h \
pop3.h \
progress.h \
psl.h \
quic.h \
rand.h \
rename.h \
rtsp.h \
select.h \
sendf.h \
setopt.h \
setup-vms.h \
share.h \
sigpipe.h \
slist.h \
smb.h \
smtp.h \
sockaddr.h \
socketpair.h \
socks.h \
speedcheck.h \
splay.h \
strcase.h \
strdup.h \
strerror.h \
strtok.h \
strtoofft.h \
system_win32.h \
telnet.h \
tftp.h \
timeval.h \
transfer.h \
url.h \
urlapi-int.h \
urldata.h \
version_win32.h \
warnless.h \
wildcard.h \
x509asn1.h
LIB_RCFILES = libcurl.rc
CSOURCES = $(LIB_CFILES) $(LIB_VAUTH_CFILES) $(LIB_VTLS_CFILES) \
$(LIB_VQUIC_CFILES) $(LIB_VSSH_CFILES)
HHEADERS = $(LIB_HFILES) $(LIB_VAUTH_HFILES) $(LIB_VTLS_HFILES) \
$(LIB_VQUIC_HFILES) $(LIB_VSSH_HFILES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/lib/strerror.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2004 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_STRERROR_R
# if (!defined(HAVE_POSIX_STRERROR_R) && \
!defined(HAVE_GLIBC_STRERROR_R) && \
!defined(HAVE_VXWORKS_STRERROR_R)) || \
(defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
(defined(HAVE_GLIBC_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)) || \
(defined(HAVE_POSIX_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R))
# error "strerror_r MUST be either POSIX, glibc or vxworks-style"
# endif
#endif
#include <curl/curl.h>
#ifdef USE_LIBIDN2
#include <idn2.h>
#endif
#ifdef USE_WINDOWS_SSPI
#include "curl_sspi.h"
#endif
#include "strerror.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
#if defined(WIN32) || defined(_WIN32_WCE)
#define PRESERVE_WINDOWS_ERROR_CODE
#endif
const char *
curl_easy_strerror(CURLcode error)
{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
case CURLE_OK:
return "No error";
case CURLE_UNSUPPORTED_PROTOCOL:
return "Unsupported protocol";
case CURLE_FAILED_INIT:
return "Failed initialization";
case CURLE_URL_MALFORMAT:
return "URL using bad/illegal format or missing URL";
case CURLE_NOT_BUILT_IN:
return "A requested feature, protocol or option was not found built-in in"
" this libcurl due to a build-time decision.";
case CURLE_COULDNT_RESOLVE_PROXY:
return "Couldn't resolve proxy name";
case CURLE_COULDNT_RESOLVE_HOST:
return "Couldn't resolve host name";
case CURLE_COULDNT_CONNECT:
return "Couldn't connect to server";
case CURLE_WEIRD_SERVER_REPLY:
return "Weird server reply";
case CURLE_REMOTE_ACCESS_DENIED:
return "Access denied to remote resource";
case CURLE_FTP_ACCEPT_FAILED:
return "FTP: The server failed to connect to data port";
case CURLE_FTP_ACCEPT_TIMEOUT:
return "FTP: Accepting server connect has timed out";
case CURLE_FTP_PRET_FAILED:
return "FTP: The server did not accept the PRET command.";
case CURLE_FTP_WEIRD_PASS_REPLY:
return "FTP: unknown PASS reply";
case CURLE_FTP_WEIRD_PASV_REPLY:
return "FTP: unknown PASV reply";
case CURLE_FTP_WEIRD_227_FORMAT:
return "FTP: unknown 227 response format";
case CURLE_FTP_CANT_GET_HOST:
return "FTP: can't figure out the host in the PASV response";
case CURLE_HTTP2:
return "Error in the HTTP2 framing layer";
case CURLE_FTP_COULDNT_SET_TYPE:
return "FTP: couldn't set file type";
case CURLE_PARTIAL_FILE:
return "Transferred a partial file";
case CURLE_FTP_COULDNT_RETR_FILE:
return "FTP: couldn't retrieve (RETR failed) the specified file";
case CURLE_QUOTE_ERROR:
return "Quote command returned error";
case CURLE_HTTP_RETURNED_ERROR:
return "HTTP response code said error";
case CURLE_WRITE_ERROR:
return "Failed writing received data to disk/application";
case CURLE_UPLOAD_FAILED:
return "Upload failed (at start/before it took off)";
case CURLE_READ_ERROR:
return "Failed to open/read local data from file/application";
case CURLE_OUT_OF_MEMORY:
return "Out of memory";
case CURLE_OPERATION_TIMEDOUT:
return "Timeout was reached";
case CURLE_FTP_PORT_FAILED:
return "FTP: command PORT failed";
case CURLE_FTP_COULDNT_USE_REST:
return "FTP: command REST failed";
case CURLE_RANGE_ERROR:
return "Requested range was not delivered by the server";
case CURLE_HTTP_POST_ERROR:
return "Internal problem setting up the POST";
case CURLE_SSL_CONNECT_ERROR:
return "SSL connect error";
case CURLE_BAD_DOWNLOAD_RESUME:
return "Couldn't resume download";
case CURLE_FILE_COULDNT_READ_FILE:
return "Couldn't read a file:// file";
case CURLE_LDAP_CANNOT_BIND:
return "LDAP: cannot bind";
case CURLE_LDAP_SEARCH_FAILED:
return "LDAP: search failed";
case CURLE_FUNCTION_NOT_FOUND:
return "A required function in the library was not found";
case CURLE_ABORTED_BY_CALLBACK:
return "Operation was aborted by an application callback";
case CURLE_BAD_FUNCTION_ARGUMENT:
return "A libcurl function was given a bad argument";
case CURLE_INTERFACE_FAILED:
return "Failed binding local connection end";
case CURLE_TOO_MANY_REDIRECTS :
return "Number of redirects hit maximum amount";
case CURLE_UNKNOWN_OPTION:
return "An unknown option was passed in to libcurl";
case CURLE_SETOPT_OPTION_SYNTAX :
return "Malformed option provided in a setopt";
case CURLE_GOT_NOTHING:
return "Server returned nothing (no headers, no data)";
case CURLE_SSL_ENGINE_NOTFOUND:
return "SSL crypto engine not found";
case CURLE_SSL_ENGINE_SETFAILED:
return "Can not set SSL crypto engine as default";
case CURLE_SSL_ENGINE_INITFAILED:
return "Failed to initialise SSL crypto engine";
case CURLE_SEND_ERROR:
return "Failed sending data to the peer";
case CURLE_RECV_ERROR:
return "Failure when receiving data from the peer";
case CURLE_SSL_CERTPROBLEM:
return "Problem with the local SSL certificate";
case CURLE_SSL_CIPHER:
return "Couldn't use specified SSL cipher";
case CURLE_PEER_FAILED_VERIFICATION:
return "SSL peer certificate or SSH remote key was not OK";
case CURLE_SSL_CACERT_BADFILE:
return "Problem with the SSL CA cert (path? access rights?)";
case CURLE_BAD_CONTENT_ENCODING:
return "Unrecognized or bad HTTP Content or Transfer-Encoding";
case CURLE_LDAP_INVALID_URL:
return "Invalid LDAP URL";
case CURLE_FILESIZE_EXCEEDED:
return "Maximum file size exceeded";
case CURLE_USE_SSL_FAILED:
return "Requested SSL level failed";
case CURLE_SSL_SHUTDOWN_FAILED:
return "Failed to shut down the SSL connection";
case CURLE_SSL_CRL_BADFILE:
return "Failed to load CRL file (path? access rights?, format?)";
case CURLE_SSL_ISSUER_ERROR:
return "Issuer check against peer certificate failed";
case CURLE_SEND_FAIL_REWIND:
return "Send failed since rewinding of the data stream failed";
case CURLE_LOGIN_DENIED:
return "Login denied";
case CURLE_TFTP_NOTFOUND:
return "TFTP: File Not Found";
case CURLE_TFTP_PERM:
return "TFTP: Access Violation";
case CURLE_REMOTE_DISK_FULL:
return "Disk full or allocation exceeded";
case CURLE_TFTP_ILLEGAL:
return "TFTP: Illegal operation";
case CURLE_TFTP_UNKNOWNID:
return "TFTP: Unknown transfer ID";
case CURLE_REMOTE_FILE_EXISTS:
return "Remote file already exists";
case CURLE_TFTP_NOSUCHUSER:
return "TFTP: No such user";
case CURLE_CONV_FAILED:
return "Conversion failed";
case CURLE_CONV_REQD:
return "Caller must register CURLOPT_CONV_ callback options";
case CURLE_REMOTE_FILE_NOT_FOUND:
return "Remote file not found";
case CURLE_SSH:
return "Error in the SSH layer";
case CURLE_AGAIN:
return "Socket not ready for send/recv";
case CURLE_RTSP_CSEQ_ERROR:
return "RTSP CSeq mismatch or invalid CSeq";
case CURLE_RTSP_SESSION_ERROR:
return "RTSP session error";
case CURLE_FTP_BAD_FILE_LIST:
return "Unable to parse FTP file list";
case CURLE_CHUNK_FAILED:
return "Chunk callback failed";
case CURLE_NO_CONNECTION_AVAILABLE:
return "The max connection limit is reached";
case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
return "SSL public key does not match pinned public key";
case CURLE_SSL_INVALIDCERTSTATUS:
return "SSL server certificate status verification FAILED";
case CURLE_HTTP2_STREAM:
return "Stream error in the HTTP/2 framing layer";
case CURLE_RECURSIVE_API_CALL:
return "API function called from within callback";
case CURLE_AUTH_ERROR:
return "An authentication function returned an error";
case CURLE_HTTP3:
return "HTTP/3 error";
case CURLE_QUIC_CONNECT_ERROR:
return "QUIC connection error";
case CURLE_PROXY:
return "proxy handshake error";
case CURLE_SSL_CLIENTCERT:
return "SSL Client Certificate required";
/* error codes not used by current libcurl */
case CURLE_OBSOLETE20:
case CURLE_OBSOLETE24:
case CURLE_OBSOLETE29:
case CURLE_OBSOLETE32:
case CURLE_OBSOLETE40:
case CURLE_OBSOLETE44:
case CURLE_OBSOLETE46:
case CURLE_OBSOLETE50:
case CURLE_OBSOLETE51:
case CURLE_OBSOLETE57:
case CURL_LAST:
break;
}
/*
* By using a switch, gcc -Wall will complain about enum values
* which do not appear, helping keep this function up-to-date.
* By using gcc -Wall -Werror, you can't forget.
*
* A table would not have the same benefit. Most compilers will
* generate code very similar to a table in any case, so there
* is little performance gain from a table. And something is broken
* for the user's application, anyways, so does it matter how fast
* it _doesn't_ work?
*
* The line number for the error will be near this comment, which
* is why it is here, and not at the start of the switch.
*/
return "Unknown error";
#else
if(!error)
return "No error";
else
return "Error";
#endif
}
const char *
curl_multi_strerror(CURLMcode error)
{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
case CURLM_CALL_MULTI_PERFORM:
return "Please call curl_multi_perform() soon";
case CURLM_OK:
return "No error";
case CURLM_BAD_HANDLE:
return "Invalid multi handle";
case CURLM_BAD_EASY_HANDLE:
return "Invalid easy handle";
case CURLM_OUT_OF_MEMORY:
return "Out of memory";
case CURLM_INTERNAL_ERROR:
return "Internal error";
case CURLM_BAD_SOCKET:
return "Invalid socket argument";
case CURLM_UNKNOWN_OPTION:
return "Unknown option";
case CURLM_ADDED_ALREADY:
return "The easy handle is already added to a multi handle";
case CURLM_RECURSIVE_API_CALL:
return "API function called from within callback";
case CURLM_WAKEUP_FAILURE:
return "Wakeup is unavailable or failed";
case CURLM_BAD_FUNCTION_ARGUMENT:
return "A libcurl function was given a bad argument";
case CURLM_LAST:
break;
}
return "Unknown error";
#else
if(error == CURLM_OK)
return "No error";
else
return "Error";
#endif
}
const char *
curl_share_strerror(CURLSHcode error)
{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
case CURLSHE_OK:
return "No error";
case CURLSHE_BAD_OPTION:
return "Unknown share option";
case CURLSHE_IN_USE:
return "Share currently in use";
case CURLSHE_INVALID:
return "Invalid share handle";
case CURLSHE_NOMEM:
return "Out of memory";
case CURLSHE_NOT_BUILT_IN:
return "Feature not enabled in this library";
case CURLSHE_LAST:
break;
}
return "CURLSHcode unknown";
#else
if(error == CURLSHE_OK)
return "No error";
else
return "Error";
#endif
}
const char *
curl_url_strerror(CURLUcode error)
{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(error) {
case CURLUE_OK:
return "No error";
case CURLUE_BAD_HANDLE:
return "An invalid CURLU pointer was passed as argument";
case CURLUE_BAD_PARTPOINTER:
return "An invalid 'part' argument was passed as argument";
case CURLUE_MALFORMED_INPUT:
return "A malformed input was passed to a URL API function";
case CURLUE_BAD_PORT_NUMBER:
return "The port number was not a decimal number between 0 and 65535";
case CURLUE_UNSUPPORTED_SCHEME:
return "This libcurl build doesn't support the given URL scheme";
case CURLUE_URLDECODE:
return "URL decode error, most likely because of rubbish in the input";
case CURLUE_OUT_OF_MEMORY:
return "A memory function failed";
case CURLUE_USER_NOT_ALLOWED:
return "Credentials was passed in the URL when prohibited";
case CURLUE_UNKNOWN_PART:
return "An unknown part ID was passed to a URL API function";
case CURLUE_NO_SCHEME:
return "There is no scheme part in the URL";
case CURLUE_NO_USER:
return "There is no user part in the URL";
case CURLUE_NO_PASSWORD:
return "There is no password part in the URL";
case CURLUE_NO_OPTIONS:
return "There is no options part in the URL";
case CURLUE_NO_HOST:
return "There is no host part in the URL";
case CURLUE_NO_PORT:
return "There is no port part in the URL";
case CURLUE_NO_QUERY:
return "There is no query part in the URL";
case CURLUE_NO_FRAGMENT:
return "There is no fragment part in the URL";
case CURLUE_LAST:
break;
}
return "CURLUcode unknown";
#else
if(error == CURLUE_OK)
return "No error";
else
return "Error";
#endif
}
#ifdef USE_WINSOCK
/* This is a helper function for Curl_strerror that converts Winsock error
* codes (WSAGetLastError) to error messages.
* Returns NULL if no error message was found for error code.
*/
static const char *
get_winsock_error (int err, char *buf, size_t len)
{
#ifndef CURL_DISABLE_VERBOSE_STRINGS
const char *p;
#endif
if(!len)
return NULL;
*buf = '\0';
#ifdef CURL_DISABLE_VERBOSE_STRINGS
(void)err;
return NULL;
#else
switch(err) {
case WSAEINTR:
p = "Call interrupted";
break;
case WSAEBADF:
p = "Bad file";
break;
case WSAEACCES:
p = "Bad access";
break;
case WSAEFAULT:
p = "Bad argument";
break;
case WSAEINVAL:
p = "Invalid arguments";
break;
case WSAEMFILE:
p = "Out of file descriptors";
break;
case WSAEWOULDBLOCK:
p = "Call would block";
break;
case WSAEINPROGRESS:
case WSAEALREADY:
p = "Blocking call in progress";
break;
case WSAENOTSOCK:
p = "Descriptor is not a socket";
break;
case WSAEDESTADDRREQ:
p = "Need destination address";
break;
case WSAEMSGSIZE:
p = "Bad message size";
break;
case WSAEPROTOTYPE:
p = "Bad protocol";
break;
case WSAENOPROTOOPT:
p = "Protocol option is unsupported";
break;
case WSAEPROTONOSUPPORT:
p = "Protocol is unsupported";
break;
case WSAESOCKTNOSUPPORT:
p = "Socket is unsupported";
break;
case WSAEOPNOTSUPP:
p = "Operation not supported";
break;
case WSAEAFNOSUPPORT:
p = "Address family not supported";
break;
case WSAEPFNOSUPPORT:
p = "Protocol family not supported";
break;
case WSAEADDRINUSE:
p = "Address already in use";
break;
case WSAEADDRNOTAVAIL:
p = "Address not available";
break;
case WSAENETDOWN:
p = "Network down";
break;
case WSAENETUNREACH:
p = "Network unreachable";
break;
case WSAENETRESET:
p = "Network has been reset";
break;
case WSAECONNABORTED:
p = "Connection was aborted";
break;
case WSAECONNRESET:
p = "Connection was reset";
break;
case WSAENOBUFS:
p = "No buffer space";
break;
case WSAEISCONN:
p = "Socket is already connected";
break;
case WSAENOTCONN:
p = "Socket is not connected";
break;
case WSAESHUTDOWN:
p = "Socket has been shut down";
break;
case WSAETOOMANYREFS:
p = "Too many references";
break;
case WSAETIMEDOUT:
p = "Timed out";
break;
case WSAECONNREFUSED:
p = "Connection refused";
break;
case WSAELOOP:
p = "Loop??";
break;
case WSAENAMETOOLONG:
p = "Name too long";
break;
case WSAEHOSTDOWN:
p = "Host down";
break;
case WSAEHOSTUNREACH:
p = "Host unreachable";
break;
case WSAENOTEMPTY:
p = "Not empty";
break;
case WSAEPROCLIM:
p = "Process limit reached";
break;
case WSAEUSERS:
p = "Too many users";
break;
case WSAEDQUOT:
p = "Bad quota";
break;
case WSAESTALE:
p = "Something is stale";
break;
case WSAEREMOTE:
p = "Remote error";
break;
#ifdef WSAEDISCON /* missing in SalfordC! */
case WSAEDISCON:
p = "Disconnected";
break;
#endif
/* Extended Winsock errors */
case WSASYSNOTREADY:
p = "Winsock library is not ready";
break;
case WSANOTINITIALISED:
p = "Winsock library not initialised";
break;
case WSAVERNOTSUPPORTED:
p = "Winsock version not supported";
break;
/* getXbyY() errors (already handled in herrmsg):
* Authoritative Answer: Host not found */
case WSAHOST_NOT_FOUND:
p = "Host not found";
break;
/* Non-Authoritative: Host not found, or SERVERFAIL */
case WSATRY_AGAIN:
p = "Host not found, try again";
break;
/* Non recoverable errors, FORMERR, REFUSED, NOTIMP */
case WSANO_RECOVERY:
p = "Unrecoverable error in call to nameserver";
break;
/* Valid name, no data record of requested type */
case WSANO_DATA:
p = "No data record of requested type";
break;
default:
return NULL;
}
strncpy(buf, p, len);
buf [len-1] = '\0';
return buf;
#endif
}
#endif /* USE_WINSOCK */
#if defined(WIN32) || defined(_WIN32_WCE)
/* This is a helper function for Curl_strerror that converts Windows API error
* codes (GetLastError) to error messages.
* Returns NULL if no error message was found for error code.
*/
static const char *
get_winapi_error(int err, char *buf, size_t buflen)
{
char *p;
wchar_t wbuf[256];
if(!buflen)
return NULL;
*buf = '\0';
*wbuf = L'\0';
/* We return the local codepage version of the error string because if it is
output to the user's terminal it will likely be with functions which
expect the local codepage (eg fprintf, failf, infof).
FormatMessageW -> wcstombs is used for Windows CE compatibility. */
if(FormatMessageW((FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err,
LANG_NEUTRAL, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL)) {
size_t written = wcstombs(buf, wbuf, buflen - 1);
if(written != (size_t)-1)
buf[written] = '\0';
else
*buf = '\0';
}
/* Truncate multiple lines */
p = strchr(buf, '\n');
if(p) {
if(p > buf && *(p-1) == '\r')
*(p-1) = '\0';
else
*p = '\0';
}
return (*buf ? buf : NULL);
}
#endif /* WIN32 || _WIN32_WCE */
/*
* Our thread-safe and smart strerror() replacement.
*
* The 'err' argument passed in to this function MUST be a true errno number
* as reported on this system. We do no range checking on the number before
* we pass it to the "number-to-message" conversion function and there might
* be systems that don't do proper range checking in there themselves.
*
* We don't do range checking (on systems other than Windows) since there is
* no good reliable and portable way to do it.
*
* On Windows different types of error codes overlap. This function has an
* order of preference when trying to match error codes:
* CRT (errno), Winsock (WSAGetLastError), Windows API (GetLastError).
*
* It may be more correct to call one of the variant functions instead:
* Call Curl_sspi_strerror if the error code is definitely Windows SSPI.
* Call Curl_winapi_strerror if the error code is definitely Windows API.
*/
const char *Curl_strerror(int err, char *buf, size_t buflen)
{
#ifdef PRESERVE_WINDOWS_ERROR_CODE
DWORD old_win_err = GetLastError();
#endif
int old_errno = errno;
char *p;
size_t max;
if(!buflen)
return NULL;
#ifndef WIN32
DEBUGASSERT(err >= 0);
#endif
max = buflen - 1;
*buf = '\0';
#if defined(WIN32) || defined(_WIN32_WCE)
#if defined(WIN32)
/* 'sys_nerr' is the maximum errno number, it is not widely portable */
if(err >= 0 && err < sys_nerr)
strncpy(buf, sys_errlist[err], max);
else
#endif
{
if(
#ifdef USE_WINSOCK
!get_winsock_error(err, buf, max) &&
#endif
!get_winapi_error((DWORD)err, buf, max))
msnprintf(buf, max, "Unknown error %d (%#x)", err, err);
}
#else /* not Windows coming up */
#if defined(HAVE_STRERROR_R) && defined(HAVE_POSIX_STRERROR_R)
/*
* The POSIX-style strerror_r() may set errno to ERANGE if insufficient
* storage is supplied via 'strerrbuf' and 'buflen' to hold the generated
* message string, or EINVAL if 'errnum' is not a valid error number.
*/
if(0 != strerror_r(err, buf, max)) {
if('\0' == buf[0])
msnprintf(buf, max, "Unknown error %d", err);
}
#elif defined(HAVE_STRERROR_R) && defined(HAVE_GLIBC_STRERROR_R)
/*
* The glibc-style strerror_r() only *might* use the buffer we pass to
* the function, but it always returns the error message as a pointer,
* so we must copy that string unconditionally (if non-NULL).
*/
{
char buffer[256];
char *msg = strerror_r(err, buffer, sizeof(buffer));
if(msg)
strncpy(buf, msg, max);
else
msnprintf(buf, max, "Unknown error %d", err);
}
#elif defined(HAVE_STRERROR_R) && defined(HAVE_VXWORKS_STRERROR_R)
/*
* The vxworks-style strerror_r() does use the buffer we pass to the function.
* The buffer size should be at least NAME_MAX (256)
*/
{
char buffer[256];
if(OK == strerror_r(err, buffer))
strncpy(buf, buffer, max);
else
msnprintf(buf, max, "Unknown error %d", err);
}
#else
{
/* !checksrc! disable STRERROR 1 */
const char *msg = strerror(err);
if(msg)
strncpy(buf, msg, max);
else
msnprintf(buf, max, "Unknown error %d", err);
}
#endif
#endif /* end of not Windows */
buf[max] = '\0'; /* make sure the string is null-terminated */
/* strip trailing '\r\n' or '\n'. */
p = strrchr(buf, '\n');
if(p && (p - buf) >= 2)
*p = '\0';
p = strrchr(buf, '\r');
if(p && (p - buf) >= 1)
*p = '\0';
if(errno != old_errno)
errno = old_errno;
#ifdef PRESERVE_WINDOWS_ERROR_CODE
if(old_win_err != GetLastError())
SetLastError(old_win_err);
#endif
return buf;
}
/*
* Curl_winapi_strerror:
* Variant of Curl_strerror if the error code is definitely Windows API.
*/
#if defined(WIN32) || defined(_WIN32_WCE)
const char *Curl_winapi_strerror(DWORD err, char *buf, size_t buflen)
{
#ifdef PRESERVE_WINDOWS_ERROR_CODE
DWORD old_win_err = GetLastError();
#endif
int old_errno = errno;
if(!buflen)
return NULL;
*buf = '\0';
#ifndef CURL_DISABLE_VERBOSE_STRINGS
if(!get_winapi_error(err, buf, buflen)) {
msnprintf(buf, buflen, "Unknown error %u (0x%08X)", err, err);
}
#else
{
const char *txt = (err == ERROR_SUCCESS) ? "No error" : "Error";
strncpy(buf, txt, buflen);
buf[buflen - 1] = '\0';
}
#endif
if(errno != old_errno)
errno = old_errno;
#ifdef PRESERVE_WINDOWS_ERROR_CODE
if(old_win_err != GetLastError())
SetLastError(old_win_err);
#endif
return buf;
}
#endif /* WIN32 || _WIN32_WCE */
#ifdef USE_WINDOWS_SSPI
/*
* Curl_sspi_strerror:
* Variant of Curl_strerror if the error code is definitely Windows SSPI.
*/
const char *Curl_sspi_strerror(int err, char *buf, size_t buflen)
{
#ifdef PRESERVE_WINDOWS_ERROR_CODE
DWORD old_win_err = GetLastError();
#endif
int old_errno = errno;
const char *txt;
if(!buflen)
return NULL;
*buf = '\0';
#ifndef CURL_DISABLE_VERBOSE_STRINGS
switch(err) {
case SEC_E_OK:
txt = "No error";
break;
#define SEC2TXT(sec) case sec: txt = #sec; break
SEC2TXT(CRYPT_E_REVOKED);
SEC2TXT(SEC_E_ALGORITHM_MISMATCH);
SEC2TXT(SEC_E_BAD_BINDINGS);
SEC2TXT(SEC_E_BAD_PKGID);
SEC2TXT(SEC_E_BUFFER_TOO_SMALL);
SEC2TXT(SEC_E_CANNOT_INSTALL);
SEC2TXT(SEC_E_CANNOT_PACK);
SEC2TXT(SEC_E_CERT_EXPIRED);
SEC2TXT(SEC_E_CERT_UNKNOWN);
SEC2TXT(SEC_E_CERT_WRONG_USAGE);
SEC2TXT(SEC_E_CONTEXT_EXPIRED);
SEC2TXT(SEC_E_CROSSREALM_DELEGATION_FAILURE);
SEC2TXT(SEC_E_CRYPTO_SYSTEM_INVALID);
SEC2TXT(SEC_E_DECRYPT_FAILURE);
SEC2TXT(SEC_E_DELEGATION_POLICY);
SEC2TXT(SEC_E_DELEGATION_REQUIRED);
SEC2TXT(SEC_E_DOWNGRADE_DETECTED);
SEC2TXT(SEC_E_ENCRYPT_FAILURE);
SEC2TXT(SEC_E_ILLEGAL_MESSAGE);
SEC2TXT(SEC_E_INCOMPLETE_CREDENTIALS);
SEC2TXT(SEC_E_INCOMPLETE_MESSAGE);
SEC2TXT(SEC_E_INSUFFICIENT_MEMORY);
SEC2TXT(SEC_E_INTERNAL_ERROR);
SEC2TXT(SEC_E_INVALID_HANDLE);
SEC2TXT(SEC_E_INVALID_PARAMETER);
SEC2TXT(SEC_E_INVALID_TOKEN);
SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED);
SEC2TXT(SEC_E_ISSUING_CA_UNTRUSTED_KDC);
SEC2TXT(SEC_E_KDC_CERT_EXPIRED);
SEC2TXT(SEC_E_KDC_CERT_REVOKED);
SEC2TXT(SEC_E_KDC_INVALID_REQUEST);
SEC2TXT(SEC_E_KDC_UNABLE_TO_REFER);
SEC2TXT(SEC_E_KDC_UNKNOWN_ETYPE);
SEC2TXT(SEC_E_LOGON_DENIED);
SEC2TXT(SEC_E_MAX_REFERRALS_EXCEEDED);
SEC2TXT(SEC_E_MESSAGE_ALTERED);
SEC2TXT(SEC_E_MULTIPLE_ACCOUNTS);
SEC2TXT(SEC_E_MUST_BE_KDC);
SEC2TXT(SEC_E_NOT_OWNER);
SEC2TXT(SEC_E_NO_AUTHENTICATING_AUTHORITY);
SEC2TXT(SEC_E_NO_CREDENTIALS);
SEC2TXT(SEC_E_NO_IMPERSONATION);
SEC2TXT(SEC_E_NO_IP_ADDRESSES);
SEC2TXT(SEC_E_NO_KERB_KEY);
SEC2TXT(SEC_E_NO_PA_DATA);
SEC2TXT(SEC_E_NO_S4U_PROT_SUPPORT);
SEC2TXT(SEC_E_NO_TGT_REPLY);
SEC2TXT(SEC_E_OUT_OF_SEQUENCE);
SEC2TXT(SEC_E_PKINIT_CLIENT_FAILURE);
SEC2TXT(SEC_E_PKINIT_NAME_MISMATCH);
SEC2TXT(SEC_E_POLICY_NLTM_ONLY);
SEC2TXT(SEC_E_QOP_NOT_SUPPORTED);
SEC2TXT(SEC_E_REVOCATION_OFFLINE_C);
SEC2TXT(SEC_E_REVOCATION_OFFLINE_KDC);
SEC2TXT(SEC_E_SECPKG_NOT_FOUND);
SEC2TXT(SEC_E_SECURITY_QOS_FAILED);
SEC2TXT(SEC_E_SHUTDOWN_IN_PROGRESS);
SEC2TXT(SEC_E_SMARTCARD_CERT_EXPIRED);
SEC2TXT(SEC_E_SMARTCARD_CERT_REVOKED);
SEC2TXT(SEC_E_SMARTCARD_LOGON_REQUIRED);
SEC2TXT(SEC_E_STRONG_CRYPTO_NOT_SUPPORTED);
SEC2TXT(SEC_E_TARGET_UNKNOWN);
SEC2TXT(SEC_E_TIME_SKEW);
SEC2TXT(SEC_E_TOO_MANY_PRINCIPALS);
SEC2TXT(SEC_E_UNFINISHED_CONTEXT_DELETED);
SEC2TXT(SEC_E_UNKNOWN_CREDENTIALS);
SEC2TXT(SEC_E_UNSUPPORTED_FUNCTION);
SEC2TXT(SEC_E_UNSUPPORTED_PREAUTH);
SEC2TXT(SEC_E_UNTRUSTED_ROOT);
SEC2TXT(SEC_E_WRONG_CREDENTIAL_HANDLE);
SEC2TXT(SEC_E_WRONG_PRINCIPAL);
SEC2TXT(SEC_I_COMPLETE_AND_CONTINUE);
SEC2TXT(SEC_I_COMPLETE_NEEDED);
SEC2TXT(SEC_I_CONTEXT_EXPIRED);
SEC2TXT(SEC_I_CONTINUE_NEEDED);
SEC2TXT(SEC_I_INCOMPLETE_CREDENTIALS);
SEC2TXT(SEC_I_LOCAL_LOGON);
SEC2TXT(SEC_I_NO_LSA_CONTEXT);
SEC2TXT(SEC_I_RENEGOTIATE);
SEC2TXT(SEC_I_SIGNATURE_NEEDED);
default:
txt = "Unknown error";
}
if(err == SEC_E_ILLEGAL_MESSAGE) {
msnprintf(buf, buflen,
"SEC_E_ILLEGAL_MESSAGE (0x%08X) - This error usually occurs "
"when a fatal SSL/TLS alert is received (e.g. handshake failed)."
" More detail may be available in the Windows System event log.",
err);
}
else {
char txtbuf[80];
char msgbuf[256];
msnprintf(txtbuf, sizeof(txtbuf), "%s (0x%08X)", txt, err);
if(get_winapi_error(err, msgbuf, sizeof(msgbuf)))
msnprintf(buf, buflen, "%s - %s", txtbuf, msgbuf);
else {
strncpy(buf, txtbuf, buflen);
buf[buflen - 1] = '\0';
}
}
#else
if(err == SEC_E_OK)
txt = "No error";
else
txt = "Error";
strncpy(buf, txt, buflen);
buf[buflen - 1] = '\0';
#endif
if(errno != old_errno)
errno = old_errno;
#ifdef PRESERVE_WINDOWS_ERROR_CODE
if(old_win_err != GetLastError())
SetLastError(old_win_err);
#endif
return buf;
}
#endif /* USE_WINDOWS_SSPI */
|
Subsets and Splits