S3 Http: Multipart Upload with Checksums and Checkpoint
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.
Starts, transfers and completes one upload. Saves state before parts and a pending completion record before completion. Run the resume companion after interruptions; do not rerun start against an existing cache. Metadata binds an uncertain completion to a random upload identity.
Chilkat Python Downloads
import sys
import chilkat2
success = False
stringCompare = chilkat2.StringBuilder()
# 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 = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != True):
print("Could not load private S3 credentials.")
sys.exit()
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.")
sys.exit()
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.")
sys.exit()
http = chilkat2.Http()
http.AwsAccessKey = credentials.StringOf("access_key")
http.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.")
sys.exit()
http.AwsSessionToken = credentials.StringOf("session_token")
# 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.AwsRegion = region
endpoint = chilkat2.StringBuilder()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.AwsEndpoint = endpoint.GetAsString()
http.RequireSslCertVerify = True
http.FollowRedirects = False
# A region redirect is not success. Correct the endpoint and signing region.
bucketName = "your-bucket-name"
objectKey = "examples/archive.bin"
response = chilkat2.HttpResponse()
signer = chilkat2.Crypt2()
signer.Charset = "utf-8"
signer.HashAlgorithm = "sha256"
signer.EncodingMode = "hexlower"
signer.MacAlgorithm = "hmac"
now = chilkat2.CkDateTime()
timestamp = chilkat2.StringBuilder()
canonical = chilkat2.StringBuilder()
canonicalHeaders = chilkat2.StringBuilder()
signedHeaders = chilkat2.StringBuilder()
scope = chilkat2.StringBuilder()
stringToSign = chilkat2.StringBuilder()
signingKey = chilkat2.StringBuilder()
authorization = chilkat2.StringBuilder()
url = chilkat2.StringBuilder()
query = chilkat2.StringBuilder()
number = chilkat2.StringBuilder()
host = chilkat2.StringBuilder()
uri = chilkat2.StringBuilder()
xml = chilkat2.Xml()
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.")
sys.exit()
uri.Prepend("/")
files = chilkat2.FileAccess()
filePath = "qa_data/bin/archive.bin"
fileSize = files.FileSizeStr(filePath)
if (files.LastMethodSuccess != True):
print("Could not read source file size.")
sys.exit()
digest = chilkat2.Crypt2()
digest.HashAlgorithm = "sha256"
digest.EncodingMode = "hexlower"
sourceHash = digest.HashFileENC(filePath)
if (digest.LastMethodSuccess != True):
print("Could not hash source file.")
sys.exit()
digest.EncodingMode = "base64"
sourceChecksum = digest.HashFileENC(filePath)
if (digest.LastMethodSuccess != True):
print("Could not compute checksum.")
sys.exit()
cacheDir = "qa_output/s3-multipart"
statePath = "qa_output/s3-multipart/state.json"
pendingPath = "qa_output/s3-multipart/completion.json"
receiptPath = "qa_output/s3-multipart/completed.json"
state = chilkat2.JsonObject()
state.Strict = True
pending = chilkat2.JsonObject()
pending.Strict = True
success = files.OpenForRead(filePath)
if (success != True):
print("Could not open immutable source file.")
sys.exit()
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.")
sys.exit()
remoteEtags = chilkat2.Hashtable()
remoteSizes = chilkat2.Hashtable()
remoteChecksums = chilkat2.Hashtable()
partNumbers = chilkat2.Hashtable()
partNumberText = chilkat2.StringBuilder()
success = files.DirEnsureExists(cacheDir)
if (success != True):
print("Could not create private checkpoint directory.")
sys.exit()
entries = chilkat2.DirTree()
entries.BaseDir = cacheDir
entries.Recurse = False
success = entries.BeginIterate()
if ((success == True) or (entries.DoneIterating != True)):
print("Start requires an empty checkpoint directory; use resume for an existing upload.")
sys.exit()
random = chilkat2.Prng()
uploadToken = random.GenRandom(16,"hex")
if (random.LastMethodSuccess != True):
print("Could not create upload identity.")
sys.exit()
query.Clear()
if (query.Length > 0):
query.Append("&")
query.Append("uploads=")
query.Append(http.UrlEncode(""))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read system time.")
sys.exit()
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.LastMethodSuccess != True):
print("Could not hash payload.")
sys.exit()
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.GetAsString())
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("x-amz-checksum-algorithm")
canonicalHeaders.Append("x-amz-checksum-algorithm:")
canonicalHeaders.Append("SHA256")
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-checksum-algorithm","SHA256")
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-date",amzDate)
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("x-amz-meta-source-sha256")
canonicalHeaders.Append("x-amz-meta-source-sha256:")
canonicalHeaders.Append(sourceHash)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-meta-source-sha256",sourceHash)
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("x-amz-meta-upload-token")
canonicalHeaders.Append("x-amz-meta-upload-token:")
canonicalHeaders.Append(uploadToken)
canonicalHeaders.Append("\n")
http.SetRequestHeader("x-amz-meta-upload-token",uploadToken)
if (credentials.HasMember("session_token") == True):
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
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"))
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.LastMethodSuccess != True):
print("Could not hash canonical request.")
sys.exit()
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.")
sys.exit()
derivedKey = signer.MacStringENC(dateStamp)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC(region)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("s3")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("aws4_request")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
signature = signer.MacStringENC(stringToSign.GetAsString())
if (signer.LastMethodSuccess != True):
print("Could not sign request.")
sys.exit()
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.Length > 0):
url.Append("?")
url.Append(query.GetAsString())
success = http.HttpNoBody("POST",url.GetAsString(),response)
if ((success != True) or (response.StatusCode != 200)):
print("Request failed or returned unexpected HTTP status: " + str(response.StatusCode))
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
sys.exit()
success = xml.LoadXml(response.BodyStr)
if (success != True):
print("Invalid XML response.")
sys.exit()
stringCompare.SetString(xml.Tag)
stringMatch4 = stringCompare.ContentsEqual("InitiateMultipartUploadResult",True)
if (stringMatch4 != True):
print("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
sys.exit()
uploadId = xml.GetChildContent("UploadId")
stringCompare.SetString(uploadId)
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch5 == True)):
print("Missing required UploadId.")
sys.exit()
print("Created upload ID: " + uploadId)
# Save the upload ID before sending parts. If saving fails, retain the printed ID.
success = state.UpdateString("schema","1")
if (success != True):
print("Could not save schema.")
sys.exit()
success = state.UpdateString("bucket",bucketName)
if (success != True):
print("Could not save bucket.")
sys.exit()
success = state.UpdateString("key",objectKey)
if (success != True):
print("Could not save key.")
sys.exit()
success = state.UpdateString("region",region)
if (success != True):
print("Could not save region.")
sys.exit()
success = state.UpdateString("filePath",filePath)
if (success != True):
print("Could not save filePath.")
sys.exit()
success = state.UpdateString("fileSize",fileSize)
if (success != True):
print("Could not save fileSize.")
sys.exit()
success = state.UpdateString("sourceHash",sourceHash)
if (success != True):
print("Could not save sourceHash.")
sys.exit()
success = state.UpdateString("partSize","8388608")
if (success != True):
print("Could not save partSize.")
sys.exit()
success = state.UpdateString("uploadId",uploadId)
if (success != True):
print("Could not save uploadId.")
sys.exit()
success = state.UpdateString("uploadToken",uploadToken)
if (success != True):
print("Could not save uploadToken.")
sys.exit()
success = state.WriteFile("qa_output/s3-multipart/state.json.tmp")
if (success != True):
print("Upload was initiated but checkpoint could not be saved; retain its ID.")
sys.exit()
success = files.FileRename("qa_output/s3-multipart/state.json.tmp",statePath)
if (success != True):
print("Checkpoint rename failed; preserve the temporary checkpoint and upload ID.")
sys.exit()
part = chilkat2.BinData()
concatenatedDigests = chilkat2.BinData()
completion = chilkat2.Xml()
completion.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.")
sys.exit()
if ((part.NumBytes == 0) or ((partIndex < numParts - 1) and (part.NumBytes != partSize))):
print("Source changed or part read was incomplete.")
sys.exit()
partChecksum = digest.HashBdENC(part)
if (digest.LastMethodSuccess != True):
print("Could not checksum part.")
sys.exit()
partHash = signer.HashBdENC(part)
if (signer.LastMethodSuccess != True):
print("Could not hash part.")
sys.exit()
success = concatenatedDigests.AppendEncoded(partChecksum,"base64")
if (success != True):
print("Could not accumulate part digests.")
sys.exit()
partNumberText.Clear()
partNumberText.AppendInt(partIndex + 1)
number.Clear()
number.AppendInt(part.NumBytes)
sizeText = number.GetAsString()
partNumberKey = partNumberText.GetAsString()
reuse = False
partEtag = ""
if (remoteChecksums.Contains(partNumberKey) == True):
stringCompare.SetString(remoteChecksums.LookupStr(partNumberKey))
stringMatch6 = stringCompare.ContentsEqual(partChecksum,True)
stringCompare.SetString(remoteSizes.LookupStr(partNumberKey))
stringMatch7 = stringCompare.ContentsEqual(sizeText,True)
if ((stringMatch6 == True) and (stringMatch7 == True)):
partEtag = remoteEtags.LookupStr(partNumberKey)
stringCompare.SetString(partEtag)
stringMatch8 = stringCompare.ContentsEqual("",True)
if ((remoteEtags.LastMethodSuccess == True) and (stringMatch8 != True)):
reuse = True
if (reuse != True):
query.Clear()
if (query.Length > 0):
query.Append("&")
query.Append("partNumber=")
query.Append(http.UrlEncode(partNumberText.GetAsString()))
if (query.Length > 0):
query.Append("&")
query.Append("uploadId=")
query.Append(http.UrlEncode(uploadId))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read system time.")
sys.exit()
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.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.GetAsString())
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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"))
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.LastMethodSuccess != True):
print("Could not hash canonical request.")
sys.exit()
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.")
sys.exit()
derivedKey = signer.MacStringENC(dateStamp)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC(region)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("s3")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("aws4_request")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
signature = signer.MacStringENC(stringToSign.GetAsString())
if (signer.LastMethodSuccess != True):
print("Could not sign request.")
sys.exit()
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.Length > 0):
url.Append("?")
url.Append(query.GetAsString())
success = http.HttpBd("PUT",url.GetAsString(),part,"application/octet-stream",response)
if ((success != True) or (response.StatusCode != 200)):
print("Request failed or returned unexpected HTTP status: " + str(response.StatusCode))
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
sys.exit()
confirmed = response.GetHeaderField("x-amz-checksum-sha256")
stringCompare.SetString(confirmed)
stringMatch9 = stringCompare.ContentsEqual("",True)
if ((response.LastMethodSuccess != True) or (stringMatch9 == True)):
print("Missing required response header x-amz-checksum-sha256.")
sys.exit()
stringCompare.SetString(confirmed)
stringMatch10 = stringCompare.ContentsEqual(partChecksum,True)
if (stringMatch10 != True):
print("Part checksum mismatch; preserve checkpoint.")
sys.exit()
partEtag = response.GetHeaderField("ETag")
stringCompare.SetString(partEtag)
stringMatch11 = stringCompare.ContentsEqual("",True)
if ((response.LastMethodSuccess != True) or (stringMatch11 == True)):
print("Missing required response header ETag.")
sys.exit()
else:
print("Reusing verified remote part: " + partNumberText.GetAsString())
completion.I = partIndex
completion.UpdateChildContent("Part[i]|PartNumber",partNumberText.GetAsString())
completion.UpdateChildContent("Part[i]|ETag",partEtag)
completion.UpdateChildContent("Part[i]|ChecksumSHA256",partChecksum)
partIndex = partIndex + 1
files.FileClose()
# Recheck the entire immutable source before committing its parts.
finalSourceHash = signer.HashFileENC(filePath)
stringCompare.SetString(finalSourceHash)
stringMatch12 = stringCompare.ContentsEqual(sourceHash,True)
if ((signer.LastMethodSuccess != True) or (stringMatch12 != True)):
print("Source changed; completion was not sent.")
sys.exit()
compositeChecksum = digest.HashBdENC(concatenatedDigests)
if (digest.LastMethodSuccess != True):
print("Could not compute composite checksum.")
sys.exit()
number.SetString(compositeChecksum)
number.Append("-")
number.AppendInt(numParts)
compositeChecksum = number.GetAsString()
success = pending.UpdateString("uploadId",uploadId)
if (success != True):
print("Could not save uploadId.")
sys.exit()
success = pending.UpdateString("sourceHash",sourceHash)
if (success != True):
print("Could not save sourceHash.")
sys.exit()
success = pending.UpdateString("uploadToken",uploadToken)
if (success != True):
print("Could not save uploadToken.")
sys.exit()
success = pending.UpdateString("checksum",compositeChecksum)
if (success != True):
print("Could not save checksum.")
sys.exit()
success = pending.WriteFile(pendingPath)
if (success != True):
print("Could not save completion recovery record.")
sys.exit()
requestBody = completion.GetXml()
query.Clear()
if (query.Length > 0):
query.Append("&")
query.Append("uploadId=")
query.Append(http.UrlEncode(uploadId))
http.ClearHeaders()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read system time.")
sys.exit()
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.LastMethodSuccess != True):
print("Could not hash payload.")
sys.exit()
canonicalHeaders.Clear()
signedHeaders.Clear()
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString())
canonicalHeaders.Append("\n")
http.SetRequestHeader("host",host.GetAsString())
if (signedHeaders.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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.Length > 0):
signedHeaders.Append(";")
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"))
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.LastMethodSuccess != True):
print("Could not hash canonical request.")
sys.exit()
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.")
sys.exit()
derivedKey = signer.MacStringENC(dateStamp)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC(region)
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("s3")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
derivedKey = signer.MacStringENC("aws4_request")
if (signer.LastMethodSuccess != True):
print("Could not derive signing key.")
sys.exit()
success = signer.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
print("Could not set signing key.")
sys.exit()
signature = signer.MacStringENC(stringToSign.GetAsString())
if (signer.LastMethodSuccess != True):
print("Could not sign request.")
sys.exit()
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.Length > 0):
url.Append("?")
url.Append(query.GetAsString())
success = http.HttpStr("POST",url.GetAsString(),requestBody,"utf-8","application/xml",response)
if ((success != True) or (response.StatusCode != 200)):
print("Request failed or returned unexpected HTTP status: " + str(response.StatusCode))
# Preserve progress. Inspect full diagnostics privately; do not log secrets.
sys.exit()
success = xml.LoadXml(response.BodyStr)
if (success != True):
print("Invalid XML response.")
sys.exit()
stringCompare.SetString(xml.Tag)
stringMatch13 = stringCompare.ContentsEqual("CompleteMultipartUploadResult",True)
if (stringMatch13 != True):
print("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
sys.exit()
confirmed = xml.GetChildContent("ChecksumSHA256")
stringCompare.SetString(confirmed)
stringMatch14 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch14 == True)):
print("Missing required ChecksumSHA256.")
sys.exit()
stringCompare.SetString(confirmed)
stringMatch15 = stringCompare.ContentsEqual(compositeChecksum,True)
if (stringMatch15 != True):
print("Completion checksum differs; preserve checkpoint and inspect object.")
sys.exit()
success = state.UpdateString("compositeChecksum",compositeChecksum)
if (success != True):
print("Could not save compositeChecksum.")
sys.exit()
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.")
sys.exit()
success = files.FileRename("qa_output/s3-multipart/completed.json.tmp",receiptPath)
if (success != True):
print("Completion receipt remains at its temporary path.")
sys.exit()
print("Multipart upload completed and verified.")