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