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 Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkCrypt2W.h>
#include <CkDateTimeW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
#include <CkDirTreeW.h>
#include <CkMimeW.h>
#include <CkBinDataW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// 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.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/s3.json");
if (success != true) {
wprintf(L"Could not load private S3 credentials.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"access_key"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
CkHttpW http;
http.put_AwsAccessKey(credentials.stringOf(L"access_key"));
http.put_AwsSecretKey(credentials.stringOf(L"secret_key"));
if (credentials.HasMember(L"session_token") == true) {
stringCompare.SetString(credentials.stringOf(L"session_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
wprintf(L"session_token must be a nonempty string when supplied.\n");
return;
}
http.put_AwsSessionToken(credentials.stringOf(L"session_token"));
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
const wchar_t *region = L"us-west-2";
http.put_AwsRegion(region);
CkStringBuilderW endpoint;
endpoint.Append(L"s3.");
endpoint.Append(region);
endpoint.Append(L".amazonaws.com");
http.put_AwsEndpoint(endpoint.getAsString());
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
// A region redirect is not success. Correct the endpoint and signing region.
const wchar_t *bucketName = L"your-bucket-name";
const wchar_t *objectKey = L"examples/archive.bin";
CkHttpResponseW response;
CkCrypt2W signer;
signer.put_Charset(L"utf-8");
signer.put_HashAlgorithm(L"sha256");
signer.put_EncodingMode(L"hexlower");
signer.put_MacAlgorithm(L"hmac");
CkDateTimeW now;
CkStringBuilderW timestamp;
CkStringBuilderW canonical;
CkStringBuilderW canonicalHeaders;
CkStringBuilderW signedHeaders;
CkStringBuilderW scope;
CkStringBuilderW stringToSign;
CkStringBuilderW signingKey;
CkStringBuilderW authorization;
CkStringBuilderW url;
CkStringBuilderW query;
CkStringBuilderW number;
CkStringBuilderW host;
CkStringBuilderW uri;
CkXmlW xml;
const wchar_t *amzDate = 0;
const wchar_t *dateStamp = 0;
const wchar_t *payloadHash = 0;
const wchar_t *canonicalHash = 0;
const wchar_t *derivedKey = 0;
const wchar_t *signature = 0;
int replaceCount;
host.Append(bucketName);
host.Append(L".");
host.Append(endpoint.getAsString());
// Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.urlEncode(objectKey));
replaceCount = uri.ReplaceNoCase(L"%2f",L"/");
if ((uri.StartsWith(L"/",true) == true) || (uri.Contains(L"/../",true) == true) || (uri.Contains(L"/./",true) == true)) {
wprintf(L"Use a key without a leading slash or dot path segments for these examples.\n");
return;
}
uri.Prepend(L"/");
const wchar_t *versionId = L"";
const wchar_t *etag = 0;
const wchar_t *expectedSize = 0;
const wchar_t *expectedChecksum = 0;
const wchar_t *checksumType = 0;
const wchar_t *returnedVersion = 0;
CkFileAccessW files;
const wchar_t *cacheDir = L"qa_output/s3-download-cache";
const wchar_t *manifestPath = L"qa_output/s3-download-cache/state.json";
const wchar_t *finalPath = L"qa_output/s3-resumed.bin";
const wchar_t *requestedVersionId = versionId;
CkJsonObjectW state;
state.put_Strict(true);
CkJsonObjectW identity;
bool hasCheckpoint = files.FileExists(manifestPath);
if (hasCheckpoint == true) {
success = state.LoadFile(manifestPath);
if (success != true) {
wprintf(L"Invalid download checkpoint. Preserve the cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"schema"));
bool stringMatch4 = stringCompare.ContentsEqual(L"1",true);
if (stringMatch4 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"bucket"));
bool stringMatch5 = stringCompare.ContentsEqual(bucketName,true);
if (stringMatch5 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"key"));
bool stringMatch6 = stringCompare.ContentsEqual(objectKey,true);
if (stringMatch6 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"region"));
bool stringMatch7 = stringCompare.ContentsEqual(region,true);
if (stringMatch7 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"requestedVersion"));
bool stringMatch8 = stringCompare.ContentsEqual(requestedVersionId,true);
if (stringMatch8 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"finalPath"));
bool stringMatch9 = stringCompare.ContentsEqual(finalPath,true);
if (stringMatch9 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
stringCompare.SetString(state.stringOf(L"chunkSize"));
bool stringMatch10 = stringCompare.ContentsEqual(L"8388608",true);
if (stringMatch10 != true) {
wprintf(L"Checkpoint settings differ. Use the original settings or a new empty cache.\n");
return;
}
versionId = state.stringOf(L"versionId");
if (state.JsonTypeOf(L"versionId") != 1) {
wprintf(L"Checkpoint version ID is invalid.\n");
return;
}
}
query.Clear();
stringCompare.SetString(versionId);
bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
if (stringMatch11 != true) {
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"versionId=");
query.Append(http.urlEncode(versionId));
}
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(L"");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-mode");
canonicalHeaders.Append(L"x-amz-checksum-mode:");
canonicalHeaders.Append(L"ENABLED");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-mode",L"ENABLED");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"HEAD\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.HttpNoBody(L"HEAD",url.getAsString(),response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",response.get_StatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
etag = response.getHeaderField(L"ETag");
stringCompare.SetString(etag);
bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
wprintf(L"Missing required response header ETag.\n");
return;
}
expectedSize = response.getHeaderField(L"Content-Length");
stringCompare.SetString(expectedSize);
bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch13 == true)) {
wprintf(L"Missing required response header Content-Length.\n");
return;
}
returnedVersion = response.getHeaderField(L"x-amz-version-id");
if (response.get_LastMethodSuccess() != true) {
returnedVersion = L"";
}
stringCompare.SetString(versionId);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if (stringMatch14 == true) {
versionId = returnedVersion;
}
else {
stringCompare.SetString(returnedVersion);
bool stringMatch15 = stringCompare.ContentsEqual(versionId,true);
if (stringMatch15 != true) {
wprintf(L"Unexpected object version.\n");
return;
}
}
expectedChecksum = response.getHeaderField(L"x-amz-checksum-sha256");
stringCompare.SetString(expectedChecksum);
bool stringMatch16 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch16 == true)) {
wprintf(L"Missing required response header x-amz-checksum-sha256.\n");
return;
}
checksumType = response.getHeaderField(L"x-amz-checksum-type");
stringCompare.SetString(checksumType);
bool stringMatch17 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch17 == true)) {
wprintf(L"Missing required response header x-amz-checksum-type.\n");
return;
}
stringCompare.SetString(checksumType);
bool stringMatch18 = stringCompare.ContentsEqual(L"FULL_OBJECT",true);
if (stringMatch18 != true) {
wprintf(L"This example requires a FULL_OBJECT SHA-256 checksum; COMPOSITE needs separate verification.\n");
return;
}
// Portable decimal long division; no 32-bit byte-offset overflow.
int chunkSize = 8388608;
int chunkCount = 0;
int remainder = 0;
int position = 0;
CkStringBuilderW sizeText;
CkStringBuilderW decimalDigits;
CkStringBuilderW digit;
sizeText.Append(expectedSize);
decimalDigits.Append(L"0123456789");
if ((sizeText.get_Length() == 0) || (sizeText.get_Length() > 14)) {
wprintf(L"Invalid object size.\n");
return;
}
while ((position < sizeText.get_Length())) {
digit.SetString(sizeText.getRange(position,1,false));
if (decimalDigits.Contains(digit.getAsString(),true) != true) {
wprintf(L"Invalid decimal object size.\n");
return;
}
remainder = remainder * 10 + digit.get_IntValue();
chunkCount = chunkCount * 10;
while ((remainder >= chunkSize)) {
chunkCount = chunkCount + 1;
remainder = remainder - chunkSize;
}
position = position + 1;
}
if (remainder != 0) {
chunkCount = chunkCount + 1;
}
if ((chunkCount < 1) || (chunkCount > 10000)) {
wprintf(L"Use a nonempty object of at most 10,000 fixed 8 MiB chunks; empty objects use the single-download example.\n");
return;
}
success = identity.UpdateString(L"schema",L"1");
if (success != true) {
wprintf(L"Could not save schema.\n");
return;
}
success = identity.UpdateString(L"bucket",bucketName);
if (success != true) {
wprintf(L"Could not save bucket.\n");
return;
}
success = identity.UpdateString(L"key",objectKey);
if (success != true) {
wprintf(L"Could not save key.\n");
return;
}
success = identity.UpdateString(L"region",region);
if (success != true) {
wprintf(L"Could not save region.\n");
return;
}
success = identity.UpdateString(L"requestedVersion",requestedVersionId);
if (success != true) {
wprintf(L"Could not save requestedVersion.\n");
return;
}
success = identity.UpdateString(L"versionId",versionId);
if (success != true) {
wprintf(L"Could not save versionId.\n");
return;
}
success = identity.UpdateString(L"etag",etag);
if (success != true) {
wprintf(L"Could not save etag.\n");
return;
}
success = identity.UpdateString(L"size",expectedSize);
if (success != true) {
wprintf(L"Could not save size.\n");
return;
}
success = identity.UpdateString(L"checksum",expectedChecksum);
if (success != true) {
wprintf(L"Could not save checksum.\n");
return;
}
success = identity.UpdateString(L"finalPath",finalPath);
if (success != true) {
wprintf(L"Could not save finalPath.\n");
return;
}
success = identity.UpdateString(L"chunkSize",L"8388608");
if (success != true) {
wprintf(L"Could not save chunkSize.\n");
return;
}
if (hasCheckpoint == true) {
stringCompare.SetString(state.stringOf(L"versionId"));
bool stringMatch19 = stringCompare.ContentsEqual(identity.stringOf(L"versionId"),true);
if (stringMatch19 != true) {
wprintf(L"Object identity changed. Do not mix old cached bytes with this object.\n");
return;
}
stringCompare.SetString(state.stringOf(L"etag"));
bool stringMatch20 = stringCompare.ContentsEqual(identity.stringOf(L"etag"),true);
if (stringMatch20 != true) {
wprintf(L"Object identity changed. Do not mix old cached bytes with this object.\n");
return;
}
stringCompare.SetString(state.stringOf(L"size"));
bool stringMatch21 = stringCompare.ContentsEqual(identity.stringOf(L"size"),true);
if (stringMatch21 != true) {
wprintf(L"Object identity changed. Do not mix old cached bytes with this object.\n");
return;
}
stringCompare.SetString(state.stringOf(L"checksum"));
bool stringMatch22 = stringCompare.ContentsEqual(identity.stringOf(L"checksum"),true);
if (stringMatch22 != true) {
wprintf(L"Object identity changed. Do not mix old cached bytes with this object.\n");
return;
}
}
else {
success = files.DirEnsureExists(cacheDir);
if (success != true) {
wprintf(L"Could not create private cache.\n");
return;
}
CkDirTreeW entries;
entries.put_BaseDir(cacheDir);
entries.put_Recurse(false);
success = entries.BeginIterate();
if ((success == true) || (entries.get_DoneIterating() != true)) {
wprintf(L"First download requires an empty, readable cache directory.\n");
return;
}
success = identity.WriteFile(L"qa_output/s3-download-cache/state.json.tmp");
if (success != true) {
wprintf(L"Could not save download identity.\n");
return;
}
success = files.FileRename(L"qa_output/s3-download-cache/state.json.tmp",manifestPath);
if (success != true) {
wprintf(L"Checkpoint remains at its temporary path.\n");
return;
}
}
CkCrypt2W digest;
digest.put_HashAlgorithm(L"sha256");
digest.put_EncodingMode(L"base64");
if (files.FileExists(finalPath) == true) {
const wchar_t *existingSize = files.fileSizeStr(finalPath);
const wchar_t *existingChecksum = digest.hashFileENC(finalPath);
stringCompare.SetString(existingSize);
bool stringMatch23 = stringCompare.ContentsEqual(expectedSize,true);
stringCompare.SetString(existingChecksum);
bool stringMatch24 = stringCompare.ContentsEqual(expectedChecksum,true);
if ((digest.get_LastMethodSuccess() != true) || (stringMatch23 != true) || (stringMatch24 != true)) {
wprintf(L"Existing final file does not match; preserve it.\n");
return;
}
wprintf(L"Object already downloaded and checksum verified.\n");
return;
}
digest.put_EncodingMode(L"hexlower");
CkStringBuilderW path;
CkStringBuilderW range;
CkStringBuilderW digits;
CkStringBuilderW rangeHeader;
CkStringBuilderW contentRange;
CkStringBuilderW byteCount;
CkJsonObjectW receipt;
receipt.put_Strict(true);
CkMimeW received;
int chunkIndex = 0;
int byteHigh = 0;
int byteLow = 0;
int endHigh;
int endLow;
const wchar_t *actualRange = 0;
const wchar_t *actualLength = 0;
const wchar_t *actualEtag = 0;
const wchar_t *actualVersion = 0;
const wchar_t *actualSize = 0;
const wchar_t *actualHash = 0;
while ((chunkIndex < chunkCount)) {
int chunkBytes = chunkSize;
if ((chunkIndex == chunkCount - 1) && (remainder != 0)) {
chunkBytes = remainder;
}
range.Clear();
digits.Clear();
digits.AppendInt(byteLow);
if (byteHigh > 0) {
while ((digits.get_Length() < 9)) {
digits.Prepend(L"0");
}
range.AppendInt(byteHigh);
}
range.Append(digits.getAsString());
range.Append(L"-");
endHigh = byteHigh;
endLow = byteLow + chunkBytes - 1;
if (endLow >= 1000000000) {
endLow = endLow - 1000000000;
endHigh = endHigh + 1;
}
digits.Clear();
digits.AppendInt(endLow);
if (endHigh > 0) {
while ((digits.get_Length() < 9)) {
digits.Prepend(L"0");
}
range.AppendInt(endHigh);
}
range.Append(digits.getAsString());
const wchar_t *rangeKey = range.getAsString();
rangeHeader.SetString(L"bytes=");
rangeHeader.Append(rangeKey);
contentRange.SetString(L"bytes ");
contentRange.Append(rangeKey);
contentRange.Append(L"/");
contentRange.Append(expectedSize);
byteCount.Clear();
byteCount.AppendInt(chunkBytes);
path.SetString(cacheDir);
path.Append(L"/chunk-");
path.AppendInt(chunkIndex);
const wchar_t *chunkPath = path.getAsString();
path.Append(L".json");
const wchar_t *receiptPath = path.getAsString();
path.SetString(chunkPath);
path.Append(L".part");
const wchar_t *partialPath = path.getAsString();
if (files.FileExists(chunkPath) == true) {
success = receipt.LoadFile(receiptPath);
if (success != true) {
wprintf(L"Cached chunk has no valid receipt. Preserve the cache.\n");
return;
}
actualHash = digest.hashFileENC(chunkPath);
stringCompare.SetString(actualHash);
bool stringMatch25 = stringCompare.ContentsEqual(receipt.stringOf(L"hash"),true);
stringCompare.SetString(receipt.stringOf(L"range"));
bool stringMatch26 = stringCompare.ContentsEqual(rangeKey,true);
stringCompare.SetString(files.fileSizeStr(chunkPath));
bool stringMatch27 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
if ((digest.get_LastMethodSuccess() != true) || (stringMatch25 != true) || (stringMatch26 != true) || (stringMatch27 != true)) {
wprintf(L"Cached chunk failed verification. Remove only this chunk and receipt before retrying.\n");
return;
}
wprintf(L"Reusing verified chunk: %d\n",chunkIndex);
}
else {
query.Clear();
stringCompare.SetString(versionId);
bool stringMatch28 = stringCompare.ContentsEqual(L"",true);
if (stringMatch28 != true) {
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"versionId=");
query.Append(http.urlEncode(versionId));
}
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(L"");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"if-match");
canonicalHeaders.Append(L"if-match:");
canonicalHeaders.Append(etag);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"if-match",etag);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"range");
canonicalHeaders.Append(L"range:");
canonicalHeaders.Append(rangeHeader.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"range",rangeHeader.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"GET\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.Download(url.getAsString(),partialPath);
if ((http.get_LastStatus() == 412) || (http.get_LastStatus() == 416)) {
wprintf(L"Object changed or range is invalid. Preserve the cache; do not append.\n");
return;
}
if ((success != true) || (http.get_LastStatus() != 206)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",http.get_LastStatus());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
success = received.LoadMime(http.lastResponseHeader());
if (success != true) {
wprintf(L"Could not parse range response.\n");
return;
}
actualRange = received.getHeaderField(L"Content-Range");
stringCompare.SetString(actualRange);
bool stringMatch29 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch29 == true)) {
wprintf(L"Missing download header Content-Range.\n");
return;
}
actualLength = received.getHeaderField(L"Content-Length");
stringCompare.SetString(actualLength);
bool stringMatch30 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch30 == true)) {
wprintf(L"Missing download header Content-Length.\n");
return;
}
actualEtag = received.getHeaderField(L"ETag");
stringCompare.SetString(actualEtag);
bool stringMatch31 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch31 == true)) {
wprintf(L"Missing download header ETag.\n");
return;
}
stringCompare.SetString(actualRange);
bool stringMatch32 = stringCompare.ContentsEqual(contentRange.getAsString(),true);
stringCompare.SetString(actualLength);
bool stringMatch33 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
stringCompare.SetString(actualEtag);
bool stringMatch34 = stringCompare.ContentsEqual(etag,true);
if ((stringMatch32 != true) || (stringMatch33 != true) || (stringMatch34 != true)) {
wprintf(L"Unexpected range response; no chunk committed.\n");
return;
}
stringCompare.SetString(versionId);
bool stringMatch35 = stringCompare.ContentsEqual(L"",true);
if (stringMatch35 != true) {
actualVersion = received.getHeaderField(L"x-amz-version-id");
stringCompare.SetString(actualVersion);
bool stringMatch36 = stringCompare.ContentsEqual(L"",true);
if ((received.get_LastMethodSuccess() != true) || (stringMatch36 == true)) {
wprintf(L"Missing download header x-amz-version-id.\n");
return;
}
stringCompare.SetString(actualVersion);
bool stringMatch37 = stringCompare.ContentsEqual(versionId,true);
if (stringMatch37 != true) {
wprintf(L"Unexpected returned version.\n");
return;
}
}
actualSize = files.fileSizeStr(partialPath);
stringCompare.SetString(actualSize);
bool stringMatch38 = stringCompare.ContentsEqual(byteCount.getAsString(),true);
if ((files.get_LastMethodSuccess() != true) || (stringMatch38 != true)) {
wprintf(L"Range byte count mismatch.\n");
return;
}
actualHash = digest.hashFileENC(partialPath);
if (digest.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash range bytes.\n");
return;
}
success = receipt.UpdateString(L"range",rangeKey);
if (success != true) {
wprintf(L"Could not save range.\n");
return;
}
success = receipt.UpdateString(L"hash",actualHash);
if (success != true) {
wprintf(L"Could not save hash.\n");
return;
}
success = receipt.WriteFile(receiptPath);
if (success != true) {
wprintf(L"Could not save chunk receipt.\n");
return;
}
success = files.FileRename(partialPath,chunkPath);
if (success != true) {
wprintf(L"Could not commit downloaded chunk.\n");
return;
}
wprintf(L"Downloaded chunk: %d\n",chunkIndex);
}
byteHigh = endHigh;
byteLow = endLow + 1;
if (byteLow == 1000000000) {
byteLow = 0;
byteHigh = byteHigh + 1;
}
chunkIndex = chunkIndex + 1;
}
// 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.
const wchar_t *assembledPath = L"qa_output/s3-download-cache/assembled.part";
CkFileAccessW assembled;
success = assembled.OpenForWrite(assembledPath);
if (success != true) {
wprintf(L"Could not open assembly file.\n");
return;
}
CkBinDataW data;
chunkIndex = 0;
while ((chunkIndex < chunkCount)) {
path.SetString(cacheDir);
path.Append(L"/chunk-");
path.AppendInt(chunkIndex);
data.Clear();
success = data.LoadFile(path.getAsString());
if (success == true) {
success = assembled.FileWriteBd(data,0,0);
}
if (success != true) {
assembled.FileClose();
wprintf(L"Assembly failed; verified progress is retained.\n");
return;
}
chunkIndex = chunkIndex + 1;
}
assembled.FileClose();
actualSize = files.fileSizeStr(assembledPath);
digest.put_EncodingMode(L"base64");
actualHash = digest.hashFileENC(assembledPath);
stringCompare.SetString(actualSize);
bool stringMatch39 = stringCompare.ContentsEqual(expectedSize,true);
stringCompare.SetString(actualHash);
bool stringMatch40 = stringCompare.ContentsEqual(expectedChecksum,true);
if ((digest.get_LastMethodSuccess() != true) || (stringMatch39 != true) || (stringMatch40 != true)) {
wprintf(L"Assembled object checksum/size mismatch; final file not created.\n");
return;
}
success = files.FileRename(assembledPath,finalPath);
if (success != true) {
wprintf(L"Verified assembly remains in cache; rename failed.\n");
return;
}
wprintf(L"Resumable download completed and checksum verified. Cache retained for manual cleanup.\n");
}