S3 Http: Resume a Version-Pinned, Checksum-Verified Download
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.
Downloads an object with a stored FULL_OBJECT SHA-256 checksum in 8 MiB chunks. Start with a private empty cache and run one process. The checkpoint binds region, bucket, key, requested/selected version, ETag, size, checksum, chunk size and final path. On resume it reuses the saved version ID, so a newer current version does not silently replace the original target; null/unversioned objects still need the matching ETag and checksum.
Checks HTTP 206, exact Content-Range/Content-Length, ETag, version and actual bytes before committing each range. Rehashes cached chunks before reuse. Interrupted chunks are redownloaded; interrupted assembly is rebuilt. The assembled file must match the entire object's SHA-256 before final rename. Cached chunk hashes alone are not an S3 checksum of each range. HTTP 200, 412, 416, changed metadata, corrupt cache and checksum failures never promote output.
Use the companion SHA-256 upload to create a suitable object. Absent or COMPOSITE SHA-256 checksums stop explicitly. This fixed-size demonstration supports nonempty objects up to 10,000 chunks (78.125 GiB), with portable offsets beyond 2 GiB. Empty objects use the single checksum download. Larger objects need a suitably adjusted chunk size/checkpoint schema.
Requires s3:GetObject/s3:GetObjectVersion and relevant KMS permissions. Create qa_output; keep the same working directory and settings. Cache and final output must share a filesystem. Allow about twice the object size plus a temporary chunk in disk space. Protect manifests/receipts from other writers and retain them after failure. No automatic object replacement, restoration request, or deletion occurs.
Chilkat B4X Downloads
Dim success As Boolean = False
Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
' 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.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
If success <> True Then
Log("Could not load private S3 credentials.")
Return
End If
stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid access_key.")
Return
End If
stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid secret_key.")
Return
End If
Dim http As ChilkatHttp
http.Initialize("http")
http.AwsAccessKey = credentials.StringOf("access_key")
http.AwsSecretKey = credentials.StringOf("secret_key")
If credentials.HasMember("session_token") = True Then
stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
Log("session_token must be a nonempty string when supplied.")
Return
End If
http.AwsSessionToken = credentials.StringOf("session_token")
End If
' Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
' Set the actual bucket region, not the caller's location.
Dim region As String = "us-west-2"
http.AwsRegion = region
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
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.
Dim bucketName As String = "your-bucket-name"
Dim objectKey As String = "examples/archive.bin"
Dim response As ChilkatHttpResponse
response.Initialize
Dim signer As ChilkatCrypt2
signer.Initialize("signer")
signer.Charset = "utf-8"
signer.HashAlgorithm = "sha256"
signer.EncodingMode = "hexlower"
signer.MacAlgorithm = "hmac"
Dim now As ChilkatDateTime
now.Initialize
Dim timestamp As ChilkatStringBuilder
timestamp.Initialize
Dim canonical As ChilkatStringBuilder
canonical.Initialize
Dim canonicalHeaders As ChilkatStringBuilder
canonicalHeaders.Initialize
Dim signedHeaders As ChilkatStringBuilder
signedHeaders.Initialize
Dim scope As ChilkatStringBuilder
scope.Initialize
Dim stringToSign As ChilkatStringBuilder
stringToSign.Initialize
Dim signingKey As ChilkatStringBuilder
signingKey.Initialize
Dim authorization As ChilkatStringBuilder
authorization.Initialize
Dim url As ChilkatStringBuilder
url.Initialize
Dim query As ChilkatStringBuilder
query.Initialize
Dim number As ChilkatStringBuilder
number.Initialize
Dim host As ChilkatStringBuilder
host.Initialize
Dim uri As ChilkatStringBuilder
uri.Initialize
Dim xml As ChilkatXml
xml.Initialize
Dim amzDate As String
Dim dateStamp As String
Dim payloadHash As String
Dim canonicalHash As String
Dim derivedKey As String
Dim signature As String
Dim replaceCount As Int
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) Then
Log("Use a key without a leading slash or dot path segments for these examples.")
Return
End If
uri.Prepend("/")
Dim versionId As String = ""
Dim etag As String
Dim expectedSize As String
Dim expectedChecksum As String
Dim checksumType As String
Dim returnedVersion As String
Dim files As ChilkatFileAccess
files.Initialize
Dim cacheDir As String = "qa_output/s3-download-cache"
Dim manifestPath As String = "qa_output/s3-download-cache/state.json"
Dim finalPath As String = "qa_output/s3-resumed.bin"
Dim requestedVersionId As String = versionId
Dim state As ChilkatJsonObject
state.Initialize
state.Strict = True
Dim identity As ChilkatJsonObject
identity.Initialize
Dim hasCheckpoint As Boolean = files.FileExists(manifestPath)
If hasCheckpoint = True Then
success = state.LoadFile(manifestPath)
If success <> True Then
Log("Invalid download checkpoint. Preserve the cache.")
Return
End If
stringCompare.SetString(state.StringOf("schema"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("1", True)
If stringMatch4 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("bucket"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual(bucketName, True)
If stringMatch5 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("key"))
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual(objectKey, True)
If stringMatch6 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("region"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual(region, True)
If stringMatch7 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("requestedVersion"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual(requestedVersionId, True)
If stringMatch8 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("finalPath"))
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual(finalPath, True)
If stringMatch9 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
stringCompare.SetString(state.StringOf("chunkSize"))
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("8388608", True)
If stringMatch10 <> True Then
Log("Checkpoint settings differ. Use the original settings or a new empty cache.")
Return
End If
versionId = state.StringOf("versionId")
If state.JsonTypeOf("versionId") <> 1 Then
Log("Checkpoint version ID is invalid.")
Return
End If
End If
query.Clear
stringCompare.SetString(versionId)
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch11 <> True Then
If query.Length > 0 Then
query.Append("&")
End If
query.Append("versionId=")
query.Append(http.UrlEncode(versionId))
End If
http.ClearHeaders
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read system time.")
Return
End If
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 Then
Log("Could not hash payload.")
Return
End If
canonicalHeaders.Clear
signedHeaders.Clear
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("host", host.GetAsString)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-checksum-mode")
canonicalHeaders.Append("x-amz-checksum-mode:")
canonicalHeaders.Append("ENABLED")
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-checksum-mode", "ENABLED")
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-content-sha256", payloadHash)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-date", amzDate)
If credentials.HasMember("session_token") = True Then
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.StringOf("session_token"))
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
End If
canonical.Clear
canonical.Append("HEAD" & Chr(10))
canonical.Append(uri.GetAsString)
canonical.Append(Chr(10))
canonical.Append(query.GetAsString)
canonical.Append(Chr(10))
canonical.Append(canonicalHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(signedHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(payloadHash)
canonicalHash = signer.HashStringENC(canonical.GetAsString)
If signer.LastMethodSuccess <> True Then
Log("Could not hash canonical request.")
Return
End If
scope.Clear
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear
stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
stringToSign.Append(amzDate)
stringToSign.Append(Chr(10))
stringToSign.Append(scope.GetAsString)
stringToSign.Append(Chr(10))
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.StringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.GetAsString)
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC(dateStamp)
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC(region)
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC("s3")
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC("aws4_request")
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
signature = signer.MacStringENC(stringToSign.GetAsString)
If signer.LastMethodSuccess <> True Then
Log("Could not sign request.")
Return
End If
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 Then
url.Append("?")
url.Append(query.GetAsString)
End If
success = http.HttpNoBody("HEAD", url.GetAsString, response)
If (success <> True) Or (response.StatusCode <> 200) Then
Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
' Preserve progress. Inspect full diagnostics privately; do not log secrets.
Return
End If
etag = response.GetHeaderField("ETag")
stringCompare.SetString(etag)
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
If (response.LastMethodSuccess <> True) Or (stringMatch12 = True) Then
Log("Missing required response header ETag.")
Return
End If
expectedSize = response.GetHeaderField("Content-Length")
stringCompare.SetString(expectedSize)
Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
If (response.LastMethodSuccess <> True) Or (stringMatch13 = True) Then
Log("Missing required response header Content-Length.")
Return
End If
returnedVersion = response.GetHeaderField("x-amz-version-id")
If response.LastMethodSuccess <> True Then
returnedVersion = ""
End If
stringCompare.SetString(versionId)
Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch14 = True Then
versionId = returnedVersion
Else
stringCompare.SetString(returnedVersion)
Dim stringMatch15 As Boolean = stringCompare.ContentsEqual(versionId, True)
If stringMatch15 <> True Then
Log("Unexpected object version.")
Return
End If
End If
expectedChecksum = response.GetHeaderField("x-amz-checksum-sha256")
stringCompare.SetString(expectedChecksum)
Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("", True)
If (response.LastMethodSuccess <> True) Or (stringMatch16 = True) Then
Log("Missing required response header x-amz-checksum-sha256.")
Return
End If
checksumType = response.GetHeaderField("x-amz-checksum-type")
stringCompare.SetString(checksumType)
Dim stringMatch17 As Boolean = stringCompare.ContentsEqual("", True)
If (response.LastMethodSuccess <> True) Or (stringMatch17 = True) Then
Log("Missing required response header x-amz-checksum-type.")
Return
End If
stringCompare.SetString(checksumType)
Dim stringMatch18 As Boolean = stringCompare.ContentsEqual("FULL_OBJECT", True)
If stringMatch18 <> True Then
Log("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.")
Return
End If
' Portable decimal long division; no 32-bit byte-offset overflow.
Dim chunkSize As Int = 8388608
Dim chunkCount As Int = 0
Dim remainder As Int = 0
Dim position As Int = 0
Dim sizeText As ChilkatStringBuilder
sizeText.Initialize
Dim decimalDigits As ChilkatStringBuilder
decimalDigits.Initialize
Dim digit As ChilkatStringBuilder
digit.Initialize
sizeText.Append(expectedSize)
decimalDigits.Append("0123456789")
If (sizeText.Length = 0) Or (sizeText.Length > 14) Then
Log("Invalid object size.")
Return
End If
Do While (position < sizeText.Length)
digit.SetString(sizeText.GetRange(position, 1, False))
If decimalDigits.Contains(digit.GetAsString, True) <> True Then
Log("Invalid decimal object size.")
Return
End If
remainder = remainder * 10 + digit.IntValue
chunkCount = chunkCount * 10
Do While (remainder >= chunkSize)
chunkCount = chunkCount + 1
remainder = remainder - chunkSize
Loop
position = position + 1
Loop
If remainder <> 0 Then
chunkCount = chunkCount + 1
End If
If (chunkCount < 1) Or (chunkCount > 10000) Then
Log("Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example.")
Return
End If
success = identity.UpdateString("schema", "1")
If success <> True Then
Log("Could not save schema.")
Return
End If
success = identity.UpdateString("bucket", bucketName)
If success <> True Then
Log("Could not save bucket.")
Return
End If
success = identity.UpdateString("key", objectKey)
If success <> True Then
Log("Could not save key.")
Return
End If
success = identity.UpdateString("region", region)
If success <> True Then
Log("Could not save region.")
Return
End If
success = identity.UpdateString("requestedVersion", requestedVersionId)
If success <> True Then
Log("Could not save requestedVersion.")
Return
End If
success = identity.UpdateString("versionId", versionId)
If success <> True Then
Log("Could not save versionId.")
Return
End If
success = identity.UpdateString("etag", etag)
If success <> True Then
Log("Could not save etag.")
Return
End If
success = identity.UpdateString("size", expectedSize)
If success <> True Then
Log("Could not save size.")
Return
End If
success = identity.UpdateString("checksum", expectedChecksum)
If success <> True Then
Log("Could not save checksum.")
Return
End If
success = identity.UpdateString("finalPath", finalPath)
If success <> True Then
Log("Could not save finalPath.")
Return
End If
success = identity.UpdateString("chunkSize", "8388608")
If success <> True Then
Log("Could not save chunkSize.")
Return
End If
If hasCheckpoint = True Then
stringCompare.SetString(state.StringOf("versionId"))
Dim stringMatch19 As Boolean = stringCompare.ContentsEqual(identity.StringOf("versionId"), True)
If stringMatch19 <> True Then
Log("Object identity changed. Do not mix old cached bytes with this object.")
Return
End If
stringCompare.SetString(state.StringOf("etag"))
Dim stringMatch20 As Boolean = stringCompare.ContentsEqual(identity.StringOf("etag"), True)
If stringMatch20 <> True Then
Log("Object identity changed. Do not mix old cached bytes with this object.")
Return
End If
stringCompare.SetString(state.StringOf("size"))
Dim stringMatch21 As Boolean = stringCompare.ContentsEqual(identity.StringOf("size"), True)
If stringMatch21 <> True Then
Log("Object identity changed. Do not mix old cached bytes with this object.")
Return
End If
stringCompare.SetString(state.StringOf("checksum"))
Dim stringMatch22 As Boolean = stringCompare.ContentsEqual(identity.StringOf("checksum"), True)
If stringMatch22 <> True Then
Log("Object identity changed. Do not mix old cached bytes with this object.")
Return
End If
Else
success = files.DirEnsureExists(cacheDir)
If success <> True Then
Log("Could not create private cache.")
Return
End If
Dim entries As ChilkatDirTree
entries.Initialize
entries.BaseDir = cacheDir
entries.Recurse = False
success = entries.BeginIterate
If (success = True) Or (entries.DoneIterating <> True) Then
Log("First download requires an empty, readable cache directory.")
Return
End If
success = identity.WriteFile("qa_output/s3-download-cache/state.json.tmp")
If success <> True Then
Log("Could not save download identity.")
Return
End If
success = files.FileRename("qa_output/s3-download-cache/state.json.tmp", manifestPath)
If success <> True Then
Log("Checkpoint remains at its temporary path.")
Return
End If
End If
Dim digest As ChilkatCrypt2
digest.Initialize("digest")
digest.HashAlgorithm = "sha256"
digest.EncodingMode = "base64"
If files.FileExists(finalPath) = True Then
Dim existingSize As String = files.FileSizeStr(finalPath)
Dim existingChecksum As String = digest.HashFileENC(finalPath)
stringCompare.SetString(existingSize)
Dim stringMatch23 As Boolean = stringCompare.ContentsEqual(expectedSize, True)
stringCompare.SetString(existingChecksum)
Dim stringMatch24 As Boolean = stringCompare.ContentsEqual(expectedChecksum, True)
If (digest.LastMethodSuccess <> True) Or (stringMatch23 <> True) Or (stringMatch24 <> True) Then
Log("Existing final file does not match; preserve it.")
Return
End If
Log("Object already downloaded and checksum verified.")
Return
End If
digest.EncodingMode = "hexlower"
Dim path As ChilkatStringBuilder
path.Initialize
Dim range As ChilkatStringBuilder
range.Initialize
Dim digits As ChilkatStringBuilder
digits.Initialize
Dim rangeHeader As ChilkatStringBuilder
rangeHeader.Initialize
Dim contentRange As ChilkatStringBuilder
contentRange.Initialize
Dim byteCount As ChilkatStringBuilder
byteCount.Initialize
Dim receipt As ChilkatJsonObject
receipt.Initialize
receipt.Strict = True
Dim received As ChilkatMime
received.Initialize
Dim chunkIndex As Int = 0
Dim byteHigh As Int = 0
Dim byteLow As Int = 0
Dim endHigh As Int
Dim endLow As Int
Dim actualRange As String
Dim actualLength As String
Dim actualEtag As String
Dim actualVersion As String
Dim actualSize As String
Dim actualHash As String
Do While (chunkIndex < chunkCount)
Dim chunkBytes As Int = chunkSize
If (chunkIndex = chunkCount - 1) And (remainder <> 0) Then
chunkBytes = remainder
End If
range.Clear
digits.Clear
digits.AppendInt(byteLow)
If byteHigh > 0 Then
Do While (digits.Length < 9)
digits.Prepend("0")
Loop
range.AppendInt(byteHigh)
End If
range.Append(digits.GetAsString)
range.Append("-")
endHigh = byteHigh
endLow = byteLow + chunkBytes - 1
If endLow >= 1000000000 Then
endLow = endLow - 1000000000
endHigh = endHigh + 1
End If
digits.Clear
digits.AppendInt(endLow)
If endHigh > 0 Then
Do While (digits.Length < 9)
digits.Prepend("0")
Loop
range.AppendInt(endHigh)
End If
range.Append(digits.GetAsString)
Dim rangeKey As String = range.GetAsString
rangeHeader.SetString("bytes=")
rangeHeader.Append(rangeKey)
contentRange.SetString("bytes ")
contentRange.Append(rangeKey)
contentRange.Append("/")
contentRange.Append(expectedSize)
byteCount.Clear
byteCount.AppendInt(chunkBytes)
path.SetString(cacheDir)
path.Append("/chunk-")
path.AppendInt(chunkIndex)
Dim chunkPath As String = path.GetAsString
path.Append(".json")
Dim receiptPath As String = path.GetAsString
path.SetString(chunkPath)
path.Append(".part")
Dim partialPath As String = path.GetAsString
If files.FileExists(chunkPath) = True Then
success = receipt.LoadFile(receiptPath)
If success <> True Then
Log("Cached chunk has no valid receipt. Preserve the cache.")
Return
End If
actualHash = digest.HashFileENC(chunkPath)
stringCompare.SetString(actualHash)
Dim stringMatch25 As Boolean = stringCompare.ContentsEqual(receipt.StringOf("hash"), True)
stringCompare.SetString(receipt.StringOf("range"))
Dim stringMatch26 As Boolean = stringCompare.ContentsEqual(rangeKey, True)
stringCompare.SetString(files.FileSizeStr(chunkPath))
Dim stringMatch27 As Boolean = stringCompare.ContentsEqual(byteCount.GetAsString, True)
If (digest.LastMethodSuccess <> True) Or (stringMatch25 <> True) Or (stringMatch26 <> True) Or (stringMatch27 <> True) Then
Log("Cached chunk failed verification. Remove only this chunk and receipt before retrying.")
Return
End If
Log("Reusing verified chunk: " & chunkIndex)
Else
query.Clear
stringCompare.SetString(versionId)
Dim stringMatch28 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch28 <> True Then
If query.Length > 0 Then
query.Append("&")
End If
query.Append("versionId=")
query.Append(http.UrlEncode(versionId))
End If
http.ClearHeaders
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read system time.")
Return
End If
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 Then
Log("Could not hash payload.")
Return
End If
canonicalHeaders.Clear
signedHeaders.Clear
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("host", host.GetAsString)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("if-match")
canonicalHeaders.Append("if-match:")
canonicalHeaders.Append(etag)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("if-match", etag)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("range")
canonicalHeaders.Append("range:")
canonicalHeaders.Append(rangeHeader.GetAsString)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("range", rangeHeader.GetAsString)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-content-sha256", payloadHash)
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-date", amzDate)
If credentials.HasMember("session_token") = True Then
If signedHeaders.Length > 0 Then
signedHeaders.Append(";")
End If
signedHeaders.Append("x-amz-security-token")
canonicalHeaders.Append("x-amz-security-token:")
canonicalHeaders.Append(credentials.StringOf("session_token"))
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
End If
canonical.Clear
canonical.Append("GET" & Chr(10))
canonical.Append(uri.GetAsString)
canonical.Append(Chr(10))
canonical.Append(query.GetAsString)
canonical.Append(Chr(10))
canonical.Append(canonicalHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(signedHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(payloadHash)
canonicalHash = signer.HashStringENC(canonical.GetAsString)
If signer.LastMethodSuccess <> True Then
Log("Could not hash canonical request.")
Return
End If
scope.Clear
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear
stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
stringToSign.Append(amzDate)
stringToSign.Append(Chr(10))
stringToSign.Append(scope.GetAsString)
stringToSign.Append(Chr(10))
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.StringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.GetAsString)
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC(dateStamp)
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC(region)
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC("s3")
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
derivedKey = signer.MacStringENC("aws4_request")
If signer.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set signing key.")
Return
End If
signature = signer.MacStringENC(stringToSign.GetAsString)
If signer.LastMethodSuccess <> True Then
Log("Could not sign request.")
Return
End If
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 Then
url.Append("?")
url.Append(query.GetAsString)
End If
success = http.Download(url.GetAsString, partialPath)
If (http.LastStatus = 412) Or (http.LastStatus = 416) Then
Log("Object changed or range is invalid. Preserve the cache; do not append.")
Return
End If
If (success <> True) Or (http.LastStatus <> 206) Then
Log("Request failed or returned unexpected HTTP status: " & http.LastStatus)
' Preserve progress. Inspect full diagnostics privately; do not log secrets.
Return
End If
success = received.LoadMime(http.LastResponseHeader)
If success <> True Then
Log("Could not parse range response.")
Return
End If
actualRange = received.GetHeaderField("Content-Range")
stringCompare.SetString(actualRange)
Dim stringMatch29 As Boolean = stringCompare.ContentsEqual("", True)
If (received.LastMethodSuccess <> True) Or (stringMatch29 = True) Then
Log("Missing download header Content-Range.")
Return
End If
actualLength = received.GetHeaderField("Content-Length")
stringCompare.SetString(actualLength)
Dim stringMatch30 As Boolean = stringCompare.ContentsEqual("", True)
If (received.LastMethodSuccess <> True) Or (stringMatch30 = True) Then
Log("Missing download header Content-Length.")
Return
End If
actualEtag = received.GetHeaderField("ETag")
stringCompare.SetString(actualEtag)
Dim stringMatch31 As Boolean = stringCompare.ContentsEqual("", True)
If (received.LastMethodSuccess <> True) Or (stringMatch31 = True) Then
Log("Missing download header ETag.")
Return
End If
stringCompare.SetString(actualRange)
Dim stringMatch32 As Boolean = stringCompare.ContentsEqual(contentRange.GetAsString, True)
stringCompare.SetString(actualLength)
Dim stringMatch33 As Boolean = stringCompare.ContentsEqual(byteCount.GetAsString, True)
stringCompare.SetString(actualEtag)
Dim stringMatch34 As Boolean = stringCompare.ContentsEqual(etag, True)
If (stringMatch32 <> True) Or (stringMatch33 <> True) Or (stringMatch34 <> True) Then
Log("Unexpected range response; no chunk committed.")
Return
End If
stringCompare.SetString(versionId)
Dim stringMatch35 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch35 <> True Then
actualVersion = received.GetHeaderField("x-amz-version-id")
stringCompare.SetString(actualVersion)
Dim stringMatch36 As Boolean = stringCompare.ContentsEqual("", True)
If (received.LastMethodSuccess <> True) Or (stringMatch36 = True) Then
Log("Missing download header x-amz-version-id.")
Return
End If
stringCompare.SetString(actualVersion)
Dim stringMatch37 As Boolean = stringCompare.ContentsEqual(versionId, True)
If stringMatch37 <> True Then
Log("Unexpected returned version.")
Return
End If
End If
actualSize = files.FileSizeStr(partialPath)
stringCompare.SetString(actualSize)
Dim stringMatch38 As Boolean = stringCompare.ContentsEqual(byteCount.GetAsString, True)
If (files.LastMethodSuccess <> True) Or (stringMatch38 <> True) Then
Log("Range byte count mismatch.")
Return
End If
actualHash = digest.HashFileENC(partialPath)
If digest.LastMethodSuccess <> True Then
Log("Could not hash range bytes.")
Return
End If
success = receipt.UpdateString("range", rangeKey)
If success <> True Then
Log("Could not save range.")
Return
End If
success = receipt.UpdateString("hash", actualHash)
If success <> True Then
Log("Could not save hash.")
Return
End If
success = receipt.WriteFile(receiptPath)
If success <> True Then
Log("Could not save chunk receipt.")
Return
End If
success = files.FileRename(partialPath, chunkPath)
If success <> True Then
Log("Could not commit downloaded chunk.")
Return
End If
Log("Downloaded chunk: " & chunkIndex)
End If
byteHigh = endHigh
byteLow = endLow + 1
If byteLow = 1000000000 Then
byteLow = 0
byteHigh = byteHigh + 1
End If
chunkIndex = chunkIndex + 1
Loop
' Cache hashes detect local damage, but only the final stored S3 checksum
' establishes whole-object integrity. A range is not verified by a full hash.
Dim assembledPath As String = "qa_output/s3-download-cache/assembled.part"
Dim assembled As ChilkatFileAccess
assembled.Initialize
success = assembled.OpenForWrite(assembledPath)
If success <> True Then
Log("Could not open assembly file.")
Return
End If
Dim data As ChilkatBinData
data.Initialize
chunkIndex = 0
Do While (chunkIndex < chunkCount)
path.SetString(cacheDir)
path.Append("/chunk-")
path.AppendInt(chunkIndex)
data.Clear
success = data.LoadFile(path.GetAsString)
If success = True Then
success = assembled.FileWriteBd(data, 0, 0)
End If
If success <> True Then
assembled.FileClose
Log("Assembly failed; verified progress is retained.")
Return
End If
chunkIndex = chunkIndex + 1
Loop
assembled.FileClose
actualSize = files.FileSizeStr(assembledPath)
digest.EncodingMode = "base64"
actualHash = digest.HashFileENC(assembledPath)
stringCompare.SetString(actualSize)
Dim stringMatch39 As Boolean = stringCompare.ContentsEqual(expectedSize, True)
stringCompare.SetString(actualHash)
Dim stringMatch40 As Boolean = stringCompare.ContentsEqual(expectedChecksum, True)
If (digest.LastMethodSuccess <> True) Or (stringMatch39 <> True) Or (stringMatch40 <> True) Then
Log("Assembled object checksum/size mismatch; final file not created.")
Return
End If
success = files.FileRename(assembledPath, finalPath)
If success <> True Then
Log("Verified assembly remains in cache; rename failed.")
Return
End If
Log("Resumable download completed and checksum verified. Cache retained for manual cleanup.")