S3 Http: Resume and Recover a Multipart Upload
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.
Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.
Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.
Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.
Lists all uploaded parts and reuses only parts whose SHA-256 and byte count match the local source; mismatched parts are replaced. If ListParts returns NoSuchUpload after a recorded completion attempt, a checksum-enabled HEAD must match the unique upload token, source hash, composite checksum and size before recovery is reported. A missing upload alone is never treated as completion. If another write has replaced the current object, inspect version history manually.
Chilkat Ruby Downloads
require 'chilkat'
success = false
stringCompare = Chilkat::CkStringBuilder.new()
# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
# Load private credentials; never put access keys or session tokens in source.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != true)
print "Could not load private S3 credentials." + "\n";
exit
end
stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
print "Missing or invalid access_key." + "\n";
exit
end
stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
print "Missing or invalid secret_key." + "\n";
exit
end
http = Chilkat::CkHttp.new()
http.put_AwsAccessKey(credentials.stringOf("access_key"))
http.put_AwsSecretKey(credentials.stringOf("secret_key"))
if (credentials.HasMember("session_token") == true)
stringCompare.SetString(credentials.stringOf("session_token"))
stringMatch3 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
print "session_token must be a nonempty string when supplied." + "\n";
exit
end
http.put_AwsSessionToken(credentials.stringOf("session_token"))
end
# Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
# Set the actual bucket region, not the caller's location.
region = "us-west-2"
http.put_AwsRegion(region)
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.put_AwsEndpoint(endpoint.getAsString())
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
# A region redirect is not success. Correct the endpoint and signing region.
bucketName = "your-bucket-name"
objectKey = "examples/archive.bin"
response = Chilkat::CkHttpResponse.new()
signer = Chilkat::CkCrypt2.new()
signer.put_Charset("utf-8")
signer.put_HashAlgorithm("sha256")
signer.put_EncodingMode("hexlower")
signer.put_MacAlgorithm("hmac")
now = Chilkat::CkDateTime.new()
timestamp = Chilkat::CkStringBuilder.new()
canonical = Chilkat::CkStringBuilder.new()
canonicalHeaders = Chilkat::CkStringBuilder.new()
signedHeaders = Chilkat::CkStringBuilder.new()
scope = Chilkat::CkStringBuilder.new()
stringToSign = Chilkat::CkStringBuilder.new()
signingKey = Chilkat::CkStringBuilder.new()
authorization = Chilkat::CkStringBuilder.new()
url = Chilkat::CkStringBuilder.new()
query = Chilkat::CkStringBuilder.new()
number = Chilkat::CkStringBuilder.new()
host = Chilkat::CkStringBuilder.new()
uri = Chilkat::CkStringBuilder.new()
xml = Chilkat::CkXml.new()
host.Append(bucketName)
host.Append(".")
host.Append(endpoint.getAsString())
# Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.urlEncode(objectKey))
replaceCount = uri.ReplaceNoCase("%2f","/")
if ((uri.StartsWith("/",true) == true) or (uri.Contains("/../",true) == true) or (uri.Contains("/./",true) == true))
print "Use a key without a leading slash or dot path segments for these examples." + "\n";
exit
end
uri.Prepend("/")
files = Chilkat::CkFileAccess.new()
filePath = "qa_data/bin/archive.bin"
fileSize = files.fileSizeStr(filePath)
if (files.get_LastMethodSuccess() != true)
print "Could not read source file size." + "\n";
exit
end
digest = Chilkat::CkCrypt2.new()
digest.put_HashAlgorithm("sha256")
digest.put_EncodingMode("hexlower")
sourceHash = digest.hashFileENC(filePath)
if (digest.get_LastMethodSuccess() != true)
print "Could not hash source file." + "\n";
exit
end
digest.put_EncodingMode("base64")
sourceChecksum = digest.hashFileENC(filePath)
if (digest.get_LastMethodSuccess() != true)
print "Could not compute checksum." + "\n";
exit
end
statePath = "qa_output/s3-multipart/state.json"
pendingPath = "qa_output/s3-multipart/completion.json"
receiptPath = "qa_output/s3-multipart/completed.json"
state = Chilkat::CkJsonObject.new()
state.put_Strict(true)
pending = Chilkat::CkJsonObject.new()
pending.put_Strict(true)
success = files.OpenForRead(filePath)
if (success != true)
print "Could not open immutable source file." + "\n";
exit
end
partSize = 8388608
numParts = files.GetNumBlocks(partSize)
if ((numParts < 1) or (numParts > 10000))
print "Use a nonempty source of at most 10,000 fixed 8 MiB parts." + "\n";
exit
end
remoteEtags = Chilkat::CkHashtable.new()
remoteSizes = Chilkat::CkHashtable.new()
remoteChecksums = Chilkat::CkHashtable.new()
partNumbers = Chilkat::CkHashtable.new()
partNumberText = Chilkat::CkStringBuilder.new()
success = state.LoadFile(statePath)
if (success != true)
print "Could not load multipart checkpoint." + "\n";
exit
end
stringCompare.SetString(state.stringOf("schema"))
stringMatch4 = stringCompare.ContentsEqual("1",true)
if (stringMatch4 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("bucket"))
stringMatch5 = stringCompare.ContentsEqual(bucketName,true)
if (stringMatch5 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("key"))
stringMatch6 = stringCompare.ContentsEqual(objectKey,true)
if (stringMatch6 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("region"))
stringMatch7 = stringCompare.ContentsEqual(region,true)
if (stringMatch7 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("filePath"))
stringMatch8 = stringCompare.ContentsEqual(filePath,true)
if (stringMatch8 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("fileSize"))
stringMatch9 = stringCompare.ContentsEqual(fileSize,true)
if (stringMatch9 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("sourceHash"))
stringMatch10 = stringCompare.ContentsEqual(sourceHash,true)
if (stringMatch10 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
stringCompare.SetString(state.stringOf("partSize"))
stringMatch11 = stringCompare.ContentsEqual("8388608",true)
if (stringMatch11 != true)
print "Checkpoint/source identity differs. Do not resume another file or destination." + "\n";
exit
end
uploadId = state.stringOf("uploadId")
uploadToken = state.stringOf("uploadToken")
stringCompare.SetString(uploadId)
stringMatch12 = stringCompare.ContentsEqual("",true)
stringCompare.SetString(uploadToken)
stringMatch13 = stringCompare.ContentsEqual("",true)
if ((stringMatch12 == true) or (stringMatch13 == true) or (state.JsonTypeOf("uploadId") != 1) or (state.JsonTypeOf("uploadToken") != 1))
print "Checkpoint has no upload identity." + "\n";
exit
end
if (files.FileExists(receiptPath) == true)
success = pending.LoadFile(receiptPath)
if (success != true)
print "Invalid completion receipt." + "\n";
exit
end
stringCompare.SetString(pending.stringOf("uploadId"))
stringMatch14 = stringCompare.ContentsEqual(uploadId,true)
stringCompare.SetString(pending.stringOf("sourceHash"))
stringMatch15 = stringCompare.ContentsEqual(sourceHash,true)
if ((stringMatch14 != true) or (stringMatch15 != true))
print "Completion receipt belongs to another upload." + "\n";
exit
end
print "Multipart upload already completed; receipt retained." + "\n";
exit
end
seen = Chilkat::CkHashtable.new()
more = true
page = 0
marker = ""
while (more == true)
if (page == 10000)
print "Page bound reached; results are incomplete." + "\n";
exit
end
page = page + 1
query.Clear()
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("max-parts=")
query.Append(http.urlEncode("1000"))
stringCompare.SetString(marker)
stringMatch16 = stringCompare.ContentsEqual("",true)
if (stringMatch16 != true)
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("part-number-marker=")
query.Append(http.urlEncode(marker))
end
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("uploadId=")
query.Append(http.urlEncode(uploadId))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read system time." + "\n";
exit
end
timestamp.SetString(now.getAsTimestamp(false))
replaceCount = timestamp.Replace("-","")
replaceCount = timestamp.Replace(":","")
amzDate = timestamp.getAsString()
dateStamp = timestamp.getRange(0,8,false)
payloadHash = signer.hashStringENC("")
if (signer.get_LastMethodSuccess() != true)
print "Could not hash payload." + "\n";
exit
end
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.getAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.getAsString())
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-content-sha256",payloadHash)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-date",amzDate)
if (credentials.HasMember("session_token") == true)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.stringOf("session_token"))
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"))
end
canonical.Clear()
canonical.Append("GET\n")
canonical.Append(uri.getAsString())
canonical.Append("\n")
canonical.Append(query.getAsString())
canonical.Append("\n")
canonical.Append(canonicalHeaders.getAsString())
canonical.Append("\n")
canonical.Append(signedHeaders.getAsString())
canonical.Append("\n")
canonical.Append(payloadHash)
canonicalHash = signer.hashStringENC(canonical.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not hash canonical request." + "\n";
exit
end
scope.Clear()
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear()
stringToSign.Append("AWS4-HMAC-SHA256\n")
stringToSign.Append(amzDate)
stringToSign.Append("\n")
stringToSign.Append(scope.getAsString())
stringToSign.Append("\n")
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.stringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.getAsString())
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(dateStamp)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(region)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("s3")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("aws4_request")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
signature = signer.macStringENC(stringToSign.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not sign request." + "\n";
exit
end
authorization.Clear()
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.stringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.getAsString())
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.getAsString())
authorization.Append(", Signature=")
authorization.Append(signature)
http.SetRequestHeader("Authorization",authorization.getAsString())
url.SetString("https://")
url.Append(host.getAsString())
url.Append(uri.getAsString())
if (query.get_Length() > 0)
url.Append("?")
url.Append(query.getAsString())
end
success = http.HttpNoBody("GET",url.getAsString(),response)
if (response.get_StatusCode() == 404)
success = xml.LoadXml(response.bodyStr())
if (success != true)
print "Could not parse missing-upload response." + "\n";
exit
end
stringCompare.SetString(xml.getChildContent("Code"))
stringMatch17 = stringCompare.ContentsEqual("NoSuchUpload",true)
if (stringMatch17 != true)
print "404 was not NoSuchUpload; inspect target bucket/key." + "\n";
exit
end
success = pending.LoadFile(pendingPath)
if (success != true)
print "Upload no longer exists. No valid pending completion record; inspect object state manually." + "\n";
exit
end
stringCompare.SetString(pending.stringOf("uploadId"))
stringMatch18 = stringCompare.ContentsEqual(uploadId,true)
if (stringMatch18 != true)
print "Pending completion does not match this upload." + "\n";
exit
end
stringCompare.SetString(pending.stringOf("sourceHash"))
stringMatch19 = stringCompare.ContentsEqual(sourceHash,true)
if (stringMatch19 != true)
print "Pending completion does not match this upload." + "\n";
exit
end
stringCompare.SetString(pending.stringOf("uploadToken"))
stringMatch20 = stringCompare.ContentsEqual(uploadToken,true)
if (stringMatch20 != true)
print "Pending completion does not match this upload." + "\n";
exit
end
compositeChecksum = pending.stringOf("checksum")
stringCompare.SetString(compositeChecksum)
stringMatch21 = stringCompare.ContentsEqual("",true)
if ((pending.get_LastMethodSuccess() != true) or (stringMatch21 == true))
print "Missing pending checksum." + "\n";
exit
end
query.Clear()
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read system time." + "\n";
exit
end
timestamp.SetString(now.getAsTimestamp(false))
replaceCount = timestamp.Replace("-","")
replaceCount = timestamp.Replace(":","")
amzDate = timestamp.getAsString()
dateStamp = timestamp.getRange(0,8,false)
payloadHash = signer.hashStringENC("")
if (signer.get_LastMethodSuccess() != true)
print "Could not hash payload." + "\n";
exit
end
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.getAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.getAsString())
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-checksum-mode")
canonicalHeaders.Append("x-amz-checksum-mode:")
canonicalHeaders.Append("ENABLED")
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-checksum-mode","ENABLED")
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-content-sha256",payloadHash)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-date",amzDate)
if (credentials.HasMember("session_token") == true)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.stringOf("session_token"))
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"))
end
canonical.Clear()
canonical.Append("HEAD\n")
canonical.Append(uri.getAsString())
canonical.Append("\n")
canonical.Append(query.getAsString())
canonical.Append("\n")
canonical.Append(canonicalHeaders.getAsString())
canonical.Append("\n")
canonical.Append(signedHeaders.getAsString())
canonical.Append("\n")
canonical.Append(payloadHash)
canonicalHash = signer.hashStringENC(canonical.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not hash canonical request." + "\n";
exit
end
scope.Clear()
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear()
stringToSign.Append("AWS4-HMAC-SHA256\n")
stringToSign.Append(amzDate)
stringToSign.Append("\n")
stringToSign.Append(scope.getAsString())
stringToSign.Append("\n")
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.stringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.getAsString())
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(dateStamp)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(region)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("s3")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("aws4_request")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
signature = signer.macStringENC(stringToSign.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not sign request." + "\n";
exit
end
authorization.Clear()
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.stringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.getAsString())
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.getAsString())
authorization.Append(", Signature=")
authorization.Append(signature)
http.SetRequestHeader("Authorization",authorization.getAsString())
url.SetString("https://")
url.Append(host.getAsString())
url.Append(uri.getAsString())
if (query.get_Length() > 0)
url.Append("?")
url.Append(query.getAsString())
end
success = http.HttpNoBody("HEAD",url.getAsString(),response)
if ((success != true) or (response.get_StatusCode() != 200))
print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit
end
stringCompare.SetString(response.getHeaderField("x-amz-meta-upload-token"))
stringMatch22 = stringCompare.ContentsEqual(uploadToken,true)
if (stringMatch22 != true)
print "Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state." + "\n";
exit
end
stringCompare.SetString(response.getHeaderField("x-amz-meta-source-sha256"))
stringMatch23 = stringCompare.ContentsEqual(sourceHash,true)
if (stringMatch23 != true)
print "Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state." + "\n";
exit
end
stringCompare.SetString(response.getHeaderField("x-amz-checksum-sha256"))
stringMatch24 = stringCompare.ContentsEqual(compositeChecksum,true)
if (stringMatch24 != true)
print "Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state." + "\n";
exit
end
stringCompare.SetString(response.getHeaderField("x-amz-checksum-type"))
stringMatch25 = stringCompare.ContentsEqual("COMPOSITE",true)
if (stringMatch25 != true)
print "Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state." + "\n";
exit
end
stringCompare.SetString(response.getHeaderField("Content-Length"))
stringMatch26 = stringCompare.ContentsEqual(fileSize,true)
if (stringMatch26 != true)
print "Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state." + "\n";
exit
end
success = state.UpdateString("compositeChecksum",compositeChecksum)
if (success != true)
print "Could not save compositeChecksum." + "\n";
exit
end
success = state.WriteFile("qa_output/s3-multipart/completed.json.tmp")
if (success != true)
print "Completion succeeded but receipt could not be saved; preserve the checkpoint." + "\n";
exit
end
success = files.FileRename("qa_output/s3-multipart/completed.json.tmp",receiptPath)
if (success != true)
print "Completion receipt remains at its temporary path." + "\n";
exit
end
print "Multipart upload completed and verified." + "\n";
exit
end
if ((success != true) or (response.get_StatusCode() != 200))
print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit
end
success = xml.LoadXml(response.bodyStr())
if (success != true)
print "Invalid XML response." + "\n";
exit
end
stringCompare.SetString(xml.tag())
stringMatch27 = stringCompare.ContentsEqual("ListPartsResult",true)
if (stringMatch27 != true)
print "Unexpected XML result, possibly an embedded S3 error. Inspect privately." + "\n";
exit
end
i = 0
while (i < xml.NumChildrenHavingTag("Part"))
xml.put_I(i)
remoteNumber = xml.GetChildIntValue("Part[i]|PartNumber")
if ((xml.get_LastMethodSuccess() != true) or (remoteNumber < 1) or (remoteNumber > numParts))
print "Unexpected remote part number." + "\n";
exit
end
partNumberText.Clear()
partNumberText.AppendInt(remoteNumber)
if (partNumbers.Contains(partNumberText.getAsString()) == true)
print "Duplicate remote part number." + "\n";
exit
end
success = partNumbers.AddStr(partNumberText.getAsString(),"seen")
if (success != true)
print "Could not track remote part." + "\n";
exit
end
item = xml.getChildContent("Part[i]|ETag")
stringCompare.SetString(item)
stringMatch28 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch28 == true))
print "Missing required Part[i]|ETag." + "\n";
exit
end
success = remoteEtags.AddStr(partNumberText.getAsString(),item)
if (success != true)
print "Could not retain part ETag." + "\n";
exit
end
item = xml.getChildContent("Part[i]|Size")
stringCompare.SetString(item)
stringMatch29 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch29 == true))
print "Missing required Part[i]|Size." + "\n";
exit
end
success = remoteSizes.AddStr(partNumberText.getAsString(),item)
if (success != true)
print "Could not retain part size." + "\n";
exit
end
item = xml.getChildContent("Part[i]|ChecksumSHA256")
if (xml.get_LastMethodSuccess() == true)
success = remoteChecksums.AddStr(partNumberText.getAsString(),item)
if (success != true)
print "Could not retain part checksum." + "\n";
exit
end
end
i = i + 1
end
truncated = xml.getChildContent("IsTruncated")
stringCompare.SetString(truncated)
stringMatch30 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch30 == true))
print "Missing required IsTruncated." + "\n";
exit
end
stringCompare.SetString(truncated)
stringMatch31 = stringCompare.ContentsEqual("true",true)
stringCompare.SetString(truncated)
stringMatch32 = stringCompare.ContentsEqual("false",true)
if ((stringMatch31 != true) and (stringMatch32 != true))
print "Invalid IsTruncated; results are incomplete." + "\n";
exit
end
more = false
stringCompare.SetString(truncated)
stringMatch33 = stringCompare.ContentsEqual("true",true)
if (stringMatch33 == true)
marker = xml.getChildContent("NextPartNumberMarker")
stringCompare.SetString(marker)
stringMatch34 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch34 == true))
print "Missing required NextPartNumberMarker." + "\n";
exit
end
if (seen.Contains(marker) == true)
print "Repeated pagination marker; results are incomplete." + "\n";
exit
end
success = seen.AddStr(marker,"seen")
if (success != true)
print "Could not track marker." + "\n";
exit
end
more = true
end
end
part = Chilkat::CkBinData.new()
concatenatedDigests = Chilkat::CkBinData.new()
completion = Chilkat::CkXml.new()
completion.put_Tag("CompleteMultipartUpload")
completion.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/")
partIndex = 0
while (partIndex < numParts)
part.Clear()
success = files.ReadBlockBd(partIndex,partSize,part)
if (success != true)
print "Could not read source part; preserve checkpoint." + "\n";
exit
end
if ((part.get_NumBytes() == 0) or ((partIndex < numParts - 1) and (part.get_NumBytes() != partSize)))
print "Source changed or part read was incomplete." + "\n";
exit
end
partChecksum = digest.hashBdENC(part)
if (digest.get_LastMethodSuccess() != true)
print "Could not checksum part." + "\n";
exit
end
partHash = signer.hashBdENC(part)
if (signer.get_LastMethodSuccess() != true)
print "Could not hash part." + "\n";
exit
end
success = concatenatedDigests.AppendEncoded(partChecksum,"base64")
if (success != true)
print "Could not accumulate part digests." + "\n";
exit
end
partNumberText.Clear()
partNumberText.AppendInt(partIndex + 1)
number.Clear()
number.AppendInt(part.get_NumBytes())
sizeText = number.getAsString()
partNumberKey = partNumberText.getAsString()
reuse = false
partEtag = ""
if (remoteChecksums.Contains(partNumberKey) == true)
stringCompare.SetString(remoteChecksums.lookupStr(partNumberKey))
stringMatch35 = stringCompare.ContentsEqual(partChecksum,true)
stringCompare.SetString(remoteSizes.lookupStr(partNumberKey))
stringMatch36 = stringCompare.ContentsEqual(sizeText,true)
if ((stringMatch35 == true) and (stringMatch36 == true))
partEtag = remoteEtags.lookupStr(partNumberKey)
stringCompare.SetString(partEtag)
stringMatch37 = stringCompare.ContentsEqual("",true)
if ((remoteEtags.get_LastMethodSuccess() == true) and (stringMatch37 != true))
reuse = true
end
end
end
if (reuse != true)
query.Clear()
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("partNumber=")
query.Append(http.urlEncode(partNumberText.getAsString()))
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("uploadId=")
query.Append(http.urlEncode(uploadId))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read system time." + "\n";
exit
end
timestamp.SetString(now.getAsTimestamp(false))
replaceCount = timestamp.Replace("-","")
replaceCount = timestamp.Replace(":","")
amzDate = timestamp.getAsString()
dateStamp = timestamp.getRange(0,8,false)
payloadHash = partHash
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.getAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.getAsString())
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-checksum-sha256")
canonicalHeaders.Append("x-amz-checksum-sha256:")
canonicalHeaders.Append(partChecksum)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-checksum-sha256",partChecksum)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-content-sha256",payloadHash)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-date",amzDate)
if (credentials.HasMember("session_token") == true)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.stringOf("session_token"))
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"))
end
canonical.Clear()
canonical.Append("PUT\n")
canonical.Append(uri.getAsString())
canonical.Append("\n")
canonical.Append(query.getAsString())
canonical.Append("\n")
canonical.Append(canonicalHeaders.getAsString())
canonical.Append("\n")
canonical.Append(signedHeaders.getAsString())
canonical.Append("\n")
canonical.Append(payloadHash)
canonicalHash = signer.hashStringENC(canonical.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not hash canonical request." + "\n";
exit
end
scope.Clear()
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear()
stringToSign.Append("AWS4-HMAC-SHA256\n")
stringToSign.Append(amzDate)
stringToSign.Append("\n")
stringToSign.Append(scope.getAsString())
stringToSign.Append("\n")
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.stringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.getAsString())
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(dateStamp)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(region)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("s3")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("aws4_request")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
signature = signer.macStringENC(stringToSign.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not sign request." + "\n";
exit
end
authorization.Clear()
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.stringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.getAsString())
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.getAsString())
authorization.Append(", Signature=")
authorization.Append(signature)
http.SetRequestHeader("Authorization",authorization.getAsString())
url.SetString("https://")
url.Append(host.getAsString())
url.Append(uri.getAsString())
if (query.get_Length() > 0)
url.Append("?")
url.Append(query.getAsString())
end
success = http.HttpBd("PUT",url.getAsString(),part,"application/octet-stream",response)
if ((success != true) or (response.get_StatusCode() != 200))
print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit
end
confirmed = response.getHeaderField("x-amz-checksum-sha256")
stringCompare.SetString(confirmed)
stringMatch38 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch38 == true))
print "Missing required response header x-amz-checksum-sha256." + "\n";
exit
end
stringCompare.SetString(confirmed)
stringMatch39 = stringCompare.ContentsEqual(partChecksum,true)
if (stringMatch39 != true)
print "Part checksum mismatch; preserve checkpoint." + "\n";
exit
end
partEtag = response.getHeaderField("ETag")
stringCompare.SetString(partEtag)
stringMatch40 = stringCompare.ContentsEqual("",true)
if ((response.get_LastMethodSuccess() != true) or (stringMatch40 == true))
print "Missing required response header ETag." + "\n";
exit
end
else
print "Reusing verified remote part: " + partNumberText.getAsString() + "\n";
end
completion.put_I(partIndex)
completion.UpdateChildContent("Part[i]|PartNumber",partNumberText.getAsString())
completion.UpdateChildContent("Part[i]|ETag",partEtag)
completion.UpdateChildContent("Part[i]|ChecksumSHA256",partChecksum)
partIndex = partIndex + 1
end
files.FileClose()
# Recheck the entire immutable source before committing its parts.
finalSourceHash = signer.hashFileENC(filePath)
stringCompare.SetString(finalSourceHash)
stringMatch41 = stringCompare.ContentsEqual(sourceHash,true)
if ((signer.get_LastMethodSuccess() != true) or (stringMatch41 != true))
print "Source changed; completion was not sent." + "\n";
exit
end
compositeChecksum = digest.hashBdENC(concatenatedDigests)
if (digest.get_LastMethodSuccess() != true)
print "Could not compute composite checksum." + "\n";
exit
end
number.SetString(compositeChecksum)
number.Append("-")
number.AppendInt(numParts)
compositeChecksum = number.getAsString()
success = pending.UpdateString("uploadId",uploadId)
if (success != true)
print "Could not save uploadId." + "\n";
exit
end
success = pending.UpdateString("sourceHash",sourceHash)
if (success != true)
print "Could not save sourceHash." + "\n";
exit
end
success = pending.UpdateString("uploadToken",uploadToken)
if (success != true)
print "Could not save uploadToken." + "\n";
exit
end
success = pending.UpdateString("checksum",compositeChecksum)
if (success != true)
print "Could not save checksum." + "\n";
exit
end
success = pending.WriteFile(pendingPath)
if (success != true)
print "Could not save completion recovery record." + "\n";
exit
end
requestBody = completion.getXml()
query.Clear()
if (query.get_Length() > 0)
query.Append("&")
end
query.Append("uploadId=")
query.Append(http.urlEncode(uploadId))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != true)
print "Could not read system time." + "\n";
exit
end
timestamp.SetString(now.getAsTimestamp(false))
replaceCount = timestamp.Replace("-","")
replaceCount = timestamp.Replace(":","")
amzDate = timestamp.getAsString()
dateStamp = timestamp.getRange(0,8,false)
payloadHash = signer.hashStringENC(requestBody)
if (signer.get_LastMethodSuccess() != true)
print "Could not hash payload." + "\n";
exit
end
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.getAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.getAsString())
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-checksum-type")
canonicalHeaders.Append("x-amz-checksum-type:")
canonicalHeaders.Append("COMPOSITE")
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-checksum-type","COMPOSITE")
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-content-sha256",payloadHash)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-date",amzDate)
if (credentials.HasMember("session_token") == true)
if (signedHeaders.get_Length() > 0)
signedHeaders.Append(";")
end
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.stringOf("session_token"))
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"))
end
canonical.Clear()
canonical.Append("POST\n")
canonical.Append(uri.getAsString())
canonical.Append("\n")
canonical.Append(query.getAsString())
canonical.Append("\n")
canonical.Append(canonicalHeaders.getAsString())
canonical.Append("\n")
canonical.Append(signedHeaders.getAsString())
canonical.Append("\n")
canonical.Append(payloadHash)
canonicalHash = signer.hashStringENC(canonical.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not hash canonical request." + "\n";
exit
end
scope.Clear()
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear()
stringToSign.Append("AWS4-HMAC-SHA256\n")
stringToSign.Append(amzDate)
stringToSign.Append("\n")
stringToSign.Append(scope.getAsString())
stringToSign.Append("\n")
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.stringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.getAsString())
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(dateStamp)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC(region)
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("s3")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
derivedKey = signer.macStringENC("aws4_request")
if (signer.get_LastMethodSuccess() != true)
print "Could not derive signing key." + "\n";
exit
end
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != true)
print "Could not set signing key." + "\n";
exit
end
signature = signer.macStringENC(stringToSign.getAsString())
if (signer.get_LastMethodSuccess() != true)
print "Could not sign request." + "\n";
exit
end
authorization.Clear()
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.stringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.getAsString())
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.getAsString())
authorization.Append(", Signature=")
authorization.Append(signature)
http.SetRequestHeader("Authorization",authorization.getAsString())
url.SetString("https://")
url.Append(host.getAsString())
url.Append(uri.getAsString())
if (query.get_Length() > 0)
url.Append("?")
url.Append(query.getAsString())
end
success = http.HttpStr("POST",url.getAsString(),requestBody,"utf-8","application/xml",response)
if ((success != true) or (response.get_StatusCode() != 200))
print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
exit
end
success = xml.LoadXml(response.bodyStr())
if (success != true)
print "Invalid XML response." + "\n";
exit
end
stringCompare.SetString(xml.tag())
stringMatch42 = stringCompare.ContentsEqual("CompleteMultipartUploadResult",true)
if (stringMatch42 != true)
print "Unexpected XML result, possibly an embedded S3 error. Inspect privately." + "\n";
exit
end
confirmed = xml.getChildContent("ChecksumSHA256")
stringCompare.SetString(confirmed)
stringMatch43 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch43 == true))
print "Missing required ChecksumSHA256." + "\n";
exit
end
stringCompare.SetString(confirmed)
stringMatch44 = stringCompare.ContentsEqual(compositeChecksum,true)
if (stringMatch44 != true)
print "Completion checksum differs; preserve checkpoint and inspect object." + "\n";
exit
end
success = state.UpdateString("compositeChecksum",compositeChecksum)
if (success != true)
print "Could not save compositeChecksum." + "\n";
exit
end
success = state.WriteFile("qa_output/s3-multipart/completed.json.tmp")
if (success != true)
print "Completion succeeded but receipt could not be saved; preserve the checkpoint." + "\n";
exit
end
success = files.FileRename("qa_output/s3-multipart/completed.json.tmp",receiptPath)
if (success != true)
print "Completion receipt remains at its temporary path." + "\n";
exit
end
print "Multipart upload completed and verified." + "\n";