Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

Amazon Glacier: Download and Verify Range Retrieval Output

See more Amazon Glacier Examples

For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.

Downloads the 8 MiB output of the companion range retrieval job. Set its job ID and create qa_output first. DescribeJob must report successful archive retrieval and the expected archive range. The HTTP range bytes=0-8388607 is relative to the job output, although the original archive range starts at 8388608.

Requires HTTP 206, exact Content-Range and Content-Length, the response tree hash, the actual downloaded size, and the job output's SHA256TreeHash before renaming the temporary file. ArchiveSHA256TreeHash hashes the entire original archive and must not be used to validate a partial retrieval. Existing output files are not overwritten. A failed download remains marked .part.

Requires glacier:DescribeJob and glacier:GetJobOutput. Download promptly: job output remains available for at least 24 hours after completion. Both retrieval and download ranges must be tree-hash aligned to receive a checksum. For other range lengths, adjust all expected ranges and lengths together.

Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.

Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.

AWS reference

Chilkat B4X Downloads

B4X
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean = False
'  Private configuration, not a file in public web content or source control.
'  Load current IAM credentials authorized for the Glacier operation.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/glacier.json")
If success <> True Then
    Log("Could not load private AWS credentials.")
    Return
End If

If (credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "") Then
    Log("Missing or invalid access_key.")
    Return
End If

If (credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "") Then
    Log("Missing or invalid secret_key.")
    Return
End If

'  Set this once to the region containing the vault.
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("glacier.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "glacier"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure AWS signing.")
    Return
End If

'  Temporary IAM/STS credentials require their session token on every signed request.
'  Include the token in the signed query. Keep request URLs and diagnostics private.
'  Leave session_token absent or empty only for credentials that do not have one.
If credentials.HasMember("session_token") = True Then
    If credentials.JsonTypeOf("session_token") <> 1 Then
        Log("session_token must be a string.")
        Return
    End If

    If credentials.StringOf("session_token") <> "" Then
        success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
        If success <> True Then
            Log("Could not set the session-token parameter.")
            Return
        End If

    End If

End If

'  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach the TLS connection.")
    Return
End If

success = rest.AddHeader("x-amz-glacier-version", "2012-06-01")
If success <> True Then
    Log("Could not set x-amz-glacier-version.")
    Return
End If

'  A hyphen selects the account belonging to the signing credentials.
'  Use the original, URL-safe vault name and IDs returned by Glacier.
success = rest.AddPathParam("{vault}", "chilkat")
If success <> True Then
    Log("Could not set vault name.")
    Return
End If


Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim error As ChilkatJsonObject
error.Initialize
error.Strict = True
Dim responseBody As ChilkatStringBuilder
responseBody.Initialize
Dim jobId As String = "YOUR_JOB_ID"
success = rest.AddPathParam("{job}", jobId)
If success <> True Then
    Log("Could not set job ID.")
    Return
End If

success = rest.FullRequestNoBodySb("GET", "/-/vaults/{vault}/jobs/{job}", responseBody)
If success <> True Then
    Log("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    Return
End If

If rest.ResponseStatusCode <> 200 Then
    Log("Glacier HTTP status: " & rest.ResponseStatusCode)
    success = error.LoadSb(responseBody)
    If success = True Then
        If error.JsonTypeOf("code") = 1 Then
            Log("AWS error code: " & error.StringOf("code"))
        End If

    End If

    Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Inspect full errors privately. An HTTP error is not a successful operation.
    Return
End If

success = result.LoadSb(responseBody)
If success <> True Then
    Log("Expected valid JSON response.")
    Return
End If

If result.JsonTypeOf("Completed") <> 5 Then
    Log("Missing or invalid Completed.")
    Return
End If

If result.JsonTypeOf("StatusCode") <> 1 Then
    Log("Missing or invalid StatusCode.")
    Return
End If

If result.StringOf("StatusCode") = "" Then
    Log("Empty StatusCode.")
    Return
End If

If (result.BoolOf("Completed") <> True) Or (result.StringOf("StatusCode") <> "Succeeded") Then
    Log("Job is not successfully complete. Resume later only if InProgress.")
    Return
End If

If result.StringOf("Action") <> "ArchiveRetrieval" Then
    Log("Wrong job type.")
    Return
End If

If result.JsonTypeOf("SHA256TreeHash") <> 1 Then
    Log("Missing or invalid SHA256TreeHash.")
    Return
End If

If result.StringOf("SHA256TreeHash") = "" Then
    Log("Empty SHA256TreeHash.")
    Return
End If

If result.StringOf("RetrievalByteRange") <> "8388608-16777215" Then
    Log("Use the 8 MiB range job created by the companion example.")
    Return
End If

'  These offsets are relative to the JOB OUTPUT, not the original archive.
'  Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
Dim expectedHash As String = result.StringOf("SHA256TreeHash")
Dim rangeHeader As ChilkatStringBuilder
rangeHeader.Initialize
Dim contentRange As ChilkatStringBuilder
contentRange.Initialize
Dim byteCount As ChilkatStringBuilder
byteCount.Initialize
rangeHeader.Append("bytes=0-8388607")
contentRange.Append("bytes 0-8388607/8388608")
byteCount.Append("8388608")
Dim files As ChilkatFileAccess
files.Initialize
Dim crypt As ChilkatCrypt2
crypt.Initialize("crypt")
crypt.HashAlgorithm = "sha256-tree-hash"
crypt.EncodingMode = "hexlower"
Dim temporaryPath As String = "qa_output/archive-range.dat.part"
Dim finalPath As String = "qa_output/archive-range.dat"
If (files.FileExists(temporaryPath) = True) Or (files.FileExists(finalPath) = True) Then
    Log("Choose unused output paths.")
    Return
End If

success = rest.AddHeader("Range", rangeHeader.GetAsString)
If success <> True Then
    Log("Could not set Range.")
    Return
End If

success = rest.SendReqNoBody("GET", "/-/vaults/{vault}/jobs/{job}/output")
If success <> True Then
    Log("Could not send range request. Rerun to resume.")
    Return
End If

Dim httpStatus As Int = rest.ReadResponseHeader
If httpStatus <> 206 Then
    Log("Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.")
    Return
End If

Dim responseRange As String = rest.ResponseHdrByName("Content-Range")
If (rest.LastMethodSuccess <> True) Or (responseRange <> contentRange.GetAsString) Then
    Log("Unexpected Content-Range; refusing download.")
    Return
End If

Dim responseLength As String = rest.ResponseHdrByName("Content-Length")
If (rest.LastMethodSuccess <> True) Or (responseLength <> byteCount.GetAsString) Then
    Log("Unexpected Content-Length; refusing download.")
    Return
End If

Dim responseHash As String = rest.ResponseHdrByName("x-amz-sha256-tree-hash")
If (rest.LastMethodSuccess <> True) Or (responseHash = "") Then
    Log("Missing range tree hash. Require a tree-hash-aligned retrieval and download range.")
    Return
End If

Dim output As ChilkatStream
output.Initialize("output")
output.SinkFile = temporaryPath
success = rest.ReadRespBodyStream(output, True)
If success <> True Then
    Log("Download interrupted; rerun to resume. Temporary bytes are not trusted.")
    Return
End If

Dim actualSize As String = files.FileSizeStr(temporaryPath)
If (files.LastMethodSuccess <> True) Or (actualSize <> byteCount.GetAsString) Then
    Log("Downloaded size mismatch.")
    Return
End If

Dim actualHash As String = crypt.HashFileENC(temporaryPath)
If (crypt.LastMethodSuccess <> True) Or (actualHash <> responseHash) Then
    Log("Downloaded tree hash mismatch.")
    Return
End If

If actualHash <> expectedHash Then
    Log("Range output does not match the retrieval job tree hash.")
    Return
End If

success = files.FileRename(temporaryPath, finalPath)
If success <> True Then
    Log("Verified range remains at the temporary path; rename failed.")
    Return
End If

Log("Archive range downloaded and verified.")