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