Sample code for 30+ languages & platforms
Objective-C 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 Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoFileAccess.h>
#import <CkoCrypt2.h>
#import <CkoStream.h>

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
BOOL success = NO;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the Glacier operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/glacier.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private AWS credentials.");
    return;
}

if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || ([credentials StringOf: @"access_key"] == @"")) {
    NSLog(@"%@",@"Missing or invalid access_key.");
    return;
}

if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || ([credentials StringOf: @"secret_key"] == @"")) {
    NSLog(@"%@",@"Missing or invalid secret_key.");
    return;
}

//  Set this once to the region containing the vault.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"glacier."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"glacier";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
success = [rest SetAuthAws: aws];
if (success != YES) {
    NSLog(@"%@",@"Could not configure AWS signing.");
    return;
}

//  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"] == YES) {
    if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
        NSLog(@"%@",@"session_token must be a string.");
        return;
    }

    if ([credentials StringOf: @"session_token"] != @"") {
        success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not set the session-token parameter.");
            return;
        }

    }

}

//  Supply a Socket to explicitly enable TLS certificate verification.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
    NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
    return;
}

success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
    NSLog(@"%@",@"Could not attach the TLS connection.");
    return;
}

success = [rest AddHeader: @"x-amz-glacier-version" value: @"2012-06-01"];
if (success != YES) {
    NSLog(@"%@",@"Could not set x-amz-glacier-version.");
    return;
}

//  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}" value: @"chilkat"];
if (success != YES) {
    NSLog(@"%@",@"Could not set vault name.");
    return;
}

CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoJsonObject *error = [[CkoJsonObject alloc] init];
error.Strict = YES;
CkoStringBuilder *responseBody = [[CkoStringBuilder alloc] init];
NSString *jobId = @"YOUR_JOB_ID";
success = [rest AddPathParam: @"{job}" value: jobId];
if (success != YES) {
    NSLog(@"%@",@"Could not set job ID.");
    return;
}

success = [rest FullRequestNoBodySb: @"GET" uriPath: @"/-/vaults/{vault}/jobs/{job}" sb: responseBody];
if (success != YES) {
    NSLog(@"%@",@"Request did not complete; inspect diagnostics privately. Check state before retrying a change.");
    return;
}

if ([rest.ResponseStatusCode intValue] != 200) {
    NSLog(@"%@%d",@"Glacier HTTP status: ",[rest.ResponseStatusCode intValue]);
    success = [error LoadSb: responseBody];
    if (success == YES) {
        if ([[error JsonTypeOf: @"code"] intValue] == 1) {
            NSLog(@"%@%@",@"AWS error code: ",[error StringOf: @"code"]);
        }

    }

    NSLog(@"%@%@",@"AWS request ID: ",[rest ResponseHdrByName: @"x-amzn-RequestId"]);
    //  Inspect full errors privately. An HTTP error is not a successful operation.
    return;
}

success = [result LoadSb: responseBody];
if (success != YES) {
    NSLog(@"%@",@"Expected valid JSON response.");
    return;
}

if ([[result JsonTypeOf: @"Completed"] intValue] != 5) {
    NSLog(@"%@",@"Missing or invalid Completed.");
    return;
}

if ([[result JsonTypeOf: @"StatusCode"] intValue] != 1) {
    NSLog(@"%@",@"Missing or invalid StatusCode.");
    return;
}

if ([result StringOf: @"StatusCode"] == @"") {
    NSLog(@"%@",@"Empty StatusCode.");
    return;
}

if (([result BoolOf: @"Completed"] != YES) || ([result StringOf: @"StatusCode"] != @"Succeeded")) {
    NSLog(@"%@",@"Job is not successfully complete. Resume later only if InProgress.");
    return;
}

if ([result StringOf: @"Action"] != @"ArchiveRetrieval") {
    NSLog(@"%@",@"Wrong job type.");
    return;
}

if ([[result JsonTypeOf: @"SHA256TreeHash"] intValue] != 1) {
    NSLog(@"%@",@"Missing or invalid SHA256TreeHash.");
    return;
}

if ([result StringOf: @"SHA256TreeHash"] == @"") {
    NSLog(@"%@",@"Empty SHA256TreeHash.");
    return;
}

if ([result StringOf: @"RetrievalByteRange"] != @"8388608-16777215") {
    NSLog(@"%@",@"Use the 8 MiB range job created by the companion example.");
    return;
}

//  These offsets are relative to the JOB OUTPUT, not the original archive.
//  Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
NSString *expectedHash = [result StringOf: @"SHA256TreeHash"];
CkoStringBuilder *rangeHeader = [[CkoStringBuilder alloc] init];
CkoStringBuilder *contentRange = [[CkoStringBuilder alloc] init];
CkoStringBuilder *byteCount = [[CkoStringBuilder alloc] init];
[rangeHeader Append: @"bytes=0-8388607"];
[contentRange Append: @"bytes 0-8388607/8388608"];
[byteCount Append: @"8388608"];
CkoFileAccess *files = [[CkoFileAccess alloc] init];
CkoCrypt2 *crypt = [[CkoCrypt2 alloc] init];
crypt.HashAlgorithm = @"sha256-tree-hash";
crypt.EncodingMode = @"hexlower";
NSString *temporaryPath = @"qa_output/archive-range.dat.part";
NSString *finalPath = @"qa_output/archive-range.dat";
if (([files FileExists: temporaryPath] == YES) || ([files FileExists: finalPath] == YES)) {
    NSLog(@"%@",@"Choose unused output paths.");
    return;
}

success = [rest AddHeader: @"Range" value: [rangeHeader GetAsString]];
if (success != YES) {
    NSLog(@"%@",@"Could not set Range.");
    return;
}

success = [rest SendReqNoBody: @"GET" uriPath: @"/-/vaults/{vault}/jobs/{job}/output"];
if (success != YES) {
    NSLog(@"%@",@"Could not send range request. Rerun to resume.");
    return;
}

int httpStatus = [[rest ReadResponseHeader] intValue];
if (httpStatus != 206) {
    NSLog(@"%@",@"Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.");
    return;
}

NSString *responseRange = [rest ResponseHdrByName: @"Content-Range"];
if ((rest.LastMethodSuccess != YES) || (responseRange != [contentRange GetAsString])) {
    NSLog(@"%@",@"Unexpected Content-Range; refusing download.");
    return;
}

NSString *responseLength = [rest ResponseHdrByName: @"Content-Length"];
if ((rest.LastMethodSuccess != YES) || (responseLength != [byteCount GetAsString])) {
    NSLog(@"%@",@"Unexpected Content-Length; refusing download.");
    return;
}

NSString *responseHash = [rest ResponseHdrByName: @"x-amz-sha256-tree-hash"];
if ((rest.LastMethodSuccess != YES) || (responseHash == @"")) {
    NSLog(@"%@",@"Missing range tree hash. Require a tree-hash-aligned retrieval and download range.");
    return;
}

CkoStream *output = [[CkoStream alloc] init];
output.SinkFile = temporaryPath;
success = [rest ReadRespBodyStream: output autoSetStreamCharset: YES];
if (success != YES) {
    NSLog(@"%@",@"Download interrupted; rerun to resume. Temporary bytes are not trusted.");
    return;
}

NSString *actualSize = [files FileSizeStr: temporaryPath];
if ((files.LastMethodSuccess != YES) || (actualSize != [byteCount GetAsString])) {
    NSLog(@"%@",@"Downloaded size mismatch.");
    return;
}

NSString *actualHash = [crypt HashFileENC: temporaryPath];
if ((crypt.LastMethodSuccess != YES) || (actualHash != responseHash)) {
    NSLog(@"%@",@"Downloaded tree hash mismatch.");
    return;
}

if (actualHash != expectedHash) {
    NSLog(@"%@",@"Range output does not match the retrieval job tree hash.");
    return;
}

success = [files FileRename: temporaryPath newPath: finalPath];
if (success != YES) {
    NSLog(@"%@",@"Verified range remains at the temporary path; rename failed.");
    return;
}

NSLog(@"%@",@"Archive range downloaded and verified.");