code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 "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(NTLM_NEEDS_NSS_INIT) #include "vtls/nssg.h" #elif 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 connectdata *conn, 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; 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) { result = Curl_auth_decode_ntlm_type2_message(conn->data, header, ntlm); if(result) return result; *state = NTLMSTATE_TYPE2; /* We got a type-2 message */ } else { if(*state == NTLMSTATE_LAST) { infof(conn->data, "NTLM auth restarted\n"); Curl_http_auth_cleanup_ntlm(conn); } else if(*state == NTLMSTATE_TYPE3) { infof(conn->data, "NTLM handshake rejected\n"); Curl_http_auth_cleanup_ntlm(conn); *state = NTLMSTATE_NONE; return CURLE_REMOTE_ACCESS_DENIED; } else if(*state >= NTLMSTATE_TYPE1) { infof(conn->data, "NTLM handshake failure (internal error)\n"); 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 connectdata *conn, bool proxy) { char *base64 = NULL; size_t len = 0; CURLcode result; /* 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; DEBUGASSERT(conn); DEBUGASSERT(conn->data); #if defined(NTLM_NEEDS_NSS_INIT) if(CURLE_OK != Curl_nss_force_init(conn->data)) return CURLE_OUT_OF_MEMORY; #endif if(proxy) { allocuserpwd = &conn->allocptr.proxyuserpwd; userp = conn->http_proxy.user; passwdp = conn->http_proxy.passwd; service = conn->data->set.str[STRING_PROXY_SERVICE_NAME] ? conn->data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; hostname = conn->http_proxy.host.name; ntlm = &conn->proxyntlm; state = &conn->proxy_ntlm_state; authp = &conn->data->state.authproxy; } else { allocuserpwd = &conn->allocptr.userpwd; userp = conn->user; passwdp = conn->passwd; service = conn->data->set.str[STRING_SERVICE_NAME] ? conn->data->set.str[STRING_SERVICE_NAME] : "HTTP"; hostname = conn->host.name; ntlm = &conn->ntlm; state = &conn->http_ntlm_state; authp = &conn->data->state.authhost; } authp->done = FALSE; /* not set means empty */ if(!userp) userp = ""; if(!passwdp) passwdp = ""; #ifdef USE_WINDOWS_SSPI if(s_hSecDll == NULL) { /* not thread safe and leaks - use curl_global_init() to avoid */ CURLcode err = Curl_sspi_global_init(); if(s_hSecDll == NULL) return err; } #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS ntlm->sslContext = conn->sslContext; #endif #endif 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(conn->data, userp, passwdp, service, hostname, ntlm, &base64, &len); if(result) return result; if(base64) { free(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", proxy ? "Proxy-" : "", base64); free(base64); if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; DEBUG_OUT(fprintf(stderr, "**** Header %s\n ", *allocuserpwd)); } break; case NTLMSTATE_TYPE2: /* We already received the type-2 message, create a type-3 message */ result = Curl_auth_create_ntlm_type3_message(conn->data, userp, passwdp, ntlm, &base64, &len); if(result) return result; if(base64) { free(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: NTLM %s\r\n", proxy ? "Proxy-" : "", base64); free(base64); if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; DEBUG_OUT(fprintf(stderr, "**** %s\n ", *allocuserpwd)); *state = NTLMSTATE_TYPE3; /* we send a type-3 */ authp->done = TRUE; } break; case NTLMSTATE_TYPE3: /* connection is already authenticated, * don't send a header in future requests */ *state = NTLMSTATE_LAST; /* FALLTHROUGH */ case NTLMSTATE_LAST: Curl_safefree(*allocuserpwd); authp->done = TRUE; break; } return CURLE_OK; } 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 */
YifuLiu/AliOS-Things
components/curl/lib/http_ntlm.c
C
apache-2.0
7,419
#ifndef HEADER_CURL_HTTP_NTLM_H #define HEADER_CURL_HTTP_NTLM_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) /* this is for ntlm header input */ CURLcode Curl_input_ntlm(struct connectdata *conn, bool proxy, const char *header); /* this is for creating ntlm header output */ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy); void Curl_http_auth_cleanup_ntlm(struct connectdata *conn); #endif /* !CURL_DISABLE_HTTP && USE_NTLM */ #endif /* HEADER_CURL_HTTP_NTLM_H */
YifuLiu/AliOS-Things
components/curl/lib/http_ntlm.h
C
apache-2.0
1,571
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "http_proxy.h" #if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP) #include <curl/curl.h> #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" /* 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 connectdata *conn, int sockindex) { #ifdef USE_SSL 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(conn, sockindex, &conn->bits.proxy_ssl_connected[sockindex]); if(result) conn->bits.close = TRUE; /* a failed connection is marked for closure to prevent (bad) re-use or similar */ } return result; #else (void) conn; (void) sockindex; return CURLE_NOT_BUILT_IN; #endif } CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex) { if(conn->http_proxy.proxytype == CURLPROXY_HTTPS) { const CURLcode result = https_proxy_connect(conn, 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 */ struct HTTP http_proxy; void *prot_save; const char *hostname; int remote_port; CURLcode result; /* BLOCKING */ /* We want "seamless" operations through HTTP proxy tunnel */ /* 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. */ prot_save = conn->data->req.protop; memset(&http_proxy, 0, sizeof(http_proxy)); conn->data->req.protop = &http_proxy; connkeep(conn, "HTTP proxy CONNECT"); /* 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(conn, sockindex, hostname, remote_port); conn->data->req.protop = prot_save; if(CURLE_OK != result) return result; Curl_safefree(conn->allocptr.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); } static CURLcode connect_init(struct connectdata *conn, bool reinit) { struct http_connect_state *s; if(!reinit) { DEBUGASSERT(!conn->connect_state); s = calloc(1, sizeof(struct http_connect_state)); if(!s) return CURLE_OUT_OF_MEMORY; infof(conn->data, "allocate connect buffer!\n"); conn->connect_state = s; } else { DEBUGASSERT(conn->connect_state); s = conn->connect_state; } s->tunnel_state = TUNNEL_INIT; s->keepon = TRUE; s->line_start = s->connect_buffer; s->ptr = s->line_start; s->cl = 0; s->close_connection = FALSE; return CURLE_OK; } static void connect_done(struct connectdata *conn) { struct http_connect_state *s = conn->connect_state; s->tunnel_state = TUNNEL_COMPLETE; infof(conn->data, "CONNECT phase completed!\n"); } static CURLcode CONNECT(struct connectdata *conn, int sockindex, const char *hostname, int remote_port) { int subversion = 0; struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; CURLcode result; curl_socket_t tunnelsocket = conn->sock[sockindex]; struct http_connect_state *s = conn->connect_state; #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 */ char *host_port; Curl_send_buffer *req_buffer; infof(data, "Establish HTTP proxy tunnel to %s:%d\n", 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. */ free(data->req.newurl); data->req.newurl = NULL; /* initialize a dynamic send-buffer */ req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; host_port = aprintf("%s:%d", hostname, remote_port); if(!host_port) { Curl_add_buffer_free(&req_buffer); return CURLE_OUT_OF_MEMORY; } /* Setup the proxy-authorization header, if any */ result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE); free(host_port); if(!result) { char *host = NULL; const char *proxyconn = ""; const char *useragent = ""; const char *http = (conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) ? "1.0" : "1.1"; bool ipv6_ip = conn->bits.ipv6_ip; char *hostheader; /* 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) { Curl_add_buffer_free(&req_buffer); return CURLE_OUT_OF_MEMORY; } if(!Curl_checkProxyheaders(conn, "Host")) { host = aprintf("Host: %s\r\n", hostheader); if(!host) { free(hostheader); Curl_add_buffer_free(&req_buffer); return CURLE_OUT_OF_MEMORY; } } if(!Curl_checkProxyheaders(conn, "Proxy-Connection")) proxyconn = "Proxy-Connection: Keep-Alive\r\n"; if(!Curl_checkProxyheaders(conn, "User-Agent") && data->set.str[STRING_USERAGENT]) useragent = conn->allocptr.uagent; result = Curl_add_bufferf(&req_buffer, "CONNECT %s HTTP/%s\r\n" "%s" /* Host: */ "%s" /* Proxy-Authorization */ "%s" /* User-Agent */ "%s", /* Proxy-Connection */ hostheader, http, host?host:"", conn->allocptr.proxyuserpwd? conn->allocptr.proxyuserpwd:"", useragent, proxyconn); if(host) free(host); free(hostheader); if(!result) result = Curl_add_custom_headers(conn, TRUE, req_buffer); if(!result) /* CRLF terminate the request */ result = Curl_add_bufferf(&req_buffer, "\r\n"); if(!result) { /* Send the connect request to the proxy */ /* BLOCKING */ result = Curl_add_buffer_send(&req_buffer, conn, &data->info.request_size, 0, sockindex); } req_buffer = NULL; if(result) failf(data, "Failed sending CONNECT to proxy"); } Curl_add_buffer_free(&req_buffer); if(result) return result; s->tunnel_state = TUNNEL_CONNECT; s->perline = 0; } /* 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)) /* return so we'll be called again polling-style */ return CURLE_OK; /* at this point, the tunnel_connecting phase is over. */ { /* READING RESPONSE PHASE */ int error = SELECT_OK; while(s->keepon && !error) { ssize_t gotbytes; /* make sure we have space to read more data */ if(s->ptr >= &s->connect_buffer[CONNECT_BUFFER_SIZE]) { failf(data, "CONNECT response too large!"); return CURLE_RECV_ERROR; } /* 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(conn, tunnelsocket, s->ptr, 1, &gotbytes); if(result == CURLE_AGAIN) /* socket buffer drained, return */ return CURLE_OK; if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; if(result) { s->keepon = FALSE; break; } else if(gotbytes <= 0) { if(data->set.proxyauth && data->state.authproxy.avail) { /* 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\n"); } else { error = SELECT_ERROR; failf(data, "Proxy CONNECT aborted"); } s->keepon = FALSE; break; } if(s->keepon > TRUE) { /* This means we are currently ignoring a response-body */ s->ptr = s->connect_buffer; 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 = FALSE; 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; 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(conn, s->ptr, 1, &tookcareof); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); s->keepon = FALSE; /* we did the full CONNECT treatment, go COMPLETE */ s->tunnel_state = TUNNEL_COMPLETE; } } continue; } s->perline++; /* amount of bytes in this line so far */ /* if this is not the end of a header line then continue */ if(*s->ptr != 0x0a) { s->ptr++; continue; } /* convert from the network encoding */ result = Curl_convert_from_network(data, s->line_start, (size_t)s->perline); /* Curl_convert_from_network calls failf if unsuccessful */ if(result) return result; /* output debug if that is requested */ if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, s->line_start, (size_t)s->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(conn, writetype, s->line_start, s->perline); if(result) return result; } data->info.header_size += (long)s->perline; data->req.headerbytecount += (long)s->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' == s->line_start[0]) || ('\n' == s->line_start[0])) { /* end of response-headers from the proxy */ s->ptr = s->connect_buffer; 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 = 2; if(s->cl) { infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T " bytes of response-body\n", s->cl); } else if(s->chunked_encoding) { CHUNKcode r; infof(data, "Ignore chunked response-body\n"); /* 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(s->line_start[1] == '\n') { /* this can only be a LF if the letter at index 0 was a CR */ s->line_start++; } /* now parse the chunked piece of data so that we can properly tell when the stream ends */ r = Curl_httpchunk_read(conn, s->line_start + 1, 1, &gotbytes); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); s->keepon = FALSE; /* 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 = FALSE; } } else s->keepon = FALSE; if(!s->cl) /* we did the full CONNECT treatment, go to COMPLETE */ s->tunnel_state = TUNNEL_COMPLETE; continue; } s->line_start[s->perline] = 0; /* zero terminate the buffer */ if((checkprefix("WWW-Authenticate:", s->line_start) && (401 == k->httpcode)) || (checkprefix("Proxy-authenticate:", s->line_start) && (407 == k->httpcode))) { bool proxy = (k->httpcode == 407) ? TRUE : FALSE; char *auth = Curl_copy_header_value(s->line_start); if(!auth) return CURLE_OUT_OF_MEMORY; result = Curl_http_input_auth(conn, proxy, auth); free(auth); if(result) return result; } else if(checkprefix("Content-Length:", s->line_start)) { 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\n", k->httpcode); } else { (void)curlx_strtoofft(s->line_start + strlen("Content-Length:"), NULL, 10, &s->cl); } } else if(Curl_compareheader(s->line_start, "Connection:", "close")) s->close_connection = TRUE; else if(checkprefix("Transfer-Encoding:", s->line_start)) { 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\n", k->httpcode); } else if(Curl_compareheader(s->line_start, "Transfer-Encoding:", "chunked")) { infof(data, "CONNECT responded chunked\n"); s->chunked_encoding = TRUE; /* init our chunky engine */ Curl_httpchunk_init(conn); } } else if(Curl_compareheader(s->line_start, "Proxy-Connection:", "close")) s->close_connection = TRUE; else if(2 == sscanf(s->line_start, "HTTP/1.%d %d", &subversion, &k->httpcode)) { /* store the HTTP code from the proxy */ data->info.httpproxycode = k->httpcode; } s->perline = 0; /* line starts over here */ s->ptr = s->connect_buffer; s->line_start = s->ptr; } /* while there's buffer left and loop is requested */ if(Curl_pgrsUpdate(conn)) 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(conn); 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(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(conn, 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\n"); connect_done(conn); } else { free(data->req.newurl); data->req.newurl = NULL; /* failure, close this connection to avoid re-use */ streamclose(conn, "proxy CONNECT failure"); Curl_closesocket(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; 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(conn->allocptr.proxyuserpwd); conn->allocptr.proxyuserpwd = NULL; data->state.authproxy.done = TRUE; infof(data, "Proxy replied %d to CONNECT request\n", 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 */ return CURLE_OK; } 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 connectdata *conn, int sockindex, const char *hostname, int remote_port) { CURLcode result; if(!conn->connect_state) { result = connect_init(conn, FALSE); if(result) return result; } result = CONNECT(conn, sockindex, hostname, remote_port); if(result || Curl_connect_complete(conn)) connect_done(conn); return result; } #else void Curl_connect_free(struct Curl_easy *data) { (void)data; } #endif /* CURL_DISABLE_PROXY */
YifuLiu/AliOS-Things
components/curl/lib/http_proxy.c
C
apache-2.0
22,960
#ifndef HEADER_CURL_HTTP_PROXY_H #define HEADER_CURL_HTTP_PROXY_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 connectdata *conn, int tunnelsocket, const char *hostname, int remote_port); /* Default proxy timeout in milliseconds */ #define PROXY_TIMEOUT (3600*1000) CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex); bool Curl_connect_complete(struct connectdata *conn); bool Curl_connect_ongoing(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 #endif void Curl_connect_free(struct Curl_easy *data); #endif /* HEADER_CURL_HTTP_PROXY_H */
YifuLiu/AliOS-Things
components/curl/lib/http_proxy.h
C
apache-2.0
1,934
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * IDN conversions using Windows kernel32 and normaliz libraries. */ #include "curl_setup.h" #ifdef USE_WIN32_IDN #include "curl_multibyte.h" #include "curl_memory.h" #include "warnless.h" /* The last #include file should be: */ #include "memdebug.h" #ifdef WANT_IDN_PROTOTYPES # if defined(_SAL_VERSION) WINNORMALIZEAPI int WINAPI IdnToAscii(_In_ DWORD dwFlags, _In_reads_(cchUnicodeChar) LPCWSTR lpUnicodeCharStr, _In_ int cchUnicodeChar, _Out_writes_opt_(cchASCIIChar) LPWSTR lpASCIICharStr, _In_ int cchASCIIChar); WINNORMALIZEAPI int WINAPI IdnToUnicode(_In_ DWORD dwFlags, _In_reads_(cchASCIIChar) LPCWSTR lpASCIICharStr, _In_ int cchASCIIChar, _Out_writes_opt_(cchUnicodeChar) LPWSTR lpUnicodeCharStr, _In_ int cchUnicodeChar); # else WINBASEAPI int WINAPI IdnToAscii(DWORD dwFlags, const WCHAR *lpUnicodeCharStr, int cchUnicodeChar, WCHAR *lpASCIICharStr, int cchASCIIChar); WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, const WCHAR *lpASCIICharStr, int cchASCIIChar, WCHAR *lpUnicodeCharStr, int cchUnicodeChar); # endif #endif #define IDN_MAX_LENGTH 255 bool curl_win32_idn_to_ascii(const char *in, char **out); bool curl_win32_ascii_to_idn(const char *in, char **out); bool curl_win32_idn_to_ascii(const char *in, char **out) { bool success = FALSE; wchar_t *in_w = Curl_convert_UTF8_to_wchar(in); if(in_w) { wchar_t punycode[IDN_MAX_LENGTH]; int chars = IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH); free(in_w); if(chars) { *out = Curl_convert_wchar_to_UTF8(punycode); if(*out) success = TRUE; } } return success; } bool curl_win32_ascii_to_idn(const char *in, char **out) { bool success = FALSE; wchar_t *in_w = Curl_convert_UTF8_to_wchar(in); if(in_w) { size_t in_len = wcslen(in_w) + 1; wchar_t unicode[IDN_MAX_LENGTH]; int chars = IdnToUnicode(0, in_w, curlx_uztosi(in_len), unicode, IDN_MAX_LENGTH); free(in_w); if(chars) { *out = Curl_convert_wchar_to_UTF8(unicode); if(*out) success = TRUE; } } return success; } #endif /* USE_WIN32_IDN */
YifuLiu/AliOS-Things
components/curl/lib/idn_win32.c
C
apache-2.0
3,723
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H # include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H # include <sys/ioctl.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK # include <lwip/netdb.h> #else # include <netdb.h> #endif #endif #ifdef HAVE_SYS_SOCKIO_H # include <sys/sockio.h> #endif #ifdef HAVE_IFADDRS_H # include <ifaddrs.h> #endif #ifdef HAVE_STROPTS_H # include <stropts.h> #endif #ifdef __VMS # include <inet.h> #endif #include "inet_ntop.h" #include "strcase.h" #include "if2ip.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* ------------------------------------------------------------------ */ /* Return the scope of the given address. */ unsigned int Curl_ipv6_scope(const struct sockaddr *sa) { #ifndef ENABLE_IPV6 (void) sa; #else if(sa->sa_family == AF_INET6) { const struct sockaddr_in6 * sa6 = (const struct sockaddr_in6 *)(void *) sa; const unsigned char *b = sa6->sin6_addr.s6_addr; unsigned short w = (unsigned short) ((b[0] << 8) | b[1]); if((b[0] & 0xFE) == 0xFC) /* Handle ULAs */ return IPV6_SCOPE_UNIQUELOCAL; switch(w & 0xFFC0) { case 0xFE80: return IPV6_SCOPE_LINKLOCAL; case 0xFEC0: return IPV6_SCOPE_SITELOCAL; case 0x0000: w = b[1] | b[2] | b[3] | b[4] | b[5] | b[6] | b[7] | b[8] | b[9] | b[10] | b[11] | b[12] | b[13] | b[14]; if(w || b[15] != 0x01) break; return IPV6_SCOPE_NODELOCAL; default: break; } } #endif return IPV6_SCOPE_GLOBAL; } #if defined(HAVE_GETIFADDRS) if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, unsigned int local_scope_id, const char *interf, char *buf, int buf_size) { struct ifaddrs *iface, *head; if2ip_result_t res = IF2IP_NOT_FOUND; #ifndef ENABLE_IPV6 (void) remote_scope; #endif #if !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) || \ !defined(ENABLE_IPV6) (void) local_scope_id; #endif if(getifaddrs(&head) >= 0) { for(iface = head; iface != NULL; iface = iface->ifa_next) { if(iface->ifa_addr != NULL) { if(iface->ifa_addr->sa_family == af) { if(strcasecompare(iface->ifa_name, interf)) { void *addr; char *ip; char scope[12] = ""; char ipstr[64]; #ifdef ENABLE_IPV6 if(af == AF_INET6) { #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID unsigned int scopeid = 0; #endif unsigned int ifscope = Curl_ipv6_scope(iface->ifa_addr); if(ifscope != remote_scope) { /* We are interested only in interface addresses whose scope matches the remote address we want to connect to: global for global, link-local for link-local, etc... */ if(res == IF2IP_NOT_FOUND) res = IF2IP_AF_NOT_SUPPORTED; continue; } addr = &((struct sockaddr_in6 *)(void *)iface->ifa_addr)->sin6_addr; #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID /* Include the scope of this interface as part of the address */ scopeid = ((struct sockaddr_in6 *)(void *)iface->ifa_addr) ->sin6_scope_id; /* If given, scope id should match. */ if(local_scope_id && scopeid != local_scope_id) { if(res == IF2IP_NOT_FOUND) res = IF2IP_AF_NOT_SUPPORTED; continue; } if(scopeid) msnprintf(scope, sizeof(scope), "%%%u", scopeid); #endif } else #endif addr = &((struct sockaddr_in *)(void *)iface->ifa_addr)->sin_addr; res = IF2IP_FOUND; ip = (char *) Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr)); msnprintf(buf, buf_size, "%s%s", ip, scope); break; } } else if((res == IF2IP_NOT_FOUND) && strcasecompare(iface->ifa_name, interf)) { res = IF2IP_AF_NOT_SUPPORTED; } } } freeifaddrs(head); } return res; } #elif defined(HAVE_IOCTL_SIOCGIFADDR) if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, unsigned int local_scope_id, const char *interf, char *buf, int buf_size) { struct ifreq req; struct in_addr in; struct sockaddr_in *s; curl_socket_t dummy; size_t len; (void)remote_scope; (void)local_scope_id; if(!interf || (af != AF_INET)) return IF2IP_NOT_FOUND; len = strlen(interf); if(len >= sizeof(req.ifr_name)) return IF2IP_NOT_FOUND; dummy = socket(AF_INET, SOCK_STREAM, 0); if(CURL_SOCKET_BAD == dummy) return IF2IP_NOT_FOUND; memset(&req, 0, sizeof(req)); memcpy(req.ifr_name, interf, len + 1); req.ifr_addr.sa_family = AF_INET; if(ioctl(dummy, SIOCGIFADDR, &req) < 0) { sclose(dummy); /* With SIOCGIFADDR, we cannot tell the difference between an interface that does not exist and an interface that has no address of the correct family. Assume the interface does not exist */ return IF2IP_NOT_FOUND; } s = (struct sockaddr_in *)(void *)&req.ifr_addr; memcpy(&in, &s->sin_addr, sizeof(in)); Curl_inet_ntop(s->sin_family, &in, buf, buf_size); sclose(dummy); return IF2IP_FOUND; } #else if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, unsigned int local_scope_id, const char *interf, char *buf, int buf_size) { (void) af; (void) remote_scope; (void) local_scope_id; (void) interf; (void) buf; (void) buf_size; return IF2IP_NOT_FOUND; } #endif
YifuLiu/AliOS-Things
components/curl/lib/if2ip.c
C
apache-2.0
6,965
#ifndef HEADER_CURL_IF2IP_H #define HEADER_CURL_IF2IP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */
YifuLiu/AliOS-Things
components/curl/lib/if2ip.h
C
apache-2.0
3,004
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2195 CRAM-MD5 authentication * RFC2595 Using TLS with IMAP, POP3 and ACAP * RFC2831 DIGEST-MD5 authentication * RFC3501 IMAPv4 protocol * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * RFC4959 IMAP Extension for SASL Initial Client Response * RFC5092 IMAP URL Scheme * RFC6749 OAuth 2.0 Authorization Framework * RFC8314 Use of TLS for Email Submission and Access * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_IMAP #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "socks.h" #include "imap.h" #include "mime.h" #include "strtoofft.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "select.h" #include "multiif.h" #include "url.h" #include "strcase.h" #include "curl_sasl.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" /* Local API functions */ static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done); static CURLcode imap_do(struct connectdata *conn, bool *done); static CURLcode imap_done(struct connectdata *conn, CURLcode status, bool premature); static CURLcode imap_connect(struct connectdata *conn, bool *done); static CURLcode imap_disconnect(struct connectdata *conn, bool dead); static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done); static int imap_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done); static CURLcode imap_setup_connection(struct connectdata *conn); static char *imap_atom(const char *str, bool escape_only); static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...); static CURLcode imap_parse_url_options(struct connectdata *conn); static CURLcode imap_parse_url_path(struct connectdata *conn); static CURLcode imap_parse_custom_request(struct connectdata *conn); static CURLcode imap_perform_authenticate(struct connectdata *conn, const char *mech, const char *initresp); static CURLcode imap_continue_authenticate(struct connectdata *conn, const char *resp); static void imap_get_message(char *buffer, char **outptr); /* * IMAP protocol handler. */ const struct Curl_handler Curl_handler_imap = { "IMAP", /* scheme */ imap_setup_connection, /* setup_connection */ imap_do, /* do_it */ imap_done, /* done */ ZERO_NULL, /* do_more */ imap_connect, /* connect_it */ imap_multi_statemach, /* connecting */ imap_doing, /* doing */ imap_getsock, /* proto_getsock */ imap_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ imap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_IMAP, /* defport */ CURLPROTO_IMAP, /* protocol */ PROTOPT_CLOSEACTION| /* flags */ PROTOPT_URLOPTIONS }; #ifdef USE_SSL /* * IMAPS protocol handler. */ const struct Curl_handler Curl_handler_imaps = { "IMAPS", /* scheme */ imap_setup_connection, /* setup_connection */ imap_do, /* do_it */ imap_done, /* done */ ZERO_NULL, /* do_more */ imap_connect, /* connect_it */ imap_multi_statemach, /* connecting */ imap_doing, /* doing */ imap_getsock, /* proto_getsock */ imap_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ imap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_IMAPS, /* defport */ CURLPROTO_IMAPS, /* protocol */ PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ PROTOPT_URLOPTIONS }; #endif #define IMAP_RESP_OK 1 #define IMAP_RESP_NOT_OK 2 #define IMAP_RESP_PREAUTH 3 /* SASL parameters for the imap protocol */ static const struct SASLproto saslimap = { "imap", /* The service name */ '+', /* Code received when continuation is expected */ IMAP_RESP_OK, /* Code to receive upon authentication success */ 0, /* Maximum initial response length (no max) */ imap_perform_authenticate, /* Send authentication command */ imap_continue_authenticate, /* Send authentication continuation */ imap_get_message /* Get SASL response message */ }; #ifdef USE_SSL static void imap_to_imaps(struct connectdata *conn) { /* Change the connection handler */ conn->handler = &Curl_handler_imaps; /* Set the connection's upgraded to TLS flag */ conn->tls_upgraded = TRUE; } #else #define imap_to_imaps(x) Curl_nop_stmt #endif /*********************************************************************** * * imap_matchresp() * * Determines whether the untagged response is related to the specified * command by checking if it is in format "* <command-name> ..." or * "* <number> <command-name> ...". * * The "* " marker is assumed to have already been checked by the caller. */ static bool imap_matchresp(const char *line, size_t len, const char *cmd) { const char *end = line + len; size_t cmd_len = strlen(cmd); /* Skip the untagged response marker */ line += 2; /* Do we have a number after the marker? */ if(line < end && ISDIGIT(*line)) { /* Skip the number */ do line++; while(line < end && ISDIGIT(*line)); /* Do we have the space character? */ if(line == end || *line != ' ') return FALSE; line++; } /* Does the command name match and is it followed by a space character or at the end of line? */ if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) && (line[cmd_len] == ' ' || line + cmd_len + 2 == end)) return TRUE; return FALSE; } /*********************************************************************** * * imap_endofresp() * * Checks whether the given string is a valid tagged, untagged or continuation * response which can be processed by the response handler. */ static bool imap_endofresp(struct connectdata *conn, char *line, size_t len, int *resp) { struct IMAP *imap = conn->data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; const char *id = imapc->resptag; size_t id_len = strlen(id); /* Do we have a tagged command response? */ if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') { line += id_len + 1; len -= id_len + 1; if(len >= 2 && !memcmp(line, "OK", 2)) *resp = IMAP_RESP_OK; else if(len >= 7 && !memcmp(line, "PREAUTH", 7)) *resp = IMAP_RESP_PREAUTH; else *resp = IMAP_RESP_NOT_OK; return TRUE; } /* Do we have an untagged command response? */ if(len >= 2 && !memcmp("* ", line, 2)) { switch(imapc->state) { /* States which are interested in untagged responses */ case IMAP_CAPABILITY: if(!imap_matchresp(line, len, "CAPABILITY")) return FALSE; break; case IMAP_LIST: if((!imap->custom && !imap_matchresp(line, len, "LIST")) || (imap->custom && !imap_matchresp(line, len, imap->custom) && (!strcasecompare(imap->custom, "STORE") || !imap_matchresp(line, len, "FETCH")) && !strcasecompare(imap->custom, "SELECT") && !strcasecompare(imap->custom, "EXAMINE") && !strcasecompare(imap->custom, "SEARCH") && !strcasecompare(imap->custom, "EXPUNGE") && !strcasecompare(imap->custom, "LSUB") && !strcasecompare(imap->custom, "UID") && !strcasecompare(imap->custom, "NOOP"))) return FALSE; break; case IMAP_SELECT: /* SELECT is special in that its untagged responses do not have a common prefix so accept anything! */ break; case IMAP_FETCH: if(!imap_matchresp(line, len, "FETCH")) return FALSE; break; case IMAP_SEARCH: if(!imap_matchresp(line, len, "SEARCH")) return FALSE; break; /* Ignore other untagged responses */ default: return FALSE; } *resp = '*'; return TRUE; } /* Do we have a continuation response? This should be a + symbol followed by a space and optionally some text as per RFC-3501 for the AUTHENTICATE and APPEND commands and as outlined in Section 4. Examples of RFC-4959 but some e-mail servers ignore this and only send a single + instead. */ if(imap && !imap->custom && ((len == 3 && line[0] == '+') || (len >= 2 && !memcmp("+ ", line, 2)))) { switch(imapc->state) { /* States which are interested in continuation responses */ case IMAP_AUTHENTICATE: case IMAP_APPEND: *resp = '+'; break; default: failf(conn->data, "Unexpected continuation response"); *resp = -1; break; } return TRUE; } return FALSE; /* Nothing for us */ } /*********************************************************************** * * imap_get_message() * * Gets the authentication message from the response buffer. */ static void imap_get_message(char *buffer, char **outptr) { size_t len = strlen(buffer); char *message = NULL; if(len > 2) { /* Find the start of the message */ len -= 2; for(message = buffer + 2; *message == ' ' || *message == '\t'; message++, len--) ; /* Find the end of the message */ for(; len--;) if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && message[len] != '\t') break; /* Terminate the message */ if(++len) { message[len] = '\0'; } } else /* junk input => zero length output */ message = &buffer[len]; *outptr = message; } /*********************************************************************** * * state() * * This is the ONLY way to change IMAP state! */ static void state(struct connectdata *conn, imapstate newstate) { struct imap_conn *imapc = &conn->proto.imapc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "SERVERGREET", "CAPABILITY", "STARTTLS", "UPGRADETLS", "AUTHENTICATE", "LOGIN", "LIST", "SELECT", "FETCH", "FETCH_FINAL", "APPEND", "APPEND_FINAL", "SEARCH", "LOGOUT", /* LAST */ }; if(imapc->state != newstate) infof(conn->data, "IMAP %p state change from %s to %s\n", (void *)imapc, names[imapc->state], names[newstate]); #endif imapc->state = newstate; } /*********************************************************************** * * imap_perform_capability() * * Sends the CAPABILITY command in order to obtain a list of server side * supported capabilities. */ static CURLcode imap_perform_capability(struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ imapc->tls_supported = FALSE; /* Clear the TLS capability */ /* Send the CAPABILITY command */ result = imap_sendf(conn, "CAPABILITY"); if(!result) state(conn, IMAP_CAPABILITY); return result; } /*********************************************************************** * * imap_perform_starttls() * * Sends the STARTTLS command to start the upgrade to TLS. */ static CURLcode imap_perform_starttls(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the STARTTLS command */ result = imap_sendf(conn, "STARTTLS"); if(!result) state(conn, IMAP_STARTTLS); return result; } /*********************************************************************** * * imap_perform_upgrade_tls() * * Performs the upgrade to TLS. */ static CURLcode imap_perform_upgrade_tls(struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; /* Start the SSL connection */ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone); if(!result) { if(imapc->state != IMAP_UPGRADETLS) state(conn, IMAP_UPGRADETLS); if(imapc->ssldone) { imap_to_imaps(conn); result = imap_perform_capability(conn); } } return result; } /*********************************************************************** * * imap_perform_login() * * Sends a clear text LOGIN command to authenticate with. */ static CURLcode imap_perform_login(struct connectdata *conn) { CURLcode result = CURLE_OK; char *user; char *passwd; /* Check we have a username and password to authenticate with and end the connect phase if we don't */ if(!conn->bits.user_passwd) { state(conn, IMAP_STOP); return result; } /* Make sure the username and password are in the correct atom format */ user = imap_atom(conn->user, false); passwd = imap_atom(conn->passwd, false); /* Send the LOGIN command */ result = imap_sendf(conn, "LOGIN %s %s", user ? user : "", passwd ? passwd : ""); free(user); free(passwd); if(!result) state(conn, IMAP_LOGIN); return result; } /*********************************************************************** * * imap_perform_authenticate() * * Sends an AUTHENTICATE command allowing the client to login with the given * SASL authentication mechanism. */ static CURLcode imap_perform_authenticate(struct connectdata *conn, const char *mech, const char *initresp) { CURLcode result = CURLE_OK; if(initresp) { /* Send the AUTHENTICATE command with the initial response */ result = imap_sendf(conn, "AUTHENTICATE %s %s", mech, initresp); } else { /* Send the AUTHENTICATE command */ result = imap_sendf(conn, "AUTHENTICATE %s", mech); } return result; } /*********************************************************************** * * imap_continue_authenticate() * * Sends SASL continuation data or cancellation. */ static CURLcode imap_continue_authenticate(struct connectdata *conn, const char *resp) { struct imap_conn *imapc = &conn->proto.imapc; return Curl_pp_sendf(&imapc->pp, "%s", resp); } /*********************************************************************** * * imap_perform_authentication() * * Initiates the authentication sequence, with the appropriate SASL * authentication mechanism, falling back to clear text should a common * mechanism not be available between the client and server. */ static CURLcode imap_perform_authentication(struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; saslprogress progress; /* Check if already authenticated OR if there is enough data to authenticate with and end the connect phase if we don't */ if(imapc->preauth || !Curl_sasl_can_authenticate(&imapc->sasl, conn)) { state(conn, IMAP_STOP); return result; } /* Calculate the SASL login details */ result = Curl_sasl_start(&imapc->sasl, conn, imapc->ir_supported, &progress); if(!result) { if(progress == SASL_INPROGRESS) state(conn, IMAP_AUTHENTICATE); else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) /* Perform clear text authentication */ result = imap_perform_login(conn); else { /* Other mechanisms not supported */ infof(conn->data, "No known authentication mechanisms supported!\n"); result = CURLE_LOGIN_DENIED; } } return result; } /*********************************************************************** * * imap_perform_list() * * Sends a LIST command or an alternative custom request. */ static CURLcode imap_perform_list(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; if(imap->custom) /* Send the custom request */ result = imap_sendf(conn, "%s%s", imap->custom, imap->custom_params ? imap->custom_params : ""); else { /* Make sure the mailbox is in the correct atom format if necessary */ char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) : strdup(""); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the LIST command */ result = imap_sendf(conn, "LIST \"%s\" *", mailbox); free(mailbox); } if(!result) state(conn, IMAP_LIST); return result; } /*********************************************************************** * * imap_perform_select() * * Sends a SELECT command to ask the server to change the selected mailbox. */ static CURLcode imap_perform_select(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; char *mailbox; /* Invalidate old information as we are switching mailboxes */ Curl_safefree(imapc->mailbox); Curl_safefree(imapc->mailbox_uidvalidity); /* Check we have a mailbox */ if(!imap->mailbox) { failf(conn->data, "Cannot SELECT without a mailbox."); return CURLE_URL_MALFORMAT; } /* Make sure the mailbox is in the correct atom format */ mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the SELECT command */ result = imap_sendf(conn, "SELECT %s", mailbox); free(mailbox); if(!result) state(conn, IMAP_SELECT); return result; } /*********************************************************************** * * imap_perform_fetch() * * Sends a FETCH command to initiate the download of a message. */ static CURLcode imap_perform_fetch(struct connectdata *conn) { CURLcode result = CURLE_OK; struct IMAP *imap = conn->data->req.protop; /* Check we have a UID */ if(imap->uid) { /* Send the FETCH command */ if(imap->partial) result = imap_sendf(conn, "UID FETCH %s BODY[%s]<%s>", imap->uid, imap->section ? imap->section : "", imap->partial); else result = imap_sendf(conn, "UID FETCH %s BODY[%s]", imap->uid, imap->section ? imap->section : ""); } else if(imap->mindex) { /* Send the FETCH command */ if(imap->partial) result = imap_sendf(conn, "FETCH %s BODY[%s]<%s>", imap->mindex, imap->section ? imap->section : "", imap->partial); else result = imap_sendf(conn, "FETCH %s BODY[%s]", imap->mindex, imap->section ? imap->section : ""); } else { failf(conn->data, "Cannot FETCH without a UID."); return CURLE_URL_MALFORMAT; } if(!result) state(conn, IMAP_FETCH); return result; } /*********************************************************************** * * imap_perform_append() * * Sends an APPEND command to initiate the upload of a message. */ static CURLcode imap_perform_append(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; char *mailbox; /* Check we have a mailbox */ if(!imap->mailbox) { failf(data, "Cannot APPEND without a mailbox."); return CURLE_URL_MALFORMAT; } /* Prepare the mime data if some. */ if(data->set.mimepost.kind != MIMEKIND_NONE) { /* Use the whole structure as data. */ data->set.mimepost.flags &= ~MIME_BODY_ONLY; /* Add external headers and mime version. */ curl_mime_headers(&data->set.mimepost, data->set.headers, 0); result = Curl_mime_prepare_headers(&data->set.mimepost, NULL, NULL, MIMESTRATEGY_MAIL); if(!result) if(!Curl_checkheaders(conn, "Mime-Version")) result = Curl_mime_add_header(&data->set.mimepost.curlheaders, "Mime-Version: 1.0"); /* Make sure we will read the entire mime structure. */ if(!result) result = Curl_mime_rewind(&data->set.mimepost); if(result) return result; data->state.infilesize = Curl_mime_size(&data->set.mimepost); /* Read from mime structure. */ data->state.fread_func = (curl_read_callback) Curl_mime_read; data->state.in = (void *) &data->set.mimepost; } /* Check we know the size of the upload */ if(data->state.infilesize < 0) { failf(data, "Cannot APPEND with unknown input file size\n"); return CURLE_UPLOAD_FAILED; } /* Make sure the mailbox is in the correct atom format */ mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the APPEND command */ result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}", mailbox, data->state.infilesize); free(mailbox); if(!result) state(conn, IMAP_APPEND); return result; } /*********************************************************************** * * imap_perform_search() * * Sends a SEARCH command. */ static CURLcode imap_perform_search(struct connectdata *conn) { CURLcode result = CURLE_OK; struct IMAP *imap = conn->data->req.protop; /* Check we have a query string */ if(!imap->query) { failf(conn->data, "Cannot SEARCH without a query string."); return CURLE_URL_MALFORMAT; } /* Send the SEARCH command */ result = imap_sendf(conn, "SEARCH %s", imap->query); if(!result) state(conn, IMAP_SEARCH); return result; } /*********************************************************************** * * imap_perform_logout() * * Performs the logout action prior to sclose() being called. */ static CURLcode imap_perform_logout(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the LOGOUT command */ result = imap_sendf(conn, "LOGOUT"); if(!result) state(conn, IMAP_LOGOUT); return result; } /* For the initial server greeting */ static CURLcode imap_state_servergreet_resp(struct connectdata *conn, int imapcode, imapstate instate) { struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(imapcode == IMAP_RESP_PREAUTH) { /* PREAUTH */ struct imap_conn *imapc = &conn->proto.imapc; imapc->preauth = TRUE; infof(data, "PREAUTH connection, already authenticated!\n"); } else if(imapcode != IMAP_RESP_OK) { failf(data, "Got unexpected imap-server response"); return CURLE_WEIRD_SERVER_REPLY; } return imap_perform_capability(conn); } /* For CAPABILITY responses */ static CURLcode imap_state_capability_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; (void)instate; /* no use for this yet */ /* Do we have a untagged response? */ if(imapcode == '*') { line += 2; /* Loop through the data line */ for(;;) { size_t wordlen; while(*line && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { line++; } if(!*line) break; /* Extract the word */ for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' && line[wordlen] != '\t' && line[wordlen] != '\r' && line[wordlen] != '\n';) wordlen++; /* Does the server support the STARTTLS capability? */ if(wordlen == 8 && !memcmp(line, "STARTTLS", 8)) imapc->tls_supported = TRUE; /* Has the server explicitly disabled clear text authentication? */ else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13)) imapc->login_disabled = TRUE; /* Does the server support the SASL-IR capability? */ else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7)) imapc->ir_supported = TRUE; /* Do we have a SASL based authentication mechanism? */ else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) { size_t llen; unsigned int mechbit; line += 5; wordlen -= 5; /* Test the word for a matching authentication mechanism */ mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); if(mechbit && llen == wordlen) imapc->sasl.authmechs |= mechbit; } line += wordlen; } } else if(imapcode == IMAP_RESP_OK) { if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) { /* We don't have a SSL/TLS connection yet, but SSL is requested */ if(imapc->tls_supported) /* Switch to TLS connection now */ result = imap_perform_starttls(conn); else if(data->set.use_ssl == CURLUSESSL_TRY) /* Fallback and carry on with authentication */ result = imap_perform_authentication(conn); else { failf(data, "STARTTLS not supported."); result = CURLE_USE_SSL_FAILED; } } else result = imap_perform_authentication(conn); } else result = imap_perform_authentication(conn); return result; } /* For STARTTLS responses */ static CURLcode imap_state_starttls_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(imapcode != IMAP_RESP_OK) { if(data->set.use_ssl != CURLUSESSL_TRY) { failf(data, "STARTTLS denied"); result = CURLE_USE_SSL_FAILED; } else result = imap_perform_authentication(conn); } else result = imap_perform_upgrade_tls(conn); return result; } /* For SASL authentication responses */ static CURLcode imap_state_auth_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; saslprogress progress; (void)instate; /* no use for this yet */ result = Curl_sasl_continue(&imapc->sasl, conn, imapcode, &progress); if(!result) switch(progress) { case SASL_DONE: state(conn, IMAP_STOP); /* Authenticated */ break; case SASL_IDLE: /* No mechanism left after cancellation */ if((!imapc->login_disabled) && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) /* Perform clear text authentication */ result = imap_perform_login(conn); else { failf(data, "Authentication cancelled"); result = CURLE_LOGIN_DENIED; } break; default: break; } return result; } /* For LOGIN responses */ static CURLcode imap_state_login_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(imapcode != IMAP_RESP_OK) { failf(data, "Access denied. %c", imapcode); result = CURLE_LOGIN_DENIED; } else /* End of connect phase */ state(conn, IMAP_STOP); return result; } /* For LIST and SEARCH responses */ static CURLcode imap_state_listsearch_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; char *line = conn->data->state.buffer; size_t len = strlen(line); (void)instate; /* No use for this yet */ if(imapcode == '*') { /* Temporarily add the LF character back and send as body to the client */ line[len] = '\n'; result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1); line[len] = '\0'; } else if(imapcode != IMAP_RESP_OK) result = CURLE_QUOTE_ERROR; else /* End of DO phase */ state(conn, IMAP_STOP); return result; } /* For SELECT responses */ static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = conn->data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; (void)instate; /* no use for this yet */ if(imapcode == '*') { /* See if this is an UIDVALIDITY response */ char tmp[20]; if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) { Curl_safefree(imapc->mailbox_uidvalidity); imapc->mailbox_uidvalidity = strdup(tmp); } } else if(imapcode == IMAP_RESP_OK) { /* Check if the UIDVALIDITY has been specified and matches */ if(imap->uidvalidity && imapc->mailbox_uidvalidity && !strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity)) { failf(conn->data, "Mailbox UIDVALIDITY has changed"); result = CURLE_REMOTE_FILE_NOT_FOUND; } else { /* Note the currently opened mailbox on this connection */ imapc->mailbox = strdup(imap->mailbox); if(imap->custom) result = imap_perform_list(conn); else if(imap->query) result = imap_perform_search(conn); else result = imap_perform_fetch(conn); } } else { failf(data, "Select failed"); result = CURLE_LOGIN_DENIED; } return result; } /* For the (first line of the) FETCH responses */ static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; const char *ptr = data->state.buffer; bool parsed = FALSE; curl_off_t size = 0; (void)instate; /* no use for this yet */ if(imapcode != '*') { Curl_pgrsSetDownloadSize(data, -1); state(conn, IMAP_STOP); return CURLE_REMOTE_FILE_NOT_FOUND; } /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse the continuation data contained within the curly brackets */ while(*ptr && (*ptr != '{')) ptr++; if(*ptr == '{') { char *endptr; if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) { if(endptr - ptr > 1 && endptr[0] == '}' && endptr[1] == '\r' && endptr[2] == '\0') parsed = TRUE; } } if(parsed) { infof(data, "Found %" CURL_FORMAT_CURL_OFF_T " bytes to download\n", size); Curl_pgrsSetDownloadSize(data, size); if(pp->cache) { /* At this point there is a bunch of data in the header "cache" that is actually body content, send it as body and then skip it. Do note that there may even be additional "headers" after the body. */ size_t chunk = pp->cache_size; if(chunk > (size_t)size) /* The conversion from curl_off_t to size_t is always fine here */ chunk = (size_t)size; if(!chunk) { /* no size, we're done with the data */ state(conn, IMAP_STOP); return CURLE_OK; } result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk); if(result) return result; data->req.bytecount += chunk; infof(data, "Written %zu bytes, %" CURL_FORMAT_CURL_OFF_TU " bytes are left for transfer\n", chunk, size - chunk); /* Have we used the entire cache or just part of it?*/ if(pp->cache_size > chunk) { /* Only part of it so shrink the cache to fit the trailing data */ memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk); pp->cache_size -= chunk; } else { /* Free the cache */ Curl_safefree(pp->cache); /* Reset the cache size */ pp->cache_size = 0; } } if(data->req.bytecount == size) /* The entire data is already transferred! */ Curl_setup_transfer(data, -1, -1, FALSE, -1); else { /* IMAP download */ data->req.maxdownload = size; Curl_setup_transfer(data, FIRSTSOCKET, size, FALSE, -1); } } else { /* We don't know how to parse this line */ failf(pp->conn->data, "Failed to parse FETCH response."); result = CURLE_WEIRD_SERVER_REPLY; } /* End of DO phase */ state(conn, IMAP_STOP); return result; } /* For final FETCH responses performed after the download */ static CURLcode imap_state_fetch_final_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* No use for this yet */ if(imapcode != IMAP_RESP_OK) result = CURLE_WEIRD_SERVER_REPLY; else /* End of DONE phase */ state(conn, IMAP_STOP); return result; } /* For APPEND responses */ static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* No use for this yet */ if(imapcode != '+') { result = CURLE_UPLOAD_FAILED; } else { /* Set the progress upload size */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* IMAP upload */ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); /* End of DO phase */ state(conn, IMAP_STOP); } return result; } /* For final APPEND responses performed after the upload */ static CURLcode imap_state_append_final_resp(struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* No use for this yet */ if(imapcode != IMAP_RESP_OK) result = CURLE_UPLOAD_FAILED; else /* End of DONE phase */ state(conn, IMAP_STOP); return result; } static CURLcode imap_statemach_act(struct connectdata *conn) { CURLcode result = CURLE_OK; curl_socket_t sock = conn->sock[FIRSTSOCKET]; int imapcode; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; size_t nread = 0; /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */ if(imapc->state == IMAP_UPGRADETLS) return imap_perform_upgrade_tls(conn); /* Flush any data that needs to be sent */ if(pp->sendleft) return Curl_pp_flushsend(pp); do { /* Read the response from the server */ result = Curl_pp_readresp(sock, pp, &imapcode, &nread); if(result) return result; /* Was there an error parsing the response line? */ if(imapcode == -1) return CURLE_WEIRD_SERVER_REPLY; if(!imapcode) break; /* We have now received a full IMAP server response */ switch(imapc->state) { case IMAP_SERVERGREET: result = imap_state_servergreet_resp(conn, imapcode, imapc->state); break; case IMAP_CAPABILITY: result = imap_state_capability_resp(conn, imapcode, imapc->state); break; case IMAP_STARTTLS: result = imap_state_starttls_resp(conn, imapcode, imapc->state); break; case IMAP_AUTHENTICATE: result = imap_state_auth_resp(conn, imapcode, imapc->state); break; case IMAP_LOGIN: result = imap_state_login_resp(conn, imapcode, imapc->state); break; case IMAP_LIST: result = imap_state_listsearch_resp(conn, imapcode, imapc->state); break; case IMAP_SELECT: result = imap_state_select_resp(conn, imapcode, imapc->state); break; case IMAP_FETCH: result = imap_state_fetch_resp(conn, imapcode, imapc->state); break; case IMAP_FETCH_FINAL: result = imap_state_fetch_final_resp(conn, imapcode, imapc->state); break; case IMAP_APPEND: result = imap_state_append_resp(conn, imapcode, imapc->state); break; case IMAP_APPEND_FINAL: result = imap_state_append_final_resp(conn, imapcode, imapc->state); break; case IMAP_SEARCH: result = imap_state_listsearch_resp(conn, imapcode, imapc->state); break; case IMAP_LOGOUT: /* fallthrough, just stop! */ default: /* internal error */ state(conn, IMAP_STOP); break; } } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp)); return result; } /* Called repeatedly until done from multi.c */ static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) { result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone); if(result || !imapc->ssldone) return result; } result = Curl_pp_statemach(&imapc->pp, FALSE, FALSE); *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE; return result; } static CURLcode imap_block_statemach(struct connectdata *conn, bool disconnecting) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; while(imapc->state != IMAP_STOP && !result) result = Curl_pp_statemach(&imapc->pp, TRUE, disconnecting); return result; } /* Allocate and initialize the struct IMAP for the current Curl_easy if required */ static CURLcode imap_init(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap; imap = data->req.protop = calloc(sizeof(struct IMAP), 1); if(!imap) result = CURLE_OUT_OF_MEMORY; return result; } /* For the IMAP "protocol connect" and "doing" phases only */ static int imap_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks); } /*********************************************************************** * * imap_connect() * * This function should do everything that is to be considered a part of the * connection phase. * * The variable 'done' points to will be TRUE if the protocol-layer connect * phase is done when this function returns, or FALSE if not. */ static CURLcode imap_connect(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections in IMAP */ connkeep(conn, "IMAP default"); /* Set the default response time-out */ pp->response_time = RESP_TIMEOUT; pp->statemach_act = imap_statemach_act; pp->endofresp = imap_endofresp; pp->conn = conn; /* Set the default preferred authentication type and mechanism */ imapc->preftype = IMAP_TYPE_ANY; Curl_sasl_init(&imapc->sasl, &saslimap); /* Initialise the pingpong layer */ Curl_pp_init(pp); /* Parse the URL options */ result = imap_parse_url_options(conn); if(result) return result; /* Start off waiting for the server greeting response */ state(conn, IMAP_SERVERGREET); /* Start off with an response id of '*' */ strcpy(imapc->resptag, "*"); result = imap_multi_statemach(conn, done); return result; } /*********************************************************************** * * imap_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */ static CURLcode imap_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; (void)premature; if(!imap) return CURLE_OK; if(status) { connclose(conn, "IMAP done with bad status"); /* marked for closure */ result = status; /* use the already set error code */ } else if(!data->set.connect_only && !imap->custom && (imap->uid || imap->mindex || data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE)) { /* Handle responses after FETCH or APPEND transfer has finished */ if(!data->set.upload && data->set.mimepost.kind == MIMEKIND_NONE) state(conn, IMAP_FETCH_FINAL); else { /* End the APPEND command first by sending an empty line */ result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", ""); if(!result) state(conn, IMAP_APPEND_FINAL); } /* Run the state-machine */ if(!result) result = imap_block_statemach(conn, FALSE); } /* Cleanup our per-request based variables */ Curl_safefree(imap->mailbox); Curl_safefree(imap->uidvalidity); Curl_safefree(imap->uid); Curl_safefree(imap->mindex); Curl_safefree(imap->section); Curl_safefree(imap->partial); Curl_safefree(imap->query); Curl_safefree(imap->custom); Curl_safefree(imap->custom_params); /* Clear the transfer mode for the next request */ imap->transfer = FTPTRANSFER_BODY; return result; } /*********************************************************************** * * imap_perform() * * This is the actual DO function for IMAP. Fetch or append a message, or do * other things according to the options previously setup. */ static CURLcode imap_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { /* This is IMAP and no proxy */ CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; struct imap_conn *imapc = &conn->proto.imapc; bool selected = FALSE; DEBUGF(infof(conn->data, "DO phase starts\n")); if(conn->data->set.opt_no_body) { /* Requested no body means no transfer */ imap->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* Determine if the requested mailbox (with the same UIDVALIDITY if set) has already been selected on this connection */ if(imap->mailbox && imapc->mailbox && strcasecompare(imap->mailbox, imapc->mailbox) && (!imap->uidvalidity || !imapc->mailbox_uidvalidity || strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity))) selected = TRUE; /* Start the first command in the DO phase */ if(conn->data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE) /* APPEND can be executed directly */ result = imap_perform_append(conn); else if(imap->custom && (selected || !imap->mailbox)) /* Custom command using the same mailbox or no mailbox */ result = imap_perform_list(conn); else if(!imap->custom && selected && (imap->uid || imap->mindex)) /* FETCH from the same mailbox */ result = imap_perform_fetch(conn); else if(!imap->custom && selected && imap->query) /* SEARCH the current mailbox */ result = imap_perform_search(conn); else if(imap->mailbox && !selected && (imap->custom || imap->uid || imap->mindex || imap->query)) /* SELECT the mailbox */ result = imap_perform_select(conn); else /* LIST */ result = imap_perform_list(conn); if(result) return result; /* Run the state-machine */ result = imap_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; } /*********************************************************************** * * imap_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (imap_perform). * * The input argument is already checked for validity. */ static CURLcode imap_do(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; *done = FALSE; /* default to false */ /* Parse the URL path */ result = imap_parse_url_path(conn); if(result) return result; /* Parse the custom request */ result = imap_parse_custom_request(conn); if(result) return result; result = imap_regular_transfer(conn, done); return result; } /*********************************************************************** * * imap_disconnect() * * Disconnect from an IMAP server. Cleanup protocol-specific per-connection * resources. BLOCKING. */ static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection) { struct imap_conn *imapc = &conn->proto.imapc; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. */ /* The IMAP session may or may not have been allocated/setup at this point! */ if(!dead_connection && imapc->pp.conn && imapc->pp.conn->bits.protoconnstart) if(!imap_perform_logout(conn)) (void)imap_block_statemach(conn, TRUE); /* ignore errors on LOGOUT */ /* Disconnect from the server */ Curl_pp_disconnect(&imapc->pp); /* Cleanup the SASL module */ Curl_sasl_cleanup(conn, imapc->sasl.authused); /* Cleanup our connection based variables */ Curl_safefree(imapc->mailbox); Curl_safefree(imapc->mailbox_uidvalidity); return CURLE_OK; } /* Call this when the DO phase has completed */ static CURLcode imap_dophase_done(struct connectdata *conn, bool connected) { struct IMAP *imap = conn->data->req.protop; (void)connected; if(imap->transfer != FTPTRANSFER_BODY) /* no data to transfer */ Curl_setup_transfer(conn->data, -1, -1, FALSE, -1); return CURLE_OK; } /* Called from multi.c while DOing */ static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = imap_multi_statemach(conn, dophase_done); if(result) DEBUGF(infof(conn->data, "DO phase failed\n")); else if(*dophase_done) { result = imap_dophase_done(conn, FALSE /* not connected */); DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /*********************************************************************** * * imap_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. */ static CURLcode imap_regular_transfer(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; bool connected = FALSE; struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; /* Set the progress data */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); /* Carry out the perform */ result = imap_perform(conn, &connected, dophase_done); /* Perform post DO phase operations if necessary */ if(!result && *dophase_done) result = imap_dophase_done(conn, connected); return result; } static CURLcode imap_setup_connection(struct connectdata *conn) { /* Initialise the IMAP layer */ CURLcode result = imap_init(conn); if(result) return result; /* Clear the TLS upgraded flag */ conn->tls_upgraded = FALSE; return CURLE_OK; } /*********************************************************************** * * imap_sendf() * * Sends the formatted string as an IMAP command to the server. * * Designed to never block. */ static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; char *taggedfmt; va_list ap; DEBUGASSERT(fmt); /* Calculate the next command ID wrapping at 3 digits */ imapc->cmdid = (imapc->cmdid + 1) % 1000; /* Calculate the tag based on the connection ID and command ID */ msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d", 'A' + curlx_sltosi(conn->connection_id % 26), imapc->cmdid); /* Prefix the format with the tag */ taggedfmt = aprintf("%s %s", imapc->resptag, fmt); if(!taggedfmt) return CURLE_OUT_OF_MEMORY; /* Send the data with the tag */ va_start(ap, fmt); result = Curl_pp_vsendf(&imapc->pp, taggedfmt, ap); va_end(ap); free(taggedfmt); return result; } /*********************************************************************** * * imap_atom() * * Checks the input string for characters that need escaping and returns an * atom ready for sending to the server. * * The returned string needs to be freed. * */ static char *imap_atom(const char *str, bool escape_only) { /* !checksrc! disable PARENBRACE 1 */ const char atom_specials[] = "(){ %*]"; const char *p1; char *p2; size_t backsp_count = 0; size_t quote_count = 0; bool others_exists = FALSE; size_t newlen = 0; char *newstr = NULL; if(!str) return NULL; /* Look for "atom-specials", counting the backslash and quote characters as these will need escaping */ p1 = str; while(*p1) { if(*p1 == '\\') backsp_count++; else if(*p1 == '"') quote_count++; else if(!escape_only) { const char *p3 = atom_specials; while(*p3 && !others_exists) { if(*p1 == *p3) others_exists = TRUE; p3++; } } p1++; } /* Does the input contain any "atom-special" characters? */ if(!backsp_count && !quote_count && !others_exists) return strdup(str); /* Calculate the new string length */ newlen = strlen(str) + backsp_count + quote_count + (escape_only ? 0 : 2); /* Allocate the new string */ newstr = (char *) malloc((newlen + 1) * sizeof(char)); if(!newstr) return NULL; /* Surround the string in quotes if necessary */ p2 = newstr; if(!escape_only) { newstr[0] = '"'; newstr[newlen - 1] = '"'; p2++; } /* Copy the string, escaping backslash and quote characters along the way */ p1 = str; while(*p1) { if(*p1 == '\\' || *p1 == '"') { *p2 = '\\'; p2++; } *p2 = *p1; p1++; p2++; } /* Terminate the string */ newstr[newlen] = '\0'; return newstr; } /*********************************************************************** * * imap_is_bchar() * * Portable test of whether the specified char is a "bchar" as defined in the * grammar of RFC-5092. */ static bool imap_is_bchar(char ch) { switch(ch) { /* bchar */ case ':': case '@': case '/': /* bchar -> achar */ case '&': case '=': /* bchar -> achar -> uchar -> unreserved */ 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 '~': /* bchar -> achar -> uchar -> sub-delims-sh */ case '!': case '$': case '\'': case '(': case ')': case '*': case '+': case ',': /* bchar -> achar -> uchar -> pct-encoded */ case '%': /* HEXDIG chars are already included above */ return true; default: return false; } } /*********************************************************************** * * imap_parse_url_options() * * Parse the URL login options. */ static CURLcode imap_parse_url_options(struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; const char *ptr = conn->options; imapc->sasl.resetprefs = TRUE; while(!result && ptr && *ptr) { const char *key = ptr; const char *value; while(*ptr && *ptr != '=') ptr++; value = ptr + 1; while(*ptr && *ptr != ';') ptr++; if(strncasecompare(key, "AUTH=", 5)) result = Curl_sasl_parse_url_auth_option(&imapc->sasl, value, ptr - value); else result = CURLE_URL_MALFORMAT; if(*ptr == ';') ptr++; } switch(imapc->sasl.prefmech) { case SASL_AUTH_NONE: imapc->preftype = IMAP_TYPE_NONE; break; case SASL_AUTH_DEFAULT: imapc->preftype = IMAP_TYPE_ANY; break; default: imapc->preftype = IMAP_TYPE_SASL; break; } return result; } /*********************************************************************** * * imap_parse_url_path() * * Parse the URL path into separate path components. * */ static CURLcode imap_parse_url_path(struct connectdata *conn) { /* The imap struct is already initialised in imap_connect() */ CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; const char *begin = &data->state.up.path[1]; /* skip leading slash */ const char *ptr = begin; /* See how much of the URL is a valid path and decode it */ while(imap_is_bchar(*ptr)) ptr++; if(ptr != begin) { /* Remove the trailing slash if present */ const char *end = ptr; if(end > begin && end[-1] == '/') end--; result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL, TRUE); if(result) return result; } else imap->mailbox = NULL; /* There can be any number of parameters in the form ";NAME=VALUE" */ while(*ptr == ';') { char *name; char *value; size_t valuelen; /* Find the length of the name parameter */ begin = ++ptr; while(*ptr && *ptr != '=') ptr++; if(!*ptr) return CURLE_URL_MALFORMAT; /* Decode the name parameter */ result = Curl_urldecode(data, begin, ptr - begin, &name, NULL, TRUE); if(result) return result; /* Find the length of the value parameter */ begin = ++ptr; while(imap_is_bchar(*ptr)) ptr++; /* Decode the value parameter */ result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen, TRUE); if(result) { free(name); return result; } DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value)); /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and PARTIAL) stripping of the trailing slash character if it is present. Note: Unknown parameters trigger a URL_MALFORMAT error. */ if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->uidvalidity = value; value = NULL; } else if(strcasecompare(name, "UID") && !imap->uid) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->uid = value; value = NULL; } else if(strcasecompare(name, "MAILINDEX") && !imap->mindex) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->mindex = value; value = NULL; } else if(strcasecompare(name, "SECTION") && !imap->section) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->section = value; value = NULL; } else if(strcasecompare(name, "PARTIAL") && !imap->partial) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->partial = value; value = NULL; } else { free(name); free(value); return CURLE_URL_MALFORMAT; } free(name); free(value); } /* Does the URL contain a query parameter? Only valid when we have a mailbox and no UID as per RFC-5092 */ if(imap->mailbox && !imap->uid && !imap->mindex) { /* Get the query parameter, URL decoded */ (void)curl_url_get(data->state.uh, CURLUPART_QUERY, &imap->query, CURLU_URLDECODE); } /* Any extra stuff at the end of the URL is an error */ if(*ptr) return CURLE_URL_MALFORMAT; return CURLE_OK; } /*********************************************************************** * * imap_parse_custom_request() * * Parse the custom request. */ static CURLcode imap_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct IMAP *imap = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; if(custom) { /* URL decode the custom request */ result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, TRUE); /* Extract the parameters if specified */ if(!result) { const char *params = imap->custom; while(*params && *params != ' ') params++; if(*params) { imap->custom_params = strdup(params); imap->custom[params - imap->custom] = '\0'; if(!imap->custom_params) result = CURLE_OUT_OF_MEMORY; } } } return result; } #endif /* CURL_DISABLE_IMAP */
YifuLiu/AliOS-Things
components/curl/lib/imap.c
C
apache-2.0
60,104
#ifndef HEADER_CURL_IMAP_H #define HEADER_CURL_IMAP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2009 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */ 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 */ }; 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 */
YifuLiu/AliOS-Things
components/curl/lib/imap.h
C
apache-2.0
3,941
/* * Copyright (C) 1996-2001 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_ntoa(). * * 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 != 0) *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 */
YifuLiu/AliOS-Things
components/curl/lib/inet_ntop.c
C
apache-2.0
5,407
#ifndef HEADER_CURL_INET_NTOP_H #define HEADER_CURL_INET_NTOP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" char *Curl_inet_ntop(int af, const void *addr, char *buf, size_t size); #ifdef HAVE_INET_NTOP #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #define Curl_inet_ntop(af,addr,buf,size) \ inet_ntop(af, addr, buf, (curl_socklen_t)size) #endif #endif /* HEADER_CURL_INET_NTOP_H */
YifuLiu/AliOS-Things
components/curl/lib/inet_ntop.h
C
apache-2.0
1,408
/* This is from the BIND 4.9.4 release, modified to compile by itself */ /* Copyright (c) 1996 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 */
YifuLiu/AliOS-Things
components/curl/lib/inet_pton.c
C
apache-2.0
6,122
#ifndef HEADER_CURL_INET_PTON_H #define HEADER_CURL_INET_PTON_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */
YifuLiu/AliOS-Things
components/curl/lib/inet_pton.h
C
apache-2.0
1,428
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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. */ #ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */ # include <winldap.h> # ifndef LDAP_VENDOR_NAME # error Your Platform SDK is NOT sufficient for LDAP support! \ Update your Platform SDK, or disable LDAP support! # else # include <winber.h> # endif #else # define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */ # ifdef HAVE_LBER_H # include <lber.h> # endif # include <ldap.h> # if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H)) # include <ldap_ssl.h> # endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */ #endif #include "urldata.h" #include <curl/curl.h> #include "sendf.h" #include "escape.h" #include "progress.h" #include "transfer.h" #include "strcase.h" #include "strtok.h" #include "curl_ldap.h" #include "curl_multibyte.h" #include "curl_base64.h" #include "connect.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #ifndef HAVE_LDAP_URL_PARSE /* Use our own implementation. */ typedef struct { char *lud_host; int lud_port; #if defined(USE_WIN32_LDAP) TCHAR *lud_dn; TCHAR **lud_attrs; #else char *lud_dn; char **lud_attrs; #endif int lud_scope; #if defined(USE_WIN32_LDAP) TCHAR *lud_filter; #else char *lud_filter; #endif char **lud_exts; size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the "real" struct so can only be used in code without HAVE_LDAP_URL_PARSE defined */ } CURL_LDAPURLDesc; #undef LDAPURLDesc #define LDAPURLDesc CURL_LDAPURLDesc static int _ldap_url_parse(const struct connectdata *conn, LDAPURLDesc **ludp); static void _ldap_free_urldesc(LDAPURLDesc *ludp); #undef ldap_free_urldesc #define ldap_free_urldesc _ldap_free_urldesc #endif #ifdef DEBUG_LDAP #define LDAP_TRACE(x) do { \ _ldap_trace("%u: ", __LINE__); \ _ldap_trace x; \ } WHILE_FALSE static void _ldap_trace(const char *fmt, ...); #else #define LDAP_TRACE(x) Curl_nop_stmt #endif static CURLcode Curl_ldap(struct connectdata *conn, bool *done); /* * LDAP protocol handler. */ const struct Curl_handler Curl_handler_ldap = { "LDAP", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_ldap, /* 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 */ PORT_LDAP, /* defport */ CURLPROTO_LDAP, /* protocol */ PROTOPT_NONE /* flags */ }; #ifdef HAVE_LDAP_SSL /* * LDAPS protocol handler. */ const struct Curl_handler Curl_handler_ldaps = { "LDAPS", /* scheme */ ZERO_NULL, /* setup_connection */ Curl_ldap, /* 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 */ PORT_LDAPS, /* defport */ CURLPROTO_LDAPS, /* protocol */ PROTOPT_SSL /* flags */ }; #endif #if defined(USE_WIN32_LDAP) #if defined(USE_WINDOWS_SSPI) static int ldap_win_bind_auth(LDAP *server, const char *user, const char *passwd, unsigned long authflags) { ULONG method = 0; SEC_WINNT_AUTH_IDENTITY cred; int rc = LDAP_AUTH_METHOD_NOT_SUPPORTED; memset(&cred, 0, sizeof(cred)); #if defined(USE_SPNEGO) if(authflags & CURLAUTH_NEGOTIATE) { method = LDAP_AUTH_NEGOTIATE; } else #endif #if defined(USE_NTLM) if(authflags & CURLAUTH_NTLM) { method = LDAP_AUTH_NTLM; } else #endif #if !defined(CURL_DISABLE_CRYPTO_AUTH) if(authflags & CURLAUTH_DIGEST) { method = LDAP_AUTH_DIGEST; } else #endif { /* required anyway if one of upper preprocessor definitions enabled */ } if(method && user && passwd) { rc = Curl_create_sspi_identity(user, passwd, &cred); if(!rc) { rc = ldap_bind_s(server, NULL, (TCHAR *)&cred, method); Curl_sspi_free_identity(&cred); } } else { /* proceed with current user credentials */ method = LDAP_AUTH_NEGOTIATE; rc = ldap_bind_s(server, NULL, NULL, method); } return rc; } #endif /* #if defined(USE_WINDOWS_SSPI) */ static int ldap_win_bind(struct connectdata *conn, LDAP *server, const char *user, const char *passwd) { int rc = LDAP_INVALID_CREDENTIALS; PTCHAR inuser = NULL; PTCHAR inpass = NULL; if(user && passwd && (conn->data->set.httpauth & CURLAUTH_BASIC)) { inuser = Curl_convert_UTF8_to_tchar((char *) user); inpass = Curl_convert_UTF8_to_tchar((char *) passwd); rc = ldap_simple_bind_s(server, inuser, inpass); Curl_unicodefree(inuser); Curl_unicodefree(inpass); } #if defined(USE_WINDOWS_SSPI) else { rc = ldap_win_bind_auth(server, user, passwd, conn->data->set.httpauth); } #endif return rc; } #endif /* #if defined(USE_WIN32_LDAP) */ static CURLcode Curl_ldap(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; int rc = 0; LDAP *server = NULL; LDAPURLDesc *ludp = NULL; LDAPMessage *ldapmsg = NULL; LDAPMessage *entryIterator; int num = 0; struct Curl_easy *data = conn->data; int ldap_proto = LDAP_VERSION3; int ldap_ssl = 0; char *val_b64 = NULL; size_t val_b64_sz = 0; curl_off_t dlsize = 0; #ifdef LDAP_OPT_NETWORK_TIMEOUT struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */ #endif #if defined(USE_WIN32_LDAP) TCHAR *host = NULL; #else char *host = NULL; #endif char *user = NULL; char *passwd = NULL; *done = TRUE; /* unconditionally */ infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n", LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); infof(data, "LDAP local: %s\n", data->change.url); #ifdef HAVE_LDAP_URL_PARSE rc = ldap_url_parse(data->change.url, &ludp); #else rc = _ldap_url_parse(conn, &ludp); #endif if(rc != 0) { failf(data, "LDAP local: %s", ldap_err2string(rc)); result = CURLE_LDAP_INVALID_URL; goto quit; } /* Get the URL scheme (either ldap or ldaps) */ if(conn->given->flags & PROTOPT_SSL) ldap_ssl = 1; infof(data, "LDAP local: trying to establish %s connection\n", ldap_ssl ? "encrypted" : "cleartext"); #if defined(USE_WIN32_LDAP) host = Curl_convert_UTF8_to_tchar(conn->host.name); if(!host) { result = CURLE_OUT_OF_MEMORY; goto quit; } #else host = conn->host.name; #endif if(conn->bits.user_passwd) { user = conn->user; passwd = conn->passwd; } #ifdef LDAP_OPT_NETWORK_TIMEOUT ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); #endif ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); if(ldap_ssl) { #ifdef HAVE_LDAP_SSL #ifdef USE_WIN32_LDAP /* Win32 LDAP SDK doesn't support insecure mode without CA! */ server = ldap_sslinit(host, (int)conn->port, 1); ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); #else int ldap_option; char *ldap_ca = conn->ssl_config.CAfile; #if defined(CURL_HAS_NOVELL_LDAPSDK) rc = ldapssl_client_init(NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(conn->ssl_config.verifypeer) { /* Novell SDK supports DER or BASE64 files. */ int cert_type = LDAPSSL_CERT_FILETYPE_B64; if((data->set.ssl.cert_type) && (strcasecompare(data->set.ssl.cert_type, "DER"))) cert_type = LDAPSSL_CERT_FILETYPE_DER; if(!ldap_ca) { failf(data, "LDAP local: ERROR %s CA cert not set!", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM")); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using %s CA cert '%s'\n", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_ca); rc = ldapssl_add_trusted_cert(ldap_ca, cert_type); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting %s CA cert: %s", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAPSSL_VERIFY_SERVER; } else ldap_option = LDAPSSL_VERIFY_NONE; rc = ldapssl_set_verify_mode(ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldapssl_init(host, (int)conn->port, 1); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } #elif defined(LDAP_OPT_X_TLS) if(conn->ssl_config.verifypeer) { /* OpenLDAP SDK supports BASE64 files. */ if((data->set.ssl.cert_type) && (!strcasecompare(data->set.ssl.cert_type, "PEM"))) { failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(!ldap_ca) { failf(data, "LDAP local: ERROR PEM CA cert not set!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca); rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting PEM CA cert: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAP_OPT_X_TLS_DEMAND; } else ldap_option = LDAP_OPT_X_TLS_NEVER; rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldap_init(host, (int)conn->port); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } ldap_option = LDAP_OPT_X_TLS_HARD; rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } /* rc = ldap_start_tls_s(server, NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } */ #else /* we should probably never come up to here since configure should check in first place if we can support LDAP SSL/TLS */ failf(data, "LDAP local: SSL/TLS not supported with this version " "of the OpenLDAP toolkit\n"); result = CURLE_SSL_CERTPROBLEM; goto quit; #endif #endif #endif /* CURL_LDAP_USE_SSL */ } else { server = ldap_init(host, (int)conn->port); if(server == NULL) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } } #ifdef USE_WIN32_LDAP ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); #endif #ifdef USE_WIN32_LDAP rc = ldap_win_bind(conn, server, user, passwd); #else rc = ldap_simple_bind_s(server, user, passwd); #endif if(!ldap_ssl && rc != 0) { ldap_proto = LDAP_VERSION2; ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); #ifdef USE_WIN32_LDAP rc = ldap_win_bind(conn, server, user, passwd); #else rc = ldap_simple_bind_s(server, user, passwd); #endif } if(rc != 0) { #ifdef USE_WIN32_LDAP failf(data, "LDAP local: bind via ldap_win_bind %s", ldap_err2string(rc)); #else failf(data, "LDAP local: bind via ldap_simple_bind_s %s", ldap_err2string(rc)); #endif result = CURLE_LDAP_CANNOT_BIND; goto quit; } rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); if(rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) { failf(data, "LDAP remote: %s", ldap_err2string(rc)); result = CURLE_LDAP_SEARCH_FAILED; goto quit; } for(num = 0, entryIterator = ldap_first_entry(server, ldapmsg); entryIterator; entryIterator = ldap_next_entry(server, entryIterator), num++) { BerElement *ber = NULL; #if defined(USE_WIN32_LDAP) TCHAR *attribute; #else char *attribute; /*! suspicious that this isn't 'const' */ #endif int i; /* Get the DN and write it to the client */ { char *name; size_t name_len; #if defined(USE_WIN32_LDAP) TCHAR *dn = ldap_get_dn(server, entryIterator); name = Curl_convert_tchar_to_UTF8(dn); if(!name) { ldap_memfree(dn); result = CURLE_OUT_OF_MEMORY; goto quit; } #else char *dn = name = ldap_get_dn(server, entryIterator); #endif name_len = strlen(name); result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); if(result) { #if defined(USE_WIN32_LDAP) Curl_unicodefree(name); #endif ldap_memfree(dn); goto quit; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *) name, name_len); if(result) { #if defined(USE_WIN32_LDAP) Curl_unicodefree(name); #endif ldap_memfree(dn); goto quit; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) { #if defined(USE_WIN32_LDAP) Curl_unicodefree(name); #endif ldap_memfree(dn); goto quit; } dlsize += name_len + 5; #if defined(USE_WIN32_LDAP) Curl_unicodefree(name); #endif ldap_memfree(dn); } /* Get the attributes and write them to the client */ for(attribute = ldap_first_attribute(server, entryIterator, &ber); attribute; attribute = ldap_next_attribute(server, entryIterator, ber)) { BerValue **vals; size_t attr_len; #if defined(USE_WIN32_LDAP) char *attr = Curl_convert_tchar_to_UTF8(attribute); if(!attr) { if(ber) ber_free(ber, 0); result = CURLE_OUT_OF_MEMORY; goto quit; } #else char *attr = attribute; #endif attr_len = strlen(attr); vals = ldap_get_values_len(server, entryIterator, attribute); if(vals != NULL) { for(i = 0; (vals[i] != NULL); i++) { result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *) attr, attr_len); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += attr_len + 3; if((attr_len > 7) && (strcmp(";binary", (char *) attr + (attr_len - 7)) == 0)) { /* Binary attribute, encode to base64. */ result = Curl_base64_encode(data, vals[i]->bv_val, vals[i]->bv_len, &val_b64, &val_b64_sz); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } if(val_b64_sz > 0) { result = Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz); free(val_b64); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += val_b64_sz; } } else { result = Curl_client_write(conn, CLIENTWRITE_BODY, vals[i]->bv_val, vals[i]->bv_len); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += vals[i]->bv_len; } result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) { ldap_value_free_len(vals); #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize++; } /* Free memory used to store values */ ldap_value_free_len(vals); } /* Free the attribute as we are done with it */ #if defined(USE_WIN32_LDAP) Curl_unicodefree(attr); #endif ldap_memfree(attribute); result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) goto quit; dlsize++; Curl_pgrsSetDownloadCounter(data, dlsize); } if(ber) ber_free(ber, 0); } quit: if(ldapmsg) { ldap_msgfree(ldapmsg); LDAP_TRACE(("Received %d entries\n", num)); } if(rc == LDAP_SIZELIMIT_EXCEEDED) infof(data, "There are more than %d entries\n", num); if(ludp) ldap_free_urldesc(ludp); if(server) ldap_unbind_s(server); #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK) if(ldap_ssl) ldapssl_client_deinit(); #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */ #if defined(USE_WIN32_LDAP) Curl_unicodefree(host); #endif /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); connclose(conn, "LDAP connection always disable re-use"); return result; } #ifdef DEBUG_LDAP static void _ldap_trace(const char *fmt, ...) { static int do_trace = -1; va_list args; if(do_trace == -1) { const char *env = getenv("CURL_TRACE"); do_trace = (env && strtol(env, NULL, 10) > 0); } if(!do_trace) return; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } #endif #ifndef HAVE_LDAP_URL_PARSE /* * Return scope-value for a scope-string. */ static int str2scope(const char *p) { if(strcasecompare(p, "one")) return LDAP_SCOPE_ONELEVEL; if(strcasecompare(p, "onetree")) return LDAP_SCOPE_ONELEVEL; if(strcasecompare(p, "base")) return LDAP_SCOPE_BASE; if(strcasecompare(p, "sub")) return LDAP_SCOPE_SUBTREE; if(strcasecompare(p, "subtree")) return LDAP_SCOPE_SUBTREE; return (-1); } /* * Split 'str' into strings separated by commas. * Note: out[] points into 'str'. */ static bool split_str(char *str, char ***out, size_t *count) { char **res; char *lasts; char *s; size_t i; size_t items = 1; s = strchr(str, ','); while(s) { items++; s = strchr(++s, ','); } res = calloc(items, sizeof(char *)); if(!res) return FALSE; for(i = 0, s = strtok_r(str, ",", &lasts); s && i < items; s = strtok_r(NULL, ",", &lasts), i++) res[i] = s; *out = res; *count = items; return TRUE; } /* * Break apart the pieces of an LDAP URL. * Syntax: * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext> * * <hostname> already known from 'conn->host.name'. * <port> already known from 'conn->remote_port'. * extract the rest from 'conn->data->state.path+1'. All fields are optional. * e.g. * ldap://<hostname>:<port>/?<attributes>?<scope>?<filter> * yields ludp->lud_dn = "". * * Defined in RFC4516 section 2. */ static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp) { int rc = LDAP_SUCCESS; char *path; char *query; char *p; char *q; size_t i; if(!conn->data || !conn->data->state.up.path || conn->data->state.up.path[0] != '/' || !strncasecompare("LDAP", conn->data->state.up.scheme, 4)) return LDAP_INVALID_SYNTAX; ludp->lud_scope = LDAP_SCOPE_BASE; ludp->lud_port = conn->remote_port; ludp->lud_host = conn->host.name; /* Duplicate the path */ p = path = strdup(conn->data->state.up.path + 1); if(!path) return LDAP_NO_MEMORY; /* Duplicate the query */ q = query = strdup(conn->data->state.up.query); if(!query) { free(path); return LDAP_NO_MEMORY; } /* Parse the DN (Distinguished Name) */ if(*p) { char *dn = p; char *unescaped; CURLcode result; LDAP_TRACE(("DN '%s'\n", dn)); /* Unescape the DN */ result = Curl_urldecode(conn->data, dn, 0, &unescaped, NULL, FALSE); if(result) { rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_dn = Curl_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ Curl_unicodefree(unescaped); if(!ludp->lud_dn) { rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_dn = unescaped; #endif } p = q; if(!p) goto quit; /* Parse the attributes. skip "??" */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { char **attributes; size_t count = 0; /* Split the string into an array of attributes */ if(!split_str(p, &attributes, &count)) { rc = LDAP_NO_MEMORY; goto quit; } /* Allocate our array (+1 for the NULL entry) */ #if defined(USE_WIN32_LDAP) ludp->lud_attrs = calloc(count + 1, sizeof(TCHAR *)); #else ludp->lud_attrs = calloc(count + 1, sizeof(char *)); #endif if(!ludp->lud_attrs) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } for(i = 0; i < count; i++) { char *unescaped; CURLcode result; LDAP_TRACE(("attr[%d] '%s'\n", i, attributes[i])); /* Unescape the attribute */ result = Curl_urldecode(conn->data, attributes[i], 0, &unescaped, NULL, FALSE); if(result) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_attrs[i] = Curl_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ Curl_unicodefree(unescaped); if(!ludp->lud_attrs[i]) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_attrs[i] = unescaped; #endif ludp->lud_attrs_dups++; } free(attributes); } p = q; if(!p) goto quit; /* Parse the scope. skip "??" */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { ludp->lud_scope = str2scope(p); if(ludp->lud_scope == -1) { rc = LDAP_INVALID_SYNTAX; goto quit; } LDAP_TRACE(("scope %d\n", ludp->lud_scope)); } p = q; if(!p) goto quit; /* Parse the filter */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { char *filter = p; char *unescaped; CURLcode result; LDAP_TRACE(("filter '%s'\n", filter)); /* Unescape the filter */ result = Curl_urldecode(conn->data, filter, 0, &unescaped, NULL, FALSE); if(result) { rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_filter = Curl_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ Curl_unicodefree(unescaped); if(!ludp->lud_filter) { rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_filter = unescaped; #endif } p = q; if(p && !*p) { rc = LDAP_INVALID_SYNTAX; goto quit; } quit: free(path); free(query); return rc; } static int _ldap_url_parse(const struct connectdata *conn, LDAPURLDesc **ludpp) { LDAPURLDesc *ludp = calloc(1, sizeof(*ludp)); int rc; *ludpp = NULL; if(!ludp) return LDAP_NO_MEMORY; rc = _ldap_url_parse2(conn, ludp); if(rc != LDAP_SUCCESS) { _ldap_free_urldesc(ludp); ludp = NULL; } *ludpp = ludp; return (rc); } static void _ldap_free_urldesc(LDAPURLDesc *ludp) { if(!ludp) return; free(ludp->lud_dn); free(ludp->lud_filter); if(ludp->lud_attrs) { size_t i; for(i = 0; i < ludp->lud_attrs_dups; i++) free(ludp->lud_attrs[i]); free(ludp->lud_attrs); } free(ludp); } #endif /* !HAVE_LDAP_URL_PARSE */ #endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */
YifuLiu/AliOS-Things
components/curl/lib/ldap.c
C
apache-2.0
28,761
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "llist.h" #include "curl_memory.h" /* this must be the last include file */ #include "memdebug.h" /* * @unittest: 1300 */ void Curl_llist_init(struct curl_llist *l, curl_llist_dtor dtor) { l->size = 0; l->dtor = dtor; l->head = NULL; l->tail = NULL; } /* * Curl_llist_insert_next() * * Inserts a new list element after the given one 'e'. If the given existing * entry is NULL and the list already has elements, the new one will be * inserted first in the list. * * The 'ne' argument should be a pointer into the object to store. * * @unittest: 1300 */ void Curl_llist_insert_next(struct curl_llist *list, struct curl_llist_element *e, const void *p, struct curl_llist_element *ne) { ne->ptr = (void *) p; if(list->size == 0) { list->head = ne; list->head->prev = NULL; list->head->next = NULL; list->tail = ne; } else { /* if 'e' is NULL here, we insert the new element first in the list */ ne->next = e?e->next:list->head; ne->prev = e; if(!e) { list->head->prev = ne; list->head = ne; } else if(e->next) { e->next->prev = ne; } else { list->tail = ne; } if(e) e->next = ne; } ++list->size; } /* * @unittest: 1300 */ void Curl_llist_remove(struct curl_llist *list, struct curl_llist_element *e, void *user) { void *ptr; if(e == NULL || list->size == 0) return; if(e == list->head) { list->head = e->next; if(list->head == NULL) list->tail = NULL; else e->next->prev = NULL; } else { if(!e->prev) list->head = e->next; else e->prev->next = e->next; if(!e->next) list->tail = e->prev; else e->next->prev = e->prev; } ptr = e->ptr; e->ptr = NULL; e->prev = NULL; e->next = NULL; --list->size; /* call the dtor() last for when it actually frees the 'e' memory itself */ if(list->dtor) list->dtor(user, ptr); } void Curl_llist_destroy(struct curl_llist *list, void *user) { if(list) { while(list->size > 0) Curl_llist_remove(list, list->tail, user); } } size_t Curl_llist_count(struct curl_llist *list) { return list->size; } /* * @unittest: 1300 */ void Curl_llist_move(struct curl_llist *list, struct curl_llist_element *e, struct curl_llist *to_list, struct curl_llist_element *to_e) { /* Remove element from list */ if(e == NULL || list->size == 0) return; if(e == list->head) { list->head = e->next; if(list->head == NULL) list->tail = NULL; else e->next->prev = NULL; } else { e->prev->next = e->next; if(!e->next) list->tail = e->prev; else e->next->prev = e->prev; } --list->size; /* Add element to to_list after to_e */ if(to_list->size == 0) { to_list->head = e; to_list->head->prev = NULL; to_list->head->next = NULL; to_list->tail = e; } else { e->next = to_e->next; e->prev = to_e; if(to_e->next) { to_e->next->prev = e; } else { to_list->tail = e; } to_e->next = e; } ++to_list->size; }
YifuLiu/AliOS-Things
components/curl/lib/llist.c
C
apache-2.0
4,279
#ifndef HEADER_CURL_LLIST_H #define HEADER_CURL_LLIST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <stddef.h> typedef void (*curl_llist_dtor)(void *, void *); struct curl_llist_element { void *ptr; struct curl_llist_element *prev; struct curl_llist_element *next; }; struct curl_llist { struct curl_llist_element *head; struct curl_llist_element *tail; curl_llist_dtor dtor; size_t size; }; void Curl_llist_init(struct curl_llist *, curl_llist_dtor); void Curl_llist_insert_next(struct curl_llist *, struct curl_llist_element *, const void *, struct curl_llist_element *node); void Curl_llist_remove(struct curl_llist *, struct curl_llist_element *, void *); size_t Curl_llist_count(struct curl_llist *); void Curl_llist_destroy(struct curl_llist *, void *); void Curl_llist_move(struct curl_llist *, struct curl_llist_element *, struct curl_llist *, struct curl_llist_element *); #endif /* HEADER_CURL_LLIST_H */
YifuLiu/AliOS-Things
components/curl/lib/llist.h
C
apache-2.0
2,022
/* * !checksrc! disable COPYRIGHT * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD4 Message-Digest Algorithm (RFC 1320). * * Homepage: https://openwall.info/wiki/people/solar/software/public-domain-source-code/md4 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. In case * this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2001 * Alexander Peslyak and it is hereby released to the general public under the * following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #include "curl_setup.h" /* The NSS, OS/400, and when not included, OpenSSL and mbed TLS crypto * libraries do not provide the MD4 hash algorithm, so we use this * implementation of it */ #if defined(USE_NSS) || defined(USE_OS400CRYPTO) || \ (defined(USE_OPENSSL) && defined(OPENSSL_NO_MD4)) || \ (defined(USE_MBEDTLS) && !defined(MBEDTLS_MD4_C)) #include "curl_md4.h" #include "warnless.h" #ifndef HAVE_OPENSSL #include <string.h> /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD4_u32plus; typedef struct { MD4_u32plus lo, hi; MD4_u32plus a, b, c, d; unsigned char buffer[64]; MD4_u32plus block[16]; } MD4_CTX; static void MD4_Init(MD4_CTX *ctx); static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size); static void MD4_Final(unsigned char *result, MD4_CTX *ctx); /* * The basic MD4 functions. * * F and G are optimized compared to their RFC 1320 definitions, with the * optimization for F borrowed from Colin Plumb's MD5 implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) (((x) & ((y) | (z))) | ((y) & (z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) /* * The MD4 transformation for all three rounds. */ #define STEP(f, a, b, c, d, x, s) \ (a) += f((b), (c), (d)) + (x); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD4_u32plus *)(void *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD4_u32plus)ptr[(n) * 4] | \ ((MD4_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD4_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD4_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static const void *body(MD4_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD4_u32plus a, b, c, d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { MD4_u32plus saved_a, saved_b, saved_c, saved_d; saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 3) STEP(F, d, a, b, c, SET(1), 7) STEP(F, c, d, a, b, SET(2), 11) STEP(F, b, c, d, a, SET(3), 19) STEP(F, a, b, c, d, SET(4), 3) STEP(F, d, a, b, c, SET(5), 7) STEP(F, c, d, a, b, SET(6), 11) STEP(F, b, c, d, a, SET(7), 19) STEP(F, a, b, c, d, SET(8), 3) STEP(F, d, a, b, c, SET(9), 7) STEP(F, c, d, a, b, SET(10), 11) STEP(F, b, c, d, a, SET(11), 19) STEP(F, a, b, c, d, SET(12), 3) STEP(F, d, a, b, c, SET(13), 7) STEP(F, c, d, a, b, SET(14), 11) STEP(F, b, c, d, a, SET(15), 19) /* Round 2 */ STEP(G, a, b, c, d, GET(0) + 0x5a827999, 3) STEP(G, d, a, b, c, GET(4) + 0x5a827999, 5) STEP(G, c, d, a, b, GET(8) + 0x5a827999, 9) STEP(G, b, c, d, a, GET(12) + 0x5a827999, 13) STEP(G, a, b, c, d, GET(1) + 0x5a827999, 3) STEP(G, d, a, b, c, GET(5) + 0x5a827999, 5) STEP(G, c, d, a, b, GET(9) + 0x5a827999, 9) STEP(G, b, c, d, a, GET(13) + 0x5a827999, 13) STEP(G, a, b, c, d, GET(2) + 0x5a827999, 3) STEP(G, d, a, b, c, GET(6) + 0x5a827999, 5) STEP(G, c, d, a, b, GET(10) + 0x5a827999, 9) STEP(G, b, c, d, a, GET(14) + 0x5a827999, 13) STEP(G, a, b, c, d, GET(3) + 0x5a827999, 3) STEP(G, d, a, b, c, GET(7) + 0x5a827999, 5) STEP(G, c, d, a, b, GET(11) + 0x5a827999, 9) STEP(G, b, c, d, a, GET(15) + 0x5a827999, 13) /* Round 3 */ STEP(H, a, b, c, d, GET(0) + 0x6ed9eba1, 3) STEP(H, d, a, b, c, GET(8) + 0x6ed9eba1, 9) STEP(H, c, d, a, b, GET(4) + 0x6ed9eba1, 11) STEP(H, b, c, d, a, GET(12) + 0x6ed9eba1, 15) STEP(H, a, b, c, d, GET(2) + 0x6ed9eba1, 3) STEP(H, d, a, b, c, GET(10) + 0x6ed9eba1, 9) STEP(H, c, d, a, b, GET(6) + 0x6ed9eba1, 11) STEP(H, b, c, d, a, GET(14) + 0x6ed9eba1, 15) STEP(H, a, b, c, d, GET(1) + 0x6ed9eba1, 3) STEP(H, d, a, b, c, GET(9) + 0x6ed9eba1, 9) STEP(H, c, d, a, b, GET(5) + 0x6ed9eba1, 11) STEP(H, b, c, d, a, GET(13) + 0x6ed9eba1, 15) STEP(H, a, b, c, d, GET(3) + 0x6ed9eba1, 3) STEP(H, d, a, b, c, GET(11) + 0x6ed9eba1, 9) STEP(H, c, d, a, b, GET(7) + 0x6ed9eba1, 11) STEP(H, b, c, d, a, GET(15) + 0x6ed9eba1, 15) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while(size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } static void MD4_Init(MD4_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } static void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size) { MD4_u32plus saved_lo; unsigned long used; saved_lo = ctx->lo; ctx->lo = (saved_lo + size) & 0x1fffffff; if(ctx->lo < saved_lo) ctx->hi++; ctx->hi += (MD4_u32plus)size >> 29; used = saved_lo & 0x3f; if(used) { unsigned long available = 64 - used; if(size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if(size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } static void MD4_Final(unsigned char *result, MD4_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if(available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); ctx->buffer[59] = curlx_ultouc((ctx->lo >> 24)&0xff); ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); body(ctx, ctx->buffer, 64); result[0] = curlx_ultouc((ctx->a)&0xff); result[1] = curlx_ultouc((ctx->a >> 8)&0xff); result[2] = curlx_ultouc((ctx->a >> 16)&0xff); result[3] = curlx_ultouc(ctx->a >> 24); result[4] = curlx_ultouc((ctx->b)&0xff); result[5] = curlx_ultouc((ctx->b >> 8)&0xff); result[6] = curlx_ultouc((ctx->b >> 16)&0xff); result[7] = curlx_ultouc(ctx->b >> 24); result[8] = curlx_ultouc((ctx->c)&0xff); result[9] = curlx_ultouc((ctx->c >> 8)&0xff); result[10] = curlx_ultouc((ctx->c >> 16)&0xff); result[11] = curlx_ultouc(ctx->c >> 24); result[12] = curlx_ultouc((ctx->d)&0xff); result[13] = curlx_ultouc((ctx->d >> 8)&0xff); result[14] = curlx_ultouc((ctx->d >> 16)&0xff); result[15] = curlx_ultouc(ctx->d >> 24); memset(ctx, 0, sizeof(*ctx)); } #endif void Curl_md4it(unsigned char *output, const unsigned char *input, size_t len) { MD4_CTX ctx; MD4_Init(&ctx); MD4_Update(&ctx, input, curlx_uztoui(len)); MD4_Final(output, &ctx); } #endif /* defined(USE_NSS) || defined(USE_OS400CRYPTO) || (defined(USE_OPENSSL) && defined(OPENSSL_NO_MD4)) || (defined(USE_MBEDTLS) && !defined(MBEDTLS_MD4_C)) */
YifuLiu/AliOS-Things
components/curl/lib/md4.c
C
apache-2.0
9,572
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_CRYPTO_AUTH #include <curl/curl.h> #include "curl_md5.h" #include "curl_hmac.h" #include "warnless.h" #if defined(USE_GNUTLS_NETTLE) #include <nettle/md5.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef struct md5_ctx MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { md5_init(ctx); } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { md5_update(ctx, inputLen, input); } static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { md5_digest(ctx, 16, digest); } #elif defined(USE_GNUTLS) #include <gcrypt.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef gcry_md_hd_t MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { gcry_md_open(ctx, GCRY_MD_MD5, 0); } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { gcry_md_write(*ctx, input, inputLen); } static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { memcpy(digest, gcry_md_read(*ctx, 0), 16); gcry_md_close(*ctx); } #elif defined(USE_OPENSSL) && !defined(USE_AMISSL) /* When OpenSSL is available we use the MD5-function from OpenSSL */ #include <openssl/md5.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #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)) /* For Apple operating systems: CommonCrypto has the functions we need. These functions are available on Tiger and later, as well as iOS 2.0 and later. If you're building for an older cat, well, sorry. Declaring the functions as static like this seems to be a bit more reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */ # include <CommonCrypto/CommonDigest.h> # define MD5_CTX CC_MD5_CTX #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" static void MD5_Init(MD5_CTX *ctx) { CC_MD5_Init(ctx); } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { CC_MD5_Update(ctx, input, inputLen); } static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { CC_MD5_Final(digest, ctx); } #elif defined(WIN32) && !defined(CURL_WINDOWS_APP) #include <wincrypt.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef struct { HCRYPTPROV hCryptProv; HCRYPTHASH hHash; } MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash); } } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0); } static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) { unsigned long length = 0; CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); if(length == 16) CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); if(ctx->hHash) CryptDestroyHash(ctx->hHash); if(ctx->hCryptProv) CryptReleaseContext(ctx->hCryptProv, 0); } #else /* When no other crypto library is available we use this code segment */ /* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #include <string.h> /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; static void MD5_Init(MD5_CTX *ctx); static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); static void MD5_Final(unsigned char *result, MD5_CTX *ctx); /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)(void *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD5_u32plus a, b, c, d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { MD5_u32plus saved_a, saved_b, saved_c, saved_d; saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while(size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } static void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used; saved_lo = ctx->lo; ctx->lo = (saved_lo + size) & 0x1fffffff; if(ctx->lo < saved_lo) ctx->hi++; ctx->hi += (MD5_u32plus)size >> 29; used = saved_lo & 0x3f; if(used) { unsigned long available = 64 - used; if(size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if(size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } static void MD5_Final(unsigned char *result, MD5_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if(available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); ctx->buffer[59] = curlx_ultouc(ctx->lo >> 24); ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); body(ctx, ctx->buffer, 64); result[0] = curlx_ultouc((ctx->a)&0xff); result[1] = curlx_ultouc((ctx->a >> 8)&0xff); result[2] = curlx_ultouc((ctx->a >> 16)&0xff); result[3] = curlx_ultouc(ctx->a >> 24); result[4] = curlx_ultouc((ctx->b)&0xff); result[5] = curlx_ultouc((ctx->b >> 8)&0xff); result[6] = curlx_ultouc((ctx->b >> 16)&0xff); result[7] = curlx_ultouc(ctx->b >> 24); result[8] = curlx_ultouc((ctx->c)&0xff); result[9] = curlx_ultouc((ctx->c >> 8)&0xff); result[10] = curlx_ultouc((ctx->c >> 16)&0xff); result[11] = curlx_ultouc(ctx->c >> 24); result[12] = curlx_ultouc((ctx->d)&0xff); result[13] = curlx_ultouc((ctx->d >> 8)&0xff); result[14] = curlx_ultouc((ctx->d >> 16)&0xff); result[15] = curlx_ultouc(ctx->d >> 24); memset(ctx, 0, sizeof(*ctx)); } #endif /* CRYPTO LIBS */ const HMAC_params Curl_HMAC_MD5[] = { { /* Hash initialization function. */ CURLX_FUNCTION_CAST(HMAC_hinit_func, MD5_Init), /* Hash update function. */ CURLX_FUNCTION_CAST(HMAC_hupdate_func, MD5_Update), /* Hash computation end function. */ CURLX_FUNCTION_CAST(HMAC_hfinal_func, MD5_Final), /* Size of hash context structure. */ sizeof(MD5_CTX), /* Maximum key length. */ 64, /* Result size. */ 16 } }; const MD5_params Curl_DIGEST_MD5[] = { { /* Digest initialization function */ CURLX_FUNCTION_CAST(Curl_MD5_init_func, MD5_Init), /* Digest update function */ CURLX_FUNCTION_CAST(Curl_MD5_update_func, MD5_Update), /* Digest computation end function */ CURLX_FUNCTION_CAST(Curl_MD5_final_func, MD5_Final), /* Size of digest context struct */ sizeof(MD5_CTX), /* Result size */ 16 } }; /* * @unittest: 1601 */ void Curl_md5it(unsigned char *outbuffer, /* 16 bytes */ const unsigned char *input) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, input, curlx_uztoui(strlen((char *)input))); MD5_Final(outbuffer, &ctx); } MD5_context *Curl_MD5_init(const MD5_params *md5params) { MD5_context *ctxt; /* Create MD5 context */ ctxt = malloc(sizeof(*ctxt)); if(!ctxt) return ctxt; ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize); if(!ctxt->md5_hashctx) { free(ctxt); return NULL; } ctxt->md5_hash = md5params; (*md5params->md5_init_func)(ctxt->md5_hashctx); return ctxt; } CURLcode Curl_MD5_update(MD5_context *context, const unsigned char *data, unsigned int len) { (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len); return CURLE_OK; } CURLcode Curl_MD5_final(MD5_context *context, unsigned char *result) { (*context->md5_hash->md5_final_func)(result, context->md5_hashctx); free(context->md5_hashctx); free(context); return CURLE_OK; } #endif /* CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/md5.c
C
apache-2.0
16,661
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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" /* * Until 2011-08-17 libcurl's Memory Tracking feature also performed * automatic malloc and free filling operations using 0xA5 and 0x13 * values. Our own preinitialization of dynamically allocated memory * might be useful when not using third party memory debuggers, but * on the other hand this would fool memory debuggers into thinking * that all dynamically allocated memory is properly initialized. * * As a default setting, libcurl's Memory Tracking feature no longer * performs preinitialization of dynamically allocated memory on its * own. If you know what you are doing, and really want to retain old * behavior, you can achieve this compiling with preprocessor symbols * CURL_MT_MALLOC_FILL and CURL_MT_FREE_FILL defined with appropriate * values. */ #ifdef CURL_MT_MALLOC_FILL # if (CURL_MT_MALLOC_FILL < 0) || (CURL_MT_MALLOC_FILL > 0xff) # error "invalid CURL_MT_MALLOC_FILL or out of range" # endif #endif #ifdef CURL_MT_FREE_FILL # if (CURL_MT_FREE_FILL < 0) || (CURL_MT_FREE_FILL > 0xff) # error "invalid CURL_MT_FREE_FILL or out of range" # endif #endif #if defined(CURL_MT_MALLOC_FILL) && defined(CURL_MT_FREE_FILL) # if (CURL_MT_MALLOC_FILL == CURL_MT_FREE_FILL) # error "CURL_MT_MALLOC_FILL same as CURL_MT_FREE_FILL" # endif #endif #ifdef CURL_MT_MALLOC_FILL # define mt_malloc_fill(buf,len) memset((buf), CURL_MT_MALLOC_FILL, (len)) #else # define mt_malloc_fill(buf,len) Curl_nop_stmt #endif #ifdef CURL_MT_FREE_FILL # define mt_free_fill(buf,len) memset((buf), CURL_MT_FREE_FILL, (len)) #else # define mt_free_fill(buf,len) Curl_nop_stmt #endif 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 memlimit = FALSE; /* enable memory limit */ static long memsize = 0; /* set number of mallocs allowed */ /* 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 } } /* 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) { if(source) { /* 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) { /* fill memory with junk */ mt_malloc_fill(mem->mem, wantedsize); 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 /* destroy */ mt_free_fill(mem->mem, mem->size); /* free for real */ (Curl_cfree)(mem); } if(source) 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; } 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 */
YifuLiu/AliOS-Things
components/curl/lib/memdebug.c
C
apache-2.0
13,374
#ifndef HEADER_CURL_MEMDEBUG_H #define HEADER_CURL_MEMDEBUG_H #ifdef CURLDEBUG /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * 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 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_FALSE #endif /* HEADER_CURL_MEMDEBUG_H */
YifuLiu/AliOS-Things
components/curl/lib/memdebug.h
C
apache-2.0
6,934
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "mime.h" #include "non-ascii.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) /* 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 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 == NULL) return 0; count = 0; ret_stat = 1; while(ret_stat > 0) { ret_stat = fread(buffer, 1, sizeof(buffer), file); if(ret_stat != 0) 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(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(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, curl_mimepart *part) { mime_encoder_state *st = &part->encstate; size_t insize = st->bufend - st->bufbeg; (void) ateof; if(size > insize) size = insize; if(size) memcpy(buffer, st->buf, 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) { mime_encoder_state *st = &part->encstate; size_t cursize = st->bufend - st->bufbeg; (void) ateof; 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) { 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) 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 || 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 && size >= 4) { /* Buffered data size can only be 0, 1 or 2. */ ptr[2] = ptr[3] = '='; i = 0; switch(st->bufend - st->bufbeg) { case 2: i = (st->buf[st->bufbeg + 1] & 0xFF) << 8; /* FALLTHROUGH */ case 1: 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; break; } } #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(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) { 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; break; 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) 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 = (size_t) part->datasize - part->state.offset; (void) size; /* Always 1.*/ if(sz > nitems) sz = nitems; if(sz) memcpy(buffer, (char *) &part->data[part->state.offset], sz); 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 = (size_t) 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(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(mime_state *state, char *buffer, size_t bufsize, const char *bytes, size_t numbytes, const char *trail) { size_t sz; if(numbytes > state->offset) { sz = numbytes - state->offset; bytes += state->offset; } else { size_t tsz = strlen(trail); sz = state->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) { size_t sz = 0; if(part->readfunc) sz = part->readfunc(buffer, 1, bufsize, part->arg); return sz; } /* Read and encode part content. */ static size_t read_encoded_part_content(curl_mimepart *part, char *buffer, size_t bufsize) { mime_encoder_state *st = &part->encstate; size_t cursize = 0; size_t sz; bool ateof = FALSE; while(bufsize) { 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 CURL_READFUNC_ABORT: case CURL_READFUNC_PAUSE: case READ_ERROR: 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); switch(sz) { case 0: ateof = TRUE; break; case CURL_READFUNC_ABORT: case CURL_READFUNC_PAUSE: case READ_ERROR: return cursize? cursize: sz; default: st->bufend += sz; break; } } return cursize; } /* Readback a mime part. */ static size_t readback_part(curl_mimepart *part, char *buffer, size_t bufsize) { 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); else sz = read_part_content(part, buffer, bufsize); 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: 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. */ static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems, void *instream) { 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 CRLK. 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); switch(sz) { case CURL_READFUNC_ABORT: case CURL_READFUNC_PAUSE: case READ_ERROR: 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); 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; } 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; /* 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); } } /* Duplicate other fields. */ if(dst != NULL) dst->encoder = src->encoder; else res = CURLE_WRITE_ERROR; if(!res) 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 && dst) 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; 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 nul terminator as sentinel. */ part->readfunc = mime_mem_read; part->seekfunc = mime_mem_seek; part->freefunc = mime_mem_free; 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 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; part->readfunc = mime_subparts_read; 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; (void) size; /* Always 1. */ return readback_part(part, buffer, nitems); } /* 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; } 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 && strcasecompare(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(strcasecompare(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; } #else /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */ /* Mime not compiled in: define stubs for externally-referenced functions. */ curl_mime *curl_mime_init(CURL *easy) { (void) easy; return NULL; } void curl_mime_free(curl_mime *mime) { (void) mime; } curl_mimepart *curl_mime_addpart(curl_mime *mime) { (void) mime; return NULL; } CURLcode curl_mime_name(curl_mimepart *part, const char *name) { (void) part; (void) name; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_filename(curl_mimepart *part, const char *filename) { (void) part; (void) filename; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype) { (void) part; (void) mimetype; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding) { (void) part; (void) encoding; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize) { (void) part; (void) data; (void) datasize; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename) { (void) part; (void) filename; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize, curl_read_callback readfunc, curl_seek_callback seekfunc, curl_free_callback freefunc, void *arg) { (void) part; (void) datasize; (void) readfunc; (void) seekfunc; (void) freefunc; (void) arg; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts) { (void) part; (void) subparts; return CURLE_NOT_BUILT_IN; } CURLcode curl_mime_headers(curl_mimepart *part, struct curl_slist *headers, int take_ownership) { (void) part; (void) headers; (void) take_ownership; return CURLE_NOT_BUILT_IN; } #endif /* if disabled */
YifuLiu/AliOS-Things
components/curl/lib/mime.c
C
apache-2.0
51,009
#ifndef HEADER_CURL_MIME_H #define HEADER_CURL_MIME_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 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. */ typedef struct { 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. */ } mime_encoder; /* Content transfer encoder state. */ typedef struct { 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_encoder_state; /* Mime readback state. */ typedef struct { enum mimestate state; /* Current state token. */ void *ptr; /* State-dependent pointer. */ size_t offset; /* State-dependent offset. */ } mime_state; /* minimum buffer size for the boundary string */ #define MIME_BOUNDARY_LEN (24 + MIME_RAND_BOUNDARY_CHARS + 1) /* A mime multipart. */ struct curl_mime_s { 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. */ mime_state state; /* Current readback state. */ }; /* A mime part. */ struct curl_mimepart_s { 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. */ 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. */ unsigned int flags; /* Flags. */ mime_state state; /* Current readback state. */ const mime_encoder *encoder; /* Content data encoder. */ mime_encoder_state encstate; /* Data encoder state. */ }; #if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)) || \ !defined(CURL_DISABLE_SMTP) || !defined(CURL_DISABLE_IMAP) /* Prototypes. */ void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy); void Curl_mime_cleanpart(curl_mimepart *part); CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src); CURLcode Curl_mime_set_subparts(curl_mimepart *part, curl_mime *subparts, int take_ownership); CURLcode Curl_mime_prepare_headers(curl_mimepart *part, const char *contenttype, const char *disposition, enum mimestrategy strategy); curl_off_t Curl_mime_size(curl_mimepart *part); size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream); CURLcode Curl_mime_rewind(curl_mimepart *part); CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...); const char *Curl_mime_contenttype(const char *filename); #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_add_header(x,y,...) CURLE_NOT_BUILT_IN #endif #endif /* HEADER_CURL_MIME_H */
YifuLiu/AliOS-Things
components/curl/lib/mime.h
C
apache-2.0
6,990
#!/usr/bin/env perl # *************************************************************************** # * _ _ ____ _ # * Project ___| | | | _ \| | # * / __| | | | |_) | | # * | (__| |_| | _ <| |___ # * \___|\___/|_| \_\_____| # * # * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. # * # * This software is licensed as described in the file COPYING, which # * you should have received as part of this distribution. The terms # * are also available at https://curl.haxx.se/docs/copyright.html. # * # * You may opt to use, copy, modify, merge, publish, distribute and/or sell # * copies of the Software, and permit persons to whom the Software is # * furnished to do so, under the terms of the COPYING file. # * # * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # * KIND, either express or implied. # * # *************************************************************************** # This Perl script creates a fresh ca-bundle.crt file for use with libcurl. # It downloads certdata.txt from Mozilla's source tree (see URL below), # then parses certdata.txt and extracts CA Root Certificates into PEM format. # These are then processed with the OpenSSL commandline tool to produce the # final ca-bundle.crt file. # The script is based on the parse-certs script written by Roland Krikava. # This Perl script works on almost any platform since its only external # dependency is the OpenSSL commandline tool for optional text listing. # Hacked by Guenter Knauf. # use Encode; use Getopt::Std; use MIME::Base64; use strict; use warnings; use vars qw($opt_b $opt_d $opt_f $opt_h $opt_i $opt_k $opt_l $opt_m $opt_n $opt_p $opt_q $opt_s $opt_t $opt_u $opt_v $opt_w); use List::Util; use Text::Wrap; my $MOD_SHA = "Digest::SHA"; eval "require $MOD_SHA"; if ($@) { $MOD_SHA = "Digest::SHA::PurePerl"; eval "require $MOD_SHA"; } eval "require LWP::UserAgent"; my %urls = ( 'nss' => 'https://hg.mozilla.org/projects/nss/raw-file/default/lib/ckfw/builtins/certdata.txt', 'central' => 'https://hg.mozilla.org/mozilla-central/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt', 'beta' => 'https://hg.mozilla.org/releases/mozilla-beta/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt', 'release' => 'https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt', ); $opt_d = 'release'; # If the OpenSSL commandline is not in search path you can configure it here! my $openssl = 'openssl'; my $version = '1.27'; $opt_w = 76; # default base64 encoded lines length # default cert types to include in the output (default is to include CAs which may issue SSL server certs) my $default_mozilla_trust_purposes = "SERVER_AUTH"; my $default_mozilla_trust_levels = "TRUSTED_DELEGATOR"; $opt_p = $default_mozilla_trust_purposes . ":" . $default_mozilla_trust_levels; my @valid_mozilla_trust_purposes = ( "DIGITAL_SIGNATURE", "NON_REPUDIATION", "KEY_ENCIPHERMENT", "DATA_ENCIPHERMENT", "KEY_AGREEMENT", "KEY_CERT_SIGN", "CRL_SIGN", "SERVER_AUTH", "CLIENT_AUTH", "CODE_SIGNING", "EMAIL_PROTECTION", "IPSEC_END_SYSTEM", "IPSEC_TUNNEL", "IPSEC_USER", "TIME_STAMPING", "STEP_UP_APPROVED" ); my @valid_mozilla_trust_levels = ( "TRUSTED_DELEGATOR", # CAs "NOT_TRUSTED", # Don't trust these certs. "MUST_VERIFY_TRUST", # This explicitly tells us that it ISN'T a CA but is otherwise ok. In other words, this should tell the app to ignore any other sources that claim this is a CA. "TRUSTED" # This cert is trusted, but only for itself and not for delegates (i.e. it is not a CA). ); my $default_signature_algorithms = $opt_s = "MD5"; my @valid_signature_algorithms = ( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" ); $0 =~ s@.*(/|\\)@@; $Getopt::Std::STANDARD_HELP_VERSION = 1; getopts('bd:fhiklmnp:qs:tuvw:'); if(!defined($opt_d)) { # to make plain "-d" use not cause warnings, and actually still work $opt_d = 'release'; } # Use predefined URL or else custom URL specified on command line. my $url; if(defined($urls{$opt_d})) { $url = $urls{$opt_d}; if(!$opt_k && $url !~ /^https:\/\//i) { die "The URL for '$opt_d' is not HTTPS. Use -k to override (insecure).\n"; } } else { $url = $opt_d; } my $curl = `curl -V`; if ($opt_i) { print ("=" x 78 . "\n"); print "Script Version : $version\n"; print "Perl Version : $]\n"; print "Operating System Name : $^O\n"; print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n"; print "Encode::Encoding.pm Version : ${Encode::Encoding::VERSION}\n"; print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n"; print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n" if($LWP::UserAgent::VERSION); print "LWP.pm Version : ${LWP::VERSION}\n" if($LWP::VERSION); print "Digest::SHA.pm Version : ${Digest::SHA::VERSION}\n" if ($Digest::SHA::VERSION); print "Digest::SHA::PurePerl.pm Version : ${Digest::SHA::PurePerl::VERSION}\n" if ($Digest::SHA::PurePerl::VERSION); print ("=" x 78 . "\n"); } sub warning_message() { if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit print "Warning: Use of this script may pose some risk:\n"; print "\n"; print " 1) If you use HTTP URLs they are subject to a man in the middle attack\n"; print " 2) Default to 'release', but more recent updates may be found in other trees\n"; print " 3) certdata.txt file format may change, lag time to update this script\n"; print " 4) Generally unwise to blindly trust CAs without manual review & verification\n"; print " 5) Mozilla apps use additional security checks aren't represented in certdata\n"; print " 6) Use of this script will make a security engineer grind his teeth and\n"; print " swear at you. ;)\n"; exit; } else { # Short Form Warning print "Warning: Use of this script may pose some risk, -d risk for more details.\n"; } } sub HELP_MESSAGE() { print "Usage:\t${0} [-b] [-d<certdata>] [-f] [-i] [-k] [-l] [-n] [-p<purposes:levels>] [-q] [-s<algorithms>] [-t] [-u] [-v] [-w<l>] [<outputfile>]\n"; print "\t-b\tbackup an existing version of ca-bundle.crt\n"; print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n"; print "\t\t Valid names are:\n"; print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n"; print "\t-f\tforce rebuild even if certdata.txt is current\n"; print "\t-i\tprint version info about used modules\n"; print "\t-k\tallow URLs other than HTTPS, enable HTTP fallback (insecure)\n"; print "\t-l\tprint license info about certdata.txt\n"; print "\t-m\tinclude meta data in output\n"; print "\t-n\tno download of certdata.txt (to use existing)\n"; print wrap("\t","\t\t", "-p\tlist of Mozilla trust purposes and levels for certificates to include in output. Takes the form of a comma separated list of purposes, a colon, and a comma separated list of levels. (default: $default_mozilla_trust_purposes:$default_mozilla_trust_levels)"), "\n"; print "\t\t Valid purposes are:\n"; print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n"; print "\t\t Valid levels are:\n"; print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n"; print "\t-q\tbe really quiet (no progress output at all)\n"; print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n"); print "\t\t Valid signature algorithms are:\n"; print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n"; print "\t-t\tinclude plain text listing of certificates\n"; print "\t-u\tunlink (remove) certdata.txt after processing\n"; print "\t-v\tbe verbose and print out processed CAs\n"; print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n"; exit; } sub VERSION_MESSAGE() { print "${0} version ${version} running Perl ${]} on ${^O}\n"; } warning_message() unless ($opt_q || $url =~ m/^(ht|f)tps:/i ); HELP_MESSAGE() if ($opt_h); sub report($@) { my $output = shift; print STDERR $output . "\n" unless $opt_q; } sub is_in_list($@) { my $target = shift; return defined(List::Util::first { $target eq $_ } @_); } # Parses $param_string as a case insensitive comma separated list with optional whitespace # validates that only allowed parameters are supplied sub parse_csv_param($$@) { my $description = shift; my $param_string = shift; my @valid_values = @_; my @values = map { s/^\s+//; # strip leading spaces s/\s+$//; # strip trailing spaces uc $_ # return the modified string as upper case } split( ',', $param_string ); # Find all values which are not in the list of valid values or "ALL" my @invalid = grep { !is_in_list($_,"ALL",@valid_values) } @values; if ( scalar(@invalid) > 0 ) { # Tell the user which parameters were invalid and print the standard help message which will exit print "Error: Invalid ", $description, scalar(@invalid) == 1 ? ": " : "s: ", join( ", ", map { "\"$_\"" } @invalid ), "\n"; HELP_MESSAGE(); } @values = @valid_values if ( is_in_list("ALL",@values) ); return @values; } sub sha256 { my $result; if ($Digest::SHA::VERSION || $Digest::SHA::PurePerl::VERSION) { open(FILE, $_[0]) or die "Can't open '$_[0]': $!"; binmode(FILE); $result = $MOD_SHA->new(256)->addfile(*FILE)->hexdigest; close(FILE); } else { # Use OpenSSL command if Perl Digest::SHA modules not available $result = `"$openssl" dgst -r -sha256 "$_[0]"`; $result =~ s/^([0-9a-f]{64}) .+/$1/is; } return $result; } sub oldhash { my $hash = ""; open(C, "<$_[0]") || return 0; while(<C>) { chomp; if($_ =~ /^\#\# SHA256: (.*)/) { $hash = $1; last; } } close(C); return $hash; } if ( $opt_p !~ m/:/ ) { print "Error: Mozilla trust identifier list must include both purposes and levels\n"; HELP_MESSAGE(); } (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p ); my @included_mozilla_trust_purposes = parse_csv_param( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes ); my @included_mozilla_trust_levels = parse_csv_param( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels ); my @included_signature_algorithms = parse_csv_param( "signature algorithm", $opt_s, @valid_signature_algorithms ); sub should_output_cert(%) { my %trust_purposes_by_level = @_; foreach my $level (@included_mozilla_trust_levels) { # for each level we want to output, see if any of our desired purposes are included return 1 if ( defined( List::Util::first { is_in_list( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) ); } return 0; } my $crt = $ARGV[0] || 'ca-bundle.crt'; (my $txt = $url) =~ s@(.*/|\?.*)@@g; my $stdout = $crt eq '-'; my $resp; my $fetched; my $oldhash = oldhash($crt); report "SHA256 of old file: $oldhash"; if(!$opt_n) { report "Downloading $txt ..."; # If we have an HTTPS URL then use curl if($url =~ /^https:\/\//i) { if($curl) { if($curl =~ /^Protocols:.* https( |$)/m) { report "Get certdata with curl!"; my $proto = !$opt_k ? "--proto =https" : ""; my $quiet = $opt_q ? "-s" : ""; my @out = `curl -w %{response_code} $proto $quiet -o "$txt" "$url"`; if(!$? && @out && $out[0] == 200) { $fetched = 1; report "Downloaded $txt"; } else { report "Failed downloading via HTTPS with curl"; if(-e $txt && !unlink($txt)) { report "Failed to remove '$txt': $!"; } } } else { report "curl lacks https support"; } } else { report "curl not found"; } } # If nothing was fetched then use LWP if(!$fetched) { if($url =~ /^https:\/\//i) { report "Falling back to HTTP"; $url =~ s/^https:\/\//http:\/\//i; } if(!$opt_k) { report "URLs other than HTTPS are disabled by default, to enable use -k"; exit 1; } report "Get certdata with LWP!"; if(!defined(${LWP::UserAgent::VERSION})) { report "LWP is not available (LWP::UserAgent not found)"; exit 1; } my $ua = new LWP::UserAgent(agent => "$0/$version"); $ua->env_proxy(); $resp = $ua->mirror($url, $txt); if($resp && $resp->code eq '304') { report "Not modified"; exit 0 if -e $crt && !$opt_f; } else { $fetched = 1; report "Downloaded $txt"; } if(!$resp || $resp->code !~ /^(?:200|304)$/) { report "Unable to download latest data: " . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed"); exit 1 if -e $crt || ! -r $txt; } } } my $filedate = $resp ? $resp->last_modified : (stat($txt))[9]; my $datesrc = "as of"; if(!$filedate) { # mxr.mozilla.org gave us a time, hg.mozilla.org does not! $filedate = time(); $datesrc="downloaded on"; } # get the hash from the download file my $newhash= sha256($txt); if(!$opt_f && $oldhash eq $newhash) { report "Downloaded file identical to previous run\'s source file. Exiting"; if($opt_u && -e $txt && !unlink($txt)) { report "Failed to remove $txt: $!\n"; } exit; } report "SHA256 of new file: $newhash"; my $currentdate = scalar gmtime($filedate); my $format = $opt_t ? "plain text and " : ""; if( $stdout ) { open(CRT, '> -') or die "Couldn't open STDOUT: $!\n"; } else { open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n"; } print CRT <<EOT; ## ## Bundle of CA Root Certificates ## ## Certificate data from Mozilla ${datesrc}: ${currentdate} GMT ## ## This is a bundle of X.509 certificates of public Certificate Authorities ## (CA). These were automatically extracted from Mozilla's root certificates ## file (certdata.txt). This file can be found in the mozilla source tree: ## ${url} ## ## It contains the certificates in ${format}PEM format and therefore ## can be directly used with curl / libcurl / php_curl, or with ## an Apache+mod_ssl webserver for SSL client authentication. ## Just configure this file as the SSLCACertificateFile. ## ## Conversion done with mk-ca-bundle.pl version $version. ## SHA256: $newhash ## EOT report "Processing '$txt' ..."; my $caname; my $certnum = 0; my $skipnum = 0; my $start_of_cert = 0; my @precert; open(TXT,"$txt") or die "Couldn't open $txt: $!\n"; while (<TXT>) { if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) { print CRT; print if ($opt_l); while (<TXT>) { print CRT; print if ($opt_l); last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/); } } elsif(/^# (Issuer|Serial Number|Subject|Not Valid Before|Not Valid After |Fingerprint \(MD5\)|Fingerprint \(SHA1\)):/) { push @precert, $_; next; } elsif(/^#|^\s*$/) { undef @precert; next; } chomp; # this is a match for the start of a certificate if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) { $start_of_cert = 1 } if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) { $caname = $1; } my %trust_purposes_by_level; if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) { my $data; while (<TXT>) { last if (/^END/); chomp; my @octets = split(/\\/); shift @octets; for (@octets) { $data .= chr(oct); } } # scan forwards until the trust part while (<TXT>) { last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/); chomp; } # now scan the trust part to determine how we should trust this cert while (<TXT>) { last if (/^#/); if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) { if ( !is_in_list($1,@valid_mozilla_trust_purposes) ) { report "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2"; } elsif ( !is_in_list($2,@valid_mozilla_trust_levels) ) { report "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2"; } else { push @{$trust_purposes_by_level{$2}}, $1; } } } if ( !should_output_cert(%trust_purposes_by_level) ) { $skipnum ++; report "Skipping: $caname" if ($opt_v); } else { my $encoded = MIME::Base64::encode_base64($data, ''); $encoded =~ s/(.{1,${opt_w}})/$1\n/g; my $pem = "-----BEGIN CERTIFICATE-----\n" . $encoded . "-----END CERTIFICATE-----\n"; print CRT "\n$caname\n"; print CRT @precert if($opt_m); my $maxStringLength = length(decode('UTF-8', $caname, Encode::FB_CROAK | Encode::LEAVE_SRC)); if ($opt_t) { foreach my $key (keys %trust_purposes_by_level) { my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}}); $maxStringLength = List::Util::max( length($string), $maxStringLength ); print CRT $string . "\n"; } } print CRT ("=" x $maxStringLength . "\n"); if (!$opt_t) { print CRT $pem; } else { my $pipe = ""; foreach my $hash (@included_signature_algorithms) { $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM"; if (!$stdout) { $pipe .= " >> $crt.~"; close(CRT) or die "Couldn't close $crt.~: $!"; } open(TMP, $pipe) or die "Couldn't open openssl pipe: $!"; print TMP $pem; close(TMP) or die "Couldn't close openssl pipe: $!"; if (!$stdout) { open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!"; } } $pipe = "|$openssl x509 -text -inform PEM"; if (!$stdout) { $pipe .= " >> $crt.~"; close(CRT) or die "Couldn't close $crt.~: $!"; } open(TMP, $pipe) or die "Couldn't open openssl pipe: $!"; print TMP $pem; close(TMP) or die "Couldn't close openssl pipe: $!"; if (!$stdout) { open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!"; } } report "Parsing: $caname" if ($opt_v); $certnum ++; $start_of_cert = 0; } undef @precert; } } close(TXT) or die "Couldn't close $txt: $!\n"; close(CRT) or die "Couldn't close $crt.~: $!\n"; unless( $stdout ) { if ($opt_b && -e $crt) { my $bk = 1; while (-e "$crt.~${bk}~") { $bk++; } rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n"; } elsif( -e $crt ) { unlink( $crt ) or die "Failed to remove $crt: $!\n"; } rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n"; } if($opt_u && -e $txt && !unlink($txt)) { report "Failed to remove $txt: $!\n"; } report "Done ($certnum CA certs processed, $skipnum skipped).";
YifuLiu/AliOS-Things
components/curl/lib/mk-ca-bundle.pl
Perl
apache-2.0
19,351
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1999 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * * 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 <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_FALSE /* 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 */ }; typedef struct { 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; } va_stack_t; struct nsprintf { char *buffer; size_t length; size_t max; }; struct asprintf { char *buffer; /* allocated buffer */ size_t len; /* length of string */ size_t alloc; /* length of alloc */ int fail; /* (!= 0) 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)) { number *= 10; number += *input-'0'; input++; } if(number && ('$'==*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, va_stack_t *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; 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; 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; 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 + 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 */ va_stack_t vto[MAX_PARAMETERS]; char *endpos[MAX_PARAMETERS]; char **end; char work[BUFFSIZE]; va_stack_t *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-- = '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 == NULL) { /* 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; while(val >= 10.0) { val /= 10; maxprec--; } if(prec > (long)maxprec) prec = (long)maxprec-1; /* 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; 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(!infop->buffer) { infop->buffer = malloc(32); if(!infop->buffer) { infop->fail = 1; return -1; /* fail */ } infop->alloc = 32; infop->len = 0; } else if(infop->len + 1 >= infop->alloc) { char *newptr = NULL; size_t newsize = infop->alloc*2; /* detect wrap-around or other overflow problems */ if(newsize > infop->alloc) newptr = realloc(infop->buffer, newsize); if(!newptr) { infop->fail = 1; return -1; /* fail */ } infop->buffer = newptr; infop->alloc = newsize; } infop->buffer[ infop->len ] = outc; infop->len++; return outc; /* fputc() returns like this on success */ } char *curl_maprintf(const char *format, ...) { va_list ap_save; /* argument pointer */ int retcode; struct asprintf info; info.buffer = NULL; info.len = 0; info.alloc = 0; info.fail = 0; va_start(ap_save, format); retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save); va_end(ap_save); if((-1 == retcode) || info.fail) { if(info.alloc) free(info.buffer); return NULL; } if(info.alloc) { info.buffer[info.len] = 0; /* we terminate this with a zero byte */ return info.buffer; } return strdup(""); } char *curl_mvaprintf(const char *format, va_list ap_save) { int retcode; struct asprintf info; info.buffer = NULL; info.len = 0; info.alloc = 0; info.fail = 0; retcode = dprintf_formatf(&info, alloc_addbyter, format, ap_save); if((-1 == retcode) || info.fail) { if(info.alloc) free(info.buffer); return NULL; } if(info.alloc) { info.buffer[info.len] = 0; /* we terminate this with a zero byte */ return info.buffer; } return strdup(""); } 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); }
YifuLiu/AliOS-Things
components/curl/lib/mprintf.c
C
apache-2.0
30,444
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "transfer.h" #include "url.h" #include "connect.h" #include "progress.h" #include "easyif.h" #include "share.h" #include "psl.h" #include "multiif.h" #include "sendf.h" #include "timeval.h" #include "http.h" #include "select.h" #include "warnless.h" #include "speedcheck.h" #include "conncache.h" #include "multihandle.h" #include "sigpipe.h" #include "vtls/vtls.h" #include "connect.h" #include "http_proxy.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" /* CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every CURL handle takes 45-50 K memory, therefore this 3K are not significant. */ #ifndef CURL_SOCKET_HASH_TABLE_SIZE #define CURL_SOCKET_HASH_TABLE_SIZE 911 #endif #ifndef CURL_CONNECTION_HASH_SIZE #define CURL_CONNECTION_HASH_SIZE 97 #endif #define CURL_MULTI_HANDLE 0x000bab1e #define GOOD_MULTI_HANDLE(x) \ ((x) && (x)->type == CURL_MULTI_HANDLE) static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data); static int update_timer(struct Curl_multi *multi); static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d); static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms); static void process_pending_handles(struct Curl_multi *multi); static void detach_connnection(struct Curl_easy *data); #ifdef DEBUGBUILD static const char * const statename[]={ "INIT", "CONNECT_PEND", "CONNECT", "WAITRESOLVE", "WAITCONNECT", "WAITPROXYCONNECT", "SENDPROTOCONNECT", "PROTOCONNECT", "DO", "DOING", "DO_MORE", "DO_DONE", "PERFORM", "TOOFAST", "DONE", "COMPLETED", "MSGSENT", }; #endif /* function pointer called once when switching TO a state */ typedef void (*init_multistate_func)(struct Curl_easy *data); static void Curl_init_completed(struct Curl_easy *data) { /* this is a completed transfer */ /* Important: reset the conn pointer so that we don't point to memory that could be freed anytime */ detach_connnection(data); Curl_expire_clear(data); /* stop all timers */ } /* always use this function to change state, to make debugging easier */ static void mstate(struct Curl_easy *data, CURLMstate state #ifdef DEBUGBUILD , int lineno #endif ) { CURLMstate oldstate = data->mstate; static const init_multistate_func finit[CURLM_STATE_LAST] = { NULL, /* INIT */ NULL, /* CONNECT_PEND */ Curl_init_CONNECT, /* CONNECT */ NULL, /* WAITRESOLVE */ NULL, /* WAITCONNECT */ NULL, /* WAITPROXYCONNECT */ NULL, /* SENDPROTOCONNECT */ NULL, /* PROTOCONNECT */ Curl_connect_free, /* DO */ NULL, /* DOING */ NULL, /* DO_MORE */ NULL, /* DO_DONE */ NULL, /* PERFORM */ NULL, /* TOOFAST */ NULL, /* DONE */ Curl_init_completed, /* COMPLETED */ NULL /* MSGSENT */ }; #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS) (void) lineno; #endif if(oldstate == state) /* don't bother when the new state is the same as the old state */ return; data->mstate = state; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) if(data->mstate >= CURLM_STATE_CONNECT_PEND && data->mstate < CURLM_STATE_COMPLETED) { long connection_id = -5000; if(data->conn) connection_id = data->conn->connection_id; infof(data, "STATE: %s => %s handle %p; line %d (connection #%ld)\n", statename[oldstate], statename[data->mstate], (void *)data, lineno, connection_id); } #endif if(state == CURLM_STATE_COMPLETED) /* changing to COMPLETED means there's one less easy handle 'alive' */ data->multi->num_alive--; /* if this state has an init-function, run it */ if(finit[state]) finit[state](data); } #ifndef DEBUGBUILD #define multistate(x,y) mstate(x,y) #else #define multistate(x,y) mstate(x,y, __LINE__) #endif /* * We add one of these structs to the sockhash for each socket */ struct Curl_sh_entry { struct curl_llist list; /* list of easy handles using this socket */ unsigned int action; /* what combined action READ/WRITE this socket waits for */ void *socketp; /* settable by users with curl_multi_assign() */ unsigned int users; /* number of transfers using this */ unsigned int readers; /* this many transfers want to read */ unsigned int writers; /* this many transfers want to write */ }; /* bits for 'action' having no bits means this socket is not expecting any action */ #define SH_READ 1 #define SH_WRITE 2 /* look up a given socket in the socket hash, skip invalid sockets */ static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh, curl_socket_t s) { if(s != CURL_SOCKET_BAD) /* only look for proper sockets */ return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); return NULL; } /* make sure this socket is present in the hash for this handle */ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, curl_socket_t s) { struct Curl_sh_entry *there = sh_getentry(sh, s); struct Curl_sh_entry *check; if(there) /* it is present, return fine */ return there; /* not present, add it */ check = calloc(1, sizeof(struct Curl_sh_entry)); if(!check) return NULL; /* major failure */ Curl_llist_init(&check->list, NULL); /* make/add new hash entry */ if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { free(check); return NULL; /* major failure */ } return check; /* things are good in sockhash land */ } /* delete the given socket + handle from the hash */ static void sh_delentry(struct curl_hash *sh, curl_socket_t s) { /* We remove the hash entry. This will end up in a call to sh_freeentry(). */ Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); } /* * free a sockhash entry */ static void sh_freeentry(void *freethis) { struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis; free(p); } static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void) k1_len; (void) k2_len; return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); } static size_t hash_fd(void *key, size_t key_length, size_t slots_num) { curl_socket_t fd = *((curl_socket_t *) key); (void) key_length; return (fd % slots_num); } /* * sh_init() creates a new socket hash and returns the handle for it. * * Quote from README.multi_socket: * * "Some tests at 7000 and 9000 connections showed that the socket hash lookup * is somewhat of a bottle neck. Its current implementation may be a bit too * limiting. It simply has a fixed-size array, and on each entry in the array * it has a linked list with entries. So the hash only checks which list to * scan through. The code I had used so for used a list with merely 7 slots * (as that is what the DNS hash uses) but with 7000 connections that would * make an average of 1000 nodes in each list to run through. I upped that to * 97 slots (I believe a prime is suitable) and noticed a significant speed * increase. I need to reconsider the hash implementation or use a rather * large default value like this. At 9000 connections I was still below 10us * per call." * */ static int sh_init(struct curl_hash *hash, int hashsize) { return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare, sh_freeentry); } /* * multi_addmsg() * * Called when a transfer is completed. Adds the given msg pointer to * the list kept in the multi handle. */ static CURLMcode multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) { Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg, &msg->list); return CURLM_OK; } /* * multi_freeamsg() * * Callback used by the llist system when a single list entry is destroyed. */ static void multi_freeamsg(void *a, void *b) { (void)a; (void)b; } struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ int chashsize) /* connection hash */ { struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi)); if(!multi) return NULL; multi->type = CURL_MULTI_HANDLE; if(Curl_mk_dnscache(&multi->hostcache)) goto error; if(sh_init(&multi->sockhash, hashsize)) goto error; if(Curl_conncache_init(&multi->conn_cache, chashsize)) goto error; Curl_llist_init(&multi->msglist, multi_freeamsg); Curl_llist_init(&multi->pending, multi_freeamsg); /* -1 means it not set by user, use the default value */ multi->maxconnects = -1; return multi; error: Curl_hash_destroy(&multi->sockhash); Curl_hash_destroy(&multi->hostcache); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); free(multi); return NULL; } struct Curl_multi *curl_multi_init(void) { return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE, CURL_CONNECTION_HASH_SIZE); } CURLMcode curl_multi_add_handle(struct Curl_multi *multi, struct Curl_easy *data) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from adding same easy handle more than once and prevent adding to more than one multi stack */ if(data->multi) return CURLM_ADDED_ALREADY; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Initialize timeout list for this handle */ Curl_llist_init(&data->state.timeoutlist, NULL); /* * No failure allowed in this function beyond this point. And no * modification of easy nor multi handle allowed before this except for * potential multi's connection cache growing which won't be undone in this * function no matter what. */ if(data->set.errorbuffer) data->set.errorbuffer[0] = 0; /* set the easy handle */ multistate(data, CURLM_STATE_INIT); /* for multi interface connections, we share DNS cache automatically if the easy handle's one is currently not set. */ if(!data->dns.hostcache || (data->dns.hostcachetype == HCACHE_NONE)) { data->dns.hostcache = &multi->hostcache; data->dns.hostcachetype = HCACHE_MULTI; } /* Point to the shared or multi handle connection cache */ if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT))) data->state.conn_cache = &data->share->conn_cache; else data->state.conn_cache = &multi->conn_cache; #ifdef USE_LIBPSL /* Do the same for PSL. */ if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) data->psl = &data->share->psl; else data->psl = &multi->psl; #endif /* We add the new entry last in the list. */ data->next = NULL; /* end of the line */ if(multi->easyp) { struct Curl_easy *last = multi->easylp; last->next = data; data->prev = last; multi->easylp = data; /* the new last node */ } else { /* first node, make prev NULL! */ data->prev = NULL; multi->easylp = multi->easyp = data; /* both first and last */ } /* make the Curl_easy refer back to this multi handle */ data->multi = multi; /* Set the timeout for this handle to expire really soon so that it will be taken care of even when this handle is added in the midst of operation when only the curl_multi_socket() API is used. During that flow, only sockets that time-out or have actions will be dealt with. Since this handle has no action yet, we make sure it times out to get things to happen. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* increase the node-counter */ multi->num_easy++; /* increase the alive-counter */ multi->num_alive++; /* A somewhat crude work-around for a little glitch in update_timer() that happens if the lastcall time is set to the same time when the handle is removed as when the next handle is added, as then the check in update_timer() that prevents calling the application multiple times with the same timer info will not trigger and then the new handle's timeout will not be notified to the app. The work-around is thus simply to clear the 'lastcall' variable to force update_timer() to always trigger a callback to the app when a new easy handle is added */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); /* The closure handle only ever has default timeouts set. To improve the state somewhat we clone the timeouts from each added handle so that the closure handle always has the same timeouts as the most recently added easy handle. */ data->state.conn_cache->closure_handle->set.timeout = data->set.timeout; data->state.conn_cache->closure_handle->set.server_response_timeout = data->set.server_response_timeout; data->state.conn_cache->closure_handle->set.no_signal = data->set.no_signal; update_timer(multi); return CURLM_OK; } #if 0 /* Debug-function, used like this: * * Curl_hash_print(multi->sockhash, debug_print_sock_hash); * * Enable the hash print function first by editing hash.c */ static void debug_print_sock_hash(void *p) { struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p; fprintf(stderr, " [easy %p/magic %x/socket %d]", (void *)sh->data, sh->data->magic, (int)sh->socket); } #endif static CURLcode multi_done(struct Curl_easy *data, CURLcode status, /* an error if this is called after an error was detected */ bool premature) { CURLcode result; struct connectdata *conn = data->conn; unsigned int i; DEBUGF(infof(data, "multi_done\n")); if(data->state.done) /* Stop if multi_done() has already been called */ return CURLE_OK; /* Stop the resolver and free its own resources (but not dns_entry yet). */ Curl_resolver_kill(conn); /* Cleanup possible redirect junk */ Curl_safefree(data->req.newurl); Curl_safefree(data->req.location); switch(status) { case CURLE_ABORTED_BY_CALLBACK: case CURLE_READ_ERROR: case CURLE_WRITE_ERROR: /* When we're aborted due to a callback return code it basically have to be counted as premature as there is trouble ahead if we don't. We have many callbacks and protocols work differently, we could potentially do this more fine-grained in the future. */ premature = TRUE; default: break; } /* this calls the protocol-specific function pointer previously set */ if(conn->handler->done) result = conn->handler->done(conn, status, premature); else result = status; if(CURLE_ABORTED_BY_CALLBACK != result) { /* avoid this if we already aborted by callback to avoid this calling another callback */ CURLcode rc = Curl_pgrsDone(conn); if(!result && rc) result = CURLE_ABORTED_BY_CALLBACK; } process_pending_handles(data->multi); /* connection / multiplex */ detach_connnection(data); if(CONN_INUSE(conn)) { /* Stop if still used. */ DEBUGF(infof(data, "Connection still in use %zu, " "no more multi_done now!\n", conn->easyq.size)); return CURLE_OK; } data->state.done = TRUE; /* called just now! */ if(conn->dns_entry) { Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ conn->dns_entry = NULL; } Curl_hostcache_prune(data); Curl_safefree(data->state.ulbuf); /* if the transfer was completed in a paused state there can be buffered data left to free */ for(i = 0; i < data->state.tempcount; i++) { free(data->state.tempwrite[i].buf); } data->state.tempcount = 0; /* if data->set.reuse_forbid is TRUE, it means the libcurl client has forced us to close this connection. This is ignored for requests taking place in a NTLM/NEGOTIATE authentication handshake if conn->bits.close is TRUE, it means that the connection should be closed in spite of all our efforts to be nice, due to protocol restrictions in our or the server's end if premature is TRUE, it means this connection was said to be DONE before the entire request operation is complete and thus we can't know in what state it is for re-using, so we're forced to close it. In a perfect world we can add code that keep track of if we really must close it here or not, but currently we have no such detail knowledge. */ if((data->set.reuse_forbid #if defined(USE_NTLM) && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || conn->proxy_ntlm_state == NTLMSTATE_TYPE2) #endif #if defined(USE_SPNEGO) && !(conn->http_negotiate_state == GSS_AUTHRECV || conn->proxy_negotiate_state == GSS_AUTHRECV) #endif ) || conn->bits.close || (premature && !(conn->handler->flags & PROTOPT_STREAM))) { CURLcode res2 = Curl_disconnect(data, conn, premature); /* If we had an error already, make sure we return that one. But if we got a new error, return that. */ if(!result && res2) result = res2; } else { char buffer[256]; /* create string before returning the connection */ msnprintf(buffer, sizeof(buffer), "Connection #%ld to host %s left intact", conn->connection_id, conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname); /* the connection is no longer in use by this transfer */ if(Curl_conncache_return_conn(conn)) { /* remember the most recently used connection */ data->state.lastconnect = conn; infof(data, "%s\n", buffer); } else data->state.lastconnect = NULL; } Curl_free_request_state(data); return result; } CURLMcode curl_multi_remove_handle(struct Curl_multi *multi, struct Curl_easy *data) { struct Curl_easy *easy = data; bool premature; bool easy_owns_conn; struct curl_llist_element *e; /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from trying to remove same easy handle more than once */ if(!data->multi) return CURLM_OK; /* it is already removed so let's say it is fine! */ if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE; easy_owns_conn = (data->conn && (data->conn->data == easy)) ? TRUE : FALSE; /* If the 'state' is not INIT or COMPLETED, we might need to do something nice to put the easy_handle in a good known state when this returns. */ if(premature) { /* this handle is "alive" so we need to count down the total number of alive connections when this is removed */ multi->num_alive--; } if(data->conn && data->mstate > CURLM_STATE_DO && data->mstate < CURLM_STATE_COMPLETED) { /* Set connection owner so that the DONE function closes it. We can safely do this here since connection is killed. */ data->conn->data = easy; streamclose(data->conn, "Removed with partial response"); easy_owns_conn = TRUE; } /* The timer must be shut down before data->multi is set to NULL, else the timenode will remain in the splay tree after curl_easy_cleanup is called. */ Curl_expire_clear(data); if(data->conn) { /* we must call multi_done() here (if we still own the connection) so that we don't leave a half-baked one around */ if(easy_owns_conn) { /* multi_done() clears the conn->data field to lose the association between the easy handle and the connection Note that this ignores the return code simply because there's nothing really useful to do with it anyway! */ (void)multi_done(data, data->result, premature); } } if(data->connect_queue.ptr) /* the handle was in the pending list waiting for an available connection, so go ahead and remove it */ Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); if(data->dns.hostcachetype == HCACHE_MULTI) { /* stop using the multi handle's DNS cache, *after* the possible multi_done() call above */ data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } Curl_wildcard_dtor(&data->wildcard); /* destroy the timeout list that is held in the easy handle, do this *after* multi_done() as that may actually call Curl_expire that uses this */ Curl_llist_destroy(&data->state.timeoutlist, NULL); /* as this was using a shared connection cache we clear the pointer to that since we're not part of that multi handle anymore */ data->state.conn_cache = NULL; /* change state without using multistate(), only to make singlesocket() do what we want */ data->mstate = CURLM_STATE_COMPLETED; singlesocket(multi, easy); /* to let the application know what sockets that vanish with this handle */ /* Remove the association between the connection and the handle */ if(data->conn) { data->conn->data = NULL; detach_connnection(data); } #ifdef USE_LIBPSL /* Remove the PSL association. */ if(data->psl == &multi->psl) data->psl = NULL; #endif data->multi = NULL; /* clear the association to this multi handle */ /* make sure there's no pending message in the queue sent from this easy handle */ for(e = multi->msglist.head; e; e = e->next) { struct Curl_message *msg = e->ptr; if(msg->extmsg.easy_handle == easy) { Curl_llist_remove(&multi->msglist, e, NULL); /* there can only be one from this specific handle */ break; } } /* make the previous node point to our next */ if(data->prev) data->prev->next = data->next; else multi->easyp = data->next; /* point to first node */ /* make our next point to our previous node */ if(data->next) data->next->prev = data->prev; else multi->easylp = data->prev; /* point to last node */ /* NOTE NOTE NOTE We do not touch the easy handle here! */ multi->num_easy--; /* one less to care about now */ update_timer(multi); return CURLM_OK; } /* Return TRUE if the application asked for multiplexing */ bool Curl_multiplex_wanted(const struct Curl_multi *multi) { return (multi && (multi->multiplexing)); } /* This is the only function that should clear data->conn. This will occasionally be called with the pointer already cleared. */ static void detach_connnection(struct Curl_easy *data) { struct connectdata *conn = data->conn; if(conn) Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL); data->conn = NULL; } /* This is the only function that should assign data->conn */ void Curl_attach_connnection(struct Curl_easy *data, struct connectdata *conn) { DEBUGASSERT(!data->conn); DEBUGASSERT(conn); data->conn = conn; Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data, &data->conn_queue); } static int waitconnect_getsock(struct connectdata *conn, curl_socket_t *sock, int numsocks) { int i; int s = 0; int rc = 0; if(!numsocks) return GETSOCK_BLANK; #ifdef USE_SSL if(CONNECT_FIRSTSOCKET_PROXY_SSL()) return Curl_ssl_getsock(conn, sock, numsocks); #endif for(i = 0; i<2; i++) { if(conn->tempsock[i] != CURL_SOCKET_BAD) { sock[s] = conn->tempsock[i]; rc |= GETSOCK_WRITESOCK(s++); } } return rc; } static int waitproxyconnect_getsock(struct connectdata *conn, curl_socket_t *sock, int numsocks) { if(!numsocks) return GETSOCK_BLANK; sock[0] = conn->sock[FIRSTSOCKET]; /* when we've sent a CONNECT to a proxy, we should rather wait for the socket to become readable to be able to get the response headers */ if(conn->connect_state) return GETSOCK_READSOCK(0); return GETSOCK_WRITESOCK(0); } static int domore_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(conn && conn->handler->domore_getsock) return conn->handler->domore_getsock(conn, socks, numsocks); return GETSOCK_BLANK; } /* returns bitmapped flags for this handle and its sockets */ static int multi_getsock(struct Curl_easy *data, curl_socket_t *socks, /* points to numsocks number of sockets */ int numsocks) { /* The no connection case can happen when this is called from curl_multi_remove_handle() => singlesocket() => multi_getsock(). */ if(!data->conn) return 0; if(data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Set up ownership correctly */ data->conn->data = data; } switch(data->mstate) { default: #if 0 /* switch back on these cases to get the compiler to check for all enums to be present */ case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */ case CURLM_STATE_COMPLETED: case CURLM_STATE_MSGSENT: case CURLM_STATE_INIT: case CURLM_STATE_CONNECT: case CURLM_STATE_WAITDO: case CURLM_STATE_DONE: case CURLM_STATE_LAST: /* this will get called with CURLM_STATE_COMPLETED when a handle is removed */ #endif return 0; case CURLM_STATE_WAITRESOLVE: return Curl_resolv_getsock(data->conn, socks, numsocks); case CURLM_STATE_PROTOCONNECT: case CURLM_STATE_SENDPROTOCONNECT: return Curl_protocol_getsock(data->conn, socks, numsocks); case CURLM_STATE_DO: case CURLM_STATE_DOING: return Curl_doing_getsock(data->conn, socks, numsocks); case CURLM_STATE_WAITPROXYCONNECT: return waitproxyconnect_getsock(data->conn, socks, numsocks); case CURLM_STATE_WAITCONNECT: return waitconnect_getsock(data->conn, socks, numsocks); case CURLM_STATE_DO_MORE: return domore_getsock(data->conn, socks, numsocks); case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch to waiting for the same as the *PERFORM states */ case CURLM_STATE_PERFORM: return Curl_single_getsock(data->conn, socks, numsocks); } } CURLMcode curl_multi_fdset(struct Curl_multi *multi, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd) { /* Scan through all the easy handles to get the file descriptors set. Some easy handles may not have connected to the remote host yet, and then we must make sure that is done. */ struct Curl_easy *data; int this_max_fd = -1; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int i; (void)exc_fd_set; /* not used */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { int bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], read_fd_set); s = sockbunch[i]; } if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], write_fd_set); s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) /* this socket is unused, break out of loop */ break; if((int)s > this_max_fd) this_max_fd = (int)s; } data = data->next; /* check next handle */ } *max_fd = this_max_fd; return CURLM_OK; } #define NUM_POLLS_ON_STACK 10 CURLMcode Curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret, bool *gotsocket) /* if any socket was checked */ { struct Curl_easy *data; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int bitmap; unsigned int i; unsigned int nfds = 0; unsigned int curlfds; bool ufds_malloc = FALSE; long timeout_internal; int retcode = 0; struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; struct pollfd *ufds = &a_few_on_stack[0]; if(gotsocket) *gotsocket = FALSE; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Count up how many fds we have from the multi handle */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } /* If the internally desired timeout is actually shorter than requested from the outside, then use the shorter time! But only if the internal timer is actually larger than -1! */ (void)multi_timeout(multi, &timeout_internal); if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms)) timeout_ms = (int)timeout_internal; curlfds = nfds; /* number of internal file descriptors */ nfds += extra_nfds; /* add the externally provided ones */ if(nfds > NUM_POLLS_ON_STACK) { /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes big, so at 2^29 sockets this value might wrap. When a process gets the capability to actually handle over 500 million sockets this calculation needs a integer overflow check. */ ufds = malloc(nfds * sizeof(struct pollfd)); if(!ufds) return CURLM_OUT_OF_MEMORY; ufds_malloc = TRUE; } nfds = 0; /* only do the second loop if we found descriptors in the first stage run above */ if(curlfds) { /* Add the curl handles to our pollfds first */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLIN; ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLOUT; ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } } /* Add external file descriptions from poll-like struct curl_waitfd */ for(i = 0; i < extra_nfds; i++) { ufds[nfds].fd = extra_fds[i].fd; ufds[nfds].events = 0; if(extra_fds[i].events & CURL_WAIT_POLLIN) ufds[nfds].events |= POLLIN; if(extra_fds[i].events & CURL_WAIT_POLLPRI) ufds[nfds].events |= POLLPRI; if(extra_fds[i].events & CURL_WAIT_POLLOUT) ufds[nfds].events |= POLLOUT; ++nfds; } if(nfds) { int pollrc; /* wait... */ pollrc = Curl_poll(ufds, nfds, timeout_ms); if(pollrc > 0) { retcode = pollrc; /* copy revents results from the poll to the curl_multi_wait poll struct, the bit values of the actual underlying poll() implementation may not be the same as the ones in the public libcurl API! */ for(i = 0; i < extra_nfds; i++) { unsigned short mask = 0; unsigned r = ufds[curlfds + i].revents; if(r & POLLIN) mask |= CURL_WAIT_POLLIN; if(r & POLLOUT) mask |= CURL_WAIT_POLLOUT; if(r & POLLPRI) mask |= CURL_WAIT_POLLPRI; extra_fds[i].revents = mask; } } } if(ufds_malloc) free(ufds); if(ret) *ret = retcode; if(gotsocket && (extra_fds || curlfds)) /* if any socket was checked */ *gotsocket = TRUE; return CURLM_OK; } CURLMcode curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, NULL); } /* * multi_ischanged() is called * * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND * => CONNECT action. * * Set 'clear' to TRUE to have it also clear the state variable. */ static bool multi_ischanged(struct Curl_multi *multi, bool clear) { bool retval = multi->recheckstate; if(clear) multi->recheckstate = FALSE; return retval; } CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, struct Curl_easy *data, struct connectdata *conn) { CURLMcode rc; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; rc = curl_multi_add_handle(multi, data); if(!rc) { struct SingleRequest *k = &data->req; /* pass in NULL for 'conn' here since we don't want to init the connection, only this transfer */ Curl_init_do(data, NULL); /* take this handle to the perform state right away */ multistate(data, CURLM_STATE_PERFORM); Curl_attach_connnection(data, conn); k->keepon |= KEEP_RECV; /* setup to receive! */ } return rc; } /* * do_complete is called when the DO actions are complete. * * We init chunking and trailer bits to their default values here immediately * before receiving any header data for the current request. */ static void do_complete(struct connectdata *conn) { conn->data->req.chunk = FALSE; Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); } static CURLcode multi_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; DEBUGASSERT(conn); DEBUGASSERT(conn->handler); if(conn->handler->do_it) { /* generic protocol-specific function pointer set in curl_connect() */ result = conn->handler->do_it(conn, done); if(!result && *done) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); } return result; } /* * multi_do_more() is called during the DO_MORE multi state. It is basically a * second stage DO state which (wrongly) was introduced to support FTP's * second connection. * * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to * DOING state there's more work to do! */ static CURLcode multi_do_more(struct connectdata *conn, int *complete) { CURLcode result = CURLE_OK; *complete = 0; if(conn->handler->do_more) result = conn->handler->do_more(conn, complete); if(!result && (*complete == 1)) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); return result; } static CURLMcode multi_runsingle(struct Curl_multi *multi, struct curltime now, struct Curl_easy *data) { struct Curl_message *msg = NULL; bool connected; bool async; bool protocol_connect = FALSE; bool dophase_done = FALSE; bool done = FALSE; CURLMcode rc; CURLcode result = CURLE_OK; timediff_t timeout_ms; timediff_t recv_timeout_ms; timediff_t send_timeout_ms; int control; if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; do { /* A "stream" here is a logical stream if the protocol can handle that (HTTP/2), or the full connection for older protocols */ bool stream_error = FALSE; rc = CURLM_OK; if(!data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_DONE) { /* In all these states, the code will blindly access 'data->conn' so this is precaution that it isn't NULL. And it silences static analyzers. */ failf(data, "In state %d with no conn, bail out!\n", data->mstate); return CURLM_INTERNAL_ERROR; } if(multi_ischanged(multi, TRUE)) { DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n")); process_pending_handles(multi); /* multiplexed */ } if(data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Make sure we set the connection's current owner */ data->conn->data = data; } if(data->conn && (data->mstate >= CURLM_STATE_CONNECT) && (data->mstate < CURLM_STATE_COMPLETED)) { /* we need to wait for the connect state as only then is the start time stored, but we must not check already completed handles */ timeout_ms = Curl_timeleft(data, &now, (data->mstate <= CURLM_STATE_DO)? TRUE:FALSE); if(timeout_ms < 0) { /* Handle timed out */ if(data->mstate == CURLM_STATE_WAITRESOLVE) failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else if(data->mstate == CURLM_STATE_WAITCONNECT) failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else { struct SingleRequest *k = &data->req; if(k->size != -1) { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount); } } /* Force connection closed if the connection has indeed been used */ if(data->mstate > CURLM_STATE_DO) { streamclose(data->conn, "Disconnected with pending data"); stream_error = TRUE; } result = CURLE_OPERATION_TIMEDOUT; (void)multi_done(data, result, TRUE); /* Skip the statemachine and go directly to error handling section. */ goto statemachine_end; } } switch(data->mstate) { case CURLM_STATE_INIT: /* init this transfer. */ result = Curl_pretransfer(data); if(!result) { /* after init, go CONNECT */ multistate(data, CURLM_STATE_CONNECT); Curl_pgrsTime(data, TIMER_STARTOP); rc = CURLM_CALL_MULTI_PERFORM; } break; case CURLM_STATE_CONNECT_PEND: /* We will stay here until there is a connection available. Then we try again in the CURLM_STATE_CONNECT state. */ break; case CURLM_STATE_CONNECT: /* Connect. We want to get a connection identifier filled in. */ Curl_pgrsTime(data, TIMER_STARTSINGLE); if(data->set.timeout) Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT); if(data->set.connecttimeout) Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT); result = Curl_connect(data, &async, &protocol_connect); if(CURLE_NO_CONNECTION_AVAILABLE == result) { /* There was no connection available. We will go to the pending state and wait for an available connection. */ multistate(data, CURLM_STATE_CONNECT_PEND); /* add this handle to the list of connect-pending handles */ Curl_llist_insert_next(&multi->pending, multi->pending.tail, data, &data->connect_queue); result = CURLE_OK; break; } else if(data->state.previouslypending) { /* this transfer comes from the pending queue so try move another */ infof(data, "Transfer was pending, now try another\n"); process_pending_handles(data->multi); } if(!result) { if(async) /* We're now waiting for an asynchronous name lookup */ multistate(data, CURLM_STATE_WAITRESOLVE); else { /* after the connect has been sent off, go WAITCONNECT unless the protocol connect is already done and we can go directly to WAITDO or DO! */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connect) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } break; case CURLM_STATE_WAITRESOLVE: /* awaiting an asynch name resolve to complete */ { struct Curl_dns_entry *dns = NULL; struct connectdata *conn = data->conn; const char *hostname; DEBUGASSERT(conn); if(conn->bits.httpproxy) hostname = conn->http_proxy.host.name; else if(conn->bits.conn_to_host) hostname = conn->conn_to_host.name; else hostname = conn->host.name; /* check if we have the name resolved by now */ dns = Curl_fetch_addr(conn, hostname, (int)conn->port); if(dns) { #ifdef CURLRES_ASYNCH conn->async.dns = dns; conn->async.done = TRUE; #endif result = CURLE_OK; infof(data, "Hostname '%s' was found in DNS cache\n", hostname); } if(!dns) result = Curl_resolv_check(data->conn, &dns); /* Update sockets here, because the socket(s) may have been closed and the application thus needs to be told, even if it is likely that the same socket(s) will again be used further down. If the name has not yet been resolved, it is likely that new sockets have been opened in an attempt to contact another resolver. */ singlesocket(multi, data); if(dns) { /* Perform the next step in the connection phase, and then move on to the WAITCONNECT state */ result = Curl_once_resolved(data->conn, &protocol_connect); if(result) /* if Curl_once_resolved() returns failure, the connection struct is already freed and gone */ data->conn = NULL; /* no more connection */ else { /* call again please so that we get the next socket setup */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connect) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } if(result) { /* failure detected */ stream_error = TRUE; break; } } break; #ifndef CURL_DISABLE_HTTP case CURLM_STATE_WAITPROXYCONNECT: /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ DEBUGASSERT(data->conn); result = Curl_http_connect(data->conn, &protocol_connect); if(data->conn->bits.proxy_connect_closed) { rc = CURLM_CALL_MULTI_PERFORM; /* connect back to proxy again */ result = CURLE_OK; multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_CONNECT); } else if(!result) { if((data->conn->http_proxy.proxytype != CURLPROXY_HTTPS || data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) && Curl_connect_complete(data->conn)) { rc = CURLM_CALL_MULTI_PERFORM; /* initiate protocol connect phase */ multistate(data, CURLM_STATE_SENDPROTOCONNECT); } } else if(result) stream_error = TRUE; break; #endif case CURLM_STATE_WAITCONNECT: /* awaiting a completion of an asynch TCP connect */ DEBUGASSERT(data->conn); result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected); if(connected && !result) { #ifndef CURL_DISABLE_HTTP if((data->conn->http_proxy.proxytype == CURLPROXY_HTTPS && !data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) || Curl_connect_ongoing(data->conn)) { multistate(data, CURLM_STATE_WAITPROXYCONNECT); break; } #endif rc = CURLM_CALL_MULTI_PERFORM; multistate(data, data->conn->bits.tunnel_proxy? CURLM_STATE_WAITPROXYCONNECT: CURLM_STATE_SENDPROTOCONNECT); } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; break; } break; case CURLM_STATE_SENDPROTOCONNECT: result = Curl_protocol_connect(data->conn, &protocol_connect); if(!result && !protocol_connect) /* switch to waiting state */ multistate(data, CURLM_STATE_PROTOCONNECT); else if(!result) { /* protocol connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_PROTOCONNECT: /* protocol-specific connect phase */ result = Curl_protocol_connecting(data->conn, &protocol_connect); if(!result && protocol_connect) { /* after the connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_DO: if(data->set.connect_only) { /* keep connection open for application to use the socket */ connkeep(data->conn, "CONNECT_ONLY"); multistate(data, CURLM_STATE_DONE); result = CURLE_OK; rc = CURLM_CALL_MULTI_PERFORM; } else { /* Perform the protocol's DO action */ result = multi_do(data, &dophase_done); /* When multi_do() returns failure, data->conn might be NULL! */ if(!result) { if(!dophase_done) { #ifndef CURL_DISABLE_FTP /* some steps needed for wildcard matching */ if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { /* skip some states if it is important */ multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; break; } } #endif /* DO was not completed in one function call, we must continue DOING... */ multistate(data, CURLM_STATE_DOING); rc = CURLM_OK; } /* after DO, go DO_DONE... or DO_MORE */ else if(data->conn->bits.do_more) { /* we're supposed to do more, but we need to sit down, relax and wait a little while first */ multistate(data, CURLM_STATE_DO_MORE); rc = CURLM_OK; } else { /* we're done with the DO, now DO_DONE */ multistate(data, CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } else if((CURLE_SEND_ERROR == result) && data->conn->bits.reuse) { /* * In this situation, a connection that we were trying to use * may have unexpectedly died. If possible, send the connection * back to the CONNECT phase so we can try again. */ char *newurl = NULL; followtype follow = FOLLOW_NONE; CURLcode drc; drc = Curl_retry_request(data->conn, &newurl); if(drc) { /* a failure here pretty much implies an out of memory */ result = drc; stream_error = TRUE; } Curl_posttransfer(data); drc = multi_done(data, result, FALSE); /* When set to retry the connection, we must to go back to * the CONNECT state */ if(newurl) { if(!drc || (drc == CURLE_SEND_ERROR)) { follow = FOLLOW_RETRY; drc = Curl_follow(data, newurl, follow); if(!drc) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; result = CURLE_OK; } else { /* Follow failed */ result = drc; } } else { /* done didn't return OK or SEND_ERROR */ result = drc; } } else { /* Have error handler disconnect conn if we can't retry */ stream_error = TRUE; } free(newurl); } else { /* failure detected */ Curl_posttransfer(data); if(data->conn) multi_done(data, result, FALSE); stream_error = TRUE; } } break; case CURLM_STATE_DOING: /* we continue DOING until the DO phase is complete */ DEBUGASSERT(data->conn); result = Curl_protocol_doing(data->conn, &dophase_done); if(!result) { if(dophase_done) { /* after DO, go DO_DONE or DO_MORE */ multistate(data, data->conn->bits.do_more? CURLM_STATE_DO_MORE: CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } /* dophase_done */ } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_MORE: /* * When we are connected, DO MORE and then go DO_DONE */ DEBUGASSERT(data->conn); result = multi_do_more(data->conn, &control); if(!result) { if(control) { /* if positive, advance to DO_DONE if negative, go back to DOING */ multistate(data, control == 1? CURLM_STATE_DO_DONE: CURLM_STATE_DOING); rc = CURLM_CALL_MULTI_PERFORM; } else /* stay in DO_MORE */ rc = CURLM_OK; } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_DONE: DEBUGASSERT(data->conn); if(data->conn->bits.multiplex) /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* multiplexed */ /* Only perform the transfer if there's a good socket to work with. Having both BAD is a signal to skip immediately to DONE */ if((data->conn->sockfd != CURL_SOCKET_BAD) || (data->conn->writesockfd != CURL_SOCKET_BAD)) multistate(data, CURLM_STATE_PERFORM); else { #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch && ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) { data->wildcard.state = CURLWC_DONE; } #endif multistate(data, CURLM_STATE_DONE); } rc = CURLM_CALL_MULTI_PERFORM; break; case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */ DEBUGASSERT(data->conn); /* if both rates are within spec, resume transfer */ if(Curl_pgrsUpdate(data->conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, now); if(!result) { send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(!send_timeout_ms && !recv_timeout_ms) { multistate(data, CURLM_STATE_PERFORM); Curl_ratelimit(data, now); } else if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); } break; case CURLM_STATE_PERFORM: { char *newurl = NULL; bool retry = FALSE; bool comeback = FALSE; /* check if over send speed */ send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); /* check if over recv speed */ recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(send_timeout_ms || recv_timeout_ms) { Curl_ratelimit(data, now); multistate(data, CURLM_STATE_TOOFAST); if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); break; } /* read/write data if it is ready to do so */ result = Curl_readwrite(data->conn, data, &done, &comeback); if(done || (result == CURLE_RECV_ERROR)) { /* If CURLE_RECV_ERROR happens early enough, we assume it was a race * condition and the server closed the re-used connection exactly when * we wanted to use it, so figure out if that is indeed the case. */ CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) retry = (newurl)?TRUE:FALSE; else if(!result) result = ret; if(retry) { /* if we are to retry, set the result to OK and consider the request as done */ result = CURLE_OK; done = TRUE; } } else if((CURLE_HTTP2_STREAM == result) && Curl_h2_http_1_1_error(data->conn)) { CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) { infof(data, "Downgrades to HTTP/1.1!\n"); data->set.httpversion = CURL_HTTP_VERSION_1_1; /* clear the error message bit too as we ignore the one we got */ data->state.errorbuf = FALSE; if(!newurl) /* typically for HTTP_1_1_REQUIRED error on first flight */ newurl = strdup(data->change.url); /* if we are to retry, set the result to OK and consider the request as done */ retry = TRUE; result = CURLE_OK; done = TRUE; } else result = ret; } if(result) { /* * The transfer phase returned error, we mark the connection to get * closed to prevent being re-used. This is because we can't possibly * know if the connection is in a good shape or not now. Unless it is * a protocol which uses two "channels" like FTP, as then the error * happened in the data connection. */ if(!(data->conn->handler->flags & PROTOPT_DUAL) && result != CURLE_HTTP2_STREAM) streamclose(data->conn, "Transfer returned error"); Curl_posttransfer(data); multi_done(data, result, TRUE); } else if(done) { followtype follow = FOLLOW_NONE; /* call this even if the readwrite function returned error */ Curl_posttransfer(data); /* When we follow redirects or is set to retry the connection, we must to go back to the CONNECT state */ if(data->req.newurl || retry) { if(!retry) { /* if the URL is a follow-location and not just a retried request then figure out the URL here */ free(newurl); newurl = data->req.newurl; data->req.newurl = NULL; follow = FOLLOW_REDIR; } else follow = FOLLOW_RETRY; (void)multi_done(data, CURLE_OK, FALSE); /* multi_done() might return CURLE_GOT_NOTHING */ result = Curl_follow(data, newurl, follow); if(!result) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; } free(newurl); } else { /* after the transfer is done, go DONE */ /* but first check to see if we got a location info even though we're not following redirects */ if(data->req.location) { free(newurl); newurl = data->req.location; data->req.location = NULL; result = Curl_follow(data, newurl, FOLLOW_FAKE); free(newurl); if(result) { stream_error = TRUE; result = multi_done(data, result, TRUE); } } if(!result) { multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } } else if(comeback) rc = CURLM_CALL_MULTI_PERFORM; break; } case CURLM_STATE_DONE: /* this state is highly transient, so run another loop after this */ rc = CURLM_CALL_MULTI_PERFORM; if(data->conn) { CURLcode res; if(data->conn->bits.multiplex) /* Check if we can move pending requests to connection */ process_pending_handles(multi); /* multiplexing */ /* post-transfer command */ res = multi_done(data, result, FALSE); /* allow a previously set error code take precedence */ if(!result) result = res; /* * If there are other handles on the connection, multi_done won't set * conn to NULL. In such a case, curl_multi_remove_handle() can * access free'd data, if the connection is free'd and the handle * removed before we perform the processing in CURLM_STATE_COMPLETED */ if(data->conn) detach_connnection(data); } #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { if(data->wildcard.state != CURLWC_DONE) { /* if a wildcard is set and we are not ending -> lets start again with CURLM_STATE_INIT */ multistate(data, CURLM_STATE_INIT); break; } } #endif /* after we have DONE what we're supposed to do, go COMPLETED, and it doesn't matter what the multi_done() returned! */ multistate(data, CURLM_STATE_COMPLETED); break; case CURLM_STATE_COMPLETED: break; case CURLM_STATE_MSGSENT: data->result = result; return CURLM_OK; /* do nothing */ default: return CURLM_INTERNAL_ERROR; } statemachine_end: if(data->mstate < CURLM_STATE_COMPLETED) { if(result) { /* * If an error was returned, and we aren't in completed state now, * then we go to completed and consider this transfer aborted. */ /* NOTE: no attempt to disconnect connections must be made in the case blocks above - cleanup happens only here */ /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* connection */ if(data->conn) { if(stream_error) { /* Don't attempt to send data over a connection that timed out */ bool dead_connection = result == CURLE_OPERATION_TIMEDOUT; /* disconnect properly */ Curl_disconnect(data, data->conn, dead_connection); /* This is where we make sure that the conn pointer is reset. We don't have to do this in every case block above where a failure is detected */ detach_connnection(data); } } else if(data->mstate == CURLM_STATE_CONNECT) { /* Curl_connect() failed */ (void)Curl_posttransfer(data); } multistate(data, CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } /* if there's still a connection to use, call the progress function */ else if(data->conn && Curl_pgrsUpdate(data->conn)) { /* aborted due to progress callback return code must close the connection */ result = CURLE_ABORTED_BY_CALLBACK; streamclose(data->conn, "Aborted by callback"); /* if not yet in DONE state, go there, otherwise COMPLETED */ multistate(data, (data->mstate < CURLM_STATE_DONE)? CURLM_STATE_DONE: CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } } if(CURLM_STATE_COMPLETED == data->mstate) { if(data->set.fmultidone) { /* signal via callback instead */ data->set.fmultidone(data, result); } else { /* now fill in the Curl_message with this info */ msg = &data->msg; msg->extmsg.msg = CURLMSG_DONE; msg->extmsg.easy_handle = data; msg->extmsg.data.result = result; rc = multi_addmsg(multi, msg); DEBUGASSERT(!data->conn); } multistate(data, CURLM_STATE_MSGSENT); } } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE)); data->result = result; return rc; } CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) { struct Curl_easy *data; CURLMcode returncode = CURLM_OK; struct Curl_tree *t; struct curltime now = Curl_now(); if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { CURLMcode result; SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(result) returncode = result; data = data->next; /* operate on next handle */ } /* * Simply remove all expired timers from the splay since handles are dealt * with unconditionally by this function and curl_multi_timeout() requires * that already passed/handled expire times are removed from the splay. * * It is important that the 'now' value is set at the entry of this function * and not for the current time as it may have ticked a little while since * then and then we risk this loop to remove timers that actually have not * been handled! */ do { multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) /* the removed may have another timeout in queue */ (void)add_next_timeout(now, multi, t->payload); } while(t); *running_handles = multi->num_alive; if(CURLM_OK >= returncode) update_timer(multi); return returncode; } CURLMcode curl_multi_cleanup(struct Curl_multi *multi) { struct Curl_easy *data; struct Curl_easy *nextdata; if(GOOD_MULTI_HANDLE(multi)) { if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; multi->type = 0; /* not good anymore */ /* Firsrt remove all remaining easy handles */ data = multi->easyp; while(data) { nextdata = data->next; if(!data->state.done && data->conn) /* if DONE was never called for this handle */ (void)multi_done(data, CURLE_OK, TRUE); if(data->dns.hostcachetype == HCACHE_MULTI) { /* clear out the usage of the shared DNS cache */ Curl_hostcache_clean(data, data->dns.hostcache); data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } /* Clear the pointer to the connection cache */ data->state.conn_cache = NULL; data->multi = NULL; /* clear the association */ #ifdef USE_LIBPSL if(data->psl == &multi->psl) data->psl = NULL; #endif data = nextdata; } /* Close all the connections in the connection cache */ Curl_conncache_close_all_connections(&multi->conn_cache); Curl_hash_destroy(&multi->sockhash); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); Curl_hash_destroy(&multi->hostcache); Curl_psl_destroy(&multi->psl); free(multi); return CURLM_OK; } return CURLM_BAD_HANDLE; } /* * curl_multi_info_read() * * This function is the primary way for a multi/multi_socket application to * figure out if a transfer has ended. We MUST make this function as fast as * possible as it will be polled frequently and we MUST NOT scan any lists in * here to figure out things. We must scale fine to thousands of handles and * beyond. The current design is fully O(1). */ CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue) { struct Curl_message *msg; *msgs_in_queue = 0; /* default to none */ if(GOOD_MULTI_HANDLE(multi) && !multi->in_callback && Curl_llist_count(&multi->msglist)) { /* there is one or more messages in the list */ struct curl_llist_element *e; /* extract the head of the list to return */ e = multi->msglist.head; msg = e->ptr; /* remove the extracted entry */ Curl_llist_remove(&multi->msglist, e, NULL); *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); return &msg->extmsg; } return NULL; } /* * singlesocket() checks what sockets we deal with and their "action state" * and if we have a different state in any of those sockets from last time we * call the callback accordingly. */ static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data) { curl_socket_t socks[MAX_SOCKSPEREASYHANDLE]; int i; struct Curl_sh_entry *entry; curl_socket_t s; int num; unsigned int curraction; int actions[MAX_SOCKSPEREASYHANDLE]; for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) socks[i] = CURL_SOCKET_BAD; /* Fill in the 'current' struct with the state as it is now: what sockets to supervise and for what actions */ curraction = multi_getsock(data, socks, MAX_SOCKSPEREASYHANDLE); /* We have 0 .. N sockets already and we get to know about the 0 .. M sockets we should have from now on. Detect the differences, remove no longer supervised ones and add new ones */ /* walk over the sockets we got right now */ for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) && (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))); i++) { unsigned int action = CURL_POLL_NONE; unsigned int prevaction = 0; unsigned int comboaction; bool sincebefore = FALSE; s = socks[i]; /* get it from the hash */ entry = sh_getentry(&multi->sockhash, s); if(curraction & GETSOCK_READSOCK(i)) action |= CURL_POLL_IN; if(curraction & GETSOCK_WRITESOCK(i)) action |= CURL_POLL_OUT; actions[i] = action; if(entry) { /* check if new for this transfer */ for(i = 0; i< data->numsocks; i++) { if(s == data->sockets[i]) { prevaction = data->actions[i]; sincebefore = TRUE; break; } } } else { /* this is a socket we didn't have before, add it to the hash! */ entry = sh_addentry(&multi->sockhash, s); if(!entry) /* fatal */ return CURLM_OUT_OF_MEMORY; } if(sincebefore && (prevaction != action)) { /* Socket was used already, but different action now */ if(prevaction & CURL_POLL_IN) entry->readers--; if(prevaction & CURL_POLL_OUT) entry->writers--; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; } else if(!sincebefore) { /* a new user */ entry->users++; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; /* add 'data' to the list of handles using this socket! */ Curl_llist_insert_next(&entry->list, entry->list.tail, data, &data->sh_queue); } comboaction = (entry->writers? CURL_POLL_OUT : 0) | (entry->readers ? CURL_POLL_IN : 0); #if 0 infof(data, "--- Comboaction: %u readers %u writers\n", entry->readers, entry->writers); #endif /* check if it has the same action set */ if(entry->action == comboaction) /* same, continue */ continue; /* we know (entry != NULL) at this point, see the logic above */ if(multi->socket_cb) multi->socket_cb(data, s, comboaction, multi->socket_userp, entry->socketp); entry->action = comboaction; /* store the current action state */ } num = i; /* number of sockets */ /* when we've walked over all the sockets we should have right now, we must make sure to detect sockets that are removed */ for(i = 0; i< data->numsocks; i++) { int j; bool stillused = FALSE; s = data->sockets[i]; for(j = 0; j < num; j++) { if(s == socks[j]) { /* this is still supervised */ stillused = TRUE; break; } } if(stillused) continue; entry = sh_getentry(&multi->sockhash, s); /* if this is NULL here, the socket has been closed and notified so already by Curl_multi_closed() */ if(entry) { int oldactions = data->actions[i]; /* this socket has been removed. Decrease user count */ entry->users--; if(oldactions & CURL_POLL_OUT) entry->writers--; if(oldactions & CURL_POLL_IN) entry->readers--; if(!entry->users) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); sh_delentry(&multi->sockhash, s); } else { /* remove this transfer as a user of this socket */ Curl_llist_remove(&entry->list, &data->sh_queue, NULL); } } } /* for loop over numsocks */ memcpy(data->sockets, socks, num*sizeof(curl_socket_t)); memcpy(data->actions, actions, num*sizeof(int)); data->numsocks = num; return CURLM_OK; } void Curl_updatesocket(struct Curl_easy *data) { singlesocket(data->multi, data); } /* * Curl_multi_closed() * * Used by the connect code to tell the multi_socket code that one of the * sockets we were using is about to be closed. This function will then * remove it from the sockethash for this handle to make the multi_socket API * behave properly, especially for the case when libcurl will create another * socket again and it gets the same file descriptor number. */ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s) { if(data) { /* if there's still an easy handle associated with this connection */ struct Curl_multi *multi = data->multi; if(multi) { /* this is set if this connection is part of a handle that is added to a multi handle, and only then this is necessary */ struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(entry) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); /* now remove it from the socket hash */ sh_delentry(&multi->sockhash, s); } } } } /* * add_next_timeout() * * Each Curl_easy has a list of timeouts. The add_next_timeout() is called * when it has just been removed from the splay tree because the timeout has * expired. This function is then to advance in the list to pick the next * timeout to use (skip the already expired ones) and add this node back to * the splay tree again. * * The splay tree only has each sessionhandle as a single node and the nearest * timeout is used to sort it on. */ static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d) { struct curltime *tv = &d->state.expiretime; struct curl_llist *list = &d->state.timeoutlist; struct curl_llist_element *e; struct time_node *node = NULL; /* move over the timeout list for this specific handle and remove all timeouts that are now passed tense and store the next pending timeout in *tv */ for(e = list->head; e;) { struct curl_llist_element *n = e->next; timediff_t diff; node = (struct time_node *)e->ptr; diff = Curl_timediff(node->time, now); if(diff <= 0) /* remove outdated entry */ Curl_llist_remove(list, e, NULL); else /* the list is sorted so get out on the first mismatch */ break; e = n; } e = list->head; if(!e) { /* clear the expire times within the handles that we remove from the splay tree */ tv->tv_sec = 0; tv->tv_usec = 0; } else { /* copy the first entry to 'tv' */ memcpy(tv, &node->time, sizeof(*tv)); /* Insert this node again into the splay. Keep the timer in the list in case we need to recompute future timers. */ multi->timetree = Curl_splayinsert(*tv, multi->timetree, &d->state.timenode); } return CURLM_OK; } static CURLMcode multi_socket(struct Curl_multi *multi, bool checkall, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result = CURLM_OK; struct Curl_easy *data = NULL; struct Curl_tree *t; struct curltime now = Curl_now(); if(checkall) { /* *perform() deals with running_handles on its own */ result = curl_multi_perform(multi, running_handles); /* walk through each easy handle and do the socket state change magic and callbacks */ if(result != CURLM_BAD_HANDLE) { data = multi->easyp; while(data && !result) { result = singlesocket(multi, data); data = data->next; } } /* or should we fall-through and do the timer-based stuff? */ return result; } if(s != CURL_SOCKET_TIMEOUT) { struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(!entry) /* Unmatched socket, we can't act on it but we ignore this fact. In real-world tests it has been proved that libevent can in fact give the application actions even though the socket was just previously asked to get removed, so thus we better survive stray socket actions and just move on. */ ; else { struct curl_llist *list = &entry->list; struct curl_llist_element *e; SIGPIPE_VARIABLE(pipe_st); /* the socket can be shared by many transfers, iterate */ for(e = list->head; e; e = e->next) { data = (struct Curl_easy *)e->ptr; if(data->magic != CURLEASY_MAGIC_NUMBER) /* bad bad bad bad bad bad bad */ return CURLM_INTERNAL_ERROR; if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) /* set socket event bitmask if they're not locked */ data->conn->cselect_bits = ev_bitmask; sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) /* clear the bitmask only if not locked */ data->conn->cselect_bits = 0; if(CURLM_OK >= result) { /* get the socket(s) and check if the state has been changed since last */ result = singlesocket(multi, data); if(result) return result; } } /* Now we fall-through and do the timer-based stuff, since we don't want to force the user to have to deal with timeouts as long as at least one connection in fact has traffic. */ data = NULL; /* set data to NULL again to avoid calling multi_runsingle() in case there's no need to */ now = Curl_now(); /* get a newer time since the multi_runsingle() loop may have taken some time */ } } else { /* Asked to run due to time-out. Clear the 'lastcall' variable to force update_timer() to trigger a callback to the app again even if the same timeout is still the one to run after this call. That handles the case when the application asks libcurl to run the timeout prematurely. */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); } /* * The loop following here will go on as long as there are expire-times left * to process in the splay and 'data' will be re-assigned for every expired * handle we deal with. */ do { /* the first loop lap 'data' can be NULL */ if(data) { SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(CURLM_OK >= result) { /* get the socket(s) and check if the state has been changed since last */ result = singlesocket(multi, data); if(result) return result; } } /* Check if there's one (more) expired timer to deal with! This function extracts a matching node if there is one */ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) { data = t->payload; /* assign this for next loop */ (void)add_next_timeout(now, multi, t->payload); } } while(t); *running_handles = multi->num_alive; return result; } #undef curl_multi_setopt CURLMcode curl_multi_setopt(struct Curl_multi *multi, CURLMoption option, ...) { CURLMcode res = CURLM_OK; va_list param; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; va_start(param, option); switch(option) { case CURLMOPT_SOCKETFUNCTION: multi->socket_cb = va_arg(param, curl_socket_callback); break; case CURLMOPT_SOCKETDATA: multi->socket_userp = va_arg(param, void *); break; case CURLMOPT_PUSHFUNCTION: multi->push_cb = va_arg(param, curl_push_callback); break; case CURLMOPT_PUSHDATA: multi->push_userp = va_arg(param, void *); break; case CURLMOPT_PIPELINING: multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX; break; case CURLMOPT_TIMERFUNCTION: multi->timer_cb = va_arg(param, curl_multi_timer_callback); break; case CURLMOPT_TIMERDATA: multi->timer_userp = va_arg(param, void *); break; case CURLMOPT_MAXCONNECTS: multi->maxconnects = va_arg(param, long); break; case CURLMOPT_MAX_HOST_CONNECTIONS: multi->max_host_connections = va_arg(param, long); break; case CURLMOPT_MAX_TOTAL_CONNECTIONS: multi->max_total_connections = va_arg(param, long); break; /* options formerly used for pipelining */ case CURLMOPT_MAX_PIPELINE_LENGTH: break; case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE: break; case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE: break; case CURLMOPT_PIPELINING_SITE_BL: break; case CURLMOPT_PIPELINING_SERVER_BL: break; default: res = CURLM_UNKNOWN_OPTION; break; } va_end(param); return res; } /* we define curl_multi_socket() in the public multi.h header */ #undef curl_multi_socket CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, 0, running_handles); if(CURLM_OK >= result) update_timer(multi); return result; } CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); if(CURLM_OK >= result) update_timer(multi); return result; } CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles); if(CURLM_OK >= result) update_timer(multi); return result; } static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms) { static struct curltime tv_zero = {0, 0}; if(multi->timetree) { /* we have a tree of expire times */ struct curltime now = Curl_now(); /* splay the lowest to the bottom */ multi->timetree = Curl_splay(tv_zero, multi->timetree); if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) { /* some time left before expiration */ timediff_t diff = Curl_timediff(multi->timetree->key, now); if(diff <= 0) /* * Since we only provide millisecond resolution on the returned value * and the diff might be less than one millisecond here, we don't * return zero as that may cause short bursts of busyloops on fast * processors while the diff is still present but less than one * millisecond! instead we return 1 until the time is ripe. */ *timeout_ms = 1; else /* this should be safe even on 64 bit archs, as we don't use that overly long timeouts */ *timeout_ms = (long)diff; } else /* 0 means immediately */ *timeout_ms = 0; } else *timeout_ms = -1; return CURLM_OK; } CURLMcode curl_multi_timeout(struct Curl_multi *multi, long *timeout_ms) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; return multi_timeout(multi, timeout_ms); } /* * Tell the application it should update its timers, if it subscribes to the * update timer callback. */ static int update_timer(struct Curl_multi *multi) { long timeout_ms; if(!multi->timer_cb) return 0; if(multi_timeout(multi, &timeout_ms)) { return -1; } if(timeout_ms < 0) { static const struct curltime none = {0, 0}; if(Curl_splaycomparekeys(none, multi->timer_lastcall)) { multi->timer_lastcall = none; /* there's no timeout now but there was one previously, tell the app to disable it */ return multi->timer_cb(multi, -1, multi->timer_userp); } return 0; } /* When multi_timeout() is done, multi->timetree points to the node with the * timeout we got the (relative) time-out time for. We can thus easily check * if this is the same (fixed) time as we got in a previous call and then * avoid calling the callback again. */ if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0) return 0; multi->timer_lastcall = multi->timetree->key; return multi->timer_cb(multi, timeout_ms, multi->timer_userp); } /* * multi_deltimeout() * * Remove a given timestamp from the list of timeouts. */ static void multi_deltimeout(struct Curl_easy *data, expire_id eid) { struct curl_llist_element *e; struct curl_llist *timeoutlist = &data->state.timeoutlist; /* find and remove the specific node from the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *n = (struct time_node *)e->ptr; if(n->eid == eid) { Curl_llist_remove(timeoutlist, e, NULL); return; } } } /* * multi_addtimeout() * * Add a timestamp to the list of timeouts. Keep the list sorted so that head * of list is always the timeout nearest in time. * */ static CURLMcode multi_addtimeout(struct Curl_easy *data, struct curltime *stamp, expire_id eid) { struct curl_llist_element *e; struct time_node *node; struct curl_llist_element *prev = NULL; size_t n; struct curl_llist *timeoutlist = &data->state.timeoutlist; node = &data->state.expires[eid]; /* copy the timestamp and id */ memcpy(&node->time, stamp, sizeof(*stamp)); node->eid = eid; /* also marks it as in use */ n = Curl_llist_count(timeoutlist); if(n) { /* find the correct spot in the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *check = (struct time_node *)e->ptr; timediff_t diff = Curl_timediff(check->time, node->time); if(diff > 0) break; prev = e; } } /* else this is the first timeout on the list */ Curl_llist_insert_next(timeoutlist, prev, node, &node->list); return CURLM_OK; } /* * Curl_expire() * * given a number of milliseconds from now to use to set the 'act before * this'-time for the transfer, to be extracted by curl_multi_timeout() * * The timeout will be added to a queue of timeouts if it defines a moment in * time that is later than the current head of queue. * * Expire replaces a former timeout using the same id if already set. */ void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; struct curltime set; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; DEBUGASSERT(id < EXPIRE_LAST); set = Curl_now(); set.tv_sec += milli/1000; set.tv_usec += (unsigned int)(milli%1000)*1000; if(set.tv_usec >= 1000000) { set.tv_sec++; set.tv_usec -= 1000000; } /* Remove any timer with the same id just in case. */ multi_deltimeout(data, id); /* Add it to the timer list. It must stay in the list until it has expired in case we need to recompute the minimum timer later. */ multi_addtimeout(data, &set, id); if(nowp->tv_sec || nowp->tv_usec) { /* This means that the struct is added as a node in the splay tree. Compare if the new time is earlier, and only remove-old/add-new if it is. */ timediff_t diff = Curl_timediff(set, *nowp); int rc; if(diff > 0) { /* The current splay tree entry is sooner than this new expiry time. We don't need to update our splay tree entry. */ return; } /* Since this is an updated time, we must remove the previous entry from the splay tree first and then re-add the new value */ rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error removing splay node = %d\n", rc); } /* Indicate that we are in the splay tree and insert the new timer expiry value since it is our local minimum. */ *nowp = set; data->state.timenode.payload = data; multi->timetree = Curl_splayinsert(*nowp, multi->timetree, &data->state.timenode); } /* * Curl_expire_done() * * Removes the expire timer. Marks it as done. * */ void Curl_expire_done(struct Curl_easy *data, expire_id id) { /* remove the timer, if there */ multi_deltimeout(data, id); } /* * Curl_expire_clear() * * Clear ALL timeout values for this handle. */ void Curl_expire_clear(struct Curl_easy *data) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; if(nowp->tv_sec || nowp->tv_usec) { /* Since this is an cleared time, we must remove the previous entry from the splay tree */ struct curl_llist *list = &data->state.timeoutlist; int rc; rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error clearing splay node = %d\n", rc); /* flush the timeout list too */ while(list->size > 0) { Curl_llist_remove(list, list->tail, NULL); } #ifdef DEBUGBUILD infof(data, "Expire cleared (transfer %p)\n", data); #endif nowp->tv_sec = 0; nowp->tv_usec = 0; } } CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, void *hashp) { struct Curl_sh_entry *there = NULL; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; there = sh_getentry(&multi->sockhash, s); if(!there) return CURLM_BAD_SOCKET; there->socketp = hashp; return CURLM_OK; } size_t Curl_multi_max_host_connections(struct Curl_multi *multi) { return multi ? multi->max_host_connections : 0; } size_t Curl_multi_max_total_connections(struct Curl_multi *multi) { return multi ? multi->max_total_connections : 0; } /* * When information about a connection has appeared, call this! */ void Curl_multiuse_state(struct connectdata *conn, int bundlestate) /* use BUNDLE_* defines */ { DEBUGASSERT(conn); DEBUGASSERT(conn->bundle); DEBUGASSERT(conn->data); DEBUGASSERT(conn->data->multi); conn->bundle->multiuse = bundlestate; process_pending_handles(conn->data->multi); } static void process_pending_handles(struct Curl_multi *multi) { struct curl_llist_element *e = multi->pending.head; if(e) { struct Curl_easy *data = e->ptr; DEBUGASSERT(data->mstate == CURLM_STATE_CONNECT_PEND); multistate(data, CURLM_STATE_CONNECT); /* Remove this node from the list */ Curl_llist_remove(&multi->pending, e, NULL); /* Make sure that the handle will be processed soonish. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* mark this as having been in the pending queue */ data->state.previouslypending = TRUE; } } void Curl_set_in_callback(struct Curl_easy *data, bool value) { /* might get called when there is no data pointer! */ if(data) { if(data->multi_easy) data->multi_easy->in_callback = value; else if(data->multi) data->multi->in_callback = value; } } bool Curl_is_in_callback(struct Curl_easy *easy) { return ((easy->multi && easy->multi->in_callback) || (easy->multi_easy && easy->multi_easy->in_callback)); } #ifdef DEBUGBUILD void Curl_multi_dump(struct Curl_multi *multi) { struct Curl_easy *data; int i; fprintf(stderr, "* Multi status: %d handles, %d alive\n", multi->num_easy, multi->num_alive); for(data = multi->easyp; data; data = data->next) { if(data->mstate < CURLM_STATE_COMPLETED) { /* only display handles that are not completed */ fprintf(stderr, "handle %p, state %s, %d sockets\n", (void *)data, statename[data->mstate], data->numsocks); for(i = 0; i < data->numsocks; i++) { curl_socket_t s = data->sockets[i]; struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); fprintf(stderr, "%d ", (int)s); if(!entry) { fprintf(stderr, "INTERNAL CONFUSION\n"); continue; } fprintf(stderr, "[%s %s] ", (entry->action&CURL_POLL_IN)?"RECVING":"", (entry->action&CURL_POLL_OUT)?"SENDING":""); } if(data->numsocks) fprintf(stderr, "\n"); } } } #endif
YifuLiu/AliOS-Things
components/curl/lib/multi.c
C
apache-2.0
95,565
#ifndef HEADER_CURL_MULTIHANDLE_H #define HEADER_CURL_MULTIHANDLE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "conncache.h" #include "psl.h" 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 { CURLM_STATE_INIT, /* 0 - start in this state */ CURLM_STATE_CONNECT_PEND, /* 1 - no connections, waiting for one */ CURLM_STATE_CONNECT, /* 2 - resolve/connect has been sent off */ CURLM_STATE_WAITRESOLVE, /* 3 - awaiting the resolve to finalize */ CURLM_STATE_WAITCONNECT, /* 4 - awaiting the TCP connect to finalize */ CURLM_STATE_WAITPROXYCONNECT, /* 5 - awaiting HTTPS proxy SSL initialization to complete and/or proxy CONNECT to finalize */ CURLM_STATE_SENDPROTOCONNECT, /* 6 - initiate protocol connect procedure */ CURLM_STATE_PROTOCONNECT, /* 7 - completing the protocol-specific connect phase */ CURLM_STATE_DO, /* 8 - start send off the request (part 1) */ CURLM_STATE_DOING, /* 9 - sending off the request (part 1) */ CURLM_STATE_DO_MORE, /* 10 - send off the request (part 2) */ CURLM_STATE_DO_DONE, /* 11 - done sending off request */ CURLM_STATE_PERFORM, /* 12 - transfer data */ CURLM_STATE_TOOFAST, /* 13 - wait because limit-rate exceeded */ CURLM_STATE_DONE, /* 14 - post data transfer operation */ CURLM_STATE_COMPLETED, /* 15 - operation complete */ CURLM_STATE_MSGSENT, /* 16 - the operation complete message is sent */ CURLM_STATE_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) /* 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. */ long type; /* We have a doubly-linked circular 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 CURLM_STATE_CONNECT_PEND 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; /* multiplexing wanted */ bool multiplexing; bool recheckstate; /* see Curl_multi_connchanged */ /* 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 */ bool in_callback; /* true while executing a callback */ }; #endif /* HEADER_CURL_MULTIHANDLE_H */
YifuLiu/AliOS-Things
components/curl/lib/multihandle.h
C
apache-2.0
5,540
#ifndef HEADER_CURL_MULTIIF_H #define HEADER_CURL_MULTIIF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Prototypes for library-wide functions provided by multi.c */ void Curl_updatesocket(struct Curl_easy *data); void Curl_expire(struct Curl_easy *data, time_t milli, expire_id); void Curl_expire_clear(struct Curl_easy *data); void Curl_expire_done(struct Curl_easy *data, expire_id id); void Curl_detach_connnection(struct Curl_easy *data); void Curl_attach_connnection(struct Curl_easy *data, struct connectdata *conn); bool Curl_multiplex_wanted(const struct Curl_multi *multi); void Curl_set_in_callback(struct Curl_easy *data, bool value); bool Curl_is_in_callback(struct Curl_easy *easy); /* Internal version of curl_multi_init() accepts size parameters for the socket and connection hashes */ struct Curl_multi *Curl_multi_handle(int hashsize, int chashsize); /* the write bits start at bit 16 for the *getsock() bitmap */ #define GETSOCK_WRITEBITSTART 16 #define GETSOCK_BLANK 0 /* no bits set */ /* set the bit for the given sock number to make the bitmap for writable */ #define GETSOCK_WRITESOCK(x) (1 << (GETSOCK_WRITEBITSTART + (x))) /* set the bit for the given sock number to make the bitmap for readable */ #define GETSOCK_READSOCK(x) (1 << (x)) #ifdef DEBUGBUILD /* * Curl_multi_dump is not a stable public function, this is only meant to * allow easier tracking of the internal handle's state and what sockets * they use. Only for research and development DEBUGBUILD enabled builds. */ void Curl_multi_dump(struct Curl_multi *multi); #endif /* Return the value of the CURLMOPT_MAX_HOST_CONNECTIONS option */ size_t Curl_multi_max_host_connections(struct Curl_multi *multi); /* Return the value of the CURLMOPT_MAX_TOTAL_CONNECTIONS option */ size_t Curl_multi_max_total_connections(struct Curl_multi *multi); void Curl_multiuse_state(struct connectdata *conn, int bundlestate); /* use BUNDLE_* defines */ /* * Curl_multi_closed() * * Used by the connect code to tell the multi_socket code that one of the * sockets we were using is about to be closed. This function will then * remove it from the sockethash for this handle to make the multi_socket API * behave properly, especially for the case when libcurl will create another * socket again and it gets the same file descriptor number. */ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s); /* * Add a handle and move it into PERFORM state at once. For pushed streams. */ CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, struct Curl_easy *data, struct connectdata *conn); CURLMcode Curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret, bool *gotsocket); /* if any socket was checked */ #endif /* HEADER_CURL_MULTIIF_H */
YifuLiu/AliOS-Things
components/curl/lib/multiif.h
C
apache-2.0
4,065
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_NETRC #ifdef HAVE_PWD_H #include <pwd.h> #endif #include <curl/curl.h> #include "netrc.h" #include "strtok.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" /* Get user and password from .netrc when given a machine name */ enum host_lookup_state { NOTHING, HOSTFOUND, /* the 'machine' keyword was found */ HOSTVALID /* this is "our" machine! */ }; /* * @unittest: 1304 * * *loginp and *passwordp MUST be allocated if they aren't NULL when passed * in. */ int Curl_parsenetrc(const char *host, char **loginp, char **passwordp, bool *login_changed, bool *password_changed, char *netrcfile) { FILE *file; int retcode = 1; char *login = *loginp; char *password = *passwordp; bool specific_login = (login && *login != 0); bool login_alloc = FALSE; bool password_alloc = FALSE; bool netrc_alloc = FALSE; enum host_lookup_state state = NOTHING; char state_login = 0; /* Found a login keyword */ char state_password = 0; /* Found a password keyword */ int state_our_login = FALSE; /* With specific_login, found *our* login name */ #define NETRC DOT_CHAR "netrc" if(!netrcfile) { bool home_alloc = FALSE; char *home = curl_getenv("HOME"); /* portable environment reader */ if(home) { home_alloc = TRUE; #if defined(HAVE_GETPWUID_R) && defined(HAVE_GETEUID) } else { struct passwd pw, *pw_res; char pwbuf[1024]; if(!getpwuid_r(geteuid(), &pw, pwbuf, sizeof(pwbuf), &pw_res) && pw_res) { home = strdup(pw.pw_dir); if(!home) return CURLE_OUT_OF_MEMORY; home_alloc = TRUE; } #elif defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) } else { struct passwd *pw; pw = getpwuid(geteuid()); if(pw) { home = pw->pw_dir; } #endif } if(!home) return retcode; /* no home directory found (or possibly out of memory) */ netrcfile = curl_maprintf("%s%s%s", home, DIR_CHAR, NETRC); if(home_alloc) free(home); if(!netrcfile) { return -1; } netrc_alloc = TRUE; } file = fopen(netrcfile, FOPEN_READTEXT); if(netrc_alloc) free(netrcfile); if(file) { char *tok; char *tok_buf; bool done = FALSE; char netrcbuffer[4096]; int netrcbuffsize = (int)sizeof(netrcbuffer); while(!done && fgets(netrcbuffer, netrcbuffsize, file)) { tok = strtok_r(netrcbuffer, " \t\n", &tok_buf); if(tok && *tok == '#') /* treat an initial hash as a comment line */ continue; while(!done && tok) { if((login && *login) && (password && *password)) { done = TRUE; break; } switch(state) { case NOTHING: if(strcasecompare("machine", tok)) { /* the next tok is the machine name, this is in itself the delimiter that starts the stuff entered for this machine, after this we need to search for 'login' and 'password'. */ state = HOSTFOUND; } else if(strcasecompare("default", tok)) { state = HOSTVALID; retcode = 0; /* we did find our host */ } break; case HOSTFOUND: if(strcasecompare(host, tok)) { /* and yes, this is our host! */ state = HOSTVALID; retcode = 0; /* we did find our host */ } else /* not our host */ state = NOTHING; break; case HOSTVALID: /* we are now parsing sub-keywords concerning "our" host */ if(state_login) { if(specific_login) { state_our_login = strcasecompare(login, tok); } else if(!login || strcmp(login, tok)) { if(login_alloc) { free(login); login_alloc = FALSE; } login = strdup(tok); if(!login) { retcode = -1; /* allocation failed */ goto out; } login_alloc = TRUE; } state_login = 0; } else if(state_password) { if((state_our_login || !specific_login) && (!password || strcmp(password, tok))) { if(password_alloc) { free(password); password_alloc = FALSE; } password = strdup(tok); if(!password) { retcode = -1; /* allocation failed */ goto out; } password_alloc = TRUE; } state_password = 0; } else if(strcasecompare("login", tok)) state_login = 1; else if(strcasecompare("password", tok)) state_password = 1; else if(strcasecompare("machine", tok)) { /* ok, there's machine here go => */ state = HOSTFOUND; state_our_login = FALSE; } break; } /* switch (state) */ tok = strtok_r(NULL, " \t\n", &tok_buf); } /* while(tok) */ } /* while fgets() */ out: if(!retcode) { *login_changed = FALSE; *password_changed = FALSE; if(login_alloc) { if(*loginp) free(*loginp); *loginp = login; *login_changed = TRUE; } if(password_alloc) { if(*passwordp) free(*passwordp); *passwordp = password; *password_changed = TRUE; } } else { if(login_alloc) free(login); if(password_alloc) free(password); } fclose(file); } return retcode; } #endif
YifuLiu/AliOS-Things
components/curl/lib/netrc.c
C
apache-2.0
7,009
#ifndef HEADER_CURL_NETRC_H #define HEADER_CURL_NETRC_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */
YifuLiu/AliOS-Things
components/curl/lib/netrc.h
C
apache-2.0
1,773
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 "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; /* 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, strerror(errno)); 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 != 0)) { failf(data, "The Curl_convert_to_network iconv call failed with errno %i: %s", errno, strerror(errno)); 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; /* 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, strerror(errno)); 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 != 0)) { failf(data, "Curl_convert_from_network iconv call failed with errno %i: %s", errno, strerror(errno)); 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; /* 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, strerror(errno)); 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 != 0)) { failf(data, "The Curl_convert_from_utf8 iconv call failed with errno %i: %s", errno, strerror(errno)); 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 */
YifuLiu/AliOS-Things
components/curl/lib/non-ascii.c
C
apache-2.0
9,786
#ifndef HEADER_CURL_NON_ASCII_H #define HEADER_CURL_NON_ASCII_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef CURL_DOES_CONVERSIONS #include "urldata.h" /* * Curl_convert_clone() returns a malloced copy of the source string (if * returning CURLE_OK), with the data converted to network format. * * If no conversion was needed *outbuf may be NULL. */ CURLcode Curl_convert_clone(struct Curl_easy *data, const char *indata, size_t insize, char **outbuf); void Curl_convert_init(struct Curl_easy *data); void Curl_convert_setup(struct Curl_easy *data); void Curl_convert_close(struct Curl_easy *data); CURLcode Curl_convert_to_network(struct Curl_easy *data, char *buffer, size_t length); CURLcode Curl_convert_from_network(struct Curl_easy *data, char *buffer, size_t length); CURLcode Curl_convert_from_utf8(struct Curl_easy *data, char *buffer, size_t length); #else #define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK) #define Curl_convert_init(x) Curl_nop_stmt #define Curl_convert_setup(x) Curl_nop_stmt #define Curl_convert_close(x) Curl_nop_stmt #define Curl_convert_to_network(a,b,c) ((void)a, CURLE_OK) #define Curl_convert_from_network(a,b,c) ((void)a, CURLE_OK) #define Curl_convert_from_utf8(a,b,c) ((void)a, CURLE_OK) #endif #endif /* HEADER_CURL_NON_ASCII_H */
YifuLiu/AliOS-Things
components/curl/lib/non-ascii.h
C
apache-2.0
2,481
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE)) #include <sys/filio.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #include "nonblock.h" /* * curlx_nonblock() set the given socket to either blocking or non-blocking * mode based on the 'nonblock' boolean argument. This function is highly * portable. */ int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ int nonblock /* TRUE or FALSE */) { #if defined(USE_BLOCKING_SOCKETS) (void)sockfd; (void)nonblock; return 0; /* returns success */ #elif defined(HAVE_FCNTL_O_NONBLOCK) /* most recent unix versions */ int flags; flags = sfcntl(sockfd, F_GETFL, 0); if(nonblock) return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK); return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK)); #elif defined(HAVE_IOCTL_FIONBIO) /* older unix versions */ int flags = nonblock ? 1 : 0; return ioctl(sockfd, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_FIONBIO) /* Windows */ unsigned long flags = nonblock ? 1UL : 0UL; return ioctlsocket(sockfd, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) /* Amiga */ long flags = nonblock ? 1L : 0L; return IoctlSocket(sockfd, FIONBIO, (char *)&flags); #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) /* BeOS */ long b = nonblock ? 1L : 0L; return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); #else # error "no non-blocking method was found/used/set" #endif }
YifuLiu/AliOS-Things
components/curl/lib/nonblock.c
C
apache-2.0
2,629
#ifndef HEADER_CURL_NONBLOCK_H #define HEADER_CURL_NONBLOCK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> /* for curl_socket_t */ int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ int nonblock /* TRUE or FALSE */); #endif /* HEADER_CURL_NONBLOCK_H */
YifuLiu/AliOS-Things
components/curl/lib/nonblock.h
C
apache-2.0
1,296
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef NETWARE /* Novell NetWare */ #ifdef __NOVELL_LIBC__ /* For native LibC-based NLM we need to register as a real lib. */ #include <library.h> #include <netware.h> #include <screen.h> #include <nks/thread.h> #include <nks/synch.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef struct { int _errno; void *twentybytes; } libthreaddata_t; typedef struct { int x; int y; int z; void *tenbytes; NXKey_t perthreadkey; /* if -1, no key obtained... */ NXMutex_t *lock; } libdata_t; int gLibId = -1; void *gLibHandle = (void *) NULL; rtag_t gAllocTag = (rtag_t) NULL; NXMutex_t *gLibLock = (NXMutex_t *) NULL; /* internal library function prototypes... */ int DisposeLibraryData(void *); void DisposeThreadData(void *); int GetOrSetUpData(int id, libdata_t **data, libthreaddata_t **threaddata); int _NonAppStart(void *NLMHandle, void *errorScreen, const char *cmdLine, const char *loadDirPath, size_t uninitializedDataLength, void *NLMFileHandle, int (*readRoutineP)(int conn, void *fileHandle, size_t offset, size_t nbytes, size_t *bytesRead, void *buffer), size_t customDataOffset, size_t customDataSize, int messageCount, const char **messages) { NX_LOCK_INFO_ALLOC(liblock, "Per-Application Data Lock", 0); #ifndef __GNUC__ #pragma unused(cmdLine) #pragma unused(loadDirPath) #pragma unused(uninitializedDataLength) #pragma unused(NLMFileHandle) #pragma unused(readRoutineP) #pragma unused(customDataOffset) #pragma unused(customDataSize) #pragma unused(messageCount) #pragma unused(messages) #endif /* * Here we process our command line, post errors (to the error screen), * perform initializations and anything else we need to do before being able * to accept calls into us. If we succeed, we return non-zero and the NetWare * Loader will leave us up, otherwise we fail to load and get dumped. */ gAllocTag = AllocateResourceTag(NLMHandle, "<library-name> memory allocations", AllocSignature); if(!gAllocTag) { OutputToScreen(errorScreen, "Unable to allocate resource tag for " "library memory allocations.\n"); return -1; } gLibId = register_library(DisposeLibraryData); if(gLibId < -1) { OutputToScreen(errorScreen, "Unable to register library with kernel.\n"); return -1; } gLibHandle = NLMHandle; gLibLock = NXMutexAlloc(0, 0, &liblock); if(!gLibLock) { OutputToScreen(errorScreen, "Unable to allocate library data lock.\n"); return -1; } return 0; } /* * Here we clean up any resources we allocated. Resource tags is a big part * of what we created, but NetWare doesn't ask us to free those. */ void _NonAppStop(void) { (void) unregister_library(gLibId); NXMutexFree(gLibLock); } /* * This function cannot be the first in the file for if the file is linked * first, then the check-unload function's offset will be nlmname.nlm+0 * which is how to tell that there isn't one. When the check function is * first in the linked objects, it is ambiguous. For this reason, we will * put it inside this file after the stop function. * * Here we check to see if it's alright to ourselves to be unloaded. If not, * we return a non-zero value. Right now, there isn't any reason not to allow * it. */ int _NonAppCheckUnload(void) { return 0; } int GetOrSetUpData(int id, libdata_t **appData, libthreaddata_t **threadData) { int err; libdata_t *app_data; libthreaddata_t *thread_data; NXKey_t key; NX_LOCK_INFO_ALLOC(liblock, "Application Data Lock", 0); err = 0; thread_data = (libthreaddata_t *) NULL; /* * Attempt to get our data for the application calling us. This is where we * store whatever application-specific information we need to carry in * support of calling applications. */ app_data = (libdata_t *) get_app_data(id); if(!app_data) { /* * This application hasn't called us before; set up application AND * per-thread data. Of course, just in case a thread from this same * application is calling us simultaneously, we better lock our application * data-creation mutex. We also need to recheck for data after we acquire * the lock because WE might be that other thread that was too late to * create the data and the first thread in will have created it. */ NXLock(gLibLock); app_data = (libdata_t *) get_app_data(id); if(!app_data) { app_data = calloc(1, sizeof(libdata_t)); if(app_data) { app_data->tenbytes = malloc(10); app_data->lock = NXMutexAlloc(0, 0, &liblock); if(!app_data->tenbytes || !app_data->lock) { if(app_data->lock) NXMutexFree(app_data->lock); free(app_data->tenbytes); free(app_data); app_data = (libdata_t *) NULL; err = ENOMEM; } if(app_data) { /* * Here we burn in the application data that we were trying to get * by calling get_app_data(). Next time we call the first function, * we'll get this data we're just now setting. We also go on here to * establish the per-thread data for the calling thread, something * we'll have to do on each application thread the first time * it calls us. */ err = set_app_data(gLibId, app_data); if(err) { if(app_data->lock) NXMutexFree(app_data->lock); free(app_data->tenbytes); free(app_data); app_data = (libdata_t *) NULL; err = ENOMEM; } else { /* create key for thread-specific data... */ err = NXKeyCreate(DisposeThreadData, (void *) NULL, &key); if(err) /* (no more keys left?) */ key = -1; app_data->perthreadkey = key; } } } } NXUnlock(gLibLock); } if(app_data) { key = app_data->perthreadkey; if(key != -1 /* couldn't create a key? no thread data */ && !(err = NXKeyGetValue(key, (void **) &thread_data)) && !thread_data) { /* * Allocate the per-thread data for the calling thread. Regardless of * whether there was already application data or not, this may be the * first call by a new thread. The fact that we allocation 20 bytes on * a pointer is not very important, this just helps to demonstrate that * we can have arbitrarily complex per-thread data. */ thread_data = malloc(sizeof(libthreaddata_t)); if(thread_data) { thread_data->_errno = 0; thread_data->twentybytes = malloc(20); if(!thread_data->twentybytes) { free(thread_data); thread_data = (libthreaddata_t *) NULL; err = ENOMEM; } err = NXKeySetValue(key, thread_data); if(err) { free(thread_data->twentybytes); free(thread_data); thread_data = (libthreaddata_t *) NULL; } } } } if(appData) *appData = app_data; if(threadData) *threadData = thread_data; return err; } int DisposeLibraryData(void *data) { if(data) { void *tenbytes = ((libdata_t *) data)->tenbytes; free(tenbytes); free(data); } return 0; } void DisposeThreadData(void *data) { if(data) { void *twentybytes = ((libthreaddata_t *) data)->twentybytes; free(twentybytes); free(data); } } #else /* __NOVELL_LIBC__ */ /* For native CLib-based NLM seems we can do a bit more simple. */ #include <nwthread.h> int main(void) { /* initialize any globals here... */ /* do this if any global initializing was done SynchronizeStart(); */ ExitThread(TSR_THREAD, 0); return 0; } #endif /* __NOVELL_LIBC__ */ #else /* NETWARE */ #ifdef __POCC__ # pragma warn(disable:2024) /* Disable warning #2024: Empty input file */ #endif #endif /* NETWARE */
YifuLiu/AliOS-Things
components/curl/lib/nwlib.c
C
apache-2.0
9,645
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef NETWARE /* Novell NetWare */ #ifdef __NOVELL_LIBC__ /* For native LibC-based NLM we need to do nothing. */ int netware_init(void) { return 0; } #else /* __NOVELL_LIBC__ */ /* For native CLib-based NLM we need to initialize the LONG namespace. */ #include <nwnspace.h> #include <nwthread.h> #include <nwadv.h> /* Make the CLIB Ctx stuff link */ #include <netdb.h> NETDB_DEFINE_CONTEXT /* Make the CLIB Inet stuff link */ #include <netinet/in.h> #include <arpa/inet.h> NETINET_DEFINE_CONTEXT int netware_init(void) { int rc = 0; unsigned int myHandle = GetNLMHandle(); /* import UnAugmentAsterisk dynamically for NW4.x compatibility */ void (*pUnAugmentAsterisk)(int) = (void(*)(int)) ImportSymbol(myHandle, "UnAugmentAsterisk"); /* import UseAccurateCaseForPaths dynamically for NW3.x compatibility */ void (*pUseAccurateCaseForPaths)(int) = (void(*)(int)) ImportSymbol(myHandle, "UseAccurateCaseForPaths"); if(pUnAugmentAsterisk) pUnAugmentAsterisk(1); if(pUseAccurateCaseForPaths) pUseAccurateCaseForPaths(1); UnimportSymbol(myHandle, "UnAugmentAsterisk"); UnimportSymbol(myHandle, "UseAccurateCaseForPaths"); /* set long name space */ if((SetCurrentNameSpace(4) == 255)) { rc = 1; } if((SetTargetNameSpace(4) == 255)) { rc = rc + 2; } return rc; } /* dummy function to satisfy newer prelude */ int __init_environment(void) { return 0; } /* dummy function to satisfy newer prelude */ int __deinit_environment(void) { return 0; } #endif /* __NOVELL_LIBC__ */ #endif /* NETWARE */
YifuLiu/AliOS-Things
components/curl/lib/nwos.c
C
apache-2.0
2,621
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010, Howard Chu, <hyc@openldap.org> * Copyright (C) 2011 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 ldap_setup_connection(struct connectdata *conn); static CURLcode ldap_do(struct connectdata *conn, bool *done); static CURLcode ldap_done(struct connectdata *conn, CURLcode, bool); static CURLcode ldap_connect(struct connectdata *conn, bool *done); static CURLcode ldap_connecting(struct connectdata *conn, bool *done); static CURLcode ldap_disconnect(struct connectdata *conn, bool dead); static Curl_recv ldap_recv; /* * LDAP protocol handler. */ const struct Curl_handler Curl_handler_ldap = { "LDAP", /* scheme */ ldap_setup_connection, /* setup_connection */ ldap_do, /* do_it */ ldap_done, /* done */ ZERO_NULL, /* do_more */ ldap_connect, /* connect_it */ ldap_connecting, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ldap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_LDAP, /* defport */ CURLPROTO_LDAP, /* protocol */ PROTOPT_NONE /* flags */ }; #ifdef USE_SSL /* * LDAPS protocol handler. */ const struct Curl_handler Curl_handler_ldaps = { "LDAPS", /* scheme */ ldap_setup_connection, /* setup_connection */ ldap_do, /* do_it */ ldap_done, /* done */ ZERO_NULL, /* do_more */ ldap_connect, /* connect_it */ ldap_connecting, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ldap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_LDAPS, /* defport */ CURLPROTO_LDAP, /* protocol */ 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" }; typedef struct ldapconninfo { LDAP *ld; Curl_recv *recv; /* for stacking SSL handler */ Curl_send *send; int proto; int msgid; bool ssldone; bool sslinst; bool didbind; } ldapconninfo; typedef struct ldapreqinfo { int msgid; int nument; } ldapreqinfo; static CURLcode ldap_setup_connection(struct connectdata *conn) { ldapconninfo *li; LDAPURLDesc *lud; struct Curl_easy *data = conn->data; int rc, proto; CURLcode status; rc = ldap_url_parse(data->change.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(conn->data, "LDAP local: %s", msg); return status; } proto = ldap_pvt_url_scheme2proto(lud->lud_scheme); ldap_free_urldesc(lud); li = calloc(1, sizeof(ldapconninfo)); if(!li) return CURLE_OUT_OF_MEMORY; li->proto = proto; conn->proto.generic = li; connkeep(conn, "OpenLDAP default"); return CURLE_OK; } #ifdef USE_SSL static Sockbuf_IO ldapsb_tls; #endif static CURLcode ldap_connect(struct connectdata *conn, bool *done) { ldapconninfo *li = conn->proto.generic; struct Curl_easy *data = conn->data; 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(conn, FIRSTSOCKET, &li->ssldone); if(result) return result; } #endif return CURLE_OK; } static CURLcode ldap_connecting(struct connectdata *conn, bool *done) { ldapconninfo *li = conn->proto.generic; struct Curl_easy *data = conn->data; 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(conn, 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, conn); 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] = ldap_recv; *done = TRUE; return CURLE_OK; } static CURLcode ldap_disconnect(struct connectdata *conn, bool dead_connection) { ldapconninfo *li = conn->proto.generic; (void) dead_connection; if(li) { if(li->ld) { ldap_unbind_ext(li->ld, NULL, NULL); li->ld = NULL; } conn->proto.generic = NULL; free(li); } return CURLE_OK; } static CURLcode ldap_do(struct connectdata *conn, bool *done) { ldapconninfo *li = conn->proto.generic; ldapreqinfo *lr; CURLcode status = CURLE_OK; int rc = 0; LDAPURLDesc *ludp = NULL; int msgid; struct Curl_easy *data = conn->data; connkeep(conn, "OpenLDAP do"); infof(data, "LDAP local: %s\n", data->change.url); rc = ldap_url_parse(data->change.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(conn->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(ldapreqinfo)); if(!lr) return CURLE_OUT_OF_MEMORY; lr->msgid = msgid; data->req.protop = lr; Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); *done = TRUE; return CURLE_OK; } static CURLcode ldap_done(struct connectdata *conn, CURLcode res, bool premature) { ldapreqinfo *lr = conn->data->req.protop; (void)res; (void)premature; if(lr) { /* if there was a search in progress, abandon it */ if(lr->msgid) { ldapconninfo *li = conn->proto.generic; ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL); lr->msgid = 0; } conn->data->req.protop = NULL; free(lr); } return CURLE_OK; } static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf, size_t len, CURLcode *err) { ldapconninfo *li = conn->proto.generic; struct Curl_easy *data = conn->data; ldapreqinfo *lr = data->req.protop; 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\n", 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(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, bv.bv_len); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, 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 == NULL) break; if(bv.bv_len > 7 && !strncmp(bv.bv_val + bv.bv_len - 7, ";binary", 7)) binary = 1; else binary = 0; if(bvals == NULL) { writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, bv.bv_len); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, 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(conn, CLIENTWRITE_BODY, (char *)"\t", 1); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)bv.bv_val, bv.bv_len); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, 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(conn, CLIENTWRITE_BODY, (char *)": ", 2); if(writeerr) { *err = writeerr; return -1; } data->req.bytecount += 2; if(val_b64_sz > 0) { writeerr = Curl_client_write(conn, 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(conn, CLIENTWRITE_BODY, (char *)" ", 1); if(writeerr) { *err = writeerr; return -1; } writeerr = Curl_client_write(conn, 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(conn, CLIENTWRITE_BODY, (char *)"\n", 0); if(writeerr) { *err = writeerr; return -1; } data->req.bytecount++; } ber_memfree(bvals); writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); if(writeerr) { *err = writeerr; return -1; } data->req.bytecount++; } writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0); 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 connectdata *conn = sbiod->sbiod_pvt; return Curl_ssl_data_pending(conn, FIRSTSOCKET); } return 0; } static ber_slen_t ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len) { struct connectdata *conn = sbiod->sbiod_pvt; ldapconninfo *li = conn->proto.generic; ber_slen_t ret; CURLcode err = CURLE_RECV_ERROR; ret = (li->recv)(conn, 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 connectdata *conn = sbiod->sbiod_pvt; ldapconninfo *li = conn->proto.generic; ber_slen_t ret; CURLcode err = CURLE_SEND_ERROR; ret = (li->send)(conn, 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 */
YifuLiu/AliOS-Things
components/curl/lib/openldap.c
C
apache-2.0
21,430
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* 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 #ifndef CURL_DISABLE_PARSEDATE const char * const Curl_wkday[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; static const char * const weekday[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; const char * const Curl_month[]= { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 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 }; /* this is a clone of 'struct tm' but with all fields we don't need or use cut out */ struct my_tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; /* full year */ }; /* struct tm to time since epoch in GMT time zone. * This is similar to the standard mktime function but for GMT only, and * doesn't suffer from the various bugs and portability problems that * some systems' implementations have. * * Returns 0 on success, otherwise non-zero. */ static void my_timegm(struct my_tm *tm, time_t *t) { static const int month_days_cumulative [12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int month, year, leap_days; year = tm->tm_year; month = tm->tm_mon; if(month < 0) { year += (11 - month) / 12; month = 11 - (11 - month) % 12; } else if(month >= 12) { year -= month / 12; month = month % 12; } leap_days = year - (tm->tm_mon <= 1); leap_days = ((leap_days / 4) - (leap_days / 100) + (leap_days / 400) - (1969 / 4) + (1969 / 100) - (1969 / 400)); *t = ((((time_t) (year - 1970) * 365 + leap_days + month_days_cumulative[month] + tm->tm_mday - 1) * 24 + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_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; struct my_tm tm; 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 */ tm.tm_sec = secnum; tm.tm_min = minnum; tm.tm_hour = hournum; tm.tm_mday = mdaynum; tm.tm_mon = monnum; tm.tm_year = yearnum; /* my_timegm() 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. */ my_timegm(&tm, &t); /* 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_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 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; }
YifuLiu/AliOS-Things
components/curl/lib/parsedate.c
C
apache-2.0
16,737
#ifndef HEADER_CURL_PARSEDATE_H #define HEADER_CURL_PARSEDATE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ extern const char * const Curl_wkday[7]; extern const char * const Curl_month[12]; CURLcode Curl_gmtime(time_t intime, struct tm *store); #endif /* HEADER_CURL_PARSEDATE_H */
YifuLiu/AliOS-Things
components/curl/lib/parsedate.h
C
apache-2.0
1,268
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * 'pingpong' is for generic back-and-forth support functions used by FTP, * IMAP, POP3, SMTP and whatever more that likes them. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include "sendf.h" #include "select.h" #include "progress.h" #include "speedcheck.h" #include "pingpong.h" #include "multiif.h" #include "non-ascii.h" #include "vtls/vtls.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #ifdef USE_PINGPONG /* Returns timeout in ms. 0 or negative number means the timeout has already triggered */ time_t Curl_pp_state_timeout(struct pingpong *pp, bool disconnecting) { struct connectdata *conn = pp->conn; struct Curl_easy *data = conn->data; time_t timeout_ms; /* in milliseconds */ long response_time = (data->set.server_response_timeout)? data->set.server_response_timeout: pp->response_time; /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is supposed to govern the response for any given server response, not for the time from connect to the given server response. */ /* Without a requested timeout, we only wait 'response_time' seconds for the full response to arrive before we bail out */ timeout_ms = response_time - Curl_timediff(Curl_now(), pp->response); /* spent time */ if(data->set.timeout && !disconnecting) { /* if timeout is requested, find out how much remaining time we have */ time_t timeout2_ms = data->set.timeout - /* timeout time */ Curl_timediff(Curl_now(), conn->now); /* spent time */ /* pick the lowest number */ timeout_ms = CURLMIN(timeout_ms, timeout2_ms); } return timeout_ms; } /* * Curl_pp_statemach() */ CURLcode Curl_pp_statemach(struct pingpong *pp, bool block, bool disconnecting) { struct connectdata *conn = pp->conn; curl_socket_t sock = conn->sock[FIRSTSOCKET]; int rc; time_t interval_ms; time_t timeout_ms = Curl_pp_state_timeout(pp, disconnecting); struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; if(timeout_ms <= 0) { failf(data, "server response timeout"); return CURLE_OPERATION_TIMEDOUT; /* already too little time */ } if(block) { interval_ms = 1000; /* use 1 second timeout intervals */ if(timeout_ms < interval_ms) interval_ms = timeout_ms; } else interval_ms = 0; /* immediate */ if(Curl_ssl_data_pending(conn, FIRSTSOCKET)) rc = 1; else if(Curl_pp_moredata(pp)) /* We are receiving and there is data in the cache so just read it */ rc = 1; else if(!pp->sendleft && Curl_ssl_data_pending(conn, FIRSTSOCKET)) /* We are receiving and there is data ready in the SSL library */ rc = 1; else rc = Curl_socket_check(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */ CURL_SOCKET_BAD, pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */ interval_ms); if(block) { /* if we didn't wait, we don't have to spend time on this now */ if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, Curl_now()); if(result) return result; } if(rc == -1) { failf(data, "select/poll error"); result = CURLE_OUT_OF_MEMORY; } else if(rc) result = pp->statemach_act(conn); return result; } /* initialize stuff to prepare for reading a fresh new response */ void Curl_pp_init(struct pingpong *pp) { struct connectdata *conn = pp->conn; pp->nread_resp = 0; pp->linestart_resp = conn->data->state.buffer; pp->pending_resp = TRUE; pp->response = Curl_now(); /* start response time-out now! */ } /*********************************************************************** * * 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 pingpong *pp, const char *fmt, va_list args) { ssize_t bytes_written; size_t write_len; char *fmt_crlf; char *s; CURLcode result; struct connectdata *conn = pp->conn; struct Curl_easy *data; #ifdef HAVE_GSSAPI enum protection_level data_sec; #endif DEBUGASSERT(pp->sendleft == 0); DEBUGASSERT(pp->sendsize == 0); DEBUGASSERT(pp->sendthis == NULL); if(!conn) /* can't send without a connection! */ return CURLE_SEND_ERROR; data = conn->data; fmt_crlf = aprintf("%s\r\n", fmt); /* append a trailing CRLF */ if(!fmt_crlf) return CURLE_OUT_OF_MEMORY; s = vaprintf(fmt_crlf, args); /* trailing CRLF appended */ free(fmt_crlf); if(!s) return CURLE_OUT_OF_MEMORY; bytes_written = 0; write_len = strlen(s); Curl_pp_init(pp); result = Curl_convert_to_network(data, s, write_len); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) { free(s); return result; } #ifdef HAVE_GSSAPI conn->data_prot = PROT_CMD; #endif result = Curl_write(conn, conn->sock[FIRSTSOCKET], s, write_len, &bytes_written); #ifdef HAVE_GSSAPI data_sec = conn->data_prot; DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); conn->data_prot = data_sec; #endif if(result) { free(s); return result; } if(conn->data->set.verbose) Curl_debug(conn->data, CURLINFO_HEADER_OUT, s, (size_t)bytes_written); if(bytes_written != (ssize_t)write_len) { /* the whole chunk was not sent, keep it around and adjust sizes */ pp->sendthis = s; pp->sendsize = write_len; pp->sendleft = write_len - bytes_written; } else { free(s); pp->sendthis = NULL; pp->sendleft = pp->sendsize = 0; pp->response = Curl_now(); } return CURLE_OK; } /*********************************************************************** * * Curl_pp_sendf() * * Send the formatted string as a command to a pingpong server. Note that * the string should not have any CRLF appended, as this function will * append the necessary things itself. * * made to never block */ CURLcode Curl_pp_sendf(struct pingpong *pp, const char *fmt, ...) { CURLcode result; va_list ap; va_start(ap, fmt); result = Curl_pp_vsendf(pp, fmt, ap); va_end(ap); return result; } /* * Curl_pp_readresp() * * Reads a piece of a server response. */ CURLcode Curl_pp_readresp(curl_socket_t sockfd, struct pingpong *pp, int *code, /* return the server code if done */ size_t *size) /* size of the response */ { ssize_t perline; /* count bytes per line */ bool keepon = TRUE; ssize_t gotbytes; char *ptr; struct connectdata *conn = pp->conn; struct Curl_easy *data = conn->data; char * const buf = data->state.buffer; CURLcode result = CURLE_OK; *code = 0; /* 0 for errors or not done */ *size = 0; ptr = buf + pp->nread_resp; /* number of bytes in the current line, so far */ perline = (ssize_t)(ptr-pp->linestart_resp); while((pp->nread_resp < (size_t)data->set.buffer_size) && (keepon && !result)) { if(pp->cache) { /* we had data in the "cache", copy that instead of doing an actual * read * * pp->cache_size is cast to ssize_t here. This should be safe, because * it would have been populated with something of size int to begin * with, even though its datatype may be larger than an int. */ if((ptr + pp->cache_size) > (buf + data->set.buffer_size + 1)) { failf(data, "cached response data too big to handle"); return CURLE_RECV_ERROR; } memcpy(ptr, pp->cache, pp->cache_size); gotbytes = (ssize_t)pp->cache_size; free(pp->cache); /* free the cache */ pp->cache = NULL; /* clear the pointer */ pp->cache_size = 0; /* zero the size just in case */ } else { #ifdef HAVE_GSSAPI enum protection_level prot = conn->data_prot; conn->data_prot = PROT_CLEAR; #endif DEBUGASSERT((ptr + data->set.buffer_size - pp->nread_resp) <= (buf + data->set.buffer_size + 1)); result = Curl_read(conn, sockfd, ptr, data->set.buffer_size - pp->nread_resp, &gotbytes); #ifdef HAVE_GSSAPI DEBUGASSERT(prot > PROT_NONE && prot < PROT_LAST); conn->data_prot = prot; #endif if(result == CURLE_AGAIN) return CURLE_OK; /* return */ if(!result && (gotbytes > 0)) /* convert from the network encoding */ result = Curl_convert_from_network(data, ptr, gotbytes); /* Curl_convert_from_network calls failf if unsuccessful */ if(result) /* Set outer result variable to this error. */ keepon = FALSE; } if(!keepon) ; else if(gotbytes <= 0) { keepon = FALSE; result = CURLE_RECV_ERROR; failf(data, "response reading failed"); } else { /* we got a whole chunk of data, which can be anything from one * byte to a set of lines and possible just a piece of the last * line */ ssize_t i; ssize_t clipamount = 0; bool restart = FALSE; data->req.headerbytecount += (long)gotbytes; pp->nread_resp += gotbytes; for(i = 0; i < gotbytes; ptr++, i++) { perline++; if(*ptr == '\n') { /* a newline is CRLF in pp-talk, so the CR is ignored as the line isn't really terminated until the LF comes */ /* output debug output if that is requested */ #ifdef HAVE_GSSAPI if(!conn->sec_complete) #endif if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, pp->linestart_resp, (size_t)perline); /* * We pass all response-lines to the callback function registered * for "headers". The response lines can be seen as a kind of * headers. */ result = Curl_client_write(conn, CLIENTWRITE_HEADER, pp->linestart_resp, perline); if(result) return result; if(pp->endofresp(conn, pp->linestart_resp, perline, code)) { /* This is the end of the last line, copy the last line to the start of the buffer and zero terminate, for old times sake */ size_t n = ptr - pp->linestart_resp; memmove(buf, pp->linestart_resp, n); buf[n] = 0; /* zero terminate */ keepon = FALSE; pp->linestart_resp = ptr + 1; /* advance pointer */ i++; /* skip this before getting out */ *size = pp->nread_resp; /* size of the response */ pp->nread_resp = 0; /* restart */ break; } perline = 0; /* line starts over here */ pp->linestart_resp = ptr + 1; } } if(!keepon && (i != gotbytes)) { /* We found the end of the response lines, but we didn't parse the full chunk of data we have read from the server. We therefore need to store the rest of the data to be checked on the next invoke as it may actually contain another end of response already! */ clipamount = gotbytes - i; restart = TRUE; DEBUGF(infof(data, "Curl_pp_readresp_ %d bytes of trailing " "server response left\n", (int)clipamount)); } else if(keepon) { if((perline == gotbytes) && (gotbytes > data->set.buffer_size/2)) { /* We got an excessive line without newlines and we need to deal with it. We keep the first bytes of the line then we throw away the rest. */ infof(data, "Excessive server response line length received, " "%zd bytes. Stripping\n", gotbytes); restart = TRUE; /* we keep 40 bytes since all our pingpong protocols are only interested in the first piece */ clipamount = 40; } else if(pp->nread_resp > (size_t)data->set.buffer_size/2) { /* We got a large chunk of data and there's potentially still trailing data to take care of, so we put any such part in the "cache", clear the buffer to make space and restart. */ clipamount = perline; restart = TRUE; } } else if(i == gotbytes) restart = TRUE; if(clipamount) { pp->cache_size = clipamount; pp->cache = malloc(pp->cache_size); if(pp->cache) memcpy(pp->cache, pp->linestart_resp, pp->cache_size); else return CURLE_OUT_OF_MEMORY; } if(restart) { /* now reset a few variables to start over nicely from the start of the big buffer */ pp->nread_resp = 0; /* start over from scratch in the buffer */ ptr = pp->linestart_resp = buf; perline = 0; } } /* there was data */ } /* while there's buffer left and loop is requested */ pp->pending_resp = FALSE; return result; } int Curl_pp_getsock(struct pingpong *pp, curl_socket_t *socks, int numsocks) { struct connectdata *conn = pp->conn; if(!numsocks) return GETSOCK_BLANK; socks[0] = conn->sock[FIRSTSOCKET]; if(pp->sendleft) { /* write mode */ return GETSOCK_WRITESOCK(0); } /* read mode */ return GETSOCK_READSOCK(0); } CURLcode Curl_pp_flushsend(struct pingpong *pp) { /* we have a piece of a command still left to send */ struct connectdata *conn = pp->conn; ssize_t written; curl_socket_t sock = conn->sock[FIRSTSOCKET]; CURLcode result = Curl_write(conn, sock, pp->sendthis + pp->sendsize - pp->sendleft, pp->sendleft, &written); if(result) return result; if(written != (ssize_t)pp->sendleft) { /* only a fraction was sent */ pp->sendleft -= written; } else { free(pp->sendthis); pp->sendthis = NULL; pp->sendleft = pp->sendsize = 0; pp->response = Curl_now(); } return CURLE_OK; } CURLcode Curl_pp_disconnect(struct pingpong *pp) { free(pp->cache); pp->cache = NULL; return CURLE_OK; } bool Curl_pp_moredata(struct pingpong *pp) { return (!pp->sendleft && pp->cache && pp->nread_resp < pp->cache_size) ? TRUE : FALSE; } #endif
YifuLiu/AliOS-Things
components/curl/lib/pingpong.c
C
apache-2.0
15,676
#ifndef HEADER_CURL_PINGPONG_H #define HEADER_CURL_PINGPONG_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 { FTPTRANSFER_BODY, /* yes do transfer a body */ FTPTRANSFER_INFO, /* do still go through to get info/headers */ FTPTRANSFER_NONE, /* don't get anything and don't get info */ FTPTRANSFER_LAST /* end of list marker, never used */ } 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 */ long response_time; /* When no timeout is given, this is the amount of milliseconds we await for a server response. */ struct connectdata *conn; /* points to the connectdata struct that this belongs to */ /* Function pointers the protocols MUST implement and provide for the pingpong layer to function */ CURLcode (*statemach_act)(struct connectdata *conn); bool (*endofresp)(struct connectdata *conn, char *ptr, size_t len, int *code); }; /* * 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 pingpong *pp, bool block, bool disconnecting); /* initialize stuff to prepare for reading a fresh new response */ void Curl_pp_init(struct pingpong *pp); /* Returns timeout in ms. 0 or negative number means the timeout has already triggered */ time_t Curl_pp_state_timeout(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 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 pingpong *pp, const char *fmt, va_list args); /* * Curl_pp_readresp() * * Reads a piece of a server response. */ CURLcode Curl_pp_readresp(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 pingpong *pp); /* call this when a pingpong connection is disconnected */ CURLcode Curl_pp_disconnect(struct pingpong *pp); int Curl_pp_getsock(struct pingpong *pp, curl_socket_t *socks, int numsocks); /*********************************************************************** * * 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 */
YifuLiu/AliOS-Things
components/curl/lib/pingpong.h
C
apache-2.0
5,523
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC1734 POP3 Authentication * RFC1939 POP3 protocol * RFC2195 CRAM-MD5 authentication * RFC2384 POP URL Scheme * RFC2449 POP3 Extension Mechanism * RFC2595 Using TLS with IMAP, POP3 and ACAP * RFC2831 DIGEST-MD5 authentication * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * RFC5034 POP3 SASL Authentication Mechanism * RFC6749 OAuth 2.0 Authorization Framework * RFC8314 Use of TLS for Email Submission and Access * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_POP3 #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "socks.h" #include "pop3.h" #include "strtoofft.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "select.h" #include "multiif.h" #include "url.h" #include "curl_sasl.h" #include "curl_md5.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" /* Local API functions */ static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *done); static CURLcode pop3_do(struct connectdata *conn, bool *done); static CURLcode pop3_done(struct connectdata *conn, CURLcode status, bool premature); static CURLcode pop3_connect(struct connectdata *conn, bool *done); static CURLcode pop3_disconnect(struct connectdata *conn, bool dead); static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done); static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done); static CURLcode pop3_setup_connection(struct connectdata *conn); static CURLcode pop3_parse_url_options(struct connectdata *conn); static CURLcode pop3_parse_url_path(struct connectdata *conn); static CURLcode pop3_parse_custom_request(struct connectdata *conn); static CURLcode pop3_perform_auth(struct connectdata *conn, const char *mech, const char *initresp); static CURLcode pop3_continue_auth(struct connectdata *conn, const char *resp); static void pop3_get_message(char *buffer, char **outptr); /* * POP3 protocol handler. */ const struct Curl_handler Curl_handler_pop3 = { "POP3", /* scheme */ pop3_setup_connection, /* setup_connection */ pop3_do, /* do_it */ pop3_done, /* done */ ZERO_NULL, /* do_more */ pop3_connect, /* connect_it */ pop3_multi_statemach, /* connecting */ pop3_doing, /* doing */ pop3_getsock, /* proto_getsock */ pop3_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ pop3_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_POP3, /* defport */ CURLPROTO_POP3, /* protocol */ PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ PROTOPT_URLOPTIONS }; #ifdef USE_SSL /* * POP3S protocol handler. */ const struct Curl_handler Curl_handler_pop3s = { "POP3S", /* scheme */ pop3_setup_connection, /* setup_connection */ pop3_do, /* do_it */ pop3_done, /* done */ ZERO_NULL, /* do_more */ pop3_connect, /* connect_it */ pop3_multi_statemach, /* connecting */ pop3_doing, /* doing */ pop3_getsock, /* proto_getsock */ pop3_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ pop3_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_POP3S, /* defport */ CURLPROTO_POP3S, /* protocol */ PROTOPT_CLOSEACTION | PROTOPT_SSL | PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */ }; #endif /* SASL parameters for the pop3 protocol */ static const struct SASLproto saslpop3 = { "pop", /* The service name */ '*', /* Code received when continuation is expected */ '+', /* Code to receive upon authentication success */ 255 - 8, /* Maximum initial response length (no max) */ pop3_perform_auth, /* Send authentication command */ pop3_continue_auth, /* Send authentication continuation */ pop3_get_message /* Get SASL response message */ }; #ifdef USE_SSL static void pop3_to_pop3s(struct connectdata *conn) { /* Change the connection handler */ conn->handler = &Curl_handler_pop3s; /* Set the connection's upgraded to TLS flag */ conn->tls_upgraded = TRUE; } #else #define pop3_to_pop3s(x) Curl_nop_stmt #endif /*********************************************************************** * * pop3_endofresp() * * Checks for an ending POP3 status code at the start of the given string, but * also detects the APOP timestamp from the server greeting and various * capabilities from the CAPA response including the supported authentication * types and allowed SASL mechanisms. */ static bool pop3_endofresp(struct connectdata *conn, char *line, size_t len, int *resp) { struct pop3_conn *pop3c = &conn->proto.pop3c; /* Do we have an error response? */ if(len >= 4 && !memcmp("-ERR", line, 4)) { *resp = '-'; return TRUE; } /* Are we processing CAPA command responses? */ if(pop3c->state == POP3_CAPA) { /* Do we have the terminating line? */ if(len >= 1 && line[0] == '.') /* Treat the response as a success */ *resp = '+'; else /* Treat the response as an untagged continuation */ *resp = '*'; return TRUE; } /* Do we have a success response? */ if(len >= 3 && !memcmp("+OK", line, 3)) { *resp = '+'; return TRUE; } /* Do we have a continuation response? */ if(len >= 1 && line[0] == '+') { *resp = '*'; return TRUE; } return FALSE; /* Nothing for us */ } /*********************************************************************** * * pop3_get_message() * * Gets the authentication message from the response buffer. */ static void pop3_get_message(char *buffer, char **outptr) { size_t len = strlen(buffer); char *message = NULL; if(len > 2) { /* Find the start of the message */ len -= 2; for(message = buffer + 2; *message == ' ' || *message == '\t'; message++, len--) ; /* Find the end of the message */ for(; len--;) if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && message[len] != '\t') break; /* Terminate the message */ if(++len) { message[len] = '\0'; } } else /* junk input => zero length output */ message = &buffer[len]; *outptr = message; } /*********************************************************************** * * state() * * This is the ONLY way to change POP3 state! */ static void state(struct connectdata *conn, pop3state newstate) { struct pop3_conn *pop3c = &conn->proto.pop3c; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[] = { "STOP", "SERVERGREET", "CAPA", "STARTTLS", "UPGRADETLS", "AUTH", "APOP", "USER", "PASS", "COMMAND", "QUIT", /* LAST */ }; if(pop3c->state != newstate) infof(conn->data, "POP3 %p state change from %s to %s\n", (void *)pop3c, names[pop3c->state], names[newstate]); #endif pop3c->state = newstate; } /*********************************************************************** * * pop3_perform_capa() * * Sends the CAPA command in order to obtain a list of server side supported * capabilities. */ static CURLcode pop3_perform_capa(struct connectdata *conn) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; pop3c->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ pop3c->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ pop3c->tls_supported = FALSE; /* Clear the TLS capability */ /* Send the CAPA command */ result = Curl_pp_sendf(&pop3c->pp, "%s", "CAPA"); if(!result) state(conn, POP3_CAPA); return result; } /*********************************************************************** * * pop3_perform_starttls() * * Sends the STLS command to start the upgrade to TLS. */ static CURLcode pop3_perform_starttls(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the STLS command */ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "STLS"); if(!result) state(conn, POP3_STARTTLS); return result; } /*********************************************************************** * * pop3_perform_upgrade_tls() * * Performs the upgrade to TLS. */ static CURLcode pop3_perform_upgrade_tls(struct connectdata *conn) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; /* Start the SSL connection */ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone); if(!result) { if(pop3c->state != POP3_UPGRADETLS) state(conn, POP3_UPGRADETLS); if(pop3c->ssldone) { pop3_to_pop3s(conn); result = pop3_perform_capa(conn); } } return result; } /*********************************************************************** * * pop3_perform_user() * * Sends a clear text USER command to authenticate with. */ static CURLcode pop3_perform_user(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Check we have a username and password to authenticate with and end the connect phase if we don't */ if(!conn->bits.user_passwd) { state(conn, POP3_STOP); return result; } /* Send the USER command */ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "USER %s", conn->user ? conn->user : ""); if(!result) state(conn, POP3_USER); return result; } #ifndef CURL_DISABLE_CRYPTO_AUTH /*********************************************************************** * * pop3_perform_apop() * * Sends an APOP command to authenticate with. */ static CURLcode pop3_perform_apop(struct connectdata *conn) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; size_t i; MD5_context *ctxt; unsigned char digest[MD5_DIGEST_LEN]; char secret[2 * MD5_DIGEST_LEN + 1]; /* Check we have a username and password to authenticate with and end the connect phase if we don't */ if(!conn->bits.user_passwd) { state(conn, POP3_STOP); return result; } /* Create the digest */ ctxt = Curl_MD5_init(Curl_DIGEST_MD5); if(!ctxt) return CURLE_OUT_OF_MEMORY; Curl_MD5_update(ctxt, (const unsigned char *) pop3c->apoptimestamp, curlx_uztoui(strlen(pop3c->apoptimestamp))); Curl_MD5_update(ctxt, (const unsigned char *) conn->passwd, curlx_uztoui(strlen(conn->passwd))); /* Finalise the digest */ Curl_MD5_final(ctxt, digest); /* Convert the calculated 16 octet digest into a 32 byte hex string */ for(i = 0; i < MD5_DIGEST_LEN; i++) msnprintf(&secret[2 * i], 3, "%02x", digest[i]); result = Curl_pp_sendf(&pop3c->pp, "APOP %s %s", conn->user, secret); if(!result) state(conn, POP3_APOP); return result; } #endif /*********************************************************************** * * pop3_perform_auth() * * Sends an AUTH command allowing the client to login with the given SASL * authentication mechanism. */ static CURLcode pop3_perform_auth(struct connectdata *conn, const char *mech, const char *initresp) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; if(initresp) { /* AUTH <mech> ...<crlf> */ /* Send the AUTH command with the initial response */ result = Curl_pp_sendf(&pop3c->pp, "AUTH %s %s", mech, initresp); } else { /* Send the AUTH command */ result = Curl_pp_sendf(&pop3c->pp, "AUTH %s", mech); } return result; } /*********************************************************************** * * pop3_continue_auth() * * Sends SASL continuation data or cancellation. */ static CURLcode pop3_continue_auth(struct connectdata *conn, const char *resp) { struct pop3_conn *pop3c = &conn->proto.pop3c; return Curl_pp_sendf(&pop3c->pp, "%s", resp); } /*********************************************************************** * * pop3_perform_authentication() * * Initiates the authentication sequence, with the appropriate SASL * authentication mechanism, falling back to APOP and clear text should a * common mechanism not be available between the client and server. */ static CURLcode pop3_perform_authentication(struct connectdata *conn) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; saslprogress progress = SASL_IDLE; /* Check we have enough data to authenticate with and end the connect phase if we don't */ if(!Curl_sasl_can_authenticate(&pop3c->sasl, conn)) { state(conn, POP3_STOP); return result; } if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_SASL) { /* Calculate the SASL login details */ result = Curl_sasl_start(&pop3c->sasl, conn, FALSE, &progress); if(!result) if(progress == SASL_INPROGRESS) state(conn, POP3_AUTH); } if(!result && progress == SASL_IDLE) { #ifndef CURL_DISABLE_CRYPTO_AUTH if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) /* Perform APOP authentication */ result = pop3_perform_apop(conn); else #endif if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) /* Perform clear text authentication */ result = pop3_perform_user(conn); else { /* Other mechanisms not supported */ infof(conn->data, "No known authentication mechanisms supported!\n"); result = CURLE_LOGIN_DENIED; } } return result; } /*********************************************************************** * * pop3_perform_command() * * Sends a POP3 based command. */ static CURLcode pop3_perform_command(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *command = NULL; /* Calculate the default command */ if(pop3->id[0] == '\0' || conn->data->set.ftp_list_only) { command = "LIST"; if(pop3->id[0] != '\0') /* Message specific LIST so skip the BODY transfer */ pop3->transfer = FTPTRANSFER_INFO; } else command = "RETR"; /* Send the command */ if(pop3->id[0] != '\0') result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s %s", (pop3->custom && pop3->custom[0] != '\0' ? pop3->custom : command), pop3->id); else result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", (pop3->custom && pop3->custom[0] != '\0' ? pop3->custom : command)); if(!result) state(conn, POP3_COMMAND); return result; } /*********************************************************************** * * pop3_perform_quit() * * Performs the quit action prior to sclose() be called. */ static CURLcode pop3_perform_quit(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the QUIT command */ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "QUIT"); if(!result) state(conn, POP3_QUIT); return result; } /* For the initial server greeting */ static CURLcode pop3_state_servergreet_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; const char *line = data->state.buffer; size_t len = strlen(line); (void)instate; /* no use for this yet */ if(pop3code != '+') { failf(data, "Got unexpected pop3-server response"); result = CURLE_WEIRD_SERVER_REPLY; } else { /* Does the server support APOP authentication? */ if(len >= 4 && line[len - 2] == '>') { /* Look for the APOP timestamp */ size_t i; for(i = 3; i < len - 2; ++i) { if(line[i] == '<') { /* Calculate the length of the timestamp */ size_t timestamplen = len - 1 - i; char *at; if(!timestamplen) break; /* Allocate some memory for the timestamp */ pop3c->apoptimestamp = (char *)calloc(1, timestamplen + 1); if(!pop3c->apoptimestamp) break; /* Copy the timestamp */ memcpy(pop3c->apoptimestamp, line + i, timestamplen); pop3c->apoptimestamp[timestamplen] = '\0'; /* If the timestamp does not contain '@' it is not (as required by RFC-1939) conformant to the RFC-822 message id syntax, and we therefore do not use APOP authentication. */ at = strchr(pop3c->apoptimestamp, '@'); if(!at) Curl_safefree(pop3c->apoptimestamp); else /* Store the APOP capability */ pop3c->authtypes |= POP3_TYPE_APOP; break; } } } result = pop3_perform_capa(conn); } return result; } /* For CAPA responses */ static CURLcode pop3_state_capa_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; const char *line = data->state.buffer; size_t len = strlen(line); (void)instate; /* no use for this yet */ /* Do we have a untagged continuation response? */ if(pop3code == '*') { /* Does the server support the STLS capability? */ if(len >= 4 && !memcmp(line, "STLS", 4)) pop3c->tls_supported = TRUE; /* Does the server support clear text authentication? */ else if(len >= 4 && !memcmp(line, "USER", 4)) pop3c->authtypes |= POP3_TYPE_CLEARTEXT; /* Does the server support SASL based authentication? */ else if(len >= 5 && !memcmp(line, "SASL ", 5)) { pop3c->authtypes |= POP3_TYPE_SASL; /* Advance past the SASL keyword */ line += 5; len -= 5; /* Loop through the data line */ for(;;) { size_t llen; size_t wordlen; unsigned int mechbit; while(len && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { line++; len--; } if(!len) break; /* Extract the word */ for(wordlen = 0; wordlen < len && line[wordlen] != ' ' && line[wordlen] != '\t' && line[wordlen] != '\r' && line[wordlen] != '\n';) wordlen++; /* Test the word for a matching authentication mechanism */ mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); if(mechbit && llen == wordlen) pop3c->sasl.authmechs |= mechbit; line += wordlen; len -= wordlen; } } } else if(pop3code == '+') { if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) { /* We don't have a SSL/TLS connection yet, but SSL is requested */ if(pop3c->tls_supported) /* Switch to TLS connection now */ result = pop3_perform_starttls(conn); else if(data->set.use_ssl == CURLUSESSL_TRY) /* Fallback and carry on with authentication */ result = pop3_perform_authentication(conn); else { failf(data, "STLS not supported."); result = CURLE_USE_SSL_FAILED; } } else result = pop3_perform_authentication(conn); } else { /* Clear text is supported when CAPA isn't recognised */ pop3c->authtypes |= POP3_TYPE_CLEARTEXT; result = pop3_perform_authentication(conn); } return result; } /* For STARTTLS responses */ static CURLcode pop3_state_starttls_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(pop3code != '+') { if(data->set.use_ssl != CURLUSESSL_TRY) { failf(data, "STARTTLS denied"); result = CURLE_USE_SSL_FAILED; } else result = pop3_perform_authentication(conn); } else result = pop3_perform_upgrade_tls(conn); return result; } /* For SASL authentication responses */ static CURLcode pop3_state_auth_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct pop3_conn *pop3c = &conn->proto.pop3c; saslprogress progress; (void)instate; /* no use for this yet */ result = Curl_sasl_continue(&pop3c->sasl, conn, pop3code, &progress); if(!result) switch(progress) { case SASL_DONE: state(conn, POP3_STOP); /* Authenticated */ break; case SASL_IDLE: /* No mechanism left after cancellation */ #ifndef CURL_DISABLE_CRYPTO_AUTH if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_APOP) /* Perform APOP authentication */ result = pop3_perform_apop(conn); else #endif if(pop3c->authtypes & pop3c->preftype & POP3_TYPE_CLEARTEXT) /* Perform clear text authentication */ result = pop3_perform_user(conn); else { failf(data, "Authentication cancelled"); result = CURLE_LOGIN_DENIED; } break; default: break; } return result; } #ifndef CURL_DISABLE_CRYPTO_AUTH /* For APOP responses */ static CURLcode pop3_state_apop_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(pop3code != '+') { failf(data, "Authentication failed: %d", pop3code); result = CURLE_LOGIN_DENIED; } else /* End of connect phase */ state(conn, POP3_STOP); return result; } #endif /* For USER responses */ static CURLcode pop3_state_user_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(pop3code != '+') { failf(data, "Access denied. %c", pop3code); result = CURLE_LOGIN_DENIED; } else /* Send the PASS command */ result = Curl_pp_sendf(&conn->proto.pop3c.pp, "PASS %s", conn->passwd ? conn->passwd : ""); if(!result) state(conn, POP3_PASS); return result; } /* For PASS responses */ static CURLcode pop3_state_pass_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(pop3code != '+') { failf(data, "Access denied. %c", pop3code); result = CURLE_LOGIN_DENIED; } else /* End of connect phase */ state(conn, POP3_STOP); return result; } /* For command responses */ static CURLcode pop3_state_command_resp(struct connectdata *conn, int pop3code, pop3state instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; struct pop3_conn *pop3c = &conn->proto.pop3c; struct pingpong *pp = &pop3c->pp; (void)instate; /* no use for this yet */ if(pop3code != '+') { state(conn, POP3_STOP); return CURLE_RECV_ERROR; } /* This 'OK' line ends with a CR LF pair which is the two first bytes of the EOB string so count this is two matching bytes. This is necessary to make the code detect the EOB if the only data than comes now is %2e CR LF like when there is no body to return. */ pop3c->eob = 2; /* But since this initial CR LF pair is not part of the actual body, we set the strip counter here so that these bytes won't be delivered. */ pop3c->strip = 2; if(pop3->transfer == FTPTRANSFER_BODY) { /* POP3 download */ Curl_setup_transfer(data, FIRSTSOCKET, -1, FALSE, -1); if(pp->cache) { /* The header "cache" contains a bunch of data that is actually body content so send it as such. Note that there may even be additional "headers" after the body */ if(!data->set.opt_no_body) { result = Curl_pop3_write(conn, pp->cache, pp->cache_size); if(result) return result; } /* Free the cache */ Curl_safefree(pp->cache); /* Reset the cache size */ pp->cache_size = 0; } } /* End of DO phase */ state(conn, POP3_STOP); return result; } static CURLcode pop3_statemach_act(struct connectdata *conn) { CURLcode result = CURLE_OK; curl_socket_t sock = conn->sock[FIRSTSOCKET]; int pop3code; struct pop3_conn *pop3c = &conn->proto.pop3c; struct pingpong *pp = &pop3c->pp; size_t nread = 0; /* Busy upgrading the connection; right now all I/O is SSL/TLS, not POP3 */ if(pop3c->state == POP3_UPGRADETLS) return pop3_perform_upgrade_tls(conn); /* Flush any data that needs to be sent */ if(pp->sendleft) return Curl_pp_flushsend(pp); do { /* Read the response from the server */ result = Curl_pp_readresp(sock, pp, &pop3code, &nread); if(result) return result; if(!pop3code) break; /* We have now received a full POP3 server response */ switch(pop3c->state) { case POP3_SERVERGREET: result = pop3_state_servergreet_resp(conn, pop3code, pop3c->state); break; case POP3_CAPA: result = pop3_state_capa_resp(conn, pop3code, pop3c->state); break; case POP3_STARTTLS: result = pop3_state_starttls_resp(conn, pop3code, pop3c->state); break; case POP3_AUTH: result = pop3_state_auth_resp(conn, pop3code, pop3c->state); break; #ifndef CURL_DISABLE_CRYPTO_AUTH case POP3_APOP: result = pop3_state_apop_resp(conn, pop3code, pop3c->state); break; #endif case POP3_USER: result = pop3_state_user_resp(conn, pop3code, pop3c->state); break; case POP3_PASS: result = pop3_state_pass_resp(conn, pop3code, pop3c->state); break; case POP3_COMMAND: result = pop3_state_command_resp(conn, pop3code, pop3c->state); break; case POP3_QUIT: /* fallthrough, just stop! */ default: /* internal error */ state(conn, POP3_STOP); break; } } while(!result && pop3c->state != POP3_STOP && Curl_pp_moredata(pp)); return result; } /* Called repeatedly until done from multi.c */ static CURLcode pop3_multi_statemach(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; if((conn->handler->flags & PROTOPT_SSL) && !pop3c->ssldone) { result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &pop3c->ssldone); if(result || !pop3c->ssldone) return result; } result = Curl_pp_statemach(&pop3c->pp, FALSE, FALSE); *done = (pop3c->state == POP3_STOP) ? TRUE : FALSE; return result; } static CURLcode pop3_block_statemach(struct connectdata *conn, bool disconnecting) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; while(pop3c->state != POP3_STOP && !result) result = Curl_pp_statemach(&pop3c->pp, TRUE, disconnecting); return result; } /* Allocate and initialize the POP3 struct for the current Curl_easy if required */ static CURLcode pop3_init(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct POP3 *pop3; pop3 = data->req.protop = calloc(sizeof(struct POP3), 1); if(!pop3) result = CURLE_OUT_OF_MEMORY; return result; } /* For the POP3 "protocol connect" and "doing" phases only */ static int pop3_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.pop3c.pp, socks, numsocks); } /*********************************************************************** * * pop3_connect() * * This function should do everything that is to be considered a part of the * connection phase. * * The variable 'done' points to will be TRUE if the protocol-layer connect * phase is done when this function returns, or FALSE if not. */ static CURLcode pop3_connect(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; struct pingpong *pp = &pop3c->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections in POP3 */ connkeep(conn, "POP3 default"); /* Set the default response time-out */ pp->response_time = RESP_TIMEOUT; pp->statemach_act = pop3_statemach_act; pp->endofresp = pop3_endofresp; pp->conn = conn; /* Set the default preferred authentication type and mechanism */ pop3c->preftype = POP3_TYPE_ANY; Curl_sasl_init(&pop3c->sasl, &saslpop3); /* Initialise the pingpong layer */ Curl_pp_init(pp); /* Parse the URL options */ result = pop3_parse_url_options(conn); if(result) return result; /* Start off waiting for the server greeting response */ state(conn, POP3_SERVERGREET); result = pop3_multi_statemach(conn, done); return result; } /*********************************************************************** * * pop3_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */ static CURLcode pop3_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; (void)premature; if(!pop3) return CURLE_OK; if(status) { connclose(conn, "POP3 done with bad status"); result = status; /* use the already set error code */ } /* Cleanup our per-request based variables */ Curl_safefree(pop3->id); Curl_safefree(pop3->custom); /* Clear the transfer mode for the next request */ pop3->transfer = FTPTRANSFER_BODY; return result; } /*********************************************************************** * * pop3_perform() * * This is the actual DO function for POP3. Get a message/listing according to * the options previously setup. */ static CURLcode pop3_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { /* This is POP3 and no proxy */ CURLcode result = CURLE_OK; struct POP3 *pop3 = conn->data->req.protop; DEBUGF(infof(conn->data, "DO phase starts\n")); if(conn->data->set.opt_no_body) { /* Requested no body means no transfer */ pop3->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* Start the first command in the DO phase */ result = pop3_perform_command(conn); if(result) return result; /* Run the state-machine */ result = pop3_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; } /*********************************************************************** * * pop3_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (pop3_perform). * * The input argument is already checked for validity. */ static CURLcode pop3_do(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; *done = FALSE; /* default to false */ /* Parse the URL path */ result = pop3_parse_url_path(conn); if(result) return result; /* Parse the custom request */ result = pop3_parse_custom_request(conn); if(result) return result; result = pop3_regular_transfer(conn, done); return result; } /*********************************************************************** * * pop3_disconnect() * * Disconnect from an POP3 server. Cleanup protocol-specific per-connection * resources. BLOCKING. */ static CURLcode pop3_disconnect(struct connectdata *conn, bool dead_connection) { struct pop3_conn *pop3c = &conn->proto.pop3c; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. */ /* The POP3 session may or may not have been allocated/setup at this point! */ if(!dead_connection && pop3c->pp.conn && pop3c->pp.conn->bits.protoconnstart) if(!pop3_perform_quit(conn)) (void)pop3_block_statemach(conn, TRUE); /* ignore errors on QUIT */ /* Disconnect from the server */ Curl_pp_disconnect(&pop3c->pp); /* Cleanup the SASL module */ Curl_sasl_cleanup(conn, pop3c->sasl.authused); /* Cleanup our connection based variables */ Curl_safefree(pop3c->apoptimestamp); return CURLE_OK; } /* Call this when the DO phase has completed */ static CURLcode pop3_dophase_done(struct connectdata *conn, bool connected) { (void)conn; (void)connected; return CURLE_OK; } /* Called from multi.c while DOing */ static CURLcode pop3_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = pop3_multi_statemach(conn, dophase_done); if(result) DEBUGF(infof(conn->data, "DO phase failed\n")); else if(*dophase_done) { result = pop3_dophase_done(conn, FALSE /* not connected */); DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /*********************************************************************** * * pop3_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. */ static CURLcode pop3_regular_transfer(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; bool connected = FALSE; struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; /* Set the progress data */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); /* Carry out the perform */ result = pop3_perform(conn, &connected, dophase_done); /* Perform post DO phase operations if necessary */ if(!result && *dophase_done) result = pop3_dophase_done(conn, connected); return result; } static CURLcode pop3_setup_connection(struct connectdata *conn) { /* Initialise the POP3 layer */ CURLcode result = pop3_init(conn); if(result) return result; /* Clear the TLS upgraded flag */ conn->tls_upgraded = FALSE; return CURLE_OK; } /*********************************************************************** * * pop3_parse_url_options() * * Parse the URL login options. */ static CURLcode pop3_parse_url_options(struct connectdata *conn) { CURLcode result = CURLE_OK; struct pop3_conn *pop3c = &conn->proto.pop3c; const char *ptr = conn->options; pop3c->sasl.resetprefs = TRUE; while(!result && ptr && *ptr) { const char *key = ptr; const char *value; while(*ptr && *ptr != '=') ptr++; value = ptr + 1; while(*ptr && *ptr != ';') ptr++; if(strncasecompare(key, "AUTH=", 5)) { result = Curl_sasl_parse_url_auth_option(&pop3c->sasl, value, ptr - value); if(result && strncasecompare(value, "+APOP", ptr - value)) { pop3c->preftype = POP3_TYPE_APOP; pop3c->sasl.prefmech = SASL_AUTH_NONE; result = CURLE_OK; } } else result = CURLE_URL_MALFORMAT; if(*ptr == ';') ptr++; } if(pop3c->preftype != POP3_TYPE_APOP) switch(pop3c->sasl.prefmech) { case SASL_AUTH_NONE: pop3c->preftype = POP3_TYPE_NONE; break; case SASL_AUTH_DEFAULT: pop3c->preftype = POP3_TYPE_ANY; break; default: pop3c->preftype = POP3_TYPE_SASL; break; } return result; } /*********************************************************************** * * pop3_parse_url_path() * * Parse the URL path into separate path components. */ static CURLcode pop3_parse_url_path(struct connectdata *conn) { /* The POP3 struct is already initialised in pop3_connect() */ struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *path = &data->state.up.path[1]; /* skip leading path */ /* URL decode the path for the message ID */ return Curl_urldecode(data, path, 0, &pop3->id, NULL, TRUE); } /*********************************************************************** * * pop3_parse_custom_request() * * Parse the custom request. */ static CURLcode pop3_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct POP3 *pop3 = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; /* URL decode the custom request */ if(custom) result = Curl_urldecode(data, custom, 0, &pop3->custom, NULL, TRUE); return result; } /*********************************************************************** * * Curl_pop3_write() * * This function scans the body after the end-of-body and writes everything * until the end is found. */ CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread) { /* This code could be made into a special function in the handler struct */ CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SingleRequest *k = &data->req; struct pop3_conn *pop3c = &conn->proto.pop3c; bool strip_dot = FALSE; size_t last = 0; size_t i; /* Search through the buffer looking for the end-of-body marker which is 5 bytes (0d 0a 2e 0d 0a). Note that a line starting with a dot matches the eob so the server will have prefixed it with an extra dot which we need to strip out. Additionally the marker could of course be spread out over 5 different data chunks. */ for(i = 0; i < nread; i++) { size_t prev = pop3c->eob; switch(str[i]) { case 0x0d: if(pop3c->eob == 0) { pop3c->eob++; if(i) { /* Write out the body part that didn't match */ result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last], i - last); if(result) return result; last = i; } } else if(pop3c->eob == 3) pop3c->eob++; else /* If the character match wasn't at position 0 or 3 then restart the pattern matching */ pop3c->eob = 1; break; case 0x0a: if(pop3c->eob == 1 || pop3c->eob == 4) pop3c->eob++; else /* If the character match wasn't at position 1 or 4 then start the search again */ pop3c->eob = 0; break; case 0x2e: if(pop3c->eob == 2) pop3c->eob++; else if(pop3c->eob == 3) { /* We have an extra dot after the CRLF which we need to strip off */ strip_dot = TRUE; pop3c->eob = 0; } else /* If the character match wasn't at position 2 then start the search again */ pop3c->eob = 0; break; default: pop3c->eob = 0; break; } /* Did we have a partial match which has subsequently failed? */ if(prev && prev >= pop3c->eob) { /* Strip can only be non-zero for the very first mismatch after CRLF and then both prev and strip are equal and nothing will be output below */ while(prev && pop3c->strip) { prev--; pop3c->strip--; } if(prev) { /* If the partial match was the CRLF and dot then only write the CRLF as the server would have inserted the dot */ result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB, strip_dot ? prev - 1 : prev); if(result) return result; last = i; strip_dot = FALSE; } } } if(pop3c->eob == POP3_EOB_LEN) { /* We have a full match so the transfer is done, however we must transfer the CRLF at the start of the EOB as this is considered to be part of the message as per RFC-1939, sect. 3 */ result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)POP3_EOB, 2); k->keepon &= ~KEEP_RECV; pop3c->eob = 0; return result; } if(pop3c->eob) /* While EOB is matching nothing should be output */ return CURLE_OK; if(nread - last) { result = Curl_client_write(conn, CLIENTWRITE_BODY, &str[last], nread - last); } return result; } #endif /* CURL_DISABLE_POP3 */
YifuLiu/AliOS-Things
components/curl/lib/pop3.c
C
apache-2.0
43,663
#ifndef HEADER_CURL_POP3_H #define HEADER_CURL_POP3_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2009 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "pingpong.h" #include "curl_sasl.h" /**************************************************************************** * POP3 unique setup ***************************************************************************/ typedef enum { POP3_STOP, /* do nothing state, stops the state machine */ POP3_SERVERGREET, /* waiting for the initial greeting immediately after a connect */ POP3_CAPA, POP3_STARTTLS, POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS (multi mode only) */ POP3_AUTH, POP3_APOP, POP3_USER, POP3_PASS, POP3_COMMAND, POP3_QUIT, POP3_LAST /* never used */ } pop3state; /* This POP3 struct is used in the Curl_easy. All POP3 data that is connection-oriented must be in pop3_conn to properly deal with the fact that perhaps the Curl_easy is changed between the times the connection is used. */ struct POP3 { curl_pp_transfer transfer; char *id; /* Message ID */ char *custom; /* Custom Request */ }; /* pop3_conn is used for struct connection-oriented data in the connectdata struct */ struct pop3_conn { struct pingpong pp; pop3state state; /* Always use pop3.c:state() to change state! */ bool ssldone; /* Is connect() over SSL done? */ size_t eob; /* Number of bytes of the EOB (End Of Body) that have been received so far */ size_t strip; /* Number of bytes from the start to ignore as non-body */ struct SASL sasl; /* SASL-related storage */ unsigned int authtypes; /* Accepted authentication types */ unsigned int preftype; /* Preferred authentication type */ char *apoptimestamp; /* APOP timestamp from the server greeting */ bool tls_supported; /* StartTLS capability supported by server */ }; extern const struct Curl_handler Curl_handler_pop3; extern const struct Curl_handler Curl_handler_pop3s; /* Authentication type flags */ #define POP3_TYPE_CLEARTEXT (1 << 0) #define POP3_TYPE_APOP (1 << 1) #define POP3_TYPE_SASL (1 << 2) /* Authentication type values */ #define POP3_TYPE_NONE 0 #define POP3_TYPE_ANY ~0U /* This is the 5-bytes End-Of-Body marker for POP3 */ #define POP3_EOB "\x0d\x0a\x2e\x0d\x0a" #define POP3_EOB_LEN 5 /* This function scans the body after the end-of-body and writes everything * until the end is found */ CURLcode Curl_pop3_write(struct connectdata *conn, char *str, size_t nread); #endif /* HEADER_CURL_POP3_H */
YifuLiu/AliOS-Things
components/curl/lib/pop3.h
C
apache-2.0
3,665
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include "sendf.h" #include "multiif.h" #include "progress.h" #include "curl_printf.h" /* check rate limits within this many recent milliseconds, at minimum. */ #define MIN_RATE_LIMIT_PERIOD 3000 #ifndef CURL_DISABLE_PROGRESS_METER /* Provide a string that is 2 + 1 + 2 + 1 + 2 = 8 letters long (plus the zero byte) */ static void time2str(char *r, curl_off_t seconds) { curl_off_t h; if(seconds <= 0) { strcpy(r, "--:--:--"); return; } h = seconds / CURL_OFF_T_C(3600); if(h <= CURL_OFF_T_C(99)) { curl_off_t m = (seconds - (h*CURL_OFF_T_C(3600))) / CURL_OFF_T_C(60); curl_off_t s = (seconds - (h*CURL_OFF_T_C(3600))) - (m*CURL_OFF_T_C(60)); msnprintf(r, 9, "%2" CURL_FORMAT_CURL_OFF_T ":%02" CURL_FORMAT_CURL_OFF_T ":%02" CURL_FORMAT_CURL_OFF_T, h, m, s); } else { /* this equals to more than 99 hours, switch to a more suitable output format to fit within the limits. */ curl_off_t d = seconds / CURL_OFF_T_C(86400); h = (seconds - (d*CURL_OFF_T_C(86400))) / CURL_OFF_T_C(3600); if(d <= CURL_OFF_T_C(999)) msnprintf(r, 9, "%3" CURL_FORMAT_CURL_OFF_T "d %02" CURL_FORMAT_CURL_OFF_T "h", d, h); else msnprintf(r, 9, "%7" CURL_FORMAT_CURL_OFF_T "d", d); } } /* The point of this function would be to return a string of the input data, but never longer than 5 columns (+ one zero byte). Add suffix k, M, G when suitable... */ static char *max5data(curl_off_t bytes, char *max5) { #define ONE_KILOBYTE CURL_OFF_T_C(1024) #define ONE_MEGABYTE (CURL_OFF_T_C(1024) * ONE_KILOBYTE) #define ONE_GIGABYTE (CURL_OFF_T_C(1024) * ONE_MEGABYTE) #define ONE_TERABYTE (CURL_OFF_T_C(1024) * ONE_GIGABYTE) #define ONE_PETABYTE (CURL_OFF_T_C(1024) * ONE_TERABYTE) if(bytes < CURL_OFF_T_C(100000)) msnprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes); else if(bytes < CURL_OFF_T_C(10000) * ONE_KILOBYTE) msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "k", bytes/ONE_KILOBYTE); else if(bytes < CURL_OFF_T_C(100) * ONE_MEGABYTE) /* 'XX.XM' is good as long as we're less than 100 megs */ msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE, (bytes%ONE_MEGABYTE) / (ONE_MEGABYTE/CURL_OFF_T_C(10)) ); #if (CURL_SIZEOF_CURL_OFF_T > 4) else if(bytes < CURL_OFF_T_C(10000) * ONE_MEGABYTE) /* 'XXXXM' is good until we're at 10000MB or above */ msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE); else if(bytes < CURL_OFF_T_C(100) * ONE_GIGABYTE) /* 10000 MB - 100 GB, we show it as XX.XG */ msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE, (bytes%ONE_GIGABYTE) / (ONE_GIGABYTE/CURL_OFF_T_C(10)) ); else if(bytes < CURL_OFF_T_C(10000) * ONE_GIGABYTE) /* up to 10000GB, display without decimal: XXXXG */ msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE); else if(bytes < CURL_OFF_T_C(10000) * ONE_TERABYTE) /* up to 10000TB, display without decimal: XXXXT */ msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "T", bytes/ONE_TERABYTE); else /* up to 10000PB, display without decimal: XXXXP */ msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "P", bytes/ONE_PETABYTE); /* 16384 petabytes (16 exabytes) is the maximum a 64 bit unsigned number can hold, but our data type is signed so 8192PB will be the maximum. */ #else else msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE); #endif return max5; } #endif /* New proposed interface, 9th of February 2000: pgrsStartNow() - sets start time pgrsSetDownloadSize(x) - known expected download size pgrsSetUploadSize(x) - known expected upload size pgrsSetDownloadCounter() - amount of data currently downloaded pgrsSetUploadCounter() - amount of data currently uploaded pgrsUpdate() - show progress pgrsDone() - transfer complete */ int Curl_pgrsDone(struct connectdata *conn) { int rc; struct Curl_easy *data = conn->data; data->progress.lastshow = 0; rc = Curl_pgrsUpdate(conn); /* the final (forced) update */ if(rc) return rc; if(!(data->progress.flags & PGRS_HIDE) && !data->progress.callback) /* only output if we don't use a progress callback and we're not * hidden */ fprintf(data->set.err, "\n"); data->progress.speeder_c = 0; /* reset the progress meter display */ return 0; } /* reset the known transfer sizes */ void Curl_pgrsResetTransferSizes(struct Curl_easy *data) { Curl_pgrsSetDownloadSize(data, -1); Curl_pgrsSetUploadSize(data, -1); } /* * @unittest: 1399 */ void Curl_pgrsTime(struct Curl_easy *data, timerid timer) { struct curltime now = Curl_now(); time_t *delta = NULL; switch(timer) { default: case TIMER_NONE: /* mistake filter */ break; case TIMER_STARTOP: /* This is set at the start of a transfer */ data->progress.t_startop = now; break; case TIMER_STARTSINGLE: /* This is set at the start of each single fetch */ data->progress.t_startsingle = now; data->progress.is_t_startransfer_set = false; break; case TIMER_STARTACCEPT: data->progress.t_acceptdata = now; break; case TIMER_NAMELOOKUP: delta = &data->progress.t_nslookup; break; case TIMER_CONNECT: delta = &data->progress.t_connect; break; case TIMER_APPCONNECT: delta = &data->progress.t_appconnect; break; case TIMER_PRETRANSFER: delta = &data->progress.t_pretransfer; break; case TIMER_STARTTRANSFER: delta = &data->progress.t_starttransfer; /* prevent updating t_starttransfer unless: * 1) this is the first time we're setting t_starttransfer * 2) a redirect has occurred since the last time t_starttransfer was set * This prevents repeated invocations of the function from incorrectly * changing the t_starttransfer time. */ if(data->progress.is_t_startransfer_set) { return; } else { data->progress.is_t_startransfer_set = true; break; } case TIMER_POSTRANSFER: /* this is the normal end-of-transfer thing */ break; case TIMER_REDIRECT: data->progress.t_redirect = Curl_timediff_us(now, data->progress.start); break; } if(delta) { timediff_t us = Curl_timediff_us(now, data->progress.t_startsingle); if(us < 1) us = 1; /* make sure at least one microsecond passed */ *delta += us; } } void Curl_pgrsStartNow(struct Curl_easy *data) { data->progress.speeder_c = 0; /* reset the progress meter display */ data->progress.start = Curl_now(); data->progress.is_t_startransfer_set = false; data->progress.ul_limit_start.tv_sec = 0; data->progress.ul_limit_start.tv_usec = 0; data->progress.dl_limit_start.tv_sec = 0; data->progress.dl_limit_start.tv_usec = 0; /* clear all bits except HIDE and HEADERS_OUT */ data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT; Curl_ratelimit(data, data->progress.start); } /* * This is used to handle speed limits, calculating how many milliseconds to * wait until we're back under the speed limit, if needed. * * The way it works is by having a "starting point" (time & amount of data * transferred by then) used in the speed computation, to be used instead of * the start of the transfer. This starting point is regularly moved as * transfer goes on, to keep getting accurate values (instead of average over * the entire transfer). * * This function takes the current amount of data transferred, the amount at * the starting point, the limit (in bytes/s), the time of the starting point * and the current time. * * Returns 0 if no waiting is needed or when no waiting is needed but the * starting point should be reset (to current); or the number of milliseconds * to wait to get back under the speed limit. */ timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize, curl_off_t startsize, curl_off_t limit, struct curltime start, struct curltime now) { curl_off_t size = cursize - startsize; time_t minimum; time_t actual; if(!limit || !size) return 0; /* * 'minimum' is the number of milliseconds 'size' should take to download to * stay below 'limit'. */ if(size < CURL_OFF_T_MAX/1000) minimum = (time_t) (CURL_OFF_T_C(1000) * size / limit); else { minimum = (time_t) (size / limit); if(minimum < TIME_T_MAX/1000) minimum *= 1000; else minimum = TIME_T_MAX; } /* * 'actual' is the time in milliseconds it took to actually download the * last 'size' bytes. */ actual = Curl_timediff(now, start); if(actual < minimum) { /* if it downloaded the data faster than the limit, make it wait the difference */ return (minimum - actual); } return 0; } /* * Set the number of downloaded bytes so far. */ void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size) { data->progress.downloaded = size; } /* * Update the timestamp and sizestamp to use for rate limit calculations. */ void Curl_ratelimit(struct Curl_easy *data, struct curltime now) { /* don't set a new stamp unless the time since last update is long enough */ if(data->set.max_recv_speed > 0) { if(Curl_timediff(now, data->progress.dl_limit_start) >= MIN_RATE_LIMIT_PERIOD) { data->progress.dl_limit_start = now; data->progress.dl_limit_size = data->progress.downloaded; } } if(data->set.max_send_speed > 0) { if(Curl_timediff(now, data->progress.ul_limit_start) >= MIN_RATE_LIMIT_PERIOD) { data->progress.ul_limit_start = now; data->progress.ul_limit_size = data->progress.uploaded; } } } /* * Set the number of uploaded bytes so far. */ void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size) { data->progress.uploaded = size; } void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size) { if(size >= 0) { data->progress.size_dl = size; data->progress.flags |= PGRS_DL_SIZE_KNOWN; } else { data->progress.size_dl = 0; data->progress.flags &= ~PGRS_DL_SIZE_KNOWN; } } void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size) { if(size >= 0) { data->progress.size_ul = size; data->progress.flags |= PGRS_UL_SIZE_KNOWN; } else { data->progress.size_ul = 0; data->progress.flags &= ~PGRS_UL_SIZE_KNOWN; } } #ifndef CURL_DISABLE_PROGRESS_METER static void progress_meter(struct connectdata *conn) { struct curltime now; curl_off_t timespent; curl_off_t timespent_ms; /* milliseconds */ struct Curl_easy *data = conn->data; bool shownow = FALSE; curl_off_t dl = data->progress.downloaded; curl_off_t ul = data->progress.uploaded; now = Curl_now(); /* what time is it */ /* The time spent so far (from the start) */ data->progress.timespent = Curl_timediff_us(now, data->progress.start); timespent = (curl_off_t)data->progress.timespent/1000000; /* seconds */ timespent_ms = (curl_off_t)data->progress.timespent/1000; /* ms */ /* The average download speed this far */ if(dl < CURL_OFF_T_MAX/1000) data->progress.dlspeed = (dl * 1000 / (timespent_ms>0?timespent_ms:1)); else data->progress.dlspeed = (dl / (timespent>0?timespent:1)); /* The average upload speed this far */ if(ul < CURL_OFF_T_MAX/1000) data->progress.ulspeed = (ul * 1000 / (timespent_ms>0?timespent_ms:1)); else data->progress.ulspeed = (ul / (timespent>0?timespent:1)); /* Calculations done at most once a second, unless end is reached */ if(data->progress.lastshow != now.tv_sec) { int countindex; /* amount of seconds stored in the speeder array */ int nowindex = data->progress.speeder_c% CURR_TIME; if(!(data->progress.flags & PGRS_HIDE)) shownow = TRUE; data->progress.lastshow = now.tv_sec; /* Let's do the "current speed" thing, with the dl + ul speeds combined. Store the speed at entry 'nowindex'. */ data->progress.speeder[ nowindex ] = data->progress.downloaded + data->progress.uploaded; /* remember the exact time for this moment */ data->progress.speeder_time [ nowindex ] = now; /* advance our speeder_c counter, which is increased every time we get here and we expect it to never wrap as 2^32 is a lot of seconds! */ data->progress.speeder_c++; /* figure out how many index entries of data we have stored in our speeder array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of transfer. Imagine, after one second we have filled in two entries, after two seconds we've filled in three entries etc. */ countindex = ((data->progress.speeder_c >= CURR_TIME)? CURR_TIME:data->progress.speeder_c) - 1; /* first of all, we don't do this if there's no counted seconds yet */ if(countindex) { int checkindex; timediff_t span_ms; /* Get the index position to compare with the 'nowindex' position. Get the oldest entry possible. While we have less than CURR_TIME entries, the first entry will remain the oldest. */ checkindex = (data->progress.speeder_c >= CURR_TIME)? data->progress.speeder_c%CURR_TIME:0; /* Figure out the exact time for the time span */ span_ms = Curl_timediff(now, data->progress.speeder_time[checkindex]); if(0 == span_ms) span_ms = 1; /* at least one millisecond MUST have passed */ /* Calculate the average speed the last 'span_ms' milliseconds */ { curl_off_t amount = data->progress.speeder[nowindex]- data->progress.speeder[checkindex]; if(amount > CURL_OFF_T_C(4294967) /* 0xffffffff/1000 */) /* the 'amount' value is bigger than would fit in 32 bits if multiplied with 1000, so we use the double math for this */ data->progress.current_speed = (curl_off_t) ((double)amount/((double)span_ms/1000.0)); else /* the 'amount' value is small enough to fit within 32 bits even when multiplied with 1000 */ data->progress.current_speed = amount*CURL_OFF_T_C(1000)/span_ms; } } else /* the first second we use the average */ data->progress.current_speed = data->progress.ulspeed + data->progress.dlspeed; } /* Calculations end */ if(!shownow) /* only show the internal progress meter once per second */ return; else { /* If there's no external callback set, use internal code to show progress */ /* progress meter has not been shut off */ char max5[6][10]; curl_off_t dlpercen = 0; curl_off_t ulpercen = 0; curl_off_t total_percen = 0; curl_off_t total_transfer; curl_off_t total_expected_transfer; char time_left[10]; char time_total[10]; char time_spent[10]; curl_off_t ulestimate = 0; curl_off_t dlestimate = 0; curl_off_t total_estimate; if(!(data->progress.flags & PGRS_HEADERS_OUT)) { if(data->state.resume_from) { fprintf(data->set.err, "** Resuming transfer from byte position %" CURL_FORMAT_CURL_OFF_T "\n", data->state.resume_from); } fprintf(data->set.err, " %% Total %% Received %% Xferd Average Speed " "Time Time Time Current\n" " Dload Upload " "Total Spent Left Speed\n"); data->progress.flags |= PGRS_HEADERS_OUT; /* headers are shown */ } /* Figure out the estimated time of arrival for the upload */ if((data->progress.flags & PGRS_UL_SIZE_KNOWN) && (data->progress.ulspeed > CURL_OFF_T_C(0))) { ulestimate = data->progress.size_ul / data->progress.ulspeed; if(data->progress.size_ul > CURL_OFF_T_C(10000)) ulpercen = data->progress.uploaded / (data->progress.size_ul/CURL_OFF_T_C(100)); else if(data->progress.size_ul > CURL_OFF_T_C(0)) ulpercen = (data->progress.uploaded*100) / data->progress.size_ul; } /* ... and the download */ if((data->progress.flags & PGRS_DL_SIZE_KNOWN) && (data->progress.dlspeed > CURL_OFF_T_C(0))) { dlestimate = data->progress.size_dl / data->progress.dlspeed; if(data->progress.size_dl > CURL_OFF_T_C(10000)) dlpercen = data->progress.downloaded / (data->progress.size_dl/CURL_OFF_T_C(100)); else if(data->progress.size_dl > CURL_OFF_T_C(0)) dlpercen = (data->progress.downloaded*100) / data->progress.size_dl; } /* Now figure out which of them is slower and use that one for the total estimate! */ total_estimate = ulestimate>dlestimate?ulestimate:dlestimate; /* create the three time strings */ time2str(time_left, total_estimate > 0?(total_estimate - timespent):0); time2str(time_total, total_estimate); time2str(time_spent, timespent); /* Get the total amount of data expected to get transferred */ total_expected_transfer = ((data->progress.flags & PGRS_UL_SIZE_KNOWN)? data->progress.size_ul:data->progress.uploaded)+ ((data->progress.flags & PGRS_DL_SIZE_KNOWN)? data->progress.size_dl:data->progress.downloaded); /* We have transferred this much so far */ total_transfer = data->progress.downloaded + data->progress.uploaded; /* Get the percentage of data transferred so far */ if(total_expected_transfer > CURL_OFF_T_C(10000)) total_percen = total_transfer / (total_expected_transfer/CURL_OFF_T_C(100)); else if(total_expected_transfer > CURL_OFF_T_C(0)) total_percen = (total_transfer*100) / total_expected_transfer; fprintf(data->set.err, "\r" "%3" CURL_FORMAT_CURL_OFF_T " %s " "%3" CURL_FORMAT_CURL_OFF_T " %s " "%3" CURL_FORMAT_CURL_OFF_T " %s %s %s %s %s %s %s", total_percen, /* 3 letters */ /* total % */ max5data(total_expected_transfer, max5[2]), /* total size */ dlpercen, /* 3 letters */ /* rcvd % */ max5data(data->progress.downloaded, max5[0]), /* rcvd size */ ulpercen, /* 3 letters */ /* xfer % */ max5data(data->progress.uploaded, max5[1]), /* xfer size */ max5data(data->progress.dlspeed, max5[3]), /* avrg dl speed */ max5data(data->progress.ulspeed, max5[4]), /* avrg ul speed */ time_total, /* 8 letters */ /* total time */ time_spent, /* 8 letters */ /* time spent */ time_left, /* 8 letters */ /* time left */ max5data(data->progress.current_speed, max5[5]) ); /* we flush the output stream to make it appear as soon as possible */ fflush(data->set.err); } /* don't show now */ } #else /* progress bar disabled */ #define progress_meter(x) #endif /* * Curl_pgrsUpdate() returns 0 for success or the value returned by the * progress callback! */ int Curl_pgrsUpdate(struct connectdata *conn) { struct Curl_easy *data = conn->data; if(!(data->progress.flags & PGRS_HIDE)) { if(data->set.fxferinfo) { int result; /* There's a callback set, call that */ Curl_set_in_callback(data, true); result = data->set.fxferinfo(data->set.progress_client, data->progress.size_dl, data->progress.downloaded, data->progress.size_ul, data->progress.uploaded); Curl_set_in_callback(data, false); if(result) failf(data, "Callback aborted"); return result; } if(data->set.fprogress) { int result; /* The older deprecated callback is set, call that */ Curl_set_in_callback(data, true); result = data->set.fprogress(data->set.progress_client, (double)data->progress.size_dl, (double)data->progress.downloaded, (double)data->progress.size_ul, (double)data->progress.uploaded); Curl_set_in_callback(data, false); if(result) failf(data, "Callback aborted"); return result; } } progress_meter(conn); return 0; }
YifuLiu/AliOS-Things
components/curl/lib/progress.c
C
apache-2.0
21,752
#ifndef HEADER_CURL_PROGRESS_H #define HEADER_CURL_PROGRESS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "timeval.h" typedef enum { TIMER_NONE, TIMER_STARTOP, TIMER_STARTSINGLE, TIMER_NAMELOOKUP, TIMER_CONNECT, TIMER_APPCONNECT, TIMER_PRETRANSFER, TIMER_STARTTRANSFER, TIMER_POSTRANSFER, TIMER_STARTACCEPT, TIMER_REDIRECT, TIMER_LAST /* must be last */ } timerid; int Curl_pgrsDone(struct connectdata *); void Curl_pgrsStartNow(struct Curl_easy *data); void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size); void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size); void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size); void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size); void Curl_ratelimit(struct Curl_easy *data, struct curltime now); int Curl_pgrsUpdate(struct connectdata *); void Curl_pgrsResetTransferSizes(struct Curl_easy *data); void Curl_pgrsTime(struct Curl_easy *data, timerid timer); timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize, curl_off_t startsize, curl_off_t limit, struct curltime start, struct curltime now); #define PGRS_HIDE (1<<4) #define PGRS_UL_SIZE_KNOWN (1<<5) #define PGRS_DL_SIZE_KNOWN (1<<6) #define PGRS_HEADERS_OUT (1<<7) /* set when the headers have been written */ #endif /* HEADER_CURL_PROGRESS_H */
YifuLiu/AliOS-Things
components/curl/lib/progress.h
C
apache-2.0
2,475
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #ifdef USE_LIBPSL #include "psl.h" #include "share.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" void Curl_psl_destroy(struct PslCache *pslcache) { if(pslcache->psl) { if(pslcache->dynamic) psl_free((psl_ctx_t *) pslcache->psl); pslcache->psl = NULL; pslcache->dynamic = FALSE; } } static time_t now_seconds(void) { struct curltime now = Curl_now(); return now.tv_sec; } const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy) { struct PslCache *pslcache = easy->psl; const psl_ctx_t *psl; time_t now; if(!pslcache) return NULL; Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); now = now_seconds(); if(!pslcache->psl || pslcache->expires <= now) { /* Let a chance to other threads to do the job: avoids deadlock. */ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Update cache: this needs an exclusive lock. */ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE); /* Recheck in case another thread did the job. */ now = now_seconds(); if(!pslcache->psl || pslcache->expires <= now) { bool dynamic = FALSE; time_t expires = TIME_T_MAX; #if defined(PSL_VERSION_NUMBER) && PSL_VERSION_NUMBER >= 0x001000 psl = psl_latest(NULL); dynamic = psl != NULL; /* Take care of possible time computation overflow. */ expires = now < TIME_T_MAX - PSL_TTL? now + PSL_TTL: TIME_T_MAX; /* Only get the built-in PSL if we do not already have the "latest". */ if(!psl && !pslcache->dynamic) #endif psl = psl_builtin(); if(psl) { Curl_psl_destroy(pslcache); pslcache->psl = psl; pslcache->dynamic = dynamic; pslcache->expires = expires; } } Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); } psl = pslcache->psl; if(!psl) Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); return psl; } void Curl_psl_release(struct Curl_easy *easy) { Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); } #endif /* USE_LIBPSL */
YifuLiu/AliOS-Things
components/curl/lib/psl.c
C
apache-2.0
3,281
#ifndef HEADER_PSL_H #define HEADER_PSL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef USE_LIBPSL #include <libpsl.h> #define PSL_TTL (72 * 3600) /* PSL time to live before a refresh. */ struct PslCache { const psl_ctx_t *psl; /* The PSL. */ time_t expires; /* Time this PSL life expires. */ bool dynamic; /* PSL should be released when no longer needed. */ }; const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy); void Curl_psl_release(struct Curl_easy *easy); void Curl_psl_destroy(struct PslCache *pslcache); #else #define Curl_psl_use(easy) NULL #define Curl_psl_release(easy) #define Curl_psl_destroy(pslcache) #endif /* USE_LIBPSL */ #endif /* HEADER_PSL_H */
YifuLiu/AliOS-Things
components/curl/lib/psl.h
C
apache-2.0
1,672
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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\n"); 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, PolarSSL 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; }
YifuLiu/AliOS-Things
components/curl/lib/rand.c
C
apache-2.0
5,326
#ifndef HEADER_CURL_RAND_H #define HEADER_CURL_RAND_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Curl_rand() stores 'num' number of random unsigned characters in the buffer * 'rnd' points to. * * If libcurl is built without TLS support or with a TLS backend that lacks a * proper random API (Gskit, PolarSSL 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); /* * 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); #endif /* HEADER_CURL_RAND_H */
YifuLiu/AliOS-Things
components/curl/lib/rand.h
C
apache-2.0
1,989
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_RTSP #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 connectdata *conn, bool *done); static CURLcode rtsp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode rtsp_connect(struct connectdata *conn, bool *done); static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead); static int rtsp_getsock_do(struct connectdata *conn, curl_socket_t *socks, int numsocks); /* * 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 connectdata *conn); static unsigned int rtsp_conncheck(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 connectdata *conn, curl_socket_t *socks, int numsocks) { /* write mode */ (void)numsocks; /* unused, we trust it to be at least 1 */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_WRITESOCK(0); } static CURLcode rtp_client_write(struct connectdata *conn, 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 */ PORT_RTSP, /* defport */ CURLPROTO_RTSP, /* protocol */ PROTOPT_NONE /* flags */ }; static CURLcode rtsp_setup_connection(struct connectdata *conn) { struct RTSP *rtsp; conn->data->req.protop = 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 connectdata *check, unsigned int checks_to_perform) { unsigned int ret_val = CONNRESULT_NONE; if(checks_to_perform & CONNCHECK_ISDEAD) { if(rtsp_connisdead(check)) ret_val |= CONNRESULT_DEAD; } return ret_val; } static CURLcode rtsp_connect(struct connectdata *conn, bool *done) { CURLcode httpStatus; struct Curl_easy *data = conn->data; httpStatus = Curl_http_connect(conn, 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; conn->proto.rtspc.rtp_channel = -1; return httpStatus; } static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead) { (void) dead; Curl_safefree(conn->proto.rtspc.rtp_buf); return CURLE_OK; } static CURLcode rtsp_done(struct connectdata *conn, CURLcode status, bool premature) { struct Curl_easy *data = conn->data; struct RTSP *rtsp = data->req.protop; CURLcode httpStatus; /* Bypass HTTP empty-reply checks on receive */ if(data->set.rtspreq == RTSPREQ_RECEIVE) premature = TRUE; httpStatus = Curl_http_done(conn, 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 && (conn->proto.rtspc.rtp_channel == -1)) { infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv); } } return httpStatus; } static CURLcode rtsp_do(struct connectdata *conn, bool *done) { struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; Curl_RtspReq rtspreq = data->set.rtspreq; struct RTSP *rtsp = data->req.protop; Curl_send_buffer *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(conn, "Transport"); if(rtspreq == RTSPREQ_SETUP && !p_transport) { /* New Transport: setting? */ if(data->set.str[STRING_RTSP_TRANSPORT]) { Curl_safefree(conn->allocptr.rtsp_transport); conn->allocptr.rtsp_transport = aprintf("Transport: %s\r\n", data->set.str[STRING_RTSP_TRANSPORT]); if(!conn->allocptr.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 = conn->allocptr.rtsp_transport; } /* Accept Headers for DESCRIBE requests */ if(rtspreq == RTSPREQ_DESCRIBE) { /* Accept Header */ p_accept = Curl_checkheaders(conn, "Accept")? NULL:"Accept: application/sdp\r\n"; /* Accept-Encoding header */ if(!Curl_checkheaders(conn, "Accept-Encoding") && data->set.str[STRING_ENCODING]) { Curl_safefree(conn->allocptr.accept_encoding); conn->allocptr.accept_encoding = aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); if(!conn->allocptr.accept_encoding) return CURLE_OUT_OF_MEMORY; p_accept_encoding = conn->allocptr.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(conn, "User-Agent") && conn->allocptr.uagent) { Curl_safefree(conn->allocptr.uagent); conn->allocptr.uagent = NULL; } else if(!Curl_checkheaders(conn, "User-Agent") && data->set.str[STRING_USERAGENT]) { p_uagent = conn->allocptr.uagent; } /* setup the authentication headers */ result = Curl_http_output_auth(conn, p_request, p_stream_uri, FALSE); if(result) return result; p_proxyuserpwd = conn->allocptr.proxyuserpwd; p_userpwd = conn->allocptr.userpwd; /* Referrer */ Curl_safefree(conn->allocptr.ref); if(data->change.referer && !Curl_checkheaders(conn, "Referer")) conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer); else conn->allocptr.ref = NULL; p_referrer = conn->allocptr.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(conn, "Range") && data->state.range) { Curl_safefree(conn->allocptr.rangeline); conn->allocptr.rangeline = aprintf("Range: %s\r\n", data->state.range); p_range = conn->allocptr.rangeline; } } /* * Sanity check the custom headers */ if(Curl_checkheaders(conn, "CSeq")) { failf(data, "CSeq cannot be set as a custom header."); return CURLE_RTSP_CSEQ_ERROR; } if(Curl_checkheaders(conn, "Session")) { failf(data, "Session ID cannot be set as a custom header."); return CURLE_BAD_FUNCTION_ARGUMENT; } /* Initialize a dynamic send buffer */ req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; result = Curl_add_bufferf(&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_add_bufferf(&req_buffer, "Session: %s\r\n", p_session_id); if(result) return result; } /* * Shared HTTP-like options */ result = Curl_add_bufferf(&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(conn->allocptr.userpwd); conn->allocptr.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(conn, 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->set.httpreq = HTTPREQ_PUT; } else { postsize = (data->state.infilesize != -1)? data->state.infilesize: (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0); data->set.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(conn, "Content-Length")) { result = Curl_add_bufferf(&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(conn, "Content-Type")) { result = Curl_add_bufferf(&req_buffer, "Content-Type: text/parameters\r\n"); if(result) return result; } } if(rtspreq == RTSPREQ_ANNOUNCE) { if(!Curl_checkheaders(conn, "Content-Type")) { result = Curl_add_bufferf(&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->set.httpreq = HTTPREQ_HEAD; data->set.opt_no_body = TRUE; } } /* RTSP never allows chunked transfer */ data->req.forbidchunk = TRUE; /* Finish the request buffer */ result = Curl_add_buffer(&req_buffer, "\r\n", 2); if(result) return result; if(postsize > 0) { result = Curl_add_buffer(&req_buffer, data->set.postfields, (size_t)postsize); if(result) return result; } /* issue the request */ result = Curl_add_buffer_send(&req_buffer, conn, &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(conn)) 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\n", rtspc->rtp_channel, rtp_length)); result = rtp_client_write(conn, &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 != 0 && rtp[0] == '$') { DEBUGF(infof(data, "RTP Rewinding %zd %s\n", 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 connectdata *conn, char *ptr, size_t len) { struct Curl_easy *data = conn->data; 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 connectdata *conn, char *header) { struct Curl_easy *data = conn->data; 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.protop; 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; /* Find the first non-space letter */ start = header + 8; while(*start && ISSPACE(*start)) start++; if(!*start) { failf(data, "Got a blank Session ID"); } else if(data->set.str[STRING_RTSP_SESSION_ID]) { /* If the Session ID is set, then compare */ if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], strlen(data->set.str[STRING_RTSP_SESSION_ID])) != 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. * * 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. */ char *end = start; while(*end && *end != ';' && !ISSPACE(*end)) end++; /* Copy the id substring into a new buffer */ data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1); if(data->set.str[STRING_RTSP_SESSION_ID] == NULL) return CURLE_OUT_OF_MEMORY; memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start); (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0'; } } return CURLE_OK; } #endif /* CURL_DISABLE_RTSP */
YifuLiu/AliOS-Things
components/curl/lib/rtsp.c
C
apache-2.0
25,656
#ifndef HEADER_CURL_RTSP_H #define HEADER_CURL_RTSP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_RTSP extern const struct Curl_handler Curl_handler_rtsp; CURLcode Curl_rtsp_parseheader(struct connectdata *conn, char *header); #else /* disabled */ #define Curl_rtsp_parseheader(x,y) CURLE_NOT_BUILT_IN #endif /* CURL_DISABLE_RTSP */ /* * RTSP Connection data * * Currently, only used for tracking incomplete RTP data reads */ struct rtsp_conn { char *rtp_buf; ssize_t rtp_bufsize; int rtp_channel; }; /**************************************************************************** * RTSP unique setup ***************************************************************************/ struct RTSP { /* * http_wrapper MUST be the first element of this structure for the wrap * logic to work. In this way, we get a cheap polymorphism because * &(data->state.proto.rtsp) == &(data->state.proto.http) per the C spec * * HTTP functions can safely treat this as an HTTP struct, but RTSP aware * functions can also index into the later elements. */ struct HTTP http_wrapper; /*wrap HTTP to do the heavy lifting */ long CSeq_sent; /* CSeq of this request */ long CSeq_recv; /* CSeq received */ }; #endif /* HEADER_CURL_RTSP_H */
YifuLiu/AliOS-Things
components/curl/lib/rtsp.h
C
apache-2.0
2,265
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #if !defined(HAVE_SELECT) && !defined(HAVE_POLL_FINE) #error "We can't compile without select() or poll() support." #endif #if defined(__BEOS__) && !defined(__HAIKU__) /* BeOS has FD_SET defined in socket.h */ #include <socket.h> #endif #ifdef MSDOS #include <dos.h> /* delay() */ #endif #ifdef __VXWORKS__ #include <strings.h> /* bzero() in FD_SET */ #endif #include <curl/curl.h> #include "urldata.h" #include "connect.h" #include "select.h" #include "warnless.h" /* Convenience local macros */ #define ELAPSED_MS() (int)Curl_timediff(Curl_now(), initial_tv) int Curl_ack_eintr = 0; #define ERROR_NOT_EINTR(error) (Curl_ack_eintr || error != EINTR) /* * Internal function used for waiting a specific amount of ms * in Curl_socket_check() and Curl_poll() when no file descriptor * is provided to wait on, just being used to delay execution. * WinSock select() and poll() timeout mechanisms need a valid * socket descriptor in a not null file descriptor set to work. * Waiting indefinitely with this function is not allowed, a * zero or negative timeout value will return immediately. * Timeout resolution, accuracy, as well as maximum supported * value is system dependent, neither factor is a citical issue * for the intended use of this function in the library. * * Return values: * -1 = system call error, invalid timeout value, or interrupted * 0 = specified timeout has elapsed */ int Curl_wait_ms(int timeout_ms) { #if !defined(MSDOS) && !defined(USE_WINSOCK) #ifndef HAVE_POLL_FINE struct timeval pending_tv; #endif struct curltime initial_tv; int pending_ms; #endif int r = 0; if(!timeout_ms) return 0; if(timeout_ms < 0) { SET_SOCKERRNO(EINVAL); return -1; } #if defined(MSDOS) delay(timeout_ms); #elif defined(USE_WINSOCK) Sleep(timeout_ms); #else pending_ms = timeout_ms; initial_tv = Curl_now(); do { int error; #if defined(HAVE_POLL_FINE) r = poll(NULL, 0, pending_ms); #else pending_tv.tv_sec = pending_ms / 1000; pending_tv.tv_usec = (pending_ms % 1000) * 1000; r = select(0, NULL, NULL, NULL, &pending_tv); #endif /* HAVE_POLL_FINE */ if(r != -1) break; error = SOCKERRNO; if(error && ERROR_NOT_EINTR(error)) break; pending_ms = timeout_ms - ELAPSED_MS(); if(pending_ms <= 0) { r = 0; /* Simulate a "call timed out" case */ break; } } while(r == -1); #endif /* USE_WINSOCK */ if(r) r = -1; return r; } /* * Wait for read or write events on a set of file descriptors. It uses poll() * when a fine poll() is available, in order to avoid limits with FD_SETSIZE, * otherwise select() is used. An error is returned if select() is being used * and a file descriptor is too large for FD_SETSIZE. * * A negative timeout value makes this function wait indefinitely, * unless no valid file descriptor is given, when this happens the * negative timeout is ignored and the function times out immediately. * * Return values: * -1 = system call error or fd >= FD_SETSIZE * 0 = timeout * [bitmask] = action as described below * * CURL_CSELECT_IN - first socket is readable * CURL_CSELECT_IN2 - second socket is readable * CURL_CSELECT_OUT - write socket is writable * CURL_CSELECT_ERR - an error condition occurred */ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ curl_socket_t readfd1, curl_socket_t writefd, /* socket to write to */ time_t timeout_ms) /* milliseconds to wait */ { #ifdef HAVE_POLL_FINE struct pollfd pfd[3]; int num; #else struct timeval pending_tv; struct timeval *ptimeout; fd_set fds_read; fd_set fds_write; fd_set fds_err; curl_socket_t maxfd; #endif struct curltime initial_tv = {0, 0}; int pending_ms = 0; int r; int ret; #if SIZEOF_TIME_T != SIZEOF_INT /* wrap-around precaution */ if(timeout_ms >= INT_MAX) timeout_ms = INT_MAX; #endif if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) && (writefd == CURL_SOCKET_BAD)) { /* no sockets, just wait */ r = Curl_wait_ms((int)timeout_ms); return r; } /* Avoid initial timestamp, avoid Curl_now() call, when elapsed time in this function does not need to be measured. This happens when function is called with a zero timeout or a negative timeout value indicating a blocking call should be performed. */ if(timeout_ms > 0) { pending_ms = (int)timeout_ms; initial_tv = Curl_now(); } #ifdef HAVE_POLL_FINE num = 0; if(readfd0 != CURL_SOCKET_BAD) { pfd[num].fd = readfd0; pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; pfd[num].revents = 0; num++; } if(readfd1 != CURL_SOCKET_BAD) { pfd[num].fd = readfd1; pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; pfd[num].revents = 0; num++; } if(writefd != CURL_SOCKET_BAD) { pfd[num].fd = writefd; pfd[num].events = POLLWRNORM|POLLOUT; pfd[num].revents = 0; num++; } do { int error; if(timeout_ms < 0) pending_ms = -1; else if(!timeout_ms) pending_ms = 0; r = poll(pfd, num, pending_ms); if(r != -1) break; error = SOCKERRNO; if(error && ERROR_NOT_EINTR(error)) break; if(timeout_ms > 0) { pending_ms = (int)(timeout_ms - ELAPSED_MS()); if(pending_ms <= 0) { r = 0; /* Simulate a "call timed out" case */ break; } } } while(r == -1); if(r < 0) return -1; if(r == 0) return 0; ret = 0; num = 0; if(readfd0 != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) ret |= CURL_CSELECT_IN; if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL)) ret |= CURL_CSELECT_ERR; num++; } if(readfd1 != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) ret |= CURL_CSELECT_IN2; if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL)) ret |= CURL_CSELECT_ERR; num++; } if(writefd != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLWRNORM|POLLOUT)) ret |= CURL_CSELECT_OUT; if(pfd[num].revents & (POLLERR|POLLHUP|POLLNVAL)) ret |= CURL_CSELECT_ERR; } return ret; #else /* HAVE_POLL_FINE */ FD_ZERO(&fds_err); maxfd = (curl_socket_t)-1; FD_ZERO(&fds_read); if(readfd0 != CURL_SOCKET_BAD) { VERIFY_SOCK(readfd0); FD_SET(readfd0, &fds_read); FD_SET(readfd0, &fds_err); maxfd = readfd0; } if(readfd1 != CURL_SOCKET_BAD) { VERIFY_SOCK(readfd1); FD_SET(readfd1, &fds_read); FD_SET(readfd1, &fds_err); if(readfd1 > maxfd) maxfd = readfd1; } FD_ZERO(&fds_write); if(writefd != CURL_SOCKET_BAD) { VERIFY_SOCK(writefd); FD_SET(writefd, &fds_write); FD_SET(writefd, &fds_err); if(writefd > maxfd) maxfd = writefd; } ptimeout = (timeout_ms < 0) ? NULL : &pending_tv; do { int error; if(timeout_ms > 0) { pending_tv.tv_sec = pending_ms / 1000; pending_tv.tv_usec = (pending_ms % 1000) * 1000; } else if(!timeout_ms) { pending_tv.tv_sec = 0; pending_tv.tv_usec = 0; } /* WinSock select() must not be called with an fd_set that contains zero fd flags, or it will return WSAEINVAL. But, it also can't be called with no fd_sets at all! From the documentation: Any two of the parameters, readfds, writefds, or exceptfds, can be given as null. At least one must be non-null, and any non-null descriptor set must contain at least one handle to a socket. We know that we have at least one bit set in at least two fd_sets in this case, but we may have no bits set in either fds_read or fd_write, so check for that and handle it. Luckily, with WinSock, we can _also_ ask how many bits are set on an fd_set. It is unclear why WinSock doesn't just handle this for us instead of calling this an error. Note also that WinSock ignores the first argument, so we don't worry about the fact that maxfd is computed incorrectly with WinSock (since curl_socket_t is unsigned in such cases and thus -1 is the largest value). */ #ifdef USE_WINSOCK r = select((int)maxfd + 1, fds_read.fd_count ? &fds_read : NULL, fds_write.fd_count ? &fds_write : NULL, &fds_err, ptimeout); #else r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout); #endif if(r != -1) break; error = SOCKERRNO; if(error && ERROR_NOT_EINTR(error)) break; if(timeout_ms > 0) { pending_ms = (int)(timeout_ms - ELAPSED_MS()); if(pending_ms <= 0) { r = 0; /* Simulate a "call timed out" case */ break; } } } while(r == -1); if(r < 0) return -1; if(r == 0) return 0; ret = 0; if(readfd0 != CURL_SOCKET_BAD) { if(FD_ISSET(readfd0, &fds_read)) ret |= CURL_CSELECT_IN; if(FD_ISSET(readfd0, &fds_err)) ret |= CURL_CSELECT_ERR; } if(readfd1 != CURL_SOCKET_BAD) { if(FD_ISSET(readfd1, &fds_read)) ret |= CURL_CSELECT_IN2; if(FD_ISSET(readfd1, &fds_err)) ret |= CURL_CSELECT_ERR; } if(writefd != CURL_SOCKET_BAD) { if(FD_ISSET(writefd, &fds_write)) ret |= CURL_CSELECT_OUT; if(FD_ISSET(writefd, &fds_err)) ret |= CURL_CSELECT_ERR; } return ret; #endif /* HAVE_POLL_FINE */ } /* * This is a wrapper around poll(). If poll() does not exist, then * select() is used instead. An error is returned if select() is * being used and a file descriptor is too large for FD_SETSIZE. * A negative timeout value makes this function wait indefinitely, * unless no valid file descriptor is given, when this happens the * negative timeout is ignored and the function times out immediately. * * Return values: * -1 = system call error or fd >= FD_SETSIZE * 0 = timeout * N = number of structures with non zero revent fields */ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms) { #ifndef HAVE_POLL_FINE struct timeval pending_tv; struct timeval *ptimeout; fd_set fds_read; fd_set fds_write; fd_set fds_err; curl_socket_t maxfd; #endif struct curltime initial_tv = {0, 0}; bool fds_none = TRUE; unsigned int i; int pending_ms = 0; int r; if(ufds) { for(i = 0; i < nfds; i++) { if(ufds[i].fd != CURL_SOCKET_BAD) { fds_none = FALSE; break; } } } if(fds_none) { r = Curl_wait_ms(timeout_ms); return r; } /* Avoid initial timestamp, avoid Curl_now() call, when elapsed time in this function does not need to be measured. This happens when function is called with a zero timeout or a negative timeout value indicating a blocking call should be performed. */ if(timeout_ms > 0) { pending_ms = timeout_ms; initial_tv = Curl_now(); } #ifdef HAVE_POLL_FINE do { int error; if(timeout_ms < 0) pending_ms = -1; else if(!timeout_ms) pending_ms = 0; r = poll(ufds, nfds, pending_ms); if(r != -1) break; error = SOCKERRNO; if(error && ERROR_NOT_EINTR(error)) break; if(timeout_ms > 0) { pending_ms = (int)(timeout_ms - ELAPSED_MS()); if(pending_ms <= 0) { r = 0; /* Simulate a "call timed out" case */ break; } } } while(r == -1); if(r < 0) return -1; if(r == 0) return 0; for(i = 0; i < nfds; i++) { if(ufds[i].fd == CURL_SOCKET_BAD) continue; if(ufds[i].revents & POLLHUP) ufds[i].revents |= POLLIN; if(ufds[i].revents & POLLERR) ufds[i].revents |= (POLLIN|POLLOUT); } #else /* HAVE_POLL_FINE */ FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_err); maxfd = (curl_socket_t)-1; for(i = 0; i < nfds; i++) { ufds[i].revents = 0; if(ufds[i].fd == CURL_SOCKET_BAD) continue; VERIFY_SOCK(ufds[i].fd); if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI| POLLRDNORM|POLLWRNORM|POLLRDBAND)) { if(ufds[i].fd > maxfd) maxfd = ufds[i].fd; if(ufds[i].events & (POLLRDNORM|POLLIN)) FD_SET(ufds[i].fd, &fds_read); if(ufds[i].events & (POLLWRNORM|POLLOUT)) FD_SET(ufds[i].fd, &fds_write); if(ufds[i].events & (POLLRDBAND|POLLPRI)) FD_SET(ufds[i].fd, &fds_err); } } #ifdef USE_WINSOCK /* WinSock select() can't handle zero events. See the comment about this in Curl_check_socket(). */ if(fds_read.fd_count == 0 && fds_write.fd_count == 0 && fds_err.fd_count == 0) { r = Curl_wait_ms(timeout_ms); return r; } #endif ptimeout = (timeout_ms < 0) ? NULL : &pending_tv; do { int error; if(timeout_ms > 0) { pending_tv.tv_sec = pending_ms / 1000; pending_tv.tv_usec = (pending_ms % 1000) * 1000; } else if(!timeout_ms) { pending_tv.tv_sec = 0; pending_tv.tv_usec = 0; } #ifdef USE_WINSOCK r = select((int)maxfd + 1, /* WinSock select() can't handle fd_sets with zero bits set, so don't give it such arguments. See the comment about this in Curl_check_socket(). */ fds_read.fd_count ? &fds_read : NULL, fds_write.fd_count ? &fds_write : NULL, fds_err.fd_count ? &fds_err : NULL, ptimeout); #else r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout); #endif if(r != -1) break; error = SOCKERRNO; if(error && ERROR_NOT_EINTR(error)) break; if(timeout_ms > 0) { pending_ms = timeout_ms - ELAPSED_MS(); if(pending_ms <= 0) { r = 0; /* Simulate a "call timed out" case */ break; } } } while(r == -1); if(r < 0) return -1; if(r == 0) return 0; r = 0; for(i = 0; i < nfds; i++) { ufds[i].revents = 0; if(ufds[i].fd == CURL_SOCKET_BAD) continue; if(FD_ISSET(ufds[i].fd, &fds_read)) ufds[i].revents |= POLLIN; if(FD_ISSET(ufds[i].fd, &fds_write)) ufds[i].revents |= POLLOUT; if(FD_ISSET(ufds[i].fd, &fds_err)) ufds[i].revents |= POLLPRI; if(ufds[i].revents != 0) r++; } #endif /* HAVE_POLL_FINE */ return r; } #ifdef TPF /* * This is a replacement for select() on the TPF platform. * It is used whenever libcurl calls select(). * The call below to tpf_process_signals() is required because * TPF's select calls are not signal interruptible. * * Return values are the same as select's. */ int tpf_select_libcurl(int maxfds, fd_set *reads, fd_set *writes, fd_set *excepts, struct timeval *tv) { int rc; rc = tpf_select_bsd(maxfds, reads, writes, excepts, tv); tpf_process_signals(); return rc; } #endif /* TPF */
YifuLiu/AliOS-Things
components/curl/lib/select.c
C
apache-2.0
15,998
#ifndef HEADER_CURL_SELECT_H #define HEADER_CURL_SELECT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_POLL_H #include <poll.h> #elif defined(HAVE_SYS_POLL_H) #include <sys/poll.h> #endif /* * Definition of pollfd struct and constants for platforms lacking them. */ #if !defined(HAVE_STRUCT_POLLFD) && \ !defined(HAVE_SYS_POLL_H) && \ !defined(HAVE_POLL_H) && \ !defined(POLLIN) #define POLLIN 0x01 #define POLLPRI 0x02 #define POLLOUT 0x04 #define POLLERR 0x08 #define POLLHUP 0x10 #define POLLNVAL 0x20 struct pollfd { curl_socket_t fd; short events; short revents; }; #endif #ifndef POLLRDNORM #define POLLRDNORM POLLIN #endif #ifndef POLLWRNORM #define POLLWRNORM POLLOUT #endif #ifndef POLLRDBAND #define POLLRDBAND POLLPRI #endif /* there are three CSELECT defines that are defined in the public header that are exposed to users, but this *IN2 bit is only ever used internally and therefore defined here */ #define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1) int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2, curl_socket_t writefd, time_t timeout_ms); #define SOCKET_READABLE(x,z) \ Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z) #define SOCKET_WRITABLE(x,z) \ Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z) int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms); /* On non-DOS and non-Winsock platforms, when Curl_ack_eintr is set, * EINTR condition is honored and function might exit early without * awaiting full timeout. Otherwise EINTR will be ignored and full * timeout will elapse. */ extern int Curl_ack_eintr; int Curl_wait_ms(int timeout_ms); #ifdef TPF int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes, fd_set* excepts, struct timeval* tv); #endif /* Winsock and TPF sockets are not in range [0..FD_SETSIZE-1], which unfortunately makes it impossible for us to easily check if they're valid */ #if defined(USE_WINSOCK) || defined(TPF) #define VALID_SOCK(x) 1 #define VERIFY_SOCK(x) Curl_nop_stmt #else #define VALID_SOCK(s) (((s) >= 0) && ((s) < FD_SETSIZE)) #define VERIFY_SOCK(x) do { \ if(!VALID_SOCK(x)) { \ SET_SOCKERRNO(EINVAL); \ return -1; \ } \ } WHILE_FALSE #endif #endif /* HEADER_CURL_SELECT_H */
YifuLiu/AliOS-Things
components/curl/lib/select.h
C
apache-2.0
3,380
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <sys/socket.h> #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_LINUX_TCP_H #include <linux/tcp.h> #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "connect.h" #include "vtls/vtls.h" #include "ssh.h" #include "easyif.h" #include "multiif.h" #include "non-ascii.h" #include "strerror.h" #include "select.h" #include "strdup.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #ifdef 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 == NULL) || (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 void pre_receive_plain(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 * conn->data->set.buffer_size; psnd->buffer = malloc(psnd->allocated_size); 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; } } } 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(c,n) do {} WHILE_FALSE #define get_pre_recved(c,n,b,l) 0 #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ /* Curl_infof() is for info message along the way */ void Curl_infof(struct Curl_easy *data, const char *fmt, ...) { if(data && data->set.verbose) { va_list ap; size_t len; char print_buffer[2048 + 1]; va_start(ap, fmt); len = mvsnprintf(print_buffer, sizeof(print_buffer), fmt, ap); /* * Indicate truncation of the input by replacing the last 3 characters * with "...", and transfer the newline over in case the format had one. */ if(len >= sizeof(print_buffer)) { len = strlen(fmt); if(fmt[--len] == '\n') msnprintf(print_buffer + (sizeof(print_buffer) - 5), 5, "...\n"); else msnprintf(print_buffer + (sizeof(print_buffer) - 4), 4, "..."); } va_end(ap); len = strlen(print_buffer); Curl_debug(data, CURLINFO_TEXT, print_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, ...) { if(data->set.verbose || data->set.errorbuffer) { va_list ap; size_t len; char error[CURL_ERROR_SIZE + 2]; va_start(ap, fmt); mvsnprintf(error, CURL_ERROR_SIZE, fmt, ap); len = strlen(error); if(data->set.errorbuffer && !data->state.errorbuf) { strcpy(data->set.errorbuffer, error); data->state.errorbuf = TRUE; /* wrote error string */ } if(data->set.verbose) { error[len] = '\n'; error[++len] = '\0'; Curl_debug(data, CURLINFO_TEXT, error, len); } va_end(ap); } } /* Curl_sendf() sends formatted data to the server */ CURLcode Curl_sendf(curl_socket_t sockfd, struct connectdata *conn, const char *fmt, ...) { struct Curl_easy *data = conn->data; ssize_t bytes_written; size_t write_len; CURLcode result = CURLE_OK; char *s; char *sptr; va_list ap; va_start(ap, fmt); s = vaprintf(fmt, ap); /* returns an allocated string */ va_end(ap); if(!s) return CURLE_OUT_OF_MEMORY; /* failure */ bytes_written = 0; write_len = strlen(s); sptr = s; for(;;) { /* Write the buffer to the socket */ result = Curl_write(conn, sockfd, sptr, write_len, &bytes_written); if(result) break; if(data->set.verbose) Curl_debug(data, CURLINFO_DATA_OUT, sptr, (size_t)bytes_written); if((size_t)bytes_written != write_len) { /* if not all was written at once, we must advance the pointer, decrease the size left and try again! */ write_len -= bytes_written; sptr += bytes_written; } else break; } free(s); /* free the output string */ return result; } /* * 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 connectdata *conn, curl_socket_t sockfd, const void *mem, size_t len, ssize_t *written) { ssize_t bytes_written; CURLcode result = CURLE_OK; int num = (sockfd == conn->sock[SECONDARYSOCKET]); bytes_written = conn->send[num](conn, 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 connectdata *conn, int num, const void *mem, size_t len, CURLcode *code) { curl_socket_t sockfd = conn->sock[num]; ssize_t bytes_written; /* 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. */ pre_receive_plain(conn, num); #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(conn->data, "Send failure: %s", Curl_strerror(err, buffer, sizeof(buffer))); conn->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 connectdata *conn, curl_socket_t sockfd, const void *mem, size_t len, ssize_t *written) { ssize_t bytes_written; CURLcode result; int num = (sockfd == conn->sock[SECONDARYSOCKET]); bytes_written = Curl_send_plain(conn, num, mem, len, &result); *written = bytes_written; return result; } ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf, size_t len, CURLcode *code) { curl_socket_t sockfd = conn->sock[num]; ssize_t nread; /* 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(conn->data, "Recv failure: %s", Curl_strerror(err, buffer, sizeof(buffer))); conn->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; char *dupl; unsigned int i; bool newtype = 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) { /* append new data to old data */ /* figure out the new size of the data to save */ size_t newlen = len + s->tempwrite[i].len; /* allocate the new memory area */ char *newptr = realloc(s->tempwrite[i].buf, newlen); if(!newptr) return CURLE_OUT_OF_MEMORY; /* copy the new data to the end of the new area */ memcpy(newptr + s->tempwrite[i].len, ptr, len); /* update the pointer and the size */ s->tempwrite[i].buf = newptr; s->tempwrite[i].len = newlen; } else { dupl = Curl_memdup(ptr, len); if(!dupl) return CURLE_OUT_OF_MEMORY; /* store this information in the state struct for later use */ s->tempwrite[i].buf = dupl; s->tempwrite[i].len = len; s->tempwrite[i].type = type; if(newtype) s->tempcount++; } /* mark the connection as RECV paused */ k->keepon |= KEEP_RECV_PAUSE; DEBUGF(infof(data, "Paused %zu bytes in buffer for type %02x\n", len, type)); 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 connectdata *conn, int type, char *optr, size_t olen) { struct Curl_easy *data = conn->data; 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, "Failed writing body (%zu != %zu)", wrote, chunklen); 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 connectdata *conn, int type, char *ptr, size_t len) { struct Curl_easy *data = conn->data; if(0 == len) len = strlen(ptr); DEBUGASSERT(type <= 3); /* 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(conn, 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) { int err = SOCKERRNO; int return_error; #ifdef USE_WINSOCK return_error = WSAEWOULDBLOCK == err; #else return_error = EWOULDBLOCK == err || EAGAIN == err || EINTR == err; #endif if(return_error) return CURLE_AGAIN; return CURLE_RECV_ERROR; } /* we only return number of bytes read when we return OK */ *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 connectdata *conn, /* connection data */ 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 Curl_easy *data = conn->data; /* 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](conn, 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) { static const char s_infotype[CURLINFO_END][3] = { "* ", "< ", "> ", "{ ", "} ", "{ ", "} " }; int rc = 0; #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; }
YifuLiu/AliOS-Things
components/curl/lib/sendf.c
C
apache-2.0
24,491
#ifndef HEADER_CURL_SENDF_H #define HEADER_CURL_SENDF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" CURLcode Curl_sendf(curl_socket_t sockfd, struct connectdata *, const char *fmt, ...); void Curl_infof(struct Curl_easy *, const char *fmt, ...); void Curl_failf(struct Curl_easy *, const char *fmt, ...); #if defined(CURL_DISABLE_VERBOSE_STRINGS) #if defined(HAVE_VARIADIC_MACROS_C99) #define infof(...) Curl_nop_stmt #elif defined(HAVE_VARIADIC_MACROS_GCC) #define infof(x...) Curl_nop_stmt #else #error "missing VARIADIC macro define, fix and rebuild!" #endif #else /* CURL_DISABLE_VERBOSE_STRINGS */ #define infof Curl_infof #endif /* CURL_DISABLE_VERBOSE_STRINGS */ #define failf Curl_failf #define CLIENTWRITE_BODY (1<<0) #define CLIENTWRITE_HEADER (1<<1) #define CLIENTWRITE_BOTH (CLIENTWRITE_BODY|CLIENTWRITE_HEADER) CURLcode Curl_client_write(struct connectdata *conn, int type, char *ptr, size_t len) WARN_UNUSED_RESULT; bool Curl_recv_has_postponed_data(struct connectdata *conn, int sockindex); /* internal read-function, does plain socket only */ CURLcode Curl_read_plain(curl_socket_t sockfd, char *buf, size_t bytesfromsocket, ssize_t *n); ssize_t Curl_recv_plain(struct connectdata *conn, int num, char *buf, size_t len, CURLcode *code); ssize_t Curl_send_plain(struct connectdata *conn, int num, const void *mem, size_t len, CURLcode *code); /* internal read-function, does plain socket, SSL and krb4 */ CURLcode Curl_read(struct connectdata *conn, curl_socket_t sockfd, char *buf, size_t buffersize, ssize_t *n); /* internal write-function, does plain socket, SSL, SCP, SFTP and krb4 */ CURLcode Curl_write(struct connectdata *conn, curl_socket_t sockfd, const void *mem, size_t len, ssize_t *written); /* internal write-function, does plain sockets ONLY */ CURLcode Curl_write_plain(struct connectdata *conn, curl_socket_t sockfd, const void *mem, size_t len, ssize_t *written); /* the function used to output verbose information */ int Curl_debug(struct Curl_easy *data, curl_infotype type, char *ptr, size_t size); #endif /* HEADER_CURL_SENDF_H */
YifuLiu/AliOS-Things
components/curl/lib/sendf.h
C
apache-2.0
3,459
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <limits.h> #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_LINUX_TCP_H #include <linux/tcp.h> #endif #include "urldata.h" #include "url.h" #include "progress.h" #include "content_encoding.h" #include "strcase.h" #include "share.h" #include "vtls/vtls.h" #include "warnless.h" #include "sendf.h" #include "http2.h" #include "setopt.h" #include "multiif.h" #include "altsvc.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" CURLcode Curl_setstropt(char **charp, const char *s) { /* Release the previous storage at `charp' and replace by a dynamic storage copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */ Curl_safefree(*charp); if(s) { char *str = strdup(s); if(str) { size_t len = strlen(str); if(len > CURL_MAX_INPUT_LENGTH) { free(str); return CURLE_BAD_FUNCTION_ARGUMENT; } } if(!str) return CURLE_OUT_OF_MEMORY; *charp = str; } return CURLE_OK; } static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp) { CURLcode result = CURLE_OK; char *user = NULL; char *passwd = NULL; /* Parse the login details if specified. It not then we treat NULL as a hint to clear the existing data */ if(option) { result = Curl_parse_login_details(option, strlen(option), (userp ? &user : NULL), (passwdp ? &passwd : NULL), NULL); } if(!result) { /* Store the username part of option if required */ if(userp) { if(!user && option && option[0] == ':') { /* Allocate an empty string instead of returning NULL as user name */ user = strdup(""); if(!user) result = CURLE_OUT_OF_MEMORY; } Curl_safefree(*userp); *userp = user; } /* Store the password part of option if required */ if(passwdp) { Curl_safefree(*passwdp); *passwdp = passwd; } } return result; } #define C_SSLVERSION_VALUE(x) (x & 0xffff) #define C_SSLVERSION_MAX_VALUE(x) (x & 0xffff0000) static CURLcode vsetopt(struct Curl_easy *data, CURLoption option, va_list param) { char *argptr; CURLcode result = CURLE_OK; long arg; unsigned long uarg; curl_off_t bigsize; switch(option) { case CURLOPT_DNS_CACHE_TIMEOUT: arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.dns_cache_timeout = arg; break; case CURLOPT_DNS_USE_GLOBAL_CACHE: /* deprecated */ break; case CURLOPT_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection for proxy */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_TLS13_CIPHERS: if(Curl_ssl_tls13_ciphersuites()) { /* set preferred list of TLS 1.3 cipher suites */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_ORIG], va_arg(param, char *)); } else return CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_TLS13_CIPHERS: if(Curl_ssl_tls13_ciphersuites()) { /* set preferred list of TLS 1.3 cipher suites for proxy */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_PROXY], va_arg(param, char *)); } else return CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_RANDOM_FILE: /* * This is the path name to a file that contains random data to seed * the random SSL stuff with. The file is only used for reading. */ result = Curl_setstropt(&data->set.str[STRING_SSL_RANDOM_FILE], va_arg(param, char *)); break; case CURLOPT_EGDSOCKET: /* * The Entropy Gathering Daemon socket pathname */ result = Curl_setstropt(&data->set.str[STRING_SSL_EGDSOCKET], va_arg(param, char *)); break; case CURLOPT_MAXCONNECTS: /* * Set the absolute number of maximum simultaneous alive connection that * libcurl is allowed to have. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxconnects = arg; break; case CURLOPT_FORBID_REUSE: /* * When this transfer is done, it must not be left to be reused by a * subsequent transfer but shall be closed immediately. */ data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FRESH_CONNECT: /* * This transfer shall not use a previously cached connection but * should be made with a fresh new connect! */ data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_VERBOSE: /* * Verbose means infof() calls that give a lot of information about * the connection and transfer procedures as well as internal choices. */ data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_HEADER: /* * Set to include the header in the general data output stream. */ data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_NOPROGRESS: /* * Shut off the internal supported progress meter */ data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.hide_progress) data->progress.flags |= PGRS_HIDE; else data->progress.flags &= ~PGRS_HIDE; break; case CURLOPT_NOBODY: /* * Do not include the body part in the output data stream. */ data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FAILONERROR: /* * Don't output the >=400 error code HTML-page, but instead only * return error. */ data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_KEEP_SENDING_ON_ERROR: data->set.http_keep_sending_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UPLOAD: case CURLOPT_PUT: /* * We want to sent data to the remote host. If this is HTTP, that equals * using the PUT request. */ data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.upload) { /* If this is HTTP, PUT is what's needed to "upload" */ data->set.httpreq = HTTPREQ_PUT; data->set.opt_no_body = FALSE; /* this is implied */ } else /* In HTTP, the opposite of upload is GET (unless NOBODY is true as then this can be changed to HEAD later on) */ data->set.httpreq = HTTPREQ_GET; break; case CURLOPT_REQUEST_TARGET: result = Curl_setstropt(&data->set.str[STRING_TARGET], va_arg(param, char *)); break; case CURLOPT_FILETIME: /* * Try to get the file time of the remote document. The time will * later (possibly) become available using curl_easy_getinfo(). */ data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SERVER_RESPONSE_TIMEOUT: /* * Option that specifies how quickly an server response must be obtained * before it is considered failure. For pingpong protocols. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.server_response_timeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; #ifndef CURL_DISABLE_TFTP case CURLOPT_TFTP_NO_OPTIONS: /* * Option that prevents libcurl from sending TFTP option requests to the * server. */ data->set.tftp_no_options = va_arg(param, long) != 0; break; case CURLOPT_TFTP_BLKSIZE: /* * TFTP option that specifies the block size to use for data transmission. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tftp_blksize = arg; break; #endif #ifndef CURL_DISABLE_NETRC case CURLOPT_NETRC: /* * Parse the $HOME/.netrc file */ arg = va_arg(param, long); if((arg < CURL_NETRC_IGNORED) || (arg > CURL_NETRC_REQUIRED)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_netrc = (enum CURL_NETRC_OPTION)arg; break; case CURLOPT_NETRC_FILE: /* * Use this file instead of the $HOME/.netrc file */ result = Curl_setstropt(&data->set.str[STRING_NETRC_FILE], va_arg(param, char *)); break; #endif case CURLOPT_TRANSFERTEXT: /* * This option was previously named 'FTPASCII'. Renamed to work with * more protocols than merely FTP. * * Transfer using ASCII (instead of BINARY). */ data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TIMECONDITION: /* * Set HTTP time condition. This must be one of the defines in the * curl/curl.h header file. */ arg = va_arg(param, long); if((arg < CURL_TIMECOND_NONE) || (arg > CURL_TIMECOND_LASTMOD)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.timecondition = (curl_TimeCond)arg; break; case CURLOPT_TIMEVALUE: /* * This is the value to compare with the remote document with the * method set with CURLOPT_TIMECONDITION */ data->set.timevalue = (time_t)va_arg(param, long); break; case CURLOPT_TIMEVALUE_LARGE: /* * This is the value to compare with the remote document with the * method set with CURLOPT_TIMECONDITION */ data->set.timevalue = (time_t)va_arg(param, curl_off_t); break; case CURLOPT_SSLVERSION: case CURLOPT_PROXY_SSLVERSION: /* * Set explicit SSL version to try to connect with, as some SSL * implementations are lame. */ #ifdef USE_SSL { long version, version_max; struct ssl_primary_config *primary = (option == CURLOPT_SSLVERSION ? &data->set.ssl.primary : &data->set.proxy_ssl.primary); arg = va_arg(param, long); version = C_SSLVERSION_VALUE(arg); version_max = C_SSLVERSION_MAX_VALUE(arg); if(version < CURL_SSLVERSION_DEFAULT || version >= CURL_SSLVERSION_LAST || version_max < CURL_SSLVERSION_MAX_NONE || version_max >= CURL_SSLVERSION_MAX_LAST) return CURLE_BAD_FUNCTION_ARGUMENT; primary->version = version; primary->version_max = version_max; } #else result = CURLE_UNKNOWN_OPTION; #endif break; #ifndef CURL_DISABLE_HTTP case CURLOPT_AUTOREFERER: /* * Switch on automatic referer that gets set if curl follows locations. */ data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_ACCEPT_ENCODING: /* * String to use at the value of Accept-Encoding header. * * If the encoding is set to "" we use an Accept-Encoding header that * encompasses all the encodings we support. * If the encoding is set to NULL we don't send an Accept-Encoding header * and ignore an received Content-Encoding header. * */ argptr = va_arg(param, char *); if(argptr && !*argptr) { argptr = Curl_all_content_encodings(); if(!argptr) result = CURLE_OUT_OF_MEMORY; else { result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr); free(argptr); } } else result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr); break; case CURLOPT_TRANSFER_ENCODING: data->set.http_transfer_encoding = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FOLLOWLOCATION: /* * Follow Location: header hints on a HTTP-server. */ data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UNRESTRICTED_AUTH: /* * Send authentication (user+password) when following locations, even when * hostname changed. */ data->set.allow_auth_to_other_hosts = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_MAXREDIRS: /* * The maximum amount of hops you allow curl to follow Location: * headers. This should mostly be used to detect never-ending loops. */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxredirs = arg; break; case CURLOPT_POSTREDIR: /* * Set the behaviour of POST when redirecting * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302 * CURL_REDIR_POST_301 - POST is kept as POST after 301 * CURL_REDIR_POST_302 - POST is kept as POST after 302 * CURL_REDIR_POST_303 - POST is kept as POST after 303 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303 * other - POST is kept as POST after 301 and 302 */ arg = va_arg(param, long); if(arg < CURL_REDIR_GET_ALL) /* no return error on too high numbers since the bitmask could be extended in a future */ return CURLE_BAD_FUNCTION_ARGUMENT; data->set.keep_post = arg & CURL_REDIR_POST_ALL; break; case CURLOPT_POST: /* Does this option serve a purpose anymore? Yes it does, when CURLOPT_POSTFIELDS isn't used and the POST data is read off the callback! */ if(va_arg(param, long)) { data->set.httpreq = HTTPREQ_POST; data->set.opt_no_body = FALSE; /* this is implied */ } else data->set.httpreq = HTTPREQ_GET; break; case CURLOPT_COPYPOSTFIELDS: /* * A string with POST data. Makes curl HTTP POST. Even if it is NULL. * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to * CURLOPT_COPYPOSTFIELDS and not altered later. */ argptr = va_arg(param, char *); if(!argptr || data->set.postfieldsize == -1) result = Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr); else { /* * Check that requested length does not overflow the size_t type. */ if((data->set.postfieldsize < 0) || ((sizeof(curl_off_t) != sizeof(size_t)) && (data->set.postfieldsize > (curl_off_t)((size_t)-1)))) result = CURLE_OUT_OF_MEMORY; else { char *p; (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); /* Allocate even when size == 0. This satisfies the need of possible later address compare to detect the COPYPOSTFIELDS mode, and to mark that postfields is used rather than read function or form data. */ p = malloc((size_t)(data->set.postfieldsize? data->set.postfieldsize:1)); if(!p) result = CURLE_OUT_OF_MEMORY; else { if(data->set.postfieldsize) memcpy(p, argptr, (size_t)data->set.postfieldsize); data->set.str[STRING_COPYPOSTFIELDS] = p; } } } data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS]; data->set.httpreq = HTTPREQ_POST; break; case CURLOPT_POSTFIELDS: /* * Like above, but use static data instead of copying it. */ data->set.postfields = va_arg(param, void *); /* Release old copied data. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.httpreq = HTTPREQ_POST; break; case CURLOPT_POSTFIELDSIZE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, long); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; case CURLOPT_POSTFIELDSIZE_LARGE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; case CURLOPT_HTTPPOST: /* * Set to make us do HTTP POST */ data->set.httppost = va_arg(param, struct curl_httppost *); data->set.httpreq = HTTPREQ_POST_FORM; data->set.opt_no_body = FALSE; /* this is implied */ break; #endif /* CURL_DISABLE_HTTP */ case CURLOPT_MIMEPOST: /* * Set to make us do MIME/form POST */ result = Curl_mime_set_subparts(&data->set.mimepost, va_arg(param, curl_mime *), FALSE); if(!result) { data->set.httpreq = HTTPREQ_POST_MIME; data->set.opt_no_body = FALSE; /* this is implied */ } break; case CURLOPT_REFERER: /* * String to set in the HTTP Referer: field. */ if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } result = Curl_setstropt(&data->set.str[STRING_SET_REFERER], va_arg(param, char *)); data->change.referer = data->set.str[STRING_SET_REFERER]; break; case CURLOPT_USERAGENT: /* * String to use in the HTTP User-Agent field */ result = Curl_setstropt(&data->set.str[STRING_USERAGENT], va_arg(param, char *)); break; case CURLOPT_HTTPHEADER: /* * Set a list with HTTP headers to use (or replace internals with) */ data->set.headers = va_arg(param, struct curl_slist *); break; #ifndef CURL_DISABLE_HTTP #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXYHEADER: /* * Set a list with proxy headers to use (or replace internals with) * * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a * long time we remain doing it this way until CURLOPT_PROXYHEADER is * used. As soon as this option has been used, if set to anything but * NULL, custom headers for proxies are only picked from this list. * * Set this option to NULL to restore the previous behavior. */ data->set.proxyheaders = va_arg(param, struct curl_slist *); break; #endif case CURLOPT_HEADEROPT: /* * Set header option. */ arg = va_arg(param, long); data->set.sep_headers = (bool)((arg & CURLHEADER_SEPARATE)? TRUE: FALSE); break; case CURLOPT_HTTP200ALIASES: /* * Set a list of aliases for HTTP 200 in response header */ data->set.http200aliases = va_arg(param, struct curl_slist *); break; #if !defined(CURL_DISABLE_COOKIES) case CURLOPT_COOKIE: /* * Cookie string to send to the remote server in the request. */ result = Curl_setstropt(&data->set.str[STRING_COOKIE], va_arg(param, char *)); break; case CURLOPT_COOKIEFILE: /* * Set cookie file to read and parse. Can be used multiple times. */ argptr = (char *)va_arg(param, void *); if(argptr) { struct curl_slist *cl; /* append the cookie file name to the list of file names, and deal with them later */ cl = curl_slist_append(data->change.cookielist, argptr); if(!cl) { curl_slist_free_all(data->change.cookielist); data->change.cookielist = NULL; return CURLE_OUT_OF_MEMORY; } data->change.cookielist = cl; /* store the list for later use */ } break; case CURLOPT_COOKIEJAR: /* * Set cookie file name to dump all cookies to when we're done. */ { struct CookieInfo *newcookies; result = Curl_setstropt(&data->set.str[STRING_COOKIEJAR], va_arg(param, char *)); /* * Activate the cookie parser. This may or may not already * have been made. */ newcookies = Curl_cookie_init(data, NULL, data->cookies, data->set.cookiesession); if(!newcookies) result = CURLE_OUT_OF_MEMORY; data->cookies = newcookies; } break; case CURLOPT_COOKIESESSION: /* * Set this option to TRUE to start a new "cookie session". It will * prevent the forthcoming read-cookies-from-file actions to accept * cookies that are marked as being session cookies, as they belong to a * previous session. * * In the original Netscape cookie spec, "session cookies" are cookies * with no expire date set. RFC2109 describes the same action if no * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds * a 'Discard' action that can enforce the discard even for cookies that * have a Max-Age. * * We run mostly with the original cookie spec, as hardly anyone implements * anything else. */ data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_COOKIELIST: argptr = va_arg(param, char *); if(argptr == NULL) break; if(strcasecompare(argptr, "ALL")) { /* clear all cookies */ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); Curl_cookie_clearall(data->cookies); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } else if(strcasecompare(argptr, "SESS")) { /* clear session cookies */ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); Curl_cookie_clearsess(data->cookies); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } else if(strcasecompare(argptr, "FLUSH")) { /* flush cookies to file, takes care of the locking */ Curl_flush_cookies(data, 0); } else if(strcasecompare(argptr, "RELOAD")) { /* reload cookies from file */ Curl_cookie_loadfiles(data); break; } else { if(!data->cookies) /* if cookie engine was not running, activate it */ data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE); argptr = strdup(argptr); if(!argptr || !data->cookies) { result = CURLE_OUT_OF_MEMORY; free(argptr); } else { Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); if(checkprefix("Set-Cookie:", argptr)) /* HTTP Header format line */ Curl_cookie_add(data, data->cookies, TRUE, FALSE, argptr + 11, NULL, NULL, TRUE); else /* Netscape format line */ Curl_cookie_add(data, data->cookies, FALSE, FALSE, argptr, NULL, NULL, TRUE); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); free(argptr); } } break; #endif /* !CURL_DISABLE_COOKIES */ case CURLOPT_HTTPGET: /* * Set to force us do HTTP GET */ if(va_arg(param, long)) { data->set.httpreq = HTTPREQ_GET; data->set.upload = FALSE; /* switch off upload */ data->set.opt_no_body = FALSE; /* this is implied */ } break; case CURLOPT_HTTP_VERSION: /* * This sets a requested HTTP version to be used. The value is one of * the listed enums in curl/curl.h. */ arg = va_arg(param, long); if(arg < CURL_HTTP_VERSION_NONE) return CURLE_BAD_FUNCTION_ARGUMENT; #ifndef USE_NGHTTP2 if(arg >= CURL_HTTP_VERSION_2) return CURLE_UNSUPPORTED_PROTOCOL; #else if(arg > CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) return CURLE_UNSUPPORTED_PROTOCOL; if(arg == CURL_HTTP_VERSION_NONE) arg = CURL_HTTP_VERSION_2TLS; #endif data->set.httpversion = arg; break; case CURLOPT_EXPECT_100_TIMEOUT_MS: /* * Time to wait for a response to a HTTP request containing an * Expect: 100-continue header before sending the data anyway. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.expect_100_timeout = arg; break; case CURLOPT_HTTP09_ALLOWED: arg = va_arg(param, unsigned long); if(arg > 1L) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.http09_allowed = arg ? TRUE : FALSE; break; #endif /* CURL_DISABLE_HTTP */ case CURLOPT_HTTPAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.httpauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authhost.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE); if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_SPNEGO auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without GSS-API or SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.httpauth = auth; } break; case CURLOPT_CUSTOMREQUEST: /* * Set a custom string to use as request */ result = Curl_setstropt(&data->set.str[STRING_CUSTOMREQUEST], va_arg(param, char *)); /* we don't set data->set.httpreq = HTTPREQ_CUSTOM; here, we continue as if we were using the already set type and this just changes the actual request keyword */ break; #ifndef CURL_DISABLE_PROXY case CURLOPT_HTTPPROXYTUNNEL: /* * Tunnel operations through the proxy instead of normal proxy use */ data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_PROXYPORT: /* * Explicitly set HTTP proxy port number. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.proxyport = arg; break; case CURLOPT_PROXYAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.proxyauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authproxy.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE); if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_SPNEGO auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without GSS-API or SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.proxyauth = auth; } break; case CURLOPT_PROXY: /* * Set proxy server:port to use as proxy. * * If the proxy is set to "" (and CURLOPT_SOCKS_PROXY is set to "" or NULL) * we explicitly say that we don't want to use a proxy * (even though there might be environment variables saying so). * * Setting it to NULL, means no proxy but allows the environment variables * to decide for us (if CURLOPT_SOCKS_PROXY setting it to NULL). */ result = Curl_setstropt(&data->set.str[STRING_PROXY], va_arg(param, char *)); break; case CURLOPT_PRE_PROXY: /* * Set proxy server:port to use as SOCKS proxy. * * If the proxy is set to "" or NULL we explicitly say that we don't want * to use the socks proxy. */ result = Curl_setstropt(&data->set.str[STRING_PRE_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXYTYPE: /* * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME */ arg = va_arg(param, long); if((arg < CURLPROXY_HTTP) || (arg > CURLPROXY_SOCKS5_HOSTNAME)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.proxytype = (curl_proxytype)arg; break; case CURLOPT_PROXY_TRANSFER_MODE: /* * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ switch(va_arg(param, long)) { case 0: data->set.proxy_transfer_mode = FALSE; break; case 1: data->set.proxy_transfer_mode = TRUE; break; default: /* reserve other values for future use */ result = CURLE_UNKNOWN_OPTION; break; } break; #endif /* CURL_DISABLE_PROXY */ case CURLOPT_SOCKS5_AUTH: data->set.socks5auth = va_arg(param, unsigned long); if(data->set.socks5auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) result = CURLE_NOT_BUILT_IN; break; #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) case CURLOPT_SOCKS5_GSSAPI_NEC: /* * Set flag for NEC SOCK5 support */ data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif #ifndef CURL_DISABLE_PROXY case CURLOPT_SOCKS5_GSSAPI_SERVICE: case CURLOPT_PROXY_SERVICE_NAME: /* * Set proxy authentication service name for Kerberos 5 and SPNEGO */ result = Curl_setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME], va_arg(param, char *)); break; #endif case CURLOPT_SERVICE_NAME: /* * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO */ result = Curl_setstropt(&data->set.str[STRING_SERVICE_NAME], va_arg(param, char *)); break; case CURLOPT_HEADERDATA: /* * Custom pointer to pass the header write callback function */ data->set.writeheader = (void *)va_arg(param, void *); break; case CURLOPT_ERRORBUFFER: /* * Error buffer provided by the caller to get the human readable * error string in. */ data->set.errorbuffer = va_arg(param, char *); break; case CURLOPT_WRITEDATA: /* * FILE pointer to write to. Or possibly * used as argument to the write callback. */ data->set.out = va_arg(param, void *); break; case CURLOPT_DIRLISTONLY: /* * An option that changes the command to one that asks for a list only, no * file info details. Used for FTP, POP3 and SFTP. */ data->set.ftp_list_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_APPEND: /* * We want to upload and append to an existing file. Used for FTP and * SFTP. */ data->set.ftp_append = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_FTP case CURLOPT_FTP_FILEMETHOD: /* * How do access files over FTP. */ arg = va_arg(param, long); if((arg < CURLFTPMETHOD_DEFAULT) || (arg > CURLFTPMETHOD_SINGLECWD)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftp_filemethod = (curl_ftpfile)arg; break; case CURLOPT_FTPPORT: /* * Use FTP PORT, this also specifies which IP address to use */ result = Curl_setstropt(&data->set.str[STRING_FTPPORT], va_arg(param, char *)); data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPRT: data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPSV: data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_PRET: data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_SSL_CCC: arg = va_arg(param, long); if((arg < CURLFTPSSL_CCC_NONE) || (arg > CURLFTPSSL_CCC_ACTIVE)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftp_ccc = (curl_ftpccc)arg; break; case CURLOPT_FTP_SKIP_PASV_IP: /* * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the * bypass of the IP address in PASV responses. */ data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_ACCOUNT: result = Curl_setstropt(&data->set.str[STRING_FTP_ACCOUNT], va_arg(param, char *)); break; case CURLOPT_FTP_ALTERNATIVE_TO_USER: result = Curl_setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER], va_arg(param, char *)); break; case CURLOPT_FTPSSLAUTH: /* * Set a specific auth for FTP-SSL transfers. */ arg = va_arg(param, long); if((arg < CURLFTPAUTH_DEFAULT) || (arg > CURLFTPAUTH_TLS)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftpsslauth = (curl_ftpauth)arg; break; case CURLOPT_KRBLEVEL: /* * A string that defines the kerberos security level. */ result = Curl_setstropt(&data->set.str[STRING_KRB_LEVEL], va_arg(param, char *)); data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE; break; #endif case CURLOPT_FTP_CREATE_MISSING_DIRS: /* * An FTP/SFTP option that modifies an upload to create missing * directories on the server. */ switch(va_arg(param, long)) { case 0: data->set.ftp_create_missing_dirs = 0; break; case 1: data->set.ftp_create_missing_dirs = 1; break; case 2: data->set.ftp_create_missing_dirs = 2; break; default: /* reserve other values for future use */ result = CURLE_UNKNOWN_OPTION; break; } break; case CURLOPT_READDATA: /* * FILE pointer to read the file to be uploaded from. Or possibly * used as argument to the read callback. */ data->set.in_set = va_arg(param, void *); break; case CURLOPT_INFILESIZE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.filesize = arg; break; case CURLOPT_INFILESIZE_LARGE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.filesize = bigsize; break; case CURLOPT_LOW_SPEED_LIMIT: /* * The low speed limit that if transfers are below this for * CURLOPT_LOW_SPEED_TIME, the transfer is aborted. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.low_speed_limit = arg; break; case CURLOPT_MAX_SEND_SPEED_LARGE: /* * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE * bytes per second the transfer is throttled.. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_send_speed = bigsize; break; case CURLOPT_MAX_RECV_SPEED_LARGE: /* * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per * second the transfer is throttled.. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_recv_speed = bigsize; break; case CURLOPT_LOW_SPEED_TIME: /* * The low speed time that if transfers are below the set * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.low_speed_time = arg; break; case CURLOPT_CURLU: /* * pass CURLU to set URL */ data->set.uh = va_arg(param, CURLU *); break; case CURLOPT_URL: /* * The URL to fetch. */ if(data->change.url_alloc) { /* the already set URL is allocated, free it first! */ Curl_safefree(data->change.url); data->change.url_alloc = FALSE; } result = Curl_setstropt(&data->set.str[STRING_SET_URL], va_arg(param, char *)); data->change.url = data->set.str[STRING_SET_URL]; break; case CURLOPT_PORT: /* * The port number to use when getting the URL */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_port = arg; break; case CURLOPT_TIMEOUT: /* * The maximum time you allow curl to use for a single transfer * operation. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.timeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLOPT_TIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.timeout = arg; break; case CURLOPT_CONNECTTIMEOUT: /* * The maximum time you allow curl to use to connect. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.connecttimeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLOPT_CONNECTTIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.connecttimeout = arg; break; case CURLOPT_ACCEPTTIMEOUT_MS: /* * The maximum time you allow curl to wait for server connect */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.accepttimeout = arg; break; case CURLOPT_USERPWD: /* * user:password to use in the operation */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_USERNAME], &data->set.str[STRING_PASSWORD]); break; case CURLOPT_USERNAME: /* * authentication user name to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_USERNAME], va_arg(param, char *)); break; case CURLOPT_PASSWORD: /* * authentication password to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PASSWORD], va_arg(param, char *)); break; case CURLOPT_LOGIN_OPTIONS: /* * authentication options to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_OPTIONS], va_arg(param, char *)); break; case CURLOPT_XOAUTH2_BEARER: /* * OAuth 2.0 bearer token to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_BEARER], va_arg(param, char *)); break; case CURLOPT_POSTQUOTE: /* * List of RAW FTP commands to use after a transfer */ data->set.postquote = va_arg(param, struct curl_slist *); break; case CURLOPT_PREQUOTE: /* * List of RAW FTP commands to use prior to RETR (Wesley Laxton) */ data->set.prequote = va_arg(param, struct curl_slist *); break; case CURLOPT_QUOTE: /* * List of RAW FTP commands to use before a transfer */ data->set.quote = va_arg(param, struct curl_slist *); break; case CURLOPT_RESOLVE: /* * List of NAME:[address] names to populate the DNS cache with * Prefix the NAME with dash (-) to _remove_ the name from the cache. * * Names added with this API will remain in the cache until explicitly * removed or the handle is cleaned up. * * This API can remove any name from the DNS cache, but only entries * that aren't actually in use right now will be pruned immediately. */ data->set.resolve = va_arg(param, struct curl_slist *); data->change.resolve = data->set.resolve; break; case CURLOPT_PROGRESSFUNCTION: /* * Progress callback function */ data->set.fprogress = va_arg(param, curl_progress_callback); if(data->set.fprogress) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_XFERINFOFUNCTION: /* * Transfer info callback function */ data->set.fxferinfo = va_arg(param, curl_xferinfo_callback); if(data->set.fxferinfo) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_PROGRESSDATA: /* * Custom client data to pass to the progress callback */ data->set.progress_client = va_arg(param, void *); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXYUSERPWD: /* * user:password needed to use the proxy */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_PROXYUSERNAME], &data->set.str[STRING_PROXYPASSWORD]); break; case CURLOPT_PROXYUSERNAME: /* * authentication user name to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PROXYUSERNAME], va_arg(param, char *)); break; case CURLOPT_PROXYPASSWORD: /* * authentication password to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PROXYPASSWORD], va_arg(param, char *)); break; case CURLOPT_NOPROXY: /* * proxy exception list */ result = Curl_setstropt(&data->set.str[STRING_NOPROXY], va_arg(param, char *)); break; #endif case CURLOPT_RANGE: /* * What range of the file you want to transfer */ result = Curl_setstropt(&data->set.str[STRING_SET_RANGE], va_arg(param, char *)); break; case CURLOPT_RESUME_FROM: /* * Resume transfer at the given file position */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.set_resume_from = arg; break; case CURLOPT_RESUME_FROM_LARGE: /* * Resume transfer at the given file position */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.set_resume_from = bigsize; break; case CURLOPT_DEBUGFUNCTION: /* * stderr write callback. */ data->set.fdebug = va_arg(param, curl_debug_callback); /* * if the callback provided is NULL, it'll use the default callback */ break; case CURLOPT_DEBUGDATA: /* * Set to a void * that should receive all error writes. This * defaults to CURLOPT_STDERR for normal operations. */ data->set.debugdata = va_arg(param, void *); break; case CURLOPT_STDERR: /* * Set to a FILE * that should receive all error writes. This * defaults to stderr for normal operations. */ data->set.err = va_arg(param, FILE *); if(!data->set.err) data->set.err = stderr; break; case CURLOPT_HEADERFUNCTION: /* * Set header write callback */ data->set.fwrite_header = va_arg(param, curl_write_callback); break; case CURLOPT_WRITEFUNCTION: /* * Set data write callback */ data->set.fwrite_func = va_arg(param, curl_write_callback); if(!data->set.fwrite_func) { data->set.is_fwrite_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fwrite_func = (curl_write_callback)fwrite; } else data->set.is_fwrite_set = 1; break; case CURLOPT_READFUNCTION: /* * Read data callback */ data->set.fread_func_set = va_arg(param, curl_read_callback); if(!data->set.fread_func_set) { data->set.is_fread_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fread_func_set = (curl_read_callback)fread; } else data->set.is_fread_set = 1; break; case CURLOPT_SEEKFUNCTION: /* * Seek callback. Might be NULL. */ data->set.seek_func = va_arg(param, curl_seek_callback); break; case CURLOPT_SEEKDATA: /* * Seek control callback. Might be NULL. */ data->set.seek_client = va_arg(param, void *); break; case CURLOPT_CONV_FROM_NETWORK_FUNCTION: /* * "Convert from network encoding" callback */ data->set.convfromnetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_TO_NETWORK_FUNCTION: /* * "Convert to network encoding" callback */ data->set.convtonetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_FROM_UTF8_FUNCTION: /* * "Convert from UTF-8 encoding" callback */ data->set.convfromutf8 = va_arg(param, curl_conv_callback); break; case CURLOPT_IOCTLFUNCTION: /* * I/O control callback. Might be NULL. */ data->set.ioctl_func = va_arg(param, curl_ioctl_callback); break; case CURLOPT_IOCTLDATA: /* * I/O control data pointer. Might be NULL. */ data->set.ioctl_client = va_arg(param, void *); break; case CURLOPT_SSLCERT: /* * String that holds file name of the SSL certificate to use */ result = Curl_setstropt(&data->set.str[STRING_CERT_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLCERT: /* * String that holds file name of the SSL certificate to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_CERT_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLCERTTYPE: /* * String that holds file type of the SSL certificate to use */ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLCERTTYPE: /* * String that holds file type of the SSL certificate to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLKEY: /* * String that holds file name of the SSL key to use */ result = Curl_setstropt(&data->set.str[STRING_KEY_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLKEY: /* * String that holds file name of the SSL key to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_KEY_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLKEYTYPE: /* * String that holds file type of the SSL key to use */ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLKEYTYPE: /* * String that holds file type of the SSL key to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_KEYPASSWD: /* * String that holds the SSL or SSH private key password. */ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_KEYPASSWD: /* * String that holds the SSL private key password for proxy. */ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLENGINE: /* * String that holds the SSL crypto engine. */ argptr = va_arg(param, char *); if(argptr && argptr[0]) { result = Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], argptr); if(!result) { result = Curl_ssl_set_engine(data, argptr); } } break; case CURLOPT_SSLENGINE_DEFAULT: /* * flag to set engine as default. */ Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], NULL); result = Curl_ssl_set_engine_default(data); break; case CURLOPT_CRLF: /* * Kludgy option to enable CRLF conversions. Subject for removal. */ data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_HAPROXYPROTOCOL: /* * Set to send the HAProxy Proxy Protocol header */ data->set.haproxyprotocol = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif case CURLOPT_INTERFACE: /* * Set what interface or address/hostname to bind the socket to when * performing an operation and thus what from-IP your connection will use. */ result = Curl_setstropt(&data->set.str[STRING_DEVICE], va_arg(param, char *)); break; case CURLOPT_LOCALPORT: /* * Set what local port to bind the socket to when performing an operation. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.localport = curlx_sltous(arg); break; case CURLOPT_LOCALPORTRANGE: /* * Set number of local ports to try, starting with CURLOPT_LOCALPORT. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.localportrange = curlx_sltosi(arg); break; case CURLOPT_GSSAPI_DELEGATION: /* * GSS-API credential delegation bitmask */ arg = va_arg(param, long); if(arg < CURLGSSAPI_DELEGATION_NONE) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.gssapi_delegation = arg; break; case CURLOPT_SSL_VERIFYPEER: /* * Enable peer SSL verifying. */ data->set.ssl.primary.verifypeer = (0 != va_arg(param, long)) ? TRUE : FALSE; /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer; } break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_VERIFYPEER: /* * Enable peer SSL verifying for proxy. */ data->set.proxy_ssl.primary.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE; /* Update the current connection proxy_ssl_config. */ if(data->conn) { data->conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer; } break; #endif case CURLOPT_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate */ arg = va_arg(param, long); /* Obviously people are not reading documentation and too many thought this argument took a boolean when it wasn't and misused it. We thus ban 1 as a sensible input and we warn about its use. Then we only have the 2 action internally stored as TRUE. */ if(1 == arg) { failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!"); return CURLE_BAD_FUNCTION_ARGUMENT; } data->set.ssl.primary.verifyhost = (0 != arg) ? TRUE : FALSE; /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost; } break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate for proxy */ arg = va_arg(param, long); /* Obviously people are not reading documentation and too many thought this argument took a boolean when it wasn't and misused it. We thus ban 1 as a sensible input and we warn about its use. Then we only have the 2 action internally stored as TRUE. */ if(1 == arg) { failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!"); return CURLE_BAD_FUNCTION_ARGUMENT; } data->set.proxy_ssl.primary.verifyhost = (0 != arg)?TRUE:FALSE; /* Update the current connection proxy_ssl_config. */ if(data->conn) { data->conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost; } break; #endif case CURLOPT_SSL_VERIFYSTATUS: /* * Enable certificate status verifying. */ if(!Curl_ssl_cert_status_request()) { result = CURLE_NOT_BUILT_IN; break; } data->set.ssl.primary.verifystatus = (0 != va_arg(param, long)) ? TRUE : FALSE; /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus; } break; case CURLOPT_SSL_CTX_FUNCTION: /* * Set a SSL_CTX callback */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_SSL_CTX) data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback); else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_SSL_CTX_DATA: /* * Set a SSL_CTX callback parameter pointer */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_SSL_CTX) data->set.ssl.fsslctxp = va_arg(param, void *); else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_SSL_FALSESTART: /* * Enable TLS false start. */ if(!Curl_ssl_false_start()) { result = CURLE_NOT_BUILT_IN; break; } data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CERTINFO: #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CERTINFO) data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE; else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_PINNEDPUBLICKEY: /* * Set pinned public key for SSL connection. * Specify file name of the public key in DER format. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY) result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_PINNEDPUBLICKEY: /* * Set pinned public key for SSL connection. * Specify file name of the public key in DER format. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY) result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_CAINFO: /* * Set CA info for SSL connection. Specify file name of the CA certificate */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CAINFO: /* * Set CA info SSL connection for proxy. Specify file name of the * CA certificate */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_CAPATH: /* * Set CA path info for SSL connection. Specify directory name of the CA * certificates which have been prepared using openssl c_rehash utility. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CA_PATH) /* This does not work on windows. */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_ORIG], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CAPATH: /* * Set CA path info for SSL connection proxy. Specify directory name of the * CA certificates which have been prepared using openssl c_rehash utility. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CA_PATH) /* This does not work on windows. */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_CRLFILE: /* * Set CRL file info for SSL connection. Specify file name of the CRL * to check certificates revocation */ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CRLFILE: /* * Set CRL file info for SSL connection for proxy. Specify file name of the * CRL to check certificates revocation */ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_ISSUERCERT: /* * Set Issuer certificate file * to check certificates issuer */ result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT_ORIG], va_arg(param, char *)); break; #ifndef CURL_DISABLE_TELNET case CURLOPT_TELNETOPTIONS: /* * Set a linked list of telnet options */ data->set.telnet_options = va_arg(param, struct curl_slist *); break; #endif case CURLOPT_BUFFERSIZE: /* * The application kindly asks for a differently sized receive buffer. * If it seems reasonable, we'll use it. */ arg = va_arg(param, long); if(arg > READBUFFER_MAX) arg = READBUFFER_MAX; else if(arg < 1) arg = READBUFFER_SIZE; else if(arg < READBUFFER_MIN) arg = READBUFFER_MIN; /* Resize if new size */ if(arg != data->set.buffer_size) { char *newbuff = realloc(data->state.buffer, arg + 1); if(!newbuff) { DEBUGF(fprintf(stderr, "Error: realloc of buffer failed\n")); result = CURLE_OUT_OF_MEMORY; } else data->state.buffer = newbuff; } data->set.buffer_size = arg; break; case CURLOPT_UPLOAD_BUFFERSIZE: /* * The application kindly asks for a differently sized upload buffer. * Cap it to sensible. */ arg = va_arg(param, long); if(arg > UPLOADBUFFER_MAX) arg = UPLOADBUFFER_MAX; else if(arg < UPLOADBUFFER_MIN) arg = UPLOADBUFFER_MIN; data->set.upload_buffer_size = arg; Curl_safefree(data->state.ulbuf); /* force a realloc next opportunity */ break; case CURLOPT_NOSIGNAL: /* * The application asks not to set any signal() or alarm() handlers, * even when using a timeout. */ data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SHARE: { struct Curl_share *set; set = va_arg(param, struct Curl_share *); /* disconnect from old share, if any */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); if(data->dns.hostcachetype == HCACHE_SHARED) { data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies == data->cookies) data->cookies = NULL; #endif if(data->share->sslsession == data->state.session) data->state.session = NULL; #ifdef USE_LIBPSL if(data->psl == &data->share->psl) data->psl = data->multi? &data->multi->psl: NULL; #endif data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); data->share = NULL; } /* use new share if it set */ data->share = set; if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty++; if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) { /* use shared host cache */ data->dns.hostcache = &data->share->hostcache; data->dns.hostcachetype = HCACHE_SHARED; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies) { /* use shared cookie list, first free own one if any */ Curl_cookie_cleanup(data->cookies); /* enable cookies since we now use a share that uses cookies! */ data->cookies = data->share->cookies; } #endif /* CURL_DISABLE_HTTP */ if(data->share->sslsession) { data->set.general_ssl.max_ssl_sessions = data->share->max_ssl_sessions; data->state.session = data->share->sslsession; } #ifdef USE_LIBPSL if(data->share->specifier & (1 << CURL_LOCK_DATA_PSL)) data->psl = &data->share->psl; #endif Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* check for host cache not needed, * it will be done by curl_easy_perform */ } break; case CURLOPT_PRIVATE: /* * Set private data pointer. */ data->set.private_data = va_arg(param, void *); break; case CURLOPT_MAXFILESIZE: /* * Set the maximum size of a file to download. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_filesize = arg; break; #ifdef USE_SSL case CURLOPT_USE_SSL: /* * Make transfers attempt to use SSL/TLS. */ arg = va_arg(param, long); if((arg < CURLUSESSL_NONE) || (arg > CURLUSESSL_ALL)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_ssl = (curl_usessl)arg; break; case CURLOPT_SSL_OPTIONS: arg = va_arg(param, long); data->set.ssl.enable_beast = (bool)((arg&CURLSSLOPT_ALLOW_BEAST) ? TRUE : FALSE); data->set.ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_OPTIONS: arg = va_arg(param, long); data->set.proxy_ssl.enable_beast = (bool)((arg&CURLSSLOPT_ALLOW_BEAST) ? TRUE : FALSE); data->set.proxy_ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); break; #endif #endif case CURLOPT_IPRESOLVE: arg = va_arg(param, long); if((arg < CURL_IPRESOLVE_WHATEVER) || (arg > CURL_IPRESOLVE_V6)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ipver = arg; break; case CURLOPT_MAXFILESIZE_LARGE: /* * Set the maximum size of a file to download. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_filesize = bigsize; break; case CURLOPT_TCP_NODELAY: /* * Enable or disable TCP_NODELAY, which will disable/enable the Nagle * algorithm */ data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_IGNORE_CONTENT_LENGTH: data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CONNECT_ONLY: /* * No data transfer, set up connection and let application use the socket */ data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SOCKOPTFUNCTION: /* * socket callback function: called after socket() but before connect() */ data->set.fsockopt = va_arg(param, curl_sockopt_callback); break; case CURLOPT_SOCKOPTDATA: /* * socket callback data pointer. Might be NULL. */ data->set.sockopt_client = va_arg(param, void *); break; case CURLOPT_OPENSOCKETFUNCTION: /* * open/create socket callback function: called instead of socket(), * before connect() */ data->set.fopensocket = va_arg(param, curl_opensocket_callback); break; case CURLOPT_OPENSOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.opensocket_client = va_arg(param, void *); break; case CURLOPT_CLOSESOCKETFUNCTION: /* * close socket callback function: called instead of close() * when shutting down a connection */ data->set.fclosesocket = va_arg(param, curl_closesocket_callback); break; case CURLOPT_RESOLVER_START_FUNCTION: /* * resolver start callback function: called before a new resolver request * is started */ data->set.resolver_start = va_arg(param, curl_resolver_start_callback); break; case CURLOPT_RESOLVER_START_DATA: /* * resolver start callback data pointer. Might be NULL. */ data->set.resolver_start_client = va_arg(param, void *); break; case CURLOPT_CLOSESOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.closesocket_client = va_arg(param, void *); break; case CURLOPT_SSL_SESSIONID_CACHE: data->set.ssl.primary.sessionid = (0 != va_arg(param, long)) ? TRUE : FALSE; data->set.proxy_ssl.primary.sessionid = data->set.ssl.primary.sessionid; break; #ifdef USE_SSH /* we only include SSH options if explicitly built to support SSH */ case CURLOPT_SSH_AUTH_TYPES: data->set.ssh_auth_types = va_arg(param, long); break; case CURLOPT_SSH_PUBLIC_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa.pub file */ result = Curl_setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_PRIVATE_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa file */ result = Curl_setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: /* * Option to allow for the MD5 of the host public key to be checked * for validation purposes. */ result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], va_arg(param, char *)); break; case CURLOPT_SSH_KNOWNHOSTS: /* * Store the file name to read known hosts from. */ result = Curl_setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS], va_arg(param, char *)); break; case CURLOPT_SSH_KEYFUNCTION: /* setting to NULL is fine since the ssh.c functions themselves will then rever to use the internal default */ data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback); break; case CURLOPT_SSH_KEYDATA: /* * Custom client data to pass to the SSH keyfunc callback */ data->set.ssh_keyfunc_userp = va_arg(param, void *); break; case CURLOPT_SSH_COMPRESSION: data->set.ssh_compression = (0 != va_arg(param, long))?TRUE:FALSE; break; #endif /* USE_SSH */ case CURLOPT_HTTP_TRANSFER_DECODING: /* * disable libcurl transfer encoding is used */ data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_HTTP_CONTENT_DECODING: /* * raw data passed to the application when content encoding is used */ data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; #if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) case CURLOPT_NEW_FILE_PERMS: /* * Uses these permissions instead of 0644 */ arg = va_arg(param, long); if((arg < 0) || (arg > 0777)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.new_file_perms = arg; break; case CURLOPT_NEW_DIRECTORY_PERMS: /* * Uses these permissions instead of 0755 */ arg = va_arg(param, long); if((arg < 0) || (arg > 0777)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.new_directory_perms = arg; break; #endif case CURLOPT_ADDRESS_SCOPE: /* * Use this scope id when using IPv6 * We always get longs when passed plain numericals so we should check * that the value fits into an unsigned 32 bit integer. */ uarg = va_arg(param, unsigned long); #if SIZEOF_LONG > 4 if(uarg > UINT_MAX) return CURLE_BAD_FUNCTION_ARGUMENT; #endif data->set.scope_id = (unsigned int)uarg; break; case CURLOPT_PROTOCOLS: /* set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO_ALL. */ data->set.allowed_protocols = va_arg(param, long); break; case CURLOPT_REDIR_PROTOCOLS: /* set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. Defaults to all protocols except FILE and SCP. */ data->set.redir_protocols = va_arg(param, long); break; case CURLOPT_DEFAULT_PROTOCOL: /* Set the protocol to use when the URL doesn't include any protocol */ result = Curl_setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL], va_arg(param, char *)); break; #ifndef CURL_DISABLE_SMTP case CURLOPT_MAIL_FROM: /* Set the SMTP mail originator */ result = Curl_setstropt(&data->set.str[STRING_MAIL_FROM], va_arg(param, char *)); break; case CURLOPT_MAIL_AUTH: /* Set the SMTP auth originator */ result = Curl_setstropt(&data->set.str[STRING_MAIL_AUTH], va_arg(param, char *)); break; case CURLOPT_MAIL_RCPT: /* Set the list of mail recipients */ data->set.mail_rcpt = va_arg(param, struct curl_slist *); break; #endif case CURLOPT_SASL_IR: /* Enable/disable SASL initial response */ data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_RTSP case CURLOPT_RTSP_REQUEST: { /* * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...) * Would this be better if the RTSPREQ_* were just moved into here? */ long curl_rtspreq = va_arg(param, long); Curl_RtspReq rtspreq = RTSPREQ_NONE; switch(curl_rtspreq) { case CURL_RTSPREQ_OPTIONS: rtspreq = RTSPREQ_OPTIONS; break; case CURL_RTSPREQ_DESCRIBE: rtspreq = RTSPREQ_DESCRIBE; break; case CURL_RTSPREQ_ANNOUNCE: rtspreq = RTSPREQ_ANNOUNCE; break; case CURL_RTSPREQ_SETUP: rtspreq = RTSPREQ_SETUP; break; case CURL_RTSPREQ_PLAY: rtspreq = RTSPREQ_PLAY; break; case CURL_RTSPREQ_PAUSE: rtspreq = RTSPREQ_PAUSE; break; case CURL_RTSPREQ_TEARDOWN: rtspreq = RTSPREQ_TEARDOWN; break; case CURL_RTSPREQ_GET_PARAMETER: rtspreq = RTSPREQ_GET_PARAMETER; break; case CURL_RTSPREQ_SET_PARAMETER: rtspreq = RTSPREQ_SET_PARAMETER; break; case CURL_RTSPREQ_RECORD: rtspreq = RTSPREQ_RECORD; break; case CURL_RTSPREQ_RECEIVE: rtspreq = RTSPREQ_RECEIVE; break; default: rtspreq = RTSPREQ_NONE; } data->set.rtspreq = rtspreq; break; } case CURLOPT_RTSP_SESSION_ID: /* * Set the RTSP Session ID manually. Useful if the application is * resuming a previously established RTSP session */ result = Curl_setstropt(&data->set.str[STRING_RTSP_SESSION_ID], va_arg(param, char *)); break; case CURLOPT_RTSP_STREAM_URI: /* * Set the Stream URI for the RTSP request. Unless the request is * for generic server options, the application will need to set this. */ result = Curl_setstropt(&data->set.str[STRING_RTSP_STREAM_URI], va_arg(param, char *)); break; case CURLOPT_RTSP_TRANSPORT: /* * The content of the Transport: header for the RTSP request */ result = Curl_setstropt(&data->set.str[STRING_RTSP_TRANSPORT], va_arg(param, char *)); break; case CURLOPT_RTSP_CLIENT_CSEQ: /* * Set the CSEQ number to issue for the next RTSP request. Useful if the * application is resuming a previously broken connection. The CSEQ * will increment from this new number henceforth. */ data->state.rtsp_next_client_CSeq = va_arg(param, long); break; case CURLOPT_RTSP_SERVER_CSEQ: /* Same as the above, but for server-initiated requests */ data->state.rtsp_next_client_CSeq = va_arg(param, long); break; case CURLOPT_INTERLEAVEDATA: data->set.rtp_out = va_arg(param, void *); break; case CURLOPT_INTERLEAVEFUNCTION: /* Set the user defined RTP write function */ data->set.fwrite_rtp = va_arg(param, curl_write_callback); break; #endif #ifndef CURL_DISABLE_FTP case CURLOPT_WILDCARDMATCH: data->set.wildcard_enabled = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CHUNK_BGN_FUNCTION: data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback); break; case CURLOPT_CHUNK_END_FUNCTION: data->set.chunk_end = va_arg(param, curl_chunk_end_callback); break; case CURLOPT_FNMATCH_FUNCTION: data->set.fnmatch = va_arg(param, curl_fnmatch_callback); break; case CURLOPT_CHUNK_DATA: data->wildcard.customptr = va_arg(param, void *); break; case CURLOPT_FNMATCH_DATA: data->set.fnmatch_data = va_arg(param, void *); break; #endif #ifdef USE_TLS_SRP case CURLOPT_TLSAUTH_USERNAME: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_ORIG], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_PROXY_TLSAUTH_USERNAME: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_PROXY], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] && !data->set.proxy_ssl.authtype) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_TLSAUTH_PASSWORD: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_ORIG], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_PROXY_TLSAUTH_PASSWORD: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_PROXY], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] && !data->set.proxy_ssl.authtype) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_TLSAUTH_TYPE: argptr = va_arg(param, char *); if(!argptr || strncasecompare(argptr, "SRP", strlen("SRP"))) data->set.ssl.authtype = CURL_TLSAUTH_SRP; else data->set.ssl.authtype = CURL_TLSAUTH_NONE; break; case CURLOPT_PROXY_TLSAUTH_TYPE: argptr = va_arg(param, char *); if(!argptr || strncasecompare(argptr, "SRP", strlen("SRP"))) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; else data->set.proxy_ssl.authtype = CURL_TLSAUTH_NONE; break; #endif #ifdef USE_ARES case CURLOPT_DNS_SERVERS: result = Curl_set_dns_servers(data, va_arg(param, char *)); break; case CURLOPT_DNS_INTERFACE: result = Curl_set_dns_interface(data, va_arg(param, char *)); break; case CURLOPT_DNS_LOCAL_IP4: result = Curl_set_dns_local_ip4(data, va_arg(param, char *)); break; case CURLOPT_DNS_LOCAL_IP6: result = Curl_set_dns_local_ip6(data, va_arg(param, char *)); break; #endif case CURLOPT_TCP_KEEPALIVE: data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TCP_KEEPIDLE: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tcp_keepidle = arg; break; case CURLOPT_TCP_KEEPINTVL: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tcp_keepintvl = arg; break; case CURLOPT_TCP_FASTOPEN: #if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) || \ defined(TCP_FASTOPEN_CONNECT) data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE; #else result = CURLE_NOT_BUILT_IN; #endif break; #ifdef USE_NGHTTP2 case CURLOPT_SSL_ENABLE_NPN: data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_ENABLE_ALPN: data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif #ifdef USE_UNIX_SOCKETS case CURLOPT_UNIX_SOCKET_PATH: data->set.abstract_unix_socket = FALSE; result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], va_arg(param, char *)); break; case CURLOPT_ABSTRACT_UNIX_SOCKET: data->set.abstract_unix_socket = TRUE; result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], va_arg(param, char *)); break; #endif case CURLOPT_PATH_AS_IS: data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_PIPEWAIT: data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_STREAM_WEIGHT: #ifndef USE_NGHTTP2 return CURLE_NOT_BUILT_IN; #else arg = va_arg(param, long); if((arg >= 1) && (arg <= 256)) data->set.stream_weight = (int)arg; break; #endif case CURLOPT_STREAM_DEPENDS: case CURLOPT_STREAM_DEPENDS_E: { #ifndef USE_NGHTTP2 return CURLE_NOT_BUILT_IN; #else struct Curl_easy *dep = va_arg(param, struct Curl_easy *); if(!dep || GOOD_EASY_HANDLE(dep)) { if(data->set.stream_depends_on) { Curl_http2_remove_child(data->set.stream_depends_on, data); } Curl_http2_add_child(dep, data, (option == CURLOPT_STREAM_DEPENDS_E)); } break; #endif } case CURLOPT_CONNECT_TO: data->set.connect_to = va_arg(param, struct curl_slist *); break; case CURLOPT_SUPPRESS_CONNECT_HEADERS: data->set.suppress_connect_headers = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.happy_eyeballs_timeout = arg; break; #ifndef CURL_DISABLE_SHUFFLE_DNS case CURLOPT_DNS_SHUFFLE_ADDRESSES: data->set.dns_shuffle_addresses = (0 != va_arg(param, long)) ? TRUE:FALSE; break; #endif case CURLOPT_DISALLOW_USERNAME_IN_URL: data->set.disallow_username_in_url = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_DOH case CURLOPT_DOH_URL: result = Curl_setstropt(&data->set.str[STRING_DOH], va_arg(param, char *)); data->set.doh = data->set.str[STRING_DOH]?TRUE:FALSE; break; #endif case CURLOPT_UPKEEP_INTERVAL_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.upkeep_interval_ms = arg; break; case CURLOPT_MAXAGE_CONN: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxage_conn = arg; break; case CURLOPT_TRAILERFUNCTION: #ifndef CURL_DISABLE_HTTP data->set.trailer_callback = va_arg(param, curl_trailer_callback); #endif break; case CURLOPT_TRAILERDATA: #ifndef CURL_DISABLE_HTTP data->set.trailer_data = va_arg(param, void *); #endif break; #ifdef USE_ALTSVC case CURLOPT_ALTSVC: if(!data->asi) { data->asi = Curl_altsvc_init(); if(!data->asi) return CURLE_OUT_OF_MEMORY; } argptr = va_arg(param, char *); result = Curl_setstropt(&data->set.str[STRING_ALTSVC], argptr); if(result) return result; (void)Curl_altsvc_load(data->asi, argptr); break; case CURLOPT_ALTSVC_CTRL: if(!data->asi) { data->asi = Curl_altsvc_init(); if(!data->asi) return CURLE_OUT_OF_MEMORY; } arg = va_arg(param, long); result = Curl_altsvc_ctrl(data->asi, arg); if(result) return result; break; #endif default: /* unknown tag and its companion, just ignore: */ result = CURLE_UNKNOWN_OPTION; break; } return result; } /* * curl_easy_setopt() is the external interface for setting options on an * easy handle. * * NOTE: This is one of few API functions that are allowed to be called from * within a callback. */ #undef curl_easy_setopt CURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...) { va_list arg; CURLcode result; if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; va_start(arg, tag); result = vsetopt(data, tag, arg); va_end(arg); return result; }
YifuLiu/AliOS-Things
components/curl/lib/setopt.c
C
apache-2.0
83,353
#ifndef HEADER_CURL_SETOPT_H #define HEADER_CURL_SETOPT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ CURLcode Curl_setstropt(char **charp, const char *s); CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list arg); #endif /* HEADER_CURL_SETOPT_H */
YifuLiu/AliOS-Things
components/curl/lib/setopt.h
C
apache-2.0
1,275
#ifndef HEADER_CURL_SETUP_OS400_H #define HEADER_CURL_SETUP_OS400_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* 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); #define connect Curl_os400_connect #define bind Curl_os400_bind #define sendto Curl_os400_sendto #define recvfrom Curl_os400_recvfrom #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 */
YifuLiu/AliOS-Things
components/curl/lib/setup-os400.h
C
apache-2.0
10,320
#ifndef HEADER_CURL_SETUP_VMS_H #define HEADER_CURL_SETUP_VMS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* */ /* 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 == NULL) { 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 == NULL) { 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 == NULL) { 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 */
YifuLiu/AliOS-Things
components/curl/lib/setup-vms.h
C
apache-2.0
14,767
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Florin Petriuc, <petriuc.florin@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_CRYPTO_AUTH #include "warnless.h" #include "curl_sha256.h" #if defined(USE_OPENSSL) #include <openssl/opensslv.h> #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) #define USE_OPENSSL_SHA256 #endif #endif #ifdef USE_OPENSSL_SHA256 /* When OpenSSL is available we use the SHA256-function from OpenSSL */ #include <openssl/sha.h> #else /* When no other crypto library is available we use this code segment */ /* ===== start - public domain SHA256 implementation ===== */ /* 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 typedef struct sha256_state { #ifdef HAVE_LONGLONG unsigned long long length; #else unsigned __int64 length; #endif unsigned long state[8], curlen; unsigned char buf[64]; } 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) \ 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; 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 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 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 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; } /* ===== end - public domain SHA256 implementation ===== */ #endif void Curl_sha256it(unsigned char *outbuffer, /* 32 unsigned chars */ const unsigned char *input) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, input, curlx_uztoui(strlen((char *)input))); SHA256_Final(outbuffer, &ctx); } #endif /* CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/sha256.c
C
apache-2.0
9,455
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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->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(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); 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) { 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: /* not supported (yet) */ 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; } 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(share == NULL) 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); 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 == NULL) 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 == NULL) 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; }
YifuLiu/AliOS-Things
components/curl/lib/share.c
C
apache-2.0
6,314
#ifndef HEADER_CURL_SHARE_H #define HEADER_CURL_SHARE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "cookie.h" #include "psl.h" #include "urldata.h" #include "conncache.h" /* SalfordC says "A structure member may not be volatile". Hence: */ #ifdef __SALFORDC__ #define CURL_VOLATILE #else #define CURL_VOLATILE volatile #endif /* this struct is libcurl-private, don't export details */ struct Curl_share { unsigned int specifier; CURL_VOLATILE unsigned int dirty; curl_lock_function lockfunc; curl_unlock_function unlockfunc; void *clientdata; struct conncache conn_cache; struct curl_hash hostcache; #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) struct CookieInfo *cookies; #endif #ifdef USE_LIBPSL struct PslCache psl; #endif struct curl_ssl_session *sslsession; size_t max_ssl_sessions; long sessionage; }; CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data, curl_lock_access); CURLSHcode Curl_share_unlock(struct Curl_easy *, curl_lock_data); #endif /* HEADER_CURL_SHARE_H */
YifuLiu/AliOS-Things
components/curl/lib/share.h
C
apache-2.0
2,108
#ifndef HEADER_CURL_SIGPIPE_H #define HEADER_CURL_SIGPIPE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(HAVE_SIGNAL_H) && defined(HAVE_SIGACTION) && \ (defined(USE_OPENSSL) || defined(USE_MBEDTLS)) #include <signal.h> struct sigpipe_ignore { struct sigaction old_pipe_act; bool no_signal; }; #define SIGPIPE_VARIABLE(x) struct sigpipe_ignore x /* * sigpipe_ignore() makes sure we ignore SIGPIPE while running libcurl * internals, and then sigpipe_restore() will restore the situation when we * return from libcurl again. */ static void sigpipe_ignore(struct Curl_easy *data, struct sigpipe_ignore *ig) { /* get a local copy of no_signal because the Curl_easy might not be around when we restore */ ig->no_signal = data->set.no_signal; if(!data->set.no_signal) { struct sigaction action; /* first, extract the existing situation */ memset(&ig->old_pipe_act, 0, sizeof(struct sigaction)); sigaction(SIGPIPE, NULL, &ig->old_pipe_act); action = ig->old_pipe_act; /* ignore this signal */ action.sa_handler = SIG_IGN; sigaction(SIGPIPE, &action, NULL); } } /* * sigpipe_restore() puts back the outside world's opinion of signal handler * and SIGPIPE handling. It MUST only be called after a corresponding * sigpipe_ignore() was used. */ static void sigpipe_restore(struct sigpipe_ignore *ig) { if(!ig->no_signal) /* restore the outside state */ sigaction(SIGPIPE, &ig->old_pipe_act, NULL); } #else /* for systems without sigaction */ #define sigpipe_ignore(x,y) Curl_nop_stmt #define sigpipe_restore(x) Curl_nop_stmt #define SIGPIPE_VARIABLE(x) #endif #endif /* HEADER_CURL_SIGPIPE_H */
YifuLiu/AliOS-Things
components/curl/lib/sigpipe.h
C
apache-2.0
2,711
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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); }
YifuLiu/AliOS-Things
components/curl/lib/slist.c
C
apache-2.0
3,940
#ifndef HEADER_CURL_SLIST_H #define HEADER_CURL_SLIST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Curl_slist_duplicate() duplicates a linked list. It always returns the * address of the first record of the cloned list or NULL in case of an * error (or if the input list was NULL). */ struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); /* * Curl_slist_append_nodup() takes ownership of the given string and appends * it to the list. */ struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data); #endif /* HEADER_CURL_SLIST_H */
YifuLiu/AliOS-Things
components/curl/lib/slist.h
C
apache-2.0
1,608
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014, Bill Nagel <wnagel@tycoint.com>, Exacq Technologies * Copyright (C) 2016-2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \ (CURL_SIZEOF_CURL_OFF_T > 4) #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) #define BUILDING_CURL_SMB_C #ifdef HAVE_PROCESS_H #include <process.h> #ifdef CURL_WINDOWS_APP #define getpid GetCurrentProcessId #elif !defined(MSDOS) #define getpid _getpid #endif #endif #include "smb.h" #include "urldata.h" #include "sendf.h" #include "multiif.h" #include "connect.h" #include "progress.h" #include "transfer.h" #include "vtls/vtls.h" #include "curl_ntlm_core.h" #include "escape.h" #include "curl_endian.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Local API functions */ static CURLcode smb_setup_connection(struct connectdata *conn); static CURLcode smb_connect(struct connectdata *conn, bool *done); static CURLcode smb_connection_state(struct connectdata *conn, bool *done); static CURLcode smb_do(struct connectdata *conn, bool *done); static CURLcode smb_request_state(struct connectdata *conn, bool *done); static CURLcode smb_done(struct connectdata *conn, CURLcode status, bool premature); static CURLcode smb_disconnect(struct connectdata *conn, bool dead); static int smb_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode smb_parse_url_path(struct connectdata *conn); /* * SMB handler interface */ const struct Curl_handler Curl_handler_smb = { "SMB", /* scheme */ smb_setup_connection, /* setup_connection */ smb_do, /* do_it */ smb_done, /* done */ ZERO_NULL, /* do_more */ smb_connect, /* connect_it */ smb_connection_state, /* connecting */ smb_request_state, /* doing */ smb_getsock, /* proto_getsock */ smb_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smb_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMB, /* defport */ CURLPROTO_SMB, /* protocol */ PROTOPT_NONE /* flags */ }; #ifdef USE_SSL /* * SMBS handler interface */ const struct Curl_handler Curl_handler_smbs = { "SMBS", /* scheme */ smb_setup_connection, /* setup_connection */ smb_do, /* do_it */ smb_done, /* done */ ZERO_NULL, /* do_more */ smb_connect, /* connect_it */ smb_connection_state, /* connecting */ smb_request_state, /* doing */ smb_getsock, /* proto_getsock */ smb_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smb_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMBS, /* defport */ CURLPROTO_SMBS, /* protocol */ PROTOPT_SSL /* flags */ }; #endif #define MAX_PAYLOAD_SIZE 0x8000 #define MAX_MESSAGE_SIZE (MAX_PAYLOAD_SIZE + 0x1000) #define CLIENTNAME "curl" #define SERVICENAME "?????" /* Append a string to an SMB message */ #define MSGCAT(str) \ strcpy(p, (str)); \ p += strlen(str); /* Append a null-terminated string to an SMB message */ #define MSGCATNULL(str) \ strcpy(p, (str)); \ p += strlen(str) + 1; /* SMB is mostly little endian */ #if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \ defined(__OS400__) static unsigned short smb_swap16(unsigned short x) { return (unsigned short) ((x << 8) | ((x >> 8) & 0xff)); } static unsigned int smb_swap32(unsigned int x) { return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | ((x >> 24) & 0xff); } static curl_off_t smb_swap64(curl_off_t x) { return ((curl_off_t) smb_swap32((unsigned int) x) << 32) | smb_swap32((unsigned int) (x >> 32)); } #else # define smb_swap16(x) (x) # define smb_swap32(x) (x) # define smb_swap64(x) (x) #endif /* SMB request state */ enum smb_req_state { SMB_REQUESTING, SMB_TREE_CONNECT, SMB_OPEN, SMB_DOWNLOAD, SMB_UPLOAD, SMB_CLOSE, SMB_TREE_DISCONNECT, SMB_DONE }; /* SMB request data */ struct smb_request { enum smb_req_state state; char *path; unsigned short tid; /* Even if we connect to the same tree as another */ unsigned short fid; /* request, the tid will be different */ CURLcode result; }; static void conn_state(struct connectdata *conn, enum smb_conn_state newstate) { struct smb_conn *smbc = &conn->proto.smbc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* For debug purposes */ static const char * const names[] = { "SMB_NOT_CONNECTED", "SMB_CONNECTING", "SMB_NEGOTIATE", "SMB_SETUP", "SMB_CONNECTED", /* LAST */ }; if(smbc->state != newstate) infof(conn->data, "SMB conn %p state change from %s to %s\n", (void *)smbc, names[smbc->state], names[newstate]); #endif smbc->state = newstate; } static void request_state(struct connectdata *conn, enum smb_req_state newstate) { struct smb_request *req = conn->data->req.protop; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* For debug purposes */ static const char * const names[] = { "SMB_REQUESTING", "SMB_TREE_CONNECT", "SMB_OPEN", "SMB_DOWNLOAD", "SMB_UPLOAD", "SMB_CLOSE", "SMB_TREE_DISCONNECT", "SMB_DONE", /* LAST */ }; if(req->state != newstate) infof(conn->data, "SMB request %p state change from %s to %s\n", (void *)req, names[req->state], names[newstate]); #endif req->state = newstate; } /* this should setup things in the connection, not in the easy handle */ static CURLcode smb_setup_connection(struct connectdata *conn) { struct smb_request *req; /* Initialize the request state */ conn->data->req.protop = req = calloc(1, sizeof(struct smb_request)); if(!req) return CURLE_OUT_OF_MEMORY; /* Parse the URL path */ return smb_parse_url_path(conn); } static CURLcode smb_connect(struct connectdata *conn, bool *done) { struct smb_conn *smbc = &conn->proto.smbc; char *slash; (void) done; /* Check we have a username and password to authenticate with */ if(!conn->bits.user_passwd) return CURLE_LOGIN_DENIED; /* Initialize the connection state */ smbc->state = SMB_CONNECTING; smbc->recv_buf = malloc(MAX_MESSAGE_SIZE); if(!smbc->recv_buf) return CURLE_OUT_OF_MEMORY; /* Multiple requests are allowed with this connection */ connkeep(conn, "SMB default"); /* Parse the username, domain, and password */ slash = strchr(conn->user, '/'); if(!slash) slash = strchr(conn->user, '\\'); if(slash) { smbc->user = slash + 1; smbc->domain = strdup(conn->user); if(!smbc->domain) return CURLE_OUT_OF_MEMORY; smbc->domain[slash - conn->user] = 0; } else { smbc->user = conn->user; smbc->domain = strdup(conn->host.name); if(!smbc->domain) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } static CURLcode smb_recv_message(struct connectdata *conn, void **msg) { struct smb_conn *smbc = &conn->proto.smbc; char *buf = smbc->recv_buf; ssize_t bytes_read; size_t nbt_size; size_t msg_size; size_t len = MAX_MESSAGE_SIZE - smbc->got; CURLcode result; result = Curl_read(conn, FIRSTSOCKET, buf + smbc->got, len, &bytes_read); if(result) return result; if(!bytes_read) return CURLE_OK; smbc->got += bytes_read; /* Check for a 32-bit nbt header */ if(smbc->got < sizeof(unsigned int)) return CURLE_OK; nbt_size = Curl_read16_be((const unsigned char *) (buf + sizeof(unsigned short))) + sizeof(unsigned int); if(smbc->got < nbt_size) return CURLE_OK; msg_size = sizeof(struct smb_header); if(nbt_size >= msg_size + 1) { /* Add the word count */ msg_size += 1 + ((unsigned char) buf[msg_size]) * sizeof(unsigned short); if(nbt_size >= msg_size + sizeof(unsigned short)) { /* Add the byte count */ msg_size += sizeof(unsigned short) + Curl_read16_le((const unsigned char *)&buf[msg_size]); if(nbt_size < msg_size) return CURLE_READ_ERROR; } } *msg = buf; return CURLE_OK; } static void smb_pop_message(struct connectdata *conn) { struct smb_conn *smbc = &conn->proto.smbc; smbc->got = 0; } static void smb_format_message(struct connectdata *conn, struct smb_header *h, unsigned char cmd, size_t len) { struct smb_conn *smbc = &conn->proto.smbc; struct smb_request *req = conn->data->req.protop; unsigned int pid; memset(h, 0, sizeof(*h)); h->nbt_length = htons((unsigned short) (sizeof(*h) - sizeof(unsigned int) + len)); memcpy((char *)h->magic, "\xffSMB", 4); h->command = cmd; h->flags = SMB_FLAGS_CANONICAL_PATHNAMES | SMB_FLAGS_CASELESS_PATHNAMES; h->flags2 = smb_swap16(SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_KNOWS_LONG_NAME); h->uid = smb_swap16(smbc->uid); h->tid = smb_swap16(req->tid); pid = getpid(); h->pid_high = smb_swap16((unsigned short)(pid >> 16)); h->pid = smb_swap16((unsigned short) pid); } static CURLcode smb_send(struct connectdata *conn, ssize_t len, size_t upload_size) { struct smb_conn *smbc = &conn->proto.smbc; ssize_t bytes_written; CURLcode result; result = Curl_write(conn, FIRSTSOCKET, conn->data->state.ulbuf, len, &bytes_written); if(result) return result; if(bytes_written != len) { smbc->send_size = len; smbc->sent = bytes_written; } smbc->upload_size = upload_size; return CURLE_OK; } static CURLcode smb_flush(struct connectdata *conn) { struct smb_conn *smbc = &conn->proto.smbc; ssize_t bytes_written; ssize_t len = smbc->send_size - smbc->sent; CURLcode result; if(!smbc->send_size) return CURLE_OK; result = Curl_write(conn, FIRSTSOCKET, conn->data->state.ulbuf + smbc->sent, len, &bytes_written); if(result) return result; if(bytes_written != len) smbc->sent += bytes_written; else smbc->send_size = 0; return CURLE_OK; } static CURLcode smb_send_message(struct connectdata *conn, unsigned char cmd, const void *msg, size_t msg_len) { CURLcode result = Curl_get_upload_buffer(conn->data); if(result) return result; smb_format_message(conn, (struct smb_header *)conn->data->state.ulbuf, cmd, msg_len); memcpy(conn->data->state.ulbuf + sizeof(struct smb_header), msg, msg_len); return smb_send(conn, sizeof(struct smb_header) + msg_len, 0); } static CURLcode smb_send_negotiate(struct connectdata *conn) { const char *msg = "\x00\x0c\x00\x02NT LM 0.12"; return smb_send_message(conn, SMB_COM_NEGOTIATE, msg, 15); } static CURLcode smb_send_setup(struct connectdata *conn) { struct smb_conn *smbc = &conn->proto.smbc; struct smb_setup msg; char *p = msg.bytes; unsigned char lm_hash[21]; unsigned char lm[24]; unsigned char nt_hash[21]; unsigned char nt[24]; size_t byte_count = sizeof(lm) + sizeof(nt); byte_count += strlen(smbc->user) + strlen(smbc->domain); byte_count += strlen(OS) + strlen(CLIENTNAME) + 4; /* 4 null chars */ if(byte_count > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; Curl_ntlm_core_mk_lm_hash(conn->data, conn->passwd, lm_hash); Curl_ntlm_core_lm_resp(lm_hash, smbc->challenge, lm); #ifdef USE_NTRESPONSES Curl_ntlm_core_mk_nt_hash(conn->data, conn->passwd, nt_hash); Curl_ntlm_core_lm_resp(nt_hash, smbc->challenge, nt); #else memset(nt, 0, sizeof(nt)); #endif memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_SETUP_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.max_buffer_size = smb_swap16(MAX_MESSAGE_SIZE); msg.max_mpx_count = smb_swap16(1); msg.vc_number = smb_swap16(1); msg.session_key = smb_swap32(smbc->session_key); msg.capabilities = smb_swap32(SMB_CAP_LARGE_FILES); msg.lengths[0] = smb_swap16(sizeof(lm)); msg.lengths[1] = smb_swap16(sizeof(nt)); memcpy(p, lm, sizeof(lm)); p += sizeof(lm); memcpy(p, nt, sizeof(nt)); p += sizeof(nt); MSGCATNULL(smbc->user); MSGCATNULL(smbc->domain); MSGCATNULL(OS); MSGCATNULL(CLIENTNAME); byte_count = p - msg.bytes; msg.byte_count = smb_swap16((unsigned short)byte_count); return smb_send_message(conn, SMB_COM_SETUP_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_tree_connect(struct connectdata *conn) { struct smb_tree_connect msg; struct smb_conn *smbc = &conn->proto.smbc; char *p = msg.bytes; size_t byte_count = strlen(conn->host.name) + strlen(smbc->share); byte_count += strlen(SERVICENAME) + 5; /* 2 nulls and 3 backslashes */ if(byte_count > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_TREE_CONNECT_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.pw_len = 0; MSGCAT("\\\\"); MSGCAT(conn->host.name); MSGCAT("\\"); MSGCATNULL(smbc->share); MSGCATNULL(SERVICENAME); /* Match any type of service */ byte_count = p - msg.bytes; msg.byte_count = smb_swap16((unsigned short)byte_count); return smb_send_message(conn, SMB_COM_TREE_CONNECT_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_open(struct connectdata *conn) { struct smb_request *req = conn->data->req.protop; struct smb_nt_create msg; size_t byte_count; if((strlen(req->path) + 1) > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_NT_CREATE_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; byte_count = strlen(req->path); msg.name_length = smb_swap16((unsigned short)byte_count); msg.share_access = smb_swap32(SMB_FILE_SHARE_ALL); if(conn->data->set.upload) { msg.access = smb_swap32(SMB_GENERIC_READ | SMB_GENERIC_WRITE); msg.create_disposition = smb_swap32(SMB_FILE_OVERWRITE_IF); } else { msg.access = smb_swap32(SMB_GENERIC_READ); msg.create_disposition = smb_swap32(SMB_FILE_OPEN); } msg.byte_count = smb_swap16((unsigned short) ++byte_count); strcpy(msg.bytes, req->path); return smb_send_message(conn, SMB_COM_NT_CREATE_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_close(struct connectdata *conn) { struct smb_request *req = conn->data->req.protop; struct smb_close msg; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_CLOSE; msg.fid = smb_swap16(req->fid); return smb_send_message(conn, SMB_COM_CLOSE, &msg, sizeof(msg)); } static CURLcode smb_send_tree_disconnect(struct connectdata *conn) { struct smb_tree_disconnect msg; memset(&msg, 0, sizeof(msg)); return smb_send_message(conn, SMB_COM_TREE_DISCONNECT, &msg, sizeof(msg)); } static CURLcode smb_send_read(struct connectdata *conn) { struct smb_request *req = conn->data->req.protop; curl_off_t offset = conn->data->req.offset; struct smb_read msg; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_READ_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.fid = smb_swap16(req->fid); msg.offset = smb_swap32((unsigned int) offset); msg.offset_high = smb_swap32((unsigned int) (offset >> 32)); msg.min_bytes = smb_swap16(MAX_PAYLOAD_SIZE); msg.max_bytes = smb_swap16(MAX_PAYLOAD_SIZE); return smb_send_message(conn, SMB_COM_READ_ANDX, &msg, sizeof(msg)); } static CURLcode smb_send_write(struct connectdata *conn) { struct smb_write *msg; struct smb_request *req = conn->data->req.protop; curl_off_t offset = conn->data->req.offset; curl_off_t upload_size = conn->data->req.size - conn->data->req.bytecount; CURLcode result = Curl_get_upload_buffer(conn->data); if(result) return result; msg = (struct smb_write *)conn->data->state.ulbuf; if(upload_size >= MAX_PAYLOAD_SIZE - 1) /* There is one byte of padding */ upload_size = MAX_PAYLOAD_SIZE - 1; memset(msg, 0, sizeof(*msg)); msg->word_count = SMB_WC_WRITE_ANDX; msg->andx.command = SMB_COM_NO_ANDX_COMMAND; msg->fid = smb_swap16(req->fid); msg->offset = smb_swap32((unsigned int) offset); msg->offset_high = smb_swap32((unsigned int) (offset >> 32)); msg->data_length = smb_swap16((unsigned short) upload_size); msg->data_offset = smb_swap16(sizeof(*msg) - sizeof(unsigned int)); msg->byte_count = smb_swap16((unsigned short) (upload_size + 1)); smb_format_message(conn, &msg->h, SMB_COM_WRITE_ANDX, sizeof(*msg) - sizeof(msg->h) + (size_t) upload_size); return smb_send(conn, sizeof(*msg), (size_t) upload_size); } static CURLcode smb_send_and_recv(struct connectdata *conn, void **msg) { struct smb_conn *smbc = &conn->proto.smbc; CURLcode result; /* Check if there is data in the transfer buffer */ if(!smbc->send_size && smbc->upload_size) { size_t nread = smbc->upload_size > conn->data->set.upload_buffer_size ? conn->data->set.upload_buffer_size : smbc->upload_size; conn->data->req.upload_fromhere = conn->data->state.ulbuf; result = Curl_fillreadbuffer(conn, nread, &nread); if(result && result != CURLE_AGAIN) return result; if(!nread) return CURLE_OK; smbc->upload_size -= nread; smbc->send_size = nread; smbc->sent = 0; } /* Check if there is data to send */ if(smbc->send_size) { result = smb_flush(conn); if(result) return result; } /* Check if there is still data to be sent */ if(smbc->send_size || smbc->upload_size) return CURLE_AGAIN; return smb_recv_message(conn, msg); } static CURLcode smb_connection_state(struct connectdata *conn, bool *done) { struct smb_conn *smbc = &conn->proto.smbc; struct smb_negotiate_response *nrsp; struct smb_header *h; CURLcode result; void *msg = NULL; if(smbc->state == SMB_CONNECTING) { #ifdef USE_SSL if((conn->handler->flags & PROTOPT_SSL)) { bool ssl_done = FALSE; result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &ssl_done); if(result && result != CURLE_AGAIN) return result; if(!ssl_done) return CURLE_OK; } #endif result = smb_send_negotiate(conn); if(result) { connclose(conn, "SMB: failed to send negotiate message"); return result; } conn_state(conn, SMB_NEGOTIATE); } /* Send the previous message and check for a response */ result = smb_send_and_recv(conn, &msg); if(result && result != CURLE_AGAIN) { connclose(conn, "SMB: failed to communicate"); return result; } if(!msg) return CURLE_OK; h = msg; switch(smbc->state) { case SMB_NEGOTIATE: if(h->status || smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) { connclose(conn, "SMB: negotiation failed"); return CURLE_COULDNT_CONNECT; } nrsp = msg; memcpy(smbc->challenge, nrsp->bytes, sizeof(smbc->challenge)); smbc->session_key = smb_swap32(nrsp->session_key); result = smb_send_setup(conn); if(result) { connclose(conn, "SMB: failed to send setup message"); return result; } conn_state(conn, SMB_SETUP); break; case SMB_SETUP: if(h->status) { connclose(conn, "SMB: authentication failed"); return CURLE_LOGIN_DENIED; } smbc->uid = smb_swap16(h->uid); conn_state(conn, SMB_CONNECTED); *done = true; break; default: smb_pop_message(conn); return CURLE_OK; /* ignore */ } smb_pop_message(conn); return CURLE_OK; } /* * Convert a timestamp from the Windows world (100 nsec units from 1 Jan 1601) * to Posix time. Cap the output to fit within a time_t. */ static void get_posix_time(time_t *out, curl_off_t timestamp) { timestamp -= 116444736000000000; timestamp /= 10000000; #if SIZEOF_TIME_T < SIZEOF_CURL_OFF_T if(timestamp > TIME_T_MAX) *out = TIME_T_MAX; else if(timestamp < TIME_T_MIN) *out = TIME_T_MIN; else #endif *out = (time_t) timestamp; } static CURLcode smb_request_state(struct connectdata *conn, bool *done) { struct smb_request *req = conn->data->req.protop; struct smb_header *h; struct smb_conn *smbc = &conn->proto.smbc; enum smb_req_state next_state = SMB_DONE; unsigned short len; unsigned short off; CURLcode result; void *msg = NULL; const struct smb_nt_create_response *smb_m; /* Start the request */ if(req->state == SMB_REQUESTING) { result = smb_send_tree_connect(conn); if(result) { connclose(conn, "SMB: failed to send tree connect message"); return result; } request_state(conn, SMB_TREE_CONNECT); } /* Send the previous message and check for a response */ result = smb_send_and_recv(conn, &msg); if(result && result != CURLE_AGAIN) { connclose(conn, "SMB: failed to communicate"); return result; } if(!msg) return CURLE_OK; h = msg; switch(req->state) { case SMB_TREE_CONNECT: if(h->status) { req->result = CURLE_REMOTE_FILE_NOT_FOUND; if(h->status == smb_swap32(SMB_ERR_NOACCESS)) req->result = CURLE_REMOTE_ACCESS_DENIED; break; } req->tid = smb_swap16(h->tid); next_state = SMB_OPEN; break; case SMB_OPEN: if(h->status || smbc->got < sizeof(struct smb_nt_create_response)) { req->result = CURLE_REMOTE_FILE_NOT_FOUND; next_state = SMB_TREE_DISCONNECT; break; } smb_m = (const struct smb_nt_create_response*) msg; req->fid = smb_swap16(smb_m->fid); conn->data->req.offset = 0; if(conn->data->set.upload) { conn->data->req.size = conn->data->state.infilesize; Curl_pgrsSetUploadSize(conn->data, conn->data->req.size); next_state = SMB_UPLOAD; } else { smb_m = (const struct smb_nt_create_response*) msg; conn->data->req.size = smb_swap64(smb_m->end_of_file); if(conn->data->req.size < 0) { req->result = CURLE_WEIRD_SERVER_REPLY; next_state = SMB_CLOSE; } else { Curl_pgrsSetDownloadSize(conn->data, conn->data->req.size); if(conn->data->set.get_filetime) get_posix_time(&conn->data->info.filetime, smb_m->last_change_time); next_state = SMB_DOWNLOAD; } } break; case SMB_DOWNLOAD: if(h->status || smbc->got < sizeof(struct smb_header) + 14) { req->result = CURLE_RECV_ERROR; next_state = SMB_CLOSE; break; } len = Curl_read16_le(((const unsigned char *) msg) + sizeof(struct smb_header) + 11); off = Curl_read16_le(((const unsigned char *) msg) + sizeof(struct smb_header) + 13); if(len > 0) { if(off + sizeof(unsigned int) + len > smbc->got) { failf(conn->data, "Invalid input packet"); result = CURLE_RECV_ERROR; } else result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)msg + off + sizeof(unsigned int), len); if(result) { req->result = result; next_state = SMB_CLOSE; break; } } conn->data->req.bytecount += len; conn->data->req.offset += len; Curl_pgrsSetDownloadCounter(conn->data, conn->data->req.bytecount); next_state = (len < MAX_PAYLOAD_SIZE) ? SMB_CLOSE : SMB_DOWNLOAD; break; case SMB_UPLOAD: if(h->status || smbc->got < sizeof(struct smb_header) + 6) { req->result = CURLE_UPLOAD_FAILED; next_state = SMB_CLOSE; break; } len = Curl_read16_le(((const unsigned char *) msg) + sizeof(struct smb_header) + 5); conn->data->req.bytecount += len; conn->data->req.offset += len; Curl_pgrsSetUploadCounter(conn->data, conn->data->req.bytecount); if(conn->data->req.bytecount >= conn->data->req.size) next_state = SMB_CLOSE; else next_state = SMB_UPLOAD; break; case SMB_CLOSE: /* We don't care if the close failed, proceed to tree disconnect anyway */ next_state = SMB_TREE_DISCONNECT; break; case SMB_TREE_DISCONNECT: next_state = SMB_DONE; break; default: smb_pop_message(conn); return CURLE_OK; /* ignore */ } smb_pop_message(conn); switch(next_state) { case SMB_OPEN: result = smb_send_open(conn); break; case SMB_DOWNLOAD: result = smb_send_read(conn); break; case SMB_UPLOAD: result = smb_send_write(conn); break; case SMB_CLOSE: result = smb_send_close(conn); break; case SMB_TREE_DISCONNECT: result = smb_send_tree_disconnect(conn); break; case SMB_DONE: result = req->result; *done = true; break; default: break; } if(result) { connclose(conn, "SMB: failed to send message"); return result; } request_state(conn, next_state); return CURLE_OK; } static CURLcode smb_done(struct connectdata *conn, CURLcode status, bool premature) { (void) premature; Curl_safefree(conn->data->req.protop); return status; } static CURLcode smb_disconnect(struct connectdata *conn, bool dead) { struct smb_conn *smbc = &conn->proto.smbc; (void) dead; Curl_safefree(smbc->share); Curl_safefree(smbc->domain); Curl_safefree(smbc->recv_buf); return CURLE_OK; } static int smb_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(!numsocks) return GETSOCK_BLANK; socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } static CURLcode smb_do(struct connectdata *conn, bool *done) { struct smb_conn *smbc = &conn->proto.smbc; *done = FALSE; if(smbc->share) { return CURLE_OK; } return CURLE_URL_MALFORMAT; } static CURLcode smb_parse_url_path(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct smb_request *req = data->req.protop; struct smb_conn *smbc = &conn->proto.smbc; char *path; char *slash; /* URL decode the path */ result = Curl_urldecode(data, data->state.up.path, 0, &path, NULL, TRUE); if(result) return result; /* Parse the path for the share */ smbc->share = strdup((*path == '/' || *path == '\\') ? path + 1 : path); free(path); if(!smbc->share) return CURLE_OUT_OF_MEMORY; slash = strchr(smbc->share, '/'); if(!slash) slash = strchr(smbc->share, '\\'); /* The share must be present */ if(!slash) { Curl_safefree(smbc->share); return CURLE_URL_MALFORMAT; } /* Parse the path for the file path converting any forward slashes into backslashes */ *slash++ = 0; req->path = slash; for(; *slash; slash++) { if(*slash == '/') *slash = '\\'; } return CURLE_OK; } #endif /* !USE_WINDOWS_SSPI || USE_WIN32_CRYPTO */ #endif /* CURL_DISABLE_SMB && USE_NTLM && CURL_SIZEOF_CURL_OFF_T > 4 */
YifuLiu/AliOS-Things
components/curl/lib/smb.c
C
apache-2.0
28,947
#ifndef HEADER_CURL_SMB_H #define HEADER_CURL_SMB_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014, Bill Nagel <wnagel@tycoint.com>, Exacq Technologies * Copyright (C) 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ 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_NTLM) && \ (CURL_SIZEOF_CURL_OFF_T > 4) #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) extern const struct Curl_handler Curl_handler_smb; extern const struct Curl_handler Curl_handler_smbs; #endif /* !USE_WINDOWS_SSPI || USE_WIN32_CRYPTO */ #endif /* CURL_DISABLE_SMB && USE_NTLM && CURL_SIZEOF_CURL_OFF_T > 4 */ #endif /* HEADER_CURL_SMB_H */
YifuLiu/AliOS-Things
components/curl/lib/smb.h
C
apache-2.0
6,826
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC1870 SMTP Service Extension for Message Size * RFC2195 CRAM-MD5 authentication * RFC2831 DIGEST-MD5 authentication * RFC3207 SMTP over TLS * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * RFC4954 SMTP Authentication * RFC5321 SMTP protocol * RFC6749 OAuth 2.0 Authorization Framework * RFC8314 Use of TLS for Email Submission and Access * Draft SMTP URL Interface <draft-earhart-url-smtp-00.txt> * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_SMTP #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "mime.h" #include "socks.h" #include "smtp.h" #include "strtoofft.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "select.h" #include "multiif.h" #include "url.h" #include "curl_gethostname.h" #include "curl_sasl.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" /* Local API functions */ static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *done); static CURLcode smtp_do(struct connectdata *conn, bool *done); static CURLcode smtp_done(struct connectdata *conn, CURLcode status, bool premature); static CURLcode smtp_connect(struct connectdata *conn, bool *done); static CURLcode smtp_disconnect(struct connectdata *conn, bool dead); static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done); static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode smtp_setup_connection(struct connectdata *conn); static CURLcode smtp_parse_url_options(struct connectdata *conn); static CURLcode smtp_parse_url_path(struct connectdata *conn); static CURLcode smtp_parse_custom_request(struct connectdata *conn); static CURLcode smtp_perform_auth(struct connectdata *conn, const char *mech, const char *initresp); static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp); static void smtp_get_message(char *buffer, char **outptr); /* * SMTP protocol handler. */ const struct Curl_handler Curl_handler_smtp = { "SMTP", /* scheme */ smtp_setup_connection, /* setup_connection */ smtp_do, /* do_it */ smtp_done, /* done */ ZERO_NULL, /* do_more */ smtp_connect, /* connect_it */ smtp_multi_statemach, /* connecting */ smtp_doing, /* doing */ smtp_getsock, /* proto_getsock */ smtp_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smtp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMTP, /* defport */ CURLPROTO_SMTP, /* protocol */ PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */ PROTOPT_URLOPTIONS }; #ifdef USE_SSL /* * SMTPS protocol handler. */ const struct Curl_handler Curl_handler_smtps = { "SMTPS", /* scheme */ smtp_setup_connection, /* setup_connection */ smtp_do, /* do_it */ smtp_done, /* done */ ZERO_NULL, /* do_more */ smtp_connect, /* connect_it */ smtp_multi_statemach, /* connecting */ smtp_doing, /* doing */ smtp_getsock, /* proto_getsock */ smtp_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smtp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMTPS, /* defport */ CURLPROTO_SMTPS, /* protocol */ PROTOPT_CLOSEACTION | PROTOPT_SSL | PROTOPT_NOURLQUERY | PROTOPT_URLOPTIONS /* flags */ }; #endif /* SASL parameters for the smtp protocol */ static const struct SASLproto saslsmtp = { "smtp", /* The service name */ 334, /* Code received when continuation is expected */ 235, /* Code to receive upon authentication success */ 512 - 8, /* Maximum initial response length (no max) */ smtp_perform_auth, /* Send authentication command */ smtp_continue_auth, /* Send authentication continuation */ smtp_get_message /* Get SASL response message */ }; #ifdef USE_SSL static void smtp_to_smtps(struct connectdata *conn) { /* Change the connection handler */ conn->handler = &Curl_handler_smtps; /* Set the connection's upgraded to TLS flag */ conn->tls_upgraded = TRUE; } #else #define smtp_to_smtps(x) Curl_nop_stmt #endif /*********************************************************************** * * smtp_endofresp() * * Checks for an ending SMTP status code at the start of the given string, but * also detects various capabilities from the EHLO response including the * supported authentication mechanisms. */ static bool smtp_endofresp(struct connectdata *conn, char *line, size_t len, int *resp) { struct smtp_conn *smtpc = &conn->proto.smtpc; bool result = FALSE; /* Nothing for us */ if(len < 4 || !ISDIGIT(line[0]) || !ISDIGIT(line[1]) || !ISDIGIT(line[2])) return FALSE; /* Do we have a command response? This should be the response code followed by a space and optionally some text as per RFC-5321 and as outlined in Section 4. Examples of RFC-4954 but some e-mail servers ignore this and only send the response code instead as per Section 4.2. */ if(line[3] == ' ' || len == 5) { char tmpline[6]; result = TRUE; memset(tmpline, '\0', sizeof(tmpline)); memcpy(tmpline, line, (len == 5 ? 5 : 3)); *resp = curlx_sltosi(strtol(tmpline, NULL, 10)); /* Make sure real server never sends internal value */ if(*resp == 1) *resp = 0; } /* Do we have a multiline (continuation) response? */ else if(line[3] == '-' && (smtpc->state == SMTP_EHLO || smtpc->state == SMTP_COMMAND)) { result = TRUE; *resp = 1; /* Internal response code */ } return result; } /*********************************************************************** * * smtp_get_message() * * Gets the authentication message from the response buffer. */ static void smtp_get_message(char *buffer, char **outptr) { size_t len = strlen(buffer); char *message = NULL; if(len > 4) { /* Find the start of the message */ len -= 4; for(message = buffer + 4; *message == ' ' || *message == '\t'; message++, len--) ; /* Find the end of the message */ for(; len--;) if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && message[len] != '\t') break; /* Terminate the message */ if(++len) { message[len] = '\0'; } } else /* junk input => zero length output */ message = &buffer[len]; *outptr = message; } /*********************************************************************** * * state() * * This is the ONLY way to change SMTP state! */ static void state(struct connectdata *conn, smtpstate newstate) { struct smtp_conn *smtpc = &conn->proto.smtpc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[] = { "STOP", "SERVERGREET", "EHLO", "HELO", "STARTTLS", "UPGRADETLS", "AUTH", "COMMAND", "MAIL", "RCPT", "DATA", "POSTDATA", "QUIT", /* LAST */ }; if(smtpc->state != newstate) infof(conn->data, "SMTP %p state change from %s to %s\n", (void *)smtpc, names[smtpc->state], names[newstate]); #endif smtpc->state = newstate; } /*********************************************************************** * * smtp_perform_ehlo() * * Sends the EHLO command to not only initialise communication with the ESMTP * server but to also obtain a list of server side supported capabilities. */ static CURLcode smtp_perform_ehlo(struct connectdata *conn) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; smtpc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanism yet */ smtpc->sasl.authused = SASL_AUTH_NONE; /* Clear the authentication mechanism used for esmtp connections */ smtpc->tls_supported = FALSE; /* Clear the TLS capability */ smtpc->auth_supported = FALSE; /* Clear the AUTH capability */ /* Send the EHLO command */ result = Curl_pp_sendf(&smtpc->pp, "EHLO %s", smtpc->domain); if(!result) state(conn, SMTP_EHLO); return result; } /*********************************************************************** * * smtp_perform_helo() * * Sends the HELO command to initialise communication with the SMTP server. */ static CURLcode smtp_perform_helo(struct connectdata *conn) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; smtpc->sasl.authused = SASL_AUTH_NONE; /* No authentication mechanism used in smtp connections */ /* Send the HELO command */ result = Curl_pp_sendf(&smtpc->pp, "HELO %s", smtpc->domain); if(!result) state(conn, SMTP_HELO); return result; } /*********************************************************************** * * smtp_perform_starttls() * * Sends the STLS command to start the upgrade to TLS. */ static CURLcode smtp_perform_starttls(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the STARTTLS command */ result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "STARTTLS"); if(!result) state(conn, SMTP_STARTTLS); return result; } /*********************************************************************** * * smtp_perform_upgrade_tls() * * Performs the upgrade to TLS. */ static CURLcode smtp_perform_upgrade_tls(struct connectdata *conn) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; /* Start the SSL connection */ result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone); if(!result) { if(smtpc->state != SMTP_UPGRADETLS) state(conn, SMTP_UPGRADETLS); if(smtpc->ssldone) { smtp_to_smtps(conn); result = smtp_perform_ehlo(conn); } } return result; } /*********************************************************************** * * smtp_perform_auth() * * Sends an AUTH command allowing the client to login with the given SASL * authentication mechanism. */ static CURLcode smtp_perform_auth(struct connectdata *conn, const char *mech, const char *initresp) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; if(initresp) { /* AUTH <mech> ...<crlf> */ /* Send the AUTH command with the initial response */ result = Curl_pp_sendf(&smtpc->pp, "AUTH %s %s", mech, initresp); } else { /* Send the AUTH command */ result = Curl_pp_sendf(&smtpc->pp, "AUTH %s", mech); } return result; } /*********************************************************************** * * smtp_continue_auth() * * Sends SASL continuation data or cancellation. */ static CURLcode smtp_continue_auth(struct connectdata *conn, const char *resp) { struct smtp_conn *smtpc = &conn->proto.smtpc; return Curl_pp_sendf(&smtpc->pp, "%s", resp); } /*********************************************************************** * * smtp_perform_authentication() * * Initiates the authentication sequence, with the appropriate SASL * authentication mechanism. */ static CURLcode smtp_perform_authentication(struct connectdata *conn) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; saslprogress progress; /* Check we have enough data to authenticate with, and the server supports authentiation, and end the connect phase if not */ if(!smtpc->auth_supported || !Curl_sasl_can_authenticate(&smtpc->sasl, conn)) { state(conn, SMTP_STOP); return result; } /* Calculate the SASL login details */ result = Curl_sasl_start(&smtpc->sasl, conn, FALSE, &progress); if(!result) { if(progress == SASL_INPROGRESS) state(conn, SMTP_AUTH); else { /* Other mechanisms not supported */ infof(conn->data, "No known authentication mechanisms supported!\n"); result = CURLE_LOGIN_DENIED; } } return result; } /*********************************************************************** * * smtp_perform_command() * * Sends a SMTP based command. */ static CURLcode smtp_perform_command(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; /* Send the command */ if(smtp->rcpt) result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s %s", smtp->custom && smtp->custom[0] != '\0' ? smtp->custom : "VRFY", smtp->rcpt->data); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", smtp->custom && smtp->custom[0] != '\0' ? smtp->custom : "HELP"); if(!result) state(conn, SMTP_COMMAND); return result; } /*********************************************************************** * * smtp_perform_mail() * * Sends an MAIL command to initiate the upload of a message. */ static CURLcode smtp_perform_mail(struct connectdata *conn) { char *from = NULL; char *auth = NULL; char *size = NULL; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; /* Calculate the FROM parameter */ if(!data->set.str[STRING_MAIL_FROM]) /* Null reverse-path, RFC-5321, sect. 3.6.3 */ from = strdup("<>"); else if(data->set.str[STRING_MAIL_FROM][0] == '<') from = aprintf("%s", data->set.str[STRING_MAIL_FROM]); else from = aprintf("<%s>", data->set.str[STRING_MAIL_FROM]); if(!from) return CURLE_OUT_OF_MEMORY; /* Calculate the optional AUTH parameter */ if(data->set.str[STRING_MAIL_AUTH] && conn->proto.smtpc.sasl.authused) { if(data->set.str[STRING_MAIL_AUTH][0] != '\0') auth = aprintf("%s", data->set.str[STRING_MAIL_AUTH]); else /* Empty AUTH, RFC-2554, sect. 5 */ auth = strdup("<>"); if(!auth) { free(from); return CURLE_OUT_OF_MEMORY; } } /* Prepare the mime data if some. */ if(data->set.mimepost.kind != MIMEKIND_NONE) { /* Use the whole structure as data. */ data->set.mimepost.flags &= ~MIME_BODY_ONLY; /* Add external headers and mime version. */ curl_mime_headers(&data->set.mimepost, data->set.headers, 0); result = Curl_mime_prepare_headers(&data->set.mimepost, NULL, NULL, MIMESTRATEGY_MAIL); if(!result) if(!Curl_checkheaders(conn, "Mime-Version")) result = Curl_mime_add_header(&data->set.mimepost.curlheaders, "Mime-Version: 1.0"); /* Make sure we will read the entire mime structure. */ if(!result) result = Curl_mime_rewind(&data->set.mimepost); if(result) { free(from); free(auth); return result; } data->state.infilesize = Curl_mime_size(&data->set.mimepost); /* Read from mime structure. */ data->state.fread_func = (curl_read_callback) Curl_mime_read; data->state.in = (void *) &data->set.mimepost; } /* Calculate the optional SIZE parameter */ if(conn->proto.smtpc.size_supported && data->state.infilesize > 0) { size = aprintf("%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize); if(!size) { free(from); free(auth); return CURLE_OUT_OF_MEMORY; } } /* Send the MAIL command */ if(!auth && !size) result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s", from); else if(auth && !size) result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s AUTH=%s", from, auth); else if(auth && size) result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s AUTH=%s SIZE=%s", from, auth, size); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "MAIL FROM:%s SIZE=%s", from, size); free(from); free(auth); free(size); if(!result) state(conn, SMTP_MAIL); return result; } /*********************************************************************** * * smtp_perform_rcpt_to() * * Sends a RCPT TO command for a given recipient as part of the message upload * process. */ static CURLcode smtp_perform_rcpt_to(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; /* Send the RCPT TO command */ if(smtp->rcpt->data[0] == '<') result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:%s", smtp->rcpt->data); else result = Curl_pp_sendf(&conn->proto.smtpc.pp, "RCPT TO:<%s>", smtp->rcpt->data); if(!result) state(conn, SMTP_RCPT); return result; } /*********************************************************************** * * smtp_perform_quit() * * Performs the quit action prior to sclose() being called. */ static CURLcode smtp_perform_quit(struct connectdata *conn) { CURLcode result = CURLE_OK; /* Send the QUIT command */ result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "QUIT"); if(!result) state(conn, SMTP_QUIT); return result; } /* For the initial server greeting */ static CURLcode smtp_state_servergreet_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(smtpcode/100 != 2) { failf(data, "Got unexpected smtp-server response: %d", smtpcode); result = CURLE_WEIRD_SERVER_REPLY; } else result = smtp_perform_ehlo(conn); return result; } /* For STARTTLS responses */ static CURLcode smtp_state_starttls_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(smtpcode != 220) { if(data->set.use_ssl != CURLUSESSL_TRY) { failf(data, "STARTTLS denied, code %d", smtpcode); result = CURLE_USE_SSL_FAILED; } else result = smtp_perform_authentication(conn); } else result = smtp_perform_upgrade_tls(conn); return result; } /* For EHLO responses */ static CURLcode smtp_state_ehlo_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; const char *line = data->state.buffer; size_t len = strlen(line); (void)instate; /* no use for this yet */ if(smtpcode/100 != 2 && smtpcode != 1) { if(data->set.use_ssl <= CURLUSESSL_TRY || conn->ssl[FIRSTSOCKET].use) result = smtp_perform_helo(conn); else { failf(data, "Remote access denied: %d", smtpcode); result = CURLE_REMOTE_ACCESS_DENIED; } } else { line += 4; len -= 4; /* Does the server support the STARTTLS capability? */ if(len >= 8 && !memcmp(line, "STARTTLS", 8)) smtpc->tls_supported = TRUE; /* Does the server support the SIZE capability? */ else if(len >= 4 && !memcmp(line, "SIZE", 4)) smtpc->size_supported = TRUE; /* Does the server support authentication? */ else if(len >= 5 && !memcmp(line, "AUTH ", 5)) { smtpc->auth_supported = TRUE; /* Advance past the AUTH keyword */ line += 5; len -= 5; /* Loop through the data line */ for(;;) { size_t llen; size_t wordlen; unsigned int mechbit; while(len && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { line++; len--; } if(!len) break; /* Extract the word */ for(wordlen = 0; wordlen < len && line[wordlen] != ' ' && line[wordlen] != '\t' && line[wordlen] != '\r' && line[wordlen] != '\n';) wordlen++; /* Test the word for a matching authentication mechanism */ mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); if(mechbit && llen == wordlen) smtpc->sasl.authmechs |= mechbit; line += wordlen; len -= wordlen; } } if(smtpcode != 1) { if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) { /* We don't have a SSL/TLS connection yet, but SSL is requested */ if(smtpc->tls_supported) /* Switch to TLS connection now */ result = smtp_perform_starttls(conn); else if(data->set.use_ssl == CURLUSESSL_TRY) /* Fallback and carry on with authentication */ result = smtp_perform_authentication(conn); else { failf(data, "STARTTLS not supported."); result = CURLE_USE_SSL_FAILED; } } else result = smtp_perform_authentication(conn); } } return result; } /* For HELO responses */ static CURLcode smtp_state_helo_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(smtpcode/100 != 2) { failf(data, "Remote access denied: %d", smtpcode); result = CURLE_REMOTE_ACCESS_DENIED; } else /* End of connect phase */ state(conn, SMTP_STOP); return result; } /* For SASL authentication responses */ static CURLcode smtp_state_auth_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; saslprogress progress; (void)instate; /* no use for this yet */ result = Curl_sasl_continue(&smtpc->sasl, conn, smtpcode, &progress); if(!result) switch(progress) { case SASL_DONE: state(conn, SMTP_STOP); /* Authenticated */ break; case SASL_IDLE: /* No mechanism left after cancellation */ failf(data, "Authentication cancelled"); result = CURLE_LOGIN_DENIED; break; default: break; } return result; } /* For command responses */ static CURLcode smtp_state_command_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *line = data->state.buffer; size_t len = strlen(line); (void)instate; /* no use for this yet */ if((smtp->rcpt && smtpcode/100 != 2 && smtpcode != 553 && smtpcode != 1) || (!smtp->rcpt && smtpcode/100 != 2 && smtpcode != 1)) { failf(data, "Command failed: %d", smtpcode); result = CURLE_RECV_ERROR; } else { /* Temporarily add the LF character back and send as body to the client */ if(!data->set.opt_no_body) { line[len] = '\n'; result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1); line[len] = '\0'; } if(smtpcode != 1) { if(smtp->rcpt) { smtp->rcpt = smtp->rcpt->next; if(smtp->rcpt) { /* Send the next command */ result = smtp_perform_command(conn); } else /* End of DO phase */ state(conn, SMTP_STOP); } else /* End of DO phase */ state(conn, SMTP_STOP); } } return result; } /* For MAIL responses */ static CURLcode smtp_state_mail_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(smtpcode/100 != 2) { failf(data, "MAIL failed: %d", smtpcode); result = CURLE_SEND_ERROR; } else /* Start the RCPT TO command */ result = smtp_perform_rcpt_to(conn); return result; } /* For RCPT responses */ static CURLcode smtp_state_rcpt_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; (void)instate; /* no use for this yet */ if(smtpcode/100 != 2) { failf(data, "RCPT failed: %d", smtpcode); result = CURLE_SEND_ERROR; } else { smtp->rcpt = smtp->rcpt->next; if(smtp->rcpt) /* Send the next RCPT TO command */ result = smtp_perform_rcpt_to(conn); else { /* Send the DATA command */ result = Curl_pp_sendf(&conn->proto.smtpc.pp, "%s", "DATA"); if(!result) state(conn, SMTP_DATA); } } return result; } /* For DATA response */ static CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; (void)instate; /* no use for this yet */ if(smtpcode != 354) { failf(data, "DATA failed: %d", smtpcode); result = CURLE_SEND_ERROR; } else { /* Set the progress upload size */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* SMTP upload */ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); /* End of DO phase */ state(conn, SMTP_STOP); } return result; } /* For POSTDATA responses, which are received after the entire DATA part has been sent to the server */ static CURLcode smtp_state_postdata_resp(struct connectdata *conn, int smtpcode, smtpstate instate) { CURLcode result = CURLE_OK; (void)instate; /* no use for this yet */ if(smtpcode != 250) result = CURLE_RECV_ERROR; /* End of DONE phase */ state(conn, SMTP_STOP); return result; } static CURLcode smtp_statemach_act(struct connectdata *conn) { CURLcode result = CURLE_OK; curl_socket_t sock = conn->sock[FIRSTSOCKET]; struct Curl_easy *data = conn->data; int smtpcode; struct smtp_conn *smtpc = &conn->proto.smtpc; struct pingpong *pp = &smtpc->pp; size_t nread = 0; /* Busy upgrading the connection; right now all I/O is SSL/TLS, not SMTP */ if(smtpc->state == SMTP_UPGRADETLS) return smtp_perform_upgrade_tls(conn); /* Flush any data that needs to be sent */ if(pp->sendleft) return Curl_pp_flushsend(pp); do { /* Read the response from the server */ result = Curl_pp_readresp(sock, pp, &smtpcode, &nread); if(result) return result; /* Store the latest response for later retrieval if necessary */ if(smtpc->state != SMTP_QUIT && smtpcode != 1) data->info.httpcode = smtpcode; if(!smtpcode) break; /* We have now received a full SMTP server response */ switch(smtpc->state) { case SMTP_SERVERGREET: result = smtp_state_servergreet_resp(conn, smtpcode, smtpc->state); break; case SMTP_EHLO: result = smtp_state_ehlo_resp(conn, smtpcode, smtpc->state); break; case SMTP_HELO: result = smtp_state_helo_resp(conn, smtpcode, smtpc->state); break; case SMTP_STARTTLS: result = smtp_state_starttls_resp(conn, smtpcode, smtpc->state); break; case SMTP_AUTH: result = smtp_state_auth_resp(conn, smtpcode, smtpc->state); break; case SMTP_COMMAND: result = smtp_state_command_resp(conn, smtpcode, smtpc->state); break; case SMTP_MAIL: result = smtp_state_mail_resp(conn, smtpcode, smtpc->state); break; case SMTP_RCPT: result = smtp_state_rcpt_resp(conn, smtpcode, smtpc->state); break; case SMTP_DATA: result = smtp_state_data_resp(conn, smtpcode, smtpc->state); break; case SMTP_POSTDATA: result = smtp_state_postdata_resp(conn, smtpcode, smtpc->state); break; case SMTP_QUIT: /* fallthrough, just stop! */ default: /* internal error */ state(conn, SMTP_STOP); break; } } while(!result && smtpc->state != SMTP_STOP && Curl_pp_moredata(pp)); return result; } /* Called repeatedly until done from multi.c */ static CURLcode smtp_multi_statemach(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; if((conn->handler->flags & PROTOPT_SSL) && !smtpc->ssldone) { result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &smtpc->ssldone); if(result || !smtpc->ssldone) return result; } result = Curl_pp_statemach(&smtpc->pp, FALSE, FALSE); *done = (smtpc->state == SMTP_STOP) ? TRUE : FALSE; return result; } static CURLcode smtp_block_statemach(struct connectdata *conn, bool disconnecting) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; while(smtpc->state != SMTP_STOP && !result) result = Curl_pp_statemach(&smtpc->pp, TRUE, disconnecting); return result; } /* Allocate and initialize the SMTP struct for the current Curl_easy if required */ static CURLcode smtp_init(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp; smtp = data->req.protop = calloc(sizeof(struct SMTP), 1); if(!smtp) result = CURLE_OUT_OF_MEMORY; return result; } /* For the SMTP "protocol connect" and "doing" phases only */ static int smtp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.smtpc.pp, socks, numsocks); } /*********************************************************************** * * smtp_connect() * * This function should do everything that is to be considered a part of * the connection phase. * * The variable pointed to by 'done' will be TRUE if the protocol-layer * connect phase is done when this function returns, or FALSE if not. */ static CURLcode smtp_connect(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; struct pingpong *pp = &smtpc->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections in SMTP */ connkeep(conn, "SMTP default"); /* Set the default response time-out */ pp->response_time = RESP_TIMEOUT; pp->statemach_act = smtp_statemach_act; pp->endofresp = smtp_endofresp; pp->conn = conn; /* Initialize the SASL storage */ Curl_sasl_init(&smtpc->sasl, &saslsmtp); /* Initialise the pingpong layer */ Curl_pp_init(pp); /* Parse the URL options */ result = smtp_parse_url_options(conn); if(result) return result; /* Parse the URL path */ result = smtp_parse_url_path(conn); if(result) return result; /* Start off waiting for the server greeting response */ state(conn, SMTP_SERVERGREET); result = smtp_multi_statemach(conn, done); return result; } /*********************************************************************** * * smtp_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */ static CURLcode smtp_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; struct pingpong *pp = &conn->proto.smtpc.pp; char *eob; ssize_t len; ssize_t bytes_written; (void)premature; if(!smtp || !pp->conn) return CURLE_OK; /* Cleanup our per-request based variables */ Curl_safefree(smtp->custom); if(status) { connclose(conn, "SMTP done with bad status"); /* marked for closure */ result = status; /* use the already set error code */ } else if(!data->set.connect_only && data->set.mail_rcpt && (data->set.upload || data->set.mimepost.kind)) { /* Calculate the EOB taking into account any terminating CRLF from the previous line of the email or the CRLF of the DATA command when there is "no mail data". RFC-5321, sect. 4.1.1.4. Note: As some SSL backends, such as OpenSSL, will cause Curl_write() to fail when using a different pointer following a previous write, that returned CURLE_AGAIN, we duplicate the EOB now rather than when the bytes written doesn't equal len. */ if(smtp->trailing_crlf || !conn->data->state.infilesize) { eob = strdup(&SMTP_EOB[2]); len = SMTP_EOB_LEN - 2; } else { eob = strdup(SMTP_EOB); len = SMTP_EOB_LEN; } if(!eob) return CURLE_OUT_OF_MEMORY; /* Send the end of block data */ result = Curl_write(conn, conn->writesockfd, eob, len, &bytes_written); if(result) { free(eob); return result; } if(bytes_written != len) { /* The whole chunk was not sent so keep it around and adjust the pingpong structure accordingly */ pp->sendthis = eob; pp->sendsize = len; pp->sendleft = len - bytes_written; } else { /* Successfully sent so adjust the response timeout relative to now */ pp->response = Curl_now(); free(eob); } state(conn, SMTP_POSTDATA); /* Run the state-machine */ result = smtp_block_statemach(conn, FALSE); } /* Clear the transfer mode for the next request */ smtp->transfer = FTPTRANSFER_BODY; return result; } /*********************************************************************** * * smtp_perform() * * This is the actual DO function for SMTP. Transfer a mail, send a command * or get some data according to the options previously setup. */ static CURLcode smtp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { /* This is SMTP and no proxy */ CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; DEBUGF(infof(conn->data, "DO phase starts\n")); if(data->set.opt_no_body) { /* Requested no body means no transfer */ smtp->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* Store the first recipient (or NULL if not specified) */ smtp->rcpt = data->set.mail_rcpt; /* Initial data character is the first character in line: it is implicitly preceded by a virtual CRLF. */ smtp->trailing_crlf = TRUE; smtp->eob = 2; /* Start the first command in the DO phase */ if((data->set.upload || data->set.mimepost.kind) && data->set.mail_rcpt) /* MAIL transfer */ result = smtp_perform_mail(conn); else /* SMTP based command (VRFY, EXPN, NOOP, RSET or HELP) */ result = smtp_perform_command(conn); if(result) return result; /* Run the state-machine */ result = smtp_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; } /*********************************************************************** * * smtp_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (smtp_perform). * * The input argument is already checked for validity. */ static CURLcode smtp_do(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; *done = FALSE; /* default to false */ /* Parse the custom request */ result = smtp_parse_custom_request(conn); if(result) return result; result = smtp_regular_transfer(conn, done); return result; } /*********************************************************************** * * smtp_disconnect() * * Disconnect from an SMTP server. Cleanup protocol-specific per-connection * resources. BLOCKING. */ static CURLcode smtp_disconnect(struct connectdata *conn, bool dead_connection) { struct smtp_conn *smtpc = &conn->proto.smtpc; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. */ /* The SMTP session may or may not have been allocated/setup at this point! */ if(!dead_connection && smtpc->pp.conn && smtpc->pp.conn->bits.protoconnstart) if(!smtp_perform_quit(conn)) (void)smtp_block_statemach(conn, TRUE); /* ignore errors on QUIT */ /* Disconnect from the server */ Curl_pp_disconnect(&smtpc->pp); /* Cleanup the SASL module */ Curl_sasl_cleanup(conn, smtpc->sasl.authused); /* Cleanup our connection based variables */ Curl_safefree(smtpc->domain); return CURLE_OK; } /* Call this when the DO phase has completed */ static CURLcode smtp_dophase_done(struct connectdata *conn, bool connected) { struct SMTP *smtp = conn->data->req.protop; (void)connected; if(smtp->transfer != FTPTRANSFER_BODY) /* no data to transfer */ Curl_setup_transfer(conn->data, -1, -1, FALSE, -1); return CURLE_OK; } /* Called from multi.c while DOing */ static CURLcode smtp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = smtp_multi_statemach(conn, dophase_done); if(result) DEBUGF(infof(conn->data, "DO phase failed\n")); else if(*dophase_done) { result = smtp_dophase_done(conn, FALSE /* not connected */); DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /*********************************************************************** * * smtp_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. */ static CURLcode smtp_regular_transfer(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; bool connected = FALSE; struct Curl_easy *data = conn->data; /* Make sure size is unknown at this point */ data->req.size = -1; /* Set the progress data */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); /* Carry out the perform */ result = smtp_perform(conn, &connected, dophase_done); /* Perform post DO phase operations if necessary */ if(!result && *dophase_done) result = smtp_dophase_done(conn, connected); return result; } static CURLcode smtp_setup_connection(struct connectdata *conn) { CURLcode result; /* Clear the TLS upgraded flag */ conn->tls_upgraded = FALSE; /* Initialise the SMTP layer */ result = smtp_init(conn); if(result) return result; return CURLE_OK; } /*********************************************************************** * * smtp_parse_url_options() * * Parse the URL login options. */ static CURLcode smtp_parse_url_options(struct connectdata *conn) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; const char *ptr = conn->options; smtpc->sasl.resetprefs = TRUE; while(!result && ptr && *ptr) { const char *key = ptr; const char *value; while(*ptr && *ptr != '=') ptr++; value = ptr + 1; while(*ptr && *ptr != ';') ptr++; if(strncasecompare(key, "AUTH=", 5)) result = Curl_sasl_parse_url_auth_option(&smtpc->sasl, value, ptr - value); else result = CURLE_URL_MALFORMAT; if(*ptr == ';') ptr++; } return result; } /*********************************************************************** * * smtp_parse_url_path() * * Parse the URL path into separate path components. */ static CURLcode smtp_parse_url_path(struct connectdata *conn) { /* The SMTP struct is already initialised in smtp_connect() */ struct Curl_easy *data = conn->data; struct smtp_conn *smtpc = &conn->proto.smtpc; const char *path = &data->state.up.path[1]; /* skip leading path */ char localhost[HOSTNAME_MAX + 1]; /* Calculate the path if necessary */ if(!*path) { if(!Curl_gethostname(localhost, sizeof(localhost))) path = localhost; else path = "localhost"; } /* URL decode the path and use it as the domain in our EHLO */ return Curl_urldecode(conn->data, path, 0, &smtpc->domain, NULL, TRUE); } /*********************************************************************** * * smtp_parse_custom_request() * * Parse the custom request. */ static CURLcode smtp_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; /* URL decode the custom request */ if(custom) result = Curl_urldecode(data, custom, 0, &smtp->custom, NULL, TRUE); return result; } CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread) { /* When sending a SMTP payload we must detect CRLF. sequences making sure they are sent as CRLF.. instead, as a . on the beginning of a line will be deleted by the server when not part of an EOB terminator and a genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of data by the server */ ssize_t i; ssize_t si; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *scratch = data->state.scratch; char *newscratch = NULL; char *oldscratch = NULL; size_t eob_sent; /* Do we need to allocate a scratch buffer? */ if(!scratch || data->set.crlf) { oldscratch = scratch; scratch = newscratch = malloc(2 * data->set.upload_buffer_size); if(!newscratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } DEBUGASSERT(data->set.upload_buffer_size >= (size_t)nread); /* Have we already sent part of the EOB? */ eob_sent = smtp->eob; /* This loop can be improved by some kind of Boyer-Moore style of approach but that is saved for later... */ for(i = 0, si = 0; i < nread; i++) { if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) { smtp->eob++; /* Is the EOB potentially the terminating CRLF? */ if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob) smtp->trailing_crlf = TRUE; else smtp->trailing_crlf = FALSE; } else if(smtp->eob) { /* A previous substring matched so output that first */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; /* Then compare the first byte */ if(SMTP_EOB[0] == data->req.upload_fromhere[i]) smtp->eob = 1; else smtp->eob = 0; eob_sent = 0; /* Reset the trailing CRLF flag as there was more data */ smtp->trailing_crlf = FALSE; } /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */ if(SMTP_EOB_FIND_LEN == smtp->eob) { /* Copy the replacement data to the target buffer */ memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent], SMTP_EOB_REPL_LEN - eob_sent); si += SMTP_EOB_REPL_LEN - eob_sent; smtp->eob = 0; eob_sent = 0; } else if(!smtp->eob) scratch[si++] = data->req.upload_fromhere[i]; } if(smtp->eob - eob_sent) { /* A substring matched before processing ended so output that now */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; } /* Only use the new buffer if we replaced something */ if(si != nread) { /* Upload from the new (replaced) buffer instead */ data->req.upload_fromhere = scratch; /* Save the buffer so it can be freed later */ data->state.scratch = scratch; /* Free the old scratch buffer */ free(oldscratch); /* Set the new amount too */ data->req.upload_present = si; } else free(newscratch); return CURLE_OK; } #endif /* CURL_DISABLE_SMTP */
YifuLiu/AliOS-Things
components/curl/lib/smtp.c
C
apache-2.0
46,836
#ifndef HEADER_CURL_SMTP_H #define HEADER_CURL_SMTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2009 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "pingpong.h" #include "curl_sasl.h" /**************************************************************************** * SMTP unique setup ***************************************************************************/ typedef enum { SMTP_STOP, /* do nothing state, stops the state machine */ SMTP_SERVERGREET, /* waiting for the initial greeting immediately after a connect */ SMTP_EHLO, SMTP_HELO, SMTP_STARTTLS, SMTP_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS (multi mode only) */ SMTP_AUTH, SMTP_COMMAND, /* VRFY, EXPN, NOOP, RSET and HELP */ SMTP_MAIL, /* MAIL FROM */ SMTP_RCPT, /* RCPT TO */ SMTP_DATA, SMTP_POSTDATA, SMTP_QUIT, SMTP_LAST /* never used */ } smtpstate; /* This SMTP struct is used in the Curl_easy. All SMTP data that is connection-oriented must be in smtp_conn to properly deal with the fact that perhaps the Curl_easy is changed between the times the connection is used. */ struct SMTP { curl_pp_transfer transfer; char *custom; /* Custom Request */ struct curl_slist *rcpt; /* Recipient list */ size_t eob; /* Number of bytes of the EOB (End Of Body) that have been received so far */ bool trailing_crlf; /* Specifies if the tailing CRLF is present */ }; /* smtp_conn is used for struct connection-oriented data in the connectdata struct */ struct smtp_conn { struct pingpong pp; smtpstate state; /* Always use smtp.c:state() to change state! */ bool ssldone; /* Is connect() over SSL done? */ char *domain; /* Client address/name to send in the EHLO */ struct SASL sasl; /* SASL-related storage */ bool tls_supported; /* StartTLS capability supported by server */ bool size_supported; /* If server supports SIZE extension according to RFC 1870 */ bool auth_supported; /* AUTH capability supported by server */ }; extern const struct Curl_handler Curl_handler_smtp; extern const struct Curl_handler Curl_handler_smtps; /* this is the 5-bytes End-Of-Body marker for SMTP */ #define SMTP_EOB "\x0d\x0a\x2e\x0d\x0a" #define SMTP_EOB_LEN 5 #define SMTP_EOB_FIND_LEN 3 /* if found in data, replace it with this string instead */ #define SMTP_EOB_REPL "\x0d\x0a\x2e\x2e" #define SMTP_EOB_REPL_LEN 4 CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread); #endif /* HEADER_CURL_SMTP_H */
YifuLiu/AliOS-Things
components/curl/lib/smtp.h
C
apache-2.0
3,627
#ifndef HEADER_CURL_SOCKADDR_H #define HEADER_CURL_SOCKADDR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" struct Curl_sockaddr_storage { union { struct sockaddr sa; struct sockaddr_in sa_in; #ifdef ENABLE_IPV6 struct sockaddr_in6 sa_in6; #endif #ifdef HAVE_STRUCT_SOCKADDR_STORAGE struct sockaddr_storage sa_stor; #else char cbuf[256]; /* this should be big enough to fit a lot */ #endif } buffer; }; #endif /* HEADER_CURL_SOCKADDR_H */
YifuLiu/AliOS-Things
components/curl/lib/sockaddr.h
C
apache-2.0
1,472
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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" /* The last #include file should be: */ #include "memdebug.h" /* * 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 behaviour which we frown upon, but right now this * is what we have... */ int Curl_blockread_all(struct connectdata *conn, /* connection data */ 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 timeleft = Curl_timeleft(conn->data, NULL, TRUE); if(timeleft < 0) { /* we already got the timeout */ result = CURLE_OPERATION_TIMEDOUT; break; } if(SOCKET_READABLE(sockfd, timeleft) <= 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; } /* * 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)" */ CURLcode Curl_SOCKS4(const char *proxy_user, const char *hostname, int remote_port, int sockindex, struct connectdata *conn) { const bool protocol4a = (conn->socks_proxy.proxytype == CURLPROXY_SOCKS4A) ? TRUE : FALSE; #define SOCKS4REQLEN 262 unsigned char socksreq[SOCKS4REQLEN]; /* room for SOCKS4 request incl. user id */ CURLcode code; curl_socket_t sock = conn->sock[sockindex]; struct Curl_easy *data = conn->data; if(Curl_timeleft(data, NULL, TRUE) < 0) { /* time-out, bail out, go home */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } if(conn->bits.httpproxy) infof(conn->data, "SOCKS4%s: connecting to HTTP proxy %s port %d\n", protocol4a ? "a" : "", hostname, remote_port); (void)curlx_nonblock(sock, FALSE); infof(data, "SOCKS4 communication to %s:%d\n", 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) { struct Curl_dns_entry *dns; Curl_addrinfo *hp = NULL; int rc; rc = Curl_resolv(conn, hostname, remote_port, FALSE, &dns); if(rc == CURLRESOLV_ERROR) return CURLE_COULDNT_RESOLVE_PROXY; if(rc == CURLRESOLV_PENDING) /* ignores the return code, but 'dns' remains NULL on failure */ (void)Curl_resolver_wait_resolv(conn, &dns); /* * 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; if(hp) { char buf[64]; Curl_printable_address(hp, buf, sizeof(buf)); if(hp->ai_family == AF_INET) { struct sockaddr_in *saddr_in; 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)\n", buf); } else { hp = NULL; /* fail! */ failf(data, "SOCKS4 connection to %s not supported\n", buf); } Curl_resolv_unlock(data, dns); /* not used anymore from now on */ } if(!hp) { failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.", hostname); return CURLE_COULDNT_RESOLVE_HOST; } } /* * 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 >= sizeof(socksreq) - 8) { failf(data, "Too long SOCKS proxy name, can't use!\n"); return CURLE_COULDNT_CONNECT; } /* copy the proxy name WITH trailing zero */ memcpy(socksreq + 8, proxy_user, plen + 1); } /* * Make connection */ { int result; ssize_t actualread; ssize_t written; ssize_t hostnamelen = 0; ssize_t packetsize = 9 + strlen((char *)socksreq + 8); /* size including NUL */ /* If SOCKS4a, set special invalid IP address 0.0.0.x */ if(protocol4a) { socksreq[4] = 0; socksreq[5] = 0; socksreq[6] = 0; socksreq[7] = 1; /* If still enough room in buffer, also append hostname */ hostnamelen = (ssize_t)strlen(hostname) + 1; /* length including NUL */ if(packetsize + hostnamelen <= SOCKS4REQLEN) strcpy((char *)socksreq + packetsize, hostname); else hostnamelen = 0; /* Flag: hostname did not fit in buffer */ } /* Send request */ code = Curl_write_plain(conn, sock, (char *)socksreq, packetsize + hostnamelen, &written); if(code || (written != packetsize + hostnamelen)) { failf(data, "Failed to send SOCKS4 connect request."); return CURLE_COULDNT_CONNECT; } if(protocol4a && hostnamelen == 0) { /* SOCKS4a with very long hostname - send that name separately */ hostnamelen = (ssize_t)strlen(hostname) + 1; code = Curl_write_plain(conn, sock, (char *)hostname, hostnamelen, &written); if(code || (written != hostnamelen)) { failf(data, "Failed to send SOCKS4 connect request."); return CURLE_COULDNT_CONNECT; } } packetsize = 8; /* receive data size */ /* Receive response */ result = Curl_blockread_all(conn, sock, (char *)socksreq, packetsize, &actualread); if(result || (actualread != packetsize)) { failf(data, "Failed to receive SOCKS4 connect request ack."); return CURLE_COULDNT_CONNECT; } /* * 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] != 0) { failf(data, "SOCKS4 reply has wrong version, version should be 0."); return CURLE_COULDNT_CONNECT; } /* Result */ switch(socksreq[1]) { case 90: infof(data, "SOCKS4%s request granted.\n", protocol4a?"a":""); break; case 91: failf(data, "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" ", request rejected or failed.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; 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.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; 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.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; default: failf(data, "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)" ", Unknown.", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]), (unsigned char)socksreq[1]); return CURLE_COULDNT_CONNECT; } } (void)curlx_nonblock(sock, TRUE); return CURLE_OK; /* Proxy was successful! */ } /* * This function logs in to a SOCKS5 proxy and sends the specifics to the final * destination server. */ CURLcode Curl_SOCKS5(const char *proxy_user, const char *proxy_password, const char *hostname, int remote_port, int sockindex, struct connectdata *conn) { /* 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 */ unsigned char socksreq[600]; /* room for large user/pw (255 max each) */ int idx; ssize_t actualread; ssize_t written; int result; CURLcode code; curl_socket_t sock = conn->sock[sockindex]; struct Curl_easy *data = conn->data; timediff_t timeout; 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; if(conn->bits.httpproxy) infof(conn->data, "SOCKS5: connecting to HTTP proxy %s port %d\n", hostname, remote_port); /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */ if(!socks5_resolve_local && hostname_len > 255) { infof(conn->data, "SOCKS5: server resolving disabled for hostnames of " "length > 255 [actual len=%zu]\n", hostname_len); socks5_resolve_local = TRUE; } /* get timeout */ timeout = Curl_timeleft(data, NULL, TRUE); if(timeout < 0) { /* time-out, bail out, go home */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } (void)curlx_nonblock(sock, TRUE); /* wait until socket gets connected */ result = SOCKET_WRITABLE(sock, timeout); if(-1 == result) { failf(conn->data, "SOCKS5: no connection here"); return CURLE_COULDNT_CONNECT; } if(0 == result) { failf(conn->data, "SOCKS5: connection timeout"); return CURLE_OPERATION_TIMEDOUT; } if(result & CURL_CSELECT_ERR) { failf(conn->data, "SOCKS5: error occurred during connection"); return CURLE_COULDNT_CONNECT; } if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) infof(conn->data, "warning: unsupported value passed to CURLOPT_SOCKS5_AUTH: %lu\n", 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++; /* reserve for the 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); (void)curlx_nonblock(sock, FALSE); infof(data, "SOCKS5 communication to %s:%d\n", hostname, remote_port); code = Curl_write_plain(conn, sock, (char *)socksreq, (2 + (int)socksreq[1]), &written); if(code || (written != (2 + (int)socksreq[1]))) { failf(data, "Unable to send initial SOCKS5 request."); return CURLE_COULDNT_CONNECT; } (void)curlx_nonblock(sock, TRUE); result = SOCKET_READABLE(sock, timeout); if(-1 == result) { failf(conn->data, "SOCKS5 nothing to read"); return CURLE_COULDNT_CONNECT; } if(0 == result) { failf(conn->data, "SOCKS5 read timeout"); return CURLE_OPERATION_TIMEDOUT; } if(result & CURL_CSELECT_ERR) { failf(conn->data, "SOCKS5 read error occurred"); return CURLE_RECV_ERROR; } (void)curlx_nonblock(sock, FALSE); result = Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread); if(result || (actualread != 2)) { failf(data, "Unable to receive initial SOCKS5 response."); return CURLE_COULDNT_CONNECT; } if(socksreq[0] != 5) { failf(data, "Received invalid version in initial SOCKS5 response."); return CURLE_COULDNT_CONNECT; } if(socksreq[1] == 0) { /* Nothing to do, no authentication needed */ ; } #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) else if(allow_gssapi && (socksreq[1] == 1)) { code = Curl_SOCKS5_gssapi_negotiate(sockindex, conn); if(code) { failf(data, "Unable to negotiate SOCKS5 GSS-API context."); return CURLE_COULDNT_CONNECT; } } #endif else if(socksreq[1] == 2) { /* 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 CURLE_BAD_FUNCTION_ARGUMENT; } 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 CURLE_BAD_FUNCTION_ARGUMENT; } memcpy(socksreq + len, proxy_password, proxy_password_len); } len += proxy_password_len; code = Curl_write_plain(conn, sock, (char *)socksreq, len, &written); if(code || (len != written)) { failf(data, "Failed to send SOCKS5 sub-negotiation request."); return CURLE_COULDNT_CONNECT; } result = Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread); if(result || (actualread != 2)) { failf(data, "Unable to receive SOCKS5 sub-negotiation response."); return CURLE_COULDNT_CONNECT; } /* ignore the first (VER) byte */ if(socksreq[1] != 0) { /* status */ failf(data, "User was rejected by the SOCKS5 server (%d %d).", socksreq[0], socksreq[1]); return CURLE_COULDNT_CONNECT; } /* Everything is good so far, user was authenticated! */ } else { /* error */ if(!allow_gssapi && (socksreq[1] == 1)) { failf(data, "SOCKS5 GSSAPI per-message authentication is not supported."); return CURLE_COULDNT_CONNECT; } if(socksreq[1] == 255) { if(!proxy_user || !*proxy_user) { failf(data, "No authentication method was acceptable. (It is quite likely" " that the SOCKS5 server wanted a username/password, since none" " was supplied to the server on this connection.)"); } else { failf(data, "No authentication method was acceptable."); } return CURLE_COULDNT_CONNECT; } else { failf(data, "Undocumented SOCKS5 mode attempted to be used by server."); return CURLE_COULDNT_CONNECT; } } /* 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; /* address length */ memcpy(&socksreq[len], hostname, hostname_len); /* address str w/o NULL */ len += hostname_len; } else { struct Curl_dns_entry *dns; Curl_addrinfo *hp = NULL; int rc = Curl_resolv(conn, hostname, remote_port, FALSE, &dns); if(rc == CURLRESOLV_ERROR) return CURLE_COULDNT_RESOLVE_HOST; if(rc == CURLRESOLV_PENDING) { /* this requires that we're in "wait for resolve" state */ code = Curl_resolver_wait_resolv(conn, &dns); if(code) return code; } /* * 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; if(hp) { char buf[64]; Curl_printable_address(hp, buf, sizeof(buf)); 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)\n", buf); } #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)\n", buf); } #endif else { hp = NULL; /* fail! */ failf(data, "SOCKS5 connection to %s not supported\n", buf); } Curl_resolv_unlock(data, dns); /* not used anymore from now on */ } if(!hp) { failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.", hostname); return CURLE_COULDNT_RESOLVE_HOST; } } socksreq[len++] = (unsigned char)((remote_port >> 8) & 0xff); /* PORT MSB */ socksreq[len++] = (unsigned char)(remote_port & 0xff); /* PORT LSB */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) if(conn->socks5_gssapi_enctype) { failf(data, "SOCKS5 GSS-API protection not yet implemented."); } else #endif code = Curl_write_plain(conn, sock, (char *)socksreq, len, &written); if(code || (len != written)) { failf(data, "Failed to send SOCKS5 connect request."); return CURLE_COULDNT_CONNECT; } len = 10; /* minimum packet size is 10 */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) if(conn->socks5_gssapi_enctype) { failf(data, "SOCKS5 GSS-API protection not yet implemented."); } else #endif result = Curl_blockread_all(conn, sock, (char *)socksreq, len, &actualread); if(result || (len != actualread)) { failf(data, "Failed to receive SOCKS5 connect request ack."); return CURLE_COULDNT_CONNECT; } if(socksreq[0] != 5) { /* version */ failf(data, "SOCKS5 reply has wrong version, version should be 5."); return CURLE_COULDNT_CONNECT; } /* 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; } /* 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) { result = Curl_blockread_all(conn, sock, (char *)&socksreq[10], len - 10, &actualread); if(result || ((len - 10) != actualread)) { failf(data, "Failed to receive SOCKS5 connect request ack."); return CURLE_COULDNT_CONNECT; } } #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) } #endif if(socksreq[1] != 0) { /* Anything besides 0 is an error */ if(socksreq[3] == 1) { failf(data, "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]), (unsigned char)socksreq[1]); } else if(socksreq[3] == 3) { unsigned char port_upper = (unsigned char)socksreq[len - 2]; socksreq[len - 2] = 0; failf(data, "Can't complete SOCKS5 connection to %s:%d. (%d)", (char *)&socksreq[5], ((port_upper << 8) | (unsigned char)socksreq[len - 1]), (unsigned char)socksreq[1]); socksreq[len - 2] = port_upper; } else if(socksreq[3] == 4) { failf(data, "Can't complete SOCKS5 connection to %02x%02x:%02x%02x:" "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%d. (%d)", (unsigned char)socksreq[4], (unsigned char)socksreq[5], (unsigned char)socksreq[6], (unsigned char)socksreq[7], (unsigned char)socksreq[8], (unsigned char)socksreq[9], (unsigned char)socksreq[10], (unsigned char)socksreq[11], (unsigned char)socksreq[12], (unsigned char)socksreq[13], (unsigned char)socksreq[14], (unsigned char)socksreq[15], (unsigned char)socksreq[16], (unsigned char)socksreq[17], (unsigned char)socksreq[18], (unsigned char)socksreq[19], (((unsigned char)socksreq[20] << 8) | (unsigned char)socksreq[21]), (unsigned char)socksreq[1]); } return CURLE_COULDNT_CONNECT; } infof(data, "SOCKS5 request granted.\n"); (void)curlx_nonblock(sock, TRUE); return CURLE_OK; /* Proxy was successful! */ } #endif /* CURL_DISABLE_PROXY */
YifuLiu/AliOS-Things
components/curl/lib/socks.c
C
apache-2.0
26,392
#ifndef HEADER_CURL_SOCKS_H #define HEADER_CURL_SOCKS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef CURL_DISABLE_PROXY #define Curl_SOCKS4(a,b,c,d,e) CURLE_NOT_BUILT_IN #define Curl_SOCKS5(a,b,c,d,e,f) CURLE_NOT_BUILT_IN #else /* * Helper read-from-socket functions. Does the same as Curl_read() but it * blocks until all bytes amount of buffersize will be read. No more, no less. * * This is STUPID BLOCKING behaviour which we frown upon, but right now this * is what we have... */ int Curl_blockread_all(struct connectdata *conn, curl_socket_t sockfd, char *buf, ssize_t buffersize, ssize_t *n); /* * This function logs in to a SOCKS4(a) proxy and sends the specifics to the * final destination server. */ CURLcode Curl_SOCKS4(const char *proxy_name, const char *hostname, int remote_port, int sockindex, struct connectdata *conn); /* * This function logs in to a SOCKS5 proxy and sends the specifics to the * final destination server. */ CURLcode Curl_SOCKS5(const char *proxy_name, const char *proxy_password, const char *hostname, int remote_port, int sockindex, struct connectdata *conn); #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) /* * This function handles the SOCKS5 GSS-API negotiation and initialisation */ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct connectdata *conn); #endif #endif /* CURL_DISABLE_PROXY */ #endif /* HEADER_CURL_SOCKS_H */
YifuLiu/AliOS-Things
components/curl/lib/socks.h
C
apache-2.0
2,735
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2009, Markus Moeller, <markus_moeller@compuserve.com> * Copyright (C) 2012 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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:\n%s", function, buf); return 1; } return 0; } CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct connectdata *conn) { struct Curl_easy *data = conn->data; 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; } /* 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 != 0) { 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(conn, 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(conn, 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(conn, 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 / messgae 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(conn, 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 authencticated user %s with GSS-API.\n",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.\n", (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(conn, 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(conn, 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(conn, 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(conn, 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 / messgae 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(conn, 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 (%d).", 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 (%d).", 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); } infof(data, "SOCKS5 access with%s protection granted.\n", (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 */
YifuLiu/AliOS-Things
components/curl/lib/socks_gssapi.c
C
apache-2.0
20,127
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 connectdata *conn, 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(conn->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 connectdata *conn) { struct Curl_easy *data = conn->data; 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(conn, status, "AcquireCredentialsHandle")) { failf(data, "Failed to acquire credentials."); free(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); return CURLE_COULDNT_CONNECT; } /* As long as we need to keep sending some context info, and there's no */ /* errors, keep sending it... */ for(;;) { TCHAR *sname; sname = Curl_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); Curl_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(conn, 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 != 0) { 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(conn, 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(conn, 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(conn, 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 / messgae 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(conn, 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(conn, 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 authencticated user %s with GSS-API.\n", 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.\n", (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(conn, 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(conn, 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(conn, 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(conn, 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(conn, 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(conn, 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(conn, 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(conn, 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); } infof(data, "SOCKS5 access with%s protection granted.\n", (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
YifuLiu/AliOS-Things
components/curl/lib/socks_sspi.c
C
apache-2.0
22,868
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "multiif.h" #include "speedcheck.h" void Curl_speedinit(struct Curl_easy *data) { memset(&data->state.keeps_speed, 0, sizeof(struct curltime)); } /* * @unittest: 1606 */ CURLcode Curl_speedcheck(struct Curl_easy *data, struct curltime now) { if((data->progress.current_speed >= 0) && data->set.low_speed_time) { if(data->progress.current_speed < data->set.low_speed_limit) { if(!data->state.keeps_speed.tv_sec) /* under the limit at this very moment */ data->state.keeps_speed = now; else { /* how long has it been under the limit */ timediff_t howlong = Curl_timediff(now, data->state.keeps_speed); if(howlong >= data->set.low_speed_time * 1000) { /* too long */ failf(data, "Operation too slow. " "Less than %ld bytes/sec transferred the last %ld seconds", data->set.low_speed_limit, data->set.low_speed_time); return CURLE_OPERATION_TIMEDOUT; } } } else /* faster right now */ data->state.keeps_speed.tv_sec = 0; } if(data->set.low_speed_limit) /* if low speed limit is enabled, set the expire timer to make this connection's speed get checked again in a second */ Curl_expire(data, 1000, EXPIRE_SPEEDCHECK); return CURLE_OK; }
YifuLiu/AliOS-Things
components/curl/lib/speedcheck.c
C
apache-2.0
2,496
#ifndef HEADER_CURL_SPEEDCHECK_H #define HEADER_CURL_SPEEDCHECK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "timeval.h" void Curl_speedinit(struct Curl_easy *data); CURLcode Curl_speedcheck(struct Curl_easy *data, struct curltime now); #endif /* HEADER_CURL_SPEEDCHECK_H */
YifuLiu/AliOS-Things
components/curl/lib/speedcheck.h
C
apache-2.0
1,320
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1997 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "splay.h" /* * This macro compares two node keys i and j and returns: * * negative value: when i is smaller than j * zero : when i is equal to j * positive when : when i is larger than j */ #define compare(i,j) Curl_splaycomparekeys((i),(j)) /* * Splay using the key i (which may or may not be in the tree.) The starting * root is t. */ struct Curl_tree *Curl_splay(struct curltime i, struct Curl_tree *t) { struct Curl_tree N, *l, *r, *y; if(t == NULL) return t; N.smaller = N.larger = NULL; l = r = &N; for(;;) { long comp = compare(i, t->key); if(comp < 0) { if(t->smaller == NULL) break; if(compare(i, t->smaller->key) < 0) { y = t->smaller; /* rotate smaller */ t->smaller = y->larger; y->larger = t; t = y; if(t->smaller == NULL) break; } r->smaller = t; /* link smaller */ r = t; t = t->smaller; } else if(comp > 0) { if(t->larger == NULL) break; if(compare(i, t->larger->key) > 0) { y = t->larger; /* rotate larger */ t->larger = y->smaller; y->smaller = t; t = y; if(t->larger == NULL) break; } l->larger = t; /* link larger */ l = t; t = t->larger; } else break; } l->larger = t->smaller; /* assemble */ r->smaller = t->larger; t->smaller = N.larger; t->larger = N.smaller; return t; } /* Insert key i into the tree t. Return a pointer to the resulting tree or * NULL if something went wrong. * * @unittest: 1309 */ struct Curl_tree *Curl_splayinsert(struct curltime i, struct Curl_tree *t, struct Curl_tree *node) { static const struct curltime KEY_NOTUSED = { (time_t)-1, (unsigned int)-1 }; /* will *NEVER* appear */ if(node == NULL) return t; if(t != NULL) { t = Curl_splay(i, t); if(compare(i, t->key) == 0) { /* There already exists a node in the tree with the very same key. Build a doubly-linked circular list of nodes. We add the new 'node' struct to the end of this list. */ node->key = KEY_NOTUSED; /* we set the key in the sub node to NOTUSED to quickly identify this node as a subnode */ node->samen = t; node->samep = t->samep; t->samep->samen = node; t->samep = node; return t; /* the root node always stays the same */ } } if(t == NULL) { node->smaller = node->larger = NULL; } else if(compare(i, t->key) < 0) { node->smaller = t->smaller; node->larger = t; t->smaller = NULL; } else { node->larger = t->larger; node->smaller = t; t->larger = NULL; } node->key = i; /* no identical nodes (yet), we are the only one in the list of nodes */ node->samen = node; node->samep = node; return node; } /* Finds and deletes the best-fit node from the tree. Return a pointer to the resulting tree. best-fit means the smallest node if it is not larger than the key */ struct Curl_tree *Curl_splaygetbest(struct curltime i, struct Curl_tree *t, struct Curl_tree **removed) { static struct curltime tv_zero = {0, 0}; struct Curl_tree *x; if(!t) { *removed = NULL; /* none removed since there was no root */ return NULL; } /* find smallest */ t = Curl_splay(tv_zero, t); if(compare(i, t->key) < 0) { /* even the smallest is too big */ *removed = NULL; return t; } /* FIRST! Check if there is a list with identical keys */ x = t->samen; if(x != t) { /* there is, pick one from the list */ /* 'x' is the new root node */ x->key = t->key; x->larger = t->larger; x->smaller = t->smaller; x->samep = t->samep; t->samep->samen = x; *removed = t; return x; /* new root */ } /* we splayed the tree to the smallest element, there is no smaller */ x = t->larger; *removed = t; return x; } /* Deletes the very node we point out from the tree if it's there. Stores a * pointer to the new resulting tree in 'newroot'. * * Returns zero on success and non-zero on errors! * When returning error, it does not touch the 'newroot' pointer. * * NOTE: when the last node of the tree is removed, there's no tree left so * 'newroot' will be made to point to NULL. * * @unittest: 1309 */ int Curl_splayremovebyaddr(struct Curl_tree *t, struct Curl_tree *removenode, struct Curl_tree **newroot) { static const struct curltime KEY_NOTUSED = { (time_t)-1, (unsigned int)-1 }; /* will *NEVER* appear */ struct Curl_tree *x; if(!t || !removenode) return 1; if(compare(KEY_NOTUSED, removenode->key) == 0) { /* Key set to NOTUSED means it is a subnode within a 'same' linked list and thus we can unlink it easily. */ if(removenode->samen == removenode) /* A non-subnode should never be set to KEY_NOTUSED */ return 3; removenode->samep->samen = removenode->samen; removenode->samen->samep = removenode->samep; /* Ensures that double-remove gets caught. */ removenode->samen = removenode; *newroot = t; /* return the same root */ return 0; } t = Curl_splay(removenode->key, t); /* First make sure that we got the same root node as the one we want to remove, as otherwise we might be trying to remove a node that isn't actually in the tree. We cannot just compare the keys here as a double remove in quick succession of a node with key != KEY_NOTUSED && same != NULL could return the same key but a different node. */ if(t != removenode) return 2; /* Check if there is a list with identical sizes, as then we're trying to remove the root node of a list of nodes with identical keys. */ x = t->samen; if(x != t) { /* 'x' is the new root node, we just make it use the root node's smaller/larger links */ x->key = t->key; x->larger = t->larger; x->smaller = t->smaller; x->samep = t->samep; t->samep->samen = x; } else { /* Remove the root node */ if(t->smaller == NULL) x = t->larger; else { x = Curl_splay(removenode->key, t->smaller); x->larger = t->larger; } } *newroot = x; /* store new root pointer */ return 0; }
YifuLiu/AliOS-Things
components/curl/lib/splay.c
C
apache-2.0
7,707
#ifndef HEADER_CURL_SPLAY_H #define HEADER_CURL_SPLAY_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1997 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "timeval.h" struct Curl_tree { struct Curl_tree *smaller; /* smaller node */ struct Curl_tree *larger; /* larger node */ struct Curl_tree *samen; /* points to the next node with identical key */ struct Curl_tree *samep; /* points to the prev node with identical key */ struct curltime key; /* this node's "sort" key */ void *payload; /* data the splay code doesn't care about */ }; struct Curl_tree *Curl_splay(struct curltime i, struct Curl_tree *t); struct Curl_tree *Curl_splayinsert(struct curltime key, struct Curl_tree *t, struct Curl_tree *newnode); #if 0 struct Curl_tree *Curl_splayremove(struct curltime key, struct Curl_tree *t, struct Curl_tree **removed); #endif struct Curl_tree *Curl_splaygetbest(struct curltime key, struct Curl_tree *t, struct Curl_tree **removed); int Curl_splayremovebyaddr(struct Curl_tree *t, struct Curl_tree *removenode, struct Curl_tree **newroot); #define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \ ( ((i.tv_sec) > (j.tv_sec)) ? 1 : \ ( ((i.tv_usec) < (j.tv_usec)) ? -1 : \ ( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0)))) #ifdef DEBUGBUILD void Curl_splayprint(struct Curl_tree * t, int d, char output); #else #define Curl_splayprint(x,y,z) Curl_nop_stmt #endif #endif /* HEADER_CURL_SPLAY_H */
YifuLiu/AliOS-Things
components/curl/lib/splay.h
C
apache-2.0
2,816
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2017 - 2019 Red Hat, Inc. * * Authors: Nikos Mavrogiannopoulos, Tomas Mraz, Stanislav Zidek, * Robert Kolcun, Andreas Schneider * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_LIBSSH #include <limits.h> #include <libssh/libssh.h> #include <libssh/sftp.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "ssh.h" #include "url.h" #include "speedcheck.h" #include "getinfo.h" #include "strdup.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "inet_ntop.h" #include "parsedate.h" /* for the week day and month names */ #include "sockaddr.h" /* required for Curl_sockaddr_storage */ #include "strtoofft.h" #include "multiif.h" #include "select.h" #include "warnless.h" /* for permission and open flags */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #include "curl_path.h" /* A recent macro provided by libssh. Or make our own. */ #ifndef SSH_STRING_FREE_CHAR /* !checksrc! disable ASSIGNWITHINCONDITION 1 */ #define SSH_STRING_FREE_CHAR(x) \ do { if((x) != NULL) { ssh_string_free_char(x); x = NULL; } } while(0) #endif /* Local functions: */ static CURLcode myssh_connect(struct connectdata *conn, bool *done); static CURLcode myssh_multi_statemach(struct connectdata *conn, bool *done); static CURLcode myssh_do_it(struct connectdata *conn, bool *done); static CURLcode scp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection); static CURLcode sftp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode sftp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode sftp_disconnect(struct connectdata *conn, bool dead); static CURLcode sftp_perform(struct connectdata *conn, bool *connected, bool *dophase_done); static void sftp_quote(struct connectdata *conn); static void sftp_quote_stat(struct connectdata *conn); static int myssh_getsock(struct connectdata *conn, curl_socket_t *sock, int numsocks); static int myssh_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, int numsocks); static CURLcode myssh_setup_connection(struct connectdata *conn); /* * SCP protocol handler. */ const struct Curl_handler Curl_handler_scp = { "SCP", /* scheme */ myssh_setup_connection, /* setup_connection */ myssh_do_it, /* do_it */ scp_done, /* done */ ZERO_NULL, /* do_more */ myssh_connect, /* connect_it */ myssh_multi_statemach, /* connecting */ scp_doing, /* doing */ myssh_getsock, /* proto_getsock */ myssh_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ myssh_perform_getsock, /* perform_getsock */ scp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SSH, /* defport */ CURLPROTO_SCP, /* protocol */ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */ }; /* * SFTP protocol handler. */ const struct Curl_handler Curl_handler_sftp = { "SFTP", /* scheme */ myssh_setup_connection, /* setup_connection */ myssh_do_it, /* do_it */ sftp_done, /* done */ ZERO_NULL, /* do_more */ myssh_connect, /* connect_it */ myssh_multi_statemach, /* connecting */ sftp_doing, /* doing */ myssh_getsock, /* proto_getsock */ myssh_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ myssh_perform_getsock, /* perform_getsock */ sftp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SSH, /* defport */ CURLPROTO_SFTP, /* protocol */ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */ }; static CURLcode sftp_error_to_CURLE(int err) { switch(err) { case SSH_FX_OK: return CURLE_OK; case SSH_FX_NO_SUCH_FILE: case SSH_FX_NO_SUCH_PATH: return CURLE_REMOTE_FILE_NOT_FOUND; case SSH_FX_PERMISSION_DENIED: case SSH_FX_WRITE_PROTECT: return CURLE_REMOTE_ACCESS_DENIED; case SSH_FX_FILE_ALREADY_EXISTS: return CURLE_REMOTE_FILE_EXISTS; default: break; } return CURLE_SSH; } #ifndef DEBUGBUILD #define state(x,y) mystate(x,y) #else #define state(x,y) mystate(x,y, __LINE__) #endif /* * SSH State machine related code */ /* This is the ONLY way to change SSH state! */ static void mystate(struct connectdata *conn, sshstate nowstate #ifdef DEBUGBUILD , int lineno #endif ) { struct ssh_conn *sshc = &conn->proto.sshc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char *const names[] = { "SSH_STOP", "SSH_INIT", "SSH_S_STARTUP", "SSH_HOSTKEY", "SSH_AUTHLIST", "SSH_AUTH_PKEY_INIT", "SSH_AUTH_PKEY", "SSH_AUTH_PASS_INIT", "SSH_AUTH_PASS", "SSH_AUTH_AGENT_INIT", "SSH_AUTH_AGENT_LIST", "SSH_AUTH_AGENT", "SSH_AUTH_HOST_INIT", "SSH_AUTH_HOST", "SSH_AUTH_KEY_INIT", "SSH_AUTH_KEY", "SSH_AUTH_GSSAPI", "SSH_AUTH_DONE", "SSH_SFTP_INIT", "SSH_SFTP_REALPATH", "SSH_SFTP_QUOTE_INIT", "SSH_SFTP_POSTQUOTE_INIT", "SSH_SFTP_QUOTE", "SSH_SFTP_NEXT_QUOTE", "SSH_SFTP_QUOTE_STAT", "SSH_SFTP_QUOTE_SETSTAT", "SSH_SFTP_QUOTE_SYMLINK", "SSH_SFTP_QUOTE_MKDIR", "SSH_SFTP_QUOTE_RENAME", "SSH_SFTP_QUOTE_RMDIR", "SSH_SFTP_QUOTE_UNLINK", "SSH_SFTP_QUOTE_STATVFS", "SSH_SFTP_GETINFO", "SSH_SFTP_FILETIME", "SSH_SFTP_TRANS_INIT", "SSH_SFTP_UPLOAD_INIT", "SSH_SFTP_CREATE_DIRS_INIT", "SSH_SFTP_CREATE_DIRS", "SSH_SFTP_CREATE_DIRS_MKDIR", "SSH_SFTP_READDIR_INIT", "SSH_SFTP_READDIR", "SSH_SFTP_READDIR_LINK", "SSH_SFTP_READDIR_BOTTOM", "SSH_SFTP_READDIR_DONE", "SSH_SFTP_DOWNLOAD_INIT", "SSH_SFTP_DOWNLOAD_STAT", "SSH_SFTP_CLOSE", "SSH_SFTP_SHUTDOWN", "SSH_SCP_TRANS_INIT", "SSH_SCP_UPLOAD_INIT", "SSH_SCP_DOWNLOAD_INIT", "SSH_SCP_DOWNLOAD", "SSH_SCP_DONE", "SSH_SCP_SEND_EOF", "SSH_SCP_WAIT_EOF", "SSH_SCP_WAIT_CLOSE", "SSH_SCP_CHANNEL_FREE", "SSH_SESSION_DISCONNECT", "SSH_SESSION_FREE", "QUIT" }; if(sshc->state != nowstate) { infof(conn->data, "SSH %p state change from %s to %s (line %d)\n", (void *) sshc, names[sshc->state], names[nowstate], lineno); } #endif sshc->state = nowstate; } /* Multiple options: * 1. data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5] is set with an MD5 * hash (90s style auth, not sure we should have it here) * 2. data->set.ssh_keyfunc callback is set. Then we do trust on first * use. We even save on knownhosts if CURLKHSTAT_FINE_ADD_TO_FILE * is returned by it. * 3. none of the above. We only accept if it is present on known hosts. * * Returns SSH_OK or SSH_ERROR. */ static int myssh_is_known(struct connectdata *conn) { int rc; struct Curl_easy *data = conn->data; struct ssh_conn *sshc = &conn->proto.sshc; ssh_key pubkey; size_t hlen; unsigned char *hash = NULL; char *base64 = NULL; int vstate; enum curl_khmatch keymatch; struct curl_khkey foundkey; curl_sshkeycallback func = data->set.ssh_keyfunc; rc = ssh_get_publickey(sshc->ssh_session, &pubkey); if(rc != SSH_OK) return rc; if(data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) { rc = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_MD5, &hash, &hlen); if(rc != SSH_OK) goto cleanup; if(hlen != strlen(data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) || memcmp(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], hash, hlen)) { rc = SSH_ERROR; goto cleanup; } rc = SSH_OK; goto cleanup; } if(data->set.ssl.primary.verifyhost != TRUE) { rc = SSH_OK; goto cleanup; } vstate = ssh_is_server_known(sshc->ssh_session); switch(vstate) { case SSH_SERVER_KNOWN_OK: keymatch = CURLKHMATCH_OK; break; case SSH_SERVER_FILE_NOT_FOUND: /* fallthrough */ case SSH_SERVER_NOT_KNOWN: keymatch = CURLKHMATCH_MISSING; break; default: keymatch = CURLKHMATCH_MISMATCH; break; } if(func) { /* use callback to determine action */ rc = ssh_pki_export_pubkey_base64(pubkey, &base64); if(rc != SSH_OK) goto cleanup; foundkey.key = base64; foundkey.len = strlen(base64); switch(ssh_key_type(pubkey)) { case SSH_KEYTYPE_RSA: foundkey.keytype = CURLKHTYPE_RSA; break; case SSH_KEYTYPE_RSA1: foundkey.keytype = CURLKHTYPE_RSA1; break; case SSH_KEYTYPE_ECDSA: foundkey.keytype = CURLKHTYPE_ECDSA; break; #if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,7,0) case SSH_KEYTYPE_ED25519: foundkey.keytype = CURLKHTYPE_ED25519; break; #endif case SSH_KEYTYPE_DSS: foundkey.keytype = CURLKHTYPE_DSS; break; default: rc = SSH_ERROR; goto cleanup; } /* we don't have anything equivalent to knownkey. Always NULL */ Curl_set_in_callback(data, true); rc = func(data, NULL, &foundkey, /* from the remote host */ keymatch, data->set.ssh_keyfunc_userp); Curl_set_in_callback(data, false); switch(rc) { case CURLKHSTAT_FINE_ADD_TO_FILE: rc = ssh_write_knownhost(sshc->ssh_session); if(rc != SSH_OK) { goto cleanup; } break; case CURLKHSTAT_FINE: break; default: /* REJECT/DEFER */ rc = SSH_ERROR; goto cleanup; } } else { if(keymatch != CURLKHMATCH_OK) { rc = SSH_ERROR; goto cleanup; } } rc = SSH_OK; cleanup: if(hash) ssh_clean_pubkey_hash(&hash); ssh_key_free(pubkey); return rc; } #define MOVE_TO_ERROR_STATE(_r) { \ state(conn, SSH_SESSION_DISCONNECT); \ sshc->actualcode = _r; \ rc = SSH_ERROR; \ break; \ } #define MOVE_TO_SFTP_CLOSE_STATE() { \ state(conn, SSH_SFTP_CLOSE); \ sshc->actualcode = sftp_error_to_CURLE(sftp_get_error(sshc->sftp_session)); \ rc = SSH_ERROR; \ break; \ } #define MOVE_TO_LAST_AUTH \ if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { \ rc = SSH_OK; \ state(conn, SSH_AUTH_PASS_INIT); \ break; \ } \ else { \ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); \ } #define MOVE_TO_TERTIARY_AUTH \ if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { \ rc = SSH_OK; \ state(conn, SSH_AUTH_KEY_INIT); \ break; \ } \ else { \ MOVE_TO_LAST_AUTH; \ } #define MOVE_TO_SECONDARY_AUTH \ if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { \ rc = SSH_OK; \ state(conn, SSH_AUTH_GSSAPI); \ break; \ } \ else { \ MOVE_TO_TERTIARY_AUTH; \ } static int myssh_auth_interactive(struct connectdata *conn) { int rc; struct ssh_conn *sshc = &conn->proto.sshc; int nprompts; restart: switch(sshc->kbd_state) { case 0: rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); if(rc == SSH_AUTH_AGAIN) return SSH_AGAIN; if(rc != SSH_AUTH_INFO) return SSH_ERROR; nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); if(nprompts == SSH_ERROR || nprompts != 1) return SSH_ERROR; rc = ssh_userauth_kbdint_setanswer(sshc->ssh_session, 0, conn->passwd); if(rc < 0) return SSH_ERROR; /* FALLTHROUGH */ case 1: sshc->kbd_state = 1; rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); if(rc == SSH_AUTH_AGAIN) return SSH_AGAIN; else if(rc == SSH_AUTH_SUCCESS) rc = SSH_OK; else if(rc == SSH_AUTH_INFO) { nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session); if(nprompts != 0) return SSH_ERROR; sshc->kbd_state = 2; goto restart; } else rc = SSH_ERROR; break; case 2: sshc->kbd_state = 2; rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL); if(rc == SSH_AUTH_AGAIN) return SSH_AGAIN; else if(rc == SSH_AUTH_SUCCESS) rc = SSH_OK; else rc = SSH_ERROR; break; default: return SSH_ERROR; } sshc->kbd_state = 0; return rc; } /* * ssh_statemach_act() runs the SSH state machine as far as it can without * blocking and without reaching the end. The data the pointer 'block' points * to will be set to TRUE if the libssh function returns SSH_AGAIN * meaning it wants to be called again when the socket is ready */ static CURLcode myssh_statemach_act(struct connectdata *conn, bool *block) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SSHPROTO *protop = data->req.protop; struct ssh_conn *sshc = &conn->proto.sshc; curl_socket_t sock = conn->sock[FIRSTSOCKET]; int rc = SSH_NO_ERROR, err; char *new_readdir_line; int seekerr = CURL_SEEKFUNC_OK; const char *err_msg; *block = 0; /* we're not blocking by default */ do { switch(sshc->state) { case SSH_INIT: sshc->secondCreateDirs = 0; sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_OK; #if 0 ssh_set_log_level(SSH_LOG_PROTOCOL); #endif /* Set libssh to non-blocking, since everything internally is non-blocking */ ssh_set_blocking(sshc->ssh_session, 0); state(conn, SSH_S_STARTUP); /* FALLTHROUGH */ case SSH_S_STARTUP: rc = ssh_connect(sshc->ssh_session); if(rc == SSH_AGAIN) break; if(rc != SSH_OK) { failf(data, "Failure establishing ssh session"); MOVE_TO_ERROR_STATE(CURLE_FAILED_INIT); } state(conn, SSH_HOSTKEY); /* FALLTHROUGH */ case SSH_HOSTKEY: rc = myssh_is_known(conn); if(rc != SSH_OK) { MOVE_TO_ERROR_STATE(CURLE_PEER_FAILED_VERIFICATION); } state(conn, SSH_AUTHLIST); /* FALLTHROUGH */ case SSH_AUTHLIST:{ sshc->authed = FALSE; rc = ssh_userauth_none(sshc->ssh_session, NULL); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc == SSH_AUTH_SUCCESS) { sshc->authed = TRUE; infof(data, "Authenticated with none\n"); state(conn, SSH_AUTH_DONE); break; } else if(rc == SSH_AUTH_ERROR) { MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); } sshc->auth_methods = ssh_userauth_list(sshc->ssh_session, NULL); if(sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY) { state(conn, SSH_AUTH_PKEY_INIT); infof(data, "Authentication using SSH public key file\n"); } else if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { state(conn, SSH_AUTH_GSSAPI); } else if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { state(conn, SSH_AUTH_KEY_INIT); } else if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { state(conn, SSH_AUTH_PASS_INIT); } else { /* unsupported authentication method */ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); } break; } case SSH_AUTH_PKEY_INIT: if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY)) { MOVE_TO_SECONDARY_AUTH; } /* Two choices, (1) private key was given on CMD, * (2) use the "default" keys. */ if(data->set.str[STRING_SSH_PRIVATE_KEY]) { if(sshc->pubkey && !data->set.ssl.key_passwd) { rc = ssh_userauth_try_publickey(sshc->ssh_session, NULL, sshc->pubkey); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc != SSH_OK) { MOVE_TO_SECONDARY_AUTH; } } rc = ssh_pki_import_privkey_file(data-> set.str[STRING_SSH_PRIVATE_KEY], data->set.ssl.key_passwd, NULL, NULL, &sshc->privkey); if(rc != SSH_OK) { failf(data, "Could not load private key file %s", data->set.str[STRING_SSH_PRIVATE_KEY]); MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); break; } state(conn, SSH_AUTH_PKEY); break; } else { rc = ssh_userauth_publickey_auto(sshc->ssh_session, NULL, data->set.ssl.key_passwd); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc == SSH_AUTH_SUCCESS) { rc = SSH_OK; sshc->authed = TRUE; infof(data, "Completed public key authentication\n"); state(conn, SSH_AUTH_DONE); break; } MOVE_TO_SECONDARY_AUTH; } break; case SSH_AUTH_PKEY: rc = ssh_userauth_publickey(sshc->ssh_session, NULL, sshc->privkey); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc == SSH_AUTH_SUCCESS) { sshc->authed = TRUE; infof(data, "Completed public key authentication\n"); state(conn, SSH_AUTH_DONE); break; } else { infof(data, "Failed public key authentication (rc: %d)\n", rc); MOVE_TO_SECONDARY_AUTH; } break; case SSH_AUTH_GSSAPI: if(!(data->set.ssh_auth_types & CURLSSH_AUTH_GSSAPI)) { MOVE_TO_TERTIARY_AUTH; } rc = ssh_userauth_gssapi(sshc->ssh_session); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc == SSH_AUTH_SUCCESS) { rc = SSH_OK; sshc->authed = TRUE; infof(data, "Completed gssapi authentication\n"); state(conn, SSH_AUTH_DONE); break; } MOVE_TO_TERTIARY_AUTH; break; case SSH_AUTH_KEY_INIT: if(data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) { state(conn, SSH_AUTH_KEY); } else { MOVE_TO_LAST_AUTH; } break; case SSH_AUTH_KEY: /* Authentication failed. Continue with keyboard-interactive now. */ rc = myssh_auth_interactive(conn); if(rc == SSH_AGAIN) { break; } if(rc == SSH_OK) { sshc->authed = TRUE; infof(data, "completed keyboard interactive authentication\n"); } state(conn, SSH_AUTH_DONE); break; case SSH_AUTH_PASS_INIT: if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD)) { /* Host key authentication is intentionally not implemented */ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); } state(conn, SSH_AUTH_PASS); /* FALLTHROUGH */ case SSH_AUTH_PASS: rc = ssh_userauth_password(sshc->ssh_session, NULL, conn->passwd); if(rc == SSH_AUTH_AGAIN) { rc = SSH_AGAIN; break; } if(rc == SSH_AUTH_SUCCESS) { sshc->authed = TRUE; infof(data, "Completed password authentication\n"); state(conn, SSH_AUTH_DONE); } else { MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); } break; case SSH_AUTH_DONE: if(!sshc->authed) { failf(data, "Authentication failure"); MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); break; } /* * At this point we have an authenticated ssh session. */ infof(data, "Authentication complete\n"); Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSH is connected */ conn->sockfd = sock; conn->writesockfd = CURL_SOCKET_BAD; if(conn->handler->protocol == CURLPROTO_SFTP) { state(conn, SSH_SFTP_INIT); break; } infof(data, "SSH CONNECT phase done\n"); state(conn, SSH_STOP); break; case SSH_SFTP_INIT: ssh_set_blocking(sshc->ssh_session, 1); sshc->sftp_session = sftp_new(sshc->ssh_session); if(!sshc->sftp_session) { failf(data, "Failure initializing sftp session: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); break; } rc = sftp_init(sshc->sftp_session); if(rc != SSH_OK) { rc = sftp_get_error(sshc->sftp_session); failf(data, "Failure initializing sftp session: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_ERROR_STATE(sftp_error_to_CURLE(rc)); break; } state(conn, SSH_SFTP_REALPATH); /* FALLTHROUGH */ case SSH_SFTP_REALPATH: /* * Get the "home" directory */ sshc->homedir = sftp_canonicalize_path(sshc->sftp_session, "."); if(sshc->homedir == NULL) { MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); } conn->data->state.most_recent_ftp_entrypath = sshc->homedir; /* This is the last step in the SFTP connect phase. Do note that while we get the homedir here, we get the "workingpath" in the DO action since the homedir will remain the same between request but the working path will not. */ DEBUGF(infof(data, "SSH CONNECT phase done\n")); state(conn, SSH_STOP); break; case SSH_SFTP_QUOTE_INIT: result = Curl_getworkingpath(conn, sshc->homedir, &protop->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } if(data->set.quote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.quote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_SFTP_GETINFO); } break; case SSH_SFTP_POSTQUOTE_INIT: if(data->set.postquote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.postquote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_STOP); } break; case SSH_SFTP_QUOTE: /* Send any quote commands */ sftp_quote(conn); break; case SSH_SFTP_NEXT_QUOTE: Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); sshc->quote_item = sshc->quote_item->next; if(sshc->quote_item) { state(conn, SSH_SFTP_QUOTE); } else { if(sshc->nextstate != SSH_NO_STATE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_NO_STATE; } else { state(conn, SSH_SFTP_GETINFO); } } break; case SSH_SFTP_QUOTE_STAT: sftp_quote_stat(conn); break; case SSH_SFTP_QUOTE_SETSTAT: rc = sftp_setstat(sshc->sftp_session, sshc->quote_path2, sshc->quote_attrs); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to set SFTP stats failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; /* sshc->actualcode = sftp_error_to_CURLE(err); * we do not send the actual error; we return * the error the libssh2 backend is returning */ break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_SYMLINK: rc = sftp_symlink(sshc->sftp_session, sshc->quote_path2, sshc->quote_path1); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "symlink command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_MKDIR: rc = sftp_mkdir(sshc->sftp_session, sshc->quote_path1, (mode_t)data->set.new_directory_perms); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); failf(data, "mkdir command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RENAME: rc = sftp_rename(sshc->sftp_session, sshc->quote_path1, sshc->quote_path2); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "rename command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RMDIR: rc = sftp_rmdir(sshc->sftp_session, sshc->quote_path1); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); failf(data, "rmdir command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_UNLINK: rc = sftp_unlink(sshc->sftp_session, sshc->quote_path1); if(rc != 0 && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); failf(data, "rm command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_STATVFS: { sftp_statvfs_t statvfs; statvfs = sftp_statvfs(sshc->sftp_session, sshc->quote_path1); if(!statvfs && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); failf(data, "statvfs command failed: %s", ssh_get_error(sshc->ssh_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } else if(statvfs) { char *tmp = aprintf("statvfs:\n" "f_bsize: %llu\n" "f_frsize: %llu\n" "f_blocks: %llu\n" "f_bfree: %llu\n" "f_bavail: %llu\n" "f_files: %llu\n" "f_ffree: %llu\n" "f_favail: %llu\n" "f_fsid: %llu\n" "f_flag: %llu\n" "f_namemax: %llu\n", statvfs->f_bsize, statvfs->f_frsize, statvfs->f_blocks, statvfs->f_bfree, statvfs->f_bavail, statvfs->f_files, statvfs->f_ffree, statvfs->f_favail, statvfs->f_fsid, statvfs->f_flag, statvfs->f_namemax); sftp_statvfs_free(statvfs); if(!tmp) { result = CURLE_OUT_OF_MEMORY; state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; break; } result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); free(tmp); if(result) { state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; } } state(conn, SSH_SFTP_NEXT_QUOTE); break; } case SSH_SFTP_GETINFO: if(data->set.get_filetime) { state(conn, SSH_SFTP_FILETIME); } else { state(conn, SSH_SFTP_TRANS_INIT); } break; case SSH_SFTP_FILETIME: { sftp_attributes attrs; attrs = sftp_stat(sshc->sftp_session, protop->path); if(attrs != 0) { data->info.filetime = attrs->mtime; sftp_attributes_free(attrs); } state(conn, SSH_SFTP_TRANS_INIT); break; } case SSH_SFTP_TRANS_INIT: if(data->set.upload) state(conn, SSH_SFTP_UPLOAD_INIT); else { if(protop->path[strlen(protop->path)-1] == '/') state(conn, SSH_SFTP_READDIR_INIT); else state(conn, SSH_SFTP_DOWNLOAD_INIT); } break; case SSH_SFTP_UPLOAD_INIT: { int flags; if(data->state.resume_from != 0) { sftp_attributes attrs; if(data->state.resume_from < 0) { attrs = sftp_stat(sshc->sftp_session, protop->path); if(attrs != 0) { curl_off_t size = attrs->size; if(size < 0) { failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); MOVE_TO_ERROR_STATE(CURLE_BAD_DOWNLOAD_RESUME); } data->state.resume_from = attrs->size; sftp_attributes_free(attrs); } else { data->state.resume_from = 0; } } } if(data->set.ftp_append) /* Try to open for append, but create if nonexisting */ flags = O_WRONLY|O_CREAT|O_APPEND; else if(data->state.resume_from > 0) /* If we have restart position then open for append */ flags = O_WRONLY|O_APPEND; else /* Clear file before writing (normal behaviour) */ flags = O_WRONLY|O_APPEND|O_CREAT|O_TRUNC; if(sshc->sftp_file) sftp_close(sshc->sftp_file); sshc->sftp_file = sftp_open(sshc->sftp_session, protop->path, flags, (mode_t)data->set.new_file_perms); if(!sshc->sftp_file) { err = sftp_get_error(sshc->sftp_session); if(((err == SSH_FX_NO_SUCH_FILE || err == SSH_FX_FAILURE || err == SSH_FX_NO_SUCH_PATH)) && (data->set.ftp_create_missing_dirs && (strlen(protop->path) > 1))) { /* try to create the path remotely */ rc = 0; sshc->secondCreateDirs = 1; state(conn, SSH_SFTP_CREATE_DIRS_INIT); break; } else { MOVE_TO_SFTP_CLOSE_STATE(); } } /* If we have a restart point then we need to seek to the correct position. */ if(data->state.resume_from > 0) { /* Let's read off the proper amount of bytes from the input. */ if(conn->seek_func) { Curl_set_in_callback(data, true); seekerr = conn->seek_func(conn->seek_client, data->state.resume_from, SEEK_SET); Curl_set_in_callback(data, false); } if(seekerr != CURL_SEEKFUNC_OK) { curl_off_t passed = 0; if(seekerr != CURL_SEEKFUNC_CANTSEEK) { failf(data, "Could not seek stream"); return CURLE_FTP_COULDNT_USE_REST; } /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ do { size_t readthisamountnow = (data->state.resume_from - passed > data->set.buffer_size) ? (size_t)data->set.buffer_size : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = data->state.fread_func(data->state.buffer, 1, readthisamountnow, data->state.in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { /* this checks for greater-than only to make sure that the CURL_READFUNC_ABORT return code still aborts */ failf(data, "Failed to read data"); MOVE_TO_ERROR_STATE(CURLE_FTP_COULDNT_USE_REST); } } while(passed < data->state.resume_from); } /* now, decrease the size of the read */ if(data->state.infilesize > 0) { data->state.infilesize -= data->state.resume_from; data->req.size = data->state.infilesize; Curl_pgrsSetUploadSize(data, data->state.infilesize); } rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); if(rc != 0) { MOVE_TO_SFTP_CLOSE_STATE(); } } if(data->state.infilesize > 0) { data->req.size = data->state.infilesize; Curl_pgrsSetUploadSize(data, data->state.infilesize); } /* upload data */ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; /* store this original bitmask setup to use later on if we can't figure out a "real" bitmask */ sshc->orig_waitfor = data->req.keepon; /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh sftp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; /* since we don't really wait for anything at this point, we want the state machine to move on as soon as possible so we set a very short timeout here */ Curl_expire(data, 0, EXPIRE_RUN_NOW); state(conn, SSH_STOP); break; } case SSH_SFTP_CREATE_DIRS_INIT: if(strlen(protop->path) > 1) { sshc->slash_pos = protop->path + 1; /* ignore the leading '/' */ state(conn, SSH_SFTP_CREATE_DIRS); } else { state(conn, SSH_SFTP_UPLOAD_INIT); } break; case SSH_SFTP_CREATE_DIRS: sshc->slash_pos = strchr(sshc->slash_pos, '/'); if(sshc->slash_pos) { *sshc->slash_pos = 0; infof(data, "Creating directory '%s'\n", protop->path); state(conn, SSH_SFTP_CREATE_DIRS_MKDIR); break; } state(conn, SSH_SFTP_UPLOAD_INIT); break; case SSH_SFTP_CREATE_DIRS_MKDIR: /* 'mode' - parameter is preliminary - default to 0644 */ rc = sftp_mkdir(sshc->sftp_session, protop->path, (mode_t)data->set.new_directory_perms); *sshc->slash_pos = '/'; ++sshc->slash_pos; if(rc < 0) { /* * Abort if failure wasn't that the dir already exists or the * permission was denied (creation might succeed further down the * path) - retry on unspecific FAILURE also */ err = sftp_get_error(sshc->sftp_session); if((err != SSH_FX_FILE_ALREADY_EXISTS) && (err != SSH_FX_FAILURE) && (err != SSH_FX_PERMISSION_DENIED)) { MOVE_TO_SFTP_CLOSE_STATE(); } rc = 0; /* clear rc and continue */ } state(conn, SSH_SFTP_CREATE_DIRS); break; case SSH_SFTP_READDIR_INIT: Curl_pgrsSetDownloadSize(data, -1); if(data->set.opt_no_body) { state(conn, SSH_STOP); break; } /* * This is a directory that we are trying to get, so produce a directory * listing */ sshc->sftp_dir = sftp_opendir(sshc->sftp_session, protop->path); if(!sshc->sftp_dir) { failf(data, "Could not open directory for reading: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_SFTP_CLOSE_STATE(); } state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR: if(sshc->readdir_attrs) sftp_attributes_free(sshc->readdir_attrs); sshc->readdir_attrs = sftp_readdir(sshc->sftp_session, sshc->sftp_dir); if(sshc->readdir_attrs) { sshc->readdir_filename = sshc->readdir_attrs->name; sshc->readdir_longentry = sshc->readdir_attrs->longname; sshc->readdir_len = strlen(sshc->readdir_filename); if(data->set.ftp_list_only) { char *tmpLine; tmpLine = aprintf("%s\n", sshc->readdir_filename); if(tmpLine == NULL) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } result = Curl_client_write(conn, CLIENTWRITE_BODY, tmpLine, sshc->readdir_len + 1); free(tmpLine); if(result) { state(conn, SSH_STOP); break; } /* since this counts what we send to the client, we include the newline in this counter */ data->req.bytecount += sshc->readdir_len + 1; /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, (char *)sshc->readdir_filename, sshc->readdir_len); } } else { sshc->readdir_currLen = strlen(sshc->readdir_longentry); sshc->readdir_totalLen = 80 + sshc->readdir_currLen; sshc->readdir_line = calloc(sshc->readdir_totalLen, 1); if(!sshc->readdir_line) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } memcpy(sshc->readdir_line, sshc->readdir_longentry, sshc->readdir_currLen); if((sshc->readdir_attrs->flags & SSH_FILEXFER_ATTR_PERMISSIONS) && ((sshc->readdir_attrs->permissions & S_IFMT) == S_IFLNK)) { sshc->readdir_linkPath = malloc(PATH_MAX + 1); if(sshc->readdir_linkPath == NULL) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } msnprintf(sshc->readdir_linkPath, PATH_MAX, "%s%s", protop->path, sshc->readdir_filename); state(conn, SSH_SFTP_READDIR_LINK); break; } state(conn, SSH_SFTP_READDIR_BOTTOM); break; } } else if(sshc->readdir_attrs == NULL && sftp_dir_eof(sshc->sftp_dir)) { state(conn, SSH_SFTP_READDIR_DONE); break; } else { failf(data, "Could not open remote file for reading: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_SFTP_CLOSE_STATE(); break; } break; case SSH_SFTP_READDIR_LINK: if(sshc->readdir_link_attrs) sftp_attributes_free(sshc->readdir_link_attrs); sshc->readdir_link_attrs = sftp_lstat(sshc->sftp_session, sshc->readdir_linkPath); if(sshc->readdir_link_attrs == 0) { failf(data, "Could not read symlink for reading: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_SFTP_CLOSE_STATE(); } if(sshc->readdir_link_attrs->name == NULL) { sshc->readdir_tmp = sftp_readlink(sshc->sftp_session, sshc->readdir_linkPath); if(sshc->readdir_filename == NULL) sshc->readdir_len = 0; else sshc->readdir_len = strlen(sshc->readdir_tmp); sshc->readdir_longentry = NULL; sshc->readdir_filename = sshc->readdir_tmp; } else { sshc->readdir_len = strlen(sshc->readdir_link_attrs->name); sshc->readdir_filename = sshc->readdir_link_attrs->name; sshc->readdir_longentry = sshc->readdir_link_attrs->longname; } Curl_safefree(sshc->readdir_linkPath); /* get room for the filename and extra output */ sshc->readdir_totalLen += 4 + sshc->readdir_len; new_readdir_line = Curl_saferealloc(sshc->readdir_line, sshc->readdir_totalLen); if(!new_readdir_line) { sshc->readdir_line = NULL; state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->readdir_line = new_readdir_line; sshc->readdir_currLen += msnprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, " -> %s", sshc->readdir_filename); sftp_attributes_free(sshc->readdir_link_attrs); sshc->readdir_link_attrs = NULL; sshc->readdir_filename = NULL; sshc->readdir_longentry = NULL; state(conn, SSH_SFTP_READDIR_BOTTOM); /* FALLTHROUGH */ case SSH_SFTP_READDIR_BOTTOM: sshc->readdir_currLen += msnprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, "\n"); result = Curl_client_write(conn, CLIENTWRITE_BODY, sshc->readdir_line, sshc->readdir_currLen); if(!result) { /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_line, sshc->readdir_currLen); } data->req.bytecount += sshc->readdir_currLen; } Curl_safefree(sshc->readdir_line); ssh_string_free_char(sshc->readdir_tmp); sshc->readdir_tmp = NULL; if(result) { state(conn, SSH_STOP); } else state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR_DONE: sftp_closedir(sshc->sftp_dir); sshc->sftp_dir = NULL; /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); state(conn, SSH_STOP); break; case SSH_SFTP_DOWNLOAD_INIT: /* * Work on getting the specified file */ if(sshc->sftp_file) sftp_close(sshc->sftp_file); sshc->sftp_file = sftp_open(sshc->sftp_session, protop->path, O_RDONLY, (mode_t)data->set.new_file_perms); if(!sshc->sftp_file) { failf(data, "Could not open remote file for reading: %s", ssh_get_error(sshc->ssh_session)); MOVE_TO_SFTP_CLOSE_STATE(); } state(conn, SSH_SFTP_DOWNLOAD_STAT); break; case SSH_SFTP_DOWNLOAD_STAT: { sftp_attributes attrs; curl_off_t size; attrs = sftp_fstat(sshc->sftp_file); if(!attrs || !(attrs->flags & SSH_FILEXFER_ATTR_SIZE) || (attrs->size == 0)) { /* * sftp_fstat didn't return an error, so maybe the server * just doesn't support stat() * OR the server doesn't return a file size with a stat() * OR file size is 0 */ data->req.size = -1; data->req.maxdownload = -1; Curl_pgrsSetDownloadSize(data, -1); size = 0; } else { size = attrs->size; sftp_attributes_free(attrs); if(size < 0) { failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); return CURLE_BAD_DOWNLOAD_RESUME; } if(conn->data->state.use_range) { curl_off_t from, to; char *ptr; char *ptr2; CURLofft to_t; CURLofft from_t; from_t = curlx_strtoofft(conn->data->state.range, &ptr, 0, &from); if(from_t == CURL_OFFT_FLOW) { return CURLE_RANGE_ERROR; } while(*ptr && (ISSPACE(*ptr) || (*ptr == '-'))) ptr++; to_t = curlx_strtoofft(ptr, &ptr2, 0, &to); if(to_t == CURL_OFFT_FLOW) { return CURLE_RANGE_ERROR; } if((to_t == CURL_OFFT_INVAL) /* no "to" value given */ || (to >= size)) { to = size - 1; } if(from_t) { /* from is relative to end of file */ from = size - to; to = size - 1; } if(from > size) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", from, size); return CURLE_BAD_DOWNLOAD_RESUME; } if(from > to) { from = to; size = 0; } else { size = to - from + 1; } rc = sftp_seek64(sshc->sftp_file, from); if(rc != 0) { MOVE_TO_SFTP_CLOSE_STATE(); } } data->req.size = size; data->req.maxdownload = size; Curl_pgrsSetDownloadSize(data, size); } /* We can resume if we can seek to the resume position */ if(data->state.resume_from) { if(data->state.resume_from < 0) { /* We're supposed to download the last abs(from) bytes */ if((curl_off_t)size < -data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, size); return CURLE_BAD_DOWNLOAD_RESUME; } /* download from where? */ data->state.resume_from += size; } else { if((curl_off_t)size < data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, size); return CURLE_BAD_DOWNLOAD_RESUME; } } /* Does a completed file need to be seeked and started or closed ? */ /* Now store the number of bytes we are expected to download */ data->req.size = size - data->state.resume_from; data->req.maxdownload = size - data->state.resume_from; Curl_pgrsSetDownloadSize(data, size - data->state.resume_from); rc = sftp_seek64(sshc->sftp_file, data->state.resume_from); if(rc != 0) { MOVE_TO_SFTP_CLOSE_STATE(); } } } /* Setup the actual download */ if(data->req.size == 0) { /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); infof(data, "File already completely downloaded\n"); state(conn, SSH_STOP); break; } Curl_setup_transfer(data, FIRSTSOCKET, data->req.size, FALSE, -1); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; if(result) { /* this should never occur; the close state should be entered at the time the error occurs */ state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result; } else { sshc->sftp_recv_state = 0; state(conn, SSH_STOP); } break; case SSH_SFTP_CLOSE: if(sshc->sftp_file) { sftp_close(sshc->sftp_file); sshc->sftp_file = NULL; } Curl_safefree(protop->path); DEBUGF(infof(data, "SFTP DONE done\n")); /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT After nextstate is executed, the control should come back to SSH_SFTP_CLOSE to pass the correct result back */ if(sshc->nextstate != SSH_NO_STATE && sshc->nextstate != SSH_SFTP_CLOSE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_SFTP_CLOSE; } else { state(conn, SSH_STOP); result = sshc->actualcode; } break; case SSH_SFTP_SHUTDOWN: /* during times we get here due to a broken transfer and then the sftp_handle might not have been taken down so make sure that is done before we proceed */ if(sshc->sftp_file) { sftp_close(sshc->sftp_file); sshc->sftp_file = NULL; } if(sshc->sftp_session) { sftp_free(sshc->sftp_session); sshc->sftp_session = NULL; } SSH_STRING_FREE_CHAR(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_DISCONNECT); break; case SSH_SCP_TRANS_INIT: result = Curl_getworkingpath(conn, sshc->homedir, &protop->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } /* Functions from the SCP subsystem cannot handle/return SSH_AGAIN */ ssh_set_blocking(sshc->ssh_session, 1); if(data->set.upload) { if(data->state.infilesize < 0) { failf(data, "SCP requires a known file size for upload"); sshc->actualcode = CURLE_UPLOAD_FAILED; MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); } sshc->scp_session = ssh_scp_new(sshc->ssh_session, SSH_SCP_WRITE, protop->path); state(conn, SSH_SCP_UPLOAD_INIT); } else { sshc->scp_session = ssh_scp_new(sshc->ssh_session, SSH_SCP_READ, protop->path); state(conn, SSH_SCP_DOWNLOAD_INIT); } if(!sshc->scp_session) { err_msg = ssh_get_error(sshc->ssh_session); failf(conn->data, "%s", err_msg); MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); } break; case SSH_SCP_UPLOAD_INIT: rc = ssh_scp_init(sshc->scp_session); if(rc != SSH_OK) { err_msg = ssh_get_error(sshc->ssh_session); failf(conn->data, "%s", err_msg); MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); } rc = ssh_scp_push_file(sshc->scp_session, protop->path, data->state.infilesize, (int)data->set.new_file_perms); if(rc != SSH_OK) { err_msg = ssh_get_error(sshc->ssh_session); failf(conn->data, "%s", err_msg); MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED); } /* upload data */ Curl_setup_transfer(data, -1, data->req.size, FALSE, FIRSTSOCKET); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; /* store this original bitmask setup to use later on if we can't figure out a "real" bitmask */ sshc->orig_waitfor = data->req.keepon; /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh scp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; state(conn, SSH_STOP); break; case SSH_SCP_DOWNLOAD_INIT: rc = ssh_scp_init(sshc->scp_session); if(rc != SSH_OK) { err_msg = ssh_get_error(sshc->ssh_session); failf(conn->data, "%s", err_msg); MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT); } state(conn, SSH_SCP_DOWNLOAD); /* FALLTHROUGH */ case SSH_SCP_DOWNLOAD:{ curl_off_t bytecount; rc = ssh_scp_pull_request(sshc->scp_session); if(rc != SSH_SCP_REQUEST_NEWFILE) { err_msg = ssh_get_error(sshc->ssh_session); failf(conn->data, "%s", err_msg); MOVE_TO_ERROR_STATE(CURLE_REMOTE_FILE_NOT_FOUND); break; } /* download data */ bytecount = ssh_scp_request_get_size(sshc->scp_session); data->req.maxdownload = (curl_off_t) bytecount; Curl_setup_transfer(data, FIRSTSOCKET, bytecount, FALSE, -1); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; state(conn, SSH_STOP); break; } case SSH_SCP_DONE: if(data->set.upload) state(conn, SSH_SCP_SEND_EOF); else state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_SEND_EOF: if(sshc->scp_session) { rc = ssh_scp_close(sshc->scp_session); if(rc == SSH_AGAIN) { /* Currently the ssh_scp_close handles waiting for EOF in * blocking way. */ break; } if(rc != SSH_OK) { infof(data, "Failed to close libssh scp channel: %s\n", ssh_get_error(sshc->ssh_session)); } } state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_CHANNEL_FREE: if(sshc->scp_session) { ssh_scp_free(sshc->scp_session); sshc->scp_session = NULL; } DEBUGF(infof(data, "SCP DONE phase complete\n")); ssh_set_blocking(sshc->ssh_session, 0); state(conn, SSH_SESSION_DISCONNECT); /* FALLTHROUGH */ case SSH_SESSION_DISCONNECT: /* during weird times when we've been prematurely aborted, the channel is still alive when we reach this state and we MUST kill the channel properly first */ if(sshc->scp_session) { ssh_scp_free(sshc->scp_session); sshc->scp_session = NULL; } ssh_disconnect(sshc->ssh_session); SSH_STRING_FREE_CHAR(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_FREE); /* FALLTHROUGH */ case SSH_SESSION_FREE: if(sshc->ssh_session) { ssh_free(sshc->ssh_session); sshc->ssh_session = NULL; } /* worst-case scenario cleanup */ DEBUGASSERT(sshc->ssh_session == NULL); DEBUGASSERT(sshc->scp_session == NULL); if(sshc->readdir_tmp) { ssh_string_free_char(sshc->readdir_tmp); sshc->readdir_tmp = NULL; } if(sshc->quote_attrs) sftp_attributes_free(sshc->quote_attrs); if(sshc->readdir_attrs) sftp_attributes_free(sshc->readdir_attrs); if(sshc->readdir_link_attrs) sftp_attributes_free(sshc->readdir_link_attrs); if(sshc->privkey) ssh_key_free(sshc->privkey); if(sshc->pubkey) ssh_key_free(sshc->pubkey); Curl_safefree(sshc->rsa_pub); Curl_safefree(sshc->rsa); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); Curl_safefree(sshc->readdir_line); Curl_safefree(sshc->readdir_linkPath); SSH_STRING_FREE_CHAR(sshc->homedir); /* the code we are about to return */ result = sshc->actualcode; memset(sshc, 0, sizeof(struct ssh_conn)); connclose(conn, "SSH session free"); sshc->state = SSH_SESSION_FREE; /* current */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; case SSH_QUIT: /* fallthrough, just stop! */ default: /* internal error */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; } } while(!rc && (sshc->state != SSH_STOP)); if(rc == SSH_AGAIN) { /* we would block, we need to wait for the socket to be ready (in the right direction too)! */ *block = TRUE; } return result; } /* called by the multi interface to figure out what socket(s) to wait for and for what actions in the DO_DONE, PERFORM and WAITPERFORM states */ static int myssh_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { int bitmap = GETSOCK_BLANK; (void) numsocks; sock[0] = conn->sock[FIRSTSOCKET]; if(conn->waitfor & KEEP_RECV) bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); if(conn->waitfor & KEEP_SEND) bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); return bitmap; } /* Generic function called by the multi interface to figure out what socket(s) to wait for and for what actions during the DOING and PROTOCONNECT states*/ static int myssh_getsock(struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { /* if we know the direction we can use the generic *_getsock() function even for the protocol_connect and doing states */ return myssh_perform_getsock(conn, sock, numsocks); } static void myssh_block2waitfor(struct connectdata *conn, bool block) { struct ssh_conn *sshc = &conn->proto.sshc; /* If it didn't block, or nothing was returned by ssh_get_poll_flags * have the original set */ conn->waitfor = sshc->orig_waitfor; if(block) { int dir = ssh_get_poll_flags(sshc->ssh_session); if(dir & SSH_READ_PENDING) { /* translate the libssh define bits into our own bit defines */ conn->waitfor = KEEP_RECV; } else if(dir & SSH_WRITE_PENDING) { conn->waitfor = KEEP_SEND; } } } /* called repeatedly until done from multi.c */ static CURLcode myssh_multi_statemach(struct connectdata *conn, bool *done) { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; bool block; /* we store the status and use that to provide a ssh_getsock() implementation */ result = myssh_statemach_act(conn, &block); *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; myssh_block2waitfor(conn, block); return result; } static CURLcode myssh_block_statemach(struct connectdata *conn, bool disconnect) { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; while((sshc->state != SSH_STOP) && !result) { bool block; timediff_t left = 1000; struct curltime now = Curl_now(); result = myssh_statemach_act(conn, &block); if(result) break; if(!disconnect) { if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; result = Curl_speedcheck(data, now); if(result) break; left = Curl_timeleft(data, NULL, FALSE); if(left < 0) { failf(data, "Operation timed out"); return CURLE_OPERATION_TIMEDOUT; } } if(!result && block) { curl_socket_t fd_read = conn->sock[FIRSTSOCKET]; /* wait for the socket to become ready */ (void) Curl_socket_check(fd_read, CURL_SOCKET_BAD, CURL_SOCKET_BAD, left > 1000 ? 1000 : left); } } return result; } /* * SSH setup connection */ static CURLcode myssh_setup_connection(struct connectdata *conn) { struct SSHPROTO *ssh; conn->data->req.protop = ssh = calloc(1, sizeof(struct SSHPROTO)); if(!ssh) return CURLE_OUT_OF_MEMORY; return CURLE_OK; } static Curl_recv scp_recv, sftp_recv; static Curl_send scp_send, sftp_send; /* * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. */ static CURLcode myssh_connect(struct connectdata *conn, bool *done) { struct ssh_conn *ssh; CURLcode result; curl_socket_t sock = conn->sock[FIRSTSOCKET]; struct Curl_easy *data = conn->data; /* initialize per-handle data if not already */ if(!data->req.protop) myssh_setup_connection(conn); /* We default to persistent connections. We set this already in this connect function to make the re-use checks properly be able to check this bit. */ connkeep(conn, "SSH default"); if(conn->handler->protocol & CURLPROTO_SCP) { conn->recv[FIRSTSOCKET] = scp_recv; conn->send[FIRSTSOCKET] = scp_send; } else { conn->recv[FIRSTSOCKET] = sftp_recv; conn->send[FIRSTSOCKET] = sftp_send; } ssh = &conn->proto.sshc; ssh->ssh_session = ssh_new(); if(ssh->ssh_session == NULL) { failf(data, "Failure initialising ssh session"); return CURLE_FAILED_INIT; } ssh_options_set(ssh->ssh_session, SSH_OPTIONS_FD, &sock); if(conn->user) { infof(data, "User: %s\n", conn->user); ssh_options_set(ssh->ssh_session, SSH_OPTIONS_USER, conn->user); } if(data->set.str[STRING_SSH_KNOWNHOSTS]) { infof(data, "Known hosts: %s\n", data->set.str[STRING_SSH_KNOWNHOSTS]); ssh_options_set(ssh->ssh_session, SSH_OPTIONS_KNOWNHOSTS, data->set.str[STRING_SSH_KNOWNHOSTS]); } ssh_options_set(ssh->ssh_session, SSH_OPTIONS_HOST, conn->host.name); if(conn->remote_port) ssh_options_set(ssh->ssh_session, SSH_OPTIONS_PORT, &conn->remote_port); if(data->set.ssh_compression) { ssh_options_set(ssh->ssh_session, SSH_OPTIONS_COMPRESSION, "zlib,zlib@openssh.com,none"); } ssh->privkey = NULL; ssh->pubkey = NULL; if(data->set.str[STRING_SSH_PUBLIC_KEY]) { int rc = ssh_pki_import_pubkey_file(data->set.str[STRING_SSH_PUBLIC_KEY], &ssh->pubkey); if(rc != SSH_OK) { failf(data, "Could not load public key file"); /* ignore */ } } /* we do not verify here, we do it at the state machine, * after connection */ state(conn, SSH_INIT); result = myssh_multi_statemach(conn, done); return result; } /* called from multi.c while DOing */ static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = myssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* *********************************************************************** * * scp_perform() * * This is the actual DO function for SCP. Get a file according to * the options previously setup. */ static CURLcode scp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SCP_TRANS_INIT); result = myssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } static CURLcode myssh_do_it(struct connectdata *conn, bool *done) { CURLcode result; bool connected = 0; struct Curl_easy *data = conn->data; struct ssh_conn *sshc = &conn->proto.sshc; *done = FALSE; /* default to false */ data->req.size = -1; /* make sure this is unknown at this point */ sshc->actualcode = CURLE_OK; /* reset error code */ sshc->secondCreateDirs = 0; /* reset the create dir attempt state variable */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); if(conn->handler->protocol & CURLPROTO_SCP) result = scp_perform(conn, &connected, done); else result = sftp_perform(conn, &connected, done); return result; } /* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */ static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; struct ssh_conn *ssh = &conn->proto.sshc; (void) dead_connection; if(ssh->ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SESSION_DISCONNECT); result = myssh_block_statemach(conn, TRUE); } return result; } /* generic done function for both SCP and SFTP called from their specific done functions */ static CURLcode myssh_done(struct connectdata *conn, CURLcode status) { CURLcode result = CURLE_OK; struct SSHPROTO *protop = conn->data->req.protop; if(!status) { /* run the state-machine */ result = myssh_block_statemach(conn, FALSE); } else result = status; if(protop) Curl_safefree(protop->path); if(Curl_pgrsDone(conn)) return CURLE_ABORTED_BY_CALLBACK; conn->data->req.keepon = 0; /* clear all bits */ return result; } static CURLcode scp_done(struct connectdata *conn, CURLcode status, bool premature) { (void) premature; /* not used */ if(!status) state(conn, SSH_SCP_DONE); return myssh_done(conn, status); } static ssize_t scp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { int rc; (void) sockindex; /* we only support SCP on the fixed known primary socket */ (void) err; rc = ssh_scp_write(conn->proto.sshc.scp_session, mem, len); #if 0 /* The following code is misleading, mostly added as wishful thinking * that libssh at some point will implement non-blocking ssh_scp_write/read. * Currently rc can only be number of bytes read or SSH_ERROR. */ myssh_block2waitfor(conn, (rc == SSH_AGAIN) ? TRUE : FALSE); if(rc == SSH_AGAIN) { *err = CURLE_AGAIN; return 0; } else #endif if(rc != SSH_OK) { *err = CURLE_SSH; return -1; } return len; } static ssize_t scp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void) err; (void) sockindex; /* we only support SCP on the fixed known primary socket */ /* libssh returns int */ nread = ssh_scp_read(conn->proto.sshc.scp_session, mem, len); #if 0 /* The following code is misleading, mostly added as wishful thinking * that libssh at some point will implement non-blocking ssh_scp_write/read. * Currently rc can only be SSH_OK or SSH_ERROR. */ myssh_block2waitfor(conn, (nread == SSH_AGAIN) ? TRUE : FALSE); if(nread == SSH_AGAIN) { *err = CURLE_AGAIN; nread = -1; } #endif return nread; } /* * =============== SFTP =============== */ /* *********************************************************************** * * sftp_perform() * * This is the actual DO function for SFTP. Get a file/directory according to * the options previously setup. */ static CURLcode sftp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SFTP_QUOTE_INIT); /* run the state-machine */ result = myssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* called from multi.c while DOing */ static CURLcode sftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = myssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */ static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; (void) dead_connection; DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n")); if(conn->proto.sshc.ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SFTP_SHUTDOWN); result = myssh_block_statemach(conn, TRUE); } DEBUGF(infof(conn->data, "SSH DISCONNECT is done\n")); return result; } static CURLcode sftp_done(struct connectdata *conn, CURLcode status, bool premature) { struct ssh_conn *sshc = &conn->proto.sshc; if(!status) { /* Post quote commands are executed after the SFTP_CLOSE state to avoid errors that could happen due to open file handles during POSTQUOTE operation */ if(!premature && conn->data->set.postquote && !conn->bits.retry) sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; state(conn, SSH_SFTP_CLOSE); } return myssh_done(conn, status); } /* return number of sent bytes */ static ssize_t sftp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { ssize_t nwrite; (void)sockindex; nwrite = sftp_write(conn->proto.sshc.sftp_file, mem, len); myssh_block2waitfor(conn, FALSE); #if 0 /* not returned by libssh on write */ if(nwrite == SSH_AGAIN) { *err = CURLE_AGAIN; nwrite = 0; } else #endif if(nwrite < 0) { *err = CURLE_SSH; nwrite = -1; } return nwrite; } /* * Return number of received (decrypted) bytes * or <0 on error */ static ssize_t sftp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void)sockindex; DEBUGASSERT(len < CURL_MAX_READ_SIZE); switch(conn->proto.sshc.sftp_recv_state) { case 0: conn->proto.sshc.sftp_file_index = sftp_async_read_begin(conn->proto.sshc.sftp_file, (uint32_t)len); if(conn->proto.sshc.sftp_file_index < 0) { *err = CURLE_RECV_ERROR; return -1; } /* FALLTHROUGH */ case 1: conn->proto.sshc.sftp_recv_state = 1; nread = sftp_async_read(conn->proto.sshc.sftp_file, mem, (uint32_t)len, conn->proto.sshc.sftp_file_index); myssh_block2waitfor(conn, (nread == SSH_AGAIN)?TRUE:FALSE); if(nread == SSH_AGAIN) { *err = CURLE_AGAIN; return -1; } else if(nread < 0) { *err = CURLE_RECV_ERROR; return -1; } conn->proto.sshc.sftp_recv_state = 0; return nread; default: /* we never reach here */ return -1; } } static void sftp_quote(struct connectdata *conn) { const char *cp; struct Curl_easy *data = conn->data; struct SSHPROTO *protop = data->req.protop; struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result; /* * Support some of the "FTP" commands */ char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } if(strcasecompare("pwd", cmd)) { /* output debug output if that is requested */ char *tmp = aprintf("257 \"%s\" is current directory.\n", protop->path); if(!tmp) { sshc->actualcode = CURLE_OUT_OF_MEMORY; state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; return; } if(data->set.verbose) { Curl_debug(data, CURLINFO_HEADER_OUT, (char *) "PWD\n", 4); Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); } /* this sends an FTP-like "header" to the header callback so that the current directory can be read very similar to how it is read when using ordinary FTP. */ result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); free(tmp); if(result) { state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; } else state(conn, SSH_SFTP_NEXT_QUOTE); return; } /* * the arguments following the command must be separated from the * command with a space so we can check for it unconditionally */ cp = strchr(cmd, ' '); if(cp == NULL) { failf(data, "Syntax error in SFTP command. Supply parameter(s)!"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; return; } /* * also, every command takes at least one argument so we get that * first argument right now */ result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error: Bad first parameter"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; return; } /* * SFTP is a binary protocol, so we don't send text commands * to the server. Instead, we scan for commands used by * OpenSSH's sftp program and call the appropriate libssh * functions. */ if(strncasecompare(cmd, "chgrp ", 6) || strncasecompare(cmd, "chmod ", 6) || strncasecompare(cmd, "chown ", 6)) { /* attribute change */ /* sshc->quote_path1 contains the mode to set */ /* get the destination */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in chgrp/chmod/chown: " "Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; return; } sshc->quote_attrs = NULL; state(conn, SSH_SFTP_QUOTE_STAT); return; } if(strncasecompare(cmd, "ln ", 3) || strncasecompare(cmd, "symlink ", 8)) { /* symbolic linking */ /* sshc->quote_path1 is the source */ /* get the destination */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in ln/symlink: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; return; } state(conn, SSH_SFTP_QUOTE_SYMLINK); return; } else if(strncasecompare(cmd, "mkdir ", 6)) { /* create dir */ state(conn, SSH_SFTP_QUOTE_MKDIR); return; } else if(strncasecompare(cmd, "rename ", 7)) { /* rename file */ /* first param is the source path */ /* second param is the dest. path */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in rename: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; return; } state(conn, SSH_SFTP_QUOTE_RENAME); return; } else if(strncasecompare(cmd, "rmdir ", 6)) { /* delete dir */ state(conn, SSH_SFTP_QUOTE_RMDIR); return; } else if(strncasecompare(cmd, "rm ", 3)) { state(conn, SSH_SFTP_QUOTE_UNLINK); return; } #ifdef HAS_STATVFS_SUPPORT else if(strncasecompare(cmd, "statvfs ", 8)) { state(conn, SSH_SFTP_QUOTE_STATVFS); return; } #endif failf(data, "Unknown SFTP command"); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; } static void sftp_quote_stat(struct connectdata *conn) { struct Curl_easy *data = conn->data; struct ssh_conn *sshc = &conn->proto.sshc; char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } /* We read the file attributes, store them in sshc->quote_attrs * and modify them accordingly to command. Then we switch to * QUOTE_SETSTAT state to write new ones. */ if(sshc->quote_attrs) sftp_attributes_free(sshc->quote_attrs); sshc->quote_attrs = sftp_stat(sshc->sftp_session, sshc->quote_path2); if(sshc->quote_attrs == NULL) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to get SFTP stats failed: %d", sftp_get_error(sshc->sftp_session)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; return; } /* Now set the new attributes... */ if(strncasecompare(cmd, "chgrp", 5)) { sshc->quote_attrs->gid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10); if(sshc->quote_attrs->gid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chgrp gid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; return; } sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; } else if(strncasecompare(cmd, "chmod", 5)) { mode_t perms; perms = (mode_t)strtoul(sshc->quote_path1, NULL, 8); /* permissions are octal */ if(perms == 0 && !ISDIGIT(sshc->quote_path1[0])) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chmod permissions not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; return; } sshc->quote_attrs->permissions = perms; sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_PERMISSIONS; } else if(strncasecompare(cmd, "chown", 5)) { sshc->quote_attrs->uid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10); if(sshc->quote_attrs->uid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chown uid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; return; } sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID; } /* Now send the completed structure... */ state(conn, SSH_SFTP_QUOTE_SETSTAT); return; } #endif /* USE_LIBSSH */
YifuLiu/AliOS-Things
components/curl/lib/ssh-libssh.c
C
apache-2.0
81,473
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* #define CURL_LIBSSH2_DEBUG */ #include "curl_setup.h" #ifdef USE_LIBSSH2 #include <limits.h> #include <libssh2.h> #include <libssh2_sftp.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "ssh.h" #include "url.h" #include "speedcheck.h" #include "getinfo.h" #include "strdup.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "strerror.h" #include "inet_ntop.h" #include "parsedate.h" /* for the week day and month names */ #include "sockaddr.h" /* required for Curl_sockaddr_storage */ #include "strtoofft.h" #include "multiif.h" #include "select.h" #include "warnless.h" #include "curl_path.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if LIBSSH2_VERSION_NUM >= 0x010206 /* libssh2_sftp_statvfs and friends were added in 1.2.6 */ #define HAS_STATVFS_SUPPORT 1 #endif #define sftp_libssh2_last_error(s) curlx_ultosi(libssh2_sftp_last_error(s)) #define sftp_libssh2_realpath(s,p,t,m) \ libssh2_sftp_symlink_ex((s), (p), curlx_uztoui(strlen(p)), \ (t), (m), LIBSSH2_SFTP_REALPATH) /* Local functions: */ static const char *sftp_libssh2_strerror(int err); static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc); static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc); static LIBSSH2_FREE_FUNC(my_libssh2_free); static CURLcode ssh_connect(struct connectdata *conn, bool *done); static CURLcode ssh_multi_statemach(struct connectdata *conn, bool *done); static CURLcode ssh_do(struct connectdata *conn, bool *done); static CURLcode scp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection); static CURLcode sftp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode sftp_doing(struct connectdata *conn, bool *dophase_done); static CURLcode sftp_disconnect(struct connectdata *conn, bool dead); static CURLcode sftp_perform(struct connectdata *conn, bool *connected, bool *dophase_done); static int ssh_getsock(struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks); static int ssh_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks); static CURLcode ssh_setup_connection(struct connectdata *conn); /* * SCP protocol handler. */ const struct Curl_handler Curl_handler_scp = { "SCP", /* scheme */ ssh_setup_connection, /* setup_connection */ ssh_do, /* do_it */ scp_done, /* done */ ZERO_NULL, /* do_more */ ssh_connect, /* connect_it */ ssh_multi_statemach, /* connecting */ scp_doing, /* doing */ ssh_getsock, /* proto_getsock */ ssh_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ssh_perform_getsock, /* perform_getsock */ scp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SSH, /* defport */ CURLPROTO_SCP, /* protocol */ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */ }; /* * SFTP protocol handler. */ const struct Curl_handler Curl_handler_sftp = { "SFTP", /* scheme */ ssh_setup_connection, /* setup_connection */ ssh_do, /* do_it */ sftp_done, /* done */ ZERO_NULL, /* do_more */ ssh_connect, /* connect_it */ ssh_multi_statemach, /* connecting */ sftp_doing, /* doing */ ssh_getsock, /* proto_getsock */ ssh_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ssh_perform_getsock, /* perform_getsock */ sftp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SSH, /* defport */ CURLPROTO_SFTP, /* protocol */ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */ }; static void kbd_callback(const char *name, int name_len, const char *instruction, int instruction_len, int num_prompts, const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts, LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses, void **abstract) { struct connectdata *conn = (struct connectdata *)*abstract; #ifdef CURL_LIBSSH2_DEBUG fprintf(stderr, "name=%s\n", name); fprintf(stderr, "name_len=%d\n", name_len); fprintf(stderr, "instruction=%s\n", instruction); fprintf(stderr, "instruction_len=%d\n", instruction_len); fprintf(stderr, "num_prompts=%d\n", num_prompts); #else (void)name; (void)name_len; (void)instruction; (void)instruction_len; #endif /* CURL_LIBSSH2_DEBUG */ if(num_prompts == 1) { responses[0].text = strdup(conn->passwd); responses[0].length = curlx_uztoui(strlen(conn->passwd)); } (void)prompts; (void)abstract; } /* kbd_callback */ static CURLcode sftp_libssh2_error_to_CURLE(int err) { switch(err) { case LIBSSH2_FX_OK: return CURLE_OK; case LIBSSH2_FX_NO_SUCH_FILE: case LIBSSH2_FX_NO_SUCH_PATH: return CURLE_REMOTE_FILE_NOT_FOUND; case LIBSSH2_FX_PERMISSION_DENIED: case LIBSSH2_FX_WRITE_PROTECT: case LIBSSH2_FX_LOCK_CONFlICT: return CURLE_REMOTE_ACCESS_DENIED; case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: case LIBSSH2_FX_QUOTA_EXCEEDED: return CURLE_REMOTE_DISK_FULL; case LIBSSH2_FX_FILE_ALREADY_EXISTS: return CURLE_REMOTE_FILE_EXISTS; case LIBSSH2_FX_DIR_NOT_EMPTY: return CURLE_QUOTE_ERROR; default: break; } return CURLE_SSH; } static CURLcode libssh2_session_error_to_CURLE(int err) { switch(err) { /* Ordered by order of appearance in libssh2.h */ case LIBSSH2_ERROR_NONE: return CURLE_OK; /* This is the error returned by libssh2_scp_recv2 * on unknown file */ case LIBSSH2_ERROR_SCP_PROTOCOL: return CURLE_REMOTE_FILE_NOT_FOUND; case LIBSSH2_ERROR_SOCKET_NONE: return CURLE_COULDNT_CONNECT; case LIBSSH2_ERROR_ALLOC: return CURLE_OUT_OF_MEMORY; case LIBSSH2_ERROR_SOCKET_SEND: return CURLE_SEND_ERROR; case LIBSSH2_ERROR_HOSTKEY_INIT: case LIBSSH2_ERROR_HOSTKEY_SIGN: case LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED: case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED: return CURLE_PEER_FAILED_VERIFICATION; case LIBSSH2_ERROR_PASSWORD_EXPIRED: return CURLE_LOGIN_DENIED; case LIBSSH2_ERROR_SOCKET_TIMEOUT: case LIBSSH2_ERROR_TIMEOUT: return CURLE_OPERATION_TIMEDOUT; case LIBSSH2_ERROR_EAGAIN: return CURLE_AGAIN; } return CURLE_SSH; } static LIBSSH2_ALLOC_FUNC(my_libssh2_malloc) { (void)abstract; /* arg not used */ return malloc(count); } static LIBSSH2_REALLOC_FUNC(my_libssh2_realloc) { (void)abstract; /* arg not used */ return realloc(ptr, count); } static LIBSSH2_FREE_FUNC(my_libssh2_free) { (void)abstract; /* arg not used */ if(ptr) /* ssh2 agent sometimes call free with null ptr */ free(ptr); } /* * SSH State machine related code */ /* This is the ONLY way to change SSH state! */ static void state(struct connectdata *conn, sshstate nowstate) { struct ssh_conn *sshc = &conn->proto.sshc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[] = { "SSH_STOP", "SSH_INIT", "SSH_S_STARTUP", "SSH_HOSTKEY", "SSH_AUTHLIST", "SSH_AUTH_PKEY_INIT", "SSH_AUTH_PKEY", "SSH_AUTH_PASS_INIT", "SSH_AUTH_PASS", "SSH_AUTH_AGENT_INIT", "SSH_AUTH_AGENT_LIST", "SSH_AUTH_AGENT", "SSH_AUTH_HOST_INIT", "SSH_AUTH_HOST", "SSH_AUTH_KEY_INIT", "SSH_AUTH_KEY", "SSH_AUTH_GSSAPI", "SSH_AUTH_DONE", "SSH_SFTP_INIT", "SSH_SFTP_REALPATH", "SSH_SFTP_QUOTE_INIT", "SSH_SFTP_POSTQUOTE_INIT", "SSH_SFTP_QUOTE", "SSH_SFTP_NEXT_QUOTE", "SSH_SFTP_QUOTE_STAT", "SSH_SFTP_QUOTE_SETSTAT", "SSH_SFTP_QUOTE_SYMLINK", "SSH_SFTP_QUOTE_MKDIR", "SSH_SFTP_QUOTE_RENAME", "SSH_SFTP_QUOTE_RMDIR", "SSH_SFTP_QUOTE_UNLINK", "SSH_SFTP_QUOTE_STATVFS", "SSH_SFTP_GETINFO", "SSH_SFTP_FILETIME", "SSH_SFTP_TRANS_INIT", "SSH_SFTP_UPLOAD_INIT", "SSH_SFTP_CREATE_DIRS_INIT", "SSH_SFTP_CREATE_DIRS", "SSH_SFTP_CREATE_DIRS_MKDIR", "SSH_SFTP_READDIR_INIT", "SSH_SFTP_READDIR", "SSH_SFTP_READDIR_LINK", "SSH_SFTP_READDIR_BOTTOM", "SSH_SFTP_READDIR_DONE", "SSH_SFTP_DOWNLOAD_INIT", "SSH_SFTP_DOWNLOAD_STAT", "SSH_SFTP_CLOSE", "SSH_SFTP_SHUTDOWN", "SSH_SCP_TRANS_INIT", "SSH_SCP_UPLOAD_INIT", "SSH_SCP_DOWNLOAD_INIT", "SSH_SCP_DOWNLOAD", "SSH_SCP_DONE", "SSH_SCP_SEND_EOF", "SSH_SCP_WAIT_EOF", "SSH_SCP_WAIT_CLOSE", "SSH_SCP_CHANNEL_FREE", "SSH_SESSION_DISCONNECT", "SSH_SESSION_FREE", "QUIT" }; /* a precaution to make sure the lists are in sync */ DEBUGASSERT(sizeof(names)/sizeof(names[0]) == SSH_LAST); if(sshc->state != nowstate) { infof(conn->data, "SFTP %p state change from %s to %s\n", (void *)sshc, names[sshc->state], names[nowstate]); } #endif sshc->state = nowstate; } #ifdef HAVE_LIBSSH2_KNOWNHOST_API static int sshkeycallback(struct Curl_easy *easy, const struct curl_khkey *knownkey, /* known */ const struct curl_khkey *foundkey, /* found */ enum curl_khmatch match, void *clientp) { (void)easy; (void)knownkey; (void)foundkey; (void)clientp; /* we only allow perfect matches, and we reject everything else */ return (match != CURLKHMATCH_OK)?CURLKHSTAT_REJECT:CURLKHSTAT_FINE; } #endif /* * Earlier libssh2 versions didn't have the ability to seek to 64bit positions * with 32bit size_t. */ #ifdef HAVE_LIBSSH2_SFTP_SEEK64 #define SFTP_SEEK(x,y) libssh2_sftp_seek64(x, (libssh2_uint64_t)y) #else #define SFTP_SEEK(x,y) libssh2_sftp_seek(x, (size_t)y) #endif /* * Earlier libssh2 versions didn't do SCP properly beyond 32bit sizes on 32bit * architectures so we check of the necessary function is present. */ #ifndef HAVE_LIBSSH2_SCP_SEND64 #define SCP_SEND(a,b,c,d) libssh2_scp_send_ex(a, b, (int)(c), (size_t)d, 0, 0) #else #define SCP_SEND(a,b,c,d) libssh2_scp_send64(a, b, (int)(c), \ (libssh2_uint64_t)d, 0, 0) #endif /* * libssh2 1.2.8 fixed the problem with 32bit ints used for sockets on win64. */ #ifdef HAVE_LIBSSH2_SESSION_HANDSHAKE #define libssh2_session_startup(x,y) libssh2_session_handshake(x,y) #endif static CURLcode ssh_knownhost(struct connectdata *conn) { CURLcode result = CURLE_OK; #ifdef HAVE_LIBSSH2_KNOWNHOST_API struct Curl_easy *data = conn->data; if(data->set.str[STRING_SSH_KNOWNHOSTS]) { /* we're asked to verify the host against a file */ struct ssh_conn *sshc = &conn->proto.sshc; int rc; int keytype; size_t keylen; const char *remotekey = libssh2_session_hostkey(sshc->ssh_session, &keylen, &keytype); int keycheck = LIBSSH2_KNOWNHOST_CHECK_FAILURE; int keybit = 0; if(remotekey) { /* * A subject to figure out is what host name we need to pass in here. * What host name does OpenSSH store in its file if an IDN name is * used? */ struct libssh2_knownhost *host; enum curl_khmatch keymatch; curl_sshkeycallback func = data->set.ssh_keyfunc?data->set.ssh_keyfunc:sshkeycallback; struct curl_khkey knownkey; struct curl_khkey *knownkeyp = NULL; struct curl_khkey foundkey; keybit = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)? LIBSSH2_KNOWNHOST_KEY_SSHRSA:LIBSSH2_KNOWNHOST_KEY_SSHDSS; #ifdef HAVE_LIBSSH2_KNOWNHOST_CHECKP keycheck = libssh2_knownhost_checkp(sshc->kh, conn->host.name, (conn->remote_port != PORT_SSH)? conn->remote_port:-1, remotekey, keylen, LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_KEYENC_RAW| keybit, &host); #else keycheck = libssh2_knownhost_check(sshc->kh, conn->host.name, remotekey, keylen, LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_KEYENC_RAW| keybit, &host); #endif infof(data, "SSH host check: %d, key: %s\n", keycheck, (keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)? host->key:"<none>"); /* setup 'knownkey' */ if(keycheck <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH) { knownkey.key = host->key; knownkey.len = 0; knownkey.keytype = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)? CURLKHTYPE_RSA : CURLKHTYPE_DSS; knownkeyp = &knownkey; } /* setup 'foundkey' */ foundkey.key = remotekey; foundkey.len = keylen; foundkey.keytype = (keytype == LIBSSH2_HOSTKEY_TYPE_RSA)? CURLKHTYPE_RSA : CURLKHTYPE_DSS; /* * if any of the LIBSSH2_KNOWNHOST_CHECK_* defines and the * curl_khmatch enum are ever modified, we need to introduce a * translation table here! */ keymatch = (enum curl_khmatch)keycheck; /* Ask the callback how to behave */ Curl_set_in_callback(data, true); rc = func(data, knownkeyp, /* from the knownhosts file */ &foundkey, /* from the remote host */ keymatch, data->set.ssh_keyfunc_userp); Curl_set_in_callback(data, false); } else /* no remotekey means failure! */ rc = CURLKHSTAT_REJECT; switch(rc) { default: /* unknown return codes will equal reject */ /* FALLTHROUGH */ case CURLKHSTAT_REJECT: state(conn, SSH_SESSION_FREE); /* FALLTHROUGH */ case CURLKHSTAT_DEFER: /* DEFER means bail out but keep the SSH_HOSTKEY state */ result = sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; break; case CURLKHSTAT_FINE: case CURLKHSTAT_FINE_ADD_TO_FILE: /* proceed */ if(keycheck != LIBSSH2_KNOWNHOST_CHECK_MATCH) { /* the found host+key didn't match but has been told to be fine anyway so we add it in memory */ int addrc = libssh2_knownhost_add(sshc->kh, conn->host.name, NULL, remotekey, keylen, LIBSSH2_KNOWNHOST_TYPE_PLAIN| LIBSSH2_KNOWNHOST_KEYENC_RAW| keybit, NULL); if(addrc) infof(data, "Warning adding the known host %s failed!\n", conn->host.name); else if(rc == CURLKHSTAT_FINE_ADD_TO_FILE) { /* now we write the entire in-memory list of known hosts to the known_hosts file */ int wrc = libssh2_knownhost_writefile(sshc->kh, data->set.str[STRING_SSH_KNOWNHOSTS], LIBSSH2_KNOWNHOST_FILE_OPENSSH); if(wrc) { infof(data, "Warning, writing %s failed!\n", data->set.str[STRING_SSH_KNOWNHOSTS]); } } } break; } } #else /* HAVE_LIBSSH2_KNOWNHOST_API */ (void)conn; #endif return result; } static CURLcode ssh_check_fingerprint(struct connectdata *conn) { struct ssh_conn *sshc = &conn->proto.sshc; struct Curl_easy *data = conn->data; const char *pubkey_md5 = data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]; char md5buffer[33]; const char *fingerprint = libssh2_hostkey_hash(sshc->ssh_session, LIBSSH2_HOSTKEY_HASH_MD5); if(fingerprint) { /* The fingerprint points to static storage (!), don't free() it. */ int i; for(i = 0; i < 16; i++) msnprintf(&md5buffer[i*2], 3, "%02x", (unsigned char) fingerprint[i]); infof(data, "SSH MD5 fingerprint: %s\n", md5buffer); } /* Before we authenticate we check the hostkey's MD5 fingerprint * against a known fingerprint, if available. */ if(pubkey_md5 && strlen(pubkey_md5) == 32) { if(!fingerprint || !strcasecompare(md5buffer, pubkey_md5)) { if(fingerprint) failf(data, "Denied establishing ssh session: mismatch md5 fingerprint. " "Remote %s is not equal to %s", md5buffer, pubkey_md5); else failf(data, "Denied establishing ssh session: md5 fingerprint not available"); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_PEER_FAILED_VERIFICATION; return sshc->actualcode; } infof(data, "MD5 checksum match!\n"); /* as we already matched, we skip the check for known hosts */ return CURLE_OK; } return ssh_knownhost(conn); } /* * ssh_statemach_act() runs the SSH state machine as far as it can without * blocking and without reaching the end. The data the pointer 'block' points * to will be set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN * meaning it wants to be called again when the socket is ready */ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SSHPROTO *sftp_scp = data->req.protop; struct ssh_conn *sshc = &conn->proto.sshc; curl_socket_t sock = conn->sock[FIRSTSOCKET]; char *new_readdir_line; int rc = LIBSSH2_ERROR_NONE; int err; int seekerr = CURL_SEEKFUNC_OK; *block = 0; /* we're not blocking by default */ do { switch(sshc->state) { case SSH_INIT: sshc->secondCreateDirs = 0; sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_OK; /* Set libssh2 to non-blocking, since everything internally is non-blocking */ libssh2_session_set_blocking(sshc->ssh_session, 0); state(conn, SSH_S_STARTUP); /* FALLTHROUGH */ case SSH_S_STARTUP: rc = libssh2_session_startup(sshc->ssh_session, (int)sock); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); failf(data, "Failure establishing ssh session: %d, %s", rc, err_msg); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_FAILED_INIT; break; } state(conn, SSH_HOSTKEY); /* FALLTHROUGH */ case SSH_HOSTKEY: /* * Before we authenticate we should check the hostkey's fingerprint * against our known hosts. How that is handled (reading from file, * whatever) is up to us. */ result = ssh_check_fingerprint(conn); if(!result) state(conn, SSH_AUTHLIST); /* ssh_check_fingerprint sets state appropriately on error */ break; case SSH_AUTHLIST: /* * Figure out authentication methods * NB: As soon as we have provided a username to an openssh server we * must never change it later. Thus, always specify the correct username * here, even though the libssh2 docs kind of indicate that it should be * possible to get a 'generic' list (not user-specific) of authentication * methods, presumably with a blank username. That won't work in my * experience. * So always specify it here. */ sshc->authlist = libssh2_userauth_list(sshc->ssh_session, conn->user, curlx_uztoui(strlen(conn->user))); if(!sshc->authlist) { if(libssh2_userauth_authenticated(sshc->ssh_session)) { sshc->authed = TRUE; infof(data, "SSH user accepted with no authentication\n"); state(conn, SSH_AUTH_DONE); break; } err = libssh2_session_last_errno(sshc->ssh_session); if(err == LIBSSH2_ERROR_EAGAIN) rc = LIBSSH2_ERROR_EAGAIN; else { state(conn, SSH_SESSION_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(err); } break; } infof(data, "SSH authentication methods available: %s\n", sshc->authlist); state(conn, SSH_AUTH_PKEY_INIT); break; case SSH_AUTH_PKEY_INIT: /* * Check the supported auth types in the order I feel is most secure * with the requested type of authentication */ sshc->authed = FALSE; if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && (strstr(sshc->authlist, "publickey") != NULL)) { bool out_of_memory = FALSE; sshc->rsa_pub = sshc->rsa = NULL; if(data->set.str[STRING_SSH_PRIVATE_KEY]) sshc->rsa = strdup(data->set.str[STRING_SSH_PRIVATE_KEY]); else { /* To ponder about: should really the lib be messing about with the HOME environment variable etc? */ char *home = curl_getenv("HOME"); /* If no private key file is specified, try some common paths. */ if(home) { /* Try ~/.ssh first. */ sshc->rsa = aprintf("%s/.ssh/id_rsa", home); if(!sshc->rsa) out_of_memory = TRUE; else if(access(sshc->rsa, R_OK) != 0) { Curl_safefree(sshc->rsa); sshc->rsa = aprintf("%s/.ssh/id_dsa", home); if(!sshc->rsa) out_of_memory = TRUE; else if(access(sshc->rsa, R_OK) != 0) { Curl_safefree(sshc->rsa); } } free(home); } if(!out_of_memory && !sshc->rsa) { /* Nothing found; try the current dir. */ sshc->rsa = strdup("id_rsa"); if(sshc->rsa && access(sshc->rsa, R_OK) != 0) { Curl_safefree(sshc->rsa); sshc->rsa = strdup("id_dsa"); if(sshc->rsa && access(sshc->rsa, R_OK) != 0) { Curl_safefree(sshc->rsa); /* Out of guesses. Set to the empty string to avoid * surprising info messages. */ sshc->rsa = strdup(""); } } } } /* * Unless the user explicitly specifies a public key file, let * libssh2 extract the public key from the private key file. * This is done by simply passing sshc->rsa_pub = NULL. */ if(data->set.str[STRING_SSH_PUBLIC_KEY] /* treat empty string the same way as NULL */ && data->set.str[STRING_SSH_PUBLIC_KEY][0]) { sshc->rsa_pub = strdup(data->set.str[STRING_SSH_PUBLIC_KEY]); if(!sshc->rsa_pub) out_of_memory = TRUE; } if(out_of_memory || sshc->rsa == NULL) { Curl_safefree(sshc->rsa); Curl_safefree(sshc->rsa_pub); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->passphrase = data->set.ssl.key_passwd; if(!sshc->passphrase) sshc->passphrase = ""; if(sshc->rsa_pub) infof(data, "Using SSH public key file '%s'\n", sshc->rsa_pub); infof(data, "Using SSH private key file '%s'\n", sshc->rsa); state(conn, SSH_AUTH_PKEY); } else { state(conn, SSH_AUTH_PASS_INIT); } break; case SSH_AUTH_PKEY: /* The function below checks if the files exists, no need to stat() here. */ rc = libssh2_userauth_publickey_fromfile_ex(sshc->ssh_session, conn->user, curlx_uztoui( strlen(conn->user)), sshc->rsa_pub, sshc->rsa, sshc->passphrase); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } Curl_safefree(sshc->rsa_pub); Curl_safefree(sshc->rsa); if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized SSH public key authentication\n"); state(conn, SSH_AUTH_DONE); } else { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "SSH public key authentication failed: %s\n", err_msg); state(conn, SSH_AUTH_PASS_INIT); rc = 0; /* clear rc and continue */ } break; case SSH_AUTH_PASS_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && (strstr(sshc->authlist, "password") != NULL)) { state(conn, SSH_AUTH_PASS); } else { state(conn, SSH_AUTH_HOST_INIT); rc = 0; /* clear rc and continue */ } break; case SSH_AUTH_PASS: rc = libssh2_userauth_password_ex(sshc->ssh_session, conn->user, curlx_uztoui(strlen(conn->user)), conn->passwd, curlx_uztoui(strlen(conn->passwd)), NULL); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized password authentication\n"); state(conn, SSH_AUTH_DONE); } else { state(conn, SSH_AUTH_HOST_INIT); rc = 0; /* clear rc and continue */ } break; case SSH_AUTH_HOST_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && (strstr(sshc->authlist, "hostbased") != NULL)) { state(conn, SSH_AUTH_HOST); } else { state(conn, SSH_AUTH_AGENT_INIT); } break; case SSH_AUTH_HOST: state(conn, SSH_AUTH_AGENT_INIT); break; case SSH_AUTH_AGENT_INIT: #ifdef HAVE_LIBSSH2_AGENT_API if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT) && (strstr(sshc->authlist, "publickey") != NULL)) { /* Connect to the ssh-agent */ /* The agent could be shared by a curl thread i believe but nothing obvious as keys can be added/removed at any time */ if(!sshc->ssh_agent) { sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session); if(!sshc->ssh_agent) { infof(data, "Could not create agent object\n"); state(conn, SSH_AUTH_KEY_INIT); break; } } rc = libssh2_agent_connect(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc < 0) { infof(data, "Failure connecting to agent\n"); state(conn, SSH_AUTH_KEY_INIT); rc = 0; /* clear rc and continue */ } else { state(conn, SSH_AUTH_AGENT_LIST); } } else #endif /* HAVE_LIBSSH2_AGENT_API */ state(conn, SSH_AUTH_KEY_INIT); break; case SSH_AUTH_AGENT_LIST: #ifdef HAVE_LIBSSH2_AGENT_API rc = libssh2_agent_list_identities(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc < 0) { infof(data, "Failure requesting identities to agent\n"); state(conn, SSH_AUTH_KEY_INIT); rc = 0; /* clear rc and continue */ } else { state(conn, SSH_AUTH_AGENT); sshc->sshagent_prev_identity = NULL; } #endif break; case SSH_AUTH_AGENT: #ifdef HAVE_LIBSSH2_AGENT_API /* as prev_identity evolves only after an identity user auth finished we can safely request it again as long as EAGAIN is returned here or by libssh2_agent_userauth */ rc = libssh2_agent_get_identity(sshc->ssh_agent, &sshc->sshagent_identity, sshc->sshagent_prev_identity); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc == 0) { rc = libssh2_agent_userauth(sshc->ssh_agent, conn->user, sshc->sshagent_identity); if(rc < 0) { if(rc != LIBSSH2_ERROR_EAGAIN) { /* tried and failed? go to next identity */ sshc->sshagent_prev_identity = sshc->sshagent_identity; } break; } } if(rc < 0) infof(data, "Failure requesting identities to agent\n"); else if(rc == 1) infof(data, "No identity would match\n"); if(rc == LIBSSH2_ERROR_NONE) { sshc->authed = TRUE; infof(data, "Agent based authentication successful\n"); state(conn, SSH_AUTH_DONE); } else { state(conn, SSH_AUTH_KEY_INIT); rc = 0; /* clear rc and continue */ } #endif break; case SSH_AUTH_KEY_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) && (strstr(sshc->authlist, "keyboard-interactive") != NULL)) { state(conn, SSH_AUTH_KEY); } else { state(conn, SSH_AUTH_DONE); } break; case SSH_AUTH_KEY: /* Authentication failed. Continue with keyboard-interactive now. */ rc = libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session, conn->user, curlx_uztoui( strlen(conn->user)), &kbd_callback); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized keyboard interactive authentication\n"); } state(conn, SSH_AUTH_DONE); break; case SSH_AUTH_DONE: if(!sshc->authed) { failf(data, "Authentication failure"); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_LOGIN_DENIED; break; } /* * At this point we have an authenticated ssh session. */ infof(data, "Authentication complete\n"); Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSH is connected */ conn->sockfd = sock; conn->writesockfd = CURL_SOCKET_BAD; if(conn->handler->protocol == CURLPROTO_SFTP) { state(conn, SSH_SFTP_INIT); break; } infof(data, "SSH CONNECT phase done\n"); state(conn, SSH_STOP); break; case SSH_SFTP_INIT: /* * Start the libssh2 sftp session */ sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session); if(!sshc->sftp_session) { char *err_msg = NULL; if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); failf(data, "Failure initializing sftp session: %s", err_msg); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_FAILED_INIT; break; } state(conn, SSH_SFTP_REALPATH); break; case SSH_SFTP_REALPATH: { char tempHome[PATH_MAX]; /* * Get the "home" directory */ rc = sftp_libssh2_realpath(sshc->sftp_session, ".", tempHome, PATH_MAX-1); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc > 0) { /* It seems that this string is not always NULL terminated */ tempHome[rc] = '\0'; sshc->homedir = strdup(tempHome); if(!sshc->homedir) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } conn->data->state.most_recent_ftp_entrypath = sshc->homedir; } else { /* Return the error type */ err = sftp_libssh2_last_error(sshc->sftp_session); if(err) result = sftp_libssh2_error_to_CURLE(err); else /* in this case, the error wasn't in the SFTP level but for example a time-out or similar */ result = CURLE_SSH; sshc->actualcode = result; DEBUGF(infof(data, "error = %d makes libcurl = %d\n", err, (int)result)); state(conn, SSH_STOP); break; } } /* This is the last step in the SFTP connect phase. Do note that while we get the homedir here, we get the "workingpath" in the DO action since the homedir will remain the same between request but the working path will not. */ DEBUGF(infof(data, "SSH CONNECT phase done\n")); state(conn, SSH_STOP); break; case SSH_SFTP_QUOTE_INIT: result = Curl_getworkingpath(conn, sshc->homedir, &sftp_scp->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } if(data->set.quote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.quote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_SFTP_GETINFO); } break; case SSH_SFTP_POSTQUOTE_INIT: if(data->set.postquote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.postquote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_STOP); } break; case SSH_SFTP_QUOTE: /* Send any quote commands */ { const char *cp; /* * Support some of the "FTP" commands * * 'sshc->quote_item' is already verified to be non-NULL before it * switched to this state. */ char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } if(strcasecompare("pwd", cmd)) { /* output debug output if that is requested */ char *tmp = aprintf("257 \"%s\" is current directory.\n", sftp_scp->path); if(!tmp) { result = CURLE_OUT_OF_MEMORY; state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; break; } if(data->set.verbose) { Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"PWD\n", 4); Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp)); } /* this sends an FTP-like "header" to the header callback so that the current directory can be read very similar to how it is read when using ordinary FTP. */ result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); free(tmp); if(result) { state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; } else state(conn, SSH_SFTP_NEXT_QUOTE); break; } { /* * the arguments following the command must be separated from the * command with a space so we can check for it unconditionally */ cp = strchr(cmd, ' '); if(cp == NULL) { failf(data, "Syntax error in SFTP command. Supply parameter(s)!"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } /* * also, every command takes at least one argument so we get that * first argument right now */ result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error: Bad first parameter"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } /* * SFTP is a binary protocol, so we don't send text commands * to the server. Instead, we scan for commands used by * OpenSSH's sftp program and call the appropriate libssh2 * functions. */ if(strncasecompare(cmd, "chgrp ", 6) || strncasecompare(cmd, "chmod ", 6) || strncasecompare(cmd, "chown ", 6) ) { /* attribute change */ /* sshc->quote_path1 contains the mode to set */ /* get the destination */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in chgrp/chmod/chown: " "Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } memset(&sshc->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES)); state(conn, SSH_SFTP_QUOTE_STAT); break; } if(strncasecompare(cmd, "ln ", 3) || strncasecompare(cmd, "symlink ", 8)) { /* symbolic linking */ /* sshc->quote_path1 is the source */ /* get the destination */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in ln/symlink: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } state(conn, SSH_SFTP_QUOTE_SYMLINK); break; } else if(strncasecompare(cmd, "mkdir ", 6)) { /* create dir */ state(conn, SSH_SFTP_QUOTE_MKDIR); break; } else if(strncasecompare(cmd, "rename ", 7)) { /* rename file */ /* first param is the source path */ /* second param is the dest. path */ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in rename: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } state(conn, SSH_SFTP_QUOTE_RENAME); break; } else if(strncasecompare(cmd, "rmdir ", 6)) { /* delete dir */ state(conn, SSH_SFTP_QUOTE_RMDIR); break; } else if(strncasecompare(cmd, "rm ", 3)) { state(conn, SSH_SFTP_QUOTE_UNLINK); break; } #ifdef HAS_STATVFS_SUPPORT else if(strncasecompare(cmd, "statvfs ", 8)) { state(conn, SSH_SFTP_QUOTE_STATVFS); break; } #endif failf(data, "Unknown SFTP command"); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } break; case SSH_SFTP_NEXT_QUOTE: Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); sshc->quote_item = sshc->quote_item->next; if(sshc->quote_item) { state(conn, SSH_SFTP_QUOTE); } else { if(sshc->nextstate != SSH_NO_STATE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_NO_STATE; } else { state(conn, SSH_SFTP_GETINFO); } } break; case SSH_SFTP_QUOTE_STAT: { char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } if(!strncasecompare(cmd, "chmod", 5)) { /* Since chown and chgrp only set owner OR group but libssh2 wants to * set them both at once, we need to obtain the current ownership * first. This takes an extra protocol round trip. */ rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_STAT, &sshc->quote_attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { /* get those attributes */ err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to get SFTP stats failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } /* Now set the new attributes... */ if(strncasecompare(cmd, "chgrp", 5)) { sshc->quote_attrs.gid = strtoul(sshc->quote_path1, NULL, 10); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; if(sshc->quote_attrs.gid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chgrp gid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } else if(strncasecompare(cmd, "chmod", 5)) { sshc->quote_attrs.permissions = strtoul(sshc->quote_path1, NULL, 8); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS; /* permissions are octal */ if(sshc->quote_attrs.permissions == 0 && !ISDIGIT(sshc->quote_path1[0])) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chmod permissions not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } else if(strncasecompare(cmd, "chown", 5)) { sshc->quote_attrs.uid = strtoul(sshc->quote_path1, NULL, 10); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; if(sshc->quote_attrs.uid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chown uid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } /* Now send the completed structure... */ state(conn, SSH_SFTP_QUOTE_SETSTAT); break; } case SSH_SFTP_QUOTE_SETSTAT: rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_SETSTAT, &sshc->quote_attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to set SFTP stats failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_SYMLINK: rc = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_SYMLINK); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "symlink command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_MKDIR: rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), data->set.new_directory_perms); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "mkdir command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RENAME: rc = libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_RENAME_OVERWRITE | LIBSSH2_SFTP_RENAME_ATOMIC | LIBSSH2_SFTP_RENAME_NATIVE); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "rename command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RMDIR: rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1))); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "rmdir command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_UNLINK: rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1))); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "rm command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; #ifdef HAS_STATVFS_SUPPORT case SSH_SFTP_QUOTE_STATVFS: { LIBSSH2_SFTP_STATVFS statvfs; rc = libssh2_sftp_statvfs(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), &statvfs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "statvfs command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } else if(rc == 0) { char *tmp = aprintf("statvfs:\n" "f_bsize: %llu\n" "f_frsize: %llu\n" "f_blocks: %llu\n" "f_bfree: %llu\n" "f_bavail: %llu\n" "f_files: %llu\n" "f_ffree: %llu\n" "f_favail: %llu\n" "f_fsid: %llu\n" "f_flag: %llu\n" "f_namemax: %llu\n", statvfs.f_bsize, statvfs.f_frsize, statvfs.f_blocks, statvfs.f_bfree, statvfs.f_bavail, statvfs.f_files, statvfs.f_ffree, statvfs.f_favail, statvfs.f_fsid, statvfs.f_flag, statvfs.f_namemax); if(!tmp) { result = CURLE_OUT_OF_MEMORY; state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; break; } result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); free(tmp); if(result) { state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; } } state(conn, SSH_SFTP_NEXT_QUOTE); break; } #endif case SSH_SFTP_GETINFO: { if(data->set.get_filetime) { state(conn, SSH_SFTP_FILETIME); } else { state(conn, SSH_SFTP_TRANS_INIT); } break; } case SSH_SFTP_FILETIME: { LIBSSH2_SFTP_ATTRIBUTES attrs; rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_SFTP_STAT, &attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc == 0) { data->info.filetime = attrs.mtime; } state(conn, SSH_SFTP_TRANS_INIT); break; } case SSH_SFTP_TRANS_INIT: if(data->set.upload) state(conn, SSH_SFTP_UPLOAD_INIT); else { if(sftp_scp->path[strlen(sftp_scp->path)-1] == '/') state(conn, SSH_SFTP_READDIR_INIT); else state(conn, SSH_SFTP_DOWNLOAD_INIT); } break; case SSH_SFTP_UPLOAD_INIT: { unsigned long flags; /* * NOTE!!! libssh2 requires that the destination path is a full path * that includes the destination file and name OR ends in a "/" * If this is not done the destination file will be named the * same name as the last directory in the path. */ if(data->state.resume_from != 0) { LIBSSH2_SFTP_ATTRIBUTES attrs; if(data->state.resume_from < 0) { rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_SFTP_STAT, &attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc) { data->state.resume_from = 0; } else { curl_off_t size = attrs.filesize; if(size < 0) { failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); return CURLE_BAD_DOWNLOAD_RESUME; } data->state.resume_from = attrs.filesize; } } } if(data->set.ftp_append) /* Try to open for append, but create if nonexisting */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_APPEND; else if(data->state.resume_from > 0) /* If we have restart position then open for append */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_APPEND; else /* Clear file before writing (normal behaviour) */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC; sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), flags, data->set.new_file_perms, LIBSSH2_SFTP_OPENFILE); if(!sshc->sftp_handle) { rc = libssh2_session_last_errno(sshc->ssh_session); if(LIBSSH2_ERROR_EAGAIN == rc) break; if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc) /* only when there was an SFTP protocol error can we extract the sftp error! */ err = sftp_libssh2_last_error(sshc->sftp_session); else err = -1; /* not an sftp error at all */ if(sshc->secondCreateDirs) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = err>= LIBSSH2_FX_OK? sftp_libssh2_error_to_CURLE(err):CURLE_SSH; failf(data, "Creating the dir/file failed: %s", sftp_libssh2_strerror(err)); break; } if(((err == LIBSSH2_FX_NO_SUCH_FILE) || (err == LIBSSH2_FX_FAILURE) || (err == LIBSSH2_FX_NO_SUCH_PATH)) && (data->set.ftp_create_missing_dirs && (strlen(sftp_scp->path) > 1))) { /* try to create the path remotely */ rc = 0; /* clear rc and continue */ sshc->secondCreateDirs = 1; state(conn, SSH_SFTP_CREATE_DIRS_INIT); break; } state(conn, SSH_SFTP_CLOSE); sshc->actualcode = err>= LIBSSH2_FX_OK? sftp_libssh2_error_to_CURLE(err):CURLE_SSH; if(!sshc->actualcode) { /* Sometimes, for some reason libssh2_sftp_last_error() returns zero even though libssh2_sftp_open() failed previously! We need to work around that! */ sshc->actualcode = CURLE_SSH; err = -1; } failf(data, "Upload failed: %s (%d/%d)", err>= LIBSSH2_FX_OK?sftp_libssh2_strerror(err):"ssh error", err, rc); break; } /* If we have a restart point then we need to seek to the correct position. */ if(data->state.resume_from > 0) { /* Let's read off the proper amount of bytes from the input. */ if(conn->seek_func) { Curl_set_in_callback(data, true); seekerr = conn->seek_func(conn->seek_client, data->state.resume_from, SEEK_SET); Curl_set_in_callback(data, false); } if(seekerr != CURL_SEEKFUNC_OK) { curl_off_t passed = 0; if(seekerr != CURL_SEEKFUNC_CANTSEEK) { failf(data, "Could not seek stream"); return CURLE_FTP_COULDNT_USE_REST; } /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */ do { size_t readthisamountnow = (data->state.resume_from - passed > data->set.buffer_size) ? (size_t)data->set.buffer_size : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread; Curl_set_in_callback(data, true); actuallyread = data->state.fread_func(data->state.buffer, 1, readthisamountnow, data->state.in); Curl_set_in_callback(data, false); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { /* this checks for greater-than only to make sure that the CURL_READFUNC_ABORT return code still aborts */ failf(data, "Failed to read data"); return CURLE_FTP_COULDNT_USE_REST; } } while(passed < data->state.resume_from); } /* now, decrease the size of the read */ if(data->state.infilesize > 0) { data->state.infilesize -= data->state.resume_from; data->req.size = data->state.infilesize; Curl_pgrsSetUploadSize(data, data->state.infilesize); } SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); } if(data->state.infilesize > 0) { data->req.size = data->state.infilesize; Curl_pgrsSetUploadSize(data, data->state.infilesize); } /* upload data */ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; if(result) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result; } else { /* store this original bitmask setup to use later on if we can't figure out a "real" bitmask */ sshc->orig_waitfor = data->req.keepon; /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh2 sftp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; /* since we don't really wait for anything at this point, we want the state machine to move on as soon as possible so we set a very short timeout here */ Curl_expire(data, 0, EXPIRE_RUN_NOW); state(conn, SSH_STOP); } break; } case SSH_SFTP_CREATE_DIRS_INIT: if(strlen(sftp_scp->path) > 1) { sshc->slash_pos = sftp_scp->path + 1; /* ignore the leading '/' */ state(conn, SSH_SFTP_CREATE_DIRS); } else { state(conn, SSH_SFTP_UPLOAD_INIT); } break; case SSH_SFTP_CREATE_DIRS: sshc->slash_pos = strchr(sshc->slash_pos, '/'); if(sshc->slash_pos) { *sshc->slash_pos = 0; infof(data, "Creating directory '%s'\n", sftp_scp->path); state(conn, SSH_SFTP_CREATE_DIRS_MKDIR); break; } state(conn, SSH_SFTP_UPLOAD_INIT); break; case SSH_SFTP_CREATE_DIRS_MKDIR: /* 'mode' - parameter is preliminary - default to 0644 */ rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), data->set.new_directory_perms); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } *sshc->slash_pos = '/'; ++sshc->slash_pos; if(rc < 0) { /* * Abort if failure wasn't that the dir already exists or the * permission was denied (creation might succeed further down the * path) - retry on unspecific FAILURE also */ err = sftp_libssh2_last_error(sshc->sftp_session); if((err != LIBSSH2_FX_FILE_ALREADY_EXISTS) && (err != LIBSSH2_FX_FAILURE) && (err != LIBSSH2_FX_PERMISSION_DENIED)) { result = sftp_libssh2_error_to_CURLE(err); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result?result:CURLE_SSH; break; } rc = 0; /* clear rc and continue */ } state(conn, SSH_SFTP_CREATE_DIRS); break; case SSH_SFTP_READDIR_INIT: Curl_pgrsSetDownloadSize(data, -1); if(data->set.opt_no_body) { state(conn, SSH_STOP); break; } /* * This is a directory that we are trying to get, so produce a directory * listing */ sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui( strlen(sftp_scp->path)), 0, 0, LIBSSH2_SFTP_OPENDIR); if(!sshc->sftp_handle) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } err = sftp_libssh2_last_error(sshc->sftp_session); failf(data, "Could not open directory for reading: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; break; } sshc->readdir_filename = malloc(PATH_MAX + 1); if(!sshc->readdir_filename) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->readdir_longentry = malloc(PATH_MAX + 1); if(!sshc->readdir_longentry) { Curl_safefree(sshc->readdir_filename); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR: rc = libssh2_sftp_readdir_ex(sshc->sftp_handle, sshc->readdir_filename, PATH_MAX, sshc->readdir_longentry, PATH_MAX, &sshc->readdir_attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc > 0) { sshc->readdir_len = (size_t) rc; sshc->readdir_filename[sshc->readdir_len] = '\0'; if(data->set.ftp_list_only) { char *tmpLine; tmpLine = aprintf("%s\n", sshc->readdir_filename); if(tmpLine == NULL) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } result = Curl_client_write(conn, CLIENTWRITE_BODY, tmpLine, sshc->readdir_len + 1); free(tmpLine); if(result) { state(conn, SSH_STOP); break; } /* since this counts what we send to the client, we include the newline in this counter */ data->req.bytecount += sshc->readdir_len + 1; /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_filename, sshc->readdir_len); } } else { sshc->readdir_currLen = strlen(sshc->readdir_longentry); sshc->readdir_totalLen = 80 + sshc->readdir_currLen; sshc->readdir_line = calloc(sshc->readdir_totalLen, 1); if(!sshc->readdir_line) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } memcpy(sshc->readdir_line, sshc->readdir_longentry, sshc->readdir_currLen); if((sshc->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && ((sshc->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFLNK)) { sshc->readdir_linkPath = malloc(PATH_MAX + 1); if(sshc->readdir_linkPath == NULL) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } msnprintf(sshc->readdir_linkPath, PATH_MAX, "%s%s", sftp_scp->path, sshc->readdir_filename); state(conn, SSH_SFTP_READDIR_LINK); break; } state(conn, SSH_SFTP_READDIR_BOTTOM); break; } } else if(rc == 0) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_READDIR_DONE); break; } else if(rc < 0) { err = sftp_libssh2_last_error(sshc->sftp_session); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; failf(data, "Could not open remote file for reading: %s :: %d", sftp_libssh2_strerror(err), libssh2_session_last_errno(sshc->ssh_session)); Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); break; } break; case SSH_SFTP_READDIR_LINK: rc = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->readdir_linkPath, curlx_uztoui(strlen(sshc->readdir_linkPath)), sshc->readdir_filename, PATH_MAX, LIBSSH2_SFTP_READLINK); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } sshc->readdir_len = (size_t) rc; Curl_safefree(sshc->readdir_linkPath); /* get room for the filename and extra output */ sshc->readdir_totalLen += 4 + sshc->readdir_len; new_readdir_line = Curl_saferealloc(sshc->readdir_line, sshc->readdir_totalLen); if(!new_readdir_line) { sshc->readdir_line = NULL; Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->readdir_line = new_readdir_line; sshc->readdir_currLen += msnprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, " -> %s", sshc->readdir_filename); state(conn, SSH_SFTP_READDIR_BOTTOM); break; case SSH_SFTP_READDIR_BOTTOM: sshc->readdir_currLen += msnprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, "\n"); result = Curl_client_write(conn, CLIENTWRITE_BODY, sshc->readdir_line, sshc->readdir_currLen); if(!result) { /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_line, sshc->readdir_currLen); } data->req.bytecount += sshc->readdir_currLen; } Curl_safefree(sshc->readdir_line); if(result) { state(conn, SSH_STOP); } else state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR_DONE: if(libssh2_sftp_closedir(sshc->sftp_handle) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } sshc->sftp_handle = NULL; Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); state(conn, SSH_STOP); break; case SSH_SFTP_DOWNLOAD_INIT: /* * Work on getting the specified file */ sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_FXF_READ, data->set.new_file_perms, LIBSSH2_SFTP_OPENFILE); if(!sshc->sftp_handle) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } err = sftp_libssh2_last_error(sshc->sftp_session); failf(data, "Could not open remote file for reading: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; break; } state(conn, SSH_SFTP_DOWNLOAD_STAT); break; case SSH_SFTP_DOWNLOAD_STAT: { LIBSSH2_SFTP_ATTRIBUTES attrs; rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_SFTP_STAT, &attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc || !(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE) || (attrs.filesize == 0)) { /* * libssh2_sftp_open() didn't return an error, so maybe the server * just doesn't support stat() * OR the server doesn't return a file size with a stat() * OR file size is 0 */ data->req.size = -1; data->req.maxdownload = -1; Curl_pgrsSetDownloadSize(data, -1); } else { curl_off_t size = attrs.filesize; if(size < 0) { failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size); return CURLE_BAD_DOWNLOAD_RESUME; } if(conn->data->state.use_range) { curl_off_t from, to; char *ptr; char *ptr2; CURLofft to_t; CURLofft from_t; from_t = curlx_strtoofft(conn->data->state.range, &ptr, 0, &from); if(from_t == CURL_OFFT_FLOW) return CURLE_RANGE_ERROR; while(*ptr && (ISSPACE(*ptr) || (*ptr == '-'))) ptr++; to_t = curlx_strtoofft(ptr, &ptr2, 0, &to); if(to_t == CURL_OFFT_FLOW) return CURLE_RANGE_ERROR; if((to_t == CURL_OFFT_INVAL) /* no "to" value given */ || (to >= size)) { to = size - 1; } if(from_t) { /* from is relative to end of file */ from = size - to; to = size - 1; } if(from > size) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } if(from > to) { from = to; size = 0; } else { size = to - from + 1; } SFTP_SEEK(conn->proto.sshc.sftp_handle, from); } data->req.size = size; data->req.maxdownload = size; Curl_pgrsSetDownloadSize(data, size); } /* We can resume if we can seek to the resume position */ if(data->state.resume_from) { if(data->state.resume_from < 0) { /* We're supposed to download the last abs(from) bytes */ if((curl_off_t)attrs.filesize < -data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } /* download from where? */ data->state.resume_from += attrs.filesize; } else { if((curl_off_t)attrs.filesize < data->state.resume_from) { failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")", data->state.resume_from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } } /* Does a completed file need to be seeked and started or closed ? */ /* Now store the number of bytes we are expected to download */ data->req.size = attrs.filesize - data->state.resume_from; data->req.maxdownload = attrs.filesize - data->state.resume_from; Curl_pgrsSetDownloadSize(data, attrs.filesize - data->state.resume_from); SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); } } /* Setup the actual download */ if(data->req.size == 0) { /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); infof(data, "File already completely downloaded\n"); state(conn, SSH_STOP); break; } Curl_setup_transfer(data, FIRSTSOCKET, data->req.size, FALSE, -1); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh2 recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; if(result) { /* this should never occur; the close state should be entered at the time the error occurs */ state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result; } else { state(conn, SSH_STOP); } break; case SSH_SFTP_CLOSE: if(sshc->sftp_handle) { rc = libssh2_sftp_close(sshc->sftp_handle); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to close libssh2 file: %d %s\n", rc, err_msg); } sshc->sftp_handle = NULL; } Curl_safefree(sftp_scp->path); DEBUGF(infof(data, "SFTP DONE done\n")); /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT After nextstate is executed, the control should come back to SSH_SFTP_CLOSE to pass the correct result back */ if(sshc->nextstate != SSH_NO_STATE && sshc->nextstate != SSH_SFTP_CLOSE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_SFTP_CLOSE; } else { state(conn, SSH_STOP); result = sshc->actualcode; } break; case SSH_SFTP_SHUTDOWN: /* during times we get here due to a broken transfer and then the sftp_handle might not have been taken down so make sure that is done before we proceed */ if(sshc->sftp_handle) { rc = libssh2_sftp_close(sshc->sftp_handle); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to close libssh2 file: %d %s\n", rc, err_msg); } sshc->sftp_handle = NULL; } if(sshc->sftp_session) { rc = libssh2_sftp_shutdown(sshc->sftp_session); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { infof(data, "Failed to stop libssh2 sftp subsystem\n"); } sshc->sftp_session = NULL; } Curl_safefree(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_DISCONNECT); break; case SSH_SCP_TRANS_INIT: result = Curl_getworkingpath(conn, sshc->homedir, &sftp_scp->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } if(data->set.upload) { if(data->state.infilesize < 0) { failf(data, "SCP requires a known file size for upload"); sshc->actualcode = CURLE_UPLOAD_FAILED; state(conn, SSH_SCP_CHANNEL_FREE); break; } state(conn, SSH_SCP_UPLOAD_INIT); } else { state(conn, SSH_SCP_DOWNLOAD_INIT); } break; case SSH_SCP_UPLOAD_INIT: /* * libssh2 requires that the destination path is a full path that * includes the destination file and name OR ends in a "/" . If this is * not done the destination file will be named the same name as the last * directory in the path. */ sshc->ssh_channel = SCP_SEND(sshc->ssh_session, sftp_scp->path, data->set.new_file_perms, data->state.infilesize); if(!sshc->ssh_channel) { int ssh_err; char *err_msg = NULL; if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0)); failf(conn->data, "%s", err_msg); state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); /* Map generic errors to upload failed */ if(sshc->actualcode == CURLE_SSH || sshc->actualcode == CURLE_REMOTE_FILE_NOT_FOUND) sshc->actualcode = CURLE_UPLOAD_FAILED; break; } /* upload data */ Curl_setup_transfer(data, -1, data->req.size, FALSE, FIRSTSOCKET); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; if(result) { state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = result; } else { /* store this original bitmask setup to use later on if we can't figure out a "real" bitmask */ sshc->orig_waitfor = data->req.keepon; /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh2 scp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; state(conn, SSH_STOP); } break; case SSH_SCP_DOWNLOAD_INIT: { curl_off_t bytecount; /* * We must check the remote file; if it is a directory no values will * be set in sb */ /* * If support for >2GB files exists, use it. */ /* get a fresh new channel from the ssh layer */ #if LIBSSH2_VERSION_NUM < 0x010700 struct stat sb; memset(&sb, 0, sizeof(struct stat)); sshc->ssh_channel = libssh2_scp_recv(sshc->ssh_session, sftp_scp->path, &sb); #else libssh2_struct_stat sb; memset(&sb, 0, sizeof(libssh2_struct_stat)); sshc->ssh_channel = libssh2_scp_recv2(sshc->ssh_session, sftp_scp->path, &sb); #endif if(!sshc->ssh_channel) { int ssh_err; char *err_msg = NULL; if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0)); failf(conn->data, "%s", err_msg); state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); break; } /* download data */ bytecount = (curl_off_t)sb.st_size; data->req.maxdownload = (curl_off_t)sb.st_size; Curl_setup_transfer(data, FIRSTSOCKET, bytecount, FALSE, -1); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh2 recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; if(result) { state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = result; } else state(conn, SSH_STOP); } break; case SSH_SCP_DONE: if(data->set.upload) state(conn, SSH_SCP_SEND_EOF); else state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_SEND_EOF: if(sshc->ssh_channel) { rc = libssh2_channel_send_eof(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to send libssh2 channel EOF: %d %s\n", rc, err_msg); } } state(conn, SSH_SCP_WAIT_EOF); break; case SSH_SCP_WAIT_EOF: if(sshc->ssh_channel) { rc = libssh2_channel_wait_eof(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to get channel EOF: %d %s\n", rc, err_msg); } } state(conn, SSH_SCP_WAIT_CLOSE); break; case SSH_SCP_WAIT_CLOSE: if(sshc->ssh_channel) { rc = libssh2_channel_wait_closed(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Channel failed to close: %d %s\n", rc, err_msg); } } state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_CHANNEL_FREE: if(sshc->ssh_channel) { rc = libssh2_channel_free(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to free libssh2 scp subsystem: %d %s\n", rc, err_msg); } sshc->ssh_channel = NULL; } DEBUGF(infof(data, "SCP DONE phase complete\n")); #if 0 /* PREV */ state(conn, SSH_SESSION_DISCONNECT); #endif state(conn, SSH_STOP); result = sshc->actualcode; break; case SSH_SESSION_DISCONNECT: /* during weird times when we've been prematurely aborted, the channel is still alive when we reach this state and we MUST kill the channel properly first */ if(sshc->ssh_channel) { rc = libssh2_channel_free(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to free libssh2 scp subsystem: %d %s\n", rc, err_msg); } sshc->ssh_channel = NULL; } if(sshc->ssh_session) { rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown"); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to disconnect libssh2 session: %d %s\n", rc, err_msg); } } Curl_safefree(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_FREE); break; case SSH_SESSION_FREE: #ifdef HAVE_LIBSSH2_KNOWNHOST_API if(sshc->kh) { libssh2_knownhost_free(sshc->kh); sshc->kh = NULL; } #endif #ifdef HAVE_LIBSSH2_AGENT_API if(sshc->ssh_agent) { rc = libssh2_agent_disconnect(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to disconnect from libssh2 agent: %d %s\n", rc, err_msg); } libssh2_agent_free(sshc->ssh_agent); sshc->ssh_agent = NULL; /* NB: there is no need to free identities, they are part of internal agent stuff */ sshc->sshagent_identity = NULL; sshc->sshagent_prev_identity = NULL; } #endif if(sshc->ssh_session) { rc = libssh2_session_free(sshc->ssh_session); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } if(rc < 0) { char *err_msg = NULL; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "Failed to free libssh2 session: %d %s\n", rc, err_msg); } sshc->ssh_session = NULL; } /* worst-case scenario cleanup */ DEBUGASSERT(sshc->ssh_session == NULL); DEBUGASSERT(sshc->ssh_channel == NULL); DEBUGASSERT(sshc->sftp_session == NULL); DEBUGASSERT(sshc->sftp_handle == NULL); #ifdef HAVE_LIBSSH2_KNOWNHOST_API DEBUGASSERT(sshc->kh == NULL); #endif #ifdef HAVE_LIBSSH2_AGENT_API DEBUGASSERT(sshc->ssh_agent == NULL); #endif Curl_safefree(sshc->rsa_pub); Curl_safefree(sshc->rsa); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); Curl_safefree(sshc->homedir); Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); Curl_safefree(sshc->readdir_line); Curl_safefree(sshc->readdir_linkPath); /* the code we are about to return */ result = sshc->actualcode; memset(sshc, 0, sizeof(struct ssh_conn)); connclose(conn, "SSH session free"); sshc->state = SSH_SESSION_FREE; /* current */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; case SSH_QUIT: /* fallthrough, just stop! */ default: /* internal error */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; } } while(!rc && (sshc->state != SSH_STOP)); if(rc == LIBSSH2_ERROR_EAGAIN) { /* we would block, we need to wait for the socket to be ready (in the right direction too)! */ *block = TRUE; } return result; } /* called by the multi interface to figure out what socket(s) to wait for and for what actions in the DO_DONE, PERFORM and WAITPERFORM states */ static int ssh_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION int bitmap = GETSOCK_BLANK; (void)numsocks; sock[0] = conn->sock[FIRSTSOCKET]; if(conn->waitfor & KEEP_RECV) bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); if(conn->waitfor & KEEP_SEND) bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); return bitmap; #else /* if we don't know the direction we can use the generic *_getsock() function even for the protocol_connect and doing states */ return Curl_single_getsock(conn, sock, numsocks); #endif } /* Generic function called by the multi interface to figure out what socket(s) to wait for and for what actions during the DOING and PROTOCONNECT states*/ static int ssh_getsock(struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { #ifndef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION (void)conn; (void)sock; (void)numsocks; /* if we don't know any direction we can just play along as we used to and not provide any sensible info */ return GETSOCK_BLANK; #else /* if we know the direction we can use the generic *_getsock() function even for the protocol_connect and doing states */ return ssh_perform_getsock(conn, sock, numsocks); #endif } #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION /* * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this * function is used to figure out in what direction and stores this info so * that the multi interface can take advantage of it. Make sure to call this * function in all cases so that when it _doesn't_ return EAGAIN we can * restore the default wait bits. */ static void ssh_block2waitfor(struct connectdata *conn, bool block) { struct ssh_conn *sshc = &conn->proto.sshc; int dir = 0; if(block) { dir = libssh2_session_block_directions(sshc->ssh_session); if(dir) { /* translate the libssh2 define bits into our own bit defines */ conn->waitfor = ((dir&LIBSSH2_SESSION_BLOCK_INBOUND)?KEEP_RECV:0) | ((dir&LIBSSH2_SESSION_BLOCK_OUTBOUND)?KEEP_SEND:0); } } if(!dir) /* It didn't block or libssh2 didn't reveal in which direction, put back the original set */ conn->waitfor = sshc->orig_waitfor; } #else /* no libssh2 directional support so we simply don't know */ #define ssh_block2waitfor(x,y) Curl_nop_stmt #endif /* called repeatedly until done from multi.c */ static CURLcode ssh_multi_statemach(struct connectdata *conn, bool *done) { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; bool block; /* we store the status and use that to provide a ssh_getsock() implementation */ do { result = ssh_statemach_act(conn, &block); *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; /* if there's no error, it isn't done and it didn't EWOULDBLOCK, then try again */ } while(!result && !*done && !block); ssh_block2waitfor(conn, block); return result; } static CURLcode ssh_block_statemach(struct connectdata *conn, bool disconnect) { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; while((sshc->state != SSH_STOP) && !result) { bool block; timediff_t left = 1000; struct curltime now = Curl_now(); result = ssh_statemach_act(conn, &block); if(result) break; if(!disconnect) { if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; result = Curl_speedcheck(data, now); if(result) break; left = Curl_timeleft(data, NULL, FALSE); if(left < 0) { failf(data, "Operation timed out"); return CURLE_OPERATION_TIMEDOUT; } } #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION if(!result && block) { int dir = libssh2_session_block_directions(sshc->ssh_session); curl_socket_t sock = conn->sock[FIRSTSOCKET]; curl_socket_t fd_read = CURL_SOCKET_BAD; curl_socket_t fd_write = CURL_SOCKET_BAD; if(LIBSSH2_SESSION_BLOCK_INBOUND & dir) fd_read = sock; if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir) fd_write = sock; /* wait for the socket to become ready */ (void)Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, left>1000?1000:left); /* ignore result */ } #endif } return result; } /* * SSH setup and connection */ static CURLcode ssh_setup_connection(struct connectdata *conn) { struct SSHPROTO *ssh; conn->data->req.protop = ssh = calloc(1, sizeof(struct SSHPROTO)); if(!ssh) return CURLE_OUT_OF_MEMORY; return CURLE_OK; } static Curl_recv scp_recv, sftp_recv; static Curl_send scp_send, sftp_send; /* * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. */ static CURLcode ssh_connect(struct connectdata *conn, bool *done) { #ifdef CURL_LIBSSH2_DEBUG curl_socket_t sock; #endif struct ssh_conn *ssh; CURLcode result; struct Curl_easy *data = conn->data; /* initialize per-handle data if not already */ if(!data->req.protop) ssh_setup_connection(conn); /* We default to persistent connections. We set this already in this connect function to make the re-use checks properly be able to check this bit. */ connkeep(conn, "SSH default"); if(conn->handler->protocol & CURLPROTO_SCP) { conn->recv[FIRSTSOCKET] = scp_recv; conn->send[FIRSTSOCKET] = scp_send; } else { conn->recv[FIRSTSOCKET] = sftp_recv; conn->send[FIRSTSOCKET] = sftp_send; } ssh = &conn->proto.sshc; #ifdef CURL_LIBSSH2_DEBUG if(conn->user) { infof(data, "User: %s\n", conn->user); } if(conn->passwd) { infof(data, "Password: %s\n", conn->passwd); } sock = conn->sock[FIRSTSOCKET]; #endif /* CURL_LIBSSH2_DEBUG */ ssh->ssh_session = libssh2_session_init_ex(my_libssh2_malloc, my_libssh2_free, my_libssh2_realloc, conn); if(ssh->ssh_session == NULL) { failf(data, "Failure initialising ssh session"); return CURLE_FAILED_INIT; } if(data->set.ssh_compression) { #if LIBSSH2_VERSION_NUM >= 0x010208 if(libssh2_session_flag(ssh->ssh_session, LIBSSH2_FLAG_COMPRESS, 1) < 0) #endif infof(data, "Failed to enable compression for ssh session\n"); } #ifdef HAVE_LIBSSH2_KNOWNHOST_API if(data->set.str[STRING_SSH_KNOWNHOSTS]) { int rc; ssh->kh = libssh2_knownhost_init(ssh->ssh_session); if(!ssh->kh) { libssh2_session_free(ssh->ssh_session); return CURLE_FAILED_INIT; } /* read all known hosts from there */ rc = libssh2_knownhost_readfile(ssh->kh, data->set.str[STRING_SSH_KNOWNHOSTS], LIBSSH2_KNOWNHOST_FILE_OPENSSH); if(rc < 0) infof(data, "Failed to read known hosts from %s\n", data->set.str[STRING_SSH_KNOWNHOSTS]); } #endif /* HAVE_LIBSSH2_KNOWNHOST_API */ #ifdef CURL_LIBSSH2_DEBUG libssh2_trace(ssh->ssh_session, ~0); infof(data, "SSH socket: %d\n", (int)sock); #endif /* CURL_LIBSSH2_DEBUG */ state(conn, SSH_INIT); result = ssh_multi_statemach(conn, done); return result; } /* *********************************************************************** * * scp_perform() * * This is the actual DO function for SCP. Get a file according to * the options previously setup. */ static CURLcode scp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SCP_TRANS_INIT); /* run the state-machine */ result = ssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* called from multi.c while DOing */ static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = ssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* * The DO function is generic for both protocols. There was previously two * separate ones but this way means less duplicated code. */ static CURLcode ssh_do(struct connectdata *conn, bool *done) { CURLcode result; bool connected = 0; struct Curl_easy *data = conn->data; struct ssh_conn *sshc = &conn->proto.sshc; *done = FALSE; /* default to false */ data->req.size = -1; /* make sure this is unknown at this point */ sshc->actualcode = CURLE_OK; /* reset error code */ sshc->secondCreateDirs = 0; /* reset the create dir attempt state variable */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); if(conn->handler->protocol & CURLPROTO_SCP) result = scp_perform(conn, &connected, done); else result = sftp_perform(conn, &connected, done); return result; } /* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */ static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; struct ssh_conn *ssh = &conn->proto.sshc; (void) dead_connection; if(ssh->ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SESSION_DISCONNECT); result = ssh_block_statemach(conn, TRUE); } return result; } /* generic done function for both SCP and SFTP called from their specific done functions */ static CURLcode ssh_done(struct connectdata *conn, CURLcode status) { CURLcode result = CURLE_OK; struct SSHPROTO *sftp_scp = conn->data->req.protop; if(!status) { /* run the state-machine */ result = ssh_block_statemach(conn, FALSE); } else result = status; if(sftp_scp) Curl_safefree(sftp_scp->path); if(Curl_pgrsDone(conn)) return CURLE_ABORTED_BY_CALLBACK; conn->data->req.keepon = 0; /* clear all bits */ return result; } static CURLcode scp_done(struct connectdata *conn, CURLcode status, bool premature) { (void)premature; /* not used */ if(!status) state(conn, SSH_SCP_DONE); return ssh_done(conn, status); } static ssize_t scp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { ssize_t nwrite; (void)sockindex; /* we only support SCP on the fixed known primary socket */ /* libssh2_channel_write() returns int! */ nwrite = (ssize_t) libssh2_channel_write(conn->proto.sshc.ssh_channel, mem, len); ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nwrite == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nwrite = 0; } else if(nwrite < LIBSSH2_ERROR_NONE) { *err = libssh2_session_error_to_CURLE((int)nwrite); nwrite = -1; } return nwrite; } static ssize_t scp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void)sockindex; /* we only support SCP on the fixed known primary socket */ /* libssh2_channel_read() returns int */ nread = (ssize_t) libssh2_channel_read(conn->proto.sshc.ssh_channel, mem, len); ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nread == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nread = -1; } return nread; } /* * =============== SFTP =============== */ /* *********************************************************************** * * sftp_perform() * * This is the actual DO function for SFTP. Get a file/directory according to * the options previously setup. */ static CURLcode sftp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SFTP_QUOTE_INIT); /* run the state-machine */ result = ssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* called from multi.c while DOing */ static CURLcode sftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = ssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; } /* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */ static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; (void) dead_connection; DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n")); if(conn->proto.sshc.ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SFTP_SHUTDOWN); result = ssh_block_statemach(conn, TRUE); } DEBUGF(infof(conn->data, "SSH DISCONNECT is done\n")); return result; } static CURLcode sftp_done(struct connectdata *conn, CURLcode status, bool premature) { struct ssh_conn *sshc = &conn->proto.sshc; if(!status) { /* Post quote commands are executed after the SFTP_CLOSE state to avoid errors that could happen due to open file handles during POSTQUOTE operation */ if(!premature && conn->data->set.postquote && !conn->bits.retry) sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT; state(conn, SSH_SFTP_CLOSE); } return ssh_done(conn, status); } /* return number of sent bytes */ static ssize_t sftp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { ssize_t nwrite; /* libssh2_sftp_write() used to return size_t in 0.14 but is changed to ssize_t in 0.15. These days we don't support libssh2 0.15*/ (void)sockindex; nwrite = libssh2_sftp_write(conn->proto.sshc.sftp_handle, mem, len); ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nwrite == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nwrite = 0; } else if(nwrite < LIBSSH2_ERROR_NONE) { *err = libssh2_session_error_to_CURLE((int)nwrite); nwrite = -1; } return nwrite; } /* * Return number of received (decrypted) bytes * or <0 on error */ static ssize_t sftp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void)sockindex; nread = libssh2_sftp_read(conn->proto.sshc.sftp_handle, mem, len); ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nread == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nread = -1; } else if(nread < 0) { *err = libssh2_session_error_to_CURLE((int)nread); } return nread; } static const char *sftp_libssh2_strerror(int err) { switch(err) { case LIBSSH2_FX_NO_SUCH_FILE: return "No such file or directory"; case LIBSSH2_FX_PERMISSION_DENIED: return "Permission denied"; case LIBSSH2_FX_FAILURE: return "Operation failed"; case LIBSSH2_FX_BAD_MESSAGE: return "Bad message from SFTP server"; case LIBSSH2_FX_NO_CONNECTION: return "Not connected to SFTP server"; case LIBSSH2_FX_CONNECTION_LOST: return "Connection to SFTP server lost"; case LIBSSH2_FX_OP_UNSUPPORTED: return "Operation not supported by SFTP server"; case LIBSSH2_FX_INVALID_HANDLE: return "Invalid handle"; case LIBSSH2_FX_NO_SUCH_PATH: return "No such file or directory"; case LIBSSH2_FX_FILE_ALREADY_EXISTS: return "File already exists"; case LIBSSH2_FX_WRITE_PROTECT: return "File is write protected"; case LIBSSH2_FX_NO_MEDIA: return "No media"; case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: return "Disk full"; case LIBSSH2_FX_QUOTA_EXCEEDED: return "User quota exceeded"; case LIBSSH2_FX_UNKNOWN_PRINCIPLE: return "Unknown principle"; case LIBSSH2_FX_LOCK_CONFlICT: return "File lock conflict"; case LIBSSH2_FX_DIR_NOT_EMPTY: return "Directory not empty"; case LIBSSH2_FX_NOT_A_DIRECTORY: return "Not a directory"; case LIBSSH2_FX_INVALID_FILENAME: return "Invalid filename"; case LIBSSH2_FX_LINK_LOOP: return "Link points to itself"; } return "Unknown error in libssh2"; } #endif /* USE_LIBSSH2 */
YifuLiu/AliOS-Things
components/curl/lib/ssh.c
C
apache-2.0
108,450
#ifndef HEADER_CURL_SSH_H #define HEADER_CURL_SSH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(HAVE_LIBSSH2_H) #include <libssh2.h> #include <libssh2_sftp.h> #elif defined(HAVE_LIBSSH_LIBSSH_H) #include <libssh/libssh.h> #include <libssh/sftp.h> #endif /* HAVE_LIBSSH2_H */ /**************************************************************************** * SSH unique setup ***************************************************************************/ typedef enum { SSH_NO_STATE = -1, /* Used for "nextState" so say there is none */ SSH_STOP = 0, /* do nothing state, stops the state machine */ SSH_INIT, /* First state in SSH-CONNECT */ SSH_S_STARTUP, /* Session startup */ SSH_HOSTKEY, /* verify hostkey */ SSH_AUTHLIST, SSH_AUTH_PKEY_INIT, SSH_AUTH_PKEY, SSH_AUTH_PASS_INIT, SSH_AUTH_PASS, SSH_AUTH_AGENT_INIT, /* initialize then wait for connection to agent */ SSH_AUTH_AGENT_LIST, /* ask for list then wait for entire list to come */ SSH_AUTH_AGENT, /* attempt one key at a time */ SSH_AUTH_HOST_INIT, SSH_AUTH_HOST, SSH_AUTH_KEY_INIT, SSH_AUTH_KEY, SSH_AUTH_GSSAPI, SSH_AUTH_DONE, SSH_SFTP_INIT, SSH_SFTP_REALPATH, /* Last state in SSH-CONNECT */ SSH_SFTP_QUOTE_INIT, /* First state in SFTP-DO */ SSH_SFTP_POSTQUOTE_INIT, /* (Possibly) First state in SFTP-DONE */ SSH_SFTP_QUOTE, SSH_SFTP_NEXT_QUOTE, SSH_SFTP_QUOTE_STAT, SSH_SFTP_QUOTE_SETSTAT, SSH_SFTP_QUOTE_SYMLINK, SSH_SFTP_QUOTE_MKDIR, SSH_SFTP_QUOTE_RENAME, SSH_SFTP_QUOTE_RMDIR, SSH_SFTP_QUOTE_UNLINK, SSH_SFTP_QUOTE_STATVFS, SSH_SFTP_GETINFO, SSH_SFTP_FILETIME, SSH_SFTP_TRANS_INIT, SSH_SFTP_UPLOAD_INIT, SSH_SFTP_CREATE_DIRS_INIT, SSH_SFTP_CREATE_DIRS, SSH_SFTP_CREATE_DIRS_MKDIR, SSH_SFTP_READDIR_INIT, SSH_SFTP_READDIR, SSH_SFTP_READDIR_LINK, SSH_SFTP_READDIR_BOTTOM, SSH_SFTP_READDIR_DONE, SSH_SFTP_DOWNLOAD_INIT, SSH_SFTP_DOWNLOAD_STAT, /* Last state in SFTP-DO */ SSH_SFTP_CLOSE, /* Last state in SFTP-DONE */ SSH_SFTP_SHUTDOWN, /* First state in SFTP-DISCONNECT */ SSH_SCP_TRANS_INIT, /* First state in SCP-DO */ SSH_SCP_UPLOAD_INIT, SSH_SCP_DOWNLOAD_INIT, SSH_SCP_DOWNLOAD, SSH_SCP_DONE, SSH_SCP_SEND_EOF, SSH_SCP_WAIT_EOF, SSH_SCP_WAIT_CLOSE, SSH_SCP_CHANNEL_FREE, /* Last state in SCP-DONE */ SSH_SESSION_DISCONNECT, /* First state in SCP-DISCONNECT */ SSH_SESSION_FREE, /* Last state in SCP/SFTP-DISCONNECT */ SSH_QUIT, SSH_LAST /* never used */ } sshstate; /* this struct is used in the HandleData struct which is part of the Curl_easy, which means this is used on a per-easy handle basis. Everything that is strictly related to a connection is banned from this struct. */ struct SSHPROTO { char *path; /* the path we operate on */ }; /* ssh_conn is used for struct connection-oriented data in the connectdata struct */ struct ssh_conn { const char *authlist; /* List of auth. methods, managed by libssh2 */ /* common */ const char *passphrase; /* pass-phrase to use */ char *rsa_pub; /* path name */ char *rsa; /* path name */ bool authed; /* the connection has been authenticated fine */ sshstate state; /* always use ssh.c:state() to change state! */ sshstate nextstate; /* the state to goto after stopping */ CURLcode actualcode; /* the actual error code */ struct curl_slist *quote_item; /* for the quote option */ char *quote_path1; /* two generic pointers for the QUOTE stuff */ char *quote_path2; bool acceptfail; /* used by the SFTP_QUOTE (continue if quote command fails) */ char *homedir; /* when doing SFTP we figure out home dir in the connect phase */ size_t readdir_len, readdir_totalLen, readdir_currLen; char *readdir_line; char *readdir_linkPath; /* end of READDIR stuff */ int secondCreateDirs; /* counter use by the code to see if the second attempt has been made to change to/create a directory */ char *slash_pos; /* used by the SFTP_CREATE_DIRS state */ int orig_waitfor; /* default READ/WRITE bits wait for */ #if defined(USE_LIBSSH) /* our variables */ unsigned kbd_state; /* 0 or 1 */ ssh_key privkey; ssh_key pubkey; int auth_methods; ssh_session ssh_session; ssh_scp scp_session; sftp_session sftp_session; sftp_file sftp_file; sftp_dir sftp_dir; unsigned sftp_recv_state; /* 0 or 1 */ int sftp_file_index; /* for async read */ sftp_attributes readdir_attrs; /* used by the SFTP readdir actions */ sftp_attributes readdir_link_attrs; /* used by the SFTP readdir actions */ sftp_attributes quote_attrs; /* used by the SFTP_QUOTE state */ const char *readdir_filename; /* points within readdir_attrs */ const char *readdir_longentry; char *readdir_tmp; #elif defined(USE_LIBSSH2) char *readdir_filename; char *readdir_longentry; LIBSSH2_SFTP_ATTRIBUTES quote_attrs; /* used by the SFTP_QUOTE state */ /* Here's a set of struct members used by the SFTP_READDIR state */ LIBSSH2_SFTP_ATTRIBUTES readdir_attrs; LIBSSH2_SESSION *ssh_session; /* Secure Shell session */ LIBSSH2_CHANNEL *ssh_channel; /* Secure Shell channel handle */ LIBSSH2_SFTP *sftp_session; /* SFTP handle */ LIBSSH2_SFTP_HANDLE *sftp_handle; #ifdef HAVE_LIBSSH2_AGENT_API LIBSSH2_AGENT *ssh_agent; /* proxy to ssh-agent/pageant */ struct libssh2_agent_publickey *sshagent_identity, *sshagent_prev_identity; #endif /* note that HAVE_LIBSSH2_KNOWNHOST_API is a define set in the libssh2.h header */ #ifdef HAVE_LIBSSH2_KNOWNHOST_API LIBSSH2_KNOWNHOSTS *kh; #endif #endif /* USE_LIBSSH */ }; #if defined(USE_LIBSSH) #define CURL_LIBSSH_VERSION ssh_version(0) extern const struct Curl_handler Curl_handler_scp; extern const struct Curl_handler Curl_handler_sftp; #elif defined(USE_LIBSSH2) /* Feature detection based on version numbers to better work with non-configure platforms */ #if !defined(LIBSSH2_VERSION_NUM) || (LIBSSH2_VERSION_NUM < 0x001000) # error "SCP/SFTP protocols require libssh2 0.16 or later" #endif #if LIBSSH2_VERSION_NUM >= 0x010000 #define HAVE_LIBSSH2_SFTP_SEEK64 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010100 #define HAVE_LIBSSH2_VERSION 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010205 #define HAVE_LIBSSH2_INIT 1 #define HAVE_LIBSSH2_EXIT 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010206 #define HAVE_LIBSSH2_KNOWNHOST_CHECKP 1 #define HAVE_LIBSSH2_SCP_SEND64 1 #endif #if LIBSSH2_VERSION_NUM >= 0x010208 #define HAVE_LIBSSH2_SESSION_HANDSHAKE 1 #endif #ifdef HAVE_LIBSSH2_VERSION /* get it run-time if possible */ #define CURL_LIBSSH2_VERSION libssh2_version(0) #else /* use build-time if run-time not possible */ #define CURL_LIBSSH2_VERSION LIBSSH2_VERSION #endif extern const struct Curl_handler Curl_handler_scp; extern const struct Curl_handler Curl_handler_sftp; #endif /* USE_LIBSSH2 */ #endif /* HEADER_CURL_SSH_H */
YifuLiu/AliOS-Things
components/curl/lib/ssh.h
C
apache-2.0
8,198
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "strcase.h" /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because its behavior is altered by the current locale. */ char Curl_raw_toupper(char in) { #if !defined(CURL_DOES_CONVERSIONS) if(in >= 'a' && in <= 'z') return (char)('A' + in - 'a'); #else switch(in) { case 'a': return 'A'; case 'b': return 'B'; case 'c': return 'C'; case 'd': return 'D'; case 'e': return 'E'; case 'f': return 'F'; case 'g': return 'G'; case 'h': return 'H'; case 'i': return 'I'; case 'j': return 'J'; case 'k': return 'K'; case 'l': return 'L'; case 'm': return 'M'; case 'n': return 'N'; case 'o': return 'O'; case 'p': return 'P'; case 'q': return 'Q'; case 'r': return 'R'; case 's': return 'S'; case 't': return 'T'; case 'u': return 'U'; case 'v': return 'V'; case 'w': return 'W'; case 'x': return 'X'; case 'y': return 'Y'; case 'z': return 'Z'; } #endif return in; } /* * Curl_strcasecompare() is for doing "raw" case insensitive strings. This is * meant to be locale independent and only compare strings we know are safe * for this. See * https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for some * further explanation to why this function is necessary. * * The function is capable of comparing a-z case insensitively even for * non-ascii. * * @unittest: 1301 */ int Curl_strcasecompare(const char *first, const char *second) { while(*first && *second) { if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) /* get out of the loop as soon as they don't match */ break; first++; second++; } /* we do the comparison here (possibly again), just to make sure that if the loop above is skipped because one of the strings reached zero, we must not return this as a successful match */ return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second)); } int Curl_safe_strcasecompare(const char *first, const char *second) { if(first && second) /* both pointers point to something then compare them */ return Curl_strcasecompare(first, second); /* if both pointers are NULL then treat them as equal */ return (NULL == first && NULL == second); } /* * @unittest: 1301 */ int Curl_strncasecompare(const char *first, const char *second, size_t max) { while(*first && *second && max) { if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) { break; } max--; first++; second++; } if(0 == max) return 1; /* they are equal this far */ return Curl_raw_toupper(*first) == Curl_raw_toupper(*second); } /* Copy an upper case version of the string from src to dest. The * strings may overlap. No more than n characters of the string are copied * (including any NUL) and the destination string will NOT be * NUL-terminated if that limit is reached. */ void Curl_strntoupper(char *dest, const char *src, size_t n) { if(n < 1) return; do { *dest++ = Curl_raw_toupper(*src); } while(*src++ && --n); } /* --- public functions --- */ int curl_strequal(const char *first, const char *second) { return Curl_strcasecompare(first, second); } int curl_strnequal(const char *first, const char *second, size_t max) { return Curl_strncasecompare(first, second, max); }
YifuLiu/AliOS-Things
components/curl/lib/strcase.c
C
apache-2.0
4,471
#ifndef HEADER_CURL_STRCASE_H #define HEADER_CURL_STRCASE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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); #endif /* HEADER_CURL_STRCASE_H */
YifuLiu/AliOS-Things
components/curl/lib/strcase.h
C
apache-2.0
1,967
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #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); if(len >= ((size_t)-1) / sizeof(char)) return (char *)NULL; newstr = malloc((len + 1)*sizeof(char)); if(!newstr) return (char *)NULL; memcpy(newstr, str, (len + 1)*sizeof(char)); return newstr; } #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; }
YifuLiu/AliOS-Things
components/curl/lib/strdup.c
C
apache-2.0
2,859
#ifndef HEADER_CURL_STRDUP_H #define HEADER_CURL_STRDUP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef HAVE_STRDUP extern char *curlx_strdup(const char *str); #endif void *Curl_memdup(const void *src, size_t buffer_length); void *Curl_saferealloc(void *ptr, size_t size); #endif /* HEADER_CURL_STRDUP_H */
YifuLiu/AliOS-Things
components/curl/lib/strdup.h
C
apache-2.0
1,321
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2004 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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_TELNET_OPTION_SYNTAX : return "Malformed telnet option"; 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"; /* 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_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 } #ifdef USE_WINSOCK /* This function handles most / all (?) Winsock errors curl is able to produce. */ static const char * get_winsock_error (int err, char *buf, size_t len) { #ifdef PRESERVE_WINDOWS_ERROR_CODE DWORD old_win_err = GetLastError(); #endif int old_errno = errno; const char *p; #ifndef CURL_DISABLE_VERBOSE_STRINGS 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; } #else if(!err) return NULL; else p = "error"; #endif strncpy(buf, p, len); buf [len-1] = '\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; } #endif /* USE_WINSOCK */ /* * 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. */ 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; DEBUGASSERT(err >= 0); max = buflen - 1; *buf = '\0'; #ifdef USE_WINSOCK #ifdef _WIN32_WCE { wchar_t wbuf[256]; wbuf[0] = L'\0'; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, LANG_NEUTRAL, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL); wcstombs(buf, wbuf, max); } #else /* 'sys_nerr' is the maximum errno number, it is not widely portable */ if(err >= 0 && err < sys_nerr) strncpy(buf, strerror(err), max); else { if(!get_winsock_error(err, buf, max) && !FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, LANG_NEUTRAL, buf, (DWORD)max, NULL)) msnprintf(buf, max, "Unknown error %d (%#x)", err, err); } #endif #else /* not USE_WINSOCK 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 { char *msg = strerror(err); if(msg) strncpy(buf, msg, max); else msnprintf(buf, max, "Unknown error %d", err); } #endif #endif /* end of ! USE_WINSOCK */ buf[max] = '\0'; /* make sure the string is zero 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; } #ifdef USE_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; char *outbuf; size_t outmax; #ifndef CURL_DISABLE_VERBOSE_STRINGS char txtbuf[80]; char msgbuf[256]; char *p, *str, *msg = NULL; bool msg_formatted = FALSE; #endif outbuf = buf; outmax = buflen - 1; *outbuf = '\0'; #ifndef CURL_DISABLE_VERBOSE_STRINGS switch(err) { case SEC_E_OK: txt = "No error"; break; case CRYPT_E_REVOKED: txt = "CRYPT_E_REVOKED"; break; case SEC_E_ALGORITHM_MISMATCH: txt = "SEC_E_ALGORITHM_MISMATCH"; break; case SEC_E_BAD_BINDINGS: txt = "SEC_E_BAD_BINDINGS"; break; case SEC_E_BAD_PKGID: txt = "SEC_E_BAD_PKGID"; break; case SEC_E_BUFFER_TOO_SMALL: txt = "SEC_E_BUFFER_TOO_SMALL"; break; case SEC_E_CANNOT_INSTALL: txt = "SEC_E_CANNOT_INSTALL"; break; case SEC_E_CANNOT_PACK: txt = "SEC_E_CANNOT_PACK"; break; case SEC_E_CERT_EXPIRED: txt = "SEC_E_CERT_EXPIRED"; break; case SEC_E_CERT_UNKNOWN: txt = "SEC_E_CERT_UNKNOWN"; break; case SEC_E_CERT_WRONG_USAGE: txt = "SEC_E_CERT_WRONG_USAGE"; break; case SEC_E_CONTEXT_EXPIRED: txt = "SEC_E_CONTEXT_EXPIRED"; break; case SEC_E_CROSSREALM_DELEGATION_FAILURE: txt = "SEC_E_CROSSREALM_DELEGATION_FAILURE"; break; case SEC_E_CRYPTO_SYSTEM_INVALID: txt = "SEC_E_CRYPTO_SYSTEM_INVALID"; break; case SEC_E_DECRYPT_FAILURE: txt = "SEC_E_DECRYPT_FAILURE"; break; case SEC_E_DELEGATION_POLICY: txt = "SEC_E_DELEGATION_POLICY"; break; case SEC_E_DELEGATION_REQUIRED: txt = "SEC_E_DELEGATION_REQUIRED"; break; case SEC_E_DOWNGRADE_DETECTED: txt = "SEC_E_DOWNGRADE_DETECTED"; break; case SEC_E_ENCRYPT_FAILURE: txt = "SEC_E_ENCRYPT_FAILURE"; break; case SEC_E_ILLEGAL_MESSAGE: txt = "SEC_E_ILLEGAL_MESSAGE"; break; case SEC_E_INCOMPLETE_CREDENTIALS: txt = "SEC_E_INCOMPLETE_CREDENTIALS"; break; case SEC_E_INCOMPLETE_MESSAGE: txt = "SEC_E_INCOMPLETE_MESSAGE"; break; case SEC_E_INSUFFICIENT_MEMORY: txt = "SEC_E_INSUFFICIENT_MEMORY"; break; case SEC_E_INTERNAL_ERROR: txt = "SEC_E_INTERNAL_ERROR"; break; case SEC_E_INVALID_HANDLE: txt = "SEC_E_INVALID_HANDLE"; break; case SEC_E_INVALID_PARAMETER: txt = "SEC_E_INVALID_PARAMETER"; break; case SEC_E_INVALID_TOKEN: txt = "SEC_E_INVALID_TOKEN"; break; case SEC_E_ISSUING_CA_UNTRUSTED: txt = "SEC_E_ISSUING_CA_UNTRUSTED"; break; case SEC_E_ISSUING_CA_UNTRUSTED_KDC: txt = "SEC_E_ISSUING_CA_UNTRUSTED_KDC"; break; case SEC_E_KDC_CERT_EXPIRED: txt = "SEC_E_KDC_CERT_EXPIRED"; break; case SEC_E_KDC_CERT_REVOKED: txt = "SEC_E_KDC_CERT_REVOKED"; break; case SEC_E_KDC_INVALID_REQUEST: txt = "SEC_E_KDC_INVALID_REQUEST"; break; case SEC_E_KDC_UNABLE_TO_REFER: txt = "SEC_E_KDC_UNABLE_TO_REFER"; break; case SEC_E_KDC_UNKNOWN_ETYPE: txt = "SEC_E_KDC_UNKNOWN_ETYPE"; break; case SEC_E_LOGON_DENIED: txt = "SEC_E_LOGON_DENIED"; break; case SEC_E_MAX_REFERRALS_EXCEEDED: txt = "SEC_E_MAX_REFERRALS_EXCEEDED"; break; case SEC_E_MESSAGE_ALTERED: txt = "SEC_E_MESSAGE_ALTERED"; break; case SEC_E_MULTIPLE_ACCOUNTS: txt = "SEC_E_MULTIPLE_ACCOUNTS"; break; case SEC_E_MUST_BE_KDC: txt = "SEC_E_MUST_BE_KDC"; break; case SEC_E_NOT_OWNER: txt = "SEC_E_NOT_OWNER"; break; case SEC_E_NO_AUTHENTICATING_AUTHORITY: txt = "SEC_E_NO_AUTHENTICATING_AUTHORITY"; break; case SEC_E_NO_CREDENTIALS: txt = "SEC_E_NO_CREDENTIALS"; break; case SEC_E_NO_IMPERSONATION: txt = "SEC_E_NO_IMPERSONATION"; break; case SEC_E_NO_IP_ADDRESSES: txt = "SEC_E_NO_IP_ADDRESSES"; break; case SEC_E_NO_KERB_KEY: txt = "SEC_E_NO_KERB_KEY"; break; case SEC_E_NO_PA_DATA: txt = "SEC_E_NO_PA_DATA"; break; case SEC_E_NO_S4U_PROT_SUPPORT: txt = "SEC_E_NO_S4U_PROT_SUPPORT"; break; case SEC_E_NO_TGT_REPLY: txt = "SEC_E_NO_TGT_REPLY"; break; case SEC_E_OUT_OF_SEQUENCE: txt = "SEC_E_OUT_OF_SEQUENCE"; break; case SEC_E_PKINIT_CLIENT_FAILURE: txt = "SEC_E_PKINIT_CLIENT_FAILURE"; break; case SEC_E_PKINIT_NAME_MISMATCH: txt = "SEC_E_PKINIT_NAME_MISMATCH"; break; case SEC_E_POLICY_NLTM_ONLY: txt = "SEC_E_POLICY_NLTM_ONLY"; break; case SEC_E_QOP_NOT_SUPPORTED: txt = "SEC_E_QOP_NOT_SUPPORTED"; break; case SEC_E_REVOCATION_OFFLINE_C: txt = "SEC_E_REVOCATION_OFFLINE_C"; break; case SEC_E_REVOCATION_OFFLINE_KDC: txt = "SEC_E_REVOCATION_OFFLINE_KDC"; break; case SEC_E_SECPKG_NOT_FOUND: txt = "SEC_E_SECPKG_NOT_FOUND"; break; case SEC_E_SECURITY_QOS_FAILED: txt = "SEC_E_SECURITY_QOS_FAILED"; break; case SEC_E_SHUTDOWN_IN_PROGRESS: txt = "SEC_E_SHUTDOWN_IN_PROGRESS"; break; case SEC_E_SMARTCARD_CERT_EXPIRED: txt = "SEC_E_SMARTCARD_CERT_EXPIRED"; break; case SEC_E_SMARTCARD_CERT_REVOKED: txt = "SEC_E_SMARTCARD_CERT_REVOKED"; break; case SEC_E_SMARTCARD_LOGON_REQUIRED: txt = "SEC_E_SMARTCARD_LOGON_REQUIRED"; break; case SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: txt = "SEC_E_STRONG_CRYPTO_NOT_SUPPORTED"; break; case SEC_E_TARGET_UNKNOWN: txt = "SEC_E_TARGET_UNKNOWN"; break; case SEC_E_TIME_SKEW: txt = "SEC_E_TIME_SKEW"; break; case SEC_E_TOO_MANY_PRINCIPALS: txt = "SEC_E_TOO_MANY_PRINCIPALS"; break; case SEC_E_UNFINISHED_CONTEXT_DELETED: txt = "SEC_E_UNFINISHED_CONTEXT_DELETED"; break; case SEC_E_UNKNOWN_CREDENTIALS: txt = "SEC_E_UNKNOWN_CREDENTIALS"; break; case SEC_E_UNSUPPORTED_FUNCTION: txt = "SEC_E_UNSUPPORTED_FUNCTION"; break; case SEC_E_UNSUPPORTED_PREAUTH: txt = "SEC_E_UNSUPPORTED_PREAUTH"; break; case SEC_E_UNTRUSTED_ROOT: txt = "SEC_E_UNTRUSTED_ROOT"; break; case SEC_E_WRONG_CREDENTIAL_HANDLE: txt = "SEC_E_WRONG_CREDENTIAL_HANDLE"; break; case SEC_E_WRONG_PRINCIPAL: txt = "SEC_E_WRONG_PRINCIPAL"; break; case SEC_I_COMPLETE_AND_CONTINUE: txt = "SEC_I_COMPLETE_AND_CONTINUE"; break; case SEC_I_COMPLETE_NEEDED: txt = "SEC_I_COMPLETE_NEEDED"; break; case SEC_I_CONTEXT_EXPIRED: txt = "SEC_I_CONTEXT_EXPIRED"; break; case SEC_I_CONTINUE_NEEDED: txt = "SEC_I_CONTINUE_NEEDED"; break; case SEC_I_INCOMPLETE_CREDENTIALS: txt = "SEC_I_INCOMPLETE_CREDENTIALS"; break; case SEC_I_LOCAL_LOGON: txt = "SEC_I_LOCAL_LOGON"; break; case SEC_I_NO_LSA_CONTEXT: txt = "SEC_I_NO_LSA_CONTEXT"; break; case SEC_I_RENEGOTIATE: txt = "SEC_I_RENEGOTIATE"; break; case SEC_I_SIGNATURE_NEEDED: txt = "SEC_I_SIGNATURE_NEEDED"; break; default: txt = "Unknown error"; } if(err == SEC_E_OK) strncpy(outbuf, txt, outmax); else if(err == SEC_E_ILLEGAL_MESSAGE) msnprintf(outbuf, outmax, "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 { str = txtbuf; msnprintf(txtbuf, sizeof(txtbuf), "%s (0x%08X)", txt, err); txtbuf[sizeof(txtbuf)-1] = '\0'; #ifdef _WIN32_WCE { wchar_t wbuf[256]; wbuf[0] = L'\0'; if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, LANG_NEUTRAL, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL)) { wcstombs(msgbuf, wbuf, sizeof(msgbuf)-1); msg_formatted = TRUE; } } #else if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, LANG_NEUTRAL, msgbuf, sizeof(msgbuf)-1, NULL)) { msg_formatted = TRUE; } #endif if(msg_formatted) { msgbuf[sizeof(msgbuf)-1] = '\0'; /* strip trailing '\r\n' or '\n' */ p = strrchr(msgbuf, '\n'); if(p && (p - msgbuf) >= 2) *p = '\0'; p = strrchr(msgbuf, '\r'); if(p && (p - msgbuf) >= 1) *p = '\0'; msg = msgbuf; } if(msg) msnprintf(outbuf, outmax, "%s - %s", str, msg); else strncpy(outbuf, str, outmax); } #else if(err == SEC_E_OK) txt = "No error"; else txt = "Error"; strncpy(outbuf, txt, outmax); #endif outbuf[outmax] = '\0'; if(errno != old_errno) errno = old_errno; #ifdef PRESERVE_WINDOWS_ERROR_CODE if(old_win_err != GetLastError()) SetLastError(old_win_err); #endif return outbuf; } #endif /* USE_WINDOWS_SSPI */
YifuLiu/AliOS-Things
components/curl/lib/strerror.c
C
apache-2.0
28,345
#ifndef HEADER_CURL_STRERROR_H #define HEADER_CURL_STRERROR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "urldata.h" #define STRERROR_LEN 128 /* a suitable length */ const char *Curl_strerror(int err, char *buf, size_t buflen); #ifdef USE_WINDOWS_SSPI const char *Curl_sspi_strerror(int err, char *buf, size_t buflen); #endif #endif /* HEADER_CURL_STRERROR_H */
YifuLiu/AliOS-Things
components/curl/lib/strerror.h
C
apache-2.0
1,358
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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'; /* zero 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 */
YifuLiu/AliOS-Things
components/curl/lib/strtok.c
C
apache-2.0
2,176
#ifndef HEADER_CURL_STRTOK_H #define HEADER_CURL_STRTOK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */
YifuLiu/AliOS-Things
components/curl/lib/strtok.h
C
apache-2.0
1,312
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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; }
YifuLiu/AliOS-Things
components/curl/lib/strtoofft.c
C
apache-2.0
5,798
#ifndef HEADER_CURL_STRTOOFFT_H #define HEADER_CURL_STRTOOFFT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #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 */
YifuLiu/AliOS-Things
components/curl/lib/strtoofft.h
C
apache-2.0
2,121
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2016 - 2017, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(WIN32) #include <curl/curl.h> #include "system_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; /* 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; #if defined(ENABLE_IPV6) && (USE_WINSOCK < 2) #error IPV6_requires_winsock2 #endif wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK); res = WSAStartup(wVersionRequested, &wsaData); if(res != 0) /* 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 if(Curl_verify_windows_version(6, 0, PLATFORM_WINNT, VERSION_GREATER_THAN_EQUAL)) { Curl_isVistaOrGreater = TRUE; QueryPerformanceFrequency(&Curl_freq); } else Curl_isVistaOrGreater = FALSE; return CURLE_OK; } /* Curl_win32_cleanup() is the opposite of Curl_win32_init() */ void Curl_win32_cleanup(long init_flags) { #ifdef USE_WINDOWS_SSPI Curl_sspi_global_cleanup(); #endif if(init_flags & CURL_GLOBAL_WIN32) { #ifdef USE_WINSOCK WSACleanup(); #endif } } #if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ defined(USE_WINSOCK)) #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 #endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ /* * Curl_verify_windows_version() * * This is used to verify if we are running on a specific windows version. * * Parameters: * * majorVersion [in] - The major version number. * minorVersion [in] - The minor version number. * platform [in] - The optional platform identifier. * condition [in] - The test condition used to specifier whether we are * checking a version less then, equal to or greater than * what is specified in the major and minor version * numbers. * * Returns TRUE if matched; otherwise FALSE. */ bool Curl_verify_windows_version(const unsigned int majorVersion, const unsigned int minorVersion, const PlatformIdentifier platform, const VersionCondition condition) { bool matched = FALSE; #if defined(CURL_WINDOWS_APP) /* We have no way to determine the Windows version from Windows apps, so let's assume we're running on the target Windows version. */ const WORD fullVersion = MAKEWORD(minorVersion, majorVersion); const WORD targetVersion = (WORD)_WIN32_WINNT; switch(condition) { case VERSION_LESS_THAN: matched = targetVersion < fullVersion; break; case VERSION_LESS_THAN_EQUAL: matched = targetVersion <= fullVersion; break; case VERSION_EQUAL: matched = targetVersion == fullVersion; break; case VERSION_GREATER_THAN_EQUAL: matched = targetVersion >= fullVersion; break; case VERSION_GREATER_THAN: matched = targetVersion > fullVersion; break; } if(matched && (platform == PLATFORM_WINDOWS)) { /* we're always running on PLATFORM_WINNT */ matched = FALSE; } #elif !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \ (_WIN32_WINNT < _WIN32_WINNT_WIN2K) OSVERSIONINFO osver; memset(&osver, 0, sizeof(osver)); osver.dwOSVersionInfoSize = sizeof(osver); /* Find out Windows version */ if(GetVersionEx(&osver)) { /* Verify the Operating System version number */ switch(condition) { case VERSION_LESS_THAN: if(osver.dwMajorVersion < majorVersion || (osver.dwMajorVersion == majorVersion && osver.dwMinorVersion < minorVersion)) matched = TRUE; break; case VERSION_LESS_THAN_EQUAL: if(osver.dwMajorVersion < majorVersion || (osver.dwMajorVersion == majorVersion && osver.dwMinorVersion <= minorVersion)) matched = TRUE; break; case VERSION_EQUAL: if(osver.dwMajorVersion == majorVersion && osver.dwMinorVersion == minorVersion) matched = TRUE; break; case VERSION_GREATER_THAN_EQUAL: if(osver.dwMajorVersion > majorVersion || (osver.dwMajorVersion == majorVersion && osver.dwMinorVersion >= minorVersion)) matched = TRUE; break; case VERSION_GREATER_THAN: if(osver.dwMajorVersion > majorVersion || (osver.dwMajorVersion == majorVersion && osver.dwMinorVersion > minorVersion)) matched = TRUE; break; } /* Verify the platform identifier (if necessary) */ if(matched) { switch(platform) { case PLATFORM_WINDOWS: if(osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) matched = FALSE; break; case PLATFORM_WINNT: if(osver.dwPlatformId != VER_PLATFORM_WIN32_NT) matched = FALSE; default: /* like platform == PLATFORM_DONT_CARE */ break; } } } #else ULONGLONG cm = 0; OSVERSIONINFOEX osver; BYTE majorCondition; BYTE minorCondition; BYTE spMajorCondition; BYTE spMinorCondition; switch(condition) { case VERSION_LESS_THAN: majorCondition = VER_LESS; minorCondition = VER_LESS; spMajorCondition = VER_LESS_EQUAL; spMinorCondition = VER_LESS_EQUAL; break; case VERSION_LESS_THAN_EQUAL: majorCondition = VER_LESS_EQUAL; minorCondition = VER_LESS_EQUAL; spMajorCondition = VER_LESS_EQUAL; spMinorCondition = VER_LESS_EQUAL; break; case VERSION_EQUAL: majorCondition = VER_EQUAL; minorCondition = VER_EQUAL; spMajorCondition = VER_GREATER_EQUAL; spMinorCondition = VER_GREATER_EQUAL; break; case VERSION_GREATER_THAN_EQUAL: majorCondition = VER_GREATER_EQUAL; minorCondition = VER_GREATER_EQUAL; spMajorCondition = VER_GREATER_EQUAL; spMinorCondition = VER_GREATER_EQUAL; break; case VERSION_GREATER_THAN: majorCondition = VER_GREATER; minorCondition = VER_GREATER; spMajorCondition = VER_GREATER_EQUAL; spMinorCondition = VER_GREATER_EQUAL; break; default: return FALSE; } memset(&osver, 0, sizeof(osver)); osver.dwOSVersionInfoSize = sizeof(osver); osver.dwMajorVersion = majorVersion; osver.dwMinorVersion = minorVersion; if(platform == PLATFORM_WINDOWS) osver.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS; else if(platform == PLATFORM_WINNT) osver.dwPlatformId = VER_PLATFORM_WIN32_NT; cm = VerSetConditionMask(cm, VER_MAJORVERSION, majorCondition); cm = VerSetConditionMask(cm, VER_MINORVERSION, minorCondition); cm = VerSetConditionMask(cm, VER_SERVICEPACKMAJOR, spMajorCondition); cm = VerSetConditionMask(cm, VER_SERVICEPACKMINOR, spMinorCondition); if(platform != PLATFORM_DONT_CARE) cm = VerSetConditionMask(cm, VER_PLATFORMID, VER_EQUAL); if(VerifyVersionInfo(&osver, (VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR), cm)) matched = TRUE; #endif return matched; } #if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ defined(USE_WINSOCK)) /* * 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) { 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_LIBARY_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; } #endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ #endif /* WIN32 */
YifuLiu/AliOS-Things
components/curl/lib/system_win32.c
C
apache-2.0
12,825
#ifndef HEADER_CURL_SYSTEM_WIN32_H #define HEADER_CURL_SYSTEM_WIN32_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2016, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(WIN32) extern LARGE_INTEGER Curl_freq; extern bool Curl_isVistaOrGreater; CURLcode Curl_win32_init(long flags); void Curl_win32_cleanup(long init_flags); /* Version condition */ typedef enum { VERSION_LESS_THAN, VERSION_LESS_THAN_EQUAL, VERSION_EQUAL, VERSION_GREATER_THAN_EQUAL, VERSION_GREATER_THAN } VersionCondition; /* Platform identifier */ typedef enum { PLATFORM_DONT_CARE, PLATFORM_WINDOWS, PLATFORM_WINNT } PlatformIdentifier; /* This is used to verify if we are running on a specific windows version */ bool Curl_verify_windows_version(const unsigned int majorVersion, const unsigned int minorVersion, const PlatformIdentifier platform, const VersionCondition condition); #if defined(USE_WINDOWS_SSPI) || (!defined(CURL_DISABLE_TELNET) && \ defined(USE_WINSOCK)) /* This is used to dynamically load DLLs */ HMODULE Curl_load_library(LPCTSTR filename); #endif /* USE_WINDOWS_SSPI || (!CURL_DISABLE_TELNET && USE_WINSOCK) */ #endif /* WIN32 */ #endif /* HEADER_CURL_SYSTEM_WIN32_H */
YifuLiu/AliOS-Things
components/curl/lib/system_win32.h
C
apache-2.0
2,277
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_TELNET #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 HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "sendf.h" #include "telnet.h" #include "connect.h" #include "progress.h" #include "system_win32.h" #include "arpa_telnet.h" #include "select.h" #include "strcase.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define SUBBUFSIZE 512 #define CURL_SB_CLEAR(x) x->subpointer = x->subbuffer #define CURL_SB_TERM(x) \ do { \ x->subend = x->subpointer; \ CURL_SB_CLEAR(x); \ } WHILE_FALSE #define CURL_SB_ACCUM(x,c) \ do { \ if(x->subpointer < (x->subbuffer + sizeof(x->subbuffer))) \ *x->subpointer++ = (c); \ } WHILE_FALSE #define CURL_SB_GET(x) ((*x->subpointer++)&0xff) #define CURL_SB_LEN(x) (x->subend - x->subpointer) /* For posterity: #define CURL_SB_PEEK(x) ((*x->subpointer)&0xff) #define CURL_SB_EOF(x) (x->subpointer >= x->subend) */ #ifdef CURL_DISABLE_VERBOSE_STRINGS #define printoption(a,b,c,d) Curl_nop_stmt #endif #ifdef USE_WINSOCK typedef WSAEVENT (WINAPI *WSOCK2_EVENT)(void); typedef FARPROC WSOCK2_FUNC; static CURLcode check_wsock2(struct Curl_easy *data); #endif static CURLcode telrcv(struct connectdata *, const unsigned char *inbuf, /* Data received from socket */ ssize_t count); /* Number of bytes received */ #ifndef CURL_DISABLE_VERBOSE_STRINGS static void printoption(struct Curl_easy *data, const char *direction, int cmd, int option); #endif static void negotiate(struct connectdata *); static void send_negotiation(struct connectdata *, int cmd, int option); static void set_local_option(struct connectdata *conn, int option, int newstate); static void set_remote_option(struct connectdata *conn, int option, int newstate); static void printsub(struct Curl_easy *data, int direction, unsigned char *pointer, size_t length); static void suboption(struct connectdata *); static void sendsuboption(struct connectdata *conn, int option); static CURLcode telnet_do(struct connectdata *conn, bool *done); static CURLcode telnet_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode send_telnet_data(struct connectdata *conn, char *buffer, ssize_t nread); /* For negotiation compliant to RFC 1143 */ #define CURL_NO 0 #define CURL_YES 1 #define CURL_WANTYES 2 #define CURL_WANTNO 3 #define CURL_EMPTY 0 #define CURL_OPPOSITE 1 /* * Telnet receiver states for fsm */ typedef enum { CURL_TS_DATA = 0, CURL_TS_IAC, CURL_TS_WILL, CURL_TS_WONT, CURL_TS_DO, CURL_TS_DONT, CURL_TS_CR, CURL_TS_SB, /* sub-option collection */ CURL_TS_SE /* looking for sub-option end */ } TelnetReceive; struct TELNET { int please_negotiate; int already_negotiated; int us[256]; int usq[256]; int us_preferred[256]; int him[256]; int himq[256]; int him_preferred[256]; int subnegotiation[256]; char subopt_ttype[32]; /* Set with suboption TTYPE */ char subopt_xdisploc[128]; /* Set with suboption XDISPLOC */ unsigned short subopt_wsx; /* Set with suboption NAWS */ unsigned short subopt_wsy; /* Set with suboption NAWS */ struct curl_slist *telnet_vars; /* Environment variables */ /* suboptions */ unsigned char subbuffer[SUBBUFSIZE]; unsigned char *subpointer, *subend; /* buffer for sub-options */ TelnetReceive telrcv_state; }; /* * TELNET protocol handler. */ const struct Curl_handler Curl_handler_telnet = { "TELNET", /* scheme */ ZERO_NULL, /* setup_connection */ telnet_do, /* do_it */ telnet_done, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_TELNET, /* defport */ CURLPROTO_TELNET, /* protocol */ PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ }; #ifdef USE_WINSOCK static CURLcode check_wsock2(struct Curl_easy *data) { int err; WORD wVersionRequested; WSADATA wsaData; DEBUGASSERT(data); /* telnet requires at least WinSock 2.0 so ask for it. */ wVersionRequested = MAKEWORD(2, 0); err = WSAStartup(wVersionRequested, &wsaData); /* We must've called this once already, so this call */ /* should always succeed. But, just in case... */ if(err != 0) { failf(data,"WSAStartup failed (%d)",err); return CURLE_FAILED_INIT; } /* We have to have a WSACleanup call for every successful */ /* WSAStartup call. */ WSACleanup(); /* Check that our version is supported */ if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) || HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested)) { /* Our version isn't supported */ failf(data, "insufficient winsock version to support " "telnet"); return CURLE_FAILED_INIT; } /* Our version is supported */ return CURLE_OK; } #endif static CURLcode init_telnet(struct connectdata *conn) { struct TELNET *tn; tn = calloc(1, sizeof(struct TELNET)); if(!tn) return CURLE_OUT_OF_MEMORY; conn->data->req.protop = tn; /* make us known */ tn->telrcv_state = CURL_TS_DATA; /* Init suboptions */ CURL_SB_CLEAR(tn); /* Set the options we want by default */ tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES; tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES; /* To be compliant with previous releases of libcurl we enable this option by default. This behaviour can be changed thanks to the "BINARY" option in CURLOPT_TELNETOPTIONS */ tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES; tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES; /* We must allow the server to echo what we sent but it is not necessary to request the server to do so (it might forces the server to close the connection). Hence, we ignore ECHO in the negotiate function */ tn->him_preferred[CURL_TELOPT_ECHO] = CURL_YES; /* Set the subnegotiation fields to send information just after negotiation passed (do/will) Default values are (0,0) initialized by calloc. According to the RFC1013 it is valid: A value equal to zero is acceptable for the width (or height), and means that no character width (or height) is being sent. In this case, the width (or height) that will be assumed by the Telnet server is operating system specific (it will probably be based upon the terminal type information that may have been sent using the TERMINAL TYPE Telnet option). */ tn->subnegotiation[CURL_TELOPT_NAWS] = CURL_YES; return CURLE_OK; } static void negotiate(struct connectdata *conn) { int i; struct TELNET *tn = (struct TELNET *) conn->data->req.protop; for(i = 0; i < CURL_NTELOPTS; i++) { if(i == CURL_TELOPT_ECHO) continue; if(tn->us_preferred[i] == CURL_YES) set_local_option(conn, i, CURL_YES); if(tn->him_preferred[i] == CURL_YES) set_remote_option(conn, i, CURL_YES); } } #ifndef CURL_DISABLE_VERBOSE_STRINGS static void printoption(struct Curl_easy *data, const char *direction, int cmd, int option) { if(data->set.verbose) { if(cmd == CURL_IAC) { if(CURL_TELCMD_OK(option)) infof(data, "%s IAC %s\n", direction, CURL_TELCMD(option)); else infof(data, "%s IAC %d\n", direction, option); } else { const char *fmt = (cmd == CURL_WILL) ? "WILL" : (cmd == CURL_WONT) ? "WONT" : (cmd == CURL_DO) ? "DO" : (cmd == CURL_DONT) ? "DONT" : 0; if(fmt) { const char *opt; if(CURL_TELOPT_OK(option)) opt = CURL_TELOPT(option); else if(option == CURL_TELOPT_EXOPL) opt = "EXOPL"; else opt = NULL; if(opt) infof(data, "%s %s %s\n", direction, fmt, opt); else infof(data, "%s %s %d\n", direction, fmt, option); } else infof(data, "%s %d %d\n", direction, cmd, option); } } } #endif static void send_negotiation(struct connectdata *conn, int cmd, int option) { unsigned char buf[3]; ssize_t bytes_written; struct Curl_easy *data = conn->data; buf[0] = CURL_IAC; buf[1] = (unsigned char)cmd; buf[2] = (unsigned char)option; bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3); if(bytes_written < 0) { int err = SOCKERRNO; failf(data,"Sending data failed (%d)",err); } printoption(conn->data, "SENT", cmd, option); } static void set_remote_option(struct connectdata *conn, int option, int newstate) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; if(newstate == CURL_YES) { switch(tn->him[option]) { case CURL_NO: tn->him[option] = CURL_WANTYES; send_negotiation(conn, CURL_DO, option); break; case CURL_YES: /* Already enabled */ break; case CURL_WANTNO: switch(tn->himq[option]) { case CURL_EMPTY: /* Already negotiating for CURL_YES, queue the request */ tn->himq[option] = CURL_OPPOSITE; break; case CURL_OPPOSITE: /* Error: already queued an enable request */ break; } break; case CURL_WANTYES: switch(tn->himq[option]) { case CURL_EMPTY: /* Error: already negotiating for enable */ break; case CURL_OPPOSITE: tn->himq[option] = CURL_EMPTY; break; } break; } } else { /* NO */ switch(tn->him[option]) { case CURL_NO: /* Already disabled */ break; case CURL_YES: tn->him[option] = CURL_WANTNO; send_negotiation(conn, CURL_DONT, option); break; case CURL_WANTNO: switch(tn->himq[option]) { case CURL_EMPTY: /* Already negotiating for NO */ break; case CURL_OPPOSITE: tn->himq[option] = CURL_EMPTY; break; } break; case CURL_WANTYES: switch(tn->himq[option]) { case CURL_EMPTY: tn->himq[option] = CURL_OPPOSITE; break; case CURL_OPPOSITE: break; } break; } } } static void rec_will(struct connectdata *conn, int option) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; switch(tn->him[option]) { case CURL_NO: if(tn->him_preferred[option] == CURL_YES) { tn->him[option] = CURL_YES; send_negotiation(conn, CURL_DO, option); } else send_negotiation(conn, CURL_DONT, option); break; case CURL_YES: /* Already enabled */ break; case CURL_WANTNO: switch(tn->himq[option]) { case CURL_EMPTY: /* Error: DONT answered by WILL */ tn->him[option] = CURL_NO; break; case CURL_OPPOSITE: /* Error: DONT answered by WILL */ tn->him[option] = CURL_YES; tn->himq[option] = CURL_EMPTY; break; } break; case CURL_WANTYES: switch(tn->himq[option]) { case CURL_EMPTY: tn->him[option] = CURL_YES; break; case CURL_OPPOSITE: tn->him[option] = CURL_WANTNO; tn->himq[option] = CURL_EMPTY; send_negotiation(conn, CURL_DONT, option); break; } break; } } static void rec_wont(struct connectdata *conn, int option) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; switch(tn->him[option]) { case CURL_NO: /* Already disabled */ break; case CURL_YES: tn->him[option] = CURL_NO; send_negotiation(conn, CURL_DONT, option); break; case CURL_WANTNO: switch(tn->himq[option]) { case CURL_EMPTY: tn->him[option] = CURL_NO; break; case CURL_OPPOSITE: tn->him[option] = CURL_WANTYES; tn->himq[option] = CURL_EMPTY; send_negotiation(conn, CURL_DO, option); break; } break; case CURL_WANTYES: switch(tn->himq[option]) { case CURL_EMPTY: tn->him[option] = CURL_NO; break; case CURL_OPPOSITE: tn->him[option] = CURL_NO; tn->himq[option] = CURL_EMPTY; break; } break; } } static void set_local_option(struct connectdata *conn, int option, int newstate) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; if(newstate == CURL_YES) { switch(tn->us[option]) { case CURL_NO: tn->us[option] = CURL_WANTYES; send_negotiation(conn, CURL_WILL, option); break; case CURL_YES: /* Already enabled */ break; case CURL_WANTNO: switch(tn->usq[option]) { case CURL_EMPTY: /* Already negotiating for CURL_YES, queue the request */ tn->usq[option] = CURL_OPPOSITE; break; case CURL_OPPOSITE: /* Error: already queued an enable request */ break; } break; case CURL_WANTYES: switch(tn->usq[option]) { case CURL_EMPTY: /* Error: already negotiating for enable */ break; case CURL_OPPOSITE: tn->usq[option] = CURL_EMPTY; break; } break; } } else { /* NO */ switch(tn->us[option]) { case CURL_NO: /* Already disabled */ break; case CURL_YES: tn->us[option] = CURL_WANTNO; send_negotiation(conn, CURL_WONT, option); break; case CURL_WANTNO: switch(tn->usq[option]) { case CURL_EMPTY: /* Already negotiating for NO */ break; case CURL_OPPOSITE: tn->usq[option] = CURL_EMPTY; break; } break; case CURL_WANTYES: switch(tn->usq[option]) { case CURL_EMPTY: tn->usq[option] = CURL_OPPOSITE; break; case CURL_OPPOSITE: break; } break; } } } static void rec_do(struct connectdata *conn, int option) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; switch(tn->us[option]) { case CURL_NO: if(tn->us_preferred[option] == CURL_YES) { tn->us[option] = CURL_YES; send_negotiation(conn, CURL_WILL, option); if(tn->subnegotiation[option] == CURL_YES) /* transmission of data option */ sendsuboption(conn, option); } else if(tn->subnegotiation[option] == CURL_YES) { /* send information to achieve this option*/ tn->us[option] = CURL_YES; send_negotiation(conn, CURL_WILL, option); sendsuboption(conn, option); } else send_negotiation(conn, CURL_WONT, option); break; case CURL_YES: /* Already enabled */ break; case CURL_WANTNO: switch(tn->usq[option]) { case CURL_EMPTY: /* Error: DONT answered by WILL */ tn->us[option] = CURL_NO; break; case CURL_OPPOSITE: /* Error: DONT answered by WILL */ tn->us[option] = CURL_YES; tn->usq[option] = CURL_EMPTY; break; } break; case CURL_WANTYES: switch(tn->usq[option]) { case CURL_EMPTY: tn->us[option] = CURL_YES; if(tn->subnegotiation[option] == CURL_YES) { /* transmission of data option */ sendsuboption(conn, option); } break; case CURL_OPPOSITE: tn->us[option] = CURL_WANTNO; tn->himq[option] = CURL_EMPTY; send_negotiation(conn, CURL_WONT, option); break; } break; } } static void rec_dont(struct connectdata *conn, int option) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; switch(tn->us[option]) { case CURL_NO: /* Already disabled */ break; case CURL_YES: tn->us[option] = CURL_NO; send_negotiation(conn, CURL_WONT, option); break; case CURL_WANTNO: switch(tn->usq[option]) { case CURL_EMPTY: tn->us[option] = CURL_NO; break; case CURL_OPPOSITE: tn->us[option] = CURL_WANTYES; tn->usq[option] = CURL_EMPTY; send_negotiation(conn, CURL_WILL, option); break; } break; case CURL_WANTYES: switch(tn->usq[option]) { case CURL_EMPTY: tn->us[option] = CURL_NO; break; case CURL_OPPOSITE: tn->us[option] = CURL_NO; tn->usq[option] = CURL_EMPTY; break; } break; } } static void printsub(struct Curl_easy *data, int direction, /* '<' or '>' */ unsigned char *pointer, /* where suboption data is */ size_t length) /* length of suboption data */ { if(data->set.verbose) { unsigned int i = 0; if(direction) { infof(data, "%s IAC SB ", (direction == '<')? "RCVD":"SENT"); if(length >= 3) { int j; i = pointer[length-2]; j = pointer[length-1]; if(i != CURL_IAC || j != CURL_SE) { infof(data, "(terminated by "); if(CURL_TELOPT_OK(i)) infof(data, "%s ", CURL_TELOPT(i)); else if(CURL_TELCMD_OK(i)) infof(data, "%s ", CURL_TELCMD(i)); else infof(data, "%u ", i); if(CURL_TELOPT_OK(j)) infof(data, "%s", CURL_TELOPT(j)); else if(CURL_TELCMD_OK(j)) infof(data, "%s", CURL_TELCMD(j)); else infof(data, "%d", j); infof(data, ", not IAC SE!) "); } } length -= 2; } if(length < 1) { infof(data, "(Empty suboption?)"); return; } if(CURL_TELOPT_OK(pointer[0])) { switch(pointer[0]) { case CURL_TELOPT_TTYPE: case CURL_TELOPT_XDISPLOC: case CURL_TELOPT_NEW_ENVIRON: case CURL_TELOPT_NAWS: infof(data, "%s", CURL_TELOPT(pointer[0])); break; default: infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0])); break; } } else infof(data, "%d (unknown)", pointer[i]); switch(pointer[0]) { case CURL_TELOPT_NAWS: if(length > 4) infof(data, "Width: %d ; Height: %d", (pointer[1]<<8) | pointer[2], (pointer[3]<<8) | pointer[4]); break; default: switch(pointer[1]) { case CURL_TELQUAL_IS: infof(data, " IS"); break; case CURL_TELQUAL_SEND: infof(data, " SEND"); break; case CURL_TELQUAL_INFO: infof(data, " INFO/REPLY"); break; case CURL_TELQUAL_NAME: infof(data, " NAME"); break; } switch(pointer[0]) { case CURL_TELOPT_TTYPE: case CURL_TELOPT_XDISPLOC: pointer[length] = 0; infof(data, " \"%s\"", &pointer[2]); break; case CURL_TELOPT_NEW_ENVIRON: if(pointer[1] == CURL_TELQUAL_IS) { infof(data, " "); for(i = 3; i < length; i++) { switch(pointer[i]) { case CURL_NEW_ENV_VAR: infof(data, ", "); break; case CURL_NEW_ENV_VALUE: infof(data, " = "); break; default: infof(data, "%c", pointer[i]); break; } } } break; default: for(i = 2; i < length; i++) infof(data, " %.2x", pointer[i]); break; } } if(direction) infof(data, "\n"); } } static CURLcode check_telnet_options(struct connectdata *conn) { struct curl_slist *head; struct curl_slist *beg; char option_keyword[128] = ""; char option_arg[256] = ""; struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)conn->data->req.protop; CURLcode result = CURLE_OK; int binary_option; /* Add the user name as an environment variable if it was given on the command line */ if(conn->bits.user_passwd) { msnprintf(option_arg, sizeof(option_arg), "USER,%s", conn->user); beg = curl_slist_append(tn->telnet_vars, option_arg); if(!beg) { curl_slist_free_all(tn->telnet_vars); tn->telnet_vars = NULL; return CURLE_OUT_OF_MEMORY; } tn->telnet_vars = beg; tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; } for(head = data->set.telnet_options; head; head = head->next) { if(sscanf(head->data, "%127[^= ]%*[ =]%255s", option_keyword, option_arg) == 2) { /* Terminal type */ if(strcasecompare(option_keyword, "TTYPE")) { strncpy(tn->subopt_ttype, option_arg, 31); tn->subopt_ttype[31] = 0; /* String termination */ tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES; continue; } /* Display variable */ if(strcasecompare(option_keyword, "XDISPLOC")) { strncpy(tn->subopt_xdisploc, option_arg, 127); tn->subopt_xdisploc[127] = 0; /* String termination */ tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES; continue; } /* Environment variable */ if(strcasecompare(option_keyword, "NEW_ENV")) { beg = curl_slist_append(tn->telnet_vars, option_arg); if(!beg) { result = CURLE_OUT_OF_MEMORY; break; } tn->telnet_vars = beg; tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES; continue; } /* Window Size */ if(strcasecompare(option_keyword, "WS")) { if(sscanf(option_arg, "%hu%*[xX]%hu", &tn->subopt_wsx, &tn->subopt_wsy) == 2) tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES; else { failf(data, "Syntax error in telnet option: %s", head->data); result = CURLE_TELNET_OPTION_SYNTAX; break; } continue; } /* To take care or not of the 8th bit in data exchange */ if(strcasecompare(option_keyword, "BINARY")) { binary_option = atoi(option_arg); if(binary_option != 1) { tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO; tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO; } continue; } failf(data, "Unknown telnet option %s", head->data); result = CURLE_UNKNOWN_OPTION; break; } failf(data, "Syntax error in telnet option: %s", head->data); result = CURLE_TELNET_OPTION_SYNTAX; break; } if(result) { curl_slist_free_all(tn->telnet_vars); tn->telnet_vars = NULL; } return result; } /* * suboption() * * Look at the sub-option buffer, and try to be helpful to the other * side. */ static void suboption(struct connectdata *conn) { struct curl_slist *v; unsigned char temp[2048]; ssize_t bytes_written; size_t len; int err; char varname[128] = ""; char varval[128] = ""; struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2); switch(CURL_SB_GET(tn)) { case CURL_TELOPT_TTYPE: len = strlen(tn->subopt_ttype) + 4 + 2; msnprintf((char *)temp, sizeof(temp), "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE, CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE); bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,"Sending data failed (%d)",err); } printsub(data, '>', &temp[2], len-2); break; case CURL_TELOPT_XDISPLOC: len = strlen(tn->subopt_xdisploc) + 4 + 2; msnprintf((char *)temp, sizeof(temp), "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC, CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE); bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,"Sending data failed (%d)",err); } printsub(data, '>', &temp[2], len-2); break; case CURL_TELOPT_NEW_ENVIRON: msnprintf((char *)temp, sizeof(temp), "%c%c%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON, CURL_TELQUAL_IS); len = 4; for(v = tn->telnet_vars; v; v = v->next) { size_t tmplen = (strlen(v->data) + 1); /* Add the variable only if it fits */ if(len + tmplen < (int)sizeof(temp)-6) { if(sscanf(v->data, "%127[^,],%127s", varname, varval)) { msnprintf((char *)&temp[len], sizeof(temp) - len, "%c%s%c%s", CURL_NEW_ENV_VAR, varname, CURL_NEW_ENV_VALUE, varval); len += tmplen; } } } msnprintf((char *)&temp[len], sizeof(temp) - len, "%c%c", CURL_IAC, CURL_SE); len += 2; bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len); if(bytes_written < 0) { err = SOCKERRNO; failf(data,"Sending data failed (%d)",err); } printsub(data, '>', &temp[2], len-2); break; } return; } /* * sendsuboption() * * Send suboption information to the server side. */ static void sendsuboption(struct connectdata *conn, int option) { ssize_t bytes_written; int err; unsigned short x, y; unsigned char *uc1, *uc2; struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; switch(option) { case CURL_TELOPT_NAWS: /* We prepare data to be sent */ CURL_SB_CLEAR(tn); CURL_SB_ACCUM(tn, CURL_IAC); CURL_SB_ACCUM(tn, CURL_SB); CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS); /* We must deal either with little or big endian processors */ /* Window size must be sent according to the 'network order' */ x = htons(tn->subopt_wsx); y = htons(tn->subopt_wsy); uc1 = (unsigned char *)&x; uc2 = (unsigned char *)&y; CURL_SB_ACCUM(tn, uc1[0]); CURL_SB_ACCUM(tn, uc1[1]); CURL_SB_ACCUM(tn, uc2[0]); CURL_SB_ACCUM(tn, uc2[1]); CURL_SB_ACCUM(tn, CURL_IAC); CURL_SB_ACCUM(tn, CURL_SE); CURL_SB_TERM(tn); /* data suboption is now ready */ printsub(data, '>', (unsigned char *)tn->subbuffer + 2, CURL_SB_LEN(tn)-2); /* we send the header of the suboption... */ bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer, 3); if(bytes_written < 0) { err = SOCKERRNO; failf(data, "Sending data failed (%d)", err); } /* ... then the window size with the send_telnet_data() function to deal with 0xFF cases ... */ send_telnet_data(conn, (char *)tn->subbuffer + 3, 4); /* ... and the footer */ bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer + 7, 2); if(bytes_written < 0) { err = SOCKERRNO; failf(data, "Sending data failed (%d)", err); } break; } } static CURLcode telrcv(struct connectdata *conn, const unsigned char *inbuf, /* Data received from socket */ ssize_t count) /* Number of bytes received */ { unsigned char c; CURLcode result; int in = 0; int startwrite = -1; struct Curl_easy *data = conn->data; struct TELNET *tn = (struct TELNET *)data->req.protop; #define startskipping() \ if(startwrite >= 0) { \ result = Curl_client_write(conn, \ CLIENTWRITE_BODY, \ (char *)&inbuf[startwrite], \ in-startwrite); \ if(result) \ return result; \ } \ startwrite = -1 #define writebyte() \ if(startwrite < 0) \ startwrite = in #define bufferflush() startskipping() while(count--) { c = inbuf[in]; switch(tn->telrcv_state) { case CURL_TS_CR: tn->telrcv_state = CURL_TS_DATA; if(c == '\0') { startskipping(); break; /* Ignore \0 after CR */ } writebyte(); break; case CURL_TS_DATA: if(c == CURL_IAC) { tn->telrcv_state = CURL_TS_IAC; startskipping(); break; } else if(c == '\r') tn->telrcv_state = CURL_TS_CR; writebyte(); break; case CURL_TS_IAC: process_iac: DEBUGASSERT(startwrite < 0); switch(c) { case CURL_WILL: tn->telrcv_state = CURL_TS_WILL; break; case CURL_WONT: tn->telrcv_state = CURL_TS_WONT; break; case CURL_DO: tn->telrcv_state = CURL_TS_DO; break; case CURL_DONT: tn->telrcv_state = CURL_TS_DONT; break; case CURL_SB: CURL_SB_CLEAR(tn); tn->telrcv_state = CURL_TS_SB; break; case CURL_IAC: tn->telrcv_state = CURL_TS_DATA; writebyte(); break; case CURL_DM: case CURL_NOP: case CURL_GA: default: tn->telrcv_state = CURL_TS_DATA; printoption(data, "RCVD", CURL_IAC, c); break; } break; case CURL_TS_WILL: printoption(data, "RCVD", CURL_WILL, c); tn->please_negotiate = 1; rec_will(conn, c); tn->telrcv_state = CURL_TS_DATA; break; case CURL_TS_WONT: printoption(data, "RCVD", CURL_WONT, c); tn->please_negotiate = 1; rec_wont(conn, c); tn->telrcv_state = CURL_TS_DATA; break; case CURL_TS_DO: printoption(data, "RCVD", CURL_DO, c); tn->please_negotiate = 1; rec_do(conn, c); tn->telrcv_state = CURL_TS_DATA; break; case CURL_TS_DONT: printoption(data, "RCVD", CURL_DONT, c); tn->please_negotiate = 1; rec_dont(conn, c); tn->telrcv_state = CURL_TS_DATA; break; case CURL_TS_SB: if(c == CURL_IAC) tn->telrcv_state = CURL_TS_SE; else CURL_SB_ACCUM(tn, c); break; case CURL_TS_SE: if(c != CURL_SE) { if(c != CURL_IAC) { /* * This is an error. We only expect to get "IAC IAC" or "IAC SE". * Several things may have happened. An IAC was not doubled, the * IAC SE was left off, or another option got inserted into the * suboption are all possibilities. If we assume that the IAC was * not doubled, and really the IAC SE was left off, we could get * into an infinite loop here. So, instead, we terminate the * suboption, and process the partial suboption if we can. */ CURL_SB_ACCUM(tn, CURL_IAC); CURL_SB_ACCUM(tn, c); tn->subpointer -= 2; CURL_SB_TERM(tn); printoption(data, "In SUBOPTION processing, RCVD", CURL_IAC, c); suboption(conn); /* handle sub-option */ tn->telrcv_state = CURL_TS_IAC; goto process_iac; } CURL_SB_ACCUM(tn, c); tn->telrcv_state = CURL_TS_SB; } else { CURL_SB_ACCUM(tn, CURL_IAC); CURL_SB_ACCUM(tn, CURL_SE); tn->subpointer -= 2; CURL_SB_TERM(tn); suboption(conn); /* handle sub-option */ tn->telrcv_state = CURL_TS_DATA; } break; } ++in; } bufferflush(); return CURLE_OK; } /* Escape and send a telnet data block */ static CURLcode send_telnet_data(struct connectdata *conn, char *buffer, ssize_t nread) { ssize_t escapes, i, outlen; unsigned char *outbuf = NULL; CURLcode result = CURLE_OK; ssize_t bytes_written, total_written; /* Determine size of new buffer after escaping */ escapes = 0; for(i = 0; i < nread; i++) if((unsigned char)buffer[i] == CURL_IAC) escapes++; outlen = nread + escapes; if(outlen == nread) outbuf = (unsigned char *)buffer; else { ssize_t j; outbuf = malloc(nread + escapes + 1); if(!outbuf) return CURLE_OUT_OF_MEMORY; j = 0; for(i = 0; i < nread; i++) { outbuf[j++] = buffer[i]; if((unsigned char)buffer[i] == CURL_IAC) outbuf[j++] = CURL_IAC; } outbuf[j] = '\0'; } total_written = 0; while(!result && total_written < outlen) { /* Make sure socket is writable to avoid EWOULDBLOCK condition */ struct pollfd pfd[1]; pfd[0].fd = conn->sock[FIRSTSOCKET]; pfd[0].events = POLLOUT; switch(Curl_poll(pfd, 1, -1)) { case -1: /* error, abort writing */ case 0: /* timeout (will never happen) */ result = CURLE_SEND_ERROR; break; default: /* write! */ bytes_written = 0; result = Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf + total_written, outlen - total_written, &bytes_written); total_written += bytes_written; break; } } /* Free malloc copy if escaped */ if(outbuf != (unsigned char *)buffer) free(outbuf); return result; } static CURLcode telnet_done(struct connectdata *conn, CURLcode status, bool premature) { struct TELNET *tn = (struct TELNET *)conn->data->req.protop; (void)status; /* unused */ (void)premature; /* not used */ if(!tn) return CURLE_OK; curl_slist_free_all(tn->telnet_vars); tn->telnet_vars = NULL; Curl_safefree(conn->data->req.protop); return CURLE_OK; } static CURLcode telnet_do(struct connectdata *conn, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_EVENT create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD obj_count; DWORD wait_timeout; DWORD readfile_read; int err; #else int interval_ms; struct pollfd pfd[2]; int poll_cnt; curl_off_t total_dl = 0; curl_off_t total_ul = 0; #endif ssize_t nread; struct curltime now; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; *done = TRUE; /* unconditionally */ result = init_telnet(conn); if(result) return result; tn = (struct TELNET *)data->req.protop; result = check_telnet_options(conn); if(result) return result; #ifdef USE_WINSOCK /* ** This functionality only works with WinSock >= 2.0. So, ** make sure we have it. */ result = check_wsock2(data); if(result) return result; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = Curl_load_library(TEXT("WS2_32.DLL")); if(wsock2 == NULL) { failf(data, "failed to load WS2_32.DLL (%u)", GetLastError()); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = CURLX_FUNCTION_CAST(WSOCK2_EVENT, (GetProcAddress(wsock2, "WSACreateEvent"))); if(create_event_func == NULL) { failf(data, "failed to find WSACreateEvent function (%u)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2, "WSACloseEvent"); if(close_event_func == NULL) { failf(data, "failed to find WSACloseEvent function (%u)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2, "WSAEventSelect"); if(event_select_func == NULL) { failf(data, "failed to find WSAEventSelect function (%u)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2, "WSAEnumNetworkEvents"); if(enum_netevents_func == NULL) { failf(data, "failed to find WSAEnumNetworkEvents function (%u)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if(event_handle == WSA_INVALID_EVENT) { failf(data, "WSACreateEvent failed (%d)", SOCKERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return CURLE_OK; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = event_handle; objs[1] = stdin_handle; /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, else use the old WaitForMultipleObjects() way */ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE || data->set.is_fread_set) { /* Don't wait for stdin_handle, just wait for event_handle */ obj_count = 1; /* Check stdin_handle per 100 milliseconds */ wait_timeout = 100; } else { obj_count = 2; wait_timeout = 1000; } /* Keep on listening and act on events */ while(keepon) { const DWORD buf_size = (DWORD)data->set.buffer_size; DWORD waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout); switch(waitret) { case WAIT_TIMEOUT: { for(;;) { if(data->set.is_fread_set) { size_t n; /* read from user-supplied method */ n = data->state.fread_func(buf, 1, buf_size, data->state.in); if(n == CURL_READFUNC_ABORT) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(n == CURL_READFUNC_PAUSE) break; if(n == 0) /* no bytes */ break; /* fall through with number of bytes read */ readfile_read = (DWORD)n; } else { /* read from stdin */ if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(!readfile_read) break; if(!ReadFile(stdin_handle, buf, buf_size, &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } } break; case WAIT_OBJECT_0 + 1: { if(!ReadFile(stdin_handle, buf, buf_size, &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } break; case WAIT_OBJECT_0: events.lNetworkEvents = 0; if(SOCKET_ERROR == enum_netevents_func(sockfd, event_handle, &events)) { err = SOCKERRNO; if(err != EINPROGRESS) { infof(data, "WSAEnumNetworkEvents failed (%d)", err); keepon = FALSE; result = CURLE_READ_ERROR; } break; } if(events.lNetworkEvents & FD_READ) { /* read data from network */ result = Curl_read(conn, sockfd, buf, data->set.buffer_size, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ else if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } result = telrcv(conn, (unsigned char *) buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } break; } if(data->set.timeout) { now = Curl_now(); if(Curl_timediff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } } /* We called WSACreateEvent, so call WSACloseEvent */ if(!close_event_func(event_handle)) { infof(data, "WSACloseEvent failed (%d)", SOCKERRNO); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if(!FreeLibrary(wsock2)) infof(data, "FreeLibrary(wsock2) failed (%u)", GetLastError()); #else pfd[0].fd = sockfd; pfd[0].events = POLLIN; if(data->set.is_fread_set) { poll_cnt = 1; interval_ms = 100; /* poll user-supplied read function */ } else { /* really using fread, so infile is a FILE* */ pfd[1].fd = fileno((FILE *)data->state.in); pfd[1].events = POLLIN; poll_cnt = 2; interval_ms = 1 * 1000; } while(keepon) { switch(Curl_poll(pfd, poll_cnt, interval_ms)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ pfd[0].revents = 0; pfd[1].revents = 0; /* FALLTHROUGH */ default: /* read! */ if(pfd[0].revents & POLLIN) { /* read data from network */ result = Curl_read(conn, sockfd, buf, data->set.buffer_size, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } total_dl += nread; Curl_pgrsSetDownloadCounter(data, total_dl); result = telrcv(conn, (unsigned char *)buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } nread = 0; if(poll_cnt == 2) { if(pfd[1].revents & POLLIN) { /* read from in file */ nread = read(pfd[1].fd, buf, data->set.buffer_size); } } else { /* read from user-supplied method */ nread = (int)data->state.fread_func(buf, 1, data->set.buffer_size, data->state.in); if(nread == CURL_READFUNC_ABORT) { keepon = FALSE; break; } if(nread == CURL_READFUNC_PAUSE) break; } if(nread > 0) { result = send_telnet_data(conn, buf, nread); if(result) { keepon = FALSE; break; } total_ul += nread; Curl_pgrsSetUploadCounter(data, total_ul); } else if(nread < 0) keepon = FALSE; break; } /* poll switch statement */ if(data->set.timeout) { now = Curl_now(); if(Curl_timediff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } if(Curl_pgrsUpdate(conn)) { result = CURLE_ABORTED_BY_CALLBACK; break; } } #endif /* mark this as "no further transfer wanted" */ Curl_setup_transfer(data, -1, -1, FALSE, -1); return result; } #endif
YifuLiu/AliOS-Things
components/curl/lib/telnet.c
C
apache-2.0
47,119
#ifndef HEADER_CURL_TELNET_H #define HEADER_CURL_TELNET_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_TELNET extern const struct Curl_handler Curl_handler_telnet; #endif #endif /* HEADER_CURL_TELNET_H */
YifuLiu/AliOS-Things
components/curl/lib/telnet.h
C
apache-2.0
1,208
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_TFTP #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 HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "sendf.h" #include "tftp.h" #include "progress.h" #include "connect.h" #include "strerror.h" #include "sockaddr.h" /* required for Curl_sockaddr_storage */ #include "multiif.h" #include "url.h" #include "strcase.h" #include "speedcheck.h" #include "select.h" #include "escape.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* RFC2348 allows the block size to be negotiated */ #define TFTP_BLKSIZE_DEFAULT 512 #define TFTP_BLKSIZE_MIN 8 #define TFTP_BLKSIZE_MAX 65464 #define TFTP_OPTION_BLKSIZE "blksize" /* from RFC2349: */ #define TFTP_OPTION_TSIZE "tsize" #define TFTP_OPTION_INTERVAL "timeout" typedef enum { TFTP_MODE_NETASCII = 0, TFTP_MODE_OCTET } tftp_mode_t; typedef enum { TFTP_STATE_START = 0, TFTP_STATE_RX, TFTP_STATE_TX, TFTP_STATE_FIN } tftp_state_t; typedef enum { TFTP_EVENT_NONE = -1, TFTP_EVENT_INIT = 0, TFTP_EVENT_RRQ = 1, TFTP_EVENT_WRQ = 2, TFTP_EVENT_DATA = 3, TFTP_EVENT_ACK = 4, TFTP_EVENT_ERROR = 5, TFTP_EVENT_OACK = 6, TFTP_EVENT_TIMEOUT } tftp_event_t; typedef enum { TFTP_ERR_UNDEF = 0, TFTP_ERR_NOTFOUND, TFTP_ERR_PERM, TFTP_ERR_DISKFULL, TFTP_ERR_ILLEGAL, TFTP_ERR_UNKNOWNID, TFTP_ERR_EXISTS, TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */ /* The remaining error codes are internal to curl */ TFTP_ERR_NONE = -100, TFTP_ERR_TIMEOUT, TFTP_ERR_NORESPONSE } tftp_error_t; typedef struct tftp_packet { unsigned char *data; } tftp_packet_t; typedef struct tftp_state_data { tftp_state_t state; tftp_mode_t mode; tftp_error_t error; tftp_event_t event; struct connectdata *conn; curl_socket_t sockfd; int retries; int retry_time; int retry_max; time_t start_time; time_t max_time; time_t rx_time; unsigned short block; struct Curl_sockaddr_storage local_addr; struct Curl_sockaddr_storage remote_addr; curl_socklen_t remote_addrlen; int rbytes; int sbytes; int blksize; int requested_blksize; tftp_packet_t rpacket; tftp_packet_t spacket; } tftp_state_data_t; /* Forward declarations */ static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event); static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event); static CURLcode tftp_connect(struct connectdata *conn, bool *done); static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection); static CURLcode tftp_do(struct connectdata *conn, bool *done); static CURLcode tftp_done(struct connectdata *conn, CURLcode, bool premature); static CURLcode tftp_setup_connection(struct connectdata * conn); static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done); static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done); static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); static CURLcode tftp_translate_code(tftp_error_t error); /* * TFTP protocol handler. */ const struct Curl_handler Curl_handler_tftp = { "TFTP", /* scheme */ tftp_setup_connection, /* setup_connection */ tftp_do, /* do_it */ tftp_done, /* done */ ZERO_NULL, /* do_more */ tftp_connect, /* connect_it */ tftp_multi_statemach, /* connecting */ tftp_doing, /* doing */ tftp_getsock, /* proto_getsock */ tftp_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ tftp_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_TFTP, /* defport */ CURLPROTO_TFTP, /* protocol */ PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */ }; /********************************************************** * * tftp_set_timeouts - * * Set timeouts based on state machine state. * Use user provided connect timeouts until DATA or ACK * packet is received, then use user-provided transfer timeouts * * **********************************************************/ static CURLcode tftp_set_timeouts(tftp_state_data_t *state) { time_t maxtime, timeout; timediff_t timeout_ms; bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE; time(&state->start_time); /* Compute drop-dead time */ timeout_ms = Curl_timeleft(state->conn->data, NULL, start); if(timeout_ms < 0) { /* time-out, bail out, go home */ failf(state->conn->data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } if(start) { maxtime = (time_t)(timeout_ms + 500) / 1000; state->max_time = state->start_time + maxtime; /* Set per-block timeout to total */ timeout = maxtime; /* Average restart after 5 seconds */ state->retry_max = (int)timeout/5; if(state->retry_max < 1) /* avoid division by zero below */ state->retry_max = 1; /* Compute the re-start interval to suit the timeout */ state->retry_time = (int)timeout/state->retry_max; if(state->retry_time<1) state->retry_time = 1; } else { if(timeout_ms > 0) maxtime = (time_t)(timeout_ms + 500) / 1000; else maxtime = 3600; state->max_time = state->start_time + maxtime; /* Set per-block timeout to total */ timeout = maxtime; /* Average reposting an ACK after 5 seconds */ state->retry_max = (int)timeout/5; } /* But bound the total number */ if(state->retry_max<3) state->retry_max = 3; if(state->retry_max>50) state->retry_max = 50; /* Compute the re-ACK interval to suit the timeout */ state->retry_time = (int)(timeout/state->retry_max); if(state->retry_time<1) state->retry_time = 1; infof(state->conn->data, "set timeouts for state %d; Total %ld, retry %d maxtry %d\n", (int)state->state, (long)(state->max_time-state->start_time), state->retry_time, state->retry_max); /* init RX time */ time(&state->rx_time); return CURLE_OK; } /********************************************************** * * tftp_set_send_first * * Event handler for the START state * **********************************************************/ static void setpacketevent(tftp_packet_t *packet, unsigned short num) { packet->data[0] = (unsigned char)(num >> 8); packet->data[1] = (unsigned char)(num & 0xff); } static void setpacketblock(tftp_packet_t *packet, unsigned short num) { packet->data[2] = (unsigned char)(num >> 8); packet->data[3] = (unsigned char)(num & 0xff); } static unsigned short getrpacketevent(const tftp_packet_t *packet) { return (unsigned short)((packet->data[0] << 8) | packet->data[1]); } static unsigned short getrpacketblock(const tftp_packet_t *packet) { return (unsigned short)((packet->data[2] << 8) | packet->data[3]); } static size_t Curl_strnlen(const char *string, size_t maxlen) { const char *end = memchr(string, '\0', maxlen); return end ? (size_t) (end - string) : maxlen; } static const char *tftp_option_get(const char *buf, size_t len, const char **option, const char **value) { size_t loc; loc = Curl_strnlen(buf, len); loc++; /* NULL term */ if(loc >= len) return NULL; *option = buf; loc += Curl_strnlen(buf + loc, len-loc); loc++; /* NULL term */ if(loc > len) return NULL; *value = &buf[strlen(*option) + 1]; return &buf[loc]; } static CURLcode tftp_parse_option_ack(tftp_state_data_t *state, const char *ptr, int len) { const char *tmp = ptr; struct Curl_easy *data = state->conn->data; /* if OACK doesn't contain blksize option, the default (512) must be used */ state->blksize = TFTP_BLKSIZE_DEFAULT; while(tmp < ptr + len) { const char *option, *value; tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value); if(tmp == NULL) { failf(data, "Malformed ACK packet, rejecting"); return CURLE_TFTP_ILLEGAL; } infof(data, "got option=(%s) value=(%s)\n", option, value); if(checkprefix(option, TFTP_OPTION_BLKSIZE)) { long blksize; blksize = strtol(value, NULL, 10); if(!blksize) { failf(data, "invalid blocksize value in OACK packet"); return CURLE_TFTP_ILLEGAL; } if(blksize > TFTP_BLKSIZE_MAX) { failf(data, "%s (%d)", "blksize is larger than max supported", TFTP_BLKSIZE_MAX); return CURLE_TFTP_ILLEGAL; } else if(blksize < TFTP_BLKSIZE_MIN) { failf(data, "%s (%d)", "blksize is smaller than min supported", TFTP_BLKSIZE_MIN); return CURLE_TFTP_ILLEGAL; } else if(blksize > state->requested_blksize) { /* could realloc pkt buffers here, but the spec doesn't call out * support for the server requesting a bigger blksize than the client * requests */ failf(data, "%s (%ld)", "server requested blksize larger than allocated", blksize); return CURLE_TFTP_ILLEGAL; } state->blksize = (int)blksize; infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK", state->blksize, "requested", state->requested_blksize); } else if(checkprefix(option, TFTP_OPTION_TSIZE)) { long tsize = 0; tsize = strtol(value, NULL, 10); infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize); /* tsize should be ignored on upload: Who cares about the size of the remote file? */ if(!data->set.upload) { if(!tsize) { failf(data, "invalid tsize -:%s:- value in OACK packet", value); return CURLE_TFTP_ILLEGAL; } Curl_pgrsSetDownloadSize(data, tsize); } } } return CURLE_OK; } static size_t tftp_option_add(tftp_state_data_t *state, size_t csize, char *buf, const char *option) { if(( strlen(option) + csize + 1) > (size_t)state->blksize) return 0; strcpy(buf, option); return strlen(option) + 1; } static CURLcode tftp_connect_for_tx(tftp_state_data_t *state, tftp_event_t event) { CURLcode result; #ifndef CURL_DISABLE_VERBOSE_STRINGS struct Curl_easy *data = state->conn->data; infof(data, "%s\n", "Connected for transmit"); #endif state->state = TFTP_STATE_TX; result = tftp_set_timeouts(state); if(result) return result; return tftp_tx(state, event); } static CURLcode tftp_connect_for_rx(tftp_state_data_t *state, tftp_event_t event) { CURLcode result; #ifndef CURL_DISABLE_VERBOSE_STRINGS struct Curl_easy *data = state->conn->data; infof(data, "%s\n", "Connected for receive"); #endif state->state = TFTP_STATE_RX; result = tftp_set_timeouts(state); if(result) return result; return tftp_rx(state, event); } static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event) { size_t sbytes; ssize_t senddata; const char *mode = "octet"; char *filename; struct Curl_easy *data = state->conn->data; CURLcode result = CURLE_OK; /* Set ascii mode if -B flag was used */ if(data->set.prefer_ascii) mode = "netascii"; switch(event) { case TFTP_EVENT_INIT: /* Send the first packet out */ case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */ /* Increment the retry counter, quit if over the limit */ state->retries++; if(state->retries>state->retry_max) { state->error = TFTP_ERR_NORESPONSE; state->state = TFTP_STATE_FIN; return result; } if(data->set.upload) { /* If we are uploading, send an WRQ */ setpacketevent(&state->spacket, TFTP_EVENT_WRQ); state->conn->data->req.upload_fromhere = (char *)state->spacket.data + 4; if(data->state.infilesize != -1) Curl_pgrsSetUploadSize(data, data->state.infilesize); } else { /* If we are downloading, send an RRQ */ setpacketevent(&state->spacket, TFTP_EVENT_RRQ); } /* As RFC3617 describes the separator slash is not actually part of the file name so we skip the always-present first letter of the path string. */ result = Curl_urldecode(data, &state->conn->data->state.up.path[1], 0, &filename, NULL, FALSE); if(result) return result; if(strlen(filename) > (state->blksize - strlen(mode) - 4)) { failf(data, "TFTP file name too long\n"); free(filename); return CURLE_TFTP_ILLEGAL; /* too long file name field */ } msnprintf((char *)state->spacket.data + 2, state->blksize, "%s%c%s%c", filename, '\0', mode, '\0'); sbytes = 4 + strlen(filename) + strlen(mode); /* optional addition of TFTP options */ if(!data->set.tftp_no_options) { char buf[64]; /* add tsize option */ if(data->set.upload && (data->state.infilesize != -1)) msnprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize); else strcpy(buf, "0"); /* the destination is large enough */ sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, TFTP_OPTION_TSIZE); sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, buf); /* add blksize option */ msnprintf(buf, sizeof(buf), "%d", state->requested_blksize); sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, TFTP_OPTION_BLKSIZE); sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, buf); /* add timeout option */ msnprintf(buf, sizeof(buf), "%d", state->retry_time); sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, TFTP_OPTION_INTERVAL); sbytes += tftp_option_add(state, sbytes, (char *)state->spacket.data + sbytes, buf); } /* the typecase for the 3rd argument is mostly for systems that do not have a size_t argument, like older unixes that want an 'int' */ senddata = sendto(state->sockfd, (void *)state->spacket.data, (SEND_TYPE_ARG3)sbytes, 0, state->conn->ip_addr->ai_addr, state->conn->ip_addr->ai_addrlen); if(senddata != (ssize_t)sbytes) { char buffer[STRERROR_LEN]; failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); } free(filename); break; case TFTP_EVENT_OACK: if(data->set.upload) { result = tftp_connect_for_tx(state, event); } else { result = tftp_connect_for_rx(state, event); } break; case TFTP_EVENT_ACK: /* Connected for transmit */ result = tftp_connect_for_tx(state, event); break; case TFTP_EVENT_DATA: /* Connected for receive */ result = tftp_connect_for_rx(state, event); break; case TFTP_EVENT_ERROR: state->state = TFTP_STATE_FIN; break; default: failf(state->conn->data, "tftp_send_first: internal error"); break; } return result; } /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit boundary */ #define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff) /********************************************************** * * tftp_rx * * Event handler for the RX state * **********************************************************/ static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) { ssize_t sbytes; int rblock; struct Curl_easy *data = state->conn->data; char buffer[STRERROR_LEN]; switch(event) { case TFTP_EVENT_DATA: /* Is this the block we expect? */ rblock = getrpacketblock(&state->rpacket); if(NEXT_BLOCKNUM(state->block) == rblock) { /* This is the expected block. Reset counters and ACK it. */ state->retries = 0; } else if(state->block == rblock) { /* This is the last recently received block again. Log it and ACK it again. */ infof(data, "Received last DATA packet block %d again.\n", rblock); } else { /* totally unexpected, just log it */ infof(data, "Received unexpected DATA packet block %d, expecting block %d\n", rblock, NEXT_BLOCKNUM(state->block)); break; } /* ACK this block. */ state->block = (unsigned short)rblock; setpacketevent(&state->spacket, TFTP_EVENT_ACK); setpacketblock(&state->spacket, state->block); sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes < 0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_SEND_ERROR; } /* Check if completed (That is, a less than full packet is received) */ if(state->rbytes < (ssize_t)state->blksize + 4) { state->state = TFTP_STATE_FIN; } else { state->state = TFTP_STATE_RX; } time(&state->rx_time); break; case TFTP_EVENT_OACK: /* ACK option acknowledgement so we can move on to data */ state->block = 0; state->retries = 0; setpacketevent(&state->spacket, TFTP_EVENT_ACK); setpacketblock(&state->spacket, state->block); sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes < 0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_SEND_ERROR; } /* we're ready to RX data */ state->state = TFTP_STATE_RX; time(&state->rx_time); break; case TFTP_EVENT_TIMEOUT: /* Increment the retry count and fail if over the limit */ state->retries++; infof(data, "Timeout waiting for block %d ACK. Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries); if(state->retries > state->retry_max) { state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; } else { /* Resend the previous ACK */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes<0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_SEND_ERROR; } } break; case TFTP_EVENT_ERROR: setpacketevent(&state->spacket, TFTP_EVENT_ERROR); setpacketblock(&state->spacket, state->block); (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* don't bother with the return code, but if the socket is still up we * should be a good TFTP client and let the server know we're done */ state->state = TFTP_STATE_FIN; break; default: failf(data, "%s", "tftp_rx: internal error"); return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for this */ } return CURLE_OK; } /********************************************************** * * tftp_tx * * Event handler for the TX state * **********************************************************/ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) { struct Curl_easy *data = state->conn->data; ssize_t sbytes; CURLcode result = CURLE_OK; struct SingleRequest *k = &data->req; size_t cb; /* Bytes currently read */ char buffer[STRERROR_LEN]; switch(event) { case TFTP_EVENT_ACK: case TFTP_EVENT_OACK: if(event == TFTP_EVENT_ACK) { /* Ack the packet */ int rblock = getrpacketblock(&state->rpacket); if(rblock != state->block && /* There's a bug in tftpd-hpa that causes it to send us an ack for * 65535 when the block number wraps to 0. So when we're expecting * 0, also accept 65535. See * http://syslinux.zytor.com/archives/2010-September/015253.html * */ !(state->block == 0 && rblock == 65535)) { /* This isn't the expected block. Log it and up the retry counter */ infof(data, "Received ACK for block %d, expecting %d\n", rblock, state->block); state->retries++; /* Bail out if over the maximum */ if(state->retries>state->retry_max) { failf(data, "tftp_tx: giving up waiting for block %d ack", state->block); result = CURLE_SEND_ERROR; } else { /* Re-send the data packet */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4 + state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); result = CURLE_SEND_ERROR; } } return result; } /* This is the expected packet. Reset the counters and send the next block */ time(&state->rx_time); state->block++; } else state->block = 1; /* first data block is 1 when using OACK */ state->retries = 0; setpacketevent(&state->spacket, TFTP_EVENT_DATA); setpacketblock(&state->spacket, state->block); if(state->block > 1 && state->sbytes < state->blksize) { state->state = TFTP_STATE_FIN; return CURLE_OK; } /* TFTP considers data block size < 512 bytes as an end of session. So * in some cases we must wait for additional data to build full (512 bytes) * data block. * */ state->sbytes = 0; state->conn->data->req.upload_fromhere = (char *)state->spacket.data + 4; do { result = Curl_fillreadbuffer(state->conn, state->blksize - state->sbytes, &cb); if(result) return result; state->sbytes += (int)cb; state->conn->data->req.upload_fromhere += cb; } while(state->sbytes < state->blksize && cb != 0); sbytes = sendto(state->sockfd, (void *) state->spacket.data, 4 + state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_SEND_ERROR; } /* Update the progress meter */ k->writebytecount += state->sbytes; Curl_pgrsSetUploadCounter(data, k->writebytecount); break; case TFTP_EVENT_TIMEOUT: /* Increment the retry counter and log the timeout */ state->retries++; infof(data, "Timeout waiting for block %d ACK. " " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries); /* Decide if we've had enough */ if(state->retries > state->retry_max) { state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; } else { /* Re-send the data packet */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4 + state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_SEND_ERROR; } /* since this was a re-send, we remain at the still byte position */ Curl_pgrsSetUploadCounter(data, k->writebytecount); } break; case TFTP_EVENT_ERROR: state->state = TFTP_STATE_FIN; setpacketevent(&state->spacket, TFTP_EVENT_ERROR); setpacketblock(&state->spacket, state->block); (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* don't bother with the return code, but if the socket is still up we * should be a good TFTP client and let the server know we're done */ state->state = TFTP_STATE_FIN; break; default: failf(data, "tftp_tx: internal error, event: %i", (int)(event)); break; } return result; } /********************************************************** * * tftp_translate_code * * Translate internal error codes to CURL error codes * **********************************************************/ static CURLcode tftp_translate_code(tftp_error_t error) { CURLcode result = CURLE_OK; if(error != TFTP_ERR_NONE) { switch(error) { case TFTP_ERR_NOTFOUND: result = CURLE_TFTP_NOTFOUND; break; case TFTP_ERR_PERM: result = CURLE_TFTP_PERM; break; case TFTP_ERR_DISKFULL: result = CURLE_REMOTE_DISK_FULL; break; case TFTP_ERR_UNDEF: case TFTP_ERR_ILLEGAL: result = CURLE_TFTP_ILLEGAL; break; case TFTP_ERR_UNKNOWNID: result = CURLE_TFTP_UNKNOWNID; break; case TFTP_ERR_EXISTS: result = CURLE_REMOTE_FILE_EXISTS; break; case TFTP_ERR_NOSUCHUSER: result = CURLE_TFTP_NOSUCHUSER; break; case TFTP_ERR_TIMEOUT: result = CURLE_OPERATION_TIMEDOUT; break; case TFTP_ERR_NORESPONSE: result = CURLE_COULDNT_CONNECT; break; default: result = CURLE_ABORTED_BY_CALLBACK; break; } } else result = CURLE_OK; return result; } /********************************************************** * * tftp_state_machine * * The tftp state machine event dispatcher * **********************************************************/ static CURLcode tftp_state_machine(tftp_state_data_t *state, tftp_event_t event) { CURLcode result = CURLE_OK; struct Curl_easy *data = state->conn->data; switch(state->state) { case TFTP_STATE_START: DEBUGF(infof(data, "TFTP_STATE_START\n")); result = tftp_send_first(state, event); break; case TFTP_STATE_RX: DEBUGF(infof(data, "TFTP_STATE_RX\n")); result = tftp_rx(state, event); break; case TFTP_STATE_TX: DEBUGF(infof(data, "TFTP_STATE_TX\n")); result = tftp_tx(state, event); break; case TFTP_STATE_FIN: infof(data, "%s\n", "TFTP finished"); break; default: DEBUGF(infof(data, "STATE: %d\n", state->state)); failf(data, "%s", "Internal state machine error"); result = CURLE_TFTP_ILLEGAL; break; } return result; } /********************************************************** * * tftp_disconnect * * The disconnect callback * **********************************************************/ static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection) { tftp_state_data_t *state = conn->proto.tftpc; (void) dead_connection; /* done, free dynamically allocated pkt buffers */ if(state) { Curl_safefree(state->rpacket.data); Curl_safefree(state->spacket.data); free(state); } return CURLE_OK; } /********************************************************** * * tftp_connect * * The connect callback * **********************************************************/ static CURLcode tftp_connect(struct connectdata *conn, bool *done) { tftp_state_data_t *state; int blksize; blksize = TFTP_BLKSIZE_DEFAULT; state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t)); if(!state) return CURLE_OUT_OF_MEMORY; /* alloc pkt buffers based on specified blksize */ if(conn->data->set.tftp_blksize) { blksize = (int)conn->data->set.tftp_blksize; if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN) return CURLE_TFTP_ILLEGAL; } if(!state->rpacket.data) { state->rpacket.data = calloc(1, blksize + 2 + 2); if(!state->rpacket.data) return CURLE_OUT_OF_MEMORY; } if(!state->spacket.data) { state->spacket.data = calloc(1, blksize + 2 + 2); if(!state->spacket.data) return CURLE_OUT_OF_MEMORY; } /* we don't keep TFTP connections up basically because there's none or very * little gain for UDP */ connclose(conn, "TFTP"); state->conn = conn; state->sockfd = state->conn->sock[FIRSTSOCKET]; state->state = TFTP_STATE_START; state->error = TFTP_ERR_NONE; state->blksize = blksize; state->requested_blksize = blksize; ((struct sockaddr *)&state->local_addr)->sa_family = (CURL_SA_FAMILY_T)(conn->ip_addr->ai_family); tftp_set_timeouts(state); if(!conn->bits.bound) { /* If not already bound, bind to any interface, random UDP port. If it is * reused or a custom local port was desired, this has already been done! * * We once used the size of the local_addr struct as the third argument * for bind() to better work with IPv6 or whatever size the struct could * have, but we learned that at least Tru64, AIX and IRIX *requires* the * size of that argument to match the exact size of a 'sockaddr_in' struct * when running IPv4-only. * * Therefore we use the size from the address we connected to, which we * assume uses the same IP version and thus hopefully this works for both * IPv4 and IPv6... */ int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr, conn->ip_addr->ai_addrlen); if(rc) { char buffer[STRERROR_LEN]; failf(conn->data, "bind() failed; %s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer))); return CURLE_COULDNT_CONNECT; } conn->bits.bound = TRUE; } Curl_pgrsStartNow(conn->data); *done = TRUE; return CURLE_OK; } /********************************************************** * * tftp_done * * The done callback * **********************************************************/ static CURLcode tftp_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode result = CURLE_OK; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; (void)status; /* unused */ (void)premature; /* not used */ if(Curl_pgrsDone(conn)) return CURLE_ABORTED_BY_CALLBACK; /* If we have encountered an error */ if(state) result = tftp_translate_code(state->error); return result; } /********************************************************** * * tftp_getsock * * The getsock callback * **********************************************************/ static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(!numsocks) return GETSOCK_BLANK; socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0); } /********************************************************** * * tftp_receive_packet * * Called once select fires and data is ready on the socket * **********************************************************/ static CURLcode tftp_receive_packet(struct connectdata *conn) { struct Curl_sockaddr_storage fromaddr; curl_socklen_t fromlen; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; struct SingleRequest *k = &data->req; /* Receive the packet */ fromlen = sizeof(fromaddr); state->rbytes = (int)recvfrom(state->sockfd, (void *)state->rpacket.data, state->blksize + 4, 0, (struct sockaddr *)&fromaddr, &fromlen); if(state->remote_addrlen == 0) { memcpy(&state->remote_addr, &fromaddr, fromlen); state->remote_addrlen = fromlen; } /* Sanity check packet length */ if(state->rbytes < 4) { failf(data, "Received too short packet"); /* Not a timeout, but how best to handle it? */ state->event = TFTP_EVENT_TIMEOUT; } else { /* The event is given by the TFTP packet time */ unsigned short event = getrpacketevent(&state->rpacket); state->event = (tftp_event_t)event; switch(state->event) { case TFTP_EVENT_DATA: /* Don't pass to the client empty or retransmitted packets */ if(state->rbytes > 4 && (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) { result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)state->rpacket.data + 4, state->rbytes-4); if(result) { tftp_state_machine(state, TFTP_EVENT_ERROR); return result; } k->bytecount += state->rbytes-4; Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount); } break; case TFTP_EVENT_ERROR: { unsigned short error = getrpacketblock(&state->rpacket); char *str = (char *)state->rpacket.data + 4; size_t strn = state->rbytes - 4; state->error = (tftp_error_t)error; if(Curl_strnlen(str, strn) < strn) infof(data, "TFTP error: %s\n", str); break; } case TFTP_EVENT_ACK: break; case TFTP_EVENT_OACK: result = tftp_parse_option_ack(state, (const char *)state->rpacket.data + 2, state->rbytes-2); if(result) return result; break; case TFTP_EVENT_RRQ: case TFTP_EVENT_WRQ: default: failf(data, "%s", "Internal error: Unexpected packet"); break; } /* Update the progress meter */ if(Curl_pgrsUpdate(conn)) { tftp_state_machine(state, TFTP_EVENT_ERROR); return CURLE_ABORTED_BY_CALLBACK; } } return result; } /********************************************************** * * tftp_state_timeout * * Check if timeouts have been reached * **********************************************************/ static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event) { time_t current; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; if(event) *event = TFTP_EVENT_NONE; time(&current); if(current > state->max_time) { DEBUGF(infof(conn->data, "timeout: %ld > %ld\n", (long)current, (long)state->max_time)); state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; return 0; } if(current > state->rx_time + state->retry_time) { if(event) *event = TFTP_EVENT_TIMEOUT; time(&state->rx_time); /* update even though we received nothing */ } /* there's a typecast below here since 'time_t' may in fact be larger than 'long', but we estimate that a 'long' will still be able to hold number of seconds even if "only" 32 bit */ return (long)(state->max_time - current); } /********************************************************** * * tftp_multi_statemach * * Handle single RX socket event and return * **********************************************************/ static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done) { tftp_event_t event; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; long timeout_ms = tftp_state_timeout(conn, &event); *done = FALSE; if(timeout_ms <= 0) { failf(data, "TFTP response timeout"); return CURLE_OPERATION_TIMEDOUT; } if(event != TFTP_EVENT_NONE) { result = tftp_state_machine(state, event); if(result) return result; *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; if(*done) /* Tell curl we're done */ Curl_setup_transfer(data, -1, -1, FALSE, -1); } else { /* no timeouts to handle, check our socket */ int rc = SOCKET_READABLE(state->sockfd, 0); if(rc == -1) { /* bail out */ int error = SOCKERRNO; char buffer[STRERROR_LEN]; failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer))); state->event = TFTP_EVENT_ERROR; } else if(rc != 0) { result = tftp_receive_packet(conn); if(result) return result; result = tftp_state_machine(state, state->event); if(result) return result; *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; if(*done) /* Tell curl we're done */ Curl_setup_transfer(data, -1, -1, FALSE, -1); } /* if rc == 0, then select() timed out */ } return result; } /********************************************************** * * tftp_doing * * Called from multi.c while DOing * **********************************************************/ static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = tftp_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } else if(!result) { /* The multi code doesn't have this logic for the DOING state so we provide it for TFTP since it may do the entire transfer in this state. */ if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(conn->data, Curl_now()); } return result; } /********************************************************** * * tftp_peform * * Entry point for transfer from tftp_do, sarts state mach * **********************************************************/ static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; *dophase_done = FALSE; result = tftp_state_machine(state, TFTP_EVENT_INIT); if((state->state == TFTP_STATE_FIN) || result) return result; tftp_multi_statemach(conn, dophase_done); if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; } /********************************************************** * * tftp_do * * The do callback * * This callback initiates the TFTP transfer * **********************************************************/ static CURLcode tftp_do(struct connectdata *conn, bool *done) { tftp_state_data_t *state; CURLcode result; *done = FALSE; if(!conn->proto.tftpc) { result = tftp_connect(conn, done); if(result) return result; } state = (tftp_state_data_t *)conn->proto.tftpc; if(!state) return CURLE_TFTP_ILLEGAL; result = tftp_perform(conn, done); /* If tftp_perform() returned an error, use that for return code. If it was OK, see if tftp_translate_code() has an error. */ if(!result) /* If we have encountered an internal tftp error, translate it. */ result = tftp_translate_code(state->error); return result; } static CURLcode tftp_setup_connection(struct connectdata * conn) { struct Curl_easy *data = conn->data; char *type; conn->socktype = SOCK_DGRAM; /* UDP datagram based */ /* TFTP URLs support an extension like ";mode=<typecode>" that * we'll try to get now! */ type = strstr(data->state.up.path, ";mode="); if(!type) type = strstr(conn->host.rawalloc, ";mode="); if(type) { char command; *type = 0; /* it was in the middle of the hostname */ command = Curl_raw_toupper(type[6]); switch(command) { case 'A': /* ASCII mode */ case 'N': /* NETASCII mode */ data->set.prefer_ascii = TRUE; break; case 'O': /* octet mode */ case 'I': /* binary mode */ default: /* switch off ASCII */ data->set.prefer_ascii = FALSE; break; } } return CURLE_OK; } #endif
YifuLiu/AliOS-Things
components/curl/lib/tftp.c
C
apache-2.0
42,136
#ifndef HEADER_CURL_TFTP_H #define HEADER_CURL_TFTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_TFTP extern const struct Curl_handler Curl_handler_tftp; #endif #endif /* HEADER_CURL_TFTP_H */
YifuLiu/AliOS-Things
components/curl/lib/tftp.h
C
apache-2.0
1,198
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "timeval.h" #if defined(WIN32) && !defined(MSDOS) /* set in win32_init() */ extern LARGE_INTEGER Curl_freq; extern bool Curl_isVistaOrGreater; 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__) && (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__) && (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 #if SIZEOF_TIME_T < 8 #define TIME_MAX INT_MAX #define TIME_MIN INT_MIN #else #define TIME_MAX 9223372036854775807LL #define TIME_MIN -9223372036854775807LL #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 >= (TIME_MAX/1000)) return TIME_MAX; else if(diff <= (TIME_MIN/1000)) return TIME_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 >= (TIME_MAX/1000000)) return TIME_MAX; else if(diff <= (TIME_MIN/1000000)) return TIME_MIN; return diff * 1000000 + newer.tv_usec-older.tv_usec; }
YifuLiu/AliOS-Things
components/curl/lib/timeval.c
C
apache-2.0
5,896
#ifndef HEADER_CURL_TIMEVAL_H #define HEADER_CURL_TIMEVAL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if SIZEOF_TIME_T < 8 typedef int timediff_t; #define CURL_FORMAT_TIMEDIFF_T "d" #else typedef curl_off_t timediff_t; #define CURL_FORMAT_TIMEDIFF_T CURL_FORMAT_CURL_OFF_T #endif struct curltime { time_t tv_sec; /* seconds */ int tv_usec; /* microseconds */ }; struct curltime Curl_now(void); /* * Make sure that the first argument (t1) is the more recent time and t2 is * the older time, as otherwise you get a weird negative time-diff back... * * Returns: the time difference in number of milliseconds. */ timediff_t Curl_timediff(struct curltime t1, struct curltime t2); /* * Make sure that the first argument (t1) is the more recent time and t2 is * the older time, as otherwise you get a weird negative time-diff back... * * Returns: the time difference in number of microseconds. */ timediff_t Curl_timediff_us(struct curltime newer, struct curltime older); #endif /* HEADER_CURL_TIMEVAL_H */
YifuLiu/AliOS-Things
components/curl/lib/timeval.h
C
apache-2.0
2,032
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "strtoofft.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #ifndef HAVE_SOCKET #error "We can't compile without socket() support!" #endif #include "urldata.h" #include <curl/curl.h> #include "netrc.h" #include "content_encoding.h" #include "hostip.h" #include "transfer.h" #include "sendf.h" #include "speedcheck.h" #include "progress.h" #include "http.h" #include "url.h" #include "getinfo.h" #include "vtls/vtls.h" #include "select.h" #include "multiif.h" #include "connect.h" #include "non-ascii.h" #include "http2.h" #include "mime.h" #include "strcase.h" #include "urlapi-int.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_IMAP) /* * checkheaders() checks the linked list of custom headers for a * particular header (prefix). Provide the prefix without colon! * * Returns a pointer to the first matching header or NULL if none matched. */ char *Curl_checkheaders(const struct connectdata *conn, const char *thisheader) { struct curl_slist *head; size_t thislen = strlen(thisheader); struct Curl_easy *data = conn->data; for(head = data->set.headers; head; head = head->next) { if(strncasecompare(head->data, thisheader, thislen) && Curl_headersep(head->data[thislen]) ) return head->data; } return NULL; } #endif CURLcode Curl_get_upload_buffer(struct Curl_easy *data) { if(!data->state.ulbuf) { data->state.ulbuf = malloc(data->set.upload_buffer_size); if(!data->state.ulbuf) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } #ifndef CURL_DISABLE_HTTP /* * This function will be called to loop through the trailers buffer * until no more data is available for sending. */ static size_t Curl_trailers_read(char *buffer, size_t size, size_t nitems, void *raw) { struct Curl_easy *data = (struct Curl_easy *)raw; Curl_send_buffer *trailers_buf = data->state.trailers_buf; size_t bytes_left = trailers_buf->size_used-data->state.trailers_bytes_sent; size_t to_copy = (size*nitems < bytes_left) ? size*nitems : bytes_left; if(to_copy) { memcpy(buffer, &trailers_buf->buffer[data->state.trailers_bytes_sent], to_copy); data->state.trailers_bytes_sent += to_copy; } return to_copy; } static size_t Curl_trailers_left(void *raw) { struct Curl_easy *data = (struct Curl_easy *)raw; Curl_send_buffer *trailers_buf = data->state.trailers_buf; return trailers_buf->size_used - data->state.trailers_bytes_sent; } #endif /* * This function will call the read callback to fill our buffer with data * to upload. */ CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes, size_t *nreadp) { struct Curl_easy *data = conn->data; size_t buffersize = bytes; size_t nread; curl_read_callback readfunc = NULL; void *extra_data = NULL; #ifdef CURL_DOES_CONVERSIONS bool sending_http_headers = FALSE; if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { const struct HTTP *http = data->req.protop; if(http->sending == HTTPSEND_REQUEST) /* We're sending the HTTP request headers, not the data. Remember that so we don't re-translate them into garbage. */ sending_http_headers = TRUE; } #endif #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_INITIALIZED) { struct curl_slist *trailers = NULL; CURLcode c; int trailers_ret_code; /* at this point we already verified that the callback exists so we compile and store the trailers buffer, then proceed */ infof(data, "Moving trailers state machine from initialized to sending.\n"); data->state.trailers_state = TRAILERS_SENDING; data->state.trailers_buf = Curl_add_buffer_init(); if(!data->state.trailers_buf) { failf(data, "Unable to allocate trailing headers buffer !"); return CURLE_OUT_OF_MEMORY; } data->state.trailers_bytes_sent = 0; Curl_set_in_callback(data, true); trailers_ret_code = data->set.trailer_callback(&trailers, data->set.trailer_data); Curl_set_in_callback(data, false); if(trailers_ret_code == CURL_TRAILERFUNC_OK) { c = Curl_http_compile_trailers(trailers, data->state.trailers_buf, data); } else { failf(data, "operation aborted by trailing headers callback"); *nreadp = 0; c = CURLE_ABORTED_BY_CALLBACK; } if(c != CURLE_OK) { Curl_add_buffer_free(&data->state.trailers_buf); curl_slist_free_all(trailers); return c; } infof(data, "Successfully compiled trailers.\r\n"); curl_slist_free_all(trailers); } #endif /* if we are transmitting trailing data, we don't need to write a chunk size so we skip this */ if(data->req.upload_chunky && data->state.trailers_state == TRAILERS_NONE) { /* if chunked Transfer-Encoding */ buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */ data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */ } #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_SENDING) { /* if we're here then that means that we already sent the last empty chunk but we didn't send a final CR LF, so we sent 0 CR LF. We then start pulling trailing data until we ²have no more at which point we simply return to the previous point in the state machine as if nothing happened. */ readfunc = Curl_trailers_read; extra_data = (void *)data; } else #endif { readfunc = data->state.fread_func; extra_data = data->state.in; } Curl_set_in_callback(data, true); nread = readfunc(data->req.upload_fromhere, 1, buffersize, extra_data); Curl_set_in_callback(data, false); if(nread == CURL_READFUNC_ABORT) { failf(data, "operation aborted by callback"); *nreadp = 0; return CURLE_ABORTED_BY_CALLBACK; } if(nread == CURL_READFUNC_PAUSE) { struct SingleRequest *k = &data->req; 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, "Read callback asked for PAUSE when not supported!"); return CURLE_READ_ERROR; } /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */ if(data->req.upload_chunky) { /* Back out the preallocation done above */ data->req.upload_fromhere -= (8 + 2); } *nreadp = 0; return CURLE_OK; /* nothing was read */ } else if(nread > buffersize) { /* the read function returned a too large value */ *nreadp = 0; failf(data, "read function returned funny value"); return CURLE_READ_ERROR; } if(!data->req.forbidchunk && data->req.upload_chunky) { /* if chunked Transfer-Encoding * build chunk: * * <HEX SIZE> CRLF * <DATA> CRLF */ /* On non-ASCII platforms the <DATA> may or may not be translated based on set.prefer_ascii while the protocol portion must always be translated to the network encoding. To further complicate matters, line end conversion might be done later on, so we need to prevent CRLFs from becoming CRCRLFs if that's the case. To do this we use bare LFs here, knowing they'll become CRLFs later on. */ bool added_crlf = FALSE; int hexlen = 0; const char *endofline_native; const char *endofline_network; if( #ifdef CURL_DO_LINEEND_CONV (data->set.prefer_ascii) || #endif (data->set.crlf)) { /* \n will become \r\n later on */ endofline_native = "\n"; endofline_network = "\x0a"; } else { endofline_native = "\r\n"; endofline_network = "\x0d\x0a"; } /* if we're not handling trailing data, proceed as usual */ if(data->state.trailers_state != TRAILERS_SENDING) { char hexbuffer[11] = ""; hexlen = msnprintf(hexbuffer, sizeof(hexbuffer), "%zx%s", nread, endofline_native); if ( hexlen == -1 ) { failf(data, "msnprintf len error"); return CURLE_READ_ERROR; } /* move buffer pointer */ data->req.upload_fromhere -= hexlen; nread += hexlen; /* copy the prefix to the buffer, leaving out the NUL */ memcpy(data->req.upload_fromhere, hexbuffer, hexlen); /* always append ASCII CRLF to the data unless we have a valid trailer callback */ #ifndef CURL_DISABLE_HTTP if((nread-hexlen) == 0 && data->set.trailer_callback != NULL && data->state.trailers_state == TRAILERS_NONE) { data->state.trailers_state = TRAILERS_INITIALIZED; } else #endif { memcpy(data->req.upload_fromhere + nread, endofline_network, strlen(endofline_network)); added_crlf = TRUE; } } #ifdef CURL_DOES_CONVERSIONS { CURLcode result; size_t length; if(data->set.prefer_ascii) /* translate the protocol and data */ length = nread; else /* just translate the protocol portion */ length = hexlen; if(length) { result = Curl_convert_to_network(data, data->req.upload_fromhere, length); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; } } #endif /* CURL_DOES_CONVERSIONS */ #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_SENDING && !Curl_trailers_left(data)) { Curl_add_buffer_free(&data->state.trailers_buf); data->state.trailers_state = TRAILERS_DONE; data->set.trailer_data = NULL; data->set.trailer_callback = NULL; /* mark the transfer as done */ data->req.upload_done = TRUE; infof(data, "Signaling end of chunked upload after trailers.\n"); } else #endif if((nread - hexlen) == 0 && data->state.trailers_state != TRAILERS_INITIALIZED) { /* mark this as done once this chunk is transferred */ data->req.upload_done = TRUE; infof(data, "Signaling end of chunked upload via terminating chunk.\n"); } if(added_crlf) nread += strlen(endofline_network); /* for the added end of line */ } #ifdef CURL_DOES_CONVERSIONS else if((data->set.prefer_ascii) && (!sending_http_headers)) { CURLcode result; result = Curl_convert_to_network(data, data->req.upload_fromhere, nread); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; } #endif /* CURL_DOES_CONVERSIONS */ *nreadp = nread; return CURLE_OK; } /* * Curl_readrewind() rewinds the read stream. This is typically used for HTTP * POST/PUT with multi-pass authentication when a sending was denied and a * resend is necessary. */ CURLcode Curl_readrewind(struct connectdata *conn) { struct Curl_easy *data = conn->data; curl_mimepart *mimepart = &data->set.mimepost; conn->bits.rewindaftersend = FALSE; /* we rewind now */ /* explicitly switch off sending data on this connection now since we are about to restart a new transfer and thus we want to avoid inadvertently sending more data on the existing connection until the next transfer starts */ data->req.keepon &= ~KEEP_SEND; /* We have sent away data. If not using CURLOPT_POSTFIELDS or CURLOPT_HTTPPOST, call app to rewind */ if(conn->handler->protocol & PROTO_FAMILY_HTTP) { struct HTTP *http = data->req.protop; if(http->sendit) mimepart = http->sendit; } if(data->set.postfields) ; /* do nothing */ else if(data->set.httpreq == HTTPREQ_POST_MIME || data->set.httpreq == HTTPREQ_POST_FORM) { if(Curl_mime_rewind(mimepart)) { failf(data, "Cannot rewind mime/post data"); return CURLE_SEND_FAIL_REWIND; } } else { if(data->set.seek_func) { int err; Curl_set_in_callback(data, true); err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET); Curl_set_in_callback(data, false); if(err) { failf(data, "seek callback returned error %d", (int)err); return CURLE_SEND_FAIL_REWIND; } } else if(data->set.ioctl_func) { curlioerr err; Curl_set_in_callback(data, true); err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD, data->set.ioctl_client); Curl_set_in_callback(data, false); infof(data, "the ioctl callback returned %d\n", (int)err); if(err) { failf(data, "ioctl callback returned error %d", (int)err); return CURLE_SEND_FAIL_REWIND; } } else { /* If no CURLOPT_READFUNCTION is used, we know that we operate on a given FILE * stream and we can actually attempt to rewind that ourselves with fseek() */ if(data->state.fread_func == (curl_read_callback)fread) { if(-1 != fseek(data->state.in, 0, SEEK_SET)) /* successful rewind */ return CURLE_OK; } /* no callback set or failure above, makes us fail at once */ failf(data, "necessary data rewind wasn't possible"); return CURLE_SEND_FAIL_REWIND; } } return CURLE_OK; } static int data_pending(const struct connectdata *conn) { /* in the case of libssh2, we can never be really sure that we have emptied its internal buffers so we MUST always try until we get EAGAIN back */ return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) || #if defined(USE_NGHTTP2) Curl_ssl_data_pending(conn, FIRSTSOCKET) || /* For HTTP/2, we may read up everything including response body with header fields in Curl_http_readwrite_headers. If no content-length is provided, curl waits for the connection close, which we emulate it using conn->proto.httpc.closed = TRUE. The thing is if we read everything, then http2_recv won't be called and we cannot signal the HTTP/2 stream has closed. As a workaround, we return nonzero here to call http2_recv. */ ((conn->handler->protocol&PROTO_FAMILY_HTTP) && conn->httpversion == 20); #else Curl_ssl_data_pending(conn, FIRSTSOCKET); #endif } /* * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the * remote document with the time provided by CURLOPT_TIMEVAL */ bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc) { if((timeofdoc == 0) || (data->set.timevalue == 0)) return TRUE; switch(data->set.timecondition) { case CURL_TIMECOND_IFMODSINCE: default: if(timeofdoc <= data->set.timevalue) { infof(data, "The requested document is not new enough\n"); data->info.timecond = TRUE; return FALSE; } break; case CURL_TIMECOND_IFUNMODSINCE: if(timeofdoc >= data->set.timevalue) { infof(data, "The requested document is not old enough\n"); data->info.timecond = TRUE; return FALSE; } break; } return TRUE; } /* * Go ahead and do a read if we have a readable socket or if * the stream was rewound (in which case we have data in a * buffer) * * return '*comeback' TRUE if we didn't properly drain the socket so this * function should get called again without select() or similar in between! */ static CURLcode readwrite_data(struct Curl_easy *data, struct connectdata *conn, struct SingleRequest *k, int *didwhat, bool *done, bool *comeback) { CURLcode result = CURLE_OK; ssize_t nread; /* number of bytes read */ size_t excess = 0; /* excess bytes read */ bool readmore = FALSE; /* used by RTP to signal for more data */ int maxloops = 100; *done = FALSE; *comeback = FALSE; /* This is where we loop until we have read everything there is to read or we get a CURLE_AGAIN */ do { bool is_empty_data = FALSE; size_t buffersize = data->set.buffer_size; size_t bytestoread = buffersize; if( #if defined(USE_NGHTTP2) /* For HTTP/2, read data without caring about the content length. This is safe because body in HTTP/2 is always segmented thanks to its framing layer. Meanwhile, we have to call Curl_read to ensure that http2_handle_stream_close is called when we read all incoming bytes for a particular stream. */ !((conn->handler->protocol & PROTO_FAMILY_HTTP) && conn->httpversion == 20) && #endif k->size != -1 && !k->header) { /* make sure we don't read too much */ curl_off_t totalleft = k->size - k->bytecount; if(totalleft < (curl_off_t)bytestoread) bytestoread = (size_t)totalleft; } if(bytestoread) { /* receive data from the network! */ result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread); /* read would've blocked */ if(CURLE_AGAIN == result) break; /* get out of loop */ if(result>0) return result; } else { /* read nothing but since we wanted nothing we consider this an OK situation to proceed from */ DEBUGF(infof(data, "readwrite_data: we're done!\n")); nread = 0; } if((k->bytecount == 0) && (k->writebytecount == 0)) { Curl_pgrsTime(data, TIMER_STARTTRANSFER); if(k->exp100 > EXP100_SEND_DATA) /* set time stamp to compare with when waiting for the 100 */ k->start100 = Curl_now(); } *didwhat |= KEEP_RECV; /* indicates data of zero size, i.e. empty file */ is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE; /* NUL terminate, allowing string ops to be used */ if(0 < nread || is_empty_data) { k->buf[nread] = 0; } else { /* if we receive 0 or less here, the server closed the connection and we bail out from this! */ DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n")); k->keepon &= ~KEEP_RECV; break; } /* Default buffer to use when we write the buffer, it may be changed in the flow below before the actual storing is done. */ k->str = k->buf; if(conn->handler->readwrite) { result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) break; } #ifndef CURL_DISABLE_HTTP /* Since this is a two-state thing, we check if we are parsing headers at the moment or not. */ if(k->header) { /* we are in parse-the-header-mode */ bool stop_reading = FALSE; result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading); if(result) return result; if(conn->handler->readwrite && (k->maxdownload <= 0 && nread > 0)) { result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) break; } if(stop_reading) { /* We've stopped dealing with input, get out of the do-while loop */ if(nread > 0) { infof(data, "Excess found:" " excess = %zd" " url = %s (zero-length body)\n", nread, data->state.up.path); } break; } } #endif /* CURL_DISABLE_HTTP */ /* This is not an 'else if' since it may be a rest from the header parsing, where the beginning of the buffer is headers and the end is non-headers. */ if(k->str && !k->header && (nread > 0 || is_empty_data)) { if(data->set.opt_no_body) { /* data arrives although we want none, bail out */ streamclose(conn, "ignoring body"); *done = TRUE; return CURLE_WEIRD_SERVER_REPLY; } #ifndef CURL_DISABLE_HTTP if(0 == k->bodywrites && !is_empty_data) { /* These checks are only made the first time we are about to write a piece of the body */ if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { /* HTTP-only checks */ if(data->req.newurl) { if(conn->bits.close) { /* Abort after the headers if "follow Location" is set and we're set to close anyway. */ k->keepon &= ~KEEP_RECV; *done = TRUE; return CURLE_OK; } /* We have a new url to load, but since we want to be able to re-use this connection properly, we read the full response in "ignore more" */ k->ignorebody = TRUE; infof(data, "Ignoring the response-body\n"); } if(data->state.resume_from && !k->content_range && (data->set.httpreq == HTTPREQ_GET) && !k->ignorebody) { if(k->size == data->state.resume_from) { /* The resume point is at the end of file, consider this fine even if it doesn't allow resume from here. */ infof(data, "The entire document is already downloaded"); connclose(conn, "already downloaded"); /* Abort download */ k->keepon &= ~KEEP_RECV; *done = TRUE; return CURLE_OK; } /* we wanted to resume a download, although the server doesn't * seem to support this and we did this with a GET (if it * wasn't a GET we did a POST or PUT resume) */ failf(data, "HTTP server doesn't seem to support " "byte ranges. Cannot resume."); return CURLE_RANGE_ERROR; } if(data->set.timecondition && !data->state.range) { /* A time condition has been set AND no ranges have been requested. This seems to be what chapter 13.3.4 of RFC 2616 defines to be the correct action for a HTTP/1.1 client */ if(!Curl_meets_timecondition(data, k->timeofdoc)) { *done = TRUE; /* We're simulating a http 304 from server so we return what should have been returned from the server */ data->info.httpcode = 304; infof(data, "Simulate a HTTP 304 response!\n"); /* we abort the transfer before it is completed == we ruin the re-use ability. Close the connection */ connclose(conn, "Simulated 304 handling"); return CURLE_OK; } } /* we have a time condition */ } /* this is HTTP or RTSP */ } /* this is the first time we write a body part */ #endif /* CURL_DISABLE_HTTP */ k->bodywrites++; /* pass data to the debug function before it gets "dechunked" */ if(data->set.verbose) { if(k->badheader) { Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff, (size_t)k->hbuflen); if(k->badheader == HEADER_PARTHEADER) Curl_debug(data, CURLINFO_DATA_IN, k->str, (size_t)nread); } else Curl_debug(data, CURLINFO_DATA_IN, k->str, (size_t)nread); } #ifndef CURL_DISABLE_HTTP if(k->chunk) { /* * Here comes a chunked transfer flying and we need to decode this * properly. While the name says read, this function both reads * and writes away the data. The returned 'nread' holds the number * of actual data it wrote to the client. */ CHUNKcode res = Curl_httpchunk_read(conn, k->str, nread, &nread); if(CHUNKE_OK < res) { if(CHUNKE_WRITE_ERROR == res) { failf(data, "Failed writing data"); return CURLE_WRITE_ERROR; } failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res)); return CURLE_RECV_ERROR; } if(CHUNKE_STOP == res) { size_t dataleft; /* we're done reading chunks! */ k->keepon &= ~KEEP_RECV; /* read no more */ /* There are now possibly N number of bytes at the end of the str buffer that weren't written to the client. Push it back to be read on the next pass. */ dataleft = conn->chunk.dataleft; if(dataleft != 0) { infof(conn->data, "Leftovers after chunking: %zu bytes\n", dataleft); } } /* If it returned OK, we just keep going */ } #endif /* CURL_DISABLE_HTTP */ /* Account for body content stored in the header buffer */ if((k->badheader == HEADER_PARTHEADER) && !k->ignorebody) { DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n", k->hbuflen)); k->bytecount += k->hbuflen; } if((-1 != k->maxdownload) && (k->bytecount + nread >= k->maxdownload)) { excess = (size_t)(k->bytecount + nread - k->maxdownload); if(excess > 0 && !k->ignorebody) { infof(data, "Excess found in a read:" " excess = %zu" ", size = %" CURL_FORMAT_CURL_OFF_T ", maxdownload = %" CURL_FORMAT_CURL_OFF_T ", bytecount = %" CURL_FORMAT_CURL_OFF_T "\n", excess, k->size, k->maxdownload, k->bytecount); } nread = (ssize_t) (k->maxdownload - k->bytecount); if(nread < 0) /* this should be unusual */ nread = 0; k->keepon &= ~KEEP_RECV; /* we're done reading */ } k->bytecount += nread; Curl_pgrsSetDownloadCounter(data, k->bytecount); if(!k->chunk && (nread || k->badheader || is_empty_data)) { /* If this is chunky transfer, it was already written */ if(k->badheader && !k->ignorebody) { /* we parsed a piece of data wrongly assuming it was a header and now we output it as body instead */ /* Don't let excess data pollute body writes */ if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload) result = Curl_client_write(conn, CLIENTWRITE_BODY, data->state.headerbuff, k->hbuflen); else result = Curl_client_write(conn, CLIENTWRITE_BODY, data->state.headerbuff, (size_t)k->maxdownload); if(result) return result; } if(k->badheader < HEADER_ALLBAD) { /* This switch handles various content encodings. If there's an error here, be sure to check over the almost identical code in http_chunks.c. Make sure that ALL_CONTENT_ENCODINGS contains all the encodings handled here. */ if(conn->data->set.http_ce_skip || !k->writer_stack) { if(!k->ignorebody) { #ifndef CURL_DISABLE_POP3 if(conn->handler->protocol & PROTO_FAMILY_POP3) result = Curl_pop3_write(conn, k->str, nread); else #endif /* CURL_DISABLE_POP3 */ result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str, nread); } } else if(!k->ignorebody) result = Curl_unencode_write(conn, k->writer_stack, k->str, nread); } k->badheader = HEADER_NORMAL; /* taken care of now */ if(result) return result; } } /* if(!header and data to read) */ if(conn->handler->readwrite && excess && !conn->bits.stream_was_rewound) { /* Parse the excess data */ k->str += nread; if(&k->str[excess] > &k->buf[data->set.buffer_size]) { /* the excess amount was too excessive(!), make sure it doesn't read out of buffer */ excess = &k->buf[data->set.buffer_size] - k->str; } nread = (ssize_t)excess; result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) k->keepon |= KEEP_RECV; /* we're not done reading */ break; } if(is_empty_data) { /* if we received nothing, the server closed the connection and we are done */ k->keepon &= ~KEEP_RECV; } if(k->keepon & KEEP_RECV_PAUSE) { /* this is a paused transfer */ break; } } while(data_pending(conn) && maxloops--); if(maxloops <= 0) { /* we mark it as read-again-please */ conn->cselect_bits = CURL_CSELECT_IN; *comeback = TRUE; } if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) && conn->bits.close) { /* When we've read the entire thing and the close bit is set, the server may now close the connection. If there's now any kind of sending going on from our side, we need to stop that immediately. */ infof(data, "we are done reading and this is set to close, stop send\n"); k->keepon &= ~KEEP_SEND; /* no writing anymore either */ } return CURLE_OK; } static CURLcode done_sending(struct connectdata *conn, struct SingleRequest *k) { k->keepon &= ~KEEP_SEND; /* we're done writing */ Curl_http2_done_sending(conn); if(conn->bits.rewindaftersend) { CURLcode result = Curl_readrewind(conn); if(result) return result; } return CURLE_OK; } #if defined(WIN32) && !defined(USE_LWIPSOCK) #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B #endif static void win_update_buffer_size(curl_socket_t sockfd) { int result; ULONG ideal; DWORD ideallen; result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0, &ideal, sizeof(ideal), &ideallen, 0, 0); if(result == 0) { setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&ideal, sizeof(ideal)); } } #else #define win_update_buffer_size(x) #endif /* * Send data to upload to the server, when the socket is writable. */ static CURLcode readwrite_upload(struct Curl_easy *data, struct connectdata *conn, int *didwhat) { ssize_t i, si; ssize_t bytes_written; CURLcode result; ssize_t nread; /* number of bytes read */ bool sending_http_headers = FALSE; struct SingleRequest *k = &data->req; if((k->bytecount == 0) && (k->writebytecount == 0)) Curl_pgrsTime(data, TIMER_STARTTRANSFER); *didwhat |= KEEP_SEND; do { /* only read more data if there's no upload data already present in the upload buffer */ if(0 == k->upload_present) { result = Curl_get_upload_buffer(data); if(result) return result; /* init the "upload from here" pointer */ k->upload_fromhere = data->state.ulbuf; if(!k->upload_done) { /* HTTP pollution, this should be written nicer to become more protocol agnostic. */ size_t fillcount; struct HTTP *http = k->protop; if((k->exp100 == EXP100_SENDING_REQUEST) && (http->sending == HTTPSEND_BODY)) { /* If this call is to send body data, we must take some action: We have sent off the full HTTP 1.1 request, and we shall now go into the Expect: 100 state and await such a header */ k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */ k->keepon &= ~KEEP_SEND; /* disable writing */ k->start100 = Curl_now(); /* timeout count starts now */ *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */ /* set a timeout for the multi interface */ Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT); break; } if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { if(http->sending == HTTPSEND_REQUEST) /* We're sending the HTTP request headers, not the data. Remember that so we don't change the line endings. */ sending_http_headers = TRUE; else sending_http_headers = FALSE; } result = Curl_fillreadbuffer(conn, data->set.upload_buffer_size, &fillcount); if(result) return result; nread = fillcount; } else nread = 0; /* we're done uploading/reading */ if(!nread && (k->keepon & KEEP_SEND_PAUSE)) { /* this is a paused transfer */ break; } if(nread <= 0) { result = done_sending(conn, k); if(result) return result; break; } /* store number of bytes available for upload */ k->upload_present = nread; /* convert LF to CRLF if so asked */ if((!sending_http_headers) && ( #ifdef CURL_DO_LINEEND_CONV /* always convert if we're FTPing in ASCII mode */ (data->set.prefer_ascii) || #endif (data->set.crlf))) { /* Do we need to allocate a scratch buffer? */ if(!data->state.scratch) { data->state.scratch = malloc(2 * data->set.upload_buffer_size); if(!data->state.scratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } /* * ASCII/EBCDIC Note: This is presumably a text (not binary) * transfer so the data should already be in ASCII. * That means the hex values for ASCII CR (0x0d) & LF (0x0a) * must be used instead of the escape sequences \r & \n. */ for(i = 0, si = 0; i < nread; i++, si++) { if(k->upload_fromhere[i] == 0x0a) { data->state.scratch[si++] = 0x0d; data->state.scratch[si] = 0x0a; if(!data->set.crlf) { /* we're here only because FTP is in ASCII mode... bump infilesize for the LF we just added */ if(data->state.infilesize != -1) data->state.infilesize++; } } else data->state.scratch[si] = k->upload_fromhere[i]; } if(si != nread) { /* only perform the special operation if we really did replace anything */ nread = si; /* upload from the new (replaced) buffer instead */ k->upload_fromhere = data->state.scratch; /* set the new amount too */ k->upload_present = nread; } } #ifndef CURL_DISABLE_SMTP if(conn->handler->protocol & PROTO_FAMILY_SMTP) { result = Curl_smtp_escape_eob(conn, nread); if(result) return result; } #endif /* CURL_DISABLE_SMTP */ } /* if 0 == k->upload_present */ else { /* We have a partial buffer left from a previous "round". Use that instead of reading more data */ } /* write to socket (send away data) */ result = Curl_write(conn, conn->writesockfd, /* socket to send to */ k->upload_fromhere, /* buffer pointer */ k->upload_present, /* buffer size */ &bytes_written); /* actually sent */ if(result) return result; win_update_buffer_size(conn->writesockfd); if(data->set.verbose) /* show the data before we change the pointer upload_fromhere */ Curl_debug(data, CURLINFO_DATA_OUT, k->upload_fromhere, (size_t)bytes_written); k->writebytecount += bytes_written; Curl_pgrsSetUploadCounter(data, k->writebytecount); if((!k->upload_chunky || k->forbidchunk) && (k->writebytecount == data->state.infilesize)) { /* we have sent all data we were supposed to */ k->upload_done = TRUE; infof(data, "We are completely uploaded and fine\n"); } if(k->upload_present != bytes_written) { /* we only wrote a part of the buffer (if anything), deal with it! */ /* store the amount of bytes left in the buffer to write */ k->upload_present -= bytes_written; /* advance the pointer where to find the buffer when the next send is to happen */ k->upload_fromhere += bytes_written; } else { /* we've uploaded that buffer now */ result = Curl_get_upload_buffer(data); if(result) return result; k->upload_fromhere = data->state.ulbuf; k->upload_present = 0; /* no more bytes left */ if(k->upload_done) { result = done_sending(conn, k); if(result) return result; } } } WHILE_FALSE; /* just to break out from! */ return CURLE_OK; } /* * Curl_readwrite() is the low-level function to be called when data is to * be read and written to/from the connection. * * return '*comeback' TRUE if we didn't properly drain the socket so this * function should get called again without select() or similar in between! */ CURLcode Curl_readwrite(struct connectdata *conn, struct Curl_easy *data, bool *done, bool *comeback) { struct SingleRequest *k = &data->req; CURLcode result; int didwhat = 0; curl_socket_t fd_read; curl_socket_t fd_write; int select_res = conn->cselect_bits; conn->cselect_bits = 0; /* only use the proper socket if the *_HOLD bit is not set simultaneously as then we are in rate limiting state in that transfer direction */ if((k->keepon & KEEP_RECVBITS) == KEEP_RECV) fd_read = conn->sockfd; else fd_read = CURL_SOCKET_BAD; if((k->keepon & KEEP_SENDBITS) == KEEP_SEND) fd_write = conn->writesockfd; else fd_write = CURL_SOCKET_BAD; if(conn->data->state.drain) { select_res |= CURL_CSELECT_IN; DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data\n")); } if(!select_res) /* Call for select()/poll() only, if read/write/error status is not known. */ select_res = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0); if(select_res == CURL_CSELECT_ERR) { failf(data, "select/poll returned error"); return CURLE_SEND_ERROR; } /* We go ahead and do a read if we have a readable socket or if the stream was rewound (in which case we have data in a buffer) */ if((k->keepon & KEEP_RECV) && ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) { result = readwrite_data(data, conn, k, &didwhat, done, comeback); if(result || *done) return result; } /* If we still have writing to do, we check if we have a writable socket. */ if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) { /* write */ result = readwrite_upload(data, conn, &didwhat); if(result) return result; } k->now = Curl_now(); if(didwhat) { ; } else { /* no read no write, this is a timeout? */ if(k->exp100 == EXP100_AWAITING_CONTINUE) { /* This should allow some time for the header to arrive, but only a very short time as otherwise it'll be too much wasted time too often. */ /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status": Therefore, when a client sends this header field to an origin server (possibly via a proxy) from which it has never seen a 100 (Continue) status, the client SHOULD NOT wait for an indefinite period before sending the request body. */ timediff_t ms = Curl_timediff(k->now, k->start100); if(ms >= data->set.expect_100_timeout) { /* we've waited long enough, continue anyway */ k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; Curl_expire_done(data, EXPIRE_100_TIMEOUT); infof(data, "Done waiting for 100-continue\n"); } } } if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, k->now); if(result) return result; if(k->keepon) { if(0 > Curl_timeleft(data, &k->now, FALSE)) { if(k->size != -1) { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(k->now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(k->now, data->progress.t_startsingle), k->bytecount); } return CURLE_OPERATION_TIMEDOUT; } } else { /* * The transfer has been performed. Just make some general checks before * returning. */ if(!(data->set.opt_no_body) && (k->size != -1) && (k->bytecount != k->size) && #ifdef CURL_DO_LINEEND_CONV /* Most FTP servers don't adjust their file SIZE response for CRLFs, so we'll check to see if the discrepancy can be explained by the number of CRLFs we've changed to LFs. */ (k->bytecount != (k->size + data->state.crlf_conversions)) && #endif /* CURL_DO_LINEEND_CONV */ !k->newurl) { failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T " bytes remaining to read", k->size - k->bytecount); return CURLE_PARTIAL_FILE; } if(!(data->set.opt_no_body) && k->chunk && (conn->chunk.state != CHUNK_STOP)) { /* * In chunked mode, return an error if the connection is closed prior to * the empty (terminating) chunk is read. * * The condition above used to check for * conn->proto.http->chunk.datasize != 0 which is true after reading * *any* chunk, not just the empty chunk. * */ failf(data, "transfer closed with outstanding read data remaining"); return CURLE_PARTIAL_FILE; } if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; } /* Now update the "done" boolean we return */ *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND| KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE; return CURLE_OK; } /* * Curl_single_getsock() gets called by the multi interface code when the app * has requested to get the sockets for the current connection. This function * will then be called once for every connection that the multi interface * keeps track of. This function will only be called for connections that are * in the proper state to have this information available. */ int Curl_single_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { const struct Curl_easy *data = conn->data; int bitmap = GETSOCK_BLANK; unsigned sockindex = 0; if(conn->handler->perform_getsock) return conn->handler->perform_getsock(conn, sock, numsocks); if(numsocks < 2) /* simple check but we might need two slots */ return GETSOCK_BLANK; /* don't include HOLD and PAUSE connections */ if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) { DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD); bitmap |= GETSOCK_READSOCK(sockindex); sock[sockindex] = conn->sockfd; } /* don't include HOLD and PAUSE connections */ if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) { if((conn->sockfd != conn->writesockfd) || bitmap == GETSOCK_BLANK) { /* only if they are not the same socket and we have a readable one, we increase index */ if(bitmap != GETSOCK_BLANK) sockindex++; /* increase index if we need two entries */ DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD); sock[sockindex] = conn->writesockfd; } bitmap |= GETSOCK_WRITESOCK(sockindex); } return bitmap; } /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT which means this gets called once for each subsequent redirect etc */ void Curl_init_CONNECT(struct Curl_easy *data) { data->state.fread_func = data->set.fread_func_set; data->state.in = data->set.in_set; } /* * Curl_pretransfer() is called immediately before a transfer starts, and only * once for one transfer no matter if it has redirects or do multi-pass * authentication etc. */ CURLcode Curl_pretransfer(struct Curl_easy *data) { CURLcode result; if(!data->change.url && !data->set.uh) { /* we can't do anything without URL */ failf(data, "No URL set!"); return CURLE_URL_MALFORMAT; } /* since the URL may have been redirected in a previous use of this handle */ if(data->change.url_alloc) { /* the already set URL is allocated, free it first! */ Curl_safefree(data->change.url); data->change.url_alloc = FALSE; } if(!data->change.url && data->set.uh) { CURLUcode uc; uc = curl_url_get(data->set.uh, CURLUPART_URL, &data->set.str[STRING_SET_URL], 0); if(uc) { failf(data, "No URL set!"); return CURLE_URL_MALFORMAT; } } data->change.url = data->set.str[STRING_SET_URL]; /* Init the SSL session ID cache here. We do it here since we want to do it after the *_setopt() calls (that could specify the size of the cache) but before any transfer takes place. */ result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions); if(result) return result; data->state.wildcardmatch = data->set.wildcard_enabled; data->set.followlocation = 0; /* reset the location-follow counter */ data->state.this_is_a_follow = FALSE; /* reset this */ data->state.errorbuf = FALSE; /* no error has occurred */ data->state.httpversion = 0; /* don't assume any particular server version */ data->state.authproblem = FALSE; data->state.authhost.want = data->set.httpauth; data->state.authproxy.want = data->set.proxyauth; Curl_safefree(data->info.wouldredirect); data->info.wouldredirect = NULL; if(data->set.httpreq == HTTPREQ_PUT) data->state.infilesize = data->set.filesize; else if((data->set.httpreq != HTTPREQ_GET) && (data->set.httpreq != HTTPREQ_HEAD)) { data->state.infilesize = data->set.postfieldsize; if(data->set.postfields && (data->state.infilesize == -1)) data->state.infilesize = (curl_off_t)strlen(data->set.postfields); } else data->state.infilesize = 0; /* If there is a list of cookie files to read, do it now! */ if(data->change.cookielist) Curl_cookie_loadfiles(data); /* If there is a list of host pairs to deal with */ if(data->change.resolve) result = Curl_loadhostpairs(data); if(!result) { /* Allow data->set.use_port to set which port to use. This needs to be * disabled for example when we follow Location: headers to URLs using * different ports! */ data->state.allow_port = TRUE; #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) /************************************************************* * Tell signal handler to ignore SIGPIPE *************************************************************/ if(!data->set.no_signal) data->state.prev_signal = signal(SIGPIPE, SIG_IGN); #endif Curl_initinfo(data); /* reset session-specific information "variables" */ Curl_pgrsResetTransferSizes(data); Curl_pgrsStartNow(data); /* In case the handle is re-used and an authentication method was picked in the session we need to make sure we only use the one(s) we now consider to be fine */ data->state.authhost.picked &= data->state.authhost.want; data->state.authproxy.picked &= data->state.authproxy.want; #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state < CURLWC_INIT) { result = Curl_wildcard_init(wc); /* init wildcard structures */ if(result) return CURLE_OUT_OF_MEMORY; } } #endif } return result; } /* * Curl_posttransfer() is called immediately after a transfer ends */ CURLcode Curl_posttransfer(struct Curl_easy *data) { #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) /* restore the signal handler for SIGPIPE before we get back */ if(!data->set.no_signal) signal(SIGPIPE, data->state.prev_signal); #else (void)data; /* unused parameter */ #endif return CURLE_OK; } /* * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string * as given by the remote server and set up the new URL to request. * * This function DOES NOT FREE the given url. */ CURLcode Curl_follow(struct Curl_easy *data, char *newurl, /* the Location: string */ followtype type) /* see transfer.h */ { #ifdef CURL_DISABLE_HTTP (void)data; (void)newurl; (void)type; /* Location: following will not happen when HTTP is disabled */ return CURLE_TOO_MANY_REDIRECTS; #else /* Location: redirect */ bool disallowport = FALSE; bool reachedmax = FALSE; CURLUcode uc; if(type == FOLLOW_REDIR) { if((data->set.maxredirs != -1) && (data->set.followlocation >= data->set.maxredirs)) { reachedmax = TRUE; type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected to URL */ } else { /* mark the next request as a followed location: */ data->state.this_is_a_follow = TRUE; data->set.followlocation++; /* count location-followers */ if(data->set.http_auto_referer) { /* We are asked to automatically set the previous URL as the referer when we get the next URL. We pick the ->url field, which may or may not be 100% correct */ if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = strdup(data->change.url); if(!data->change.referer) return CURLE_OUT_OF_MEMORY; data->change.referer_alloc = TRUE; /* yes, free this later */ } } } if(Curl_is_absolute_url(newurl, NULL, MAX_SCHEME_LEN)) /* This is an absolute URL, don't allow the custom port number */ disallowport = TRUE; DEBUGASSERT(data->state.uh); uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME : 0); if(uc) { if(type != FOLLOW_FAKE) return Curl_uc_to_curlcode(uc); /* the URL could not be parsed for some reason, but since this is FAKE mode, just duplicate the field as-is */ newurl = strdup(newurl); if(!newurl) return CURLE_OUT_OF_MEMORY; } else { uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0); if(uc) return Curl_uc_to_curlcode(uc); } if(type == FOLLOW_FAKE) { /* we're only figuring out the new url if we would've followed locations but now we're done so we can get out! */ data->info.wouldredirect = newurl; if(reachedmax) { failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs); return CURLE_TOO_MANY_REDIRECTS; } return CURLE_OK; } if(disallowport) data->state.allow_port = FALSE; if(data->change.url_alloc) Curl_safefree(data->change.url); data->change.url = newurl; data->change.url_alloc = TRUE; infof(data, "Issue another request to this URL: '%s'\n", data->change.url); /* * We get here when the HTTP code is 300-399 (and 401). We need to perform * differently based on exactly what return code there was. * * News from 7.10.6: we can also get here on a 401 or 407, in case we act on * a HTTP (proxy-) authentication scheme other than Basic. */ switch(data->info.httpcode) { /* 401 - Act on a WWW-Authenticate, we keep on moving and do the Authorization: XXXX header in the HTTP request code snippet */ /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the Proxy-Authorization: XXXX header in the HTTP request code snippet */ /* 300 - Multiple Choices */ /* 306 - Not used */ /* 307 - Temporary Redirect */ default: /* for all above (and the unknown ones) */ /* Some codes are explicitly mentioned since I've checked RFC2616 and they * seem to be OK to POST to. */ break; case 301: /* Moved Permanently */ /* (quote from RFC7231, section 6.4.2) * * Note: For historical reasons, a user agent MAY change the request * method from POST to GET for the subsequent request. If this * behavior is undesired, the 307 (Temporary Redirect) status code * can be used instead. * * ---- * * Many webservers expect this, so these servers often answers to a POST * request with an error page. To be sure that libcurl gets the page that * most user agents would get, libcurl has to force GET. * * This behaviour is forbidden by RFC1945 and the obsolete RFC2616, and * can be overridden with CURLOPT_POSTREDIR. */ if((data->set.httpreq == HTTPREQ_POST || data->set.httpreq == HTTPREQ_POST_FORM || data->set.httpreq == HTTPREQ_POST_MIME) && !(data->set.keep_post & CURL_REDIR_POST_301)) { infof(data, "Switch from POST to GET\n"); data->set.httpreq = HTTPREQ_GET; } break; case 302: /* Found */ /* (quote from RFC7231, section 6.4.3) * * Note: For historical reasons, a user agent MAY change the request * method from POST to GET for the subsequent request. If this * behavior is undesired, the 307 (Temporary Redirect) status code * can be used instead. * * ---- * * Many webservers expect this, so these servers often answers to a POST * request with an error page. To be sure that libcurl gets the page that * most user agents would get, libcurl has to force GET. * * This behaviour is forbidden by RFC1945 and the obsolete RFC2616, and * can be overridden with CURLOPT_POSTREDIR. */ if((data->set.httpreq == HTTPREQ_POST || data->set.httpreq == HTTPREQ_POST_FORM || data->set.httpreq == HTTPREQ_POST_MIME) && !(data->set.keep_post & CURL_REDIR_POST_302)) { infof(data, "Switch from POST to GET\n"); data->set.httpreq = HTTPREQ_GET; } break; case 303: /* See Other */ /* Disable both types of POSTs, unless the user explicitly asks for POST after POST */ if(data->set.httpreq != HTTPREQ_GET && !(data->set.keep_post & CURL_REDIR_POST_303)) { data->set.httpreq = HTTPREQ_GET; /* enforce GET request */ infof(data, "Disables POST, goes with %s\n", data->set.opt_no_body?"HEAD":"GET"); } break; case 304: /* Not Modified */ /* 304 means we did a conditional request and it was "Not modified". * We shouldn't get any Location: header in this response! */ break; case 305: /* Use Proxy */ /* (quote from RFC2616, section 10.3.6): * "The requested resource MUST be accessed through the proxy given * by the Location field. The Location field gives the URI of the * proxy. The recipient is expected to repeat this single request * via the proxy. 305 responses MUST only be generated by origin * servers." */ break; } Curl_pgrsTime(data, TIMER_REDIRECT); Curl_pgrsResetTransferSizes(data); return CURLE_OK; #endif /* CURL_DISABLE_HTTP */ } /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted. NOTE: that the *url is malloc()ed. */ CURLcode Curl_retry_request(struct connectdata *conn, char **url) { struct Curl_easy *data = conn->data; bool retry = FALSE; *url = NULL; /* if we're talking upload, we can't do the checks below, unless the protocol is HTTP as when uploading over HTTP we will still get a response */ if(data->set.upload && !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP))) return CURLE_OK; if((data->req.bytecount + data->req.headerbytecount == 0) && conn->bits.reuse && (!data->set.opt_no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP)) && (data->set.rtspreq != RTSPREQ_RECEIVE)) /* We got no data, we attempted to re-use a connection. For HTTP this can be a retry so we try again regardless if we expected a body. For other protocols we only try again only if we expected a body. This might happen if the connection was left alive when we were done using it before, but that was closed when we wanted to read from it again. Bad luck. Retry the same request on a fresh connect! */ retry = TRUE; else if(data->state.refused_stream && (data->req.bytecount + data->req.headerbytecount == 0) ) { /* This was sent on a refused stream, safe to rerun. A refused stream error can typically only happen on HTTP/2 level if the stream is safe to issue again, but the nghttp2 API can deliver the message to other streams as well, which is why this adds the check the data counters too. */ infof(conn->data, "REFUSED_STREAM, retrying a fresh connect\n"); data->state.refused_stream = FALSE; /* clear again */ retry = TRUE; } if(retry) { infof(conn->data, "Connection died, retrying a fresh connect\n"); *url = strdup(conn->data->change.url); if(!*url) return CURLE_OUT_OF_MEMORY; connclose(conn, "retry"); /* close this connection */ conn->bits.retry = TRUE; /* mark this as a connection we're about to retry. Marking it this way should prevent i.e HTTP transfers to return error just because nothing has been transferred! */ if(conn->handler->protocol&PROTO_FAMILY_HTTP) { if(data->req.writebytecount) { CURLcode result = Curl_readrewind(conn); if(result) { Curl_safefree(*url); return result; } } } } return CURLE_OK; } /* * Curl_setup_transfer() is called to setup some basic properties for the * upcoming transfer. */ void Curl_setup_transfer( struct Curl_easy *data, /* transfer */ int sockindex, /* socket index to read from or -1 */ curl_off_t size, /* -1 if unknown at this point */ bool getheader, /* TRUE if header parsing is wanted */ int writesockindex /* socket index to write to, it may very well be the same we read from. -1 disables */ ) { struct SingleRequest *k = &data->req; struct connectdata *conn = data->conn; DEBUGASSERT(conn != NULL); DEBUGASSERT((sockindex <= 1) && (sockindex >= -1)); if(conn->bits.multiplex || conn->httpversion == 20) { /* when multiplexing, the read/write sockets need to be the same! */ conn->sockfd = sockindex == -1 ? ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) : conn->sock[sockindex]; conn->writesockfd = conn->sockfd; } else { conn->sockfd = sockindex == -1 ? CURL_SOCKET_BAD : conn->sock[sockindex]; conn->writesockfd = writesockindex == -1 ? CURL_SOCKET_BAD:conn->sock[writesockindex]; } k->getheader = getheader; k->size = size; /* The code sequence below is placed in this function just because all necessary input is not always known in do_complete() as this function may be called after that */ if(!k->getheader) { k->header = FALSE; if(size > 0) Curl_pgrsSetDownloadSize(data, size); } /* we want header and/or body, if neither then don't do this! */ if(k->getheader || !data->set.opt_no_body) { if(sockindex != -1) k->keepon |= KEEP_RECV; if(writesockindex != -1) { struct HTTP *http = data->req.protop; /* HTTP 1.1 magic: Even if we require a 100-return code before uploading data, we might need to write data before that since the REQUEST may not have been finished sent off just yet. Thus, we must check if the request has been sent before we set the state info where we wait for the 100-return code */ if((data->state.expect100header) && (conn->handler->protocol&PROTO_FAMILY_HTTP) && (http->sending == HTTPSEND_BODY)) { /* wait with write until we either got 100-continue or a timeout */ k->exp100 = EXP100_AWAITING_CONTINUE; k->start100 = Curl_now(); /* Set a timeout for the multi interface. Add the inaccuracy margin so that we don't fire slightly too early and get denied to run. */ Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT); } else { if(data->state.expect100header) /* when we've sent off the rest of the headers, we must await a 100-continue but first finish sending the request */ k->exp100 = EXP100_SENDING_REQUEST; /* enable the write bit when we're not waiting for continue */ k->keepon |= KEEP_SEND; } } /* if(writesockindex != -1) */ } /* if(k->getheader || !data->set.opt_no_body) */ }
YifuLiu/AliOS-Things
components/curl/lib/transfer.c
C
apache-2.0
63,424
#ifndef HEADER_CURL_TRANSFER_H #define HEADER_CURL_TRANSFER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #define Curl_headersep(x) ((((x)==':') || ((x)==';'))) char *Curl_checkheaders(const struct connectdata *conn, const char *thisheader); void Curl_init_CONNECT(struct Curl_easy *data); CURLcode Curl_pretransfer(struct Curl_easy *data); CURLcode Curl_second_connect(struct connectdata *conn); 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 */ FOLLOW_LAST /* never used */ } 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(const struct connectdata *conn, curl_socket_t *socks, int numsocks); CURLcode Curl_readrewind(struct connectdata *conn); CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes, size_t *nreadp); CURLcode Curl_retry_request(struct connectdata *conn, char **url); bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc); CURLcode Curl_get_upload_buffer(struct Curl_easy *data); /* 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 */
YifuLiu/AliOS-Things
components/curl/lib/transfer.h
C
apache-2.0
3,184