Amazon Glacier: Resume an Archive Download with Verified Chunks
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 a completed full-archive retrieval job in fixed 8 MiB ranges. Set the job ID, cache directory, and final path. Start with an empty, private cache directory on the same filesystem as the final output, then rerun with exactly the same settings to resume. Only one process may use the directory. No new retrieval job is initiated, even if the old job expires.
A saved identity binds progress to region, vault, job, archive ID, size, tree hash, chunk size, and final path. Every cached chunk is rehashed and its length and range checked before reuse. New chunks require HTTP 206, exact Content-Range and Content-Length, actual length, and a matching response tree hash before their temporary file is committed. An interrupted chunk is downloaded again; already verified chunks are retained. A damaged checkpoint or cached chunk stops with an explanation. Local cache files and receipts must be protected from other writers.
After downloading, the example assembles one chunk at a time and checks the entire file's byte count and archive tree hash before renaming it. Interrupted assembly is rebuilt from the cache. Existing final output is accepted only if it matches; other files are not overwritten. Chunks remain for inspection or manual cleanup. Allow disk space for both the complete chunk cache and assembled archive, plus one temporary chunk. A disk-full, network, or checksum failure is not success.
Uses decimal strings and bounded 32-bit arithmetic for archive offsets through the 40 TiB archive limit, including beyond 2 GiB. This produces up to 5,242,880 chunk files plus receipts at that limit; larger power-of-two chunks are more practical for very large archives, but require adapting the arithmetic and checkpoint schema. Empty archives use the single-download example. For partial retrieval jobs use range output download instead.
Requires glacier:DescribeJob and glacier:GetJobOutput. Resume promptly while output is retained (at least 24 hours after successful completion). If it has expired, initiate a new retrieval deliberately and use a new cache directory; cached chunks are not automatically transferred to a different job.
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.
Chilkat Delphi DLL Downloads
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
result: HCkJsonObject;
error: HCkJsonObject;
responseBody: HCkStringBuilder;
jobId: PWideChar;
expectedSize: PWideChar;
expectedHash: PWideChar;
chunkSize: Integer;
chunkCount: Integer;
remainder: Integer;
position: Integer;
sizeText: HCkStringBuilder;
decimalDigits: HCkStringBuilder;
digit: HCkStringBuilder;
cacheDir: PWideChar;
finalPath: PWideChar;
files: HCkFileAccess;
path: HCkStringBuilder;
manifestPath: PWideChar;
manifest: HCkJsonObject;
identity: HCkJsonObject;
cacheContents: HCkDirTree;
crypt: HCkCrypt2;
finalSize: PWideChar;
finalHash: PWideChar;
rangeHeader: HCkStringBuilder;
contentRange: HCkStringBuilder;
byteCount: HCkStringBuilder;
receipt: HCkJsonObject;
chunkIndex: Integer;
byteHigh: Integer;
byteLow: Integer;
endHigh: Integer;
endLow: Integer;
range: HCkStringBuilder;
digits: HCkStringBuilder;
chunkBytes: Integer;
rangeKey: PWideChar;
chunkPath: PWideChar;
receiptPath: PWideChar;
temporaryPath: PWideChar;
cachedHash: PWideChar;
httpStatus: Integer;
responseRange: PWideChar;
responseLength: PWideChar;
responseHash: PWideChar;
output: HCkStream;
actualSize: PWideChar;
actualHash: PWideChar;
assembledPath: PWideChar;
assembled: HCkFileAccess;
data: HCkBinData;
assembledSize: PWideChar;
assembledHash: PWideChar;
begin
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/glacier.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load private AWS credentials.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (CkJsonObject__stringOf(credentials,'access_key') = '')) then
begin
Memo1.Lines.Add('Missing or invalid access_key.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (CkJsonObject__stringOf(credentials,'secret_key') = '')) then
begin
Memo1.Lines.Add('Missing or invalid secret_key.');
Exit;
end;
// Set this once to the region containing the vault.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'glacier.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'glacier');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
begin
Memo1.Lines.Add('Could not configure AWS signing.');
Exit;
end;
// 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 (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
begin
Memo1.Lines.Add('session_token must be a string.');
Exit;
end;
if (CkJsonObject__stringOf(credentials,'session_token') <> '') then
begin
success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set the session-token parameter.');
Exit;
end;
end;
end;
// Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
begin
Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
Exit;
end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
begin
Memo1.Lines.Add('Could not attach the TLS connection.');
Exit;
end;
success := CkRest_AddHeader(rest,'x-amz-glacier-version','2012-06-01');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set x-amz-glacier-version.');
Exit;
end;
// A hyphen selects the account belonging to the signing credentials.
// Use the original, URL-safe vault name and IDs returned by Glacier.
success := CkRest_AddPathParam(rest,'{vault}','chilkat');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set vault name.');
Exit;
end;
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
error := CkJsonObject_Create();
CkJsonObject_putStrict(error,True);
responseBody := CkStringBuilder_Create();
jobId := 'YOUR_JOB_ID';
success := CkRest_AddPathParam(rest,'{job}',jobId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set job ID.');
Exit;
end;
success := CkRest_FullRequestNoBodySb(rest,'GET','/-/vaults/{vault}/jobs/{job}',responseBody);
if (success <> True) then
begin
Memo1.Lines.Add('Request did not complete; inspect diagnostics privately. Check state before retrying a change.');
Exit;
end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
begin
Memo1.Lines.Add('Glacier HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
success := CkJsonObject_LoadSb(error,responseBody);
if (success = True) then
begin
if (CkJsonObject_JsonTypeOf(error,'code') = 1) then
begin
Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(error,'code'));
end;
end;
Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
// Inspect full errors privately. An HTTP error is not a successful operation.
Exit;
end;
success := CkJsonObject_LoadSb(result,responseBody);
if (success <> True) then
begin
Memo1.Lines.Add('Expected valid JSON response.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'Completed') <> 5) then
begin
Memo1.Lines.Add('Missing or invalid Completed.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'StatusCode') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid StatusCode.');
Exit;
end;
if (CkJsonObject__stringOf(result,'StatusCode') = '') then
begin
Memo1.Lines.Add('Empty StatusCode.');
Exit;
end;
if ((CkJsonObject_BoolOf(result,'Completed') <> True) or (CkJsonObject__stringOf(result,'StatusCode') <> 'Succeeded')) then
begin
Memo1.Lines.Add('Job is not successfully complete. Resume later only if InProgress.');
Exit;
end;
if (CkJsonObject__stringOf(result,'Action') <> 'ArchiveRetrieval') then
begin
Memo1.Lines.Add('Wrong job type.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'SHA256TreeHash') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid SHA256TreeHash.');
Exit;
end;
if (CkJsonObject__stringOf(result,'SHA256TreeHash') = '') then
begin
Memo1.Lines.Add('Empty SHA256TreeHash.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'ArchiveSizeInBytes') <> 2) then
begin
Memo1.Lines.Add('Missing or invalid ArchiveSizeInBytes.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'ArchiveId') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid ArchiveId.');
Exit;
end;
if (CkJsonObject__stringOf(result,'ArchiveId') = '') then
begin
Memo1.Lines.Add('Empty ArchiveId.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'ArchiveSHA256TreeHash') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid ArchiveSHA256TreeHash.');
Exit;
end;
if (CkJsonObject__stringOf(result,'ArchiveSHA256TreeHash') = '') then
begin
Memo1.Lines.Add('Empty ArchiveSHA256TreeHash.');
Exit;
end;
expectedSize := CkJsonObject__stringOf(result,'ArchiveSizeInBytes');
expectedHash := CkJsonObject__stringOf(result,'ArchiveSHA256TreeHash');
if (CkJsonObject__stringOf(result,'SHA256TreeHash') <> expectedHash) then
begin
Memo1.Lines.Add('Use a full-archive retrieval job for this resumable example.');
Exit;
end;
// Fixed 8 MiB chunks are power-of-two and tree-hash aligned.
// Decimal long division avoids 32-bit overflow in every generated language.
chunkSize := 8388608;
chunkCount := 0;
remainder := 0;
position := 0;
sizeText := CkStringBuilder_Create();
decimalDigits := CkStringBuilder_Create();
digit := CkStringBuilder_Create();
CkStringBuilder_Append(sizeText,expectedSize);
CkStringBuilder_Append(decimalDigits,'0123456789');
if ((CkStringBuilder_getLength(sizeText) = 0) or (CkStringBuilder_getLength(sizeText) > 14)) then
begin
Memo1.Lines.Add('Invalid archive size.');
Exit;
end;
while (position < CkStringBuilder_getLength(sizeText)) do
begin
CkStringBuilder_SetString(digit,CkStringBuilder__getRange(sizeText,position,1,False));
if (CkStringBuilder_Contains(decimalDigits,CkStringBuilder__getAsString(digit),True) <> True) then
begin
Memo1.Lines.Add('Invalid decimal archive size.');
Exit;
end;
remainder := remainder * 10 + CkStringBuilder_getIntValue(digit);
// At most nine subtractions per digit; avoids language-specific division.
chunkCount := chunkCount * 10;
while (remainder >= chunkSize) do
begin
chunkCount := chunkCount + 1;
remainder := remainder - chunkSize;
end;
position := position + 1;
end;
if ((chunkCount > 5242880) or ((chunkCount = 5242880) and (remainder <> 0))) then
begin
Memo1.Lines.Add('Archive exceeds the 40 TiB service limit.');
Exit;
end;
if ((chunkCount = 0) and (remainder = 0)) then
begin
Memo1.Lines.Add('Use the single-download example for an empty archive.');
Exit;
end;
if (remainder <> 0) then
begin
chunkCount := chunkCount + 1;
end;
// This dedicated directory belongs to ONE job. Use a new empty directory
// when selecting another job. Run only one process against it at a time.
cacheDir := 'qa_output/glacier-download';
finalPath := 'qa_output/archive-resumed.dat';
files := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(files,cacheDir);
if (success <> True) then
begin
Memo1.Lines.Add('Could not create private download directory.');
Exit;
end;
path := CkStringBuilder_Create();
CkStringBuilder_Append(path,cacheDir);
CkStringBuilder_Append(path,'/manifest.json');
manifestPath := CkStringBuilder__getAsString(path);
manifest := CkJsonObject_Create();
CkJsonObject_putStrict(manifest,True);
identity := CkJsonObject_Create();
success := CkJsonObject_UpdateString(identity,'version','1');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set version.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'region',region);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set region.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'vault','chilkat');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set vault.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'jobId',jobId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set jobId.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'archiveId',CkJsonObject__stringOf(result,'ArchiveId'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set archiveId.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'size',expectedSize);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set size.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'treeHash',expectedHash);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set treeHash.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'chunkSize','8388608');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set chunkSize.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'finalPath',finalPath);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set finalPath.');
Exit;
end;
if (CkFileAccess_FileExists(files,manifestPath) = True) then
begin
success := CkJsonObject_LoadFile(manifest,manifestPath);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid checkpoint. Preserve the cache and inspect it before restarting.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'version') <> CkJsonObject__stringOf(identity,'version')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'region') <> CkJsonObject__stringOf(identity,'region')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'vault') <> CkJsonObject__stringOf(identity,'vault')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'jobId') <> CkJsonObject__stringOf(identity,'jobId')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'archiveId') <> CkJsonObject__stringOf(identity,'archiveId')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'size') <> CkJsonObject__stringOf(identity,'size')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'treeHash') <> CkJsonObject__stringOf(identity,'treeHash')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'chunkSize') <> CkJsonObject__stringOf(identity,'chunkSize')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
if (CkJsonObject__stringOf(manifest,'finalPath') <> CkJsonObject__stringOf(identity,'finalPath')) then
begin
Memo1.Lines.Add('Checkpoint belongs to different download settings. Use a new empty cache directory.');
Exit;
end;
end
else
begin
cacheContents := CkDirTree_Create();
CkDirTree_putBaseDir(cacheContents,cacheDir);
CkDirTree_putRecurse(cacheContents,False);
success := CkDirTree_BeginIterate(cacheContents);
if ((success = True) or (CkDirTree_getDoneIterating(cacheContents) <> True)) then
begin
Memo1.Lines.Add('First run requires an empty, readable cache directory.');
Exit;
end;
success := CkJsonObject_WriteFile(identity,manifestPath);
if (success <> True) then
begin
Memo1.Lines.Add('Could not save download identity.');
Exit;
end;
end;
crypt := CkCrypt2_Create();
CkCrypt2_putHashAlgorithm(crypt,'sha256-tree-hash');
CkCrypt2_putEncodingMode(crypt,'hexlower');
if (CkFileAccess_FileExists(files,finalPath) = True) then
begin
finalSize := CkFileAccess__fileSizeStr(files,finalPath);
finalHash := CkCrypt2__hashFileENC(crypt,finalPath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (finalSize <> expectedSize) or (finalHash <> expectedHash)) then
begin
Memo1.Lines.Add('Existing final file differs; choose another final output path.');
Exit;
end;
Memo1.Lines.Add('Archive already downloaded and verified.');
Exit;
end;
rangeHeader := CkStringBuilder_Create();
contentRange := CkStringBuilder_Create();
byteCount := CkStringBuilder_Create();
receipt := CkJsonObject_Create();
CkJsonObject_putStrict(receipt,True);
chunkIndex := 0;
byteHigh := 0;
byteLow := 0;
range := CkStringBuilder_Create();
digits := CkStringBuilder_Create();
while (chunkIndex < chunkCount) do
begin
chunkBytes := chunkSize;
if ((chunkIndex = chunkCount - 1) and (remainder <> 0)) then
begin
chunkBytes := remainder;
end;
CkStringBuilder_Clear(range);
CkStringBuilder_Clear(digits);
CkStringBuilder_AppendInt(digits,byteLow);
if (byteHigh > 0) then
begin
while (CkStringBuilder_getLength(digits) < 9) do
begin
CkStringBuilder_Prepend(digits,'0');
end;
CkStringBuilder_AppendInt(range,byteHigh);
end;
CkStringBuilder_Append(range,CkStringBuilder__getAsString(digits));
CkStringBuilder_Append(range,'-');
endHigh := byteHigh;
endLow := byteLow + chunkBytes - 1;
if (endLow >= 1000000000) then
begin
endLow := endLow - 1000000000;
endHigh := endHigh + 1;
end;
CkStringBuilder_Clear(digits);
CkStringBuilder_AppendInt(digits,endLow);
if (endHigh > 0) then
begin
while (CkStringBuilder_getLength(digits) < 9) do
begin
CkStringBuilder_Prepend(digits,'0');
end;
CkStringBuilder_AppendInt(range,endHigh);
end;
CkStringBuilder_Append(range,CkStringBuilder__getAsString(digits));
rangeKey := CkStringBuilder__getAsString(range);
CkStringBuilder_SetString(rangeHeader,'bytes=');
CkStringBuilder_Append(rangeHeader,rangeKey);
CkStringBuilder_SetString(contentRange,'bytes ');
CkStringBuilder_Append(contentRange,rangeKey);
CkStringBuilder_Append(contentRange,'/');
CkStringBuilder_Append(contentRange,expectedSize);
CkStringBuilder_Clear(byteCount);
CkStringBuilder_AppendInt(byteCount,chunkBytes);
CkStringBuilder_SetString(path,cacheDir);
CkStringBuilder_Append(path,'/chunk-');
CkStringBuilder_AppendInt(path,chunkIndex);
chunkPath := CkStringBuilder__getAsString(path);
CkStringBuilder_Append(path,'.json');
receiptPath := CkStringBuilder__getAsString(path);
CkStringBuilder_SetString(path,chunkPath);
CkStringBuilder_Append(path,'.part');
temporaryPath := CkStringBuilder__getAsString(path);
if (CkFileAccess_FileExists(files,chunkPath) = True) then
begin
success := CkJsonObject_LoadFile(receipt,receiptPath);
if (success <> True) then
begin
Memo1.Lines.Add('Cached chunk lacks a valid receipt. Preserve the cache and inspect it.');
Exit;
end;
cachedHash := CkCrypt2__hashFileENC(crypt,chunkPath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (cachedHash <> CkJsonObject__stringOf(receipt,'treeHash')) or (CkJsonObject__stringOf(receipt,'range') <> rangeKey) or (CkFileAccess__fileSizeStr(files,chunkPath) <> CkStringBuilder__getAsString(byteCount))) then
begin
Memo1.Lines.Add('Cached chunk failed verification. Remove only that chunk and its receipt, then rerun.');
Exit;
end;
Memo1.Lines.Add('Reusing verified chunk: ' + IntToStr(chunkIndex));
end
else
begin
success := CkRest_AddHeader(rest,'Range',CkStringBuilder__getAsString(rangeHeader));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set Range.');
Exit;
end;
success := CkRest_SendReqNoBody(rest,'GET','/-/vaults/{vault}/jobs/{job}/output');
if (success <> True) then
begin
Memo1.Lines.Add('Could not send range request. Rerun to resume.');
Exit;
end;
httpStatus := CkRest_ReadResponseHeader(rest);
if (httpStatus <> 206) then
begin
Memo1.Lines.Add('Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.');
Exit;
end;
responseRange := CkRest__responseHdrByName(rest,'Content-Range');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseRange <> CkStringBuilder__getAsString(contentRange))) then
begin
Memo1.Lines.Add('Unexpected Content-Range; refusing download.');
Exit;
end;
responseLength := CkRest__responseHdrByName(rest,'Content-Length');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseLength <> CkStringBuilder__getAsString(byteCount))) then
begin
Memo1.Lines.Add('Unexpected Content-Length; refusing download.');
Exit;
end;
responseHash := CkRest__responseHdrByName(rest,'x-amz-sha256-tree-hash');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseHash = '')) then
begin
Memo1.Lines.Add('Missing range tree hash. Require a tree-hash-aligned retrieval and download range.');
Exit;
end;
output := CkStream_Create();
CkStream_putSinkFile(output,temporaryPath);
success := CkRest_ReadRespBodyStream(rest,output,True);
if (success <> True) then
begin
Memo1.Lines.Add('Download interrupted; rerun to resume. Temporary bytes are not trusted.');
Exit;
end;
actualSize := CkFileAccess__fileSizeStr(files,temporaryPath);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (actualSize <> CkStringBuilder__getAsString(byteCount))) then
begin
Memo1.Lines.Add('Downloaded size mismatch.');
Exit;
end;
actualHash := CkCrypt2__hashFileENC(crypt,temporaryPath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (actualHash <> responseHash)) then
begin
Memo1.Lines.Add('Downloaded tree hash mismatch.');
Exit;
end;
success := CkJsonObject_UpdateString(receipt,'range',rangeKey);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set range.');
Exit;
end;
success := CkJsonObject_UpdateString(receipt,'treeHash',actualHash);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set treeHash.');
Exit;
end;
success := CkJsonObject_WriteFile(receipt,receiptPath);
if (success <> True) then
begin
Memo1.Lines.Add('Could not save chunk checksum; temporary bytes remain uncommitted.');
Exit;
end;
success := CkFileAccess_FileRename(files,temporaryPath,chunkPath);
if (success <> True) then
begin
Memo1.Lines.Add('Could not commit verified chunk.');
Exit;
end;
Memo1.Lines.Add('Downloaded verified chunk: ' + IntToStr(chunkIndex));
end;
byteHigh := endHigh;
byteLow := endLow + 1;
if (byteLow = 1000000000) then
begin
byteLow := 0;
byteHigh := byteHigh + 1;
end;
chunkIndex := chunkIndex + 1;
end;
// Full-archive size plus hash protects against a partial retrieval job too.
// Assemble from verified chunks; interrupted assembly is rebuilt on rerun.
CkStringBuilder_SetString(path,cacheDir);
CkStringBuilder_Append(path,'/assembled.part');
assembledPath := CkStringBuilder__getAsString(path);
assembled := CkFileAccess_Create();
success := CkFileAccess_OpenForWrite(assembled,assembledPath);
if (success <> True) then
begin
Memo1.Lines.Add('Could not open assembly file.');
Exit;
end;
data := CkBinData_Create();
chunkIndex := 0;
while (chunkIndex < chunkCount) do
begin
CkStringBuilder_SetString(path,cacheDir);
CkStringBuilder_Append(path,'/chunk-');
CkStringBuilder_AppendInt(path,chunkIndex);
CkBinData_Clear(data);
success := CkBinData_LoadFile(data,CkStringBuilder__getAsString(path));
if (success = True) then
begin
success := CkFileAccess_FileWriteBd(assembled,data,0,0);
end;
if (success <> True) then
begin
CkFileAccess_FileClose(assembled);
Memo1.Lines.Add('Assembly failed. Verified chunks are retained for resume.');
Exit;
end;
chunkIndex := chunkIndex + 1;
end;
CkFileAccess_FileClose(assembled);
assembledSize := CkFileAccess__fileSizeStr(files,assembledPath);
assembledHash := CkCrypt2__hashFileENC(crypt,assembledPath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (assembledSize <> expectedSize) or (assembledHash <> expectedHash)) then
begin
Memo1.Lines.Add('Assembled archive failed verification; final output was not created.');
Exit;
end;
success := CkFileAccess_FileRename(files,assembledPath,finalPath);
if (success <> True) then
begin
Memo1.Lines.Add('Verified assembly could not be renamed; keep the cache.');
Exit;
end;
Memo1.Lines.Add('Archive downloaded and verified. Retained chunks can now be removed manually.');
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(error);
CkStringBuilder_Dispose(responseBody);
CkStringBuilder_Dispose(sizeText);
CkStringBuilder_Dispose(decimalDigits);
CkStringBuilder_Dispose(digit);
CkFileAccess_Dispose(files);
CkStringBuilder_Dispose(path);
CkJsonObject_Dispose(manifest);
CkJsonObject_Dispose(identity);
CkDirTree_Dispose(cacheContents);
CkCrypt2_Dispose(crypt);
CkStringBuilder_Dispose(rangeHeader);
CkStringBuilder_Dispose(contentRange);
CkStringBuilder_Dispose(byteCount);
CkJsonObject_Dispose(receipt);
CkStringBuilder_Dispose(range);
CkStringBuilder_Dispose(digits);
CkStream_Dispose(output);
CkFileAccess_Dispose(assembled);
CkBinData_Dispose(data);