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
check_gss_err
static int check_gss_err(struct SessionHandle *data, OM_uint32 major_status, OM_uint32 minor_status, const char* function) { if(GSS_ERROR(major_status)) { OM_uint32 maj_stat,min_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; char buf[1024]; size_t len; len = 0; msg_ctx = 0; while(!msg_ctx) { /* convert major status code (GSS-API error) to text */ maj_stat = gss_display_status(&min_stat, major_status, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &status_string); if(maj_stat == GSS_S_COMPLETE) { if(sizeof(buf) > len + status_string.length + 1) { strcpy(buf+len, (char*) status_string.value); len += status_string.length; } gss_release_buffer(&min_stat, &status_string); break; } gss_release_buffer(&min_stat, &status_string); } if(sizeof(buf) > len + 3) { strcpy(buf+len, ".\n"); len += 2; } msg_ctx = 0; while(!msg_ctx) { /* convert minor status code (underlying routine error) to text */ maj_stat = gss_display_status(&min_stat, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &status_string); if(maj_stat == GSS_S_COMPLETE) { if(sizeof(buf) > len + status_string.length) strcpy(buf+len, (char*) status_string.value); gss_release_buffer(&min_stat, &status_string); break; } gss_release_buffer(&min_stat, &status_string); } failf(data, "GSSAPI error: %s failed:\n%s", function, buf); return(1); } return(0); }
/* * Helper gssapi error functions. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/socks_gssapi.c#L57-L111
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
check_sspi_err
static int check_sspi_err(struct connectdata *conn, SECURITY_STATUS status, const char* function) { if(status != SEC_E_OK && status != SEC_I_COMPLETE_AND_CONTINUE && status != SEC_I_COMPLETE_NEEDED && status != SEC_I_CONTINUE_NEEDED) { failf(conn->data, "SSPI error: %s failed: %s", function, Curl_sspi_strerror(conn, status)); return 1; } return 0; }
/* * Helper sspi error functions. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/socks_sspi.c#L54-L67
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_SOCKS5_gssapi_negotiate
CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct connectdata *conn) { struct SessionHandle *data = conn->data; curl_socket_t sock = conn->sock[sockindex]; CURLcode code; ssize_t actualread; ssize_t written; int result; /* Needs GSSAPI authentication */ SECURITY_STATUS status; unsigned long sspi_ret_flags = 0; int gss_enc; SecBuffer sspi_send_token, sspi_recv_token, sspi_w_token[3]; SecBufferDesc input_desc, output_desc, wrap_desc; SecPkgContext_Sizes sspi_sizes; CredHandle cred_handle; CtxtHandle sspi_context; PCtxtHandle context_handle = NULL; SecPkgCredentials_Names names; TimeStamp expiry; char *service_name = NULL; unsigned short us_length; unsigned long qop; unsigned char socksreq[4]; /* room for gssapi exchange header only */ char *service = data->set.str[STRING_SOCKS5_GSSAPI_SERVICE]; /* GSSAPI request looks like * +----+------+-----+----------------+ * |VER | MTYP | LEN | TOKEN | * +----+------+----------------------+ * | 1 | 1 | 2 | up to 2^16 - 1 | * +----+------+-----+----------------+ */ /* prepare service name */ if(strchr(service, '/')) { service_name = malloc(strlen(service)); if(!service_name) return CURLE_OUT_OF_MEMORY; memcpy(service_name, service, strlen(service)); } else { service_name = malloc(strlen(service) + strlen(conn->proxy.name) + 2); if(!service_name) return CURLE_OUT_OF_MEMORY; snprintf(service_name,strlen(service) +strlen(conn->proxy.name)+2,"%s/%s", service,conn->proxy.name); } input_desc.cBuffers = 1; input_desc.pBuffers = &sspi_recv_token; input_desc.ulVersion = SECBUFFER_VERSION; sspi_recv_token.BufferType = SECBUFFER_TOKEN; sspi_recv_token.cbBuffer = 0; sspi_recv_token.pvBuffer = NULL; output_desc.cBuffers = 1; output_desc.pBuffers = &sspi_send_token; output_desc.ulVersion = SECBUFFER_VERSION; sspi_send_token.BufferType = SECBUFFER_TOKEN; sspi_send_token.cbBuffer = 0; sspi_send_token.pvBuffer = NULL; wrap_desc.cBuffers = 3; wrap_desc.pBuffers = sspi_w_token; wrap_desc.ulVersion = SECBUFFER_VERSION; cred_handle.dwLower = 0; cred_handle.dwUpper = 0; status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT("Kerberos"), SECPKG_CRED_OUTBOUND, NULL, NULL, NULL, NULL, &cred_handle, &expiry); if(check_sspi_err(conn, status, "AcquireCredentialsHandle")) { failf(data, "Failed to acquire credentials."); Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); return CURLE_COULDNT_CONNECT; } /* As long as we need to keep sending some context info, and there's no */ /* errors, keep sending it... */ for(;;) { TCHAR *sname; sname = Curl_convert_UTF8_to_tchar(service_name); if(!sname) return CURLE_OUT_OF_MEMORY; status = s_pSecFn->InitializeSecurityContext(&cred_handle, context_handle, sname, ISC_REQ_MUTUAL_AUTH | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT, 0, SECURITY_NATIVE_DREP, &input_desc, 0, &sspi_context, &output_desc, &sspi_ret_flags, &expiry); Curl_unicodefree(sname); if(sspi_recv_token.pvBuffer) { s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); sspi_recv_token.pvBuffer = NULL; sspi_recv_token.cbBuffer = 0; } if(check_sspi_err(conn, status, "InitializeSecurityContext")) { Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); failf(data, "Failed to initialise security context."); return CURLE_COULDNT_CONNECT; } if(sspi_send_token.cbBuffer != 0) { socksreq[0] = 1; /* gssapi subnegotiation version */ socksreq[1] = 1; /* authentication message type */ us_length = htons((short)sspi_send_token.cbBuffer); memcpy(socksreq+2, &us_length, sizeof(short)); code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written); if((code != CURLE_OK) || (4 != written)) { failf(data, "Failed to send SSPI authentication request."); Curl_safefree(service_name); s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer, sspi_send_token.cbBuffer, &written); if((code != CURLE_OK) || (sspi_send_token.cbBuffer != (size_t)written)) { failf(data, "Failed to send SSPI authentication token."); Curl_safefree(service_name); s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } } s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); sspi_send_token.pvBuffer = NULL; sspi_send_token.cbBuffer = 0; s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); sspi_recv_token.pvBuffer = NULL; sspi_recv_token.cbBuffer = 0; if(status != SEC_I_CONTINUE_NEEDED) break; /* analyse response */ /* GSSAPI response looks like * +----+------+-----+----------------+ * |VER | MTYP | LEN | TOKEN | * +----+------+----------------------+ * | 1 | 1 | 2 | up to 2^16 - 1 | * +----+------+-----+----------------+ */ result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread); if(result != CURLE_OK || actualread != 4) { failf(data, "Failed to receive SSPI authentication response."); Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } /* ignore the first (VER) byte */ if(socksreq[1] == 255) { /* status / message type */ failf(data, "User was rejected by the SOCKS5 server (%d %d).", socksreq[0], socksreq[1]); Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } if(socksreq[1] != 1) { /* status / messgae type */ failf(data, "Invalid SSPI authentication response type (%d %d).", socksreq[0], socksreq[1]); Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } memcpy(&us_length, socksreq+2, sizeof(short)); us_length = ntohs(us_length); sspi_recv_token.cbBuffer = us_length; sspi_recv_token.pvBuffer = malloc(us_length); if(!sspi_recv_token.pvBuffer) { Curl_safefree(service_name); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } result = Curl_blockread_all(conn, sock, (char *)sspi_recv_token.pvBuffer, sspi_recv_token.cbBuffer, &actualread); if(result != CURLE_OK || actualread != us_length) { failf(data, "Failed to receive SSPI authentication token."); Curl_safefree(service_name); s_pSecFn->FreeContextBuffer(sspi_recv_token.pvBuffer); s_pSecFn->FreeCredentialsHandle(&cred_handle); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } context_handle = &sspi_context; } Curl_safefree(service_name); /* Everything is good so far, user was authenticated! */ status = s_pSecFn->QueryCredentialsAttributes(&cred_handle, SECPKG_CRED_ATTR_NAMES, &names); s_pSecFn->FreeCredentialsHandle(&cred_handle); if(check_sspi_err(conn, status, "QueryCredentialAttributes")) { s_pSecFn->DeleteSecurityContext(&sspi_context); s_pSecFn->FreeContextBuffer(names.sUserName); failf(data, "Failed to determine user name."); return CURLE_COULDNT_CONNECT; } infof(data, "SOCKS5 server authencticated user %s with gssapi.\n", names.sUserName); s_pSecFn->FreeContextBuffer(names.sUserName); /* Do encryption */ socksreq[0] = 1; /* gssapi subnegotiation version */ socksreq[1] = 2; /* encryption message type */ gss_enc = 0; /* no data protection */ /* do confidentiality protection if supported */ if(sspi_ret_flags & ISC_REQ_CONFIDENTIALITY) gss_enc = 2; /* else do integrity protection */ else if(sspi_ret_flags & ISC_REQ_INTEGRITY) gss_enc = 1; infof(data, "SOCKS5 server supports gssapi %s data protection.\n", (gss_enc==0)?"no":((gss_enc==1)?"integrity":"confidentiality") ); /* force to no data protection, avoid encryption/decryption for now */ gss_enc = 0; /* * Sending the encryption type in clear seems wrong. It should be * protected with gss_seal()/gss_wrap(). See RFC1961 extract below * The NEC reference implementations on which this is based is * therefore at fault * * +------+------+------+.......................+ * + ver | mtyp | len | token | * +------+------+------+.......................+ * + 0x01 | 0x02 | 0x02 | up to 2^16 - 1 octets | * +------+------+------+.......................+ * * Where: * * - "ver" is the protocol version number, here 1 to represent the * first version of the SOCKS/GSS-API protocol * * - "mtyp" is the message type, here 2 to represent a protection * -level negotiation message * * - "len" is the length of the "token" field in octets * * - "token" is the GSS-API encapsulated protection level * * The token is produced by encapsulating an octet containing the * required protection level using gss_seal()/gss_wrap() with conf_req * set to FALSE. The token is verified using gss_unseal()/ * gss_unwrap(). * */ if(data->set.socks5_gssapi_nec) { us_length = htons((short)1); memcpy(socksreq+2, &us_length, sizeof(short)); } else { status = s_pSecFn->QueryContextAttributes(&sspi_context, SECPKG_ATTR_SIZES, &sspi_sizes); if(check_sspi_err(conn, status, "QueryContextAttributes")) { s_pSecFn->DeleteSecurityContext(&sspi_context); failf(data, "Failed to query security context attributes."); return CURLE_COULDNT_CONNECT; } sspi_w_token[0].cbBuffer = sspi_sizes.cbSecurityTrailer; sspi_w_token[0].BufferType = SECBUFFER_TOKEN; sspi_w_token[0].pvBuffer = malloc(sspi_sizes.cbSecurityTrailer); if(!sspi_w_token[0].pvBuffer) { s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } sspi_w_token[1].cbBuffer = 1; sspi_w_token[1].pvBuffer = malloc(1); if(!sspi_w_token[1].pvBuffer) { s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } memcpy(sspi_w_token[1].pvBuffer,&gss_enc,1); sspi_w_token[2].BufferType = SECBUFFER_PADDING; sspi_w_token[2].cbBuffer = sspi_sizes.cbBlockSize; sspi_w_token[2].pvBuffer = malloc(sspi_sizes.cbBlockSize); if(!sspi_w_token[2].pvBuffer) { s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } status = s_pSecFn->EncryptMessage(&sspi_context, KERB_WRAP_NO_ENCRYPT, &wrap_desc, 0); if(check_sspi_err(conn, status, "EncryptMessage")) { s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); failf(data, "Failed to query security context attributes."); return CURLE_COULDNT_CONNECT; } sspi_send_token.cbBuffer = sspi_w_token[0].cbBuffer + sspi_w_token[1].cbBuffer + sspi_w_token[2].cbBuffer; sspi_send_token.pvBuffer = malloc(sspi_send_token.cbBuffer); if(!sspi_send_token.pvBuffer) { s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } memcpy(sspi_send_token.pvBuffer, sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer); memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer, sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer); memcpy((PUCHAR) sspi_send_token.pvBuffer +sspi_w_token[0].cbBuffer +sspi_w_token[1].cbBuffer, sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); sspi_w_token[0].pvBuffer = NULL; sspi_w_token[0].cbBuffer = 0; s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); sspi_w_token[1].pvBuffer = NULL; sspi_w_token[1].cbBuffer = 0; s_pSecFn->FreeContextBuffer(sspi_w_token[2].pvBuffer); sspi_w_token[2].pvBuffer = NULL; sspi_w_token[2].cbBuffer = 0; us_length = htons((short)sspi_send_token.cbBuffer); memcpy(socksreq+2,&us_length,sizeof(short)); } code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written); if((code != CURLE_OK) || (4 != written)) { failf(data, "Failed to send SSPI encryption request."); s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } if(data->set.socks5_gssapi_nec) { memcpy(socksreq,&gss_enc,1); code = Curl_write_plain(conn, sock, (char *)socksreq, 1, &written); if((code != CURLE_OK) || (1 != written)) { failf(data, "Failed to send SSPI encryption type."); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } } else { code = Curl_write_plain(conn, sock, (char *)sspi_send_token.pvBuffer, sspi_send_token.cbBuffer, &written); if((code != CURLE_OK) || (sspi_send_token.cbBuffer != (size_t)written)) { failf(data, "Failed to send SSPI encryption type."); s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } s_pSecFn->FreeContextBuffer(sspi_send_token.pvBuffer); } result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread); if(result != CURLE_OK || actualread != 4) { failf(data, "Failed to receive SSPI encryption response."); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } /* ignore the first (VER) byte */ if(socksreq[1] == 255) { /* status / message type */ failf(data, "User was rejected by the SOCKS5 server (%d %d).", socksreq[0], socksreq[1]); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } if(socksreq[1] != 2) { /* status / message type */ failf(data, "Invalid SSPI encryption response type (%d %d).", socksreq[0], socksreq[1]); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } memcpy(&us_length, socksreq+2, sizeof(short)); us_length = ntohs(us_length); sspi_w_token[0].cbBuffer = us_length; sspi_w_token[0].pvBuffer = malloc(us_length); if(!sspi_w_token[0].pvBuffer) { s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_OUT_OF_MEMORY; } result = Curl_blockread_all(conn, sock, (char *)sspi_w_token[0].pvBuffer, sspi_w_token[0].cbBuffer, &actualread); if(result != CURLE_OK || actualread != us_length) { failf(data, "Failed to receive SSPI encryption type."); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } if(!data->set.socks5_gssapi_nec) { wrap_desc.cBuffers = 2; sspi_w_token[0].BufferType = SECBUFFER_STREAM; sspi_w_token[1].BufferType = SECBUFFER_DATA; sspi_w_token[1].cbBuffer = 0; sspi_w_token[1].pvBuffer = NULL; status = s_pSecFn->DecryptMessage(&sspi_context, &wrap_desc, 0, &qop); if(check_sspi_err(conn, status, "DecryptMessage")) { s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); failf(data, "Failed to query security context attributes."); return CURLE_COULDNT_CONNECT; } if(sspi_w_token[1].cbBuffer != 1) { failf(data, "Invalid SSPI encryption response length (%d).", sspi_w_token[1].cbBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } memcpy(socksreq,sspi_w_token[1].pvBuffer,sspi_w_token[1].cbBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[1].pvBuffer); } else { if(sspi_w_token[0].cbBuffer != 1) { failf(data, "Invalid SSPI encryption response length (%d).", sspi_w_token[0].cbBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); s_pSecFn->DeleteSecurityContext(&sspi_context); return CURLE_COULDNT_CONNECT; } memcpy(socksreq,sspi_w_token[0].pvBuffer,sspi_w_token[0].cbBuffer); s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer); } infof(data, "SOCKS5 access with%s protection granted.\n", (socksreq[0]==0)?"out gssapi data": ((socksreq[0]==1)?" gssapi integrity":" gssapi confidentiality")); /* For later use if encryption is required conn->socks5_gssapi_enctype = socksreq[0]; if(socksreq[0] != 0) conn->socks5_sspi_context = sspi_context; else { s_pSecFn->DeleteSecurityContext(&sspi_context); conn->socks5_sspi_context = sspi_context; } */ return CURLE_OK; }
/* This is the SSPI-using version of this function */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/socks_sspi.c#L70-L590
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_libssh2_error_to_CURLE
static CURLcode sftp_libssh2_error_to_CURLE(int err) { switch (err) { case LIBSSH2_FX_OK: return CURLE_OK; case LIBSSH2_FX_NO_SUCH_FILE: case LIBSSH2_FX_NO_SUCH_PATH: return CURLE_REMOTE_FILE_NOT_FOUND; case LIBSSH2_FX_PERMISSION_DENIED: case LIBSSH2_FX_WRITE_PROTECT: case LIBSSH2_FX_LOCK_CONFlICT: return CURLE_REMOTE_ACCESS_DENIED; case LIBSSH2_FX_NO_SPACE_ON_FILESYSTEM: case LIBSSH2_FX_QUOTA_EXCEEDED: return CURLE_REMOTE_DISK_FULL; case LIBSSH2_FX_FILE_ALREADY_EXISTS: return CURLE_REMOTE_FILE_EXISTS; case LIBSSH2_FX_DIR_NOT_EMPTY: return CURLE_QUOTE_ERROR; default: break; } return CURLE_SSH; }
/* kbd_callback */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L233-L263
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
state
static void state(struct connectdata *conn, sshstate nowstate) { #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[] = { "SSH_STOP", "SSH_INIT", "SSH_S_STARTUP", "SSH_HOSTKEY", "SSH_AUTHLIST", "SSH_AUTH_PKEY_INIT", "SSH_AUTH_PKEY", "SSH_AUTH_PASS_INIT", "SSH_AUTH_PASS", "SSH_AUTH_AGENT_INIT", "SSH_AUTH_AGENT_LIST", "SSH_AUTH_AGENT", "SSH_AUTH_HOST_INIT", "SSH_AUTH_HOST", "SSH_AUTH_KEY_INIT", "SSH_AUTH_KEY", "SSH_AUTH_DONE", "SSH_SFTP_INIT", "SSH_SFTP_REALPATH", "SSH_SFTP_QUOTE_INIT", "SSH_SFTP_POSTQUOTE_INIT", "SSH_SFTP_QUOTE", "SSH_SFTP_NEXT_QUOTE", "SSH_SFTP_QUOTE_STAT", "SSH_SFTP_QUOTE_SETSTAT", "SSH_SFTP_QUOTE_SYMLINK", "SSH_SFTP_QUOTE_MKDIR", "SSH_SFTP_QUOTE_RENAME", "SSH_SFTP_QUOTE_RMDIR", "SSH_SFTP_QUOTE_UNLINK", "SSH_SFTP_TRANS_INIT", "SSH_SFTP_UPLOAD_INIT", "SSH_SFTP_CREATE_DIRS_INIT", "SSH_SFTP_CREATE_DIRS", "SSH_SFTP_CREATE_DIRS_MKDIR", "SSH_SFTP_READDIR_INIT", "SSH_SFTP_READDIR", "SSH_SFTP_READDIR_LINK", "SSH_SFTP_READDIR_BOTTOM", "SSH_SFTP_READDIR_DONE", "SSH_SFTP_DOWNLOAD_INIT", "SSH_SFTP_DOWNLOAD_STAT", "SSH_SFTP_CLOSE", "SSH_SFTP_SHUTDOWN", "SSH_SCP_TRANS_INIT", "SSH_SCP_UPLOAD_INIT", "SSH_SCP_DOWNLOAD_INIT", "SSH_SCP_DONE", "SSH_SCP_SEND_EOF", "SSH_SCP_WAIT_EOF", "SSH_SCP_WAIT_CLOSE", "SSH_SCP_CHANNEL_FREE", "SSH_SESSION_DISCONNECT", "SSH_SESSION_FREE", "QUIT" }; #endif struct ssh_conn *sshc = &conn->proto.sshc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) if(sshc->state != nowstate) { infof(conn->data, "SFTP %p state change from %s to %s\n", sshc, names[sshc->state], names[nowstate]); } #endif sshc->state = nowstate; }
/* * SSH State machine related code */ /* This is the ONLY way to change SSH state! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L328-L400
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_getworkingpath
static CURLcode ssh_getworkingpath(struct connectdata *conn, char *homedir, /* when SFTP is used */ char **path) /* returns the allocated real path to work with */ { struct SessionHandle *data = conn->data; char *real_path = NULL; char *working_path; int working_path_len; working_path = curl_easy_unescape(data, data->state.path, 0, &working_path_len); if(!working_path) return CURLE_OUT_OF_MEMORY; /* Check for /~/ , indicating relative to the user's home directory */ if(conn->handler->protocol & CURLPROTO_SCP) { real_path = malloc(working_path_len+1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } if((working_path_len > 3) && (!memcmp(working_path, "/~/", 3))) /* It is referenced to the home directory, so strip the leading '/~/' */ memcpy(real_path, working_path+3, 4 + working_path_len-3); else memcpy(real_path, working_path, 1 + working_path_len); } else if(conn->handler->protocol & CURLPROTO_SFTP) { if((working_path_len > 1) && (working_path[1] == '~')) { size_t homelen = strlen(homedir); real_path = malloc(homelen + working_path_len + 1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } /* It is referenced to the home directory, so strip the leading '/' */ memcpy(real_path, homedir, homelen); real_path[homelen] = '/'; real_path[homelen+1] = '\0'; if(working_path_len > 3) { memcpy(real_path+homelen+1, working_path + 3, 1 + working_path_len -3); } } else { real_path = malloc(working_path_len+1); if(real_path == NULL) { free(working_path); return CURLE_OUT_OF_MEMORY; } memcpy(real_path, working_path, 1+working_path_len); } } free(working_path); /* store the pointer for the caller to receive */ *path = real_path; return CURLE_OK; }
/* figure out the path to work with in this particular request */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L403-L465
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_statemach_act
static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block) { CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; struct SSHPROTO *sftp_scp = data->state.proto.ssh; struct ssh_conn *sshc = &conn->proto.sshc; curl_socket_t sock = conn->sock[FIRSTSOCKET]; char *new_readdir_line; int rc = LIBSSH2_ERROR_NONE; int err; int seekerr = CURL_SEEKFUNC_OK; *block = 0; /* we're not blocking by default */ do { switch(sshc->state) { case SSH_INIT: sshc->secondCreateDirs = 0; sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_OK; /* Set libssh2 to non-blocking, since everything internally is non-blocking */ libssh2_session_set_blocking(sshc->ssh_session, 0); state(conn, SSH_S_STARTUP); /* fall-through */ case SSH_S_STARTUP: rc = libssh2_session_startup(sshc->ssh_session, (int)sock); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { failf(data, "Failure establishing ssh session"); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_FAILED_INIT; break; } state(conn, SSH_HOSTKEY); /* fall-through */ case SSH_HOSTKEY: /* * Before we authenticate we should check the hostkey's fingerprint * against our known hosts. How that is handled (reading from file, * whatever) is up to us. */ result = ssh_check_fingerprint(conn); if(result == CURLE_OK) state(conn, SSH_AUTHLIST); break; case SSH_AUTHLIST: /* * Figure out authentication methods * NB: As soon as we have provided a username to an openssh server we * must never change it later. Thus, always specify the correct username * here, even though the libssh2 docs kind of indicate that it should be * possible to get a 'generic' list (not user-specific) of authentication * methods, presumably with a blank username. That won't work in my * experience. * So always specify it here. */ sshc->authlist = libssh2_userauth_list(sshc->ssh_session, conn->user, curlx_uztoui(strlen(conn->user))); if(!sshc->authlist) { if((err = libssh2_session_last_errno(sshc->ssh_session)) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { state(conn, SSH_SESSION_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(err); break; } } infof(data, "SSH authentication methods available: %s\n", sshc->authlist); state(conn, SSH_AUTH_PKEY_INIT); break; case SSH_AUTH_PKEY_INIT: /* * Check the supported auth types in the order I feel is most secure * with the requested type of authentication */ sshc->authed = FALSE; if((data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY) && (strstr(sshc->authlist, "publickey") != NULL)) { char *home = NULL; bool rsa_pub_empty_but_ok = FALSE; sshc->rsa_pub = sshc->rsa = NULL; /* To ponder about: should really the lib be messing about with the HOME environment variable etc? */ home = curl_getenv("HOME"); if(data->set.str[STRING_SSH_PUBLIC_KEY] && !*data->set.str[STRING_SSH_PUBLIC_KEY]) rsa_pub_empty_but_ok = true; else if(data->set.str[STRING_SSH_PUBLIC_KEY]) sshc->rsa_pub = aprintf("%s", data->set.str[STRING_SSH_PUBLIC_KEY]); else if(home) sshc->rsa_pub = aprintf("%s/.ssh/id_dsa.pub", home); else /* as a final resort, try current dir! */ sshc->rsa_pub = strdup("id_dsa.pub"); if(!rsa_pub_empty_but_ok && (sshc->rsa_pub == NULL)) { Curl_safefree(home); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } if(data->set.str[STRING_SSH_PRIVATE_KEY]) sshc->rsa = aprintf("%s", data->set.str[STRING_SSH_PRIVATE_KEY]); else if(home) sshc->rsa = aprintf("%s/.ssh/id_dsa", home); else /* as a final resort, try current dir! */ sshc->rsa = strdup("id_dsa"); if(sshc->rsa == NULL) { Curl_safefree(home); Curl_safefree(sshc->rsa_pub); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->passphrase = data->set.str[STRING_KEY_PASSWD]; if(!sshc->passphrase) sshc->passphrase = ""; Curl_safefree(home); infof(data, "Using ssh public key file %s\n", sshc->rsa_pub); infof(data, "Using ssh private key file %s\n", sshc->rsa); state(conn, SSH_AUTH_PKEY); } else { state(conn, SSH_AUTH_PASS_INIT); } break; case SSH_AUTH_PKEY: /* The function below checks if the files exists, no need to stat() here. */ rc = libssh2_userauth_publickey_fromfile_ex(sshc->ssh_session, conn->user, curlx_uztoui( strlen(conn->user)), sshc->rsa_pub, sshc->rsa, sshc->passphrase); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } Curl_safefree(sshc->rsa_pub); Curl_safefree(sshc->rsa); if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized SSH public key authentication\n"); state(conn, SSH_AUTH_DONE); } else { char *err_msg; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); infof(data, "SSH public key authentication failed: %s\n", err_msg); state(conn, SSH_AUTH_PASS_INIT); } break; case SSH_AUTH_PASS_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD) && (strstr(sshc->authlist, "password") != NULL)) { state(conn, SSH_AUTH_PASS); } else { state(conn, SSH_AUTH_HOST_INIT); } break; case SSH_AUTH_PASS: rc = libssh2_userauth_password_ex(sshc->ssh_session, conn->user, curlx_uztoui(strlen(conn->user)), conn->passwd, curlx_uztoui(strlen(conn->passwd)), NULL); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized password authentication\n"); state(conn, SSH_AUTH_DONE); } else { state(conn, SSH_AUTH_HOST_INIT); } break; case SSH_AUTH_HOST_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_HOST) && (strstr(sshc->authlist, "hostbased") != NULL)) { state(conn, SSH_AUTH_HOST); } else { state(conn, SSH_AUTH_AGENT_INIT); } break; case SSH_AUTH_HOST: state(conn, SSH_AUTH_AGENT_INIT); break; case SSH_AUTH_AGENT_INIT: #ifdef HAVE_LIBSSH2_AGENT_API if((data->set.ssh_auth_types & CURLSSH_AUTH_AGENT) && (strstr(sshc->authlist, "publickey") != NULL)) { /* Connect to the ssh-agent */ /* The agent could be shared by a curl thread i believe but nothing obvious as keys can be added/removed at any time */ if(!sshc->ssh_agent) { sshc->ssh_agent = libssh2_agent_init(sshc->ssh_session); if(!sshc->ssh_agent) { infof(data, "Could not create agent object\n"); state(conn, SSH_AUTH_KEY_INIT); } } rc = libssh2_agent_connect(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc < 0) { infof(data, "Failure connecting to agent\n"); state(conn, SSH_AUTH_KEY_INIT); } else { state(conn, SSH_AUTH_AGENT_LIST); } } else #endif /* HAVE_LIBSSH2_AGENT_API */ state(conn, SSH_AUTH_KEY_INIT); break; case SSH_AUTH_AGENT_LIST: #ifdef HAVE_LIBSSH2_AGENT_API rc = libssh2_agent_list_identities(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc < 0) { infof(data, "Failure requesting identities to agent\n"); state(conn, SSH_AUTH_KEY_INIT); } else { state(conn, SSH_AUTH_AGENT); sshc->sshagent_prev_identity = NULL; } #endif break; case SSH_AUTH_AGENT: #ifdef HAVE_LIBSSH2_AGENT_API /* as prev_identity evolves only after an identity user auth finished we can safely request it again as long as EAGAIN is returned here or by libssh2_agent_userauth */ rc = libssh2_agent_get_identity(sshc->ssh_agent, &sshc->sshagent_identity, sshc->sshagent_prev_identity); if(rc == LIBSSH2_ERROR_EAGAIN) break; if(rc == 0) { rc = libssh2_agent_userauth(sshc->ssh_agent, conn->user, sshc->sshagent_identity); if(rc < 0) { if(rc != LIBSSH2_ERROR_EAGAIN) { /* tried and failed? go to next identity */ sshc->sshagent_prev_identity = sshc->sshagent_identity; } break; } } if(rc < 0) infof(data, "Failure requesting identities to agent\n"); else if(rc == 1) infof(data, "No identity would match\n"); if(rc == LIBSSH2_ERROR_NONE) { sshc->authed = TRUE; infof(data, "Agent based authentication successful\n"); state(conn, SSH_AUTH_DONE); } else state(conn, SSH_AUTH_KEY_INIT); #endif break; case SSH_AUTH_KEY_INIT: if((data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) && (strstr(sshc->authlist, "keyboard-interactive") != NULL)) { state(conn, SSH_AUTH_KEY); } else { state(conn, SSH_AUTH_DONE); } break; case SSH_AUTH_KEY: /* Authentication failed. Continue with keyboard-interactive now. */ rc = libssh2_userauth_keyboard_interactive_ex(sshc->ssh_session, conn->user, curlx_uztoui( strlen(conn->user)), &kbd_callback); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc == 0) { sshc->authed = TRUE; infof(data, "Initialized keyboard interactive authentication\n"); } state(conn, SSH_AUTH_DONE); break; case SSH_AUTH_DONE: if(!sshc->authed) { failf(data, "Authentication failure"); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_LOGIN_DENIED; break; } /* * At this point we have an authenticated ssh session. */ infof(data, "Authentication complete\n"); Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSH is connected */ conn->sockfd = sock; conn->writesockfd = CURL_SOCKET_BAD; if(conn->handler->protocol == CURLPROTO_SFTP) { state(conn, SSH_SFTP_INIT); break; } infof(data, "SSH CONNECT phase done\n"); state(conn, SSH_STOP); break; case SSH_SFTP_INIT: /* * Start the libssh2 sftp session */ sshc->sftp_session = libssh2_sftp_init(sshc->ssh_session); if(!sshc->sftp_session) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { char *err_msg; (void)libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0); failf(data, "Failure initializing sftp session: %s", err_msg); state(conn, SSH_SESSION_FREE); sshc->actualcode = CURLE_FAILED_INIT; break; } } state(conn, SSH_SFTP_REALPATH); break; case SSH_SFTP_REALPATH: { char tempHome[PATH_MAX]; /* * Get the "home" directory */ rc = sftp_libssh2_realpath(sshc->sftp_session, ".", tempHome, PATH_MAX-1); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc > 0) { /* It seems that this string is not always NULL terminated */ tempHome[rc] = '\0'; sshc->homedir = strdup(tempHome); if(!sshc->homedir) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } conn->data->state.most_recent_ftp_entrypath = sshc->homedir; } else { /* Return the error type */ err = sftp_libssh2_last_error(sshc->sftp_session); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; DEBUGF(infof(data, "error = %d makes libcurl = %d\n", err, (int)result)); state(conn, SSH_STOP); break; } } /* This is the last step in the SFTP connect phase. Do note that while we get the homedir here, we get the "workingpath" in the DO action since the homedir will remain the same between request but the working path will not. */ DEBUGF(infof(data, "SSH CONNECT phase done\n")); state(conn, SSH_STOP); break; case SSH_SFTP_QUOTE_INIT: result = ssh_getworkingpath(conn, sshc->homedir, &sftp_scp->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } if(data->set.quote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.quote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_SFTP_TRANS_INIT); } break; case SSH_SFTP_POSTQUOTE_INIT: if(data->set.postquote) { infof(data, "Sending quote commands\n"); sshc->quote_item = data->set.postquote; state(conn, SSH_SFTP_QUOTE); } else { state(conn, SSH_STOP); } break; case SSH_SFTP_QUOTE: /* Send any quote commands */ { const char *cp; /* * Support some of the "FTP" commands */ char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } if(curl_strequal("pwd", cmd)) { /* output debug output if that is requested */ char *tmp = aprintf("257 \"%s\" is current directory.\n", sftp_scp->path); if(!tmp) { result = CURLE_OUT_OF_MEMORY; state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; break; } if(data->set.verbose) { Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"PWD\n", 4, conn); Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp), conn); } /* this sends an FTP-like "header" to the header callback so that the current directory can be read very similar to how it is read when using ordinary FTP. */ result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp)); free(tmp); state(conn, SSH_SFTP_NEXT_QUOTE); break; } else if(cmd) { /* * the arguments following the command must be separated from the * command with a space so we can check for it unconditionally */ cp = strchr(cmd, ' '); if(cp == NULL) { failf(data, "Syntax error in SFTP command. Supply parameter(s)!"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } /* * also, every command takes at least one argument so we get that * first argument right now */ result = get_pathname(&cp, &sshc->quote_path1); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error: Bad first parameter"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } /* * SFTP is a binary protocol, so we don't send text commands to * the server. Instead, we scan for commands for commands used by * OpenSSH's sftp program and call the appropriate libssh2 * functions. */ if(curl_strnequal(cmd, "chgrp ", 6) || curl_strnequal(cmd, "chmod ", 6) || curl_strnequal(cmd, "chown ", 6) ) { /* attribute change */ /* sshc->quote_path1 contains the mode to set */ /* get the destination */ result = get_pathname(&cp, &sshc->quote_path2); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in chgrp/chmod/chown: " "Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } memset(&sshc->quote_attrs, 0, sizeof(LIBSSH2_SFTP_ATTRIBUTES)); state(conn, SSH_SFTP_QUOTE_STAT); break; } else if(curl_strnequal(cmd, "ln ", 3) || curl_strnequal(cmd, "symlink ", 8)) { /* symbolic linking */ /* sshc->quote_path1 is the source */ /* get the destination */ result = get_pathname(&cp, &sshc->quote_path2); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in ln/symlink: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } state(conn, SSH_SFTP_QUOTE_SYMLINK); break; } else if(curl_strnequal(cmd, "mkdir ", 6)) { /* create dir */ state(conn, SSH_SFTP_QUOTE_MKDIR); break; } else if(curl_strnequal(cmd, "rename ", 7)) { /* rename file */ /* first param is the source path */ /* second param is the dest. path */ result = get_pathname(&cp, &sshc->quote_path2); if(result) { if(result == CURLE_OUT_OF_MEMORY) failf(data, "Out of memory"); else failf(data, "Syntax error in rename: Bad second parameter"); Curl_safefree(sshc->quote_path1); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = result; break; } state(conn, SSH_SFTP_QUOTE_RENAME); break; } else if(curl_strnequal(cmd, "rmdir ", 6)) { /* delete dir */ state(conn, SSH_SFTP_QUOTE_RMDIR); break; } else if(curl_strnequal(cmd, "rm ", 3)) { state(conn, SSH_SFTP_QUOTE_UNLINK); break; } failf(data, "Unknown SFTP command"); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } if(!sshc->quote_item) { state(conn, SSH_SFTP_TRANS_INIT); } break; case SSH_SFTP_NEXT_QUOTE: Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); sshc->quote_item = sshc->quote_item->next; if(sshc->quote_item) { state(conn, SSH_SFTP_QUOTE); } else { if(sshc->nextstate != SSH_NO_STATE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_NO_STATE; } else { state(conn, SSH_SFTP_TRANS_INIT); } } break; case SSH_SFTP_QUOTE_STAT: { char *cmd = sshc->quote_item->data; sshc->acceptfail = FALSE; /* if a command starts with an asterisk, which a legal SFTP command never can, the command will be allowed to fail without it causing any aborts or cancels etc. It will cause libcurl to act as if the command is successful, whatever the server reponds. */ if(cmd[0] == '*') { cmd++; sshc->acceptfail = TRUE; } if(!curl_strnequal(cmd, "chmod", 5)) { /* Since chown and chgrp only set owner OR group but libssh2 wants to * set them both at once, we need to obtain the current ownership * first. This takes an extra protocol round trip. */ rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_STAT, &sshc->quote_attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { /* get those attributes */ err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to get SFTP stats failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } /* Now set the new attributes... */ if(curl_strnequal(cmd, "chgrp", 5)) { sshc->quote_attrs.gid = strtoul(sshc->quote_path1, NULL, 10); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; if(sshc->quote_attrs.gid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chgrp gid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } else if(curl_strnequal(cmd, "chmod", 5)) { sshc->quote_attrs.permissions = strtoul(sshc->quote_path1, NULL, 8); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS; /* permissions are octal */ if(sshc->quote_attrs.permissions == 0 && !ISDIGIT(sshc->quote_path1[0])) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chmod permissions not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } else if(curl_strnequal(cmd, "chown", 5)) { sshc->quote_attrs.uid = strtoul(sshc->quote_path1, NULL, 10); sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID; if(sshc->quote_attrs.uid == 0 && !ISDIGIT(sshc->quote_path1[0]) && !sshc->acceptfail) { Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Syntax error: chown uid not a number"); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } } /* Now send the completed structure... */ state(conn, SSH_SFTP_QUOTE_SETSTAT); break; } case SSH_SFTP_QUOTE_SETSTAT: rc = libssh2_sftp_stat_ex(sshc->sftp_session, sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_SETSTAT, &sshc->quote_attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "Attempt to set SFTP stats failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_SYMLINK: rc = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_SYMLINK); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "symlink command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_MKDIR: rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), data->set.new_directory_perms); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "mkdir command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RENAME: rc = libssh2_sftp_rename_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1)), sshc->quote_path2, curlx_uztoui(strlen(sshc->quote_path2)), LIBSSH2_SFTP_RENAME_OVERWRITE | LIBSSH2_SFTP_RENAME_ATOMIC | LIBSSH2_SFTP_RENAME_NATIVE); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); failf(data, "rename command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_RMDIR: rc = libssh2_sftp_rmdir_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1))); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "rmdir command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_QUOTE_UNLINK: rc = libssh2_sftp_unlink_ex(sshc->sftp_session, sshc->quote_path1, curlx_uztoui(strlen(sshc->quote_path1))); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc != 0 && !sshc->acceptfail) { err = sftp_libssh2_last_error(sshc->sftp_session); Curl_safefree(sshc->quote_path1); failf(data, "rm command failed: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); sshc->nextstate = SSH_NO_STATE; sshc->actualcode = CURLE_QUOTE_ERROR; break; } state(conn, SSH_SFTP_NEXT_QUOTE); break; case SSH_SFTP_TRANS_INIT: if(data->set.upload) state(conn, SSH_SFTP_UPLOAD_INIT); else { if(data->set.opt_no_body) state(conn, SSH_STOP); else if(sftp_scp->path[strlen(sftp_scp->path)-1] == '/') state(conn, SSH_SFTP_READDIR_INIT); else state(conn, SSH_SFTP_DOWNLOAD_INIT); } break; case SSH_SFTP_UPLOAD_INIT: { unsigned long flags; /* * NOTE!!! libssh2 requires that the destination path is a full path * that includes the destination file and name OR ends in a "/" * If this is not done the destination file will be named the * same name as the last directory in the path. */ if(data->state.resume_from != 0) { LIBSSH2_SFTP_ATTRIBUTES attrs; if(data->state.resume_from < 0) { rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_SFTP_STAT, &attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { data->state.resume_from = 0; } else { curl_off_t size = attrs.filesize; if(size < 0) { failf(data, "Bad file size (%" FORMAT_OFF_T ")", size); return CURLE_BAD_DOWNLOAD_RESUME; } data->state.resume_from = attrs.filesize; } } } if(data->set.ftp_append) /* Try to open for append, but create if nonexisting */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_APPEND; else if(data->state.resume_from > 0) /* If we have restart position then open for append */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_APPEND; else /* Clear file before writing (normal behaviour) */ flags = LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC; sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), flags, data->set.new_file_perms, LIBSSH2_SFTP_OPENFILE); if(!sshc->sftp_handle) { rc = libssh2_session_last_errno(sshc->ssh_session); if(LIBSSH2_ERROR_EAGAIN == rc) break; else { if(LIBSSH2_ERROR_SFTP_PROTOCOL == rc) /* only when there was an SFTP protocol error can we extract the sftp error! */ err = sftp_libssh2_last_error(sshc->sftp_session); else err = -1; /* not an sftp error at all */ if(sshc->secondCreateDirs) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = err>= LIBSSH2_FX_OK? sftp_libssh2_error_to_CURLE(err):CURLE_SSH; failf(data, "Creating the dir/file failed: %s", sftp_libssh2_strerror(err)); break; } else if(((err == LIBSSH2_FX_NO_SUCH_FILE) || (err == LIBSSH2_FX_FAILURE) || (err == LIBSSH2_FX_NO_SUCH_PATH)) && (data->set.ftp_create_missing_dirs && (strlen(sftp_scp->path) > 1))) { /* try to create the path remotely */ sshc->secondCreateDirs = 1; state(conn, SSH_SFTP_CREATE_DIRS_INIT); break; } state(conn, SSH_SFTP_CLOSE); sshc->actualcode = err>= LIBSSH2_FX_OK? sftp_libssh2_error_to_CURLE(err):CURLE_SSH; if(!sshc->actualcode) { /* Sometimes, for some reason libssh2_sftp_last_error() returns zero even though libssh2_sftp_open() failed previously! We need to work around that! */ sshc->actualcode = CURLE_SSH; err=-1; } failf(data, "Upload failed: %s (%d/%d)", err>= LIBSSH2_FX_OK?sftp_libssh2_strerror(err):"ssh error", err, rc); break; } } /* If we have restart point then we need to seek to the correct position. */ if(data->state.resume_from > 0) { /* Let's read off the proper amount of bytes from the input. */ if(conn->seek_func) { 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; data->req.size = data->set.infilesize; Curl_pgrsSetUploadSize(data, data->set.infilesize); } SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); } if(data->set.infilesize > 0) { data->req.size = data->set.infilesize; Curl_pgrsSetUploadSize(data, data->set.infilesize); } /* upload data */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; if(result) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result; } else { /* store this original bitmask setup to use later on if we can't figure out a "real" bitmask */ sshc->orig_waitfor = data->req.keepon; /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh2 sftp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; /* since we don't really wait for anything at this point, we want the state machine to move on as soon as possible so we set a very short timeout here */ Curl_expire(data, 1); state(conn, SSH_STOP); } break; } case SSH_SFTP_CREATE_DIRS_INIT: if(strlen(sftp_scp->path) > 1) { sshc->slash_pos = sftp_scp->path + 1; /* ignore the leading '/' */ state(conn, SSH_SFTP_CREATE_DIRS); } else { state(conn, SSH_SFTP_UPLOAD_INIT); } break; case SSH_SFTP_CREATE_DIRS: if((sshc->slash_pos = strchr(sshc->slash_pos, '/')) != NULL) { *sshc->slash_pos = 0; infof(data, "Creating directory '%s'\n", sftp_scp->path); state(conn, SSH_SFTP_CREATE_DIRS_MKDIR); break; } else { state(conn, SSH_SFTP_UPLOAD_INIT); } break; case SSH_SFTP_CREATE_DIRS_MKDIR: /* 'mode' - parameter is preliminary - default to 0644 */ rc = libssh2_sftp_mkdir_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), data->set.new_directory_perms); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } *sshc->slash_pos = '/'; ++sshc->slash_pos; if(rc == -1) { /* * Abort if failure wasn't that the dir already exists or the * permission was denied (creation might succeed further down the * path) - retry on unspecific FAILURE also */ err = sftp_libssh2_last_error(sshc->sftp_session); if((err != LIBSSH2_FX_FILE_ALREADY_EXISTS) && (err != LIBSSH2_FX_FAILURE) && (err != LIBSSH2_FX_PERMISSION_DENIED)) { result = sftp_libssh2_error_to_CURLE(err); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result?result:CURLE_SSH; break; } } state(conn, SSH_SFTP_CREATE_DIRS); break; case SSH_SFTP_READDIR_INIT: /* * This is a directory that we are trying to get, so produce a directory * listing */ sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui( strlen(sftp_scp->path)), 0, 0, LIBSSH2_SFTP_OPENDIR); if(!sshc->sftp_handle) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { err = sftp_libssh2_last_error(sshc->sftp_session); failf(data, "Could not open directory for reading: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; break; } } if((sshc->readdir_filename = malloc(PATH_MAX+1)) == NULL) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } if((sshc->readdir_longentry = malloc(PATH_MAX+1)) == NULL) { Curl_safefree(sshc->readdir_filename); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR: sshc->readdir_len = libssh2_sftp_readdir_ex(sshc->sftp_handle, sshc->readdir_filename, PATH_MAX, sshc->readdir_longentry, PATH_MAX, &sshc->readdir_attrs); if(sshc->readdir_len == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } if(sshc->readdir_len > 0) { sshc->readdir_filename[sshc->readdir_len] = '\0'; if(data->set.ftp_list_only) { char *tmpLine; tmpLine = aprintf("%s\n", sshc->readdir_filename); if(tmpLine == NULL) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } result = Curl_client_write(conn, CLIENTWRITE_BODY, tmpLine, sshc->readdir_len+1); Curl_safefree(tmpLine); if(result) { state(conn, SSH_STOP); break; } /* since this counts what we send to the client, we include the newline in this counter */ data->req.bytecount += sshc->readdir_len+1; /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_filename, sshc->readdir_len, conn); } } else { sshc->readdir_currLen = (int)strlen(sshc->readdir_longentry); sshc->readdir_totalLen = 80 + sshc->readdir_currLen; sshc->readdir_line = calloc(sshc->readdir_totalLen, 1); if(!sshc->readdir_line) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } memcpy(sshc->readdir_line, sshc->readdir_longentry, sshc->readdir_currLen); if((sshc->readdir_attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) && ((sshc->readdir_attrs.permissions & LIBSSH2_SFTP_S_IFMT) == LIBSSH2_SFTP_S_IFLNK)) { sshc->readdir_linkPath = malloc(PATH_MAX + 1); if(sshc->readdir_linkPath == NULL) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } snprintf(sshc->readdir_linkPath, PATH_MAX, "%s%s", sftp_scp->path, sshc->readdir_filename); state(conn, SSH_SFTP_READDIR_LINK); break; } state(conn, SSH_SFTP_READDIR_BOTTOM); break; } } else if(sshc->readdir_len == 0) { Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_READDIR_DONE); break; } else if(sshc->readdir_len <= 0) { err = sftp_libssh2_last_error(sshc->sftp_session); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; failf(data, "Could not open remote file for reading: %s :: %d", sftp_libssh2_strerror(err), libssh2_session_last_errno(sshc->ssh_session)); Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); break; } break; case SSH_SFTP_READDIR_LINK: sshc->readdir_len = libssh2_sftp_symlink_ex(sshc->sftp_session, sshc->readdir_linkPath, curlx_uztoui(strlen(sshc->readdir_linkPath)), sshc->readdir_filename, PATH_MAX, LIBSSH2_SFTP_READLINK); if(sshc->readdir_len == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } Curl_safefree(sshc->readdir_linkPath); /* get room for the filename and extra output */ sshc->readdir_totalLen += 4 + sshc->readdir_len; new_readdir_line = realloc(sshc->readdir_line, sshc->readdir_totalLen); if(!new_readdir_line) { Curl_safefree(sshc->readdir_line); Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); state(conn, SSH_SFTP_CLOSE); sshc->actualcode = CURLE_OUT_OF_MEMORY; break; } sshc->readdir_line = new_readdir_line; sshc->readdir_currLen += snprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, " -> %s", sshc->readdir_filename); state(conn, SSH_SFTP_READDIR_BOTTOM); break; case SSH_SFTP_READDIR_BOTTOM: sshc->readdir_currLen += snprintf(sshc->readdir_line + sshc->readdir_currLen, sshc->readdir_totalLen - sshc->readdir_currLen, "\n"); result = Curl_client_write(conn, CLIENTWRITE_BODY, sshc->readdir_line, sshc->readdir_currLen); if(result == CURLE_OK) { /* output debug output if that is requested */ if(data->set.verbose) { Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_line, sshc->readdir_currLen, conn); } data->req.bytecount += sshc->readdir_currLen; } Curl_safefree(sshc->readdir_line); if(result) { state(conn, SSH_STOP); } else state(conn, SSH_SFTP_READDIR); break; case SSH_SFTP_READDIR_DONE: if(libssh2_sftp_closedir(sshc->sftp_handle) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } sshc->sftp_handle = NULL; Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); /* no data to transfer */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); state(conn, SSH_STOP); break; case SSH_SFTP_DOWNLOAD_INIT: /* * Work on getting the specified file */ sshc->sftp_handle = libssh2_sftp_open_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_FXF_READ, data->set.new_file_perms, LIBSSH2_SFTP_OPENFILE); if(!sshc->sftp_handle) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { err = sftp_libssh2_last_error(sshc->sftp_session); failf(data, "Could not open remote file for reading: %s", sftp_libssh2_strerror(err)); state(conn, SSH_SFTP_CLOSE); result = sftp_libssh2_error_to_CURLE(err); sshc->actualcode = result?result:CURLE_SSH; break; } } state(conn, SSH_SFTP_DOWNLOAD_STAT); break; case SSH_SFTP_DOWNLOAD_STAT: { LIBSSH2_SFTP_ATTRIBUTES attrs; rc = libssh2_sftp_stat_ex(sshc->sftp_session, sftp_scp->path, curlx_uztoui(strlen(sftp_scp->path)), LIBSSH2_SFTP_STAT, &attrs); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { /* * libssh2_sftp_open() didn't return an error, so maybe the server * just doesn't support stat() */ data->req.size = -1; data->req.maxdownload = -1; } else { curl_off_t size = attrs.filesize; if(size < 0) { failf(data, "Bad file size (%" FORMAT_OFF_T ")", size); return CURLE_BAD_DOWNLOAD_RESUME; } if(conn->data->state.use_range) { curl_off_t from, to; char *ptr; char *ptr2; from=curlx_strtoofft(conn->data->state.range, &ptr, 0); while(*ptr && (ISSPACE(*ptr) || (*ptr=='-'))) ptr++; to=curlx_strtoofft(ptr, &ptr2, 0); if((ptr == ptr2) /* no "to" value given */ || (to >= size)) { to = size - 1; } if(from < 0) { /* from is relative to end of file */ from += size; } if(from >= size) { failf(data, "Offset (%" FORMAT_OFF_T ") was beyond file size (%" FORMAT_OFF_T ")", from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } if(from > to) { from = to; size = 0; } else { size = to - from + 1; } SFTP_SEEK(conn->proto.sshc.sftp_handle, from); } data->req.size = size; data->req.maxdownload = size; Curl_pgrsSetDownloadSize(data, size); } /* We can resume if we can seek to the resume position */ if(data->state.resume_from) { if(data->state.resume_from < 0) { /* We're supposed to download the last abs(from) bytes */ if((curl_off_t)attrs.filesize < -data->state.resume_from) { failf(data, "Offset (%" FORMAT_OFF_T ") was beyond file size (%" FORMAT_OFF_T ")", data->state.resume_from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } /* download from where? */ data->state.resume_from += attrs.filesize; } else { if((curl_off_t)attrs.filesize < data->state.resume_from) { failf(data, "Offset (%" FORMAT_OFF_T ") was beyond file size (%" FORMAT_OFF_T ")", data->state.resume_from, attrs.filesize); return CURLE_BAD_DOWNLOAD_RESUME; } } /* Does a completed file need to be seeked and started or closed ? */ /* Now store the number of bytes we are expected to download */ data->req.size = attrs.filesize - data->state.resume_from; data->req.maxdownload = attrs.filesize - data->state.resume_from; Curl_pgrsSetDownloadSize(data, attrs.filesize - data->state.resume_from); SFTP_SEEK(sshc->sftp_handle, data->state.resume_from); } } /* Setup the actual download */ if(data->req.size == 0) { /* no data to transfer */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); infof(data, "File already completely downloaded\n"); state(conn, SSH_STOP); break; } else { Curl_setup_transfer(conn, FIRSTSOCKET, data->req.size, FALSE, NULL, -1, NULL); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh2 recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; } if(result) { state(conn, SSH_SFTP_CLOSE); sshc->actualcode = result; } else { state(conn, SSH_STOP); } break; case SSH_SFTP_CLOSE: if(sshc->sftp_handle) { rc = libssh2_sftp_close(sshc->sftp_handle); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to close libssh2 file\n"); } sshc->sftp_handle = NULL; } if(sftp_scp) Curl_safefree(sftp_scp->path); DEBUGF(infof(data, "SFTP DONE done\n")); /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT After nextstate is executed,the control should come back to SSH_SFTP_CLOSE to pass the correct result back */ if(sshc->nextstate != SSH_NO_STATE) { state(conn, sshc->nextstate); sshc->nextstate = SSH_SFTP_CLOSE; } else { state(conn, SSH_STOP); result = sshc->actualcode; } break; case SSH_SFTP_SHUTDOWN: /* during times we get here due to a broken transfer and then the sftp_handle might not have been taken down so make sure that is done before we proceed */ if(sshc->sftp_handle) { rc = libssh2_sftp_close(sshc->sftp_handle); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to close libssh2 file\n"); } sshc->sftp_handle = NULL; } if(sshc->sftp_session) { rc = libssh2_sftp_shutdown(sshc->sftp_session); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to stop libssh2 sftp subsystem\n"); } sshc->sftp_session = NULL; } Curl_safefree(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_DISCONNECT); break; case SSH_SCP_TRANS_INIT: result = ssh_getworkingpath(conn, sshc->homedir, &sftp_scp->path); if(result) { sshc->actualcode = result; state(conn, SSH_STOP); break; } if(data->set.upload) { if(data->set.infilesize < 0) { failf(data, "SCP requires a known file size for upload"); sshc->actualcode = CURLE_UPLOAD_FAILED; state(conn, SSH_SCP_CHANNEL_FREE); break; } state(conn, SSH_SCP_UPLOAD_INIT); } else { state(conn, SSH_SCP_DOWNLOAD_INIT); } break; case SSH_SCP_UPLOAD_INIT: /* * libssh2 requires that the destination path is a full path that * includes the destination file and name OR ends in a "/" . If this is * not done the destination file will be named the same name as the last * directory in the path. */ sshc->ssh_channel = SCP_SEND(sshc->ssh_session, sftp_scp->path, data->set.new_file_perms, data->set.infilesize); if(!sshc->ssh_channel) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { int ssh_err; char *err_msg; ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0)); failf(conn->data, "%s", err_msg); state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); break; } } /* upload data */ Curl_setup_transfer(conn, -1, data->req.size, FALSE, NULL, FIRSTSOCKET, NULL); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->sockfd = conn->writesockfd; if(result) { state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = result; } else { /* we want to use the _sending_ function even when the socket turns out readable as the underlying libssh2 scp send function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_OUT; state(conn, SSH_STOP); } break; case SSH_SCP_DOWNLOAD_INIT: { /* * We must check the remote file; if it is a directory no values will * be set in sb */ struct stat sb; curl_off_t bytecount; /* clear the struct scp recv will fill in */ memset(&sb, 0, sizeof(struct stat)); /* get a fresh new channel from the ssh layer */ sshc->ssh_channel = libssh2_scp_recv(sshc->ssh_session, sftp_scp->path, &sb); if(!sshc->ssh_channel) { if(libssh2_session_last_errno(sshc->ssh_session) == LIBSSH2_ERROR_EAGAIN) { rc = LIBSSH2_ERROR_EAGAIN; break; } else { int ssh_err; char *err_msg; ssh_err = (int)(libssh2_session_last_error(sshc->ssh_session, &err_msg, NULL, 0)); failf(conn->data, "%s", err_msg); state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = libssh2_session_error_to_CURLE(ssh_err); break; } } /* download data */ bytecount = (curl_off_t)sb.st_size; data->req.maxdownload = (curl_off_t)sb.st_size; Curl_setup_transfer(conn, FIRSTSOCKET, bytecount, FALSE, NULL, -1, NULL); /* not set by Curl_setup_transfer to preserve keepon bits */ conn->writesockfd = conn->sockfd; /* we want to use the _receiving_ function even when the socket turns out writableable as the underlying libssh2 recv function will deal with both accordingly */ conn->cselect_bits = CURL_CSELECT_IN; if(result) { state(conn, SSH_SCP_CHANNEL_FREE); sshc->actualcode = result; } else state(conn, SSH_STOP); } break; case SSH_SCP_DONE: if(data->set.upload) state(conn, SSH_SCP_SEND_EOF); else state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_SEND_EOF: if(sshc->ssh_channel) { rc = libssh2_channel_send_eof(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { infof(data, "Failed to send libssh2 channel EOF\n"); } } state(conn, SSH_SCP_WAIT_EOF); break; case SSH_SCP_WAIT_EOF: if(sshc->ssh_channel) { rc = libssh2_channel_wait_eof(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { infof(data, "Failed to get channel EOF: %d\n", rc); } } state(conn, SSH_SCP_WAIT_CLOSE); break; case SSH_SCP_WAIT_CLOSE: if(sshc->ssh_channel) { rc = libssh2_channel_wait_closed(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc) { infof(data, "Channel failed to close: %d\n", rc); } } state(conn, SSH_SCP_CHANNEL_FREE); break; case SSH_SCP_CHANNEL_FREE: if(sshc->ssh_channel) { rc = libssh2_channel_free(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to free libssh2 scp subsystem\n"); } sshc->ssh_channel = NULL; } DEBUGF(infof(data, "SCP DONE phase complete\n")); #if 0 /* PREV */ state(conn, SSH_SESSION_DISCONNECT); #endif state(conn, SSH_STOP); result = sshc->actualcode; break; case SSH_SESSION_DISCONNECT: /* during weird times when we've been prematurely aborted, the channel is still alive when we reach this state and we MUST kill the channel properly first */ if(sshc->ssh_channel) { rc = libssh2_channel_free(sshc->ssh_channel); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to free libssh2 scp subsystem\n"); } sshc->ssh_channel = NULL; } if(sshc->ssh_session) { rc = libssh2_session_disconnect(sshc->ssh_session, "Shutdown"); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to disconnect libssh2 session\n"); } } Curl_safefree(sshc->homedir); conn->data->state.most_recent_ftp_entrypath = NULL; state(conn, SSH_SESSION_FREE); break; case SSH_SESSION_FREE: #ifdef HAVE_LIBSSH2_KNOWNHOST_API if(sshc->kh) { libssh2_knownhost_free(sshc->kh); sshc->kh = NULL; } #endif #ifdef HAVE_LIBSSH2_AGENT_API if(sshc->ssh_agent) { rc = libssh2_agent_disconnect(sshc->ssh_agent); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to disconnect from libssh2 agent\n"); } libssh2_agent_free (sshc->ssh_agent); sshc->ssh_agent = NULL; /* NB: there is no need to free identities, they are part of internal agent stuff */ sshc->sshagent_identity = NULL; sshc->sshagent_prev_identity = NULL; } #endif if(sshc->ssh_session) { rc = libssh2_session_free(sshc->ssh_session); if(rc == LIBSSH2_ERROR_EAGAIN) { break; } else if(rc < 0) { infof(data, "Failed to free libssh2 session\n"); } sshc->ssh_session = NULL; } /* worst-case scenario cleanup */ DEBUGASSERT(sshc->ssh_session == NULL); DEBUGASSERT(sshc->ssh_channel == NULL); DEBUGASSERT(sshc->sftp_session == NULL); DEBUGASSERT(sshc->sftp_handle == NULL); #ifdef HAVE_LIBSSH2_KNOWNHOST_API DEBUGASSERT(sshc->kh == NULL); #endif #ifdef HAVE_LIBSSH2_AGENT_API DEBUGASSERT(sshc->ssh_agent == NULL); #endif Curl_safefree(sshc->rsa_pub); Curl_safefree(sshc->rsa); Curl_safefree(sshc->quote_path1); Curl_safefree(sshc->quote_path2); Curl_safefree(sshc->homedir); Curl_safefree(sshc->readdir_filename); Curl_safefree(sshc->readdir_longentry); Curl_safefree(sshc->readdir_line); Curl_safefree(sshc->readdir_linkPath); /* the code we are about to return */ result = sshc->actualcode; memset(sshc, 0, sizeof(struct ssh_conn)); conn->bits.close = TRUE; sshc->state = SSH_SESSION_FREE; /* current */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; case SSH_QUIT: /* fallthrough, just stop! */ default: /* internal error */ sshc->nextstate = SSH_NO_STATE; state(conn, SSH_STOP); break; } } while(!rc && (sshc->state != SSH_STOP)); if(rc == LIBSSH2_ERROR_EAGAIN) { /* we would block, we need to wait for the socket to be ready (in the right direction too)! */ *block = TRUE; } return result; }
/* * ssh_statemach_act() runs the SSH state machine as far as it can without * blocking and without reaching the end. The data the pointer 'block' points * to will be set to TRUE if the libssh2 function returns LIBSSH2_ERROR_EAGAIN * meaning it wants to be called again when the socket is ready */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L686-L2544
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_perform_getsock
static int ssh_perform_getsock(const struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { #ifdef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION int bitmap = GETSOCK_BLANK; (void)numsocks; sock[0] = conn->sock[FIRSTSOCKET]; if(conn->waitfor & KEEP_RECV) bitmap |= GETSOCK_READSOCK(FIRSTSOCKET); if(conn->waitfor & KEEP_SEND) bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET); return bitmap; #else /* if we don't know the direction we can use the generic *_getsock() function even for the protocol_connect and doing states */ return Curl_single_getsock(conn, sock, numsocks); #endif }
/* called by the multi interface to figure out what socket(s) to wait for and for what actions in the DO_DONE, PERFORM and WAITPERFORM states */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2548-L2571
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_getsock
static int ssh_getsock(struct connectdata *conn, curl_socket_t *sock, /* points to numsocks number of sockets */ int numsocks) { #ifndef HAVE_LIBSSH2_SESSION_BLOCK_DIRECTION (void)conn; (void)sock; (void)numsocks; /* if we don't know any direction we can just play along as we used to and not provide any sensible info */ return GETSOCK_BLANK; #else /* if we know the direction we can use the generic *_getsock() function even for the protocol_connect and doing states */ return ssh_perform_getsock(conn, sock, numsocks); #endif }
/* Generic function called by the multi interface to figure out what socket(s) to wait for and for what actions during the DOING and PROTOCONNECT states*/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2575-L2592
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_block2waitfor
static void ssh_block2waitfor(struct connectdata *conn, bool block) { struct ssh_conn *sshc = &conn->proto.sshc; int dir; if(!block) conn->waitfor = 0; else if((dir = libssh2_session_block_directions(sshc->ssh_session))) { /* translate the libssh2 define bits into our own bit defines */ conn->waitfor = ((dir&LIBSSH2_SESSION_BLOCK_INBOUND)?KEEP_RECV:0) | ((dir&LIBSSH2_SESSION_BLOCK_OUTBOUND)?KEEP_SEND:0); } else /* It didn't block or libssh2 didn't reveal in which direction, put back the original set */ conn->waitfor = sshc->orig_waitfor; }
/* * When one of the libssh2 functions has returned LIBSSH2_ERROR_EAGAIN this * function is used to figure out in what direction and stores this info so * that the multi interface can take advantage of it. Make sure to call this * function in all cases so that when it _doesn't_ return EAGAIN we can * restore the default wait bits. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2602-L2617
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_multi_statemach
static CURLcode ssh_multi_statemach(struct connectdata *conn, bool *done) { struct ssh_conn *sshc = &conn->proto.sshc; CURLcode result = CURLE_OK; bool block; /* we store the status and use that to provide a ssh_getsock() implementation */ result = ssh_statemach_act(conn, &block); *done = (sshc->state == SSH_STOP) ? TRUE : FALSE; ssh_block2waitfor(conn, block); 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/ssh.c#L2624-L2636
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_init
static CURLcode ssh_init(struct connectdata *conn) { struct SessionHandle *data = conn->data; struct SSHPROTO *ssh; struct ssh_conn *sshc = &conn->proto.sshc; sshc->actualcode = CURLE_OK; /* reset error code */ sshc->secondCreateDirs =0; /* reset the create dir attempt state variable */ if(data->state.proto.ssh) return CURLE_OK; ssh = calloc(1, sizeof(struct SSHPROTO)); if(!ssh) return CURLE_OUT_OF_MEMORY; data->state.proto.ssh = ssh; return CURLE_OK; }
/* * SSH setup and connection */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2692-L2712
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_connect
static CURLcode ssh_connect(struct connectdata *conn, bool *done) { #ifdef CURL_LIBSSH2_DEBUG curl_socket_t sock; #endif struct ssh_conn *ssh; CURLcode result; struct SessionHandle *data = conn->data; /* We default to persistent connections. We set this already in this connect function to make the re-use checks properly be able to check this bit. */ conn->bits.close = FALSE; /* If there already is a protocol-specific struct allocated for this sessionhandle, deal with it */ Curl_reset_reqproto(conn); result = ssh_init(conn); if(result) return result; if(conn->handler->protocol & CURLPROTO_SCP) { conn->recv[FIRSTSOCKET] = scp_recv; conn->send[FIRSTSOCKET] = scp_send; } else { conn->recv[FIRSTSOCKET] = sftp_recv; conn->send[FIRSTSOCKET] = sftp_send; } ssh = &conn->proto.sshc; #ifdef CURL_LIBSSH2_DEBUG if(conn->user) { infof(data, "User: %s\n", conn->user); } if(conn->passwd) { infof(data, "Password: %s\n", conn->passwd); } sock = conn->sock[FIRSTSOCKET]; #endif /* CURL_LIBSSH2_DEBUG */ ssh->ssh_session = libssh2_session_init_ex(my_libssh2_malloc, my_libssh2_free, my_libssh2_realloc, conn); if(ssh->ssh_session == NULL) { failf(data, "Failure initialising ssh session"); return CURLE_FAILED_INIT; } #ifdef HAVE_LIBSSH2_KNOWNHOST_API if(data->set.str[STRING_SSH_KNOWNHOSTS]) { int rc; ssh->kh = libssh2_knownhost_init(ssh->ssh_session); if(!ssh->kh) { /* eeek. TODO: free the ssh_session! */ return CURLE_FAILED_INIT; } /* read all known hosts from there */ rc = libssh2_knownhost_readfile(ssh->kh, data->set.str[STRING_SSH_KNOWNHOSTS], LIBSSH2_KNOWNHOST_FILE_OPENSSH); if(rc < 0) infof(data, "Failed to read known hosts from %s\n", data->set.str[STRING_SSH_KNOWNHOSTS]); } #endif /* HAVE_LIBSSH2_KNOWNHOST_API */ #ifdef CURL_LIBSSH2_DEBUG libssh2_trace(ssh->ssh_session, ~0); infof(data, "SSH socket: %d\n", (int)sock); #endif /* CURL_LIBSSH2_DEBUG */ state(conn, SSH_INIT); result = ssh_multi_statemach(conn, done); return result; }
/* * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to * do protocol-specific actions at connect-time. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2721-L2799
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
scp_perform
static CURLcode scp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SCP_TRANS_INIT); /* run the state-machine */ result = ssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; }
/* *********************************************************************** * * scp_perform() * * This is the actual DO function for SCP. Get a file according to * the options previously setup. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2810-L2834
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
scp_doing
static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = ssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; }
/* called from multi.c while DOing */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2837-L2847
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_do
static CURLcode ssh_do(struct connectdata *conn, bool *done) { CURLcode res; bool connected = 0; struct SessionHandle *data = conn->data; *done = FALSE; /* default to false */ /* 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 SSHPROTO' to play with. For new connections, the struct SSHPROTO is allocated and setup in the ssh_connect() function. */ Curl_reset_reqproto(conn); res = ssh_init(conn); if(res) return res; 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); if(conn->handler->protocol & CURLPROTO_SCP) res = scp_perform(conn, &connected, done); else res = sftp_perform(conn, &connected, done); return res; }
/* * The DO function is generic for both protocols. There was previously two * separate ones but this way means less duplicated code. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2854-L2887
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
scp_disconnect
static CURLcode scp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; struct ssh_conn *ssh = &conn->proto.sshc; (void) dead_connection; Curl_safefree(conn->data->state.proto.ssh); if(ssh->ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SESSION_DISCONNECT); result = ssh_easy_statemach(conn, FALSE); } return result; }
/* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2892-L2909
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssh_done
static CURLcode ssh_done(struct connectdata *conn, CURLcode status) { CURLcode result = CURLE_OK; struct SSHPROTO *sftp_scp = conn->data->state.proto.ssh; if(status == CURLE_OK) { /* run the state-machine TODO: when the multi interface is used, this _really_ should be using the ssh_multi_statemach function but we have no general support for non-blocking DONE operations, not in the multi state machine and with Curl_done() invokes on several places in the code! */ result = ssh_easy_statemach(conn, FALSE); } else result = status; if(sftp_scp) Curl_safefree(sftp_scp->path); if(Curl_pgrsDone(conn)) return CURLE_ABORTED_BY_CALLBACK; conn->data->req.keepon = 0; /* clear all bits */ return result; }
/* generic done function for both SCP and SFTP called from their specific done functions */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2913-L2938
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
scp_send
static ssize_t scp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { ssize_t nwrite; (void)sockindex; /* we only support SCP on the fixed known primary socket */ /* libssh2_channel_write() returns int! */ nwrite = (ssize_t) libssh2_channel_write(conn->proto.sshc.ssh_channel, mem, len); ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nwrite == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nwrite = 0; } else if(nwrite < LIBSSH2_ERROR_NONE) { *err = libssh2_session_error_to_CURLE((int)nwrite); nwrite = -1; } return nwrite; }
/* return number of received (decrypted) bytes */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2954-L2976
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
scp_recv
static ssize_t scp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void)sockindex; /* we only support SCP on the fixed known primary socket */ /* libssh2_channel_read() returns int */ nread = (ssize_t) libssh2_channel_read(conn->proto.sshc.ssh_channel, mem, len); ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nread == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nread = -1; } return nread; }
/* * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return * a regular CURLcode value. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L2982-L2999
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_perform
static CURLcode sftp_perform(struct connectdata *conn, bool *connected, bool *dophase_done) { CURLcode result = CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ state(conn, SSH_SFTP_QUOTE_INIT); /* run the state-machine */ result = ssh_multi_statemach(conn, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; }
/* * =============== SFTP =============== */ /* *********************************************************************** * * sftp_perform() * * This is the actual DO function for SFTP. 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/ssh.c#L3014-L3038
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_doing
static CURLcode sftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = ssh_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; }
/* called from multi.c while DOing */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L3041-L3051
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_disconnect
static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection) { CURLcode result = CURLE_OK; (void) dead_connection; DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n")); Curl_safefree(conn->data->state.proto.ssh); if(conn->proto.sshc.ssh_session) { /* only if there's a session still around to use! */ state(conn, SSH_SFTP_SHUTDOWN); result = ssh_easy_statemach(conn, FALSE); } DEBUGF(infof(conn->data, "SSH DISCONNECT is done\n")); return result; }
/* BLOCKING, but the function is using the state machine so the only reason this is still blocking is that the multi interface code has no support for disconnecting operations that takes a while */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L3056-L3075
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_send
static ssize_t sftp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *err) { ssize_t nwrite; /* libssh2_sftp_write() used to return size_t in 0.14 but is changed to ssize_t in 0.15. These days we don't support libssh2 0.15*/ (void)sockindex; nwrite = libssh2_sftp_write(conn->proto.sshc.sftp_handle, mem, len); ssh_block2waitfor(conn, (nwrite == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nwrite == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nwrite = 0; } else if(nwrite < LIBSSH2_ERROR_NONE) { *err = libssh2_session_error_to_CURLE((int)nwrite); nwrite = -1; } return nwrite; }
/* return number of sent bytes */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L3097-L3119
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
sftp_recv
static ssize_t sftp_recv(struct connectdata *conn, int sockindex, char *mem, size_t len, CURLcode *err) { ssize_t nread; (void)sockindex; nread = libssh2_sftp_read(conn->proto.sshc.sftp_handle, mem, len); ssh_block2waitfor(conn, (nread == LIBSSH2_ERROR_EAGAIN)?TRUE:FALSE); if(nread == LIBSSH2_ERROR_EAGAIN) { *err = CURLE_AGAIN; nread = -1; } return nread; }
/* * Return number of received (decrypted) bytes */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L3124-L3139
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
get_pathname
static CURLcode get_pathname(const char **cpp, char **path) { const char *cp = *cpp, *end; char quot; unsigned int i, j; static const char WHITESPACE[] = " \t\r\n"; cp += strspn(cp, WHITESPACE); if(!*cp) { *cpp = cp; *path = NULL; return CURLE_QUOTE_ERROR; } *path = malloc(strlen(cp) + 1); if(*path == NULL) return CURLE_OUT_OF_MEMORY; /* Check for quoted filenames */ if(*cp == '\"' || *cp == '\'') { quot = *cp++; /* Search for terminating quote, unescape some chars */ for(i = j = 0; i <= strlen(cp); i++) { if(cp[i] == quot) { /* Found quote */ i++; (*path)[j] = '\0'; break; } if(cp[i] == '\0') { /* End of string */ /*error("Unterminated quote");*/ goto fail; } if(cp[i] == '\\') { /* Escaped characters */ i++; if(cp[i] != '\'' && cp[i] != '\"' && cp[i] != '\\') { /*error("Bad escaped character '\\%c'", cp[i]);*/ goto fail; } } (*path)[j++] = cp[i]; } if(j == 0) { /*error("Empty quotes");*/ goto fail; } *cpp = cp + i + strspn(cp + i, WHITESPACE); } else { /* Read to end of filename */ end = strpbrk(cp, WHITESPACE); if(end == NULL) end = strchr(cp, '\0'); *cpp = end + strspn(end, WHITESPACE); memcpy(*path, cp, end - cp); (*path)[end - cp] = '\0'; } return CURLE_OK; fail: Curl_safefree(*path); return CURLE_QUOTE_ERROR; }
/* The get_pathname() function is being borrowed from OpenSSH sftp.c version 4.6p1. */ /* * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssh.c#L3158-L3225
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
x509_name_oneline
static int x509_name_oneline(X509_NAME *a, char *buf, size_t size) { #if 0 return X509_NAME_oneline(a, buf, size); #else BIO *bio_out = BIO_new(BIO_s_mem()); BUF_MEM *biomem; int rc; if(!bio_out) return 1; /* alloc failed! */ rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC); BIO_get_mem_ptr(bio_out, &biomem); if((size_t)biomem->length < size) size = biomem->length; else size--; /* don't overwrite the buffer end */ memcpy(buf, biomem->data, size); buf[size]=0; BIO_free(bio_out); return !rc; #endif }
/* returns non-zero on failure */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L623-L650
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_init
int Curl_ossl_init(void) { #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES ENGINE_load_builtin_engines(); #endif /* Lets get nice error messages */ SSL_load_error_strings(); /* Init the global ciphers and digests */ if(!SSLeay_add_ssl_algorithms()) return 0; OpenSSL_add_all_algorithms(); return 1; }
/** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L688-L704
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_cleanup
void Curl_ossl_cleanup(void) { /* Free ciphers and digests lists */ EVP_cleanup(); #ifdef HAVE_ENGINE_CLEANUP /* Free engine list */ ENGINE_cleanup(); #endif #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA /* Free OpenSSL ex_data table */ CRYPTO_cleanup_all_ex_data(); #endif /* Free OpenSSL error strings */ ERR_free_strings(); /* Free thread local error state, destroying hash upon zero refcount */ #ifdef HAVE_ERR_REMOVE_THREAD_STATE ERR_remove_thread_state(NULL); #else ERR_remove_state(0); #endif }
/* Global cleanup */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L711-L735
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_check_cxn
int Curl_ossl_check_cxn(struct connectdata *conn) { int rc; char buf; rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1); if(rc > 0) return 1; /* connection still in place */ if(rc == 0) return 0; /* connection has been closed */ return -1; /* connection status unknown */ }
/* * This function uses SSL_peek 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/ssluse.c#L745-L758
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_set_engine
CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine) { #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H) ENGINE *e; #if OPENSSL_VERSION_NUMBER >= 0x00909000L e = ENGINE_by_id(engine); #else /* avoid memory leak */ for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { const char *e_id = ENGINE_get_id(e); if(!strcmp(engine, e_id)) break; } #endif if(!e) { failf(data, "SSL Engine '%s' not found", engine); return CURLE_SSL_ENGINE_NOTFOUND; } if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } if(!ENGINE_init(e)) { char buf[256]; ENGINE_free(e); failf(data, "Failed to initialise SSL Engine '%s':\n%s", engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf))); return CURLE_SSL_ENGINE_INITFAILED; } data->state.engine = e; return CURLE_OK; #else (void)engine; failf(data, "SSL Engine not supported"); return CURLE_SSL_ENGINE_NOTFOUND; #endif }
/* Selects an OpenSSL crypto engine */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L762-L803
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_set_engine_default
CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data) { #ifdef HAVE_OPENSSL_ENGINE_H if(data->state.engine) { if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { infof(data,"set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine)); } else { failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine)); return CURLE_SSL_ENGINE_SETFAILED; } } #else (void) data; #endif return CURLE_OK; }
/* Sets engine as default for all SSL operations */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L807-L825
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_close
void Curl_ossl_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->handle) { (void)SSL_shutdown(connssl->handle); SSL_set_connect_state(connssl->handle); SSL_free (connssl->handle); connssl->handle = NULL; } if(connssl->ctx) { SSL_CTX_free (connssl->ctx); connssl->ctx = NULL; } }
/* * This function is called when an SSL connection is closed. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L853-L868
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_shutdown
int Curl_ossl_shutdown(struct connectdata *conn, int sockindex) { 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. */ unsigned long sslerror; ssize_t nread; int buffsize; int err; int done = 0; /* 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) (void)SSL_shutdown(connssl->handle); if(connssl->handle) { buffsize = (int)sizeof(buf); while(!done) { int what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT); if(what > 0) { ERR_clear_error(); /* 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].handle, buf, buffsize); err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread); switch(err) { case SSL_ERROR_NONE: /* this is not an error */ case SSL_ERROR_ZERO_RETURN: /* no more data */ /* This is the expected response. There was no data but only the close notify alert */ done = 1; break; case SSL_ERROR_WANT_READ: /* there's data pending, re-invoke SSL_read() */ infof(data, "SSL_ERROR_WANT_READ\n"); break; case SSL_ERROR_WANT_WRITE: /* SSL wants a write. Really odd. Let's bail out. */ infof(data, "SSL_ERROR_WANT_WRITE\n"); done = 1; break; default: /* openssl/ssl.h says "look at error stack/return value/errno" */ sslerror = ERR_get_error(); failf(conn->data, "SSL read: %s, errno %d", ERR_error_string(sslerror, buf), SOCKERRNO); done = 1; break; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); done = 1; } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; done = 1; } } /* while()-loop for the select() */ if(data->set.verbose) { #ifdef HAVE_SSL_GET_SHUTDOWN switch(SSL_get_shutdown(connssl->handle)) { case SSL_SENT_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n"); break; case SSL_RECEIVED_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n"); break; case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|" "SSL_RECEIVED__SHUTDOWN\n"); break; } #endif } 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/ssluse.c#L874-L969
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ossl_close_all
int Curl_ossl_close_all(struct SessionHandle *data) { #ifdef HAVE_OPENSSL_ENGINE_H if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } #else (void)data; #endif return 0; }
/* * This function is called when the 'data' struct is going away. Close * down everything and free all resources! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L981-L993
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
verifyhost
static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) { int matched = -1; /* -1 is no alternative match yet, 1 means match and 0 means mismatch */ int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */ size_t addrlen = 0; struct SessionHandle *data = conn->data; STACK_OF(GENERAL_NAME) *altnames; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif CURLcode res = CURLE_OK; #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, conn->host.name, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in6_addr); } else #endif if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in_addr); } /* get a "list" of alternative names */ altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL); if(altnames) { int numalts; int i; /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */ numalts = sk_GENERAL_NAME_num(altnames); /* loop through all alternatives while none has matched */ for(i=0; (i<numalts) && (matched != 1); i++) { /* get a handle to alternative name number i */ const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); /* only check alternatives of the same type the target is */ if(check->type == target) { /* get data and length */ const char *altptr = (char *)ASN1_STRING_data(check->d.ia5); size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5); switch(target) { case GEN_DNS: /* name/pattern comparison */ /* The OpenSSL man page explicitly says: "In general it cannot be assumed that the data returned by ASN1_STRING_data() is null terminated or does not contain embedded nulls." But also that "The actual format of the data will depend on the actual string type itself: for example for and IA5String the data will be ASCII" Gisle researched the OpenSSL sources: "I checked the 0.9.6 and 0.9.8 sources before my patch and it always 0-terminates an IA5String." */ if((altlen == strlen(altptr)) && /* if this isn't true, there was an embedded zero in the name string and we cannot match it. */ Curl_cert_hostcheck(altptr, conn->host.name)) matched = 1; else matched = 0; break; case GEN_IPADD: /* IP address comparison */ /* compare alternative IP address if the data chunk is the same size our server IP address is */ if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) matched = 1; else matched = 0; break; } } } GENERAL_NAMES_free(altnames); } if(matched == 1) /* an alternative name matched the server hostname */ infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname); else if(matched == 0) { /* an alternative name field existed, but didn't match and then we MUST fail */ infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname); res = CURLE_PEER_FAILED_VERIFICATION; } else { /* we have to look to the last occurrence of a commonName in the distinguished one to get the most significant one. */ int j,i=-1 ; /* The following is done because of a bug in 0.9.6b */ unsigned char *nulstr = (unsigned char *)""; unsigned char *peer_CN = nulstr; X509_NAME *name = X509_get_subject_name(server_cert) ; if(name) while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0) i=j; /* we have the name entry and we will now convert this to a string that we can use for comparison. Doing this we support BMPstring, UTF8 etc. */ if(i>=0) { ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i)); /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input is already UTF-8 encoded. We check for this case and copy the raw string manually to avoid the problem. This code can be made conditional in the future when OpenSSL has been fixed. Work-around brought by Alexis S. L. Carvalho. */ if(tmp) { if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { j = ASN1_STRING_length(tmp); if(j >= 0) { peer_CN = OPENSSL_malloc(j+1); if(peer_CN) { memcpy(peer_CN, ASN1_STRING_data(tmp), j); peer_CN[j] = '\0'; } } } else /* not a UTF8 name */ j = ASN1_STRING_to_UTF8(&peer_CN, tmp); if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) { /* there was a terminating zero before the end of string, this cannot match and we return failure! */ failf(data, "SSL: illegal cert name field"); res = CURLE_PEER_FAILED_VERIFICATION; } } } if(peer_CN == nulstr) peer_CN = NULL; else { /* convert peer_CN from UTF8 */ CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN)); /* Curl_convert_from_utf8 calls failf if unsuccessful */ if(rc) { OPENSSL_free(peer_CN); return rc; } } if(res) /* error already detected, pass through */ ; else if(!peer_CN) { failf(data, "SSL: unable to obtain common name from peer certificate"); res = CURLE_PEER_FAILED_VERIFICATION; } else if(!Curl_cert_hostcheck((const char *)peer_CN, conn->host.name)) { failf(data, "SSL: certificate subject name '%s' does not match " "target host name '%s'", peer_CN, conn->host.dispname); res = CURLE_PEER_FAILED_VERIFICATION; } else { infof(data, "\t common name: %s (matched)\n", peer_CN); } if(peer_CN) OPENSSL_free(peer_CN); } return res; }
/* ====================================================== */ /* Quote from RFC2818 section 3.1 "Server Identity" If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead. Matching is performed using the matching rules specified by [RFC2459]. If more than one identity of a given type is present in the certificate (e.g., more than one dNSName name, a match in any one of the set is considered acceptable.) Names may contain the wildcard character * which is considered to match any single domain name component or component fragment. E.g., *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com but not bar.com. In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L1062-L1239
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
ssl_tls_trace
static void ssl_tls_trace(int direction, int ssl_ver, int content_type, const void *buf, size_t len, const SSL *ssl, struct connectdata *conn) { struct SessionHandle *data; const char *msg_name, *tls_rt_name; char ssl_buf[1024]; int ver, msg_type, txt_len; if(!conn || !conn->data || !conn->data->set.fdebug || (direction != 0 && direction != 1)) return; data = conn->data; ssl_ver >>= 8; ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' : ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?'); /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL * always pass-up content-type as 0. But the interesting message-type * is at 'buf[0]'. */ if(ssl_ver == SSL3_VERSION_MAJOR && content_type != 0) tls_rt_name = tls_rt_type(content_type); else tls_rt_name = ""; msg_type = *(char*)buf; msg_name = ssl_msg_type(ssl_ver, msg_type); txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n", ver, tls_rt_name, msg_name, msg_type); Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL); Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT : CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL); (void) ssl; }
/* * Our callback from the SSL/TLS layers. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L1311-L1348
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
push_certinfo
static CURLcode push_certinfo(struct SessionHandle *data, int certnum, const char *label, const char *value) { size_t valuelen = strlen(value); return push_certinfo_len(data, certnum, label, value, valuelen); }
/* this is a convenience function for push_certinfo_len that takes a zero terminated value */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L1853-L1861
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
servercert
static CURLcode servercert(struct connectdata *conn, struct ssl_connect_data *connssl, bool strict) { CURLcode retcode = CURLE_OK; int rc; long lerr; ASN1_TIME *certdate; struct SessionHandle *data = conn->data; X509 *issuer; FILE *fp; char *buffer = data->state.buffer; if(data->set.ssl.certinfo) /* we've been asked to gather certificate info! */ (void)get_cert_chain(conn, connssl); data->set.ssl.certverifyresult = !X509_V_OK; connssl->server_cert = SSL_get_peer_certificate(connssl->handle); if(!connssl->server_cert) { if(strict) failf(data, "SSL: couldn't get peer certificate!"); return CURLE_PEER_FAILED_VERIFICATION; } infof (data, "Server certificate:\n"); rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert), buffer, BUFSIZE); if(rc) { if(strict) failf(data, "SSL: couldn't get X509-subject!"); X509_free(connssl->server_cert); connssl->server_cert = NULL; return CURLE_SSL_CONNECT_ERROR; } infof(data, "\t subject: %s\n", buffer); certdate = X509_get_notBefore(connssl->server_cert); asn1_output(certdate, buffer, BUFSIZE); infof(data, "\t start date: %s\n", buffer); certdate = X509_get_notAfter(connssl->server_cert); asn1_output(certdate, buffer, BUFSIZE); infof(data, "\t expire date: %s\n", buffer); if(data->set.ssl.verifyhost) { retcode = verifyhost(conn, connssl->server_cert); if(retcode) { X509_free(connssl->server_cert); connssl->server_cert = NULL; return retcode; } } rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert), buffer, BUFSIZE); if(rc) { if(strict) failf(data, "SSL: couldn't get X509-issuer name!"); retcode = CURLE_SSL_CONNECT_ERROR; } else { infof(data, "\t issuer: %s\n", buffer); /* We could do all sorts of certificate verification stuff here before deallocating the certificate. */ /* e.g. match issuer name with provided issuer certificate */ if(data->set.str[STRING_SSL_ISSUERCERT]) { fp=fopen(data->set.str[STRING_SSL_ISSUERCERT],"r"); if(!fp) { if(strict) failf(data, "SSL: Unable to open issuer cert (%s)", data->set.str[STRING_SSL_ISSUERCERT]); X509_free(connssl->server_cert); connssl->server_cert = NULL; return CURLE_SSL_ISSUER_ERROR; } issuer = PEM_read_X509(fp,NULL,ZERO_NULL,NULL); if(!issuer) { if(strict) failf(data, "SSL: Unable to read issuer cert (%s)", data->set.str[STRING_SSL_ISSUERCERT]); X509_free(connssl->server_cert); X509_free(issuer); fclose(fp); return CURLE_SSL_ISSUER_ERROR; } fclose(fp); if(X509_check_issued(issuer,connssl->server_cert) != X509_V_OK) { if(strict) failf(data, "SSL: Certificate issuer check failed (%s)", data->set.str[STRING_SSL_ISSUERCERT]); X509_free(connssl->server_cert); X509_free(issuer); connssl->server_cert = NULL; return CURLE_SSL_ISSUER_ERROR; } infof(data, "\t SSL certificate issuer check ok (%s)\n", data->set.str[STRING_SSL_ISSUERCERT]); X509_free(issuer); } lerr = data->set.ssl.certverifyresult= SSL_get_verify_result(connssl->handle); if(data->set.ssl.certverifyresult != X509_V_OK) { if(data->set.ssl.verifypeer) { /* We probably never reach this, because SSL_connect() will fail and we return earlier if verifypeer is set? */ if(strict) failf(data, "SSL certificate verify result: %s (%ld)", X509_verify_cert_error_string(lerr), lerr); retcode = CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\t SSL certificate verify result: %s (%ld)," " continuing anyway.\n", X509_verify_cert_error_string(lerr), lerr); } else infof(data, "\t SSL certificate verify ok.\n"); } X509_free(connssl->server_cert); connssl->server_cert = NULL; connssl->connecting_state = ssl_connect_done; return retcode; }
/* * Get the server cert, verify it and show it etc, only call failf() if the * 'strict' argument is TRUE as otherwise all this is for informational * purposes only! * * We check certificates to authenticate the server; otherwise we risk * man-in-the-middle attack. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/ssluse.c#L2194-L2323
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_set_timeouts
static CURLcode tftp_set_timeouts(tftp_state_data_t *state) { time_t maxtime, timeout; long timeout_ms; bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE; time(&state->start_time); /* Compute drop-dead time */ timeout_ms = Curl_timeleft(state->conn->data, NULL, start); if(timeout_ms < 0) { /* time-out, bail out, go home */ failf(state->conn->data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } if(start) { maxtime = (time_t)(timeout_ms + 500) / 1000; state->max_time = state->start_time+maxtime; /* Set per-block timeout to total */ timeout = maxtime ; /* Average restart after 5 seconds */ state->retry_max = (int)timeout/5; if(state->retry_max < 1) /* avoid division by zero below */ state->retry_max = 1; /* Compute the re-start interval to suit the timeout */ state->retry_time = (int)timeout/state->retry_max; if(state->retry_time<1) state->retry_time=1; } else { if(timeout_ms > 0) maxtime = (time_t)(timeout_ms + 500) / 1000; else maxtime = 3600; state->max_time = state->start_time+maxtime; /* Set per-block timeout to total */ timeout = maxtime; /* Average reposting an ACK after 5 seconds */ state->retry_max = (int)timeout/5; } /* But bound the total number */ if(state->retry_max<3) state->retry_max=3; if(state->retry_max>50) state->retry_max=50; /* Compute the re-ACK interval to suit the timeout */ state->retry_time = (int)(timeout/state->retry_max); if(state->retry_time<1) state->retry_time=1; infof(state->conn->data, "set timeouts for state %d; Total %ld, retry %d maxtry %d\n", (int)state->state, (long)(state->max_time-state->start_time), state->retry_time, state->retry_max); /* init RX time */ time(&state->rx_time); return CURLE_OK; }
/********************************************************** * * tftp_set_timeouts - * * Set timeouts based on state machine state. * Use user provided connect timeouts until DATA or ACK * packet is received, then use user-provided transfer timeouts * * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L200-L273
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
setpacketevent
static void setpacketevent(tftp_packet_t *packet, unsigned short num) { packet->data[0] = (unsigned char)(num >> 8); packet->data[1] = (unsigned char)(num & 0xff); }
/********************************************************** * * tftp_set_send_first * * Event handler for the START state * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L283-L287
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_rx
static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) { ssize_t sbytes; int rblock; struct SessionHandle *data = state->conn->data; switch(event) { case TFTP_EVENT_DATA: /* Is this the block we expect? */ rblock = getrpacketblock(&state->rpacket); if(NEXT_BLOCKNUM(state->block) == rblock) { /* This is the expected block. Reset counters and ACK it. */ state->retries = 0; } else if(state->block == rblock) { /* This is the last recently received block again. Log it and ACK it again. */ infof(data, "Received last DATA packet block %d again.\n", rblock); } else { /* totally unexpected, just log it */ infof(data, "Received unexpected DATA packet block %d, expecting block %d\n", rblock, NEXT_BLOCKNUM(state->block)); break; } /* ACK this block. */ state->block = (unsigned short)rblock; setpacketevent(&state->spacket, TFTP_EVENT_ACK); setpacketblock(&state->spacket, state->block); sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes < 0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); return CURLE_SEND_ERROR; } /* Check if completed (That is, a less than full packet is received) */ if(state->rbytes < (ssize_t)state->blksize+4) { state->state = TFTP_STATE_FIN; } else { state->state = TFTP_STATE_RX; } time(&state->rx_time); break; case TFTP_EVENT_OACK: /* ACK option acknowledgement so we can move on to data */ state->block = 0; state->retries = 0; setpacketevent(&state->spacket, TFTP_EVENT_ACK); setpacketblock(&state->spacket, state->block); sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes < 0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); return CURLE_SEND_ERROR; } /* we're ready to RX data */ state->state = TFTP_STATE_RX; time(&state->rx_time); break; case TFTP_EVENT_TIMEOUT: /* Increment the retry count and fail if over the limit */ state->retries++; infof(data, "Timeout waiting for block %d ACK. Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries); if(state->retries > state->retry_max) { state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; } else { /* Resend the previous ACK */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); if(sbytes<0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); return CURLE_SEND_ERROR; } } break; case TFTP_EVENT_ERROR: setpacketevent(&state->spacket, TFTP_EVENT_ERROR); setpacketblock(&state->spacket, state->block); (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* don't bother with the return code, but if the socket is still up we * should be a good TFTP client and let the server know we're done */ state->state = TFTP_STATE_FIN; break; default: failf(data, "%s", "tftp_rx: internal error"); return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for this */ } return CURLE_OK; }
/********************************************************** * * tftp_rx * * Event handler for the RX state * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L577-L689
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_tx
static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) { struct SessionHandle *data = state->conn->data; ssize_t sbytes; int rblock; CURLcode res = CURLE_OK; struct SingleRequest *k = &data->req; switch(event) { case TFTP_EVENT_ACK: case TFTP_EVENT_OACK: if(event == TFTP_EVENT_ACK) { /* Ack the packet */ rblock = getrpacketblock(&state->rpacket); if(rblock != state->block && /* There's a bug in tftpd-hpa that causes it to send us an ack for * 65535 when the block number wraps to 0. So when we're expecting * 0, also accept 65535. See * http://syslinux.zytor.com/archives/2010-September/015253.html * */ !(state->block == 0 && rblock == 65535)) { /* This isn't the expected block. Log it and up the retry counter */ infof(data, "Received ACK for block %d, expecting %d\n", rblock, state->block); state->retries++; /* Bail out if over the maximum */ if(state->retries>state->retry_max) { failf(data, "tftp_tx: giving up waiting for block %d ack", state->block); res = CURLE_SEND_ERROR; } else { /* Re-send the data packet */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4+state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); res = CURLE_SEND_ERROR; } } return res; } /* This is the expected packet. Reset the counters and send the next block */ time(&state->rx_time); state->block++; } else state->block = 1; /* first data block is 1 when using OACK */ state->retries = 0; setpacketevent(&state->spacket, TFTP_EVENT_DATA); setpacketblock(&state->spacket, state->block); if(state->block > 1 && state->sbytes < (int)state->blksize) { state->state = TFTP_STATE_FIN; return CURLE_OK; } res = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes); if(res) return res; sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4+state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); return CURLE_SEND_ERROR; } /* Update the progress meter */ k->writebytecount += state->sbytes; Curl_pgrsSetUploadCounter(data, k->writebytecount); break; case TFTP_EVENT_TIMEOUT: /* Increment the retry counter and log the timeout */ state->retries++; infof(data, "Timeout waiting for block %d ACK. " " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries); /* Decide if we've had enough */ if(state->retries > state->retry_max) { state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; } else { /* Re-send the data packet */ sbytes = sendto(state->sockfd, (void *)state->spacket.data, 4+state->sbytes, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* Check all sbytes were sent */ if(sbytes<0) { failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO)); return CURLE_SEND_ERROR; } /* since this was a re-send, we remain at the still byte position */ Curl_pgrsSetUploadCounter(data, k->writebytecount); } break; case TFTP_EVENT_ERROR: state->state = TFTP_STATE_FIN; setpacketevent(&state->spacket, TFTP_EVENT_ERROR); setpacketblock(&state->spacket, state->block); (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG, (struct sockaddr *)&state->remote_addr, state->remote_addrlen); /* don't bother with the return code, but if the socket is still up we * should be a good TFTP client and let the server know we're done */ state->state = TFTP_STATE_FIN; break; default: failf(data, "tftp_tx: internal error, event: %i", (int)(event)); break; } return res; }
/********************************************************** * * tftp_tx * * Event handler for the TX state * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L698-L821
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_translate_code
static CURLcode tftp_translate_code(tftp_error_t error) { CURLcode code = CURLE_OK; if(error != TFTP_ERR_NONE) { switch(error) { case TFTP_ERR_NOTFOUND: code = CURLE_TFTP_NOTFOUND; break; case TFTP_ERR_PERM: code = CURLE_TFTP_PERM; break; case TFTP_ERR_DISKFULL: code = CURLE_REMOTE_DISK_FULL; break; case TFTP_ERR_UNDEF: case TFTP_ERR_ILLEGAL: code = CURLE_TFTP_ILLEGAL; break; case TFTP_ERR_UNKNOWNID: code = CURLE_TFTP_UNKNOWNID; break; case TFTP_ERR_EXISTS: code = CURLE_REMOTE_FILE_EXISTS; break; case TFTP_ERR_NOSUCHUSER: code = CURLE_TFTP_NOSUCHUSER; break; case TFTP_ERR_TIMEOUT: code = CURLE_OPERATION_TIMEDOUT; break; case TFTP_ERR_NORESPONSE: code = CURLE_COULDNT_CONNECT; break; default: code= CURLE_ABORTED_BY_CALLBACK; break; } } else { code = CURLE_OK; } return(code); }
/********************************************************** * * tftp_translate_code * * Translate internal error codes to CURL error codes * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L830-L874
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_state_machine
static CURLcode tftp_state_machine(tftp_state_data_t *state, tftp_event_t event) { CURLcode res = CURLE_OK; struct SessionHandle *data = state->conn->data; switch(state->state) { case TFTP_STATE_START: DEBUGF(infof(data, "TFTP_STATE_START\n")); res = tftp_send_first(state, event); break; case TFTP_STATE_RX: DEBUGF(infof(data, "TFTP_STATE_RX\n")); res = tftp_rx(state, event); break; case TFTP_STATE_TX: DEBUGF(infof(data, "TFTP_STATE_TX\n")); res = tftp_tx(state, event); break; case TFTP_STATE_FIN: infof(data, "%s\n", "TFTP finished"); break; default: DEBUGF(infof(data, "STATE: %d\n", state->state)); failf(data, "%s", "Internal state machine error"); res = CURLE_TFTP_ILLEGAL; break; } return res; }
/********************************************************** * * tftp_state_machine * * The tftp state machine event dispatcher * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L883-L911
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_disconnect
static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection) { tftp_state_data_t *state = conn->proto.tftpc; (void) dead_connection; /* done, free dynamically allocated pkt buffers */ if(state) { Curl_safefree(state->rpacket.data); Curl_safefree(state->spacket.data); free(state); } return CURLE_OK; }
/********************************************************** * * tftp_disconnect * * The disconnect callback * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L920-L933
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_connect
static CURLcode tftp_connect(struct connectdata *conn, bool *done) { CURLcode code; tftp_state_data_t *state; int blksize, rc; blksize = TFTP_BLKSIZE_DEFAULT; /* If there already is a protocol-specific struct allocated for this sessionhandle, deal with it */ Curl_reset_reqproto(conn); state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t)); if(!state) return CURLE_OUT_OF_MEMORY; /* alloc pkt buffers based on specified blksize */ if(conn->data->set.tftp_blksize) { blksize = (int)conn->data->set.tftp_blksize; if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN ) return CURLE_TFTP_ILLEGAL; } if(!state->rpacket.data) { state->rpacket.data = calloc(1, blksize + 2 + 2); if(!state->rpacket.data) return CURLE_OUT_OF_MEMORY; } if(!state->spacket.data) { state->spacket.data = calloc(1, blksize + 2 + 2); if(!state->spacket.data) return CURLE_OUT_OF_MEMORY; } conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially because there's none or very little gain for UDP */ state->conn = conn; state->sockfd = state->conn->sock[FIRSTSOCKET]; state->state = TFTP_STATE_START; state->error = TFTP_ERR_NONE; state->blksize = TFTP_BLKSIZE_DEFAULT; state->requested_blksize = blksize; ((struct sockaddr *)&state->local_addr)->sa_family = (unsigned short)(conn->ip_addr->ai_family); tftp_set_timeouts(state); if(!conn->bits.bound) { /* If not already bound, bind to any interface, random UDP port. If it is * reused or a custom local port was desired, this has already been done! * * We once used the size of the local_addr struct as the third argument * for bind() to better work with IPv6 or whatever size the struct could * have, but we learned that at least Tru64, AIX and IRIX *requires* the * size of that argument to match the exact size of a 'sockaddr_in' struct * when running IPv4-only. * * Therefore we use the size from the address we connected to, which we * assume uses the same IP version and thus hopefully this works for both * IPv4 and IPv6... */ rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr, conn->ip_addr->ai_addrlen); if(rc) { failf(conn->data, "bind() failed; %s", Curl_strerror(conn, SOCKERRNO)); return CURLE_COULDNT_CONNECT; } conn->bits.bound = TRUE; } Curl_pgrsStartNow(conn->data); *done = TRUE; code = CURLE_OK; return(code); }
/********************************************************** * * tftp_connect * * The connect callback * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L942-L1024
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_done
static CURLcode tftp_done(struct connectdata *conn, CURLcode status, bool premature) { CURLcode code = CURLE_OK; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; (void)status; /* unused */ (void)premature; /* not used */ if(Curl_pgrsDone(conn)) return CURLE_ABORTED_BY_CALLBACK; /* If we have encountered an error */ code = tftp_translate_code(state->error); return code; }
/********************************************************** * * tftp_done * * The done callback * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1033-L1049
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_getsock
static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(!numsocks) return GETSOCK_BLANK; socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0); }
/********************************************************** * * tftp_getsock * * The getsock callback * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1058-L1067
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_receive_packet
static CURLcode tftp_receive_packet(struct connectdata *conn) { struct Curl_sockaddr_storage fromaddr; curl_socklen_t fromlen; CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; struct SingleRequest *k = &data->req; /* Receive the packet */ fromlen = sizeof(fromaddr); state->rbytes = (int)recvfrom(state->sockfd, (void *)state->rpacket.data, state->blksize+4, 0, (struct sockaddr *)&fromaddr, &fromlen); if(state->remote_addrlen==0) { memcpy(&state->remote_addr, &fromaddr, fromlen); state->remote_addrlen = fromlen; } /* Sanity check packet length */ if(state->rbytes < 4) { failf(data, "Received too short packet"); /* Not a timeout, but how best to handle it? */ state->event = TFTP_EVENT_TIMEOUT; } else { /* The event is given by the TFTP packet time */ state->event = (tftp_event_t)getrpacketevent(&state->rpacket); switch(state->event) { case TFTP_EVENT_DATA: /* Don't pass to the client empty or retransmitted packets */ if(state->rbytes > 4 && (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) { result = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)state->rpacket.data+4, state->rbytes-4); if(result) { tftp_state_machine(state, TFTP_EVENT_ERROR); return result; } k->bytecount += state->rbytes-4; Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount); } break; case TFTP_EVENT_ERROR: state->error = (tftp_error_t)getrpacketblock(&state->rpacket); infof(data, "%s\n", (const char *)state->rpacket.data+4); break; case TFTP_EVENT_ACK: break; case TFTP_EVENT_OACK: result = tftp_parse_option_ack(state, (const char *)state->rpacket.data+2, state->rbytes-2); if(result) return result; break; case TFTP_EVENT_RRQ: case TFTP_EVENT_WRQ: default: failf(data, "%s", "Internal error: Unexpected packet"); break; } /* Update the progress meter */ if(Curl_pgrsUpdate(conn)) { tftp_state_machine(state, TFTP_EVENT_ERROR); return CURLE_ABORTED_BY_CALLBACK; } } return result; }
/********************************************************** * * tftp_receive_packet * * Called once select fires and data is ready on the socket * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1076-L1151
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_state_timeout
static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event) { time_t current; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; if(event) *event = TFTP_EVENT_NONE; time(&current); if(current > state->max_time) { DEBUGF(infof(conn->data, "timeout: %ld > %ld\n", (long)current, (long)state->max_time)); state->error = TFTP_ERR_TIMEOUT; state->state = TFTP_STATE_FIN; return 0; } else if(current > state->rx_time+state->retry_time) { if(event) *event = TFTP_EVENT_TIMEOUT; time(&state->rx_time); /* update even though we received nothing */ } /* there's a typecast below here since 'time_t' may in fact be larger than 'long', but we estimate that a 'long' will still be able to hold number of seconds even if "only" 32 bit */ return (long)(state->max_time - current); }
/********************************************************** * * tftp_state_timeout * * Check if timeouts have been reached * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1160-L1186
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_multi_statemach
static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done) { int rc; tftp_event_t event; CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; long timeout_ms = tftp_state_timeout(conn, &event); *done = FALSE; if(timeout_ms <= 0) { failf(data, "TFTP response timeout"); return CURLE_OPERATION_TIMEDOUT; } else if(event != TFTP_EVENT_NONE) { result = tftp_state_machine(state, event); if(result != CURLE_OK) return(result); *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; if(*done) /* Tell curl we're done */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); } else { /* no timeouts to handle, check our socket */ rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0); if(rc == -1) { /* bail out */ int error = SOCKERRNO; failf(data, "%s", Curl_strerror(conn, error)); state->event = TFTP_EVENT_ERROR; } else if(rc != 0) { result = tftp_receive_packet(conn); if(result != CURLE_OK) return(result); result = tftp_state_machine(state, state->event); if(result != CURLE_OK) return(result); *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE; if(*done) /* Tell curl we're done */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); } /* if rc == 0, then select() timed out */ } return result; }
/********************************************************** * * tftp_multi_statemach * * Handle single RX socket event and return * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1195-L1245
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_doing
static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done) { CURLcode result; result = tftp_multi_statemach(conn, dophase_done); if(*dophase_done) { DEBUGF(infof(conn->data, "DO phase is complete\n")); } return result; }
/********************************************************** * * tftp_doing * * Called from multi.c while DOing * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1254-L1263
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_perform
static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done) { CURLcode result = CURLE_OK; tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc; *dophase_done = FALSE; result = tftp_state_machine(state, TFTP_EVENT_INIT); if(state->state == TFTP_STATE_FIN || result != CURLE_OK) return(result); tftp_multi_statemach(conn, dophase_done); if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; }
/********************************************************** * * tftp_peform * * Entry point for transfer from tftp_do, sarts state mach * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1272-L1290
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
tftp_do
static CURLcode tftp_do(struct connectdata *conn, bool *done) { tftp_state_data_t *state; CURLcode code; *done = FALSE; /* 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 TFTP' to play with. For new connections, the struct TFTP is allocated and setup in the tftp_connect() function. */ Curl_reset_reqproto(conn); if(!conn->proto.tftpc) { code = tftp_connect(conn, done); if(code) return code; } state = (tftp_state_data_t *)conn->proto.tftpc; code = tftp_perform(conn, done); /* If tftp_perform() returned an error, use that for return code. If it was OK, see if tftp_translate_code() has an error. */ if(code == CURLE_OK) /* If we have encountered an internal tftp error, translate it. */ code = tftp_translate_code(state->error); return code; }
/********************************************************** * * tftp_do * * The do callback * * This callback initiates the TFTP transfer * **********************************************************/
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/tftp.c#L1303-L1334
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_tvdiff
long curlx_tvdiff(struct timeval newer, struct timeval older) { return (newer.tv_sec-older.tv_sec)*1000+ (newer.tv_usec-older.tv_usec)/1000; }
/* * Make sure that the first argument is the more recent time, as otherwise * we'll get a weird negative time-diff back... * * Returns: the time difference in number of milliseconds. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/timeval.c#L110-L114
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_tvdiff_secs
double curlx_tvdiff_secs(struct timeval newer, struct timeval older) { if(newer.tv_sec != older.tv_sec) return (double)(newer.tv_sec-older.tv_sec)+ (double)(newer.tv_usec-older.tv_usec)/1000000.0; else return (double)(newer.tv_usec-older.tv_usec)/1000000.0; }
/* * Same as curlx_tvdiff but with full usec resolution. * * Returns: the time difference in seconds with subsecond resolution. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/timeval.c#L121-L128
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_tvlong
long Curl_tvlong(struct timeval t1) { return t1.tv_sec; }
/* return the number of seconds in the given input timeval struct */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/timeval.c#L131-L134
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_ultous
unsigned short curlx_ultous(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT); return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned long to unsigned short */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L124-L137
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_ultouc
unsigned char curlx_ultouc(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR); return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned long to unsigned char */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L143-L156
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_ultosi
int curlx_ultosi(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_SINT); return (int)(ulnum & (unsigned long) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned long to signed int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L162-L175
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_uztosi
int curlx_uztosi(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT); return (int)(uznum & (size_t) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned size_t to signed int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L181-L194
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_uztoul
unsigned long curlx_uztoul(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif #if (CURL_SIZEOF_LONG < SIZEOF_SIZE_T) DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG); #endif return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned size_t to unsigned long */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L200-L215
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_uztoui
unsigned int curlx_uztoui(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif #if (SIZEOF_INT < SIZEOF_SIZE_T) DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT); #endif return (unsigned int)(uznum & (size_t) CURL_MASK_UINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned size_t to unsigned int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L221-L236
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sltosi
int curlx_sltosi(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); #if (SIZEOF_INT < CURL_SIZEOF_LONG) DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT); #endif return (int)(slnum & (long) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed long to signed int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L242-L258
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sltoui
unsigned int curlx_sltoui(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); #if (SIZEOF_INT < CURL_SIZEOF_LONG) DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT); #endif return (unsigned int)(slnum & (long) CURL_MASK_UINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed long to unsigned int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L264-L280
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sltous
unsigned short curlx_sltous(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT); return (unsigned short)(slnum & (long) CURL_MASK_USHORT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed long to unsigned short */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L286-L300
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_uztosz
ssize_t curlx_uztosz(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T); return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** unsigned size_t to signed ssize_t */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L306-L319
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sotouz
size_t curlx_sotouz(curl_off_t sonum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sonum >= 0); return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed curl_off_t to unsigned size_t */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L325-L338
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sztosi
int curlx_sztosi(ssize_t sznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sznum >= 0); #if (SIZEOF_INT < SIZEOF_SIZE_T) DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT); #endif return (int)(sznum & (ssize_t) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed ssize_t to signed int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L344-L360
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sitouz
size_t curlx_sitouz(int sinum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sinum >= 0); return (size_t) sinum; #ifdef __INTEL_COMPILER # pragma warning(pop) #endif }
/* ** signed int to unsigned size_t */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L366-L379
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sktosi
int curlx_sktosi(curl_socket_t s) { return (int)((ssize_t) s); }
/* ** curl_socket_t to signed int */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L387-L390
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
curlx_sitosk
curl_socket_t curlx_sitosk(int i) { return (curl_socket_t)((ssize_t) i); }
/* ** signed int to curl_socket_t */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/warnless.c#L396-L399
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
setup_des_key
static void setup_des_key(const unsigned char *key_56, DES_key_schedule DESKEYARG(ks)) { DES_cblock key; key[0] = key_56[0]; key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1)); key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2)); key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3)); key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4)); key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5)); key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6)); key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF); DES_set_odd_parity(&key); DES_set_key(&key, ks); }
/* * Turns a 56 bit key into the 64 bit, odd parity key and sets the key. The * key schedule ks is also set. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L111-L127
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
extend_key_56_to_64
static void extend_key_56_to_64(const unsigned char *key_56, char *key) { key[0] = key_56[0]; key[1] = (unsigned char)(((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1)); key[2] = (unsigned char)(((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2)); key[3] = (unsigned char)(((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3)); key[4] = (unsigned char)(((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4)); key[5] = (unsigned char)(((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5)); key[6] = (unsigned char)(((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6)); key[7] = (unsigned char) ((key_56[6] << 1) & 0xFF); }
/* defined(USE_SSLEAY) */ /* * Turns a 56 bit key into the 64 bit, odd parity key. Used by GnuTLS and NSS. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L134-L144
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
setup_des_key
static void setup_des_key(const unsigned char *key_56, gcry_cipher_hd_t *des) { char key[8]; extend_key_56_to_64(key_56, key); gcry_cipher_setkey(*des, key, 8); }
/* * Turns a 56 bit key into the 64 bit, odd parity key and sets the key. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L161-L167
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
encrypt_des
static bool encrypt_des(const unsigned char *in, unsigned char *out, const unsigned char *key_56) { const CK_MECHANISM_TYPE mech = CKM_DES_ECB; /* DES cipher in ECB mode */ PK11SlotInfo *slot = NULL; char key[8]; /* expanded 64 bit key */ SECItem key_item; PK11SymKey *symkey = NULL; SECItem *param = NULL; PK11Context *ctx = NULL; int out_len; /* not used, required by NSS */ bool rv = FALSE; /* use internal slot for DES encryption (requires NSS to be initialized) */ slot = PK11_GetInternalKeySlot(); if(!slot) return FALSE; /* expand the 56 bit key to 64 bit and wrap by NSS */ extend_key_56_to_64(key_56, key); key_item.data = (unsigned char *)key; key_item.len = /* hard-wired */ 8; symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap, CKA_ENCRYPT, &key_item, NULL); if(!symkey) goto fail; /* create DES encryption context */ param = PK11_ParamFromIV(mech, /* no IV in ECB mode */ NULL); if(!param) goto fail; ctx = PK11_CreateContextBySymKey(mech, CKA_ENCRYPT, symkey, param); if(!ctx) goto fail; /* perform the encryption */ if(SECSuccess == PK11_CipherOp(ctx, out, &out_len, /* outbuflen */ 8, (unsigned char *)in, /* inbuflen */ 8) && SECSuccess == PK11_Finalize(ctx)) rv = /* all OK */ TRUE; fail: /* cleanup */ if(ctx) PK11_DestroyContext(ctx, PR_TRUE); if(symkey) PK11_FreeSymKey(symkey); if(param) SECITEM_FreeItem(param, PR_TRUE); PK11_FreeSlot(slot); return rv; }
/* * Expands a 56 bit key KEY_56 to 64 bit and encrypts 64 bit of data, using * the expanded key. The caller is responsible for giving 64 bit of valid * data is IN and (at least) 64 bit large buffer as OUT. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L176-L227
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_core_lm_resp
void Curl_ntlm_core_lm_resp(const unsigned char *keys, const unsigned char *plaintext, unsigned char *results) { #ifdef USE_SSLEAY DES_key_schedule ks; setup_des_key(keys, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) results, DESKEY(ks), DES_ENCRYPT); setup_des_key(keys + 7, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 8), DESKEY(ks), DES_ENCRYPT); setup_des_key(keys + 14, DESKEY(ks)); DES_ecb_encrypt((DES_cblock*) plaintext, (DES_cblock*) (results + 16), DESKEY(ks), DES_ENCRYPT); #elif defined(USE_GNUTLS_NETTLE) struct des_ctx des; setup_des_key(keys, &des); des_encrypt(&des, 8, results, plaintext); setup_des_key(keys + 7, &des); des_encrypt(&des, 8, results + 8, plaintext); setup_des_key(keys + 14, &des); des_encrypt(&des, 8, results + 16, plaintext); #elif defined(USE_GNUTLS) gcry_cipher_hd_t des; gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys, &des); gcry_cipher_encrypt(des, results, 8, plaintext, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys + 7, &des); gcry_cipher_encrypt(des, results + 8, 8, plaintext, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(keys + 14, &des); gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8); gcry_cipher_close(des); #elif defined(USE_NSS) || defined(USE_DARWINSSL) encrypt_des(plaintext, results, keys); encrypt_des(plaintext, results + 8, keys + 7); encrypt_des(plaintext, results + 16, keys + 14); #endif }
/* defined(USE_SSLEAY) */ /* * takes a 21 byte array and treats it as 3 56-bit DES keys. The * 8 byte plaintext is encrypted with each key and the resulting 24 * bytes are stored in the results array. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L254-L302
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_core_mk_lm_hash
void Curl_ntlm_core_mk_lm_hash(struct SessionHandle *data, const char *password, unsigned char *lmbuffer /* 21 bytes */) { CURLcode res; unsigned char pw[14]; static const unsigned char magic[] = { 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 /* i.e. KGS!@#$% */ }; size_t len = CURLMIN(strlen(password), 14); Curl_strntoupper((char *)pw, password, len); memset(&pw[len], 0, 14 - len); /* * The LanManager hashed password needs to be created using the * password in the network encoding not the host encoding. */ res = Curl_convert_to_network(data, (char *)pw, 14); if(res) return; { /* Create LanManager hashed password. */ #ifdef USE_SSLEAY DES_key_schedule ks; setup_des_key(pw, DESKEY(ks)); DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)lmbuffer, DESKEY(ks), DES_ENCRYPT); setup_des_key(pw + 7, DESKEY(ks)); DES_ecb_encrypt((DES_cblock *)magic, (DES_cblock *)(lmbuffer + 8), DESKEY(ks), DES_ENCRYPT); #elif defined(USE_GNUTLS_NETTLE) struct des_ctx des; setup_des_key(pw, &des); des_encrypt(&des, 8, lmbuffer, magic); setup_des_key(pw + 7, &des); des_encrypt(&des, 8, lmbuffer + 8, magic); #elif defined(USE_GNUTLS) gcry_cipher_hd_t des; gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(pw, &des); gcry_cipher_encrypt(des, lmbuffer, 8, magic, 8); gcry_cipher_close(des); gcry_cipher_open(&des, GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, 0); setup_des_key(pw + 7, &des); gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8); gcry_cipher_close(des); #elif defined(USE_NSS) || defined(USE_DARWINSSL) encrypt_des(magic, lmbuffer, pw); encrypt_des(magic, lmbuffer + 8, pw + 7); #endif memset(lmbuffer + 16, 0, 21 - 16); } }
/* * Set up lanmanager hashed password */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L307-L367
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_ntlm_core_mk_nt_hash
CURLcode Curl_ntlm_core_mk_nt_hash(struct SessionHandle *data, const char *password, unsigned char *ntbuffer /* 21 bytes */) { size_t len = strlen(password); unsigned char *pw = malloc(len * 2); CURLcode result; if(!pw) return CURLE_OUT_OF_MEMORY; ascii_to_unicode_le(pw, password, len); /* * The NT hashed password needs to be created using the password in the * network encoding not the host encoding. */ result = Curl_convert_to_network(data, (char *)pw, len * 2); if(result) return result; { /* Create NT hashed password. */ #ifdef USE_SSLEAY MD4_CTX MD4pw; MD4_Init(&MD4pw); MD4_Update(&MD4pw, pw, 2 * len); MD4_Final(ntbuffer, &MD4pw); #elif defined(USE_GNUTLS_NETTLE) struct md4_ctx MD4pw; md4_init(&MD4pw); md4_update(&MD4pw, (unsigned int)(2 * len), pw); md4_digest(&MD4pw, MD4_DIGEST_SIZE, ntbuffer); #elif defined(USE_GNUTLS) gcry_md_hd_t MD4pw; gcry_md_open(&MD4pw, GCRY_MD_MD4, 0); gcry_md_write(MD4pw, pw, 2 * len); memcpy (ntbuffer, gcry_md_read (MD4pw, 0), MD4_DIGEST_LENGTH); gcry_md_close(MD4pw); #elif defined(USE_NSS) Curl_md4it(ntbuffer, pw, 2 * len); #elif defined(USE_DARWINSSL) (void)CC_MD4(pw, 2 * len, ntbuffer); #endif memset(ntbuffer + 16, 0, 21 - 16); } free(pw); return CURLE_OK; }
/* * Set up nt hashed passwords */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_ntlm_core.c#L383-L433
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_proxyCONNECT
CURLcode Curl_proxyCONNECT(struct connectdata *conn, int sockindex, const char *hostname, unsigned short remote_port) { int subversion=0; struct SessionHandle *data=conn->data; struct SingleRequest *k = &data->req; CURLcode result; long timeout = data->set.timeout?data->set.timeout:PROXY_TIMEOUT; /* in milliseconds */ curl_socket_t tunnelsocket = conn->sock[sockindex]; curl_off_t cl=0; bool closeConnection = FALSE; bool chunked_encoding = FALSE; long check; #define SELECT_OK 0 #define SELECT_ERROR 1 #define SELECT_TIMEOUT 2 int error = SELECT_OK; if(conn->tunnel_state[sockindex] == TUNNEL_COMPLETE) return CURLE_OK; /* CONNECT is already completed */ conn->bits.proxy_connect_closed = FALSE; do { if(TUNNEL_INIT == conn->tunnel_state[sockindex]) { /* BEGIN CONNECT PHASE */ char *host_port; Curl_send_buffer *req_buffer; infof(data, "Establish HTTP proxy tunnel to %s:%hu\n", hostname, remote_port); if(data->req.newurl) { /* This only happens if we've looped here due to authentication reasons, and we don't really use the newly cloned URL here then. Just free() it. */ free(data->req.newurl); data->req.newurl = NULL; } /* initialize a dynamic send-buffer */ req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; host_port = aprintf("%s:%hu", hostname, remote_port); if(!host_port) { free(req_buffer); return CURLE_OUT_OF_MEMORY; } /* Setup the proxy-authorization header, if any */ result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE); free(host_port); if(CURLE_OK == result) { char *host=(char *)""; const char *proxyconn=""; const char *useragent=""; const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ? "1.0" : "1.1"; char *hostheader= /* host:port with IPv6 support */ aprintf("%s%s%s:%hu", conn->bits.ipv6_ip?"[":"", hostname, conn->bits.ipv6_ip?"]":"", remote_port); if(!hostheader) { free(req_buffer); return CURLE_OUT_OF_MEMORY; } if(!Curl_checkheaders(data, "Host:")) { host = aprintf("Host: %s\r\n", hostheader); if(!host) { free(hostheader); free(req_buffer); return CURLE_OUT_OF_MEMORY; } } if(!Curl_checkheaders(data, "Proxy-Connection:")) proxyconn = "Proxy-Connection: Keep-Alive\r\n"; if(!Curl_checkheaders(data, "User-Agent:") && data->set.str[STRING_USERAGENT]) useragent = conn->allocptr.uagent; result = Curl_add_bufferf(req_buffer, "CONNECT %s HTTP/%s\r\n" "%s" /* Host: */ "%s" /* Proxy-Authorization */ "%s" /* User-Agent */ "%s", /* Proxy-Connection */ hostheader, http, host, conn->allocptr.proxyuserpwd? conn->allocptr.proxyuserpwd:"", useragent, proxyconn); if(host && *host) free(host); free(hostheader); if(CURLE_OK == result) result = Curl_add_custom_headers(conn, req_buffer); if(CURLE_OK == result) /* CRLF terminate the request */ result = Curl_add_bufferf(req_buffer, "\r\n"); if(CURLE_OK == result) { /* Send the connect request to the proxy */ /* BLOCKING */ result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size, 0, sockindex); } req_buffer = NULL; if(result) failf(data, "Failed sending CONNECT to proxy"); } Curl_safefree(req_buffer); if(result) return result; conn->tunnel_state[sockindex] = TUNNEL_CONNECT; /* now we've issued the CONNECT and we're waiting to hear back, return and get called again polling-style */ return CURLE_OK; } /* END CONNECT PHASE */ { /* BEGIN NEGOTIATION PHASE */ size_t nread; /* total size read */ int perline; /* count bytes per line */ int keepon=TRUE; ssize_t gotbytes; char *ptr; char *line_start; ptr=data->state.buffer; line_start = ptr; nread=0; perline=0; keepon=TRUE; while((nread<BUFSIZE) && (keepon && !error)) { /* if timeout is requested, find out how much remaining time we have */ check = timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */ if(check <= 0) { failf(data, "Proxy CONNECT aborted due to timeout"); error = SELECT_TIMEOUT; /* already too little time */ break; } /* loop every second at least, less if the timeout is near */ switch (Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD, check<1000L?check:1000)) { case -1: /* select() error, stop reading */ error = SELECT_ERROR; failf(data, "Proxy CONNECT aborted due to select/poll error"); break; case 0: /* timeout */ break; default: DEBUGASSERT(ptr+BUFSIZE-nread <= data->state.buffer+BUFSIZE+1); result = Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread, &gotbytes); if(result==CURLE_AGAIN) continue; /* go loop yourself */ else if(result) keepon = FALSE; else if(gotbytes <= 0) { keepon = FALSE; if(data->set.proxyauth && data->state.authproxy.avail) { /* proxy auth was requested and there was proxy auth available, then deem this as "mere" proxy disconnect */ conn->bits.proxy_connect_closed = TRUE; } else { error = SELECT_ERROR; failf(data, "Proxy CONNECT aborted"); } } else { /* * We got a whole chunk of data, which can be anything from one * byte to a set of lines and possibly just a piece of the last * line. */ int i; nread += gotbytes; if(keepon > TRUE) { /* This means we are currently ignoring a response-body */ nread = 0; /* make next read start over in the read buffer */ ptr=data->state.buffer; if(cl) { /* A Content-Length based body: simply count down the counter and make sure to break out of the loop when we're done! */ cl -= gotbytes; if(cl<=0) { keepon = FALSE; break; } } else { /* chunked-encoded body, so we need to do the chunked dance properly to know when the end of the body is reached */ CHUNKcode r; ssize_t tookcareof=0; /* now parse the chunked piece of data so that we can properly tell when the stream ends */ r = Curl_httpchunk_read(conn, ptr, gotbytes, &tookcareof); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); keepon = FALSE; /* we did the full CONNECT treatment, go COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; } else infof(data, "Read %zd bytes of chunk, continue\n", tookcareof); } } else for(i = 0; i < gotbytes; ptr++, i++) { perline++; /* amount of bytes in this line so far */ if(*ptr == 0x0a) { char letter; int writetype; /* convert from the network encoding */ result = Curl_convert_from_network(data, line_start, perline); /* Curl_convert_from_network calls failf if unsuccessful */ if(result) return result; /* output debug if that is requested */ if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, line_start, (size_t)perline, conn); /* send the header to the callback */ writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; result = Curl_client_write(conn, writetype, line_start, perline); if(result) return result; /* Newlines are CRLF, so the CR is ignored as the line isn't really terminated until the LF comes. Treat a following CR as end-of-headers as well.*/ if(('\r' == line_start[0]) || ('\n' == line_start[0])) { /* end of response-headers from the proxy */ nread = 0; /* make next read start over in the read buffer */ ptr=data->state.buffer; if((407 == k->httpcode) && !data->state.authproblem) { /* If we get a 407 response code with content length when we have no auth problem, we must ignore the whole response-body */ keepon = 2; if(cl) { infof(data, "Ignore %" FORMAT_OFF_T " bytes of response-body\n", cl); /* remove the remaining chunk of what we already read */ cl -= (gotbytes - i); if(cl<=0) /* if the whole thing was already read, we are done! */ keepon=FALSE; } else if(chunked_encoding) { CHUNKcode r; /* We set ignorebody true here since the chunked decoder function will acknowledge that. Pay attention so that this is cleared again when this function returns! */ k->ignorebody = TRUE; infof(data, "%zd bytes of chunk left\n", gotbytes-i); if(line_start[1] == '\n') { /* this can only be a LF if the letter at index 0 was a CR */ line_start++; i++; } /* now parse the chunked piece of data so that we can properly tell when the stream ends */ r = Curl_httpchunk_read(conn, line_start+1, gotbytes -i, &gotbytes); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); keepon = FALSE; /* we did the full CONNECT treatment, go to COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; } else infof(data, "Read %zd bytes of chunk, continue\n", gotbytes); } else { /* without content-length or chunked encoding, we can't keep the connection alive since the close is the end signal so we bail out at once instead */ keepon=FALSE; } } else { keepon = FALSE; if(200 == data->info.httpproxycode) { if(gotbytes - (i+1)) failf(data, "Proxy CONNECT followed by %zd bytes " "of opaque data. Data ignored (known bug #39)", gotbytes - (i+1)); } } /* we did the full CONNECT treatment, go to COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; break; /* breaks out of for-loop, not switch() */ } /* keep a backup of the position we are about to blank */ letter = line_start[perline]; line_start[perline]=0; /* zero terminate the buffer */ if((checkprefix("WWW-Authenticate:", line_start) && (401 == k->httpcode)) || (checkprefix("Proxy-authenticate:", line_start) && (407 == k->httpcode))) { result = Curl_http_input_auth(conn, k->httpcode, line_start); if(result) return result; } else if(checkprefix("Content-Length:", line_start)) { cl = curlx_strtoofft(line_start + strlen("Content-Length:"), NULL, 10); } else if(Curl_compareheader(line_start, "Connection:", "close")) closeConnection = TRUE; else if(Curl_compareheader(line_start, "Transfer-Encoding:", "chunked")) { infof(data, "CONNECT responded chunked\n"); chunked_encoding = TRUE; /* init our chunky engine */ Curl_httpchunk_init(conn); } else if(Curl_compareheader(line_start, "Proxy-Connection:", "close")) closeConnection = TRUE; else if(2 == sscanf(line_start, "HTTP/1.%d %d", &subversion, &k->httpcode)) { /* store the HTTP code from the proxy */ data->info.httpproxycode = k->httpcode; } /* put back the letter we blanked out before */ line_start[perline]= letter; perline=0; /* line starts over here */ line_start = ptr+1; /* this skips the zero byte we wrote */ } } } break; } /* switch */ if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; } /* while there's buffer left and loop is requested */ if(error) return CURLE_RECV_ERROR; if(data->info.httpproxycode != 200) { /* Deal with the possibly already received authenticate headers. 'newurl' is set to a new URL if we must loop. */ result = Curl_http_auth_act(conn); if(result) return result; if(conn->bits.close) /* the connection has been marked for closure, most likely in the Curl_http_auth_act() function and thus we can kill it at once below */ closeConnection = TRUE; } if(closeConnection && data->req.newurl) { /* Connection closed by server. Don't use it anymore */ Curl_closesocket(conn, conn->sock[sockindex]); conn->sock[sockindex] = CURL_SOCKET_BAD; break; } } /* END NEGOTIATION PHASE */ /* If we are supposed to continue and request a new URL, which basically * means the HTTP authentication is still going on so if the tunnel * is complete we start over in INIT state */ if(data->req.newurl && (TUNNEL_COMPLETE == conn->tunnel_state[sockindex])) { conn->tunnel_state[sockindex] = TUNNEL_INIT; infof(data, "TUNNEL_STATE switched to: %d\n", conn->tunnel_state[sockindex]); } } while(data->req.newurl); if(200 != data->req.httpcode) { failf(data, "Received HTTP code %d from proxy after CONNECT", data->req.httpcode); if(closeConnection && data->req.newurl) conn->bits.proxy_connect_closed = TRUE; if(data->req.newurl) { /* this won't be used anymore for the CONNECT so free it now */ free(data->req.newurl); data->req.newurl = NULL; } /* to back to init state */ conn->tunnel_state[sockindex] = TUNNEL_INIT; return CURLE_RECV_ERROR; } conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; /* If a proxy-authorization header was used for the proxy, then we should make sure that it isn't accidentally used for the document request after we've connected. So let's free and clear it here. */ Curl_safefree(conn->allocptr.proxyuserpwd); conn->allocptr.proxyuserpwd = NULL; data->state.authproxy.done = TRUE; infof (data, "Proxy replied OK to CONNECT request\n"); data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */ return CURLE_OK; }
/* * Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This * function will issue the necessary commands to get a seamless tunnel through * this proxy. After that, the socket can be used just as a normal socket. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/http_proxy.c#L92-L564
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
setcharset
static int setcharset(unsigned char **p, unsigned char *charset) { setcharset_state state = CURLFNM_SCHS_DEFAULT; unsigned char rangestart = 0; unsigned char lastchar = 0; bool something_found = FALSE; unsigned char c; for(;;) { c = **p; switch(state) { case CURLFNM_SCHS_DEFAULT: if(ISALNUM(c)) { /* ASCII value */ rangestart = c; charset[c] = 1; (*p)++; state = CURLFNM_SCHS_MAYRANGE; something_found = TRUE; } else if(c == ']') { if(something_found) return SETCHARSET_OK; else something_found = TRUE; state = CURLFNM_SCHS_RIGHTBR; charset[c] = 1; (*p)++; } else if(c == '[') { char c2 = *((*p)+1); if(c2 == ':') { /* there has to be a keyword */ (*p) += 2; if(parsekeyword(p, charset)) { state = CURLFNM_SCHS_DEFAULT; } else return SETCHARSET_FAIL; } else { charset[c] = 1; (*p)++; } something_found = TRUE; } else if(c == '?' || c == '*') { something_found = TRUE; charset[c] = 1; (*p)++; } else if(c == '^' || c == '!') { if(!something_found) { if(charset[CURLFNM_NEGATE]) { charset[c] = 1; something_found = TRUE; } else charset[CURLFNM_NEGATE] = 1; /* negate charset */ } else charset[c] = 1; (*p)++; } else if(c == '\\') { c = *(++(*p)); if(ISPRINT((c))) { something_found = TRUE; state = CURLFNM_SCHS_MAYRANGE; charset[c] = 1; rangestart = c; (*p)++; } else return SETCHARSET_FAIL; } else if(c == '\0') { return SETCHARSET_FAIL; } else { charset[c] = 1; (*p)++; something_found = TRUE; } break; case CURLFNM_SCHS_MAYRANGE: if(c == '-') { charset[c] = 1; (*p)++; lastchar = '-'; state = CURLFNM_SCHS_MAYRANGE2; } else if(c == '[') { state = CURLFNM_SCHS_DEFAULT; } else if(ISALNUM(c)) { charset[c] = 1; (*p)++; } else if(c == '\\') { c = *(++(*p)); if(ISPRINT(c)) { charset[c] = 1; (*p)++; } else return SETCHARSET_FAIL; } else if(c == ']') { return SETCHARSET_OK; } else return SETCHARSET_FAIL; break; case CURLFNM_SCHS_MAYRANGE2: if(c == '\\') { c = *(++(*p)); if(!ISPRINT(c)) return SETCHARSET_FAIL; } if(c == ']') { return SETCHARSET_OK; } else if(c == '\\') { c = *(++(*p)); if(ISPRINT(c)) { charset[c] = 1; state = CURLFNM_SCHS_DEFAULT; (*p)++; } else return SETCHARSET_FAIL; } if(c >= rangestart) { if((ISLOWER(c) && ISLOWER(rangestart)) || (ISDIGIT(c) && ISDIGIT(rangestart)) || (ISUPPER(c) && ISUPPER(rangestart))) { charset[lastchar] = 0; rangestart++; while(rangestart++ <= c) charset[rangestart-1] = 1; (*p)++; state = CURLFNM_SCHS_DEFAULT; } else return SETCHARSET_FAIL; } break; case CURLFNM_SCHS_RIGHTBR: if(c == '[') { state = CURLFNM_SCHS_RIGHTBRLEFTBR; charset[c] = 1; (*p)++; } else if(c == ']') { return SETCHARSET_OK; } else if(c == '\0') { return SETCHARSET_FAIL; } else if(ISPRINT(c)) { charset[c] = 1; (*p)++; state = CURLFNM_SCHS_DEFAULT; } else /* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a * nonsense warning 'statement not reached' at end of the fnc when * compiling on Solaris */ goto fail; break; case CURLFNM_SCHS_RIGHTBRLEFTBR: if(c == ']') { return SETCHARSET_OK; } else { state = CURLFNM_SCHS_DEFAULT; charset[c] = 1; (*p)++; } break; } } fail: return SETCHARSET_FAIL; }
/* returns 1 (true) if pattern is OK, 0 if is bad ("p" is pattern pointer) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_fnmatch.c#L128-L310
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_fnmatch
int Curl_fnmatch(void *ptr, const char *pattern, const char *string) { (void)ptr; /* the argument is specified by the curl_fnmatch_callback prototype, but not used by Curl_fnmatch() */ if(!pattern || !string) { return CURL_FNMATCH_FAIL; } return loop((unsigned char *)pattern, (unsigned char *)string); }
/* * @unittest: 1307 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/curl_fnmatch.c#L419-L427
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
hostmatch
static int hostmatch(const char *hostname, const char *pattern) { const char *pattern_label_end, *pattern_wildcard, *hostname_label_end; int wildcard_enabled; size_t prefixlen, suffixlen; pattern_wildcard = strchr(pattern, '*'); if(pattern_wildcard == NULL) return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; /* We require at least 2 dots in pattern to avoid too wide wildcard match. */ wildcard_enabled = 1; pattern_label_end = strchr(pattern, '.'); if(pattern_label_end == NULL || strchr(pattern_label_end+1, '.') == NULL || pattern_wildcard > pattern_label_end || Curl_raw_nequal(pattern, "xn--", 4)) { wildcard_enabled = 0; } if(!wildcard_enabled) return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; hostname_label_end = strchr(hostname, '.'); if(hostname_label_end == NULL || !Curl_raw_equal(pattern_label_end, hostname_label_end)) return CURL_HOST_NOMATCH; /* The wildcard must match at least one character, so the left-most label of the hostname is at least as large as the left-most label of the pattern. */ if(hostname_label_end - hostname < pattern_label_end - pattern) return CURL_HOST_NOMATCH; prefixlen = pattern_wildcard - pattern; suffixlen = pattern_label_end - (pattern_wildcard+1); return Curl_raw_nequal(pattern, hostname, prefixlen) && Curl_raw_nequal(pattern_wildcard+1, hostname_label_end - suffixlen, suffixlen) ? CURL_HOST_MATCH : CURL_HOST_NOMATCH; }
/* * Match a hostname against a wildcard pattern. * E.g. * "foo.host.com" matches "*.host.com". * * We use the matching rule described in RFC6125, section 6.4.3. * http://tools.ietf.org/html/rfc6125#section-6.4.3 */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/hostcheck.c#L40-L80
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
num_enabled_ciphers
static int num_enabled_ciphers(void) { PRInt32 policy = 0; int count = 0; unsigned int i; for(i=0; i<NUM_OF_CIPHERS; i++) { SSL_CipherPolicyGet(cipherlist[i].num, &policy); if(policy) count++; } return count; }
/* * Get the number of ciphers that are enabled. We use this to determine * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L256-L268
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
is_file
static int is_file(const char *filename) { struct_stat st; if(filename == NULL) return 0; if(stat(filename, &st) == 0) if(S_ISREG(st.st_mode)) return 1; return 0; }
/* * Determine whether the nickname passed in is a filename that needs to * be loaded as a PEM or a regular NSS nickname. * * returns 1 for a file * returns 0 for not a file (NSS nickname) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L277-L289
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
nss_create_object
static CURLcode nss_create_object(struct ssl_connect_data *ssl, CK_OBJECT_CLASS obj_class, const char *filename, bool cacert) { PK11SlotInfo *slot; PK11GenericObject *obj; CK_BBOOL cktrue = CK_TRUE; CK_BBOOL ckfalse = CK_FALSE; CK_ATTRIBUTE attrs[/* max count of attributes */ 4]; int attr_cnt = 0; CURLcode err = (cacert) ? CURLE_SSL_CACERT_BADFILE : CURLE_SSL_CERTPROBLEM; const int slot_id = (cacert) ? 0 : 1; char *slot_name = aprintf("PEM Token #%d", slot_id); if(!slot_name) return CURLE_OUT_OF_MEMORY; slot = PK11_FindSlotByName(slot_name); free(slot_name); if(!slot) return err; PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class)); PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL)); PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename, strlen(filename) + 1); if(CKO_CERTIFICATE == obj_class) { CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse); PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval)); } obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE); PK11_FreeSlot(slot); if(!obj) return err; if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) { PK11_DestroyGenericObject(obj); return CURLE_OUT_OF_MEMORY; } if(!cacert && CKO_CERTIFICATE == obj_class) /* store reference to a client certificate */ ssl->obj_clicert = obj; return CURLE_OK; }
/* Call PK11_CreateGenericObject() with the given obj_class and filename. If * the call succeeds, append the object handle to the list of objects so that * the object can be destroyed in Curl_nss_close(). */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L321-L370
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
nss_destroy_object
static void nss_destroy_object(void *user, void *ptr) { PK11GenericObject *obj = (PK11GenericObject *)ptr; (void) user; PK11_DestroyGenericObject(obj); }
/* Destroy the NSS object whose handle is given by ptr. This function is * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy * NSS objects in Curl_nss_close() */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L375-L380
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
nss_cache_crl
static SECStatus nss_cache_crl(SECItem *crlDER) { CERTCertDBHandle *db = CERT_GetDefaultCertDB(); CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0); if(crl) { /* CRL already cached */ SEC_DestroyCrl(crl); SECITEM_FreeItem(crlDER, PR_FALSE); return SECSuccess; } /* acquire lock before call of CERT_CacheCRL() */ PR_Lock(nss_crllock); if(SECSuccess != CERT_CacheCRL(db, crlDER)) { /* unable to cache CRL */ PR_Unlock(nss_crllock); SECITEM_FreeItem(crlDER, PR_FALSE); return SECFailure; } /* we need to clear session cache, so that the CRL could take effect */ SSL_ClearSessionCache(); PR_Unlock(nss_crllock); return SECSuccess; }
/* add given CRL to cache if it is not already there */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L420-L444
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
nss_auth_cert_hook
static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer) { struct connectdata *conn = (struct connectdata *)arg; if(!conn->data->set.ssl.verifypeer) { infof(conn->data, "skipping SSL peer certificate verification\n"); return SECSuccess; } return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer); }
/* bypass the default SSL_AuthCertificate() hook in case we do not want to * verify peer */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L602-L612
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
HandshakeCallback
static void HandshakeCallback(PRFileDesc *sock, void *arg) { (void)sock; (void)arg; }
/** * Inform the application that the handshake is complete. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L617-L621
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
check_issuer_cert
static SECStatus check_issuer_cert(PRFileDesc *sock, char *issuer_nickname) { CERTCertificate *cert,*cert_issuer,*issuer; SECStatus res=SECSuccess; void *proto_win = NULL; /* PRArenaPool *tmpArena = NULL; CERTAuthKeyID *authorityKeyID = NULL; SECITEM *caname = NULL; */ cert = SSL_PeerCertificate(sock); cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner); proto_win = SSL_RevealPinArg(sock); issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win); if((!cert_issuer) || (!issuer)) res = SECFailure; else if(SECITEM_CompareItem(&cert_issuer->derCert, &issuer->derCert)!=SECEqual) res = SECFailure; CERT_DestroyCertificate(cert); CERT_DestroyCertificate(issuer); CERT_DestroyCertificate(cert_issuer); return res; }
/** * * Check that the Peer certificate's issuer certificate matches the one found * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the * issuer check, so we provide comments that mimic the OpenSSL * X509_check_issued function (in x509v3/v3_purp.c) */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L707-L736
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
SelectClientCert
static SECStatus SelectClientCert(void *arg, PRFileDesc *sock, struct CERTDistNamesStr *caNames, struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey) { struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg; struct SessionHandle *data = connssl->data; const char *nickname = connssl->client_nickname; if(connssl->obj_clicert) { /* use the cert/key provided by PEM reader */ static const char pem_slotname[] = "PEM Token #1"; SECItem cert_der = { 0, NULL, 0 }; void *proto_win = SSL_RevealPinArg(sock); struct CERTCertificateStr *cert; struct SECKEYPrivateKeyStr *key; PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname); if(NULL == slot) { failf(data, "NSS: PK11 slot not found: %s", pem_slotname); return SECFailure; } if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE, &cert_der) != SECSuccess) { failf(data, "NSS: CKA_VALUE not found in PK11 generic object"); PK11_FreeSlot(slot); return SECFailure; } cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win); SECITEM_FreeItem(&cert_der, PR_FALSE); if(NULL == cert) { failf(data, "NSS: client certificate from file not found"); PK11_FreeSlot(slot); return SECFailure; } key = PK11_FindPrivateKeyFromCert(slot, cert, NULL); PK11_FreeSlot(slot); if(NULL == key) { failf(data, "NSS: private key from file not found"); CERT_DestroyCertificate(cert); return SECFailure; } infof(data, "NSS: client certificate from file\n"); display_cert_info(data, cert); *pRetCert = cert; *pRetKey = key; return SECSuccess; } /* use the default NSS hook */ if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames, pRetCert, pRetKey) || NULL == *pRetCert) { if(NULL == nickname) failf(data, "NSS: client certificate not found (nickname not " "specified)"); else failf(data, "NSS: client certificate not found: %s", nickname); return SECFailure; } /* get certificate nickname if any */ nickname = (*pRetCert)->nickname; if(NULL == nickname) nickname = "[unknown]"; if(NULL == *pRetKey) { failf(data, "NSS: private key not found for certificate: %s", nickname); return SECFailure; } infof(data, "NSS: using client certificate: %s\n", nickname); display_cert_info(data, *pRetCert); return SECSuccess; }
/** * * Callback to pick the SSL client certificate. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L742-L823
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
isTLSIntoleranceError
static PRBool isTLSIntoleranceError(PRInt32 err) { switch (err) { case SSL_ERROR_BAD_MAC_ALERT: case SSL_ERROR_BAD_MAC_READ: case SSL_ERROR_HANDSHAKE_FAILURE_ALERT: case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT: case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE: case SSL_ERROR_ILLEGAL_PARAMETER_ALERT: case SSL_ERROR_NO_CYPHER_OVERLAP: case SSL_ERROR_BAD_SERVER: case SSL_ERROR_BAD_BLOCK_PADDING: case SSL_ERROR_UNSUPPORTED_VERSION: case SSL_ERROR_PROTOCOL_VERSION_ALERT: case SSL_ERROR_RX_MALFORMED_FINISHED: case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE: case SSL_ERROR_DECODE_ERROR_ALERT: case SSL_ERROR_RX_UNKNOWN_ALERT: return PR_TRUE; default: return PR_FALSE; } }
/* This function is supposed to decide, which error codes should be used * to conclude server is TLS intolerant. * * taken from xulrunner - nsNSSIOLayer.cpp */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L830-L853
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_nss_init
int Curl_nss_init(void) { /* curl_global_init() is not thread-safe so this test is ok */ if(nss_initlock == NULL) { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256); nss_initlock = PR_NewLock(); nss_crllock = PR_NewLock(); } /* We will actually initialize NSS later */ return 1; }
/** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L956-L968
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_nss_cleanup
void Curl_nss_cleanup(void) { /* This function isn't required to be threadsafe and this is only done * as a safety feature. */ PR_Lock(nss_initlock); if(initialized) { /* Free references to client certificates held in the SSL session cache. * Omitting this hampers destruction of the security module owning * the certificates. */ SSL_ClearSessionCache(); if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) { SECMOD_DestroyModule(mod); mod = NULL; } #ifdef HAVE_NSS_INITCONTEXT NSS_ShutdownContext(nss_context); nss_context = NULL; #else /* HAVE_NSS_INITCONTEXT */ NSS_Shutdown(); #endif } PR_Unlock(nss_initlock); PR_DestroyLock(nss_initlock); PR_DestroyLock(nss_crllock); nss_initlock = NULL; initialized = 0; }
/* Global cleanup */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L987-L1017
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_nss_check_cxn
int Curl_nss_check_cxn(struct connectdata *conn) { int rc; char buf; rc = PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK, PR_SecondsToInterval(1)); if(rc > 0) return 1; /* connection still in place */ if(rc == 0) return 0; /* connection has been closed */ return -1; /* connection status unknown */ }
/* * This function uses SSL_peek 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/nss.c#L1027-L1043
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_nss_close
void Curl_nss_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->handle) { /* NSS closes the socket we previously handed to it, so we must mark it as closed to avoid double close */ fake_sclose(conn->sock[sockindex]); conn->sock[sockindex] = CURL_SOCKET_BAD; if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL)) /* A server might require different authentication based on the * particular path being requested by the client. To support this * scenario, we must ensure that a connection will never reuse the * authentication data from a previous connection. */ SSL_InvalidateSession(connssl->handle); if(connssl->client_nickname != NULL) { free(connssl->client_nickname); connssl->client_nickname = NULL; } /* destroy all NSS objects in order to avoid failure of NSS shutdown */ Curl_llist_destroy(connssl->obj_list, NULL); connssl->obj_list = NULL; connssl->obj_clicert = NULL; PR_Close(connssl->handle); connssl->handle = NULL; } }
/* * This function is called when an SSL connection is closed. */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L1048-L1077
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
Curl_nss_close_all
int Curl_nss_close_all(struct SessionHandle *data) { (void)data; return 0; }
/* * This function is called when the 'data' struct is going away. Close * down everything and free all resources! */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L1083-L1087
4389085c8ce35cff887a4cc18fc47d1133d89ffb
BigWorld-Engine-14.4.1
github_2023
v2v3v4
c
is_nss_error
static bool is_nss_error(CURLcode err) { switch(err) { case CURLE_PEER_FAILED_VERIFICATION: case CURLE_SSL_CACERT: case CURLE_SSL_CERTPROBLEM: case CURLE_SSL_CONNECT_ERROR: case CURLE_SSL_ISSUER_ERROR: return true; default: return false; } }
/* return true if NSS can provide error code (and possibly msg) for the error */
https://github.com/v2v3v4/BigWorld-Engine-14.4.1/blob/4389085c8ce35cff887a4cc18fc47d1133d89ffb/programming/bigworld/third_party/curl/lib/nss.c#L1091-L1104
4389085c8ce35cff887a4cc18fc47d1133d89ffb