repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
destroy_async_data
static void destroy_async_data (struct Curl_async *async) { if(async->hostname) free(async->hostname); if(async->os_specific) { struct ResolverResults *res = (struct ResolverResults *)async->os_specific; if(res) { if(res->temp_ai) { Curl_freeaddrinfo(res->temp_ai); res->temp_ai = NULL; } free(res); } async->os_specific = NULL; } async->hostname = NULL; }
/* * destroy_async_data() cleans up async resolver data. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L189-L207
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_resolver_getsock
int Curl_resolver_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct timeval maxtime; struct timeval timebuf; struct timeval *timeout; long milli; int max = ares_getsock((ares_channel)conn->data->state.resolver, (ares_socket_t *)socks, numsocks); maxtime.tv_sec = CURL_TIMEOUT_RESOLVE; maxtime.tv_usec = 0; timeout = ares_timeout((ares_channel)conn->data->state.resolver, &maxtime, &timebuf); milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000); if(milli == 0) milli += 10; Curl_expire(conn->data, milli); return max; }
/* * Curl_resolver_getsock() is called when someone from the outside world * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking * with ares. The caller must make sure that this function is only called when * we have a working ares channel. * * Returns: sockets-in-use-bitmap */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L218-L241
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
waitperform
static int waitperform(struct connectdata *conn, int timeout_ms) { struct SessionHandle *data = conn->data; int nfds; int bitmask; ares_socket_t socks[ARES_GETSOCK_MAXNUM]; struct pollfd pfd[ARES_GETSOCK_MAXNUM]; int i; int num = 0; bitmask = ares_getsock((ares_channel)data->state.resolver, socks, ARES_GETSOCK_MAXNUM); for(i=0; i < ARES_GETSOCK_MAXNUM; i++) { pfd[i].events = 0; pfd[i].revents = 0; if(ARES_GETSOCK_READABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLRDNORM|POLLIN; } if(ARES_GETSOCK_WRITABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLWRNORM|POLLOUT; } if(pfd[i].events != 0) num++; else break; } if(num) nfds = Curl_poll(pfd, num, timeout_ms); else nfds = 0; if(!nfds) /* Call ares_process() unconditonally here, even if we simply timed out above, as otherwise the ares name resolve won't timeout! */ ares_process_fd((ares_channel)data->state.resolver, ARES_SOCKET_BAD, ARES_SOCKET_BAD); else { /* move through the descriptors and ask for processing on them */ for(i=0; i < num; i++) ares_process_fd((ares_channel)data->state.resolver, pfd[i].revents & (POLLRDNORM|POLLIN)? pfd[i].fd:ARES_SOCKET_BAD, pfd[i].revents & (POLLWRNORM|POLLOUT)? pfd[i].fd:ARES_SOCKET_BAD); } return nfds; }
/* * waitperform() * * 1) Ask ares what sockets it currently plays with, then * 2) wait for the timeout period to check for action on ares' sockets. * 3) tell ares to act on all the sockets marked as "with action" * * return number of sockets it worked on */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L253-L303
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_resolver_is_resolved
CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dns) { struct SessionHandle *data = conn->data; struct ResolverResults *res = (struct ResolverResults *) conn->async.os_specific; *dns = NULL; waitperform(conn, 0); if(res && !res->num_pending) { (void)Curl_addrinfo_callback(conn, res->last_status, res->temp_ai); /* temp_ai ownership is moved to the connection, so we need not free-up them */ res->temp_ai = NULL; destroy_async_data(&conn->async); if(!conn->async.dns) { failf(data, "Could not resolve %s: %s (%s)", conn->bits.proxy?"proxy":"host", conn->host.dispname, ares_strerror(conn->async.status)); return conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY: CURLE_COULDNT_RESOLVE_HOST; } *dns = conn->async.dns; } return CURLE_OK; }
/* * Curl_resolver_is_resolved() is called repeatedly to check if a previous * name resolve request has completed. It should also make sure to time-out if * the operation seems to take too long. * * Returns normal CURLcode errors. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L312-L341
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_resolver_wait_resolv
CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; timeout = Curl_timeleft(data, &now, TRUE); if(!timeout) timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ for(;;) { struct timeval *tvp, tv, store; long timediff; int itimeout; int timeout_ms; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv); /* use the timeout period ares returned to us above if less than one second is left, otherwise just use 1000ms to make sure the progress callback gets called frequent enough */ if(!tvp->tv_sec) timeout_ms = (int)(tvp->tv_usec/1000); else timeout_ms = 1000; waitperform(conn, timeout_ms); Curl_resolver_is_resolved(conn,&temp_entry); if(conn->async.done) break; if(Curl_pgrsUpdate(conn)) { rc = CURLE_ABORTED_BY_CALLBACK; timeout = -1; /* trigger the cancel below */ } else { struct timeval now2 = Curl_tvnow(); timediff = Curl_tvdiff(now2, now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ now = now2; /* for next loop */ } if(timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel((ares_channel)data->state.resolver); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(!conn->async.dns) { /* a name was not resolved */ if((timeout < 0) || (conn->async.status == ARES_ETIMEOUT)) { if(conn->bits.proxy) { failf(data, "Resolving proxy timed out: %s", conn->proxy.dispname); rc = CURLE_COULDNT_RESOLVE_PROXY; } else { failf(data, "Resolving host timed out: %s", conn->host.dispname); rc = CURLE_COULDNT_RESOLVE_HOST; } } else if(conn->async.done) { if(conn->bits.proxy) { failf(data, "Could not resolve proxy: %s (%s)", conn->proxy.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_PROXY; } else { failf(data, "Could not resolve host: %s (%s)", conn->host.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_HOST; } } else rc = CURLE_OPERATION_TIMEDOUT; /* close the connection, since we can't return failure here without cleaning up this connection properly */ conn->bits.close = TRUE; } return rc; }
/* * Curl_resolver_wait_resolv() * * waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L354-L451
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
compound_results
static void compound_results(struct ResolverResults *res, Curl_addrinfo *ai) { Curl_addrinfo *ai_tail; if(!ai) return; ai_tail = ai; while(ai_tail->ai_next) ai_tail = ai_tail->ai_next; /* Add the new results to the list of old results. */ ai_tail->ai_next = res->temp_ai; res->temp_ai = ai; }
/* Connects results to the list */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L454-L468
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
query_completed_cb
static void query_completed_cb(void *arg, /* (struct connectdata *) */ int status, #ifdef HAVE_CARES_CALLBACK_TIMEOUTS int timeouts, #endif struct hostent *hostent) { struct connectdata *conn = (struct connectdata *)arg; struct ResolverResults *res; #ifdef HAVE_CARES_CALLBACK_TIMEOUTS (void)timeouts; /* ignored */ #endif if(ARES_EDESTRUCTION == status) /* when this ares handle is getting destroyed, the 'arg' pointer may not be valid so only defer it when we know the 'status' says its fine! */ return; res = (struct ResolverResults *)conn->async.os_specific; res->num_pending--; if(CURL_ASYNC_SUCCESS == status) { Curl_addrinfo *ai = Curl_he2ai(hostent, conn->async.port); if(ai) { compound_results(res, ai); } } /* A successful result overwrites any previous error */ if(res->last_status != ARES_SUCCESS) res->last_status = status; }
/* * ares_query_completed_cb() is the callback that ares will call when * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(), * when using ares, is completed either successfully or with failure. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-ares.c#L475-L506
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
getaddrinfo_thread
static unsigned int CURL_STDCALL getaddrinfo_thread (void *arg) { struct thread_sync_data *tsd = (struct thread_sync_data*)arg; char service [NI_MAXSERV]; int rc; snprintf(service, sizeof(service), "%d", tsd->port); rc = Curl_getaddrinfo_ex(tsd->hostname, service, &tsd->hints, &tsd->res); if(rc != 0) { tsd->sock_error = SOCKERRNO?SOCKERRNO:rc; if(tsd->sock_error == 0) tsd->sock_error = RESOLVER_ENOMEM; } Curl_mutex_acquire(tsd->mtx); tsd->done = 1; Curl_mutex_release(tsd->mtx); return 0; }
/* * getaddrinfo_thread() resolves a name and then exits. * * For builds without ARES, but with ENABLE_IPV6, create a resolver thread * and wait on it. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-thread.c#L265-L286
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
gethostbyname_thread
static unsigned int CURL_STDCALL gethostbyname_thread (void *arg) { struct thread_sync_data *tsd = (struct thread_sync_data *)arg; tsd->res = Curl_ipv4_resolve_r(tsd->hostname, tsd->port); if(!tsd->res) { tsd->sock_error = SOCKERRNO; if(tsd->sock_error == 0) tsd->sock_error = RESOLVER_ENOMEM; } Curl_mutex_acquire(tsd->mtx); tsd->done = 1; Curl_mutex_release(tsd->mtx); return 0; }
/* HAVE_GETADDRINFO */ /* * gethostbyname_thread() resolves a name and then exits. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/asyn-thread.c#L293-L310
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
SSL_read
static int SSL_read(SSL *ssl, void *buf, int num) { uint8_t *read_buf; int ret; while((ret = ssl_read(ssl, &read_buf)) == SSL_OK); if(ret > SSL_OK) { memcpy(buf, read_buf, ret > num ? num : ret); } return ret; }
/* SSL_read is opied from axTLS compat layer */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L50-L62
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_axtls_init
int Curl_axtls_init(void) { /* axTLS has no global init. Everything is done through SSL and SSL_CTX * structs stored in connectdata structure. Perhaps can move to axtls.h. */ return 1; }
/* Global axTLS init, called from Curl_ssl_init() */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L65-L71
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_axtls_connect
CURLcode Curl_axtls_connect(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; SSL_CTX *ssl_ctx; SSL *ssl; int cert_types[] = {SSL_OBJ_X509_CERT, SSL_OBJ_PKCS12, 0}; int key_types[] = {SSL_OBJ_RSA_KEY, SSL_OBJ_PKCS8, SSL_OBJ_PKCS12, 0}; int i, ssl_fcn_return; const uint8_t *ssl_sessionid; size_t ssl_idsize; const char *peer_CN; uint32_t dns_altname_index; const char *dns_altname; int8_t found_subject_alt_names = 0; int8_t found_subject_alt_name_matching_conn = 0; /* Assuming users will not compile in custom key/cert to axTLS */ uint32_t client_option = SSL_NO_DEFAULT_KEY|SSL_SERVER_VERIFY_LATER; if(conn->ssl[sockindex].state == ssl_connection_complete) /* to make us tolerant against being called more than once for the same connection */ return CURLE_OK; /* axTLS only supports TLSv1 */ /* check to see if we've been told to use an explicit SSL/TLS version */ switch(data->set.ssl.version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: break; default: failf(data, "axTLS only supports TLSv1"); return CURLE_SSL_CONNECT_ERROR; } #ifdef AXTLSDEBUG client_option |= SSL_DISPLAY_STATES | SSL_DISPLAY_RSA | SSL_DISPLAY_CERTS; #endif /* AXTLSDEBUG */ /* Allocate an SSL_CTX struct */ ssl_ctx = ssl_ctx_new(client_option, SSL_DEFAULT_CLNT_SESS); if(ssl_ctx == NULL) { failf(data, "unable to create client SSL context"); return CURLE_SSL_CONNECT_ERROR; } /* Load the trusted CA cert bundle file */ if(data->set.ssl.CAfile) { if(ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, data->set.ssl.CAfile, NULL) != SSL_OK) { infof(data, "error reading ca cert file %s \n", data->set.ssl.CAfile); if(data->set.ssl.verifypeer) { Curl_axtls_close(conn, sockindex); return CURLE_SSL_CACERT_BADFILE; } } else infof(data, "found certificates in %s\n", data->set.ssl.CAfile); } /* gtls.c tasks we're skipping for now: * 1) certificate revocation list checking * 2) dns name assignment to host * 3) set protocol priority. axTLS is TLSv1 only, so can probably ignore * 4) set certificate priority. axTLS ignores type and sends certs in * order added. can probably ignore this. */ /* Load client certificate */ if(data->set.str[STRING_CERT]) { i=0; /* Instead of trying to analyze cert type here, let axTLS try them all. */ while(cert_types[i] != 0) { ssl_fcn_return = ssl_obj_load(ssl_ctx, cert_types[i], data->set.str[STRING_CERT], NULL); if(ssl_fcn_return == SSL_OK) { infof(data, "successfully read cert file %s \n", data->set.str[STRING_CERT]); break; } i++; } /* Tried all cert types, none worked. */ if(cert_types[i] == 0) { failf(data, "%s is not x509 or pkcs12 format", data->set.str[STRING_CERT]); Curl_axtls_close(conn, sockindex); return CURLE_SSL_CERTPROBLEM; } } /* Load client key. If a pkcs12 file successfully loaded a cert, then there's nothing to do because the key has already been loaded. */ if(data->set.str[STRING_KEY] && cert_types[i] != SSL_OBJ_PKCS12) { i=0; /* Instead of trying to analyze key type here, let axTLS try them all. */ while(key_types[i] != 0) { ssl_fcn_return = ssl_obj_load(ssl_ctx, key_types[i], data->set.str[STRING_KEY], NULL); if(ssl_fcn_return == SSL_OK) { infof(data, "successfully read key file %s \n", data->set.str[STRING_KEY]); break; } i++; } /* Tried all key types, none worked. */ if(key_types[i] == 0) { failf(data, "Failure: %s is not a supported key file", data->set.str[STRING_KEY]); Curl_axtls_close(conn, sockindex); return CURLE_SSL_CONNECT_ERROR; } } /* gtls.c does more here that is being left out for now * 1) set session credentials. can probably ignore since axtls puts this * info in the ssl_ctx struct * 2) setting up callbacks. these seem gnutls specific */ /* In axTLS, handshaking happens inside ssl_client_new. */ if(!Curl_ssl_getsessionid(conn, (void **) &ssl_sessionid, &ssl_idsize)) { /* we got a session id, use it! */ infof (data, "SSL re-using session ID\n"); ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], ssl_sessionid, (uint8_t)ssl_idsize); } else ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], NULL, 0); /* Check to make sure handshake was ok. */ ssl_fcn_return = ssl_handshake_status(ssl); if(ssl_fcn_return != SSL_OK) { Curl_axtls_close(conn, sockindex); ssl_display_error(ssl_fcn_return); /* goes to stdout. */ return map_error_to_curl(ssl_fcn_return); } infof (data, "handshake completed successfully\n"); /* Here, gtls.c gets the peer certificates and fails out depending on * settings in "data." axTLS api doesn't have get cert chain fcn, so omit? */ /* Verify server's certificate */ if(data->set.ssl.verifypeer) { if(ssl_verify_cert(ssl) != SSL_OK) { Curl_axtls_close(conn, sockindex); failf(data, "server cert verify failed"); return CURLE_SSL_CONNECT_ERROR; } } else infof(data, "\t server certificate verification SKIPPED\n"); /* Here, gtls.c does issuer verification. axTLS has no straightforward * equivalent, so omitting for now.*/ /* Here, gtls.c does the following * 1) x509 hostname checking per RFC2818. axTLS doesn't support this, but * it seems useful. This is now implemented, by Oscar Koeroo * 2) checks cert validity based on time. axTLS does this in ssl_verify_cert * 3) displays a bunch of cert information. axTLS doesn't support most of * this, but a couple fields are available. */ /* There is no (DNS) Altnames count in the version 1.4.8 API. There is a risk of an inifite loop */ for(dns_altname_index = 0; ; dns_altname_index++) { dns_altname = ssl_get_cert_subject_alt_dnsname(ssl, dns_altname_index); if(dns_altname == NULL) { break; } found_subject_alt_names = 1; infof(data, "\tComparing subject alt name DNS with hostname: %s <-> %s\n", dns_altname, conn->host.name); if(Curl_cert_hostcheck(dns_altname, conn->host.name)) { found_subject_alt_name_matching_conn = 1; break; } } /* RFC2818 checks */ if(found_subject_alt_names && !found_subject_alt_name_matching_conn) { /* Break connection ! */ Curl_axtls_close(conn, sockindex); failf(data, "\tsubjectAltName(s) do not match %s\n", conn->host.dispname); return CURLE_PEER_FAILED_VERIFICATION; } else if(found_subject_alt_names == 0) { /* Per RFC2818, when no Subject Alt Names were available, examine the peer CN as a legacy fallback */ peer_CN = ssl_get_cert_dn(ssl, SSL_X509_CERT_COMMON_NAME); if(peer_CN == NULL) { /* Similar behaviour to the OpenSSL interface */ Curl_axtls_close(conn, sockindex); failf(data, "unable to obtain common name from peer certificate"); return CURLE_PEER_FAILED_VERIFICATION; } else { if(!Curl_cert_hostcheck((const char *)peer_CN, conn->host.name)) { if(data->set.ssl.verifyhost) { /* Break connection ! */ Curl_axtls_close(conn, sockindex); failf(data, "\tcommon name \"%s\" does not match \"%s\"\n", peer_CN, conn->host.dispname); return CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\tcommon name \"%s\" does not match \"%s\"\n", peer_CN, conn->host.dispname); } } } /* General housekeeping */ conn->ssl[sockindex].state = ssl_connection_complete; conn->ssl[sockindex].ssl = ssl; conn->ssl[sockindex].ssl_ctx = ssl_ctx; conn->recv[sockindex] = axtls_recv; conn->send[sockindex] = axtls_send; /* Put our freshly minted SSL session in cache */ ssl_idsize = ssl_get_session_id_size(ssl); ssl_sessionid = ssl_get_session_id(ssl); if(Curl_ssl_addsessionid(conn, (void *) ssl_sessionid, ssl_idsize) != CURLE_OK) infof (data, "failed to add session to cache\n"); return CURLE_OK; }
/* * This function is called after the TCP connect has completed. Setup the TLS * layer and do all necessary magic. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L138-L375
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
axtls_send
static ssize_t axtls_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { /* ssl_write() returns 'int' while write() and send() returns 'size_t' */ int rc = ssl_write(conn->ssl[sockindex].ssl, mem, (int)len); infof(conn->data, " axtls_send\n"); if(rc < 0 ) { *err = map_error_to_curl(rc); rc = -1; /* generic error code for send failure */ } *err = CURLE_OK; return rc; }
/* return number of sent (non-SSL) bytes */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L379-L397
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_axtls_shutdown
int Curl_axtls_shutdown(struct connectdata *conn, int sockindex) { /* Outline taken from ssluse.c since functions are in axTLS compat layer. axTLS's error set is much smaller, so a lot of error-handling was removed. */ int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct SessionHandle *data = conn->data; char buf[120]; /* We will use this for the OpenSSL error buffer, so it has to be at least 120 bytes long. */ ssize_t nread; infof(conn->data, " Curl_axtls_shutdown\n"); /* This has only been tested on the proftpd server, and the mod_tls code sends a close notify alert without waiting for a close notify alert in response. Thus we wait for a close notify alert from the server, but we do not send one. Let's hope other servers do the same... */ /* axTLS compat layer does nothing for SSL_shutdown, so we do nothing too if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) (void)SSL_shutdown(connssl->ssl); */ if(connssl->ssl) { int what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT); if(what > 0) { /* Something to read, let's do it and hope that it is the close notify alert from the server */ nread = (ssize_t)SSL_read(conn->ssl[sockindex].ssl, buf, sizeof(buf)); if(nread < SSL_OK) { failf(data, "close notify alert not received during shutdown"); retval = -1; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; } ssl_free (connssl->ssl); connssl->ssl = NULL; } return retval; }
/* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L431-L483
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_axtls_check_cxn
int Curl_axtls_check_cxn(struct connectdata *conn) { /* ssluse.c line: rc = SSL_peek(conn->ssl[FIRSTSOCKET].ssl, (void*)&buf, 1); axTLS compat layer always returns the last argument, so connection is always alive? */ infof(conn->data, " Curl_axtls_check_cxn\n"); return 1; /* connection still in place */ }
/* * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/axtls.c#L522-L530
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_base64_decode
CURLcode Curl_base64_decode(const char *src, unsigned char **outptr, size_t *outlen) { size_t length = 0; size_t equalsTerm = 0; size_t i; size_t numQuantums; unsigned char lastQuantum[3]; size_t rawlen = 0; unsigned char *newstr; *outptr = NULL; *outlen = 0; while((src[length] != '=') && src[length]) length++; /* A maximum of two = padding characters is allowed */ if(src[length] == '=') { equalsTerm++; if(src[length+equalsTerm] == '=') equalsTerm++; } numQuantums = (length + equalsTerm) / 4; /* Don't allocate a buffer if the decoded length is 0 */ if(numQuantums == 0) return CURLE_OK; rawlen = (numQuantums * 3) - equalsTerm; /* The buffer must be large enough to make room for the last quantum (which may be partially thrown out) and the zero terminator. */ newstr = malloc(rawlen+4); if(!newstr) return CURLE_OUT_OF_MEMORY; *outptr = newstr; /* Decode all but the last quantum (which may not decode to a multiple of 3 bytes) */ for(i = 0; i < numQuantums - 1; i++) { decodeQuantum(newstr, src); newstr += 3; src += 4; } /* This final decode may actually read slightly past the end of the buffer if the input string is missing pad bytes. This will almost always be harmless. */ decodeQuantum(lastQuantum, src); for(i = 0; i < 3 - equalsTerm; i++) newstr[i] = lastQuantum[i]; newstr[i] = '\0'; /* zero terminate */ *outlen = rawlen; /* return size of decoded data */ return CURLE_OK; }
/* * Curl_base64_decode() * * Given a base64 NUL-terminated string at src, decode it and return a * pointer in *outptr to a newly allocated memory area holding decoded * data. Size of decoded data is returned in variable pointed by outlen. * * Returns CURLE_OK on success, otherwise specific error code. Function * output shall not be considered valid unless CURLE_OK is returned. * * When decoded data length is 0, returns NULL in *outptr. * * @unittest: 1302 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/base64.c#L82-L139
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_base64_encode
CURLcode Curl_base64_encode(struct SessionHandle *data, const char *inputbuff, size_t insize, char **outptr, size_t *outlen) { CURLcode error; unsigned char ibuf[3]; unsigned char obuf[4]; int i; int inputparts; char *output; char *base64data; char *convbuf = NULL; const char *indata = inputbuff; *outptr = NULL; *outlen = 0; if(0 == insize) insize = strlen(indata); base64data = output = malloc(insize*4/3+4); if(NULL == output) return CURLE_OUT_OF_MEMORY; /* * The base64 data needs to be created using the network encoding * not the host encoding. And we can't change the actual input * so we copy it to a buffer, translate it, and use that instead. */ error = Curl_convert_clone(data, indata, insize, &convbuf); if(error) { free(output); return error; } if(convbuf) indata = (char *)convbuf; while(insize > 0) { for(i = inputparts = 0; i < 3; i++) { if(insize > 0) { inputparts++; ibuf[i] = (unsigned char) *indata; indata++; insize--; } else ibuf[i] = 0; } obuf[0] = (unsigned char) ((ibuf[0] & 0xFC) >> 2); obuf[1] = (unsigned char) (((ibuf[0] & 0x03) << 4) | \ ((ibuf[1] & 0xF0) >> 4)); obuf[2] = (unsigned char) (((ibuf[1] & 0x0F) << 2) | \ ((ibuf[2] & 0xC0) >> 6)); obuf[3] = (unsigned char) (ibuf[2] & 0x3F); switch(inputparts) { case 1: /* only one byte read */ snprintf(output, 5, "%c%c==", table64[obuf[0]], table64[obuf[1]]); break; case 2: /* two bytes read */ snprintf(output, 5, "%c%c%c=", table64[obuf[0]], table64[obuf[1]], table64[obuf[2]]); break; default: snprintf(output, 5, "%c%c%c%c", table64[obuf[0]], table64[obuf[1]], table64[obuf[2]], table64[obuf[3]] ); break; } output += 4; } *output = '\0'; *outptr = base64data; /* return pointer to new data, allocated memory */ if(convbuf) free(convbuf); *outlen = strlen(base64data); /* return the length of the new data */ return CURLE_OK; }
/* * Curl_base64_encode() * * Given a pointer to an input buffer and an input size, encode it and * return a pointer in *outptr to a newly allocated memory area holding * encoded data. Size of encoded data is returned in variable pointed by * outlen. * * Input length of 0 indicates input buffer holds a NUL-terminated string. * * Returns CURLE_OK on success, otherwise specific error code. Function * output shall not be considered valid unless CURLE_OK is returned. * * When encoded data length is 0, returns NULL in *outptr. * * @unittest: 1302 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/base64.c#L158-L247
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_bundle_add_conn
CURLcode Curl_bundle_add_conn(struct connectbundle *cb_ptr, struct connectdata *conn) { if(!Curl_llist_insert_next(cb_ptr->conn_list, cb_ptr->conn_list->tail, conn)) return CURLE_OUT_OF_MEMORY; conn->bundle = cb_ptr; cb_ptr->num_connections++; return CURLE_OK; }
/* Add a connection to a bundle */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/bundles.c#L81-L91
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_bundle_remove_conn
int Curl_bundle_remove_conn(struct connectbundle *cb_ptr, struct connectdata *conn) { struct curl_llist_element *curr; curr = cb_ptr->conn_list->head; while(curr) { if(curr->ptr == conn) { Curl_llist_remove(cb_ptr->conn_list, curr, NULL); cb_ptr->num_connections--; conn->bundle = NULL; return 1; /* we removed a handle */ } curr = curr->next; } return 0; }
/* Remove a connection from a bundle */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/bundles.c#L94-L110
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_conncache_foreach
void Curl_conncache_foreach(struct conncache *connc, void *param, int (*func)(struct connectdata *conn, void *param)) { struct curl_hash_iterator iter; struct curl_llist_element *curr; struct curl_hash_element *he; if(!connc) return; Curl_hash_start_iterate(connc->hash, &iter); he = Curl_hash_next_element(&iter); while(he) { struct connectbundle *bundle; struct connectdata *conn; bundle = he->ptr; curr = bundle->conn_list->head; while(curr) { /* Yes, we need to update curr before calling func(), because func() might decide to remove the connection */ conn = curr->ptr; curr = curr->next; if(1 == func(conn, param)) return; } he = Curl_hash_next_element(&iter); } }
/* This function iterates the entire connection cache and calls the function func() with the connection pointer as the first argument and the supplied 'param' argument as the other, Return 0 from func() to continue the loop, return 1 to abort it. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/conncache.c#L184-L217
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_conncache_print
void Curl_conncache_print(struct conncache *connc) { struct curl_hash_iterator iter; struct curl_llist_element *curr; struct curl_hash_element *he; if(!connc) return; fprintf(stderr, "=Bundle cache=\n"); Curl_hash_start_iterate(connc->hash, &iter); he = Curl_hash_next_element(&iter); while(he) { struct connectbundle *bundle; struct connectdata *conn; bundle = he->ptr; fprintf(stderr, "%s -", he->key); curr = bundle->conn_list->head; while(curr) { conn = curr->ptr; fprintf(stderr, " [%p %d]", (void *)conn, conn->inuse); curr = curr->next; } fprintf(stderr, "\n"); he = Curl_hash_next_element(&iter); } }
/* Useful for debugging the connection cache */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/conncache.c#L249-L281
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
SocketRead
static OSStatus SocketRead(SSLConnectionRef connection, void *data, /* owned by * caller, data * RETURNED */ size_t *dataLength) /* IN/OUT */ { size_t bytesToGo = *dataLength; size_t initLen = bytesToGo; UInt8 *currData = (UInt8 *)data; /*int sock = *(int *)connection;*/ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection; int sock = connssl->ssl_sockfd; OSStatus rtn = noErr; size_t bytesRead; ssize_t rrtn; int theErr; *dataLength = 0; for(;;) { bytesRead = 0; rrtn = read(sock, currData, bytesToGo); if(rrtn <= 0) { /* this is guesswork... */ theErr = errno; if((rrtn == 0) && (theErr == 0)) { /* try fix for iSync */ rtn = errSSLClosedGraceful; } else /* do the switch */ switch(theErr) { case ENOENT: /* connection closed */ rtn = errSSLClosedGraceful; break; case ECONNRESET: rtn = errSSLClosedAbort; break; case EAGAIN: rtn = errSSLWouldBlock; connssl->ssl_direction = false; break; default: rtn = ioErr; break; } break; } else { bytesRead = rrtn; } bytesToGo -= bytesRead; currData += bytesRead; if(bytesToGo == 0) { /* filled buffer with incoming data, done */ break; } } *dataLength = initLen - bytesToGo; return rtn; }
/* In Mountain Lion and iOS 5, Apple made some changes to the API. They added TLS 1.1 and 1.2 support, and deprecated and replaced some functions. You need to build against the Mountain Lion or iOS 5 SDK or later to get TLS 1.1 or 1.2 support working in cURL. We'll weak-link to the newer functions and use them if present in the user's OS. Builders: If you want TLS 1.1 and 1.2 but still want to retain support for older cats, don't forget to set the MACOSX_DEPLOYMENT_TARGET environmental variable prior to building cURL. */ /* The following two functions were ripped from Apple sample code, * with some modifications: */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_darwinssl.c#L75-L137
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_darwinssl_check_cxn
int Curl_darwinssl_check_cxn(struct connectdata *conn) { struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET]; OSStatus err; SSLSessionState state; if(connssl->ssl_ctx) { err = SSLGetSessionState(connssl->ssl_ctx, &state); if(err == noErr) return state == kSSLConnected || state == kSSLHandshake; return -1; } return 0; }
/* * This function uses SSLGetSessionState to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_darwinssl.c#L1318-L1331
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_gethostname
int Curl_gethostname(char *name, GETHOSTNAME_TYPE_ARG2 namelen) { #ifndef HAVE_GETHOSTNAME /* Allow compilation and return failure when unavailable */ (void) name; (void) namelen; return -1; #else int err; char* dot; #ifdef DEBUGBUILD /* Override host name when environment variable CURL_GETHOSTNAME is set */ const char *force_hostname = getenv("CURL_GETHOSTNAME"); if(force_hostname) { strncpy(name, force_hostname, namelen); err = 0; } else { name[0] = '\0'; err = gethostname(name, namelen); } #else /* DEBUGBUILD */ /* The call to system's gethostname() might get intercepted by the libhostname library when libcurl is built as a non-debug shared library when running the test suite. */ name[0] = '\0'; err = gethostname(name, namelen); #endif name[namelen - 1] = '\0'; if(err) return err; /* Truncate domain, leave only machine name */ dot = strchr(name, '.'); if(dot) *dot = '\0'; return 0; #endif }
/* * Curl_gethostname() is a wrapper around gethostname() which allows * overriding the host name that the function would normally return. * This capability is used by the test suite to verify exact matching * of NTLM authentication, which exercises libcurl's MD4 and DES code * as well as by the SMTP module when a hostname is not provided. * * For libcurl debug enabled builds host name overriding takes place * when environment variable CURL_GETHOSTNAME is set, using the value * held by the variable to override returned host name. * * Note: The function always returns the un-qualified hostname rather * than being provider dependent. * * For libcurl shared library release builds the test suite preloads * another shared library named libhostname using the LD_PRELOAD * mechanism which intercepts, and might override, the gethostname() * function call. In this case a given platform must support the * LD_PRELOAD mechanism and additionally have environment variable * CURL_GETHOSTNAME set in order to override the returned host name. * * For libcurl static library release builds no overriding takes place. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_gethostname.c#L51-L100
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
readint_le
static unsigned int readint_le(unsigned char *buf) { return ((unsigned int)buf[0]) | ((unsigned int)buf[1] << 8) | ((unsigned int)buf[2] << 16) | ((unsigned int)buf[3] << 24); }
/* * This function converts from the little endian format used in the * incoming package to whatever endian format we're using natively. * Argument is a pointer to a 4 byte buffer. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_msgs.c#L156-L160
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_decode_type2_message
CURLcode Curl_ntlm_decode_type2_message(struct SessionHandle *data, const char* header, struct ntlmdata* ntlm) { #ifndef USE_WINDOWS_SSPI static const char type2_marker[] = { 0x02, 0x00, 0x00, 0x00 }; #endif /* NTLM type-2 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x02000000) 12 Target Name security buffer 20 Flags long 24 Challenge 8 bytes (32) Context 8 bytes (two consecutive longs) (*) (40) Target Information security buffer (*) (48) OS Version Structure 8 bytes (*) 32 (48) (56) Start of data block (*) (*) -> Optional */ size_t size = 0; unsigned char *buffer = NULL; CURLcode error; #if defined(CURL_DISABLE_VERBOSE_STRINGS) || defined(USE_WINDOWS_SSPI) (void)data; #endif error = Curl_base64_decode(header, &buffer, &size); if(error) return error; if(!buffer) { infof(data, "NTLM handshake failure (unhandled condition)\n"); return CURLE_REMOTE_ACCESS_DENIED; } #ifdef USE_WINDOWS_SSPI ntlm->type_2 = malloc(size + 1); if(ntlm->type_2 == NULL) { free(buffer); return CURLE_OUT_OF_MEMORY; } ntlm->n_type_2 = curlx_uztoul(size); memcpy(ntlm->type_2, buffer, size); #else ntlm->flags = 0; if((size < 32) || (memcmp(buffer, NTLMSSP_SIGNATURE, 8) != 0) || (memcmp(buffer + 8, type2_marker, sizeof(type2_marker)) != 0)) { /* This was not a good enough type-2 message */ free(buffer); infof(data, "NTLM handshake failure (bad type-2 message)\n"); return CURLE_REMOTE_ACCESS_DENIED; } ntlm->flags = readint_le(&buffer[20]); memcpy(ntlm->nonce, &buffer[24], 8); DEBUG_OUT({ fprintf(stderr, "**** TYPE2 header flags=0x%08.8lx ", ntlm->flags); ntlm_print_flags(stderr, ntlm->flags); fprintf(stderr, "\n nonce="); ntlm_print_hex(stderr, (char *)ntlm->nonce, 8); fprintf(stderr, "\n****\n"); fprintf(stderr, "**** Header %s\n ", header); }); #endif free(buffer); return CURLE_OK; }
/* NTLM message structure notes: A 'short' is a 'network short', a little-endian 16-bit unsigned value. A 'long' is a 'network long', a little-endian, 32-bit unsigned value. A 'security buffer' represents a triplet used to point to a buffer, consisting of two shorts and one long: 1. A 'short' containing the length of the buffer content in bytes. 2. A 'short' containing the allocated space for the buffer in bytes. 3. A 'long' containing the offset to the start of the buffer in bytes, from the beginning of the NTLM message. */ /* * Curl_ntlm_decode_type2_message() * * This is used to decode a ntlm type-2 message received from a: HTTP, SMTP * or POP3 server. The message is first decoded from a base64 string into a * raw ntlm message and checked for validity before the appropriate data for * creating a type-3 message is written to the given ntlm data structure. * * Parameters: * * data [in] - Pointer to session handle. * header [in] - Pointer to the input buffer. * ntlm [in] - Pointer to ntlm data struct being used and modified. * * Returns CURLE_OK on success. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_msgs.c#L195-L271
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
unicodecpy
static void unicodecpy(unsigned char *dest, const char *src, size_t length) { size_t i; for(i = 0; i < length; i++) { dest[2 * i] = (unsigned char)src[i]; dest[2 * i + 1] = '\0'; } }
/* copy the source to the destination and fill in zeroes in every other destination byte! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_msgs.c#L294-L302
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_create_type1_message
CURLcode Curl_ntlm_create_type1_message(const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { /* NTLM type-1 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x01000000) 12 Flags long (16) Supplied Domain security buffer (*) (24) Supplied Workstation security buffer (*) (32) OS Version Structure 8 bytes (*) (32) (40) Start of data block (*) (*) -> Optional */ unsigned char ntlmbuf[NTLM_BUFSIZE]; size_t size; #ifdef USE_WINDOWS_SSPI SecBuffer buf; SecBufferDesc desc; SECURITY_STATUS status; unsigned long attrs; xcharp_u useranddomain; xcharp_u user, dup_user; xcharp_u domain, dup_domain; xcharp_u passwd, dup_passwd; size_t domlen = 0; TimeStamp tsDummy; /* For Windows 9x compatibility of SSPI calls */ domain.const_tchar_ptr = TEXT(""); Curl_ntlm_sspi_cleanup(ntlm); if(userp && *userp) { /* null initialize ntlm identity's data to allow proper cleanup */ ntlm->p_identity = &ntlm->identity; memset(ntlm->p_identity, 0, sizeof(*ntlm->p_identity)); useranddomain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *)userp); if(!useranddomain.tchar_ptr) return CURLE_OUT_OF_MEMORY; user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('\\')); if(!user.const_tchar_ptr) user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('/')); if(user.tchar_ptr) { domain.tchar_ptr = useranddomain.tchar_ptr; domlen = user.tchar_ptr - useranddomain.tchar_ptr; user.tchar_ptr++; } else { user.tchar_ptr = useranddomain.tchar_ptr; domain.const_tchar_ptr = TEXT(""); domlen = 0; } /* setup ntlm identity's user and length */ dup_user.tchar_ptr = _tcsdup(user.tchar_ptr); if(!dup_user.tchar_ptr) { Curl_unicodefree(useranddomain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } ntlm->identity.User = dup_user.tbyte_ptr; ntlm->identity.UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr)); dup_user.tchar_ptr = NULL; /* setup ntlm identity's domain and length */ dup_domain.tchar_ptr = malloc(sizeof(TCHAR) * (domlen + 1)); if(!dup_domain.tchar_ptr) { Curl_unicodefree(useranddomain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } _tcsncpy(dup_domain.tchar_ptr, domain.tchar_ptr, domlen); *(dup_domain.tchar_ptr + domlen) = TEXT('\0'); ntlm->identity.Domain = dup_domain.tbyte_ptr; ntlm->identity.DomainLength = curlx_uztoul(domlen); dup_domain.tchar_ptr = NULL; Curl_unicodefree(useranddomain.tchar_ptr); /* setup ntlm identity's password and length */ passwd.tchar_ptr = Curl_convert_UTF8_to_tchar((char *)passwdp); if(!passwd.tchar_ptr) return CURLE_OUT_OF_MEMORY; dup_passwd.tchar_ptr = _tcsdup(passwd.tchar_ptr); if(!dup_passwd.tchar_ptr) { Curl_unicodefree(passwd.tchar_ptr); return CURLE_OUT_OF_MEMORY; } ntlm->identity.Password = dup_passwd.tbyte_ptr; ntlm->identity.PasswordLength = curlx_uztoul(_tcslen(dup_passwd.tchar_ptr)); dup_passwd.tchar_ptr = NULL; Curl_unicodefree(passwd.tchar_ptr); /* setup ntlm identity's flags */ ntlm->identity.Flags = SECFLAG_WINNT_AUTH_IDENTITY; } else ntlm->p_identity = NULL; status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT("NTLM"), SECPKG_CRED_OUTBOUND, NULL, ntlm->p_identity, NULL, NULL, &ntlm->handle, &tsDummy); if(status != SEC_E_OK) return CURLE_OUT_OF_MEMORY; desc.ulVersion = SECBUFFER_VERSION; desc.cBuffers = 1; desc.pBuffers = &buf; buf.cbBuffer = NTLM_BUFSIZE; buf.BufferType = SECBUFFER_TOKEN; buf.pvBuffer = ntlmbuf; status = s_pSecFn->InitializeSecurityContext(&ntlm->handle, NULL, (TCHAR *) TEXT(""), ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONNECTION, 0, SECURITY_NETWORK_DREP, NULL, 0, &ntlm->c_handle, &desc, &attrs, &tsDummy); if(status == SEC_I_COMPLETE_AND_CONTINUE || status == SEC_I_CONTINUE_NEEDED) s_pSecFn->CompleteAuthToken(&ntlm->c_handle, &desc); else if(status != SEC_E_OK) { s_pSecFn->FreeCredentialsHandle(&ntlm->handle); return CURLE_RECV_ERROR; } ntlm->has_handles = 1; size = buf.cbBuffer; #else const char *host = ""; /* empty */ const char *domain = ""; /* empty */ size_t hostlen = 0; size_t domlen = 0; size_t hostoff = 0; size_t domoff = hostoff + hostlen; /* This is 0: remember that host and domain are empty */ (void)userp; (void)passwdp; (void)ntlm; #if USE_NTLM2SESSION #define NTLM2FLAG NTLMFLAG_NEGOTIATE_NTLM2_KEY #else #define NTLM2FLAG 0 #endif snprintf((char *)ntlmbuf, NTLM_BUFSIZE, NTLMSSP_SIGNATURE "%c" "\x01%c%c%c" /* 32-bit type = 1 */ "%c%c%c%c" /* 32-bit NTLM flag field */ "%c%c" /* domain length */ "%c%c" /* domain allocated space */ "%c%c" /* domain name offset */ "%c%c" /* 2 zeroes */ "%c%c" /* host length */ "%c%c" /* host allocated space */ "%c%c" /* host name offset */ "%c%c" /* 2 zeroes */ "%s" /* host name */ "%s", /* domain string */ 0, /* trailing zero */ 0, 0, 0, /* part of type-1 long */ LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), SHORTPAIR(domlen), SHORTPAIR(domlen), SHORTPAIR(domoff), 0, 0, SHORTPAIR(hostlen), SHORTPAIR(hostlen), SHORTPAIR(hostoff), 0, 0, host, /* this is empty */ domain /* this is empty */); /* Initial packet length */ size = 32 + hostlen + domlen; #endif DEBUG_OUT({ fprintf(stderr, "* TYPE1 header flags=0x%02.2x%02.2x%02.2x%02.2x " "0x%08.8x ", LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); ntlm_print_flags(stderr, NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); fprintf(stderr, "\n****\n"); }); /* Return with binary blob encoded into base64 */ return Curl_base64_encode(NULL, (char *)ntlmbuf, size, outptr, outlen); }
/* * Curl_ntlm_create_type1_message() * * This is used to generate an already encoded NTLM type-1 message ready * for sending to the recipient, be it a: HTTP, SMTP or POP3 server, * using the appropriate compile time crypo API. * * Parameters: * * userp [in] - The user name in the format User or Domain\User. * passdwp [in] - The user's password. * ntlm [in/out] - The ntlm data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_msgs.c#L323-L550
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_create_type3_message
CURLcode Curl_ntlm_create_type3_message(struct SessionHandle *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { /* NTLM type-3 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x03000000) 12 LM/LMv2 Response security buffer 20 NTLM/NTLMv2 Response security buffer 28 Target Name security buffer 36 User Name security buffer 44 Workstation Name security buffer (52) Session Key security buffer (*) (60) Flags long (*) (64) OS Version Structure 8 bytes (*) 52 (64) (72) Start of data block (*) -> Optional */ unsigned char ntlmbuf[NTLM_BUFSIZE]; size_t size; #ifdef USE_WINDOWS_SSPI SecBuffer type_2; SecBuffer type_3; SecBufferDesc type_2_desc; SecBufferDesc type_3_desc; SECURITY_STATUS status; unsigned long attrs; TimeStamp tsDummy; /* For Windows 9x compatibility of SSPI calls */ (void)passwdp; (void)userp; (void)data; type_2_desc.ulVersion = type_3_desc.ulVersion = SECBUFFER_VERSION; type_2_desc.cBuffers = type_3_desc.cBuffers = 1; type_2_desc.pBuffers = &type_2; type_3_desc.pBuffers = &type_3; type_2.BufferType = SECBUFFER_TOKEN; type_2.pvBuffer = ntlm->type_2; type_2.cbBuffer = ntlm->n_type_2; type_3.BufferType = SECBUFFER_TOKEN; type_3.pvBuffer = ntlmbuf; type_3.cbBuffer = NTLM_BUFSIZE; status = s_pSecFn->InitializeSecurityContext(&ntlm->handle, &ntlm->c_handle, (TCHAR *) TEXT(""), ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONNECTION, 0, SECURITY_NETWORK_DREP, &type_2_desc, 0, &ntlm->c_handle, &type_3_desc, &attrs, &tsDummy); if(status != SEC_E_OK) return CURLE_RECV_ERROR; size = type_3.cbBuffer; Curl_ntlm_sspi_cleanup(ntlm); #else int lmrespoff; unsigned char lmresp[24]; /* fixed-size */ #if USE_NTRESPONSES int ntrespoff; unsigned char ntresp[24]; /* fixed-size */ #endif bool unicode = (ntlm->flags & NTLMFLAG_NEGOTIATE_UNICODE) ? TRUE : FALSE; char host[HOSTNAME_MAX + 1] = ""; const char *user; const char *domain = ""; size_t hostoff = 0; size_t useroff = 0; size_t domoff = 0; size_t hostlen = 0; size_t userlen = 0; size_t domlen = 0; CURLcode res; user = strchr(userp, '\\'); if(!user) user = strchr(userp, '/'); if(user) { domain = userp; domlen = (user - domain); user++; } else user = userp; if(user) userlen = strlen(user); /* Get the machine's un-qualified host name as NTLM doesn't like the fully qualified domain name */ if(Curl_gethostname(host, sizeof(host))) { infof(data, "gethostname() failed, continuing without!\n"); hostlen = 0; } else { hostlen = strlen(host); } if(unicode) { domlen = domlen * 2; userlen = userlen * 2; hostlen = hostlen * 2; } #if USE_NTLM2SESSION /* We don't support NTLM2 if we don't have USE_NTRESPONSES */ if(ntlm->flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) { unsigned char ntbuffer[0x18]; unsigned char tmp[0x18]; unsigned char md5sum[MD5_DIGEST_LENGTH]; unsigned char entropy[8]; /* Need to create 8 bytes random data */ Curl_ssl_random(data, entropy, sizeof(entropy)); /* 8 bytes random data as challenge in lmresp */ memcpy(lmresp, entropy, 8); /* Pad with zeros */ memset(lmresp + 8, 0, 0x10); /* Fill tmp with challenge(nonce?) + entropy */ memcpy(tmp, &ntlm->nonce[0], 8); memcpy(tmp + 8, entropy, 8); Curl_ssl_md5sum(tmp, 16, md5sum, MD5_DIGEST_LENGTH); /* We shall only use the first 8 bytes of md5sum, but the des code in Curl_ntlm_core_lm_resp only encrypt the first 8 bytes */ if(CURLE_OUT_OF_MEMORY == Curl_ntlm_core_mk_nt_hash(data, passwdp, ntbuffer)) return CURLE_OUT_OF_MEMORY; Curl_ntlm_core_lm_resp(ntbuffer, md5sum, ntresp); /* End of NTLM2 Session code */ } else #endif { #if USE_NTRESPONSES unsigned char ntbuffer[0x18]; #endif unsigned char lmbuffer[0x18]; #if USE_NTRESPONSES if(CURLE_OUT_OF_MEMORY == Curl_ntlm_core_mk_nt_hash(data, passwdp, ntbuffer)) return CURLE_OUT_OF_MEMORY; Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], ntresp); #endif Curl_ntlm_core_mk_lm_hash(data, passwdp, lmbuffer); Curl_ntlm_core_lm_resp(lmbuffer, &ntlm->nonce[0], lmresp); /* A safer but less compatible alternative is: * Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], lmresp); * See http://davenport.sourceforge.net/ntlm.html#ntlmVersion2 */ } lmrespoff = 64; /* size of the message header */ #if USE_NTRESPONSES ntrespoff = lmrespoff + 0x18; domoff = ntrespoff + 0x18; #else domoff = lmrespoff + 0x18; #endif useroff = domoff + domlen; hostoff = useroff + userlen; /* Create the big type-3 message binary blob */ size = snprintf((char *)ntlmbuf, NTLM_BUFSIZE, NTLMSSP_SIGNATURE "%c" "\x03%c%c%c" /* 32-bit type = 3 */ "%c%c" /* LanManager length */ "%c%c" /* LanManager allocated space */ "%c%c" /* LanManager offset */ "%c%c" /* 2 zeroes */ "%c%c" /* NT-response length */ "%c%c" /* NT-response allocated space */ "%c%c" /* NT-response offset */ "%c%c" /* 2 zeroes */ "%c%c" /* domain length */ "%c%c" /* domain allocated space */ "%c%c" /* domain name offset */ "%c%c" /* 2 zeroes */ "%c%c" /* user length */ "%c%c" /* user allocated space */ "%c%c" /* user offset */ "%c%c" /* 2 zeroes */ "%c%c" /* host length */ "%c%c" /* host allocated space */ "%c%c" /* host offset */ "%c%c" /* 2 zeroes */ "%c%c" /* session key length (unknown purpose) */ "%c%c" /* session key allocated space (unknown purpose) */ "%c%c" /* session key offset (unknown purpose) */ "%c%c" /* 2 zeroes */ "%c%c%c%c", /* flags */ /* domain string */ /* user string */ /* host string */ /* LanManager response */ /* NT response */ 0, /* zero termination */ 0, 0, 0, /* type-3 long, the 24 upper bits */ SHORTPAIR(0x18), /* LanManager response length, twice */ SHORTPAIR(0x18), SHORTPAIR(lmrespoff), 0x0, 0x0, #if USE_NTRESPONSES SHORTPAIR(0x18), /* NT-response length, twice */ SHORTPAIR(0x18), SHORTPAIR(ntrespoff), 0x0, 0x0, #else 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, #endif SHORTPAIR(domlen), SHORTPAIR(domlen), SHORTPAIR(domoff), 0x0, 0x0, SHORTPAIR(userlen), SHORTPAIR(userlen), SHORTPAIR(useroff), 0x0, 0x0, SHORTPAIR(hostlen), SHORTPAIR(hostlen), SHORTPAIR(hostoff), 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, LONGQUARTET(ntlm->flags)); DEBUGASSERT(size == 64); DEBUGASSERT(size == (size_t)lmrespoff); /* We append the binary hashes */ if(size < (NTLM_BUFSIZE - 0x18)) { memcpy(&ntlmbuf[size], lmresp, 0x18); size += 0x18; } DEBUG_OUT({ fprintf(stderr, "**** TYPE3 header lmresp="); ntlm_print_hex(stderr, (char *)&ntlmbuf[lmrespoff], 0x18); }); #if USE_NTRESPONSES if(size < (NTLM_BUFSIZE - 0x18)) { DEBUGASSERT(size == (size_t)ntrespoff); memcpy(&ntlmbuf[size], ntresp, 0x18); size += 0x18; } DEBUG_OUT({ fprintf(stderr, "\n ntresp="); ntlm_print_hex(stderr, (char *)&ntlmbuf[ntrespoff], 0x18); }); #endif DEBUG_OUT({ fprintf(stderr, "\n flags=0x%02.2x%02.2x%02.2x%02.2x 0x%08.8x ", LONGQUARTET(ntlm->flags), ntlm->flags); ntlm_print_flags(stderr, ntlm->flags); fprintf(stderr, "\n****\n"); }); /* Make sure that the domain, user and host strings fit in the buffer before we copy them there. */ if(size + userlen + domlen + hostlen >= NTLM_BUFSIZE) { failf(data, "user + domain + host name too big"); return CURLE_OUT_OF_MEMORY; } DEBUGASSERT(size == domoff); if(unicode) unicodecpy(&ntlmbuf[size], domain, domlen / 2); else memcpy(&ntlmbuf[size], domain, domlen); size += domlen; DEBUGASSERT(size == useroff); if(unicode) unicodecpy(&ntlmbuf[size], user, userlen / 2); else memcpy(&ntlmbuf[size], user, userlen); size += userlen; DEBUGASSERT(size == hostoff); if(unicode) unicodecpy(&ntlmbuf[size], host, hostlen / 2); else memcpy(&ntlmbuf[size], host, hostlen); size += hostlen; /* Convert domain, user, and host to ASCII but leave the rest as-is */ res = Curl_convert_to_network(data, (char *)&ntlmbuf[domoff], size - domoff); if(res) return CURLE_CONV_FAILED; #endif /* Return with binary blob encoded into base64 */ return Curl_base64_encode(NULL, (char *)ntlmbuf, size, outptr, outlen); }
/* * Curl_ntlm_create_type3_message() * * This is used to generate an already encoded NTLM type-3 message ready * for sending to the recipient, be it a: HTTP, SMTP or POP3 server, * using the appropriate compile time crypo API. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passdwp [in] - The user's password. * ntlm [in/out] - The ntlm data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_msgs.c#L571-L917
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_output_ntlm_wb
CURLcode Curl_output_ntlm_wb(struct connectdata *conn, bool proxy) { /* 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 name and password for this */ const char *userp; /* point to the correct struct with this */ struct ntlmdata *ntlm; struct auth *authp; CURLcode res = CURLE_OK; char *input; DEBUGASSERT(conn); DEBUGASSERT(conn->data); if(proxy) { allocuserpwd = &conn->allocptr.proxyuserpwd; userp = conn->proxyuser; ntlm = &conn->proxyntlm; authp = &conn->data->state.authproxy; } else { allocuserpwd = &conn->allocptr.userpwd; userp = conn->user; ntlm = &conn->ntlm; authp = &conn->data->state.authhost; } authp->done = FALSE; /* not set means empty */ if(!userp) userp=""; switch(ntlm->state) { case NTLMSTATE_TYPE1: default: /* Use Samba's 'winbind' daemon to support NTLM authentication, * by delegating the NTLM challenge/response protocal to a helper * in ntlm_auth. * http://devel.squid-cache.org/ntlm/squid_helper_protocol.html * http://www.samba.org/samba/docs/man/manpages-3/winbindd.8.html * http://www.samba.org/samba/docs/man/manpages-3/ntlm_auth.1.html * Preprocessor symbol 'NTLM_WB_ENABLED' is defined when this * feature is enabled and 'NTLM_WB_FILE' symbol holds absolute * filename of ntlm_auth helper. * If NTLM authentication using winbind fails, go back to original * request handling process. */ /* Create communication with ntlm_auth */ res = ntlm_wb_init(conn, userp); if(res) return res; res = ntlm_wb_response(conn, "YR\n", ntlm->state); if(res) return res; Curl_safefree(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: %s\r\n", proxy ? "Proxy-" : "", conn->response_header); DEBUG_OUT(fprintf(stderr, "**** Header %s\n ", *allocuserpwd)); Curl_safefree(conn->response_header); conn->response_header = NULL; break; case NTLMSTATE_TYPE2: input = aprintf("TT %s", conn->challenge_header); if(!input) return CURLE_OUT_OF_MEMORY; res = ntlm_wb_response(conn, input, ntlm->state); free(input); input = NULL; if(res) return res; Curl_safefree(*allocuserpwd); *allocuserpwd = aprintf("%sAuthorization: %s\r\n", proxy ? "Proxy-" : "", conn->response_header); DEBUG_OUT(fprintf(stderr, "**** %s\n ", *allocuserpwd)); ntlm->state = NTLMSTATE_TYPE3; /* we sent a type-3 */ authp->done = TRUE; Curl_ntlm_wb_cleanup(conn); break; case NTLMSTATE_TYPE3: /* connection is already authenticated, * don't send a header in future requests */ if(*allocuserpwd) { free(*allocuserpwd); *allocuserpwd=NULL; } authp->done = TRUE; break; } return CURLE_OK; }
/* * This is for creating ntlm header output by delegating challenge/response * to Samba's winbind daemon helper ntlm_auth. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_wb.c#L291-L389
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_sspi_global_init
CURLcode Curl_sspi_global_init(void) { OSVERSIONINFO osver; INITSECURITYINTERFACE_FN pInitSecurityInterface; /* If security interface is not yet initialized try to do this */ if(!s_hSecDll) { /* Find out Windows version */ memset(&osver, 0, sizeof(osver)); osver.dwOSVersionInfoSize = sizeof(osver); if(!GetVersionEx(&osver)) return CURLE_FAILED_INIT; /* Security Service Provider Interface (SSPI) functions are located in * security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP * have both these DLLs (security.dll forwards calls to secur32.dll) */ /* Load SSPI dll into the address space of the calling process */ if(osver.dwPlatformId == VER_PLATFORM_WIN32_NT && osver.dwMajorVersion == 4) s_hSecDll = LoadLibrary(TEXT("security.dll")); else s_hSecDll = LoadLibrary(TEXT("secur32.dll")); if(!s_hSecDll) return CURLE_FAILED_INIT; /* Get address of the InitSecurityInterfaceA function from the SSPI dll */ pInitSecurityInterface = (INITSECURITYINTERFACE_FN) GetProcAddress(s_hSecDll, SECURITYENTRYPOINT); if(!pInitSecurityInterface) return CURLE_FAILED_INIT; /* Get pointer to Security Service Provider Interface dispatch table */ s_pSecFn = pInitSecurityInterface(); if(!s_pSecFn) return CURLE_FAILED_INIT; } return CURLE_OK; }
/* * Curl_sspi_global_init() * * This is used to load the Security Service Provider Interface (SSPI) * dynamic link library portably across all Windows versions, without * the need to directly link libcurl, nor the application using it, at * build time. * * Once this function has been executed, Windows SSPI functions can be * called through the Security Service Provider Interface dispatch table. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_sspi.c#L69-L109
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_sspi_global_cleanup
void Curl_sspi_global_cleanup(void) { if(s_hSecDll) { FreeLibrary(s_hSecDll); s_hSecDll = NULL; s_pSecFn = NULL; } }
/* * Curl_sspi_global_cleanup() * * This deinitializes the Security Service Provider Interface from libcurl. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_sspi.c#L117-L124
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
cyassl_connect_step1
static CURLcode cyassl_connect_step1(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; struct ssl_connect_data* conssl = &conn->ssl[sockindex]; SSL_METHOD* req_method = NULL; void* ssl_sessionid = NULL; curl_socket_t sockfd = conn->sock[sockindex]; if(conssl->state == ssl_connection_complete) return CURLE_OK; /* CyaSSL doesn't support SSLv2 */ if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) { failf(data, "CyaSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } /* check to see if we've been told to use an explicit SSL/TLS version */ switch(data->set.ssl.version) { case CURL_SSLVERSION_DEFAULT: /* we try to figure out version */ req_method = SSLv23_client_method(); break; case CURL_SSLVERSION_TLSv1: req_method = TLSv1_client_method(); break; case CURL_SSLVERSION_SSLv3: req_method = SSLv3_client_method(); break; default: req_method = TLSv1_client_method(); } if(!req_method) { failf(data, "SSL: couldn't create a method!"); return CURLE_OUT_OF_MEMORY; } if(conssl->ctx) SSL_CTX_free(conssl->ctx); conssl->ctx = SSL_CTX_new(req_method); if(!conssl->ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } #ifndef NO_FILESYSTEM /* load trusted cacert */ if(data->set.str[STRING_SSL_CAFILE]) { if(!SSL_CTX_load_verify_locations(conssl->ctx, data->set.str[STRING_SSL_CAFILE], data->set.str[STRING_SSL_CAPATH])) { if(data->set.ssl.verifypeer) { /* Fail if we insiste on successfully verifying the server. */ failf(data,"error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s", data->set.str[STRING_SSL_CAFILE]? data->set.str[STRING_SSL_CAFILE]: "none", data->set.str[STRING_SSL_CAPATH]? data->set.str[STRING_SSL_CAPATH] : "none"); return CURLE_SSL_CACERT_BADFILE; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]: "none", data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]: "none"); } /* Load the client certificate, and private key */ if(data->set.str[STRING_CERT] && data->set.str[STRING_KEY]) { int file_type = do_file_type(data->set.str[STRING_CERT_TYPE]); if(SSL_CTX_use_certificate_file(conssl->ctx, data->set.str[STRING_CERT], file_type) != 1) { failf(data, "unable to use client certificate (no key or wrong pass" " phrase?)"); return CURLE_SSL_CONNECT_ERROR; } file_type = do_file_type(data->set.str[STRING_KEY_TYPE]); if(SSL_CTX_use_PrivateKey_file(conssl->ctx, data->set.str[STRING_KEY], file_type) != 1) { failf(data, "unable to set private key"); return CURLE_SSL_CONNECT_ERROR; } } #else if(CyaSSL_no_filesystem_verify(conssl->ctx)!= SSL_SUCCESS) { return CURLE_SSL_CONNECT_ERROR; } #endif /* NO_FILESYSTEM */ /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ SSL_CTX_set_verify(conssl->ctx, data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE, NULL); /* Let's make an SSL structure */ if(conssl->handle) SSL_free(conssl->handle); conssl->handle = SSL_new(conssl->ctx); if(!conssl->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } /* Check if there's a cached ID we can/should use here! */ if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) { /* we got a session id, use it! */ if(!SSL_set_session(conssl->handle, ssl_sessionid)) { failf(data, "SSL: SSL_set_session failed: %s", ERR_error_string(SSL_get_error(conssl->handle, 0),NULL)); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof (data, "SSL re-using session ID\n"); } /* pass the raw socket into the SSL layer */ if(!SSL_set_fd(conssl->handle, (int)sockfd)) { failf(data, "SSL: SSL_set_fd failed"); return CURLE_SSL_CONNECT_ERROR; } conssl->connecting_state = ssl_connect_2; return CURLE_OK; }
/* * This function loads all the client/CA certificates and CRLs. Setup the TLS * layer and do all necessary magic. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/cyassl.c#L75-L221
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_cyassl_shutdown
int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->handle) { SSL_free (connssl->handle); connssl->handle = NULL; } return retval; }
/* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/cyassl.c#L460-L470
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_isunreserved
static bool Curl_isunreserved(unsigned char in) { switch (in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return TRUE; default: break; } return FALSE; }
/* Portable character check (remember EBCDIC). Do not use isalnum() because its behavior is altered by the current locale. See http://tools.ietf.org/html/rfc3986#section-2.3 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/escape.c#L46-L67
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_urldecode
CURLcode Curl_urldecode(struct SessionHandle *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string))+1; char *ns = malloc(alloc); unsigned char in; size_t strindex=0; unsigned long hex; CURLcode res; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(data, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return res; } string+=2; alloc-=2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; if(ostring) /* store output string */ *ostring = ns; return CURLE_OK; }
/* * Curl_urldecode() URL decodes the given string. * * Optionally detects control characters (byte codes lower than 32) in the * data and rejects such data. * * Returns a pointer to a malloced string in *ostring with length given in * *olen. If length == 0, the length is assumed to be strlen(string). * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/escape.c#L145-L203
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curl_free
void curl_free(void *p) { if(p) free(p); }
/* For operating systems/environments that use different malloc/free systems for the app and for this library, we provide a free that uses the library's memory system */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/escape.c#L229-L233
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
file_range
static CURLcode file_range(struct connectdata *conn) { curl_off_t from, to; curl_off_t totalsize=-1; char *ptr; char *ptr2; struct SessionHandle *data = conn->data; if(data->state.use_range && data->state.range) { from=curlx_strtoofft(data->state.range, &ptr, 0); while(*ptr && (ISSPACE(*ptr) || (*ptr=='-'))) ptr++; to=curlx_strtoofft(ptr, &ptr2, 0); if(ptr == ptr2) { /* we didn't get any digit */ to=-1; } if((-1 == to) && (from>=0)) { /* X - */ data->state.resume_from = from; DEBUGF(infof(data, "RANGE %" FORMAT_OFF_T " to end of file\n", from)); } else if(from < 0) { /* -Y */ data->req.maxdownload = -from; data->state.resume_from = from; DEBUGF(infof(data, "RANGE the last %" FORMAT_OFF_T " bytes\n", -from)); } else { /* X-Y */ totalsize = to-from; data->req.maxdownload = totalsize+1; /* include last byte */ data->state.resume_from = from; DEBUGF(infof(data, "RANGE from %" FORMAT_OFF_T " getting %" FORMAT_OFF_T " bytes\n", from, data->req.maxdownload)); } DEBUGF(infof(data, "range-download from %" FORMAT_OFF_T " to %" FORMAT_OFF_T ", totally %" FORMAT_OFF_T " bytes\n", from, to, data->req.maxdownload)); } else data->req.maxdownload = -1; return CURLE_OK; }
/* Check if this is a range download, and if so, set the internal variables properly. This code is copied from the FTP implementation and might as well be factored out. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/file.c#L125-L171
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
file_connect
static CURLcode file_connect(struct connectdata *conn, bool *done) { struct SessionHandle *data = conn->data; char *real_path; struct FILEPROTO *file; int fd; #ifdef DOS_FILESYSTEM int i; char *actual_path; #endif /* If there already is a protocol-specific struct allocated for this sessionhandle, deal with it */ Curl_reset_reqproto(conn); real_path = curl_easy_unescape(data, data->state.path, 0, NULL); if(!real_path) return CURLE_OUT_OF_MEMORY; if(!data->state.proto.file) { file = calloc(1, sizeof(struct FILEPROTO)); if(!file) { free(real_path); return CURLE_OUT_OF_MEMORY; } data->state.proto.file = file; } else { /* file is not a protocol that can deal with "persistancy" */ file = data->state.proto.file; Curl_safefree(file->freepath); file->path = NULL; if(file->fd != -1) close(file->fd); file->fd = -1; } #ifdef DOS_FILESYSTEM /* If the first character is a slash, and there's something that looks like a drive at the beginning of the path, skip the slash. If we remove the initial slash in all cases, paths without drive letters end up relative to the current directory which isn't how browsers work. Some browsers accept | instead of : as the drive letter separator, so we do too. On other platforms, we need the slash to indicate an absolute pathname. On Windows, absolute paths start with a drive letter. */ actual_path = real_path; if((actual_path[0] == '/') && actual_path[1] && (actual_path[2] == ':' || actual_path[2] == '|')) { actual_path[2] = ':'; actual_path++; } /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */ for(i=0; actual_path[i] != '\0'; ++i) if(actual_path[i] == '/') actual_path[i] = '\\'; fd = open_readonly(actual_path, O_RDONLY|O_BINARY); file->path = actual_path; #else fd = open_readonly(real_path, O_RDONLY); file->path = real_path; #endif file->freepath = real_path; /* free this when done */ file->fd = fd; if(!data->set.upload && (fd == -1)) { failf(data, "Couldn't open file %s", data->state.path); file_done(conn, CURLE_FILE_COULDNT_READ_FILE, FALSE); return CURLE_FILE_COULDNT_READ_FILE; } *done = TRUE; return CURLE_OK; }
/* * file_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. We emulate a * connect-then-transfer protocol and "connect" to the file here */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/file.c#L178-L260
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
file_do
static CURLcode file_do(struct connectdata *conn, bool *done) { /* This implementation ignores the host name in conformance with RFC 1738. Only local files (reachable via the standard file system) are supported. This means that files on remotely mounted directories (via NFS, Samba, NT sharing) can be accessed through a file:// URL */ CURLcode res = CURLE_OK; struct_stat statbuf; /* struct_stat instead of struct stat just to allow the Windows version to have a different struct without having to redefine the simple word 'stat' */ curl_off_t expected_size=0; bool fstated=FALSE; ssize_t nread; struct SessionHandle *data = conn->data; char *buf = data->state.buffer; curl_off_t bytecount = 0; int fd; struct timeval now = Curl_tvnow(); *done = TRUE; /* unconditionally */ Curl_initinfo(data); Curl_pgrsStartNow(data); if(data->set.upload) return file_upload(conn); /* get the fd from the connection phase */ fd = conn->data->state.proto.file->fd; /* VMS: This only works reliable for STREAMLF files */ if(-1 != fstat(fd, &statbuf)) { /* we could stat it, then read out the size */ expected_size = statbuf.st_size; /* and store the modification time */ data->info.filetime = (long)statbuf.st_mtime; fstated = TRUE; } if(fstated && !data->state.range && data->set.timecondition) { if(!Curl_meets_timecondition(data, (time_t)data->info.filetime)) { *done = TRUE; return CURLE_OK; } } /* If we have selected NOBODY and HEADER, it means that we only want file information. Which for FILE can't be much more than the file size and date. */ if(data->set.opt_no_body && data->set.include_header && fstated) { CURLcode result; snprintf(buf, sizeof(data->state.buffer), "Content-Length: %" FORMAT_OFF_T "\r\n", expected_size); result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0); if(result) return result; result = Curl_client_write(conn, CLIENTWRITE_BOTH, (char *)"Accept-ranges: bytes\r\n", 0); if(result) return result; if(fstated) { time_t filetime = (time_t)statbuf.st_mtime; struct tm buffer; const struct tm *tm = &buffer; result = Curl_gmtime(filetime, &buffer); if(result) return result; /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */ snprintf(buf, BUFSIZE-1, "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n", Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], tm->tm_mday, Curl_month[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0); } /* if we fstat()ed the file, set the file size to make it available post- transfer */ if(fstated) Curl_pgrsSetDownloadSize(data, expected_size); return result; } /* Check whether file range has been specified */ file_range(conn); /* Adjust the start offset in case we want to get the N last bytes * of the stream iff the filesize could be determined */ if(data->state.resume_from < 0) { if(!fstated) { failf(data, "Can't get the size of file."); return CURLE_READ_ERROR; } else data->state.resume_from += (curl_off_t)statbuf.st_size; } if(data->state.resume_from <= expected_size) expected_size -= data->state.resume_from; else { failf(data, "failed to resume file:// transfer"); return CURLE_BAD_DOWNLOAD_RESUME; } /* A high water mark has been specified so we obey... */ if(data->req.maxdownload > 0) expected_size = data->req.maxdownload; if(fstated && (expected_size == 0)) return CURLE_OK; /* The following is a shortcut implementation of file reading this is both more efficient than the former call to download() and it avoids problems with select() and recv() on file descriptors in Winsock */ if(fstated) Curl_pgrsSetDownloadSize(data, expected_size); if(data->state.resume_from) { if(data->state.resume_from != lseek(fd, data->state.resume_from, SEEK_SET)) return CURLE_BAD_DOWNLOAD_RESUME; } Curl_pgrsTime(data, TIMER_STARTTRANSFER); while(res == CURLE_OK) { /* Don't fill a whole buffer if we want less than all data */ size_t bytestoread = (expected_size < CURL_OFF_T_C(BUFSIZE) - CURL_OFF_T_C(1)) ? curlx_sotouz(expected_size) : BUFSIZE - 1; nread = read(fd, buf, bytestoread); if(nread > 0) buf[nread] = 0; if(nread <= 0 || expected_size == 0) break; bytecount += nread; expected_size -= nread; res = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread); if(res) return res; Curl_pgrsSetDownloadCounter(data, bytecount); if(Curl_pgrsUpdate(conn)) res = CURLE_ABORTED_BY_CALLBACK; else res = Curl_speedcheck(data, now); } if(Curl_pgrsUpdate(conn)) res = CURLE_ABORTED_BY_CALLBACK; return res; }
/* * file_do() is the protocol-specific function for the do-phase, separated * from the connect-phase above. Other protocols merely setup the transfer in * the do-phase, to have it done in the main transfer loop but since some * platforms we support don't allow select()ing etc on file handles (as * opposed to sockets) we instead perform the whole do-operation in this * function. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/file.c#L424-L589
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
FormAdd
static CURLFORMcode FormAdd(struct curl_httppost **httppost, struct curl_httppost **last_post, va_list params) { FormInfo *first_form, *current_form, *form = NULL; CURLFORMcode return_value = CURL_FORMADD_OK; const char *prevtype = NULL; struct curl_httppost *post = NULL; CURLformoption option; struct curl_forms *forms = NULL; char *array_value=NULL; /* value read from an array */ /* This is a state variable, that if TRUE means that we're parsing an array that we got passed to us. If FALSE we're parsing the input va_list arguments. */ bool array_state = FALSE; /* * We need to allocate the first struct to fill in. */ first_form = calloc(1, sizeof(struct FormInfo)); if(!first_form) return CURL_FORMADD_MEMORY; current_form = first_form; /* * Loop through all the options set. Break if we have an error to report. */ while(return_value == CURL_FORMADD_OK) { /* first see if we have more parts of the array param */ if(array_state && forms) { /* get the upcoming option from the given array */ option = forms->option; array_value = (char *)forms->value; forms++; /* advance this to next entry */ if(CURLFORM_END == option) { /* end of array state */ array_state = FALSE; continue; } } else { /* This is not array-state, get next option */ option = va_arg(params, CURLformoption); if(CURLFORM_END == option) break; } switch (option) { case CURLFORM_ARRAY: if(array_state) /* we don't support an array from within an array */ return_value = CURL_FORMADD_ILLEGAL_ARRAY; else { forms = va_arg(params, struct curl_forms *); if(forms) array_state = TRUE; else return_value = CURL_FORMADD_NULL; } break; /* * Set the Name property. */ case CURLFORM_PTRNAME: #ifdef CURL_DOES_CONVERSIONS /* Treat CURLFORM_PTR like CURLFORM_COPYNAME so that libcurl will copy * the data in all cases so that we'll have safe memory for the eventual * conversion. */ #else current_form->flags |= HTTPPOST_PTRNAME; /* fall through */ #endif case CURLFORM_COPYNAME: if(current_form->name) return_value = CURL_FORMADD_OPTION_TWICE; else { char *name = array_state? array_value:va_arg(params, char *); if(name) current_form->name = name; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_NAMELENGTH: if(current_form->namelength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->namelength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; /* * Set the contents property. */ case CURLFORM_PTRCONTENTS: current_form->flags |= HTTPPOST_PTRCONTENTS; /* fall through */ case CURLFORM_COPYCONTENTS: if(current_form->value) return_value = CURL_FORMADD_OPTION_TWICE; else { char *value = array_state?array_value:va_arg(params, char *); if(value) current_form->value = value; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTSLENGTH: if(current_form->contentslength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->contentslength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; /* Get contents from a given file name */ case CURLFORM_FILECONTENT: if(current_form->flags != 0) return_value = CURL_FORMADD_OPTION_TWICE; else { const char *filename = array_state? array_value:va_arg(params, char *); if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_READFILE; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; /* We upload a file */ case CURLFORM_FILE: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->value) { if(current_form->flags & HTTPPOST_FILENAME) { if(filename) { char *fname = strdup(filename); if(!fname) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(fname, NULL, current_form); if(!form) { Curl_safefree(fname); return_value = CURL_FORMADD_MEMORY; } else { form->value_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_FILENAME; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_BUFFERPTR: current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER; if(current_form->buffer) return_value = CURL_FORMADD_OPTION_TWICE; else { char *buffer = array_state?array_value:va_arg(params, char *); if(buffer) { current_form->buffer = buffer; /* store for the moment */ current_form->value = buffer; /* make it non-NULL to be accepted as fine */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_BUFFERLENGTH: if(current_form->bufferlength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->bufferlength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; case CURLFORM_STREAM: current_form->flags |= HTTPPOST_CALLBACK; if(current_form->userp) return_value = CURL_FORMADD_OPTION_TWICE; else { char *userp = array_state?array_value:va_arg(params, char *); if(userp) { current_form->userp = userp; current_form->value = userp; /* this isn't strictly true but we derive a value from this later on and we need this non-NULL to be accepted as a fine form part */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTTYPE: { const char *contenttype = array_state?array_value:va_arg(params, char *); if(current_form->contenttype) { if(current_form->flags & HTTPPOST_FILENAME) { if(contenttype) { char *type = strdup(contenttype); if(!type) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(NULL, type, current_form); if(!form) { Curl_safefree(type); return_value = CURL_FORMADD_MEMORY; } else { form->contenttype_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(contenttype) { current_form->contenttype = strdup(contenttype); if(!current_form->contenttype) return_value = CURL_FORMADD_MEMORY; else current_form->contenttype_alloc = TRUE; } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_CONTENTHEADER: { /* this "cast increases required alignment of target type" but we consider it OK anyway */ struct curl_slist* list = array_state? (struct curl_slist*)array_value: va_arg(params, struct curl_slist*); if(current_form->contentheader) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->contentheader = list; break; } case CURLFORM_FILENAME: case CURLFORM_BUFFER: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->showfilename) return_value = CURL_FORMADD_OPTION_TWICE; else { current_form->showfilename = strdup(filename); if(!current_form->showfilename) return_value = CURL_FORMADD_MEMORY; else current_form->showfilename_alloc = TRUE; } break; } default: return_value = CURL_FORMADD_UNKNOWN_OPTION; break; } } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for all nodes of the FormInfo linked list without deallocating nodes. List nodes are deallocated later on */ FormInfo *ptr; for(ptr = first_form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } if(CURL_FORMADD_OK == return_value) { /* go through the list, check for completeness and if everything is * alright add the HttpPost item otherwise set return_value accordingly */ post = NULL; for(form = first_form; form != NULL; form = form->more) { if(((!form->name || !form->value) && !post) || ( (form->contentslength) && (form->flags & HTTPPOST_FILENAME) ) || ( (form->flags & HTTPPOST_FILENAME) && (form->flags & HTTPPOST_PTRCONTENTS) ) || ( (!form->buffer) && (form->flags & HTTPPOST_BUFFER) && (form->flags & HTTPPOST_PTRBUFFER) ) || ( (form->flags & HTTPPOST_READFILE) && (form->flags & HTTPPOST_PTRCONTENTS) ) ) { return_value = CURL_FORMADD_INCOMPLETE; break; } else { if(((form->flags & HTTPPOST_FILENAME) || (form->flags & HTTPPOST_BUFFER)) && !form->contenttype ) { /* our contenttype is missing */ form->contenttype = strdup(ContentTypeForFilename(form->value, prevtype)); if(!form->contenttype) { return_value = CURL_FORMADD_MEMORY; break; } form->contenttype_alloc = TRUE; } if(!(form->flags & HTTPPOST_PTRNAME) && (form == first_form) ) { /* Note that there's small risk that form->name is NULL here if the app passed in a bad combo, so we better check for that first. */ if(form->name) /* copy name (without strdup; possibly contains null characters) */ form->name = memdup(form->name, form->namelength); if(!form->name) { return_value = CURL_FORMADD_MEMORY; break; } form->name_alloc = TRUE; } if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE | HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | HTTPPOST_CALLBACK)) ) { /* copy value (without strdup; possibly contains null characters) */ form->value = memdup(form->value, form->contentslength); if(!form->value) { return_value = CURL_FORMADD_MEMORY; break; } form->value_alloc = TRUE; } post = AddHttpPost(form->name, form->namelength, form->value, form->contentslength, form->buffer, form->bufferlength, form->contenttype, form->flags, form->contentheader, form->showfilename, form->userp, post, httppost, last_post); if(!post) { return_value = CURL_FORMADD_MEMORY; break; } if(form->contenttype) prevtype = form->contenttype; } } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for nodes of the FormInfo linked list which are not already owned by the httppost linked list without deallocating nodes. List nodes are deallocated later on */ FormInfo *ptr; for(ptr = form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } } /* Always deallocate FormInfo linked list nodes without touching node fields given that these have either been deallocated or are owned now by the httppost linked list */ while(first_form) { FormInfo *ptr = first_form->more; Curl_safefree(first_form); first_form = ptr; } return return_value; }
/*************************************************************************** * * FormAdd() * * Stores a formpost parameter and builds the appropriate linked list. * * Has two principal functionalities: using files and byte arrays as * post parts. Byte arrays are either copied or just the pointer is stored * (as the user requests) while for files only the filename and not the * content is stored. * * While you may have only one byte array for each name, multiple filenames * are allowed (and because of this feature CURLFORM_END is needed after * using CURLFORM_FILE). * * Examples: * * Simple name/value pair with copied contents: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_COPYCONTENTS, "value", CURLFORM_END); * * name/value pair where only the content pointer is remembered: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END); * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used) * * storing a filename (CONTENTTYPE is optional!): * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text", * CURLFORM_END); * * storing multiple filenames: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END); * * Returns: * CURL_FORMADD_OK on success * CURL_FORMADD_MEMORY if the FormInfo allocation fails * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form * CURL_FORMADD_NULL if a null pointer was given for a char * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) * CURL_FORMADD_MEMORY if a HttpPost struct cannot be allocated * CURL_FORMADD_MEMORY if some allocation for string copying failed. * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array * ***************************************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L306-L759
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curl_formadd
CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { va_list arg; CURLFORMcode result; va_start(arg, last_post); result = FormAdd(httppost, last_post, arg); va_end(arg); return result; }
/* * curl_formadd() is a public API to add a section to the multipart formpost. * * @unittest: 1308 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L767-L777
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
AddFormData
static CURLcode AddFormData(struct FormData **formp, enum formtype type, const void *line, size_t length, curl_off_t *size) { struct FormData *newform = malloc(sizeof(struct FormData)); if(!newform) return CURLE_OUT_OF_MEMORY; newform->next = NULL; if(type <= FORM_CONTENT) { /* we make it easier for plain strings: */ if(!length) length = strlen((char *)line); newform->line = malloc(length+1); if(!newform->line) { free(newform); return CURLE_OUT_OF_MEMORY; } memcpy(newform->line, line, length); newform->length = length; newform->line[length]=0; /* zero terminate for easier debugging */ } else /* For callbacks and files we don't have any actual data so we just keep a pointer to whatever this points to */ newform->line = (char *)line; newform->type = type; if(*formp) { (*formp)->next = newform; *formp = newform; } else *formp = newform; if(size) { if(type != FORM_FILE) /* for static content as well as callback data we add the size given as input argument */ *size += length; else { /* Since this is a file to be uploaded here, add the size of the actual file */ if(!strequal("-", newform->line)) { struct_stat file; if(!stat(newform->line, &file) && S_ISREG(file.st_mode)) *size += file.st_size; else return CURLE_BAD_FUNCTION_ARGUMENT; } } } return CURLE_OK; }
/* * AddFormData() adds a chunk of data to the FormData linked list. * * size is incremented by the chunk length, unless it is NULL */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L784-L841
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
AddFormDataf
static CURLcode AddFormDataf(struct FormData **formp, curl_off_t *size, const char *fmt, ...) { char s[4096]; va_list ap; va_start(ap, fmt); vsnprintf(s, sizeof(s), fmt, ap); va_end(ap); return AddFormData(formp, FORM_DATA, s, 0, size); }
/* * AddFormDataf() adds printf()-style formatted data to the formdata chain. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L847-L858
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_formclean
void Curl_formclean(struct FormData **form_ptr) { struct FormData *next, *form; form = *form_ptr; if(!form) return; do { next=form->next; /* the following form line */ if(form->type <= FORM_CONTENT) free(form->line); /* free the line */ free(form); /* free the struct */ } while((form = next) != NULL); /* continue */ *form_ptr = NULL; }
/* * Curl_formclean() is used from http.c, this cleans a built FormData linked * list */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L864-L881
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curl_formget
int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append) { CURLcode rc; curl_off_t size; struct FormData *data, *ptr; rc = Curl_getformdata(NULL, &data, form, NULL, &size); if(rc != CURLE_OK) return (int)rc; for(ptr = data; ptr; ptr = ptr->next) { if((ptr->type == FORM_FILE) || (ptr->type == FORM_CALLBACK)) { char buffer[8192]; size_t nread; struct Form temp; Curl_FormInit(&temp, ptr); do { nread = readfromfile(&temp, buffer, sizeof(buffer)); if((nread == (size_t) -1) || (nread > sizeof(buffer)) || (nread != append(arg, buffer, nread))) { if(temp.fp) fclose(temp.fp); Curl_formclean(&data); return -1; } } while(nread); } else { if(ptr->length != append(arg, ptr->line, ptr->length)) { Curl_formclean(&data); return -1; } } } Curl_formclean(&data); return 0; }
/* * curl_formget() * Serialize a curl_httppost struct. * Returns 0 on success. * * @unittest: 1308 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L890-L930
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curl_formfree
void curl_formfree(struct curl_httppost *form) { struct curl_httppost *next; if(!form) /* no form to free, just get out of this */ return; do { next=form->next; /* the following form line */ /* recurse to sub-contents */ if(form->more) curl_formfree(form->more); if(!(form->flags & HTTPPOST_PTRNAME) && form->name) free(form->name); /* free the name */ if(!(form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_BUFFER|HTTPPOST_CALLBACK)) && form->contents) free(form->contents); /* free the contents */ if(form->contenttype) free(form->contenttype); /* free the content type */ if(form->showfilename) free(form->showfilename); /* free the faked file name */ free(form); /* free the struct */ } while((form = next) != NULL); /* continue */ }
/* * curl_formfree() is an external function to free up a whole form post * chain */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L936-L964
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_getformdata
CURLcode Curl_getformdata(struct SessionHandle *data, struct FormData **finalform, struct curl_httppost *post, const char *custom_content_type, curl_off_t *sizep) { struct FormData *form = NULL; struct FormData *firstform; struct curl_httppost *file; CURLcode result = CURLE_OK; curl_off_t size = 0; /* support potentially ENORMOUS formposts */ char *boundary; char *fileboundary = NULL; struct curl_slist* curList; *finalform = NULL; /* default form is empty */ if(!post) return result; /* no input => no output! */ boundary = Curl_FormBoundary(); if(!boundary) return CURLE_OUT_OF_MEMORY; /* Make the first line of the output */ result = AddFormDataf(&form, NULL, "%s; boundary=%s\r\n", custom_content_type?custom_content_type: "Content-Type: multipart/form-data", boundary); if(result) { Curl_safefree(boundary); return result; } /* we DO NOT include that line in the total size of the POST, since it'll be part of the header! */ firstform = form; do { if(size) { result = AddFormDataf(&form, &size, "\r\n"); if(result) break; } /* boundary */ result = AddFormDataf(&form, &size, "--%s\r\n", boundary); if(result) break; /* Maybe later this should be disabled when a custom_content_type is passed, since Content-Disposition is not meaningful for all multipart types. */ result = AddFormDataf(&form, &size, "Content-Disposition: form-data; name=\""); if(result) break; result = AddFormData(&form, FORM_DATA, post->name, post->namelength, &size); if(result) break; result = AddFormDataf(&form, &size, "\""); if(result) break; if(post->more) { /* If used, this is a link to more file names, we must then do the magic to include several files with the same field name */ Curl_safefree(fileboundary); fileboundary = Curl_FormBoundary(); if(!fileboundary) { result = CURLE_OUT_OF_MEMORY; break; } result = AddFormDataf(&form, &size, "\r\nContent-Type: multipart/mixed," " boundary=%s\r\n", fileboundary); if(result) break; } file = post; do { /* If 'showfilename' is set, that is a faked name passed on to us to use to in the formpost. If that is not set, the actually used local file name should be added. */ if(post->more) { /* if multiple-file */ result = AddFormDataf(&form, &size, "\r\n--%s\r\nContent-Disposition: " "attachment", fileboundary); if(result) break; result = formdata_add_filename(file, &form, &size); if(result) break; } else if(post->flags & (HTTPPOST_FILENAME|HTTPPOST_BUFFER| HTTPPOST_CALLBACK)) { /* it should be noted that for the HTTPPOST_FILENAME and HTTPPOST_CALLBACK cases the ->showfilename struct member is always assigned at this point */ if(post->showfilename || (post->flags & HTTPPOST_FILENAME)) { result = formdata_add_filename(post, &form, &size); } if(result) break; } if(file->contenttype) { /* we have a specified type */ result = AddFormDataf(&form, &size, "\r\nContent-Type: %s", file->contenttype); if(result) break; } curList = file->contentheader; while(curList) { /* Process the additional headers specified for this form */ result = AddFormDataf( &form, &size, "\r\n%s", curList->data ); if(result) break; curList = curList->next; } if(result) break; result = AddFormDataf(&form, &size, "\r\n\r\n"); if(result) break; if((post->flags & HTTPPOST_FILENAME) || (post->flags & HTTPPOST_READFILE)) { /* we should include the contents from the specified file */ FILE *fileread; fileread = strequal("-", file->contents)? stdin:fopen(file->contents, "rb"); /* binary read for win32 */ /* * VMS: This only allows for stream files on VMS. Stream files are * OK, as are FIXED & VAR files WITHOUT implied CC For implied CC, * every record needs to have a \n appended & 1 added to SIZE */ if(fileread) { if(fileread != stdin) { /* close the file */ fclose(fileread); /* add the file name only - for later reading from this */ result = AddFormData(&form, FORM_FILE, file->contents, 0, &size); } else { /* When uploading from stdin, we can't know the size of the file, * thus must read the full file as before. We *could* use chunked * transfer-encoding, but that only works for HTTP 1.1 and we * can't be sure we work with such a server. */ size_t nread; char buffer[512]; while((nread = fread(buffer, 1, sizeof(buffer), fileread)) != 0) { result = AddFormData(&form, FORM_CONTENT, buffer, nread, &size); if(result) break; } } } else { if(data) failf(data, "couldn't open file \"%s\"", file->contents); *finalform = NULL; result = CURLE_READ_ERROR; } } else if(post->flags & HTTPPOST_BUFFER) /* include contents of buffer */ result = AddFormData(&form, FORM_CONTENT, post->buffer, post->bufferlength, &size); else if(post->flags & HTTPPOST_CALLBACK) /* the contents should be read with the callback and the size is set with the contentslength */ result = AddFormData(&form, FORM_CALLBACK, post->userp, post->contentslength, &size); else /* include the contents we got */ result = AddFormData(&form, FORM_CONTENT, post->contents, post->contentslength, &size); file = file->more; } while(file && !result); /* for each specified file for this field */ if(result) break; if(post->more) { /* this was a multiple-file inclusion, make a termination file boundary: */ result = AddFormDataf(&form, &size, "\r\n--%s--", fileboundary); if(result) break; } } while((post = post->next) != NULL); /* for each field */ /* end-boundary for everything */ if(CURLE_OK == result) result = AddFormDataf(&form, &size, "\r\n--%s--\r\n", boundary); if(result) { Curl_formclean(&firstform); Curl_safefree(fileboundary); Curl_safefree(boundary); return result; } *sizep = size; Curl_safefree(fileboundary); Curl_safefree(boundary); *finalform = firstform; return result; }
/* * Curl_getformdata() converts a linked list of "meta data" into a complete * (possibly huge) multipart formdata. The input list is in 'post', while the * output resulting linked lists gets stored in '*finalform'. *sizep will get * the total size of the whole POST. * A multipart/form_data content-type is built, unless a custom content-type * is passed in 'custom_content_type'. * * This function will not do a failf() for the potential memory failures but * should for all other errors it spots. Just note that this function MAY get * a NULL pointer in the 'data' argument. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L1082-L1326
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_FormInit
int Curl_FormInit(struct Form *form, struct FormData *formdata ) { if(!formdata) return 1; /* error */ form->data = formdata; form->sent = 0; form->fp = NULL; form->fread_func = ZERO_NULL; return 0; }
/* * Curl_FormInit() inits the struct 'form' points to with the 'formdata' * and resets the 'sent' counter. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L1332-L1343
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
readfromfile
static size_t readfromfile(struct Form *form, char *buffer, size_t size) { size_t nread; bool callback = (form->data->type == FORM_CALLBACK)?TRUE:FALSE; if(callback) { if(form->fread_func == ZERO_NULL) return 0; else nread = form->fread_func(buffer, 1, size, form->data->line); } else { if(!form->fp) { /* this file hasn't yet been opened */ form->fp = fopen(form->data->line, "rb"); /* b is for binary */ if(!form->fp) return (size_t)-1; /* failure */ } nread = fread(buffer, 1, size, form->fp); } if(!nread) { /* this is the last chunk from the file, move on */ if(form->fp) { fclose(form->fp); form->fp = NULL; } form->data = form->data->next; } return nread; }
/* * readfromfile() * * The read callback that this function may use can return a value larger than * 'size' (which then this function returns) that indicates a problem and it * must be properly dealt with */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L1352-L1383
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_FormReader
size_t Curl_FormReader(char *buffer, size_t size, size_t nitems, FILE *mydata) { struct Form *form; size_t wantedsize; size_t gotsize = 0; form=(struct Form *)mydata; wantedsize = size * nitems; if(!form->data) return 0; /* nothing, error, empty */ if((form->data->type == FORM_FILE) || (form->data->type == FORM_CALLBACK)) { gotsize = readfromfile(form, buffer, wantedsize); if(gotsize) /* If positive or -1, return. If zero, continue! */ return gotsize; } do { if((form->data->length - form->sent ) > wantedsize - gotsize) { memcpy(buffer + gotsize , form->data->line + form->sent, wantedsize - gotsize); form->sent += wantedsize-gotsize; return wantedsize; } memcpy(buffer+gotsize, form->data->line + form->sent, (form->data->length - form->sent) ); gotsize += form->data->length - form->sent; form->sent = 0; form->data = form->data->next; /* advance */ } while(form->data && (form->data->type < FORM_CALLBACK)); /* If we got an empty line and we have more data, we proceed to the next line immediately to avoid returning zero before we've reached the end. */ return gotsize; }
/* * Curl_FormReader() is the fread() emulation function that will be used to * deliver the formdata to the transfer loop and then sent away to the peer. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L1389-L1439
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curl_formadd
CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { (void)httppost; (void)last_post; return CURL_FORMADD_DISABLED; }
/* CURL_DISABLE_HTTP */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/formdata.c#L1463-L1470
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
isBadFtpString
static bool isBadFtpString(const char *string) { return ((NULL != strchr(string, '\r')) || (NULL != strchr(string, '\n'))) ? TRUE : FALSE; }
/* Returns non-zero if the given string contains CR (\r) or LF (\n), which are not allowed within RFC 959 <string>. Note: The input string is in the client's encoding which might not be ASCII, so escape sequences \r & \n must be used instead of hex values 0x0d & 0x0a. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L316-L320
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
AcceptServerConnect
static CURLcode AcceptServerConnect(struct connectdata *conn) { struct SessionHandle *data = conn->data; curl_socket_t sock = conn->sock[SECONDARYSOCKET]; curl_socket_t s = CURL_SOCKET_BAD; #ifdef ENABLE_IPV6 struct Curl_sockaddr_storage add; #else struct sockaddr_in add; #endif curl_socklen_t size = (curl_socklen_t) sizeof(add); if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) { size = sizeof(add); s=accept(sock, (struct sockaddr *) &add, &size); } Curl_closesocket(conn, sock); /* close the first socket */ if(CURL_SOCKET_BAD == s) { failf(data, "Error accept()ing server connect"); return CURLE_FTP_PORT_FAILED; } infof(data, "Connection accepted from server\n"); conn->sock[SECONDARYSOCKET] = s; curlx_nonblock(s, TRUE); /* enable non-blocking */ conn->sock_accepted[SECONDARYSOCKET] = TRUE; if(data->set.fsockopt) { int error = 0; /* activate callback for setting socket options */ error = data->set.fsockopt(data->set.sockopt_client, s, CURLSOCKTYPE_ACCEPT); if(error) { Curl_closesocket(conn, s); /* close the socket and bail out */ conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; return CURLE_ABORTED_BY_CALLBACK; } } return CURLE_OK; }
/*********************************************************************** * * AcceptServerConnect() * * After connection request is received from the server this function is * called to accept the connection and close the listening socket * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L330-L376
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_timeleft_accept
static long ftp_timeleft_accept(struct SessionHandle *data) { long timeout_ms = DEFAULT_ACCEPT_TIMEOUT; long other; struct timeval now; if(data->set.accepttimeout > 0) timeout_ms = data->set.accepttimeout; now = Curl_tvnow(); /* check if the generic timeout possibly is set shorter */ other = Curl_timeleft(data, &now, FALSE); if(other && (other < timeout_ms)) /* note that this also works fine for when other happens to be negative due to it already having elapsed */ timeout_ms = other; else { /* subtract elapsed time */ timeout_ms -= Curl_tvdiff(now, data->progress.t_acceptdata); if(!timeout_ms) /* avoid returning 0 as that means no timeout! */ return -1; } return timeout_ms; }
/* * ftp_timeleft_accept() returns the amount of milliseconds left allowed for * waiting server to connect. If the value is negative, the timeout time has * already elapsed. * * The start time is stored in progress.t_acceptdata - as set with * Curl_pgrsTime(..., TIMER_STARTACCEPT); * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L387-L413
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ReceivedServerConnect
static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received) { struct SessionHandle *data = conn->data; curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET]; curl_socket_t data_sock = conn->sock[SECONDARYSOCKET]; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; int result; long timeout_ms; ssize_t nread; int ftpcode; *received = FALSE; timeout_ms = ftp_timeleft_accept(data); infof(data, "Checking for server connect\n"); if(timeout_ms < 0) { /* if a timeout was already reached, bail out */ failf(data, "Accept timeout occurred while waiting server connect"); return CURLE_FTP_ACCEPT_TIMEOUT; } /* First check whether there is a cached response from server */ if(pp->cache_size && pp->cache && pp->cache[0] > '3') { /* Data connection could not be established, let's return */ infof(data, "There is negative response in cache while serv connect\n"); Curl_GetFTPResponse(&nread, conn, &ftpcode); return CURLE_FTP_ACCEPT_FAILED; } result = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0); /* see if the connection request is already here */ switch (result) { case -1: /* error */ /* let's die here */ failf(data, "Error while waiting for server connect"); return CURLE_FTP_ACCEPT_FAILED; case 0: /* Server connect is not received yet */ break; /* loop */ default: if(result & CURL_CSELECT_IN2) { infof(data, "Ready to accept data connection from server\n"); *received = TRUE; } else if(result & CURL_CSELECT_IN) { infof(data, "Ctrl conn has data while waiting for data conn\n"); Curl_GetFTPResponse(&nread, conn, &ftpcode); if(ftpcode/100 > 3) return CURLE_FTP_ACCEPT_FAILED; return CURLE_FTP_WEIRD_SERVER_REPLY; } break; } /* switch() */ return CURLE_OK; }
/*********************************************************************** * * ReceivedServerConnect() * * After allowing server to connect to us from data port, this function * checks both data connection for connection establishment and ctrl * connection for a negative response regarding a failure in connecting * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L425-L485
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
InitiateTransfer
static CURLcode InitiateTransfer(struct connectdata *conn) { struct SessionHandle *data = conn->data; struct FTP *ftp = data->state.proto.ftp; CURLcode result = CURLE_OK; if(conn->ssl[SECONDARYSOCKET].use) { /* since we only have a plaintext TCP connection here, we must now * do the TLS stuff */ infof(data, "Doing the SSL/TLS handshake on the data stream\n"); result = Curl_ssl_connect(conn, SECONDARYSOCKET); if(result) return result; } if(conn->proto.ftpc.state_saved == FTP_STOR) { *(ftp->bytecountp)=0; /* When we know we're uploading a specified file, we can get the file size prior to the actual upload. */ Curl_pgrsSetUploadSize(data, data->set.infilesize); /* set the SO_SNDBUF for the secondary socket for those who need it */ Curl_sndbufset(conn->sock[SECONDARYSOCKET]); Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */ SECONDARYSOCKET, ftp->bytecountp); } else { /* FTP download: */ Curl_setup_transfer(conn, SECONDARYSOCKET, conn->proto.ftpc.retr_size_saved, FALSE, ftp->bytecountp, -1, NULL); /* no upload here */ } conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */ state(conn, FTP_STOP); return CURLE_OK; }
/*********************************************************************** * * InitiateTransfer() * * After connection from server is accepted this function is called to * setup transfer parameters and initiate the data transfer. * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L496-L536
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
AllowServerConnect
static CURLcode AllowServerConnect(struct connectdata *conn, bool *connected) { struct SessionHandle *data = conn->data; long timeout_ms; CURLcode ret = CURLE_OK; *connected = FALSE; infof(data, "Preparing for accepting server on data port\n"); /* Save the time we start accepting server connect */ Curl_pgrsTime(data, TIMER_STARTACCEPT); timeout_ms = ftp_timeleft_accept(data); if(timeout_ms < 0) { /* if a timeout was already reached, bail out */ failf(data, "Accept timeout occurred while waiting server connect"); return CURLE_FTP_ACCEPT_TIMEOUT; } /* see if the connection request is already here */ ret = ReceivedServerConnect(conn, connected); if(ret) return ret; if(*connected) { ret = AcceptServerConnect(conn); if(ret) return ret; ret = InitiateTransfer(conn); if(ret) return ret; } else { /* Add timeout to multi handle and break out of the loop */ if(ret == CURLE_OK && *connected == FALSE) { if(data->set.accepttimeout > 0) Curl_expire(data, data->set.accepttimeout); else Curl_expire(data, DEFAULT_ACCEPT_TIMEOUT); } } return ret; }
/*********************************************************************** * * AllowServerConnect() * * When we've issue the PORT command, we have told the server to connect to * us. This function checks whether data connection is established if so it is * accepted. * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L547-L591
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_GetFTPResponse
CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */ struct connectdata *conn, int *ftpcode) /* return the ftp-code */ { /* * We cannot read just one byte per read() and then go back to select() as * the OpenSSL read() doesn't grok that properly. * * Alas, read as much as possible, split up into lines, use the ending * line in a response or continue reading. */ curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; long timeout; /* timeout in milliseconds */ long interval_ms; struct SessionHandle *data = conn->data; CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; size_t nread; int cache_skip=0; int value_to_be_ignored=0; if(ftpcode) *ftpcode = 0; /* 0 for errors */ else /* make the pointer point to something for the rest of this function */ ftpcode = &value_to_be_ignored; *nreadp=0; while(!*ftpcode && !result) { /* check and reset timeout value every lap */ timeout = Curl_pp_state_timeout(pp); if(timeout <=0 ) { failf(data, "FTP response timeout"); return CURLE_OPERATION_TIMEDOUT; /* already too little time */ } interval_ms = 1000; /* use 1 second timeout intervals */ if(timeout < interval_ms) interval_ms = timeout; /* * Since this function is blocking, we need to wait here for input on the * connection and only then we call the response reading function. We do * timeout at least every second to make the timeout check run. * * A caution here is that the ftp_readresp() function has a cache that may * contain pieces of a response from the previous invoke and we need to * make sure we don't just wait for input while there is unhandled data in * that cache. But also, if the cache is there, we call ftp_readresp() and * the cache wasn't good enough to continue we must not just busy-loop * around this function. * */ if(pp->cache && (cache_skip < 2)) { /* * There's a cache left since before. We then skipping the wait for * socket action, unless this is the same cache like the previous round * as then the cache was deemed not enough to act on and we then need to * wait for more data anyway. */ } else { switch (Curl_socket_ready(sockfd, CURL_SOCKET_BAD, interval_ms)) { case -1: /* select() error, stop reading */ failf(data, "FTP response aborted due to select/poll error: %d", SOCKERRNO); return CURLE_RECV_ERROR; case 0: /* timeout */ if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; continue; /* just continue in our loop for the timeout duration */ default: /* for clarity */ break; } } result = ftp_readresp(sockfd, pp, ftpcode, &nread); if(result) break; if(!nread && pp->cache) /* bump cache skip counter as on repeated skips we must wait for more data */ cache_skip++; else /* when we got data or there is no cache left, we reset the cache skip counter */ cache_skip=0; *nreadp += nread; } /* while there's buffer left and loop is requested */ pp->pending_resp = FALSE; return result; }
/* --- parse FTP server responses --- */ /* * Curl_GetFTPResponse() is a BLOCKING function to read the full response * from a server after a command. * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L678-L779
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
_state
static void _state(struct connectdata *conn, ftpstate newstate #ifdef DEBUGBUILD , int lineno #endif ) { #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "WAIT220", "AUTH", "USER", "PASS", "ACCT", "PBSZ", "PROT", "CCC", "PWD", "SYST", "NAMEFMT", "QUOTE", "RETR_PREQUOTE", "STOR_PREQUOTE", "POSTQUOTE", "CWD", "MKD", "MDTM", "TYPE", "LIST_TYPE", "RETR_TYPE", "STOR_TYPE", "SIZE", "RETR_SIZE", "STOR_SIZE", "REST", "RETR_REST", "PORT", "PRET", "PASV", "LIST", "RETR", "STOR", "QUIT" }; #endif struct ftp_conn *ftpc = &conn->proto.ftpc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) if(ftpc->state != newstate) infof(conn->data, "FTP %p (line %d) state change from %s to %s\n", ftpc, lineno, names[ftpc->state], names[newstate]); #endif ftpc->state = newstate; }
/* This is the ONLY way to change FTP state! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L782-L836
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_getsock
static int ftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.ftpc.pp, socks, numsocks); }
/* For the FTP "protocol connect" and "doing" phases only */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L863-L868
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_domore_getsock
static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct ftp_conn *ftpc = &conn->proto.ftpc; if(!numsocks) return GETSOCK_BLANK; /* When in DO_MORE state, we could be either waiting for us to connect to a remote site, or we could wait for that site to connect to us. Or just handle ordinary commands. When waiting for a connect, we will be in FTP_STOP state and then we wait for the secondary socket to become writeable. If we're in another state, we're still handling commands on the control (primary) connection. */ switch(ftpc->state) { case FTP_STOP: break; default: return Curl_pp_getsock(&conn->proto.ftpc.pp, socks, numsocks); } socks[0] = conn->sock[SECONDARYSOCKET]; if(ftpc->wait_data_conn) { socks[1] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_READSOCK(1); } return GETSOCK_READSOCK(0); }
/* For the FTP "DO_MORE" phase only */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L871-L903
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_cwd
static CURLcode ftp_state_cwd(struct connectdata *conn) { CURLcode result = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; if(ftpc->cwddone) /* already done and fine */ result = ftp_state_post_cwd(conn); else { ftpc->count2 = 0; /* count2 counts failed CWDs */ /* count3 is set to allow a MKD to fail once. In the case when first CWD fails and then MKD fails (due to another session raced it to create the dir) this then allows for a second try to CWD to it */ ftpc->count3 = (conn->data->set.ftp_create_missing_dirs==2)?1:0; if(conn->bits.reuse && ftpc->entrypath) { /* This is a re-used connection. Since we change directory to where the transfer is taking place, we must first get back to the original dir where we ended up after login: */ ftpc->count1 = 0; /* we count this as the first path, then we add one for all upcoming ones in the ftp->dirs[] array */ PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->entrypath); state(conn, FTP_CWD); } else { if(ftpc->dirdepth) { ftpc->count1 = 1; /* issue the first CWD, the rest is sent when the CWD responses are received... */ PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->dirs[ftpc->count1 -1]); state(conn, FTP_CWD); } else { /* No CWD necessary */ result = ftp_state_post_cwd(conn); } } } return result; }
/* This is called after the FTP_QUOTE state is passed. ftp_state_cwd() sends the range of CWD commands to the server to change to the correct directory. It may also need to send MKD commands to create missing ones, if that option is enabled. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L911-L951
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_post_rest
static CURLcode ftp_state_post_rest(struct connectdata *conn) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->state.proto.ftp; struct SessionHandle *data = conn->data; if(ftp->transfer != FTPTRANSFER_BODY) { /* doesn't transfer any data */ /* still possibly do PRE QUOTE jobs */ state(conn, FTP_RETR_PREQUOTE); result = ftp_state_quote(conn, TRUE, FTP_RETR_PREQUOTE); } else if(data->set.ftp_use_port) { /* We have chosen to use the PORT (or similar) command */ result = ftp_state_use_port(conn, EPRT); } else { /* We have chosen (this is default) to use the PASV (or similar) command */ if(data->set.ftp_use_pret) { /* The user has requested that we send a PRET command to prepare the server for the upcoming PASV */ if(!conn->proto.ftpc.file) { PPSENDF(&conn->proto.ftpc.pp, "PRET %s", data->set.str[STRING_CUSTOMREQUEST]? data->set.str[STRING_CUSTOMREQUEST]: (data->set.ftp_list_only?"NLST":"LIST")); } else if(data->set.upload) { PPSENDF(&conn->proto.ftpc.pp, "PRET STOR %s", conn->proto.ftpc.file); } else { PPSENDF(&conn->proto.ftpc.pp, "PRET RETR %s", conn->proto.ftpc.file); } state(conn, FTP_PRET); } else { result = ftp_state_use_pasv(conn); } } return result; }
/* REST is the last command in the chain of commands when a "head"-like request is made. Thus, if an actual transfer is to be made this is where we take off for real. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L1374-L1415
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_post_cwd
static CURLcode ftp_state_post_cwd(struct connectdata *conn) { CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; /* Requested time of file or time-depended transfer? */ if((data->set.get_filetime || data->set.timecondition) && ftpc->file) { /* we have requested to get the modified-time of the file, this is a white spot as the MDTM is not mentioned in RFC959 */ PPSENDF(&ftpc->pp, "MDTM %s", ftpc->file); state(conn, FTP_MDTM); } else result = ftp_state_post_mdtm(conn); return result; }
/* This is called after the CWD commands have been done in the beginning of the DO phase */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L1582-L1601
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_ul_setup
static CURLcode ftp_state_ul_setup(struct connectdata *conn, bool sizechecked) { CURLcode result = CURLE_OK; struct FTP *ftp = conn->data->state.proto.ftp; struct SessionHandle *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; int seekerr = CURL_SEEKFUNC_OK; if((data->state.resume_from && !sizechecked) || ((data->state.resume_from > 0) && sizechecked)) { /* we're about to continue the uploading of a file */ /* 1. get already existing file's size. We use the SIZE command for this which may not exist in the server! The SIZE command is not in RFC959. */ /* 2. This used to set REST. But since we can do append, we don't another ftp command. We just skip the source file offset and then we APPEND the rest on the file instead */ /* 3. pass file-size number of bytes in the source file */ /* 4. lower the infilesize counter */ /* => transfer as usual */ if(data->state.resume_from < 0 ) { /* Got no given size to start from, figure it out */ PPSENDF(&ftpc->pp, "SIZE %s", ftpc->file); state(conn, FTP_STOR_SIZE); return result; } /* enable append */ data->set.ftp_append = TRUE; /* Let's read off the proper amount of bytes from the input. */ if(conn->seek_func) { seekerr = conn->seek_func(conn->seek_client, data->state.resume_from, SEEK_SET); } if(seekerr != CURL_SEEKFUNC_OK) { 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) */ else { curl_off_t passed=0; do { size_t readthisamountnow = (data->state.resume_from - passed > CURL_OFF_T_C(BUFSIZE)) ? BUFSIZE : curlx_sotouz(data->state.resume_from - passed); size_t actuallyread = conn->fread_func(data->state.buffer, 1, readthisamountnow, conn->fread_in); passed += actuallyread; if((actuallyread == 0) || (actuallyread > readthisamountnow)) { /* this checks for greater-than only to make sure that the CURL_READFUNC_ABORT return code still aborts */ failf(data, "Failed to read data"); return CURLE_FTP_COULDNT_USE_REST; } } while(passed < data->state.resume_from); } } /* now, decrease the size of the read */ if(data->set.infilesize>0) { data->set.infilesize -= data->state.resume_from; if(data->set.infilesize <= 0) { infof(data, "File already completely uploaded\n"); /* no data to transfer */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); /* Set ->transfer so that we won't get any error in * ftp_done() because we didn't transfer anything! */ ftp->transfer = FTPTRANSFER_NONE; state(conn, FTP_STOP); return CURLE_OK; } } /* we've passed, proceed as normal */ } /* resume_from */ PPSENDF(&ftpc->pp, data->set.ftp_append?"APPE %s":"STOR %s", ftpc->file); state(conn, FTP_STOR); return result; }
/* This is called after the TYPE and possible quote commands have been sent */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L1605-L1699
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_epsv_disable
static CURLcode ftp_epsv_disable(struct connectdata *conn) { CURLcode result = CURLE_OK; infof(conn->data, "got positive EPSV response, but can't connect. " "Disabling EPSV\n"); /* disable it for next transfer */ conn->bits.ftp_use_epsv = FALSE; conn->data->state.errorbuf = FALSE; /* allow error message to get rewritten */ PPSENDF(&conn->proto.ftpc.pp, "PASV", NULL); conn->proto.ftpc.count1++; /* remain in the FTP_PASV state */ return result; }
/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV problems */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L1794-L1807
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_get_resp
static CURLcode ftp_state_get_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; struct FTP *ftp = data->state.proto.ftp; char *buf = data->state.buffer; if((ftpcode == 150) || (ftpcode == 125)) { /* A; 150 Opening BINARY mode data connection for /etc/passwd (2241 bytes). (ok, the file is being transferred) B: 150 Opening ASCII mode data connection for /bin/ls C: 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes). D: 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes) E: 125 Data connection already open; Transfer starting. */ curl_off_t size=-1; /* default unknown size */ /* * It appears that there are FTP-servers that return size 0 for files when * SIZE is used on the file while being in BINARY mode. To work around * that (stupid) behavior, we attempt to parse the RETR response even if * the SIZE returned size zero. * * Debugging help from Salvatore Sorrentino on February 26, 2003. */ if((instate != FTP_LIST) && !data->set.prefer_ascii && (ftp->downloadsize < 1)) { /* * It seems directory listings either don't show the size or very * often uses size 0 anyway. ASCII transfers may very well turn out * that the transferred amount of data is not the same as this line * tells, why using this number in those cases only confuses us. * * Example D above makes this parsing a little tricky */ char *bytes; bytes=strstr(buf, " bytes"); if(bytes--) { long in=(long)(bytes-buf); /* this is a hint there is size information in there! ;-) */ while(--in) { /* scan for the left parenthesis and break there */ if('(' == *bytes) break; /* skip only digits */ if(!ISDIGIT(*bytes)) { bytes=NULL; break; } /* one more estep backwards */ bytes--; } /* if we have nothing but digits: */ if(bytes++) { /* get the number! */ size = curlx_strtoofft(bytes, NULL, 0); } } } else if(ftp->downloadsize > -1) size = ftp->downloadsize; if(size > data->req.maxdownload && data->req.maxdownload > 0) size = data->req.size = data->req.maxdownload; else if((instate != FTP_LIST) && (data->set.prefer_ascii)) size = -1; /* kludge for servers that understate ASCII mode file size */ infof(data, "Maxdownload = %" FORMAT_OFF_T "\n", data->req.maxdownload); if(instate != FTP_LIST) infof(data, "Getting file with size: %" FORMAT_OFF_T "\n", size); /* FTP download: */ conn->proto.ftpc.state_saved = instate; conn->proto.ftpc.retr_size_saved = size; if(data->set.ftp_use_port) { bool connected; result = AllowServerConnect(conn, &connected); if(result) return result; if(!connected) { struct ftp_conn *ftpc = &conn->proto.ftpc; infof(data, "Data conn was not available immediately\n"); state(conn, FTP_STOP); ftpc->wait_data_conn = TRUE; } } else return InitiateTransfer(conn); } else { if((instate == FTP_LIST) && (ftpcode == 450)) { /* simply no matching files in the dir listing */ ftp->transfer = FTPTRANSFER_NONE; /* don't download anything */ state(conn, FTP_STOP); /* this phase is over */ } else { failf(data, "RETR response: %03d", ftpcode); return instate == FTP_RETR && ftpcode == 550? CURLE_REMOTE_FILE_NOT_FOUND: CURLE_FTP_COULDNT_RETR_FILE; } } return result; }
/* for LIST and RETR responses */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L2447-L2570
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_loggedin
static CURLcode ftp_state_loggedin(struct connectdata *conn) { CURLcode result = CURLE_OK; #ifdef HAVE_KRB4 if(conn->data->set.krb) { /* We may need to issue a KAUTH here to have access to the files * do it if user supplied a password */ if(conn->passwd && *conn->passwd) { /* BLOCKING */ result = Curl_krb_kauth(conn); if(result) return result; } } #endif if(conn->ssl[FIRSTSOCKET].use) { /* PBSZ = PROTECTION BUFFER SIZE. The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says: Specifically, the PROT command MUST be preceded by a PBSZ command and a PBSZ command MUST be preceded by a successful security data exchange (the TLS negotiation in this case) ... (and on page 8): Thus the PBSZ command must still be issued, but must have a parameter of '0' to indicate that no buffering is taking place and the data connection should not be encapsulated. */ PPSENDF(&conn->proto.ftpc.pp, "PBSZ %d", 0); state(conn, FTP_PBSZ); } else { result = ftp_state_pwd(conn); } return result; }
/* after USER, PASS and ACCT */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L2573-L2612
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_user_resp
static CURLcode ftp_state_user_resp(struct connectdata *conn, int ftpcode, ftpstate instate) { CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; struct FTP *ftp = data->state.proto.ftp; struct ftp_conn *ftpc = &conn->proto.ftpc; (void)instate; /* no use for this yet */ /* some need password anyway, and others just return 2xx ignored */ if((ftpcode == 331) && (ftpc->state == FTP_USER)) { /* 331 Password required for ... (the server requires to send the user's password too) */ PPSENDF(&ftpc->pp, "PASS %s", ftp->passwd?ftp->passwd:""); state(conn, FTP_PASS); } else if(ftpcode/100 == 2) { /* 230 User ... logged in. (the user logged in with or without password) */ result = ftp_state_loggedin(conn); } else if(ftpcode == 332) { if(data->set.str[STRING_FTP_ACCOUNT]) { PPSENDF(&ftpc->pp, "ACCT %s", data->set.str[STRING_FTP_ACCOUNT]); state(conn, FTP_ACCT); } else { failf(data, "ACCT requested but none available"); result = CURLE_LOGIN_DENIED; } } else { /* All other response codes, like: 530 User ... access denied (the server denies to log the specified user) */ if(conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] && !conn->data->state.ftp_trying_alternative) { /* Ok, USER failed. Let's try the supplied command. */ PPSENDF(&conn->proto.ftpc.pp, "%s", conn->data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]); conn->data->state.ftp_trying_alternative = TRUE; state(conn, FTP_USER); result = CURLE_OK; } else { failf(data, "Access denied: %03d", ftpcode); result = CURLE_LOGIN_DENIED; } } return result; }
/* for USER and PASS responses */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L2615-L2668
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_state_acct_resp
static CURLcode ftp_state_acct_resp(struct connectdata *conn, int ftpcode) { CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; if(ftpcode != 230) { failf(data, "ACCT rejected by server: %03d", ftpcode); result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */ } else result = ftp_state_loggedin(conn); return result; }
/* for ACCT response */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L2671-L2684
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_multi_statemach
static CURLcode ftp_multi_statemach(struct connectdata *conn, bool *done) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = Curl_pp_multi_statemach(&ftpc->pp); /* Check for the state outside of the Curl_socket_ready() return code checks since at times we are in fact already in this state when this function gets called. */ *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE; return result; }
/* called repeatedly until done from multi.c */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3123-L3135
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_connect
static CURLcode ftp_connect(struct connectdata *conn, bool *done) /* see description above */ { CURLcode result; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; *done = FALSE; /* default to not done yet */ /* If there already is a protocol-specific struct allocated for this sessionhandle, deal with it */ Curl_reset_reqproto(conn); result = ftp_init(conn); if(CURLE_OK != result) return result; /* We always support persistent connections on ftp */ conn->bits.close = FALSE; pp->response_time = RESP_TIMEOUT; /* set default response time-out */ pp->statemach_act = ftp_statemach_act; pp->endofresp = ftp_endofresp; pp->conn = conn; if(conn->handler->flags & PROTOPT_SSL) { /* BLOCKING */ result = Curl_ssl_connect(conn, FIRSTSOCKET); if(result) return result; } Curl_pp_init(pp); /* init the generic pingpong data */ /* When we connect, we start in the state where we await the 220 response */ state(conn, FTP_WAIT220); result = ftp_multi_statemach(conn, done); return result; }
/* * ftp_connect() should do everything that is to be considered a part of * the connection phase. * * The variable 'done' points to will be TRUE if the protocol-layer connect * phase is done when this function returns, or FALSE is not. When called as * a part of the easy interface, it will always be TRUE. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3210-L3251
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_done
static CURLcode ftp_done(struct connectdata *conn, CURLcode status, bool premature) { struct SessionHandle *data = conn->data; struct FTP *ftp = data->state.proto.ftp; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; ssize_t nread; int ftpcode; CURLcode result = CURLE_OK; bool was_ctl_valid = ftpc->ctl_valid; char *path; const char *path_to_use = data->state.path; if(!ftp) /* When the easy handle is removed from the multi while libcurl is still * trying to resolve the host name, it seems that the ftp struct is not * yet initialized, but the removal action calls Curl_done() which calls * this function. So we simply return success if no ftp pointer is set. */ return CURLE_OK; switch(status) { case CURLE_BAD_DOWNLOAD_RESUME: case CURLE_FTP_WEIRD_PASV_REPLY: case CURLE_FTP_PORT_FAILED: case CURLE_FTP_ACCEPT_FAILED: case CURLE_FTP_ACCEPT_TIMEOUT: case CURLE_FTP_COULDNT_SET_TYPE: case CURLE_FTP_COULDNT_RETR_FILE: case CURLE_PARTIAL_FILE: case CURLE_UPLOAD_FAILED: case CURLE_REMOTE_ACCESS_DENIED: case CURLE_FILESIZE_EXCEEDED: case CURLE_REMOTE_FILE_NOT_FOUND: case CURLE_WRITE_ERROR: /* the connection stays alive fine even though this happened */ /* fall-through */ case CURLE_OK: /* doesn't affect the control connection's status */ if(!premature) { ftpc->ctl_valid = was_ctl_valid; break; } /* until we cope better with prematurely ended requests, let them * fallback as if in complete failure */ default: /* by default, an error means the control connection is wedged and should not be used anymore */ ftpc->ctl_valid = FALSE; ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the current path, as this connection is going */ conn->bits.close = TRUE; /* marked for closure */ result = status; /* use the already set error code */ break; } /* now store a copy of the directory we are in */ if(ftpc->prevpath) free(ftpc->prevpath); if(data->set.wildcardmatch) { if(data->set.chunk_end && ftpc->file) { data->set.chunk_end(data->wildcard.customptr); } ftpc->known_filesize = -1; } /* get the "raw" path */ path = curl_easy_unescape(data, path_to_use, 0, NULL); if(!path) { /* out of memory, but we can limp along anyway (and should try to * since we may already be in the out of memory cleanup path) */ if(!result) result = CURLE_OUT_OF_MEMORY; ftpc->ctl_valid = FALSE; /* mark control connection as bad */ conn->bits.close = TRUE; /* mark for connection closure */ ftpc->prevpath = NULL; /* no path remembering */ } else { size_t flen = ftpc->file?strlen(ftpc->file):0; /* file is "raw" already */ size_t dlen = strlen(path)-flen; if(!ftpc->cwdfail) { if(dlen && (data->set.ftp_filemethod != FTPFILE_NOCWD)) { ftpc->prevpath = path; if(flen) /* if 'path' is not the whole string */ ftpc->prevpath[dlen]=0; /* terminate */ } else { /* we never changed dir */ ftpc->prevpath=strdup(""); free(path); } if(ftpc->prevpath) infof(data, "Remembering we are in dir \"%s\"\n", ftpc->prevpath); } else { ftpc->prevpath = NULL; /* no path */ free(path); } } /* free the dir tree and file parts */ freedirs(ftpc); /* shut down the socket to inform the server we're done */ #ifdef _WIN32_WCE shutdown(conn->sock[SECONDARYSOCKET],2); /* SD_BOTH */ #endif if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) { if(!result && ftpc->dont_check && data->req.maxdownload > 0) /* partial download completed */ result = Curl_pp_sendf(pp, "ABOR"); if(result) { failf(data, "Failure sending ABOR command: %s", curl_easy_strerror(result)); ftpc->ctl_valid = FALSE; /* mark control connection as bad */ conn->bits.close = TRUE; /* mark for connection closure */ } if(conn->ssl[SECONDARYSOCKET].use) { /* The secondary socket is using SSL so we must close down that part first before we close the socket for real */ Curl_ssl_close(conn, SECONDARYSOCKET); /* Note that we keep "use" set to TRUE since that (next) connection is still requested to use SSL */ } if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) { Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE; } } if(!result && (ftp->transfer == FTPTRANSFER_BODY) && ftpc->ctl_valid && pp->pending_resp && !premature) { /* * Let's see what the server says about the transfer we just performed, * but lower the timeout as sometimes this connection has died while the * data has been transferred. This happens when doing through NATs etc that * abandon old silent connections. */ long old_time = pp->response_time; pp->response_time = 60*1000; /* give it only a minute for now */ pp->response = Curl_tvnow(); /* timeout relative now */ result = Curl_GetFTPResponse(&nread, conn, &ftpcode); pp->response_time = old_time; /* set this back to previous value */ if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) { failf(data, "control connection looks dead"); ftpc->ctl_valid = FALSE; /* mark control connection as bad */ conn->bits.close = TRUE; /* mark for closure */ } if(result) return result; if(ftpc->dont_check && data->req.maxdownload > 0) { /* we have just sent ABOR and there is no reliable way to check if it was * successful or not; we have to close the connection now */ infof(data, "partial download completed, closing connection\n"); conn->bits.close = TRUE; /* mark for closure */ return result; } if(!ftpc->dont_check) { /* 226 Transfer complete, 250 Requested file action okay, completed. */ if((ftpcode != 226) && (ftpcode != 250)) { failf(data, "server did not report OK, got %d", ftpcode); result = CURLE_PARTIAL_FILE; } } } if(result || premature) /* the response code from the transfer showed an error already so no use checking further */ ; else if(data->set.upload) { if((-1 != data->set.infilesize) && (data->set.infilesize != *ftp->bytecountp) && !data->set.crlf && (ftp->transfer == FTPTRANSFER_BODY)) { failf(data, "Uploaded unaligned file size (%" FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes)", *ftp->bytecountp, data->set.infilesize); result = CURLE_PARTIAL_FILE; } } else { if((-1 != data->req.size) && (data->req.size != *ftp->bytecountp) && #ifdef CURL_DO_LINEEND_CONV /* Most FTP servers don't adjust their file SIZE response for CRLFs, so * we'll check to see if the discrepancy can be explained by the number * of CRLFs we've changed to LFs. */ ((data->req.size + data->state.crlf_conversions) != *ftp->bytecountp) && #endif /* CURL_DO_LINEEND_CONV */ (data->req.maxdownload != *ftp->bytecountp)) { failf(data, "Received only partial file: %" FORMAT_OFF_T " bytes", *ftp->bytecountp); result = CURLE_PARTIAL_FILE; } else if(!ftpc->dont_check && !*ftp->bytecountp && (data->req.size>0)) { failf(data, "No data was received!"); result = CURLE_FTP_COULDNT_RETR_FILE; } } /* clear these for next connection */ ftp->transfer = FTPTRANSFER_BODY; ftpc->dont_check = FALSE; /* Send any post-transfer QUOTE strings? */ if(!status && !result && !premature && data->set.postquote) result = ftp_sendquote(conn, data->set.postquote); return result; }
/*********************************************************************** * * ftp_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3262-L3488
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_sendquote
static CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote) { struct curl_slist *item; ssize_t nread; int ftpcode; CURLcode result; struct ftp_conn *ftpc = &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; item = quote; while(item) { if(item->data) { char *cmd = item->data; bool acceptfail = FALSE; /* if a command starts with an asterisk, which a legal FTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; acceptfail = TRUE; } FTPSENDF(conn, "%s", cmd); pp->response = Curl_tvnow(); /* timeout relative now */ result = Curl_GetFTPResponse(&nread, conn, &ftpcode); if(result) return result; if(!acceptfail && (ftpcode >= 400)) { failf(conn->data, "QUOT string not accepted: %s", cmd); return CURLE_QUOTE_ERROR; } } item = item->next; } return CURLE_OK; }
/*********************************************************************** * * ftp_sendquote() * * Where a 'quote' means a list of custom commands to send to the server. * The quote list is passed as an argument. * * BLOCKING */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3500-L3544
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_need_type
static int ftp_need_type(struct connectdata *conn, bool ascii_wanted) { return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I'); }
/*********************************************************************** * * ftp_need_type() * * Returns TRUE if we in the current situation should send TYPE */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3552-L3556
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_nb_type
static CURLcode ftp_nb_type(struct connectdata *conn, bool ascii, ftpstate newstate) { struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result; char want = (char)(ascii?'A':'I'); if(ftpc->transfertype == want) { state(conn, newstate); return ftp_state_type_resp(conn, 200, newstate); } PPSENDF(&ftpc->pp, "TYPE %c", want); state(conn, newstate); /* keep track of our current transfer type */ ftpc->transfertype = want; return CURLE_OK; }
/*********************************************************************** * * ftp_nb_type() * * Set TYPE. We only deal with ASCII or BINARY so this function * sets one of them. * If the transfer type is not sent, simulate on OK response in newstate */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3566-L3584
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_range
static CURLcode ftp_range(struct connectdata *conn) { curl_off_t from, to; char *ptr; char *ptr2; struct SessionHandle *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; if(data->state.use_range && data->state.range) { from=curlx_strtoofft(data->state.range, &ptr, 0); while(*ptr && (ISSPACE(*ptr) || (*ptr=='-'))) ptr++; to=curlx_strtoofft(ptr, &ptr2, 0); if(ptr == ptr2) { /* we didn't get any digit */ to=-1; } if((-1 == to) && (from>=0)) { /* X - */ data->state.resume_from = from; DEBUGF(infof(conn->data, "FTP RANGE %" FORMAT_OFF_T " to end of file\n", from)); } else if(from < 0) { /* -Y */ data->req.maxdownload = -from; data->state.resume_from = from; DEBUGF(infof(conn->data, "FTP RANGE the last %" FORMAT_OFF_T " bytes\n", -from)); } else { /* X-Y */ data->req.maxdownload = (to-from)+1; /* include last byte */ data->state.resume_from = from; DEBUGF(infof(conn->data, "FTP RANGE from %" FORMAT_OFF_T " getting %" FORMAT_OFF_T " bytes\n", from, data->req.maxdownload)); } DEBUGF(infof(conn->data, "range-download from %" FORMAT_OFF_T " to %" FORMAT_OFF_T ", totally %" FORMAT_OFF_T " bytes\n", from, to, data->req.maxdownload)); ftpc->dont_check = TRUE; /* dont check for successful transfer */ } else data->req.maxdownload = -1; return CURLE_OK; }
/* Check if this is a range download, and if so, set the internal variables properly. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3613-L3659
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_do_more
static CURLcode ftp_do_more(struct connectdata *conn, bool *complete) { struct SessionHandle *data=conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; CURLcode result = CURLE_OK; bool connected = FALSE; /* the ftp struct is inited in ftp_connect() */ struct FTP *ftp = data->state.proto.ftp; *complete = FALSE; /* if the second connection isn't done yet, wait for it */ if(!conn->bits.tcpconnect[SECONDARYSOCKET]) { if(conn->tunnel_state[SECONDARYSOCKET] == TUNNEL_CONNECT) { /* As we're in TUNNEL_CONNECT state now, we know the proxy name and port aren't used so we blank their arguments. TODO: make this nicer */ result = Curl_proxyCONNECT(conn, SECONDARYSOCKET, NULL, 0); return result; } result = Curl_is_connected(conn, SECONDARYSOCKET, &connected); /* Ready to do more? */ if(connected) { DEBUGF(infof(data, "DO-MORE connected phase starts\n")); } else return result; } if(ftpc->state) { /* already in a state so skip the intial commands. They are only done to kickstart the do_more state */ result = ftp_multi_statemach(conn, complete); /* if we got an error or if we don't wait for a data connection return immediately */ if(result || (ftpc->wait_data_conn != TRUE)) return result; if(ftpc->wait_data_conn) /* if we reach the end of the FTP state machine here, *complete will be TRUE but so is ftpc->wait_data_conn, which says we need to wait for the data connection and therefore we're not actually complete */ *complete = FALSE; } if(ftp->transfer <= FTPTRANSFER_INFO) { /* a transfer is about to take place, or if not a file name was given so we'll do a SIZE on it later and then we need the right TYPE first */ if(ftpc->wait_data_conn == TRUE) { bool serv_conned; result = ReceivedServerConnect(conn, &serv_conned); if(result) return result; /* Failed to accept data connection */ if(serv_conned) { /* It looks data connection is established */ result = AcceptServerConnect(conn); ftpc->wait_data_conn = FALSE; if(!result) result = InitiateTransfer(conn); if(result) return result; } } else if(data->set.upload) { result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_STOR_TYPE); if(result) return result; result = ftp_multi_statemach(conn, complete); } else { /* download */ ftp->downloadsize = -1; /* unknown as of yet */ result = ftp_range(conn); if(result) ; else if(data->set.ftp_list_only || !ftpc->file) { /* The specified path ends with a slash, and therefore we think this is a directory that is requested, use LIST. But before that we need to set ASCII transfer mode. */ /* But only if a body transfer was requested. */ if(ftp->transfer == FTPTRANSFER_BODY) { result = ftp_nb_type(conn, TRUE, FTP_LIST_TYPE); if(result) return result; } /* otherwise just fall through */ } else { result = ftp_nb_type(conn, data->set.prefer_ascii, FTP_RETR_TYPE); if(result) return result; } result = ftp_multi_statemach(conn, complete); } return result; } if((result == CURLE_OK) && (ftp->transfer != FTPTRANSFER_BODY)) /* no data to transfer. FIX: it feels like a kludge to have this here too! */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); if(!ftpc->wait_data_conn) { /* no waiting for the data connection so this is now complete */ *complete = TRUE; DEBUGF(infof(data, "DO-MORE phase ends with %d\n", (int)result)); } return result; }
/* * ftp_do_more() * * This function shall be called when the second FTP (data) connection is * connected. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3669-L3790
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_perform
static CURLcode ftp_perform(struct connectdata *conn, bool *connected, /* connect status after PASV / PORT */ bool *dophase_done) { /* this is FTP and no proxy */ CURLcode result=CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); if(conn->data->set.opt_no_body) { /* requested no body means no transfer... */ struct FTP *ftp = conn->data->state.proto.ftp; ftp->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ result = ftp_state_quote(conn, TRUE, FTP_QUOTE); if(result) return result; /* run the state-machine */ result = ftp_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete1\n")); return result; }
/*********************************************************************** * * ftp_perform() * * This is the actual DO function for FTP. Get a file/directory according to * the options previously setup. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3802-L3834
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
wc_statemach
static CURLcode wc_statemach(struct connectdata *conn) { struct WildcardData * const wildcard = &(conn->data->wildcard); CURLcode ret = CURLE_OK; switch (wildcard->state) { case CURLWC_INIT: ret = init_wc_data(conn); if(wildcard->state == CURLWC_CLEAN) /* only listing! */ break; else wildcard->state = ret ? CURLWC_ERROR : CURLWC_MATCHING; break; case CURLWC_MATCHING: { /* In this state is LIST response successfully parsed, so lets restore previous WRITEFUNCTION callback and WRITEDATA pointer */ struct ftp_wc_tmpdata *ftp_tmp = wildcard->tmp; conn->data->set.fwrite_func = ftp_tmp->backup.write_function; conn->data->set.out = ftp_tmp->backup.file_descriptor; ftp_tmp->backup.write_function = ZERO_NULL; ftp_tmp->backup.file_descriptor = NULL; wildcard->state = CURLWC_DOWNLOADING; if(Curl_ftp_parselist_geterror(ftp_tmp->parser)) { /* error found in LIST parsing */ wildcard->state = CURLWC_CLEAN; return wc_statemach(conn); } else if(wildcard->filelist->size == 0) { /* no corresponding file */ wildcard->state = CURLWC_CLEAN; return CURLE_REMOTE_FILE_NOT_FOUND; } return wc_statemach(conn); } case CURLWC_DOWNLOADING: { /* filelist has at least one file, lets get first one */ struct ftp_conn *ftpc = &conn->proto.ftpc; struct curl_fileinfo *finfo = wildcard->filelist->head->ptr; char *tmp_path = malloc(strlen(conn->data->state.path) + strlen(finfo->filename) + 1); if(!tmp_path) { return CURLE_OUT_OF_MEMORY; } tmp_path[0] = 0; /* make full path to matched file */ strcat(tmp_path, wildcard->path); strcat(tmp_path, finfo->filename); /* switch default "state.pathbuffer" and tmp_path, good to see ftp_parse_url_path function to understand this trick */ Curl_safefree(conn->data->state.pathbuffer); conn->data->state.pathbuffer = tmp_path; conn->data->state.path = tmp_path; infof(conn->data, "Wildcard - START of \"%s\"\n", finfo->filename); if(conn->data->set.chunk_bgn) { long userresponse = conn->data->set.chunk_bgn( finfo, wildcard->customptr, (int)wildcard->filelist->size); switch(userresponse) { case CURL_CHUNK_BGN_FUNC_SKIP: infof(conn->data, "Wildcard - \"%s\" skipped by user\n", finfo->filename); wildcard->state = CURLWC_SKIP; return wc_statemach(conn); case CURL_CHUNK_BGN_FUNC_FAIL: return CURLE_CHUNK_FAILED; } } if(finfo->filetype != CURLFILETYPE_FILE) { wildcard->state = CURLWC_SKIP; return wc_statemach(conn); } if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE) ftpc->known_filesize = finfo->size; ret = ftp_parse_url_path(conn); if(ret) { return ret; } /* we don't need the Curl_fileinfo of first file anymore */ Curl_llist_remove(wildcard->filelist, wildcard->filelist->head, NULL); if(wildcard->filelist->size == 0) { /* remains only one file to down. */ wildcard->state = CURLWC_CLEAN; /* after that will be ftp_do called once again and no transfer will be done because of CURLWC_CLEAN state */ return CURLE_OK; } } break; case CURLWC_SKIP: { if(conn->data->set.chunk_end) conn->data->set.chunk_end(conn->data->wildcard.customptr); Curl_llist_remove(wildcard->filelist, wildcard->filelist->head, NULL); wildcard->state = (wildcard->filelist->size == 0) ? CURLWC_CLEAN : CURLWC_DOWNLOADING; return wc_statemach(conn); } case CURLWC_CLEAN: { struct ftp_wc_tmpdata *ftp_tmp = wildcard->tmp; ret = CURLE_OK; if(ftp_tmp) { ret = Curl_ftp_parselist_geterror(ftp_tmp->parser); } wildcard->state = ret ? CURLWC_ERROR : CURLWC_DONE; } break; case CURLWC_DONE: case CURLWC_ERROR: break; } return ret; }
/* This is called recursively */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L3939-L4060
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_do
static CURLcode ftp_do(struct connectdata *conn, bool *done) { CURLcode retcode = CURLE_OK; struct ftp_conn *ftpc = &conn->proto.ftpc; *done = FALSE; /* default to false */ ftpc->wait_data_conn = FALSE; /* default to no such wait */ /* Since connections can be re-used between SessionHandles, this might be a connection already existing but on a fresh SessionHandle struct so we must make sure we have a good 'struct FTP' to play with. For new connections, the struct FTP is allocated and setup in the ftp_connect() function. */ Curl_reset_reqproto(conn); retcode = ftp_init(conn); if(retcode) return retcode; if(conn->data->set.wildcardmatch) { retcode = wc_statemach(conn); if(conn->data->wildcard.state == CURLWC_SKIP || conn->data->wildcard.state == CURLWC_DONE) { /* do not call ftp_regular_transfer */ return CURLE_OK; } if(retcode) /* error, loop or skipping the file */ return retcode; } else { /* no wildcard FSM needed */ retcode = ftp_parse_url_path(conn); if(retcode) return retcode; } retcode = ftp_regular_transfer(conn, done); return retcode; }
/*********************************************************************** * * ftp_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (ftp_perform). * * The input argument is already checked for validity. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4071-L4109
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_quit
static CURLcode ftp_quit(struct connectdata *conn) { CURLcode result = CURLE_OK; if(conn->proto.ftpc.ctl_valid) { result = Curl_pp_sendf(&conn->proto.ftpc.pp, "QUIT", NULL); if(result) { failf(conn->data, "Failure sending QUIT command: %s", curl_easy_strerror(result)); conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */ conn->bits.close = TRUE; /* mark for connection closure */ state(conn, FTP_STOP); return result; } state(conn, FTP_QUIT); result = ftp_easy_statemach(conn); } return result; }
/*********************************************************************** * * ftp_quit() * * This should be called before calling sclose() on an ftp control connection * (not data connections). We should then wait for the response from the * server before returning. The calling code should then try to close the * connection. * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4179-L4200
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_disconnect
static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection) { struct ftp_conn *ftpc= &conn->proto.ftpc; struct pingpong *pp = &ftpc->pp; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. ftp_quit() will check the state of ftp->ctl_valid. If it's ok it will try to send the QUIT command, otherwise it will just return. */ if(dead_connection) ftpc->ctl_valid = FALSE; /* The FTP session may or may not have been allocated/setup at this point! */ (void)ftp_quit(conn); /* ignore errors on the QUIT */ if(ftpc->entrypath) { struct SessionHandle *data = conn->data; if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) { data->state.most_recent_ftp_entrypath = NULL; } free(ftpc->entrypath); ftpc->entrypath = NULL; } freedirs(ftpc); if(ftpc->prevpath) { free(ftpc->prevpath); ftpc->prevpath = NULL; } if(ftpc->server_os) { free(ftpc->server_os); ftpc->server_os = NULL; } Curl_pp_disconnect(pp); #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI) Curl_sec_end(conn); #endif return CURLE_OK; }
/*********************************************************************** * * ftp_disconnect() * * Disconnect from an FTP server. Cleanup protocol-specific per-connection * resources. BLOCKING. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4209-L4253
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_parse_url_path
static CURLcode ftp_parse_url_path(struct connectdata *conn) { struct SessionHandle *data = conn->data; /* the ftp struct is already inited in ftp_connect() */ struct FTP *ftp = data->state.proto.ftp; struct ftp_conn *ftpc = &conn->proto.ftpc; const char *slash_pos; /* position of the first '/' char in curpos */ const char *path_to_use = data->state.path; const char *cur_pos; const char *filename = NULL; cur_pos = path_to_use; /* current position in path. point at the begin of next path component */ ftpc->ctl_valid = FALSE; ftpc->cwdfail = FALSE; switch(data->set.ftp_filemethod) { case FTPFILE_NOCWD: /* fastest, but less standard-compliant */ /* The best time to check whether the path is a file or directory is right here. so: the first condition in the if() right here, is there just in case someone decides to set path to NULL one day */ if(data->state.path && data->state.path[0] && (data->state.path[strlen(data->state.path) - 1] != '/') ) filename = data->state.path; /* this is a full file path */ /* ftpc->file is not used anywhere other than for operations on a file. In other words, never for directory operations. So we can safely leave filename as NULL here and use it as a argument in dir/file decisions. */ break; case FTPFILE_SINGLECWD: /* get the last slash */ if(!path_to_use[0]) { /* no dir, no file */ ftpc->dirdepth = 0; break; } slash_pos=strrchr(cur_pos, '/'); if(slash_pos || !*cur_pos) { ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0])); if(!ftpc->dirs) return CURLE_OUT_OF_MEMORY; ftpc->dirs[0] = curl_easy_unescape(conn->data, slash_pos ? cur_pos : "/", slash_pos ? curlx_sztosi(slash_pos-cur_pos) : 1, NULL); if(!ftpc->dirs[0]) { freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } ftpc->dirdepth = 1; /* we consider it to be a single dir */ filename = slash_pos ? slash_pos+1 : cur_pos; /* rest is file name */ } else filename = cur_pos; /* this is a file name only */ break; default: /* allow pretty much anything */ case FTPFILE_MULTICWD: ftpc->dirdepth = 0; ftpc->diralloc = 5; /* default dir depth to allocate */ ftpc->dirs = calloc(ftpc->diralloc, sizeof(ftpc->dirs[0])); if(!ftpc->dirs) return CURLE_OUT_OF_MEMORY; /* we have a special case for listing the root dir only */ if(strequal(path_to_use, "/")) { cur_pos++; /* make it point to the zero byte */ ftpc->dirs[0] = strdup("/"); ftpc->dirdepth++; } else { /* parse the URL path into separate path components */ while((slash_pos = strchr(cur_pos, '/')) != NULL) { /* 1 or 0 pointer offset to indicate absolute directory */ ssize_t absolute_dir = ((cur_pos - data->state.path > 0) && (ftpc->dirdepth == 0))?1:0; /* seek out the next path component */ if(slash_pos-cur_pos) { /* we skip empty path components, like "x//y" since the FTP command CWD requires a parameter and a non-existent parameter a) doesn't work on many servers and b) has no effect on the others. */ int len = curlx_sztosi(slash_pos - cur_pos + absolute_dir); ftpc->dirs[ftpc->dirdepth] = curl_easy_unescape(conn->data, cur_pos - absolute_dir, len, NULL); if(!ftpc->dirs[ftpc->dirdepth]) { /* run out of memory ... */ failf(data, "no memory"); freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } if(isBadFtpString(ftpc->dirs[ftpc->dirdepth])) { free(ftpc->dirs[ftpc->dirdepth]); freedirs(ftpc); return CURLE_URL_MALFORMAT; } } else { cur_pos = slash_pos + 1; /* jump to the rest of the string */ continue; } cur_pos = slash_pos + 1; /* jump to the rest of the string */ if(++ftpc->dirdepth >= ftpc->diralloc) { /* enlarge array */ char **bigger; ftpc->diralloc *= 2; /* double the size each time */ bigger = realloc(ftpc->dirs, ftpc->diralloc * sizeof(ftpc->dirs[0])); if(!bigger) { freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } ftpc->dirs = bigger; } } } filename = cur_pos; /* the rest is the file name */ break; } /* switch */ if(filename && *filename) { ftpc->file = curl_easy_unescape(conn->data, filename, 0, NULL); if(NULL == ftpc->file) { freedirs(ftpc); failf(data, "no memory"); return CURLE_OUT_OF_MEMORY; } if(isBadFtpString(ftpc->file)) { freedirs(ftpc); return CURLE_URL_MALFORMAT; } } else ftpc->file=NULL; /* instead of point to a zero byte, we make it a NULL pointer */ if(data->set.upload && !ftpc->file && (ftp->transfer == FTPTRANSFER_BODY)) { /* We need a file name when uploading. Return error! */ failf(data, "Uploading to a URL without a file name!"); return CURLE_URL_MALFORMAT; } ftpc->cwddone = FALSE; /* default to not done */ if(ftpc->prevpath) { /* prevpath is "raw" so we convert the input path before we compare the strings */ int dlen; char *path = curl_easy_unescape(conn->data, data->state.path, 0, &dlen); if(!path) { freedirs(ftpc); return CURLE_OUT_OF_MEMORY; } dlen -= ftpc->file?curlx_uztosi(strlen(ftpc->file)):0; if((dlen == curlx_uztosi(strlen(ftpc->prevpath))) && strnequal(path, ftpc->prevpath, dlen)) { infof(data, "Request has same path as previous transfer\n"); ftpc->cwddone = TRUE; } free(path); } return CURLE_OK; }
/*********************************************************************** * * ftp_parse_url_path() * * Parse the URL path into separate path components. * */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4262-L4438
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_dophase_done
static CURLcode ftp_dophase_done(struct connectdata *conn, bool connected) { struct FTP *ftp = conn->data->state.proto.ftp; struct ftp_conn *ftpc = &conn->proto.ftpc; if(connected) { bool completed; CURLcode result = ftp_do_more(conn, &completed); if(result) { if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) { /* close the second socket if it was created already */ Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; } return result; } } if(ftp->transfer != FTPTRANSFER_BODY) /* no data to transfer */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); else if(!connected) /* since we didn't connect now, we want do_more to get called */ conn->bits.do_more = TRUE; ftpc->ctl_valid = TRUE; /* seems good */ return CURLE_OK; }
/* call this when the DO phase has completed */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4441-L4471
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_doing
static CURLcode ftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result = ftp_multi_statemach(conn, dophase_done); if(result) DEBUGF(infof(conn->data, "DO phase failed\n")); else if(*dophase_done) { result = ftp_dophase_done(conn, FALSE /* not connected */); DEBUGF(infof(conn->data, "DO phase is complete2\n")); } return result; }
/* called from multi.c while DOing */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4474-L4487
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ftp_regular_transfer
static CURLcode ftp_regular_transfer(struct connectdata *conn, bool *dophase_done) { CURLcode result=CURLE_OK; bool connected=FALSE; struct SessionHandle *data = conn->data; struct ftp_conn *ftpc = &conn->proto.ftpc; data->req.size = -1; /* make sure this is unknown at this point */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, 0); Curl_pgrsSetDownloadSize(data, 0); ftpc->ctl_valid = TRUE; /* starts good */ result = ftp_perform(conn, &connected, /* have we connected after PASV/PORT */ dophase_done); /* all commands in the DO-phase done? */ if(CURLE_OK == result) { if(!*dophase_done) /* the DO phase has not completed yet */ return CURLE_OK; result = ftp_dophase_done(conn, connected); if(result) return result; } else freedirs(ftpc); return result; }
/*********************************************************************** * * ftp_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. * * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the * ftp_done() function without finding any major problem. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ftp.c#L4501-L4537
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_initinfo
CURLcode Curl_initinfo(struct SessionHandle *data) { struct Progress *pro = &data->progress; struct PureInfo *info =&data->info; pro->t_nslookup = 0; pro->t_connect = 0; pro->t_appconnect = 0; pro->t_pretransfer = 0; pro->t_starttransfer = 0; pro->timespent = 0; pro->t_redirect = 0; info->httpcode = 0; info->httpversion=0; info->filetime=-1; /* -1 is an illegal time and thus means unknown */ if(info->contenttype) free(info->contenttype); info->contenttype = NULL; info->header_size = 0; info->request_size = 0; info->numconnects = 0; info->conn_primary_ip[0] = '\0'; info->conn_local_ip[0] = '\0'; info->conn_primary_port = 0; info->conn_local_port = 0; return CURLE_OK; }
/* * This is supposed to be called in the beginning of a perform() session * and should reset all session-info variables */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/getinfo.c#L42-L73
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_gtls_init
int Curl_gtls_init(void) { int ret = 1; if(!gtls_inited) { ret = gnutls_global_init()?0:1; #ifdef GTLSDEBUG gnutls_global_set_log_function(tls_log_func); gnutls_global_set_log_level(2); #endif gtls_inited = TRUE; } return ret; }
/* Curl_gtls_init() * * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that * are not thread-safe and thus this function itself is not thread-safe and * must only be called from within curl_global_init() to keep the thread * situation under control! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/gtls.c#L163-L175
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
handshake
static CURLcode handshake(struct connectdata *conn, int sockindex, bool duringconnect, bool nonblocking) { struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gnutls_session session = conn->ssl[sockindex].session; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int rc; int what; for(;;) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, duringconnect); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing== connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading== connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_ready(readfd, writefd, nonblocking?0: timeout_ms?timeout_ms:1000); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) return CURLE_OK; else if(timeout_ms) { /* timeout */ failf(data, "SSL connection timeout at %ld", timeout_ms); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } rc = gnutls_handshake(session); if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { connssl->connecting_state = gnutls_record_get_direction(session)? ssl_connect_2_writing:ssl_connect_2_reading; continue; if(nonblocking) return CURLE_OK; } else if((rc < 0) && !gnutls_error_is_fatal(rc)) { const char *strerr = NULL; if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) { int alert = gnutls_alert_get(session); strerr = gnutls_alert_get_name(alert); } if(strerr == NULL) strerr = gnutls_strerror(rc); failf(data, "gnutls_handshake() warning: %s", strerr); } else if(rc < 0) { const char *strerr = NULL; if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) { int alert = gnutls_alert_get(session); strerr = gnutls_alert_get_name(alert); } if(strerr == NULL) strerr = gnutls_strerror(rc); failf(data, "gnutls_handshake() failed: %s", strerr); return CURLE_SSL_CONNECT_ERROR; } /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } }
/* this function does a SSL/TLS (re-)handshake */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/gtls.c#L242-L336
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
gtls_connect_common
static CURLcode gtls_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { int rc; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; /* Initiate the connection, if not already done */ if(ssl_connect_1==connssl->connecting_state) { rc = gtls_connect_step1 (conn, sockindex); if(rc) return rc; } rc = handshake(conn, sockindex, TRUE, nonblocking); if(rc) /* handshake() sets its own error message with failf() */ return rc; /* Finish connecting once the handshake is done */ if(ssl_connect_1==connssl->connecting_state) { rc = gtls_connect_step3(conn, sockindex); if(rc) return rc; } *done = ssl_connect_1==connssl->connecting_state; return CURLE_OK; }
/* * This function is called after the TCP connect has completed. Setup the TLS * layer and do all necessary magic. */ /* We use connssl->connecting_state to keep track of the connection status; there are three states: 'ssl_connect_1' (not started yet or complete), 'ssl_connect_2_reading' (waiting for data from server), and 'ssl_connect_2_writing' (waiting to be able to write). */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/gtls.c#L835-L866
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_gtls_shutdown
int Curl_gtls_shutdown(struct connectdata *conn, int sockindex) { ssize_t result; int retval = 0; struct SessionHandle *data = conn->data; int done = 0; char buf[120]; /* This has only been tested on the proftpd server, and the mod_tls code sends a close notify alert without waiting for a close notify alert in response. Thus we wait for a close notify alert from the server, but we do not send one. Let's hope other servers do the same... */ if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR); if(conn->ssl[sockindex].session) { while(!done) { int what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT); if(what > 0) { /* Something to read, let's do it and hope that it is the close notify alert from the server */ result = gnutls_record_recv(conn->ssl[sockindex].session, buf, sizeof(buf)); switch(result) { case 0: /* This is the expected response. There was no data but only the close notify alert */ done = 1; break; case GNUTLS_E_AGAIN: case GNUTLS_E_INTERRUPTED: infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n"); break; default: retval = -1; done = 1; break; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); done = 1; break; } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; done = 1; } } gnutls_deinit(conn->ssl[sockindex].session); } gnutls_certificate_free_credentials(conn->ssl[sockindex].cred); #ifdef USE_TLS_SRP if(data->set.ssl.authtype == CURL_TLSAUTH_SRP && data->set.ssl.username != NULL) gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred); #endif conn->ssl[sockindex].cred = NULL; conn->ssl[sockindex].session = NULL; return retval; }
/* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/gtls.c#L947-L1015
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_addrinfo_callback
CURLcode Curl_addrinfo_callback(struct connectdata *conn, int status, struct Curl_addrinfo *ai) { struct Curl_dns_entry *dns = NULL; CURLcode rc = CURLE_OK; conn->async.status = status; if(CURL_ASYNC_SUCCESS == status) { if(ai) { struct SessionHandle *data = conn->data; if(data->share) Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE); dns = Curl_cache_addr(data, ai, conn->async.hostname, conn->async.port); if(!dns) { /* failed to store, cleanup and return error */ Curl_freeaddrinfo(ai); rc = CURLE_OUT_OF_MEMORY; } if(data->share) Curl_share_unlock(data, CURL_LOCK_DATA_DNS); } else { rc = CURLE_OUT_OF_MEMORY; } } conn->async.dns = dns; /* Set async.done TRUE last in this function since it may be used multi- threaded and once this is TRUE the other thread may read fields from the async struct */ conn->async.done = TRUE; /* ipv4: The input hostent struct will be freed by ares when we return from this function */ return rc; }
/* * Curl_addrinfo_callback() gets called by ares, gethostbyname_thread() * or getaddrinfo_thread() when we got the name resolved (or not!). * * If the status argument is CURL_ASYNC_SUCCESS, this function takes * ownership of the Curl_addrinfo passed, storing the resolved data * in the DNS cache. * * The storage operation locks and unlocks the DNS cache. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/hostasyn.c#L73-L116
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_async_resolved
CURLcode Curl_async_resolved(struct connectdata *conn, bool *protocol_done) { CURLcode code; if(conn->async.dns) { conn->dns_entry = conn->async.dns; conn->async.dns = NULL; } code = Curl_setup_conn(conn, protocol_done); if(code) /* We're not allowed to return failure with memory left allocated in the connectdata struct, free those here */ Curl_disconnect(conn, FALSE); /* close the connection */ return code; }
/* Call this function after Curl_connect() has returned async=TRUE and then a successful name resolve has been received. Note: this function disconnects and frees the conn data in case of resolve failure */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/hostasyn.c#L123-L141
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_set_dns_servers
CURLcode Curl_set_dns_servers(struct SessionHandle *data, char *servers) { (void)data; (void)servers; return CURLE_NOT_BUILT_IN; }
/* * Function provided by the resolver backend to set DNS servers to use. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/hostsyn.c#L66-L73
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
imap_sendf
static CURLcode imap_sendf(struct connectdata *conn, const char *idstr, /* command id to wait for */ const char *fmt, ...) { CURLcode res; struct imap_conn *imapc = &conn->proto.imapc; va_list ap; va_start(ap, fmt); imapc->idstr = idstr; res = Curl_pp_vsendf(&imapc->pp, fmt, ap); va_end(ap); return res; }
/*********************************************************************** * * imap_sendf() * * Sends the formated string as an IMAP command to the server. * * Designed to never block. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/imap.c#L214-L230
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
imap_endofresp
static int imap_endofresp(struct pingpong *pp, int *resp) { char *line = pp->linestart_resp; size_t len = pp->nread_resp; struct imap_conn *imapc = &pp->conn->proto.imapc; const char *id = imapc->idstr; size_t id_len = strlen(id); size_t wordlen; /* Do we have a generic command response? */ if(len >= id_len + 3) { if(!memcmp(id, line, id_len) && line[id_len] == ' ') { *resp = line[id_len + 1]; /* O, N or B */ return TRUE; } } /* Do we have a generic continuation response? */ if((len == 3 && !memcmp("+", line, 1)) || (len >= 2 && !memcmp("+ ", line, 2))) { *resp = '+'; return TRUE; } /* Are we processing CAPABILITY command responses? */ if(imapc->state == IMAP_CAPABILITY) { /* Do we have a valid response? */ if(len >= 2 && !memcmp("* ", line, 2)) { line += 2; len -= 2; /* Loop through the data line */ for(;;) { while(len && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { if(*line == '\n') return FALSE; 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++; /* Has the server explicitly disabled clear text authentication? */ if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13)) imapc->login_disabled = TRUE; /* Do we have a SASL based authentication mechanism? */ else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) { line += 5; len -= 5; wordlen -= 5; /* Test the word for a matching authentication mechanism */ if(wordlen == 5 && !memcmp(line, "LOGIN", 5)) imapc->authmechs |= SASL_MECH_LOGIN; if(wordlen == 5 && !memcmp(line, "PLAIN", 5)) imapc->authmechs |= SASL_MECH_PLAIN; else if(wordlen == 8 && !memcmp(line, "CRAM-MD5", 8)) imapc->authmechs |= SASL_MECH_CRAM_MD5; else if(wordlen == 10 && !memcmp(line, "DIGEST-MD5", 10)) imapc->authmechs |= SASL_MECH_DIGEST_MD5; else if(wordlen == 6 && !memcmp(line, "GSSAPI", 6)) imapc->authmechs |= SASL_MECH_GSSAPI; else if(wordlen == 8 && !memcmp(line, "EXTERNAL", 8)) imapc->authmechs |= SASL_MECH_EXTERNAL; else if(wordlen == 4 && !memcmp(line, "NTLM", 4)) imapc->authmechs |= SASL_MECH_NTLM; } line += wordlen; len -= wordlen; } } } /* Are we processing FETCH command responses? */ if(imapc->state == IMAP_FETCH) { /* Do we have a valid response? */ if(len >= 2 && !memcmp("* ", line, 2)) { *resp = '*'; return TRUE; } } return FALSE; /* Nothing for us */ }
/* Function that checks for an ending imap status code at the start of the given string but also detects the supported authentication mechanisms from the CAPABILITY response. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/imap.c#L328-L424
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
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", "STARTTLS", "UPGRADETLS", "CAPABILITY", "AUTHENTICATE_PLAIN", "AUTHENTICATE_LOGIN", "AUTHENTICATE_LOGIN_PASSWD", "AUTHENTICATE_CRAMMD5", "AUTHENTICATE_DIGESTMD5", "AUTHENTICATE_DIGESTMD5_RESP", "AUTHENTICATE_NTLM", "AUTHENTICATE_NTLM_TYPE2MSG", "AUTHENTICATE", "LOGIN", "SELECT", "FETCH", "LOGOUT", /* LAST */ }; if(imapc->state != newstate) infof(conn->data, "IMAP %p state change from %s to %s\n", imapc, names[imapc->state], names[newstate]); #endif imapc->state = newstate; }
/* This is the ONLY way to change IMAP state! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/imap.c#L427-L460
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
imap_getsock
static int imap_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks); }
/* For the IMAP "protocol connect" and "doing" phases only */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/imap.c#L578-L582
4389085c8ce35cff887a4cc18fc47d1133d89ffb