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 AutoIt Downloads
Local $bSuccess = False
$oStringCompare = ObjCreate("Chilkat.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.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/s3.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load private S3 credentials." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("access_key"))
Local $bStringMatch1 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bStringMatch1 = True)) Then
ConsoleWrite("Missing or invalid access_key." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bStringMatch2 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bStringMatch2 = True)) Then
ConsoleWrite("Missing or invalid secret_key." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AwsAccessKey = $oCredentials.StringOf("access_key")
$oHttp.AwsSecretKey = $oCredentials.StringOf("secret_key")
If ($oCredentials.HasMember("session_token") = True) Then
$oStringCompare.SetString($oCredentials.StringOf("session_token"))
Local $bStringMatch3 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("session_token") <> 1) Or ($bStringMatch3 = True)) Then
ConsoleWrite("session_token must be a nonempty string when supplied." & @CRLF)
Exit
EndIf
$oHttp.AwsSessionToken = $oCredentials.StringOf("session_token")
EndIf
; Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
; Set the actual bucket region, not the caller's location.
Local $sRegion = "us-west-2"
$oHttp.AwsRegion = $sRegion
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("s3.")
$oEndpoint.Append($sRegion)
$oEndpoint.Append(".amazonaws.com")
$oHttp.AwsEndpoint = $oEndpoint.GetAsString()
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
; A region redirect is not success. Correct the endpoint and signing region.
Local $sBucketName = "your-bucket-name"
Local $sObjectKey = "examples/archive.bin"
$oResponse = ObjCreate("Chilkat.HttpResponse")
$oSigner = ObjCreate("Chilkat.Crypt2")
$oSigner.Charset = "utf-8"
$oSigner.HashAlgorithm = "sha256"
$oSigner.EncodingMode = "hexlower"
$oSigner.MacAlgorithm = "hmac"
$oNow = ObjCreate("Chilkat.CkDateTime")
$oTimestamp = ObjCreate("Chilkat.StringBuilder")
$oCanonical = ObjCreate("Chilkat.StringBuilder")
$oCanonicalHeaders = ObjCreate("Chilkat.StringBuilder")
$oSignedHeaders = ObjCreate("Chilkat.StringBuilder")
$oScope = ObjCreate("Chilkat.StringBuilder")
$oStringToSign = ObjCreate("Chilkat.StringBuilder")
$oSigningKey = ObjCreate("Chilkat.StringBuilder")
$oAuthorization = ObjCreate("Chilkat.StringBuilder")
$oUrl = ObjCreate("Chilkat.StringBuilder")
$oQuery = ObjCreate("Chilkat.StringBuilder")
$oNumber = ObjCreate("Chilkat.StringBuilder")
$oHost = ObjCreate("Chilkat.StringBuilder")
$oUri = ObjCreate("Chilkat.StringBuilder")
$oXml = ObjCreate("Chilkat.Xml")
Local $sAmzDate
Local $sDateStamp
Local $sPayloadHash
Local $sCanonicalHash
Local $sDerivedKey
Local $signature
Local $iReplaceCount
$oHost.Append($sBucketName)
$oHost.Append(".")
$oHost.Append($oEndpoint.GetAsString())
; Encode the original key exactly once, preserving S3 path separators.
$oUri.SetString($oHttp.UrlEncode($sObjectKey))
$iReplaceCount = $oUri.ReplaceNoCase("%2f","/")
If (($oUri.StartsWith("/",True) = True) Or ($oUri.Contains("/../",True) = True) Or ($oUri.Contains("/./",True) = True)) Then
ConsoleWrite("Use a key without a leading slash or dot path segments for these examples." & @CRLF)
Exit
EndIf
$oUri.Prepend("/")
Local $sVersionId = ""
Local $sEtag
Local $sExpectedSize
Local $sExpectedChecksum
Local $sChecksumType
Local $sReturnedVersion
$oFiles = ObjCreate("Chilkat.FileAccess")
Local $sCacheDir = "qa_output/s3-download-cache"
Local $sManifestPath = "qa_output/s3-download-cache/state.json"
Local $sFinalPath = "qa_output/s3-resumed.bin"
Local $sRequestedVersionId = $sVersionId
$oState = ObjCreate("Chilkat.JsonObject")
$oState.Strict = True
$oIdentity = ObjCreate("Chilkat.JsonObject")
Local $bHasCheckpoint = $oFiles.FileExists($sManifestPath)
If ($bHasCheckpoint = True) Then
$bSuccess = $oState.LoadFile($sManifestPath)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid download checkpoint. Preserve the cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("schema"))
Local $bStringMatch4 = $oStringCompare.ContentsEqual("1",True)
If ($bStringMatch4 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("bucket"))
Local $bStringMatch5 = $oStringCompare.ContentsEqual($sBucketName,True)
If ($bStringMatch5 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("key"))
Local $bStringMatch6 = $oStringCompare.ContentsEqual($sObjectKey,True)
If ($bStringMatch6 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("region"))
Local $bStringMatch7 = $oStringCompare.ContentsEqual($sRegion,True)
If ($bStringMatch7 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("requestedVersion"))
Local $bStringMatch8 = $oStringCompare.ContentsEqual($sRequestedVersionId,True)
If ($bStringMatch8 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("finalPath"))
Local $bStringMatch9 = $oStringCompare.ContentsEqual($sFinalPath,True)
If ($bStringMatch9 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("chunkSize"))
Local $bStringMatch10 = $oStringCompare.ContentsEqual("8388608",True)
If ($bStringMatch10 <> True) Then
ConsoleWrite("Checkpoint settings differ. Use the original settings or a new empty cache." & @CRLF)
Exit
EndIf
$sVersionId = $oState.StringOf("versionId")
If ($oState.JsonTypeOf("versionId") <> 1) Then
ConsoleWrite("Checkpoint version ID is invalid." & @CRLF)
Exit
EndIf
EndIf
$oQuery.Clear
$oStringCompare.SetString($sVersionId)
Local $bStringMatch11 = $oStringCompare.ContentsEqual("",True)
If ($bStringMatch11 <> True) Then
If ($oQuery.Length > 0) Then
$oQuery.Append("&")
EndIf
$oQuery.Append("versionId=")
$oQuery.Append($oHttp.UrlEncode($sVersionId))
EndIf
$oHttp.ClearHeaders
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read system time." & @CRLF)
Exit
EndIf
$oTimestamp.SetString($oNow.GetAsTimestamp(False))
$iReplaceCount = $oTimestamp.Replace("-","")
$iReplaceCount = $oTimestamp.Replace(":","")
$sAmzDate = $oTimestamp.GetAsString()
$sDateStamp = $oTimestamp.GetRange(0,8,False)
$sPayloadHash = $oSigner.HashStringENC("")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not hash payload." & @CRLF)
Exit
EndIf
$oCanonicalHeaders.Clear
$oSignedHeaders.Clear
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("host")
$oCanonicalHeaders.Append("host:")
$oCanonicalHeaders.Append($oHost.GetAsString())
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "host",$oHost.GetAsString()
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-checksum-mode")
$oCanonicalHeaders.Append("x-amz-checksum-mode:")
$oCanonicalHeaders.Append("ENABLED")
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-checksum-mode","ENABLED"
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-content-sha256")
$oCanonicalHeaders.Append("x-amz-content-sha256:")
$oCanonicalHeaders.Append($sPayloadHash)
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-content-sha256",$sPayloadHash
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-date")
$oCanonicalHeaders.Append("x-amz-date:")
$oCanonicalHeaders.Append($sAmzDate)
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-date",$sAmzDate
If ($oCredentials.HasMember("session_token") = True) Then
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-security-token")
$oCanonicalHeaders.Append("x-amz-security-token:")
$oCanonicalHeaders.Append($oCredentials.StringOf("session_token"))
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-security-token",$oCredentials.StringOf("session_token")
EndIf
$oCanonical.Clear
$oCanonical.Append("HEAD" & @LF)
$oCanonical.Append($oUri.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oQuery.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oCanonicalHeaders.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oSignedHeaders.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($sPayloadHash)
$sCanonicalHash = $oSigner.HashStringENC($oCanonical.GetAsString())
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not hash canonical request." & @CRLF)
Exit
EndIf
$oScope.Clear
$oScope.Append($sDateStamp)
$oScope.Append("/")
$oScope.Append($sRegion)
$oScope.Append("/s3/aws4_request")
$oStringToSign.Clear
$oStringToSign.Append("AWS4-HMAC-SHA256" & @LF)
$oStringToSign.Append($sAmzDate)
$oStringToSign.Append(@LF)
$oStringToSign.Append($oScope.GetAsString())
$oStringToSign.Append(@LF)
$oStringToSign.Append($sCanonicalHash)
$oSigningKey.SetString("AWS4")
$oSigningKey.Append($oCredentials.StringOf("secret_key"))
$bSuccess = $oSigner.SetMacKeyString($oSigningKey.GetAsString())
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC($sDateStamp)
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC($sRegion)
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC("s3")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC("aws4_request")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$signature = $oSigner.MacStringENC($oStringToSign.GetAsString())
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not sign request." & @CRLF)
Exit
EndIf
$oAuthorization.Clear
$oAuthorization.Append("AWS4-HMAC-SHA256 Credential=")
$oAuthorization.Append($oCredentials.StringOf("access_key"))
$oAuthorization.Append("/")
$oAuthorization.Append($oScope.GetAsString())
$oAuthorization.Append(", SignedHeaders=")
$oAuthorization.Append($oSignedHeaders.GetAsString())
$oAuthorization.Append(", Signature=")
$oAuthorization.Append($signature)
$oHttp.SetRequestHeader "Authorization",$oAuthorization.GetAsString()
$oUrl.SetString("https://")
$oUrl.Append($oHost.GetAsString())
$oUrl.Append($oUri.GetAsString())
If ($oQuery.Length > 0) Then
$oUrl.Append("?")
$oUrl.Append($oQuery.GetAsString())
EndIf
$bSuccess = $oHttp.HttpNoBody("HEAD",$oUrl.GetAsString(),$oResponse)
If (($bSuccess <> True) Or ($oResponse.StatusCode <> 200)) Then
ConsoleWrite("Request failed or returned unexpected HTTP status: " & $oResponse.StatusCode & @CRLF)
; Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit
EndIf
$sEtag = $oResponse.GetHeaderField("ETag")
$oStringCompare.SetString($sEtag)
Local $bStringMatch12 = $oStringCompare.ContentsEqual("",True)
If (($oResponse.LastMethodSuccess <> True) Or ($bStringMatch12 = True)) Then
ConsoleWrite("Missing required response header ETag." & @CRLF)
Exit
EndIf
$sExpectedSize = $oResponse.GetHeaderField("Content-Length")
$oStringCompare.SetString($sExpectedSize)
Local $bStringMatch13 = $oStringCompare.ContentsEqual("",True)
If (($oResponse.LastMethodSuccess <> True) Or ($bStringMatch13 = True)) Then
ConsoleWrite("Missing required response header Content-Length." & @CRLF)
Exit
EndIf
$sReturnedVersion = $oResponse.GetHeaderField("x-amz-version-id")
If ($oResponse.LastMethodSuccess <> True) Then
$sReturnedVersion = ""
EndIf
$oStringCompare.SetString($sVersionId)
Local $bStringMatch14 = $oStringCompare.ContentsEqual("",True)
If ($bStringMatch14 = True) Then
$sVersionId = $sReturnedVersion
Else
$oStringCompare.SetString($sReturnedVersion)
Local $bStringMatch15 = $oStringCompare.ContentsEqual($sVersionId,True)
If ($bStringMatch15 <> True) Then
ConsoleWrite("Unexpected object version." & @CRLF)
Exit
EndIf
EndIf
$sExpectedChecksum = $oResponse.GetHeaderField("x-amz-checksum-sha256")
$oStringCompare.SetString($sExpectedChecksum)
Local $bStringMatch16 = $oStringCompare.ContentsEqual("",True)
If (($oResponse.LastMethodSuccess <> True) Or ($bStringMatch16 = True)) Then
ConsoleWrite("Missing required response header x-amz-checksum-sha256." & @CRLF)
Exit
EndIf
$sChecksumType = $oResponse.GetHeaderField("x-amz-checksum-type")
$oStringCompare.SetString($sChecksumType)
Local $bStringMatch17 = $oStringCompare.ContentsEqual("",True)
If (($oResponse.LastMethodSuccess <> True) Or ($bStringMatch17 = True)) Then
ConsoleWrite("Missing required response header x-amz-checksum-type." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($sChecksumType)
Local $bStringMatch18 = $oStringCompare.ContentsEqual("FULL_OBJECT",True)
If ($bStringMatch18 <> True) Then
ConsoleWrite("This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification." & @CRLF)
Exit
EndIf
; Portable decimal long division; no 32-bit byte-offset overflow.
Local $iChunkSize = 8388608
Local $iChunkCount = 0
Local $iRemainder = 0
Local $iPosition = 0
$oSizeText = ObjCreate("Chilkat.StringBuilder")
$oDecimalDigits = ObjCreate("Chilkat.StringBuilder")
$oDigit = ObjCreate("Chilkat.StringBuilder")
$oSizeText.Append($sExpectedSize)
$oDecimalDigits.Append("0123456789")
If (($oSizeText.Length = 0) Or ($oSizeText.Length > 14)) Then
ConsoleWrite("Invalid object size." & @CRLF)
Exit
EndIf
While ($iPosition < $oSizeText.Length)
$oDigit.SetString($oSizeText.GetRange($iPosition,1,False))
If ($oDecimalDigits.Contains($oDigit.GetAsString(),True) <> True) Then
ConsoleWrite("Invalid decimal object size." & @CRLF)
Exit
EndIf
$iRemainder = $iRemainder * 10 + $oDigit.IntValue
$iChunkCount = $iChunkCount * 10
While ($iRemainder >= $iChunkSize)
$iChunkCount = $iChunkCount + 1
$iRemainder = $iRemainder - $iChunkSize
Wend
$iPosition = $iPosition + 1
Wend
If ($iRemainder <> 0) Then
$iChunkCount = $iChunkCount + 1
EndIf
If (($iChunkCount < 1) Or ($iChunkCount > 10000)) Then
ConsoleWrite("Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("schema","1")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save schema." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("bucket",$sBucketName)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save bucket." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("key",$sObjectKey)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save key." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("region",$sRegion)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save region." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("requestedVersion",$sRequestedVersionId)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save requestedVersion." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("versionId",$sVersionId)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save versionId." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("etag",$sEtag)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save etag." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("size",$sExpectedSize)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save size." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("checksum",$sExpectedChecksum)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save checksum." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("finalPath",$sFinalPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save finalPath." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.UpdateString("chunkSize","8388608")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save chunkSize." & @CRLF)
Exit
EndIf
If ($bHasCheckpoint = True) Then
$oStringCompare.SetString($oState.StringOf("versionId"))
Local $bStringMatch19 = $oStringCompare.ContentsEqual($oIdentity.StringOf("versionId"),True)
If ($bStringMatch19 <> True) Then
ConsoleWrite("Object identity changed. Do not mix old cached bytes with this object." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("etag"))
Local $bStringMatch20 = $oStringCompare.ContentsEqual($oIdentity.StringOf("etag"),True)
If ($bStringMatch20 <> True) Then
ConsoleWrite("Object identity changed. Do not mix old cached bytes with this object." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("size"))
Local $bStringMatch21 = $oStringCompare.ContentsEqual($oIdentity.StringOf("size"),True)
If ($bStringMatch21 <> True) Then
ConsoleWrite("Object identity changed. Do not mix old cached bytes with this object." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oState.StringOf("checksum"))
Local $bStringMatch22 = $oStringCompare.ContentsEqual($oIdentity.StringOf("checksum"),True)
If ($bStringMatch22 <> True) Then
ConsoleWrite("Object identity changed. Do not mix old cached bytes with this object." & @CRLF)
Exit
EndIf
Else
$bSuccess = $oFiles.DirEnsureExists($sCacheDir)
If ($bSuccess <> True) Then
ConsoleWrite("Could not create private cache." & @CRLF)
Exit
EndIf
$oEntries = ObjCreate("Chilkat.DirTree")
$oEntries.BaseDir = $sCacheDir
$oEntries.Recurse = False
$bSuccess = $oEntries.BeginIterate()
If (($bSuccess = True) Or ($oEntries.DoneIterating <> True)) Then
ConsoleWrite("First download requires an empty, readable cache directory." & @CRLF)
Exit
EndIf
$bSuccess = $oIdentity.WriteFile("qa_output/s3-download-cache/state.json.tmp")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save download identity." & @CRLF)
Exit
EndIf
$bSuccess = $oFiles.FileRename("qa_output/s3-download-cache/state.json.tmp",$sManifestPath)
If ($bSuccess <> True) Then
ConsoleWrite("Checkpoint remains at its temporary path." & @CRLF)
Exit
EndIf
EndIf
$oDigest = ObjCreate("Chilkat.Crypt2")
$oDigest.HashAlgorithm = "sha256"
$oDigest.EncodingMode = "base64"
If ($oFiles.FileExists($sFinalPath) = True) Then
Local $sExistingSize = $oFiles.FileSizeStr($sFinalPath)
Local $sExistingChecksum = $oDigest.HashFileENC($sFinalPath)
$oStringCompare.SetString($sExistingSize)
Local $bStringMatch23 = $oStringCompare.ContentsEqual($sExpectedSize,True)
$oStringCompare.SetString($sExistingChecksum)
Local $bStringMatch24 = $oStringCompare.ContentsEqual($sExpectedChecksum,True)
If (($oDigest.LastMethodSuccess <> True) Or ($bStringMatch23 <> True) Or ($bStringMatch24 <> True)) Then
ConsoleWrite("Existing final file does not match; preserve it." & @CRLF)
Exit
EndIf
ConsoleWrite("Object already downloaded and checksum verified." & @CRLF)
Exit
EndIf
$oDigest.EncodingMode = "hexlower"
$oPath = ObjCreate("Chilkat.StringBuilder")
$oRange = ObjCreate("Chilkat.StringBuilder")
$oDigits = ObjCreate("Chilkat.StringBuilder")
$oRangeHeader = ObjCreate("Chilkat.StringBuilder")
$oContentRange = ObjCreate("Chilkat.StringBuilder")
$oByteCount = ObjCreate("Chilkat.StringBuilder")
$oReceipt = ObjCreate("Chilkat.JsonObject")
$oReceipt.Strict = True
$oReceived = ObjCreate("Chilkat.Mime")
Local $iChunkIndex = 0
Local $iByteHigh = 0
Local $iByteLow = 0
Local $iEndHigh
Local $iEndLow
Local $sActualRange
Local $sActualLength
Local $sActualEtag
Local $sActualVersion
Local $sActualSize
Local $sActualHash
While ($iChunkIndex < $iChunkCount)
Local $iChunkBytes = $iChunkSize
If (($iChunkIndex = $iChunkCount - 1) And ($iRemainder <> 0)) Then
$iChunkBytes = $iRemainder
EndIf
$oRange.Clear
$oDigits.Clear
$oDigits.AppendInt($iByteLow)
If ($iByteHigh > 0) Then
While ($oDigits.Length < 9)
$oDigits.Prepend("0")
Wend
$oRange.AppendInt($iByteHigh)
EndIf
$oRange.Append($oDigits.GetAsString())
$oRange.Append("-")
$iEndHigh = $iByteHigh
$iEndLow = $iByteLow + $iChunkBytes - 1
If ($iEndLow >= 1000000000) Then
$iEndLow = $iEndLow - 1000000000
$iEndHigh = $iEndHigh + 1
EndIf
$oDigits.Clear
$oDigits.AppendInt($iEndLow)
If ($iEndHigh > 0) Then
While ($oDigits.Length < 9)
$oDigits.Prepend("0")
Wend
$oRange.AppendInt($iEndHigh)
EndIf
$oRange.Append($oDigits.GetAsString())
Local $sRangeKey = $oRange.GetAsString()
$oRangeHeader.SetString("bytes=")
$oRangeHeader.Append($sRangeKey)
$oContentRange.SetString("bytes ")
$oContentRange.Append($sRangeKey)
$oContentRange.Append("/")
$oContentRange.Append($sExpectedSize)
$oByteCount.Clear
$oByteCount.AppendInt($iChunkBytes)
$oPath.SetString($sCacheDir)
$oPath.Append("/chunk-")
$oPath.AppendInt($iChunkIndex)
Local $sChunkPath = $oPath.GetAsString()
$oPath.Append(".json")
Local $sReceiptPath = $oPath.GetAsString()
$oPath.SetString($sChunkPath)
$oPath.Append(".part")
Local $sPartialPath = $oPath.GetAsString()
If ($oFiles.FileExists($sChunkPath) = True) Then
$bSuccess = $oReceipt.LoadFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Cached chunk has no valid receipt. Preserve the cache." & @CRLF)
Exit
EndIf
$sActualHash = $oDigest.HashFileENC($sChunkPath)
$oStringCompare.SetString($sActualHash)
Local $bStringMatch25 = $oStringCompare.ContentsEqual($oReceipt.StringOf("hash"),True)
$oStringCompare.SetString($oReceipt.StringOf("range"))
Local $bStringMatch26 = $oStringCompare.ContentsEqual($sRangeKey,True)
$oStringCompare.SetString($oFiles.FileSizeStr($sChunkPath))
Local $bStringMatch27 = $oStringCompare.ContentsEqual($oByteCount.GetAsString(),True)
If (($oDigest.LastMethodSuccess <> True) Or ($bStringMatch25 <> True) Or ($bStringMatch26 <> True) Or ($bStringMatch27 <> True)) Then
ConsoleWrite("Cached chunk failed verification. Remove only this chunk and receipt before retrying." & @CRLF)
Exit
EndIf
ConsoleWrite("Reusing verified chunk: " & $iChunkIndex & @CRLF)
Else
$oQuery.Clear
$oStringCompare.SetString($sVersionId)
Local $bStringMatch28 = $oStringCompare.ContentsEqual("",True)
If ($bStringMatch28 <> True) Then
If ($oQuery.Length > 0) Then
$oQuery.Append("&")
EndIf
$oQuery.Append("versionId=")
$oQuery.Append($oHttp.UrlEncode($sVersionId))
EndIf
$oHttp.ClearHeaders
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read system time." & @CRLF)
Exit
EndIf
$oTimestamp.SetString($oNow.GetAsTimestamp(False))
$iReplaceCount = $oTimestamp.Replace("-","")
$iReplaceCount = $oTimestamp.Replace(":","")
$sAmzDate = $oTimestamp.GetAsString()
$sDateStamp = $oTimestamp.GetRange(0,8,False)
$sPayloadHash = $oSigner.HashStringENC("")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not hash payload." & @CRLF)
Exit
EndIf
$oCanonicalHeaders.Clear
$oSignedHeaders.Clear
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("host")
$oCanonicalHeaders.Append("host:")
$oCanonicalHeaders.Append($oHost.GetAsString())
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "host",$oHost.GetAsString()
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("if-match")
$oCanonicalHeaders.Append("if-match:")
$oCanonicalHeaders.Append($sEtag)
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "if-match",$sEtag
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("range")
$oCanonicalHeaders.Append("range:")
$oCanonicalHeaders.Append($oRangeHeader.GetAsString())
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "range",$oRangeHeader.GetAsString()
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-content-sha256")
$oCanonicalHeaders.Append("x-amz-content-sha256:")
$oCanonicalHeaders.Append($sPayloadHash)
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-content-sha256",$sPayloadHash
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-date")
$oCanonicalHeaders.Append("x-amz-date:")
$oCanonicalHeaders.Append($sAmzDate)
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-date",$sAmzDate
If ($oCredentials.HasMember("session_token") = True) Then
If ($oSignedHeaders.Length > 0) Then
$oSignedHeaders.Append(";")
EndIf
$oSignedHeaders.Append("x-amz-security-token")
$oCanonicalHeaders.Append("x-amz-security-token:")
$oCanonicalHeaders.Append($oCredentials.StringOf("session_token"))
$oCanonicalHeaders.Append(@LF)
$oHttp.SetRequestHeader "x-amz-security-token",$oCredentials.StringOf("session_token")
EndIf
$oCanonical.Clear
$oCanonical.Append("GET" & @LF)
$oCanonical.Append($oUri.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oQuery.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oCanonicalHeaders.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($oSignedHeaders.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($sPayloadHash)
$sCanonicalHash = $oSigner.HashStringENC($oCanonical.GetAsString())
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not hash canonical request." & @CRLF)
Exit
EndIf
$oScope.Clear
$oScope.Append($sDateStamp)
$oScope.Append("/")
$oScope.Append($sRegion)
$oScope.Append("/s3/aws4_request")
$oStringToSign.Clear
$oStringToSign.Append("AWS4-HMAC-SHA256" & @LF)
$oStringToSign.Append($sAmzDate)
$oStringToSign.Append(@LF)
$oStringToSign.Append($oScope.GetAsString())
$oStringToSign.Append(@LF)
$oStringToSign.Append($sCanonicalHash)
$oSigningKey.SetString("AWS4")
$oSigningKey.Append($oCredentials.StringOf("secret_key"))
$bSuccess = $oSigner.SetMacKeyString($oSigningKey.GetAsString())
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC($sDateStamp)
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC($sRegion)
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC("s3")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$sDerivedKey = $oSigner.MacStringENC("aws4_request")
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not derive signing key." & @CRLF)
Exit
EndIf
$bSuccess = $oSigner.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set signing key." & @CRLF)
Exit
EndIf
$signature = $oSigner.MacStringENC($oStringToSign.GetAsString())
If ($oSigner.LastMethodSuccess <> True) Then
ConsoleWrite("Could not sign request." & @CRLF)
Exit
EndIf
$oAuthorization.Clear
$oAuthorization.Append("AWS4-HMAC-SHA256 Credential=")
$oAuthorization.Append($oCredentials.StringOf("access_key"))
$oAuthorization.Append("/")
$oAuthorization.Append($oScope.GetAsString())
$oAuthorization.Append(", SignedHeaders=")
$oAuthorization.Append($oSignedHeaders.GetAsString())
$oAuthorization.Append(", Signature=")
$oAuthorization.Append($signature)
$oHttp.SetRequestHeader "Authorization",$oAuthorization.GetAsString()
$oUrl.SetString("https://")
$oUrl.Append($oHost.GetAsString())
$oUrl.Append($oUri.GetAsString())
If ($oQuery.Length > 0) Then
$oUrl.Append("?")
$oUrl.Append($oQuery.GetAsString())
EndIf
$bSuccess = $oHttp.Download($oUrl.GetAsString(),$sPartialPath)
If (($oHttp.LastStatus = 412) Or ($oHttp.LastStatus = 416)) Then
ConsoleWrite("Object changed or range is invalid. Preserve the cache; do not append." & @CRLF)
Exit
EndIf
If (($bSuccess <> True) Or ($oHttp.LastStatus <> 206)) Then
ConsoleWrite("Request failed or returned unexpected HTTP status: " & $oHttp.LastStatus & @CRLF)
; Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit
EndIf
$bSuccess = $oReceived.LoadMime($oHttp.LastResponseHeader)
If ($bSuccess <> True) Then
ConsoleWrite("Could not parse range response." & @CRLF)
Exit
EndIf
$sActualRange = $oReceived.GetHeaderField("Content-Range")
$oStringCompare.SetString($sActualRange)
Local $bStringMatch29 = $oStringCompare.ContentsEqual("",True)
If (($oReceived.LastMethodSuccess <> True) Or ($bStringMatch29 = True)) Then
ConsoleWrite("Missing download header Content-Range." & @CRLF)
Exit
EndIf
$sActualLength = $oReceived.GetHeaderField("Content-Length")
$oStringCompare.SetString($sActualLength)
Local $bStringMatch30 = $oStringCompare.ContentsEqual("",True)
If (($oReceived.LastMethodSuccess <> True) Or ($bStringMatch30 = True)) Then
ConsoleWrite("Missing download header Content-Length." & @CRLF)
Exit
EndIf
$sActualEtag = $oReceived.GetHeaderField("ETag")
$oStringCompare.SetString($sActualEtag)
Local $bStringMatch31 = $oStringCompare.ContentsEqual("",True)
If (($oReceived.LastMethodSuccess <> True) Or ($bStringMatch31 = True)) Then
ConsoleWrite("Missing download header ETag." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($sActualRange)
Local $bStringMatch32 = $oStringCompare.ContentsEqual($oContentRange.GetAsString(),True)
$oStringCompare.SetString($sActualLength)
Local $bStringMatch33 = $oStringCompare.ContentsEqual($oByteCount.GetAsString(),True)
$oStringCompare.SetString($sActualEtag)
Local $bStringMatch34 = $oStringCompare.ContentsEqual($sEtag,True)
If (($bStringMatch32 <> True) Or ($bStringMatch33 <> True) Or ($bStringMatch34 <> True)) Then
ConsoleWrite("Unexpected range response; no chunk committed." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($sVersionId)
Local $bStringMatch35 = $oStringCompare.ContentsEqual("",True)
If ($bStringMatch35 <> True) Then
$sActualVersion = $oReceived.GetHeaderField("x-amz-version-id")
$oStringCompare.SetString($sActualVersion)
Local $bStringMatch36 = $oStringCompare.ContentsEqual("",True)
If (($oReceived.LastMethodSuccess <> True) Or ($bStringMatch36 = True)) Then
ConsoleWrite("Missing download header x-amz-version-id." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($sActualVersion)
Local $bStringMatch37 = $oStringCompare.ContentsEqual($sVersionId,True)
If ($bStringMatch37 <> True) Then
ConsoleWrite("Unexpected returned version." & @CRLF)
Exit
EndIf
EndIf
$sActualSize = $oFiles.FileSizeStr($sPartialPath)
$oStringCompare.SetString($sActualSize)
Local $bStringMatch38 = $oStringCompare.ContentsEqual($oByteCount.GetAsString(),True)
If (($oFiles.LastMethodSuccess <> True) Or ($bStringMatch38 <> True)) Then
ConsoleWrite("Range byte count mismatch." & @CRLF)
Exit
EndIf
$sActualHash = $oDigest.HashFileENC($sPartialPath)
If ($oDigest.LastMethodSuccess <> True) Then
ConsoleWrite("Could not hash range bytes." & @CRLF)
Exit
EndIf
$bSuccess = $oReceipt.UpdateString("range",$sRangeKey)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save range." & @CRLF)
Exit
EndIf
$bSuccess = $oReceipt.UpdateString("hash",$sActualHash)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save hash." & @CRLF)
Exit
EndIf
$bSuccess = $oReceipt.WriteFile($sReceiptPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not save chunk receipt." & @CRLF)
Exit
EndIf
$bSuccess = $oFiles.FileRename($sPartialPath,$sChunkPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not commit downloaded chunk." & @CRLF)
Exit
EndIf
ConsoleWrite("Downloaded chunk: " & $iChunkIndex & @CRLF)
EndIf
$iByteHigh = $iEndHigh
$iByteLow = $iEndLow + 1
If ($iByteLow = 1000000000) Then
$iByteLow = 0
$iByteHigh = $iByteHigh + 1
EndIf
$iChunkIndex = $iChunkIndex + 1
Wend
; 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.
Local $sAssembledPath = "qa_output/s3-download-cache/assembled.part"
$oAssembled = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oAssembled.OpenForWrite($sAssembledPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not open assembly file." & @CRLF)
Exit
EndIf
$oData = ObjCreate("Chilkat.BinData")
$iChunkIndex = 0
While ($iChunkIndex < $iChunkCount)
$oPath.SetString($sCacheDir)
$oPath.Append("/chunk-")
$oPath.AppendInt($iChunkIndex)
$oData.Clear()
$bSuccess = $oData.LoadFile($oPath.GetAsString())
If ($bSuccess = True) Then
$bSuccess = $oAssembled.FileWriteBd($oData,0,0)
EndIf
If ($bSuccess <> True) Then
$oAssembled.FileClose
ConsoleWrite("Assembly failed; verified progress is retained." & @CRLF)
Exit
EndIf
$iChunkIndex = $iChunkIndex + 1
Wend
$oAssembled.FileClose
$sActualSize = $oFiles.FileSizeStr($sAssembledPath)
$oDigest.EncodingMode = "base64"
$sActualHash = $oDigest.HashFileENC($sAssembledPath)
$oStringCompare.SetString($sActualSize)
Local $bStringMatch39 = $oStringCompare.ContentsEqual($sExpectedSize,True)
$oStringCompare.SetString($sActualHash)
Local $bStringMatch40 = $oStringCompare.ContentsEqual($sExpectedChecksum,True)
If (($oDigest.LastMethodSuccess <> True) Or ($bStringMatch39 <> True) Or ($bStringMatch40 <> True)) Then
ConsoleWrite("Assembled object checksum/size mismatch; final file not created." & @CRLF)
Exit
EndIf
$bSuccess = $oFiles.FileRename($sAssembledPath,$sFinalPath)
If ($bSuccess <> True) Then
ConsoleWrite("Verified assembly remains in cache; rename failed." & @CRLF)
Exit
EndIf
ConsoleWrite("Resumable download completed and checksum verified. Cache retained for manual cleanup." & @CRLF)