S3 Http: Resume and Recover a Multipart Upload
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.
Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.
Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.
Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.
Lists all uploaded parts and reuses only parts whose SHA-256 and byte count match the local source; mismatched parts are replaced. If ListParts returns NoSuchUpload after a recorded completion attempt, a checksum-enabled HEAD must match the unique upload token, source hash, composite checksum and size before recovery is reported. A missing upload alone is never treated as completion. If another write has replaced the current object, inspect version history manually.
Chilkat Delphi ActiveX Downloads
var
success: Integer;
stringCompare: TChilkatStringBuilder;
credentials: TChilkatJsonObject;
stringMatch1: Integer;
stringMatch2: Integer;
http: TChilkatHttp;
stringMatch3: Integer;
region: WideString;
endpoint: TChilkatStringBuilder;
bucketName: WideString;
objectKey: WideString;
response: TChilkatHttpResponse;
signer: TChilkatCrypt2;
now: TCkDateTime;
timestamp: TChilkatStringBuilder;
canonical: TChilkatStringBuilder;
canonicalHeaders: TChilkatStringBuilder;
signedHeaders: TChilkatStringBuilder;
scope: TChilkatStringBuilder;
stringToSign: TChilkatStringBuilder;
signingKey: TChilkatStringBuilder;
authorization: TChilkatStringBuilder;
url: TChilkatStringBuilder;
query: TChilkatStringBuilder;
number: TChilkatStringBuilder;
host: TChilkatStringBuilder;
uri: TChilkatStringBuilder;
xml: TChilkatXml;
amzDate: WideString;
dateStamp: WideString;
payloadHash: WideString;
canonicalHash: WideString;
derivedKey: WideString;
signature: WideString;
replaceCount: Integer;
files: TCkFileAccess;
filePath: WideString;
fileSize: WideString;
digest: TChilkatCrypt2;
sourceHash: WideString;
sourceChecksum: WideString;
statePath: WideString;
pendingPath: WideString;
receiptPath: WideString;
state: TChilkatJsonObject;
pending: TChilkatJsonObject;
uploadId: WideString;
uploadToken: WideString;
compositeChecksum: WideString;
partSize: Integer;
numParts: Integer;
remoteEtags: TChilkatHashtable;
remoteSizes: TChilkatHashtable;
remoteChecksums: TChilkatHashtable;
partNumbers: TChilkatHashtable;
partNumberText: TChilkatStringBuilder;
stringMatch4: Integer;
stringMatch5: Integer;
stringMatch6: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
stringMatch9: Integer;
stringMatch10: Integer;
stringMatch11: Integer;
stringMatch12: Integer;
stringMatch13: Integer;
stringMatch14: Integer;
stringMatch15: Integer;
seen: TChilkatHashtable;
more: Integer;
page: Integer;
marker: WideString;
truncated: WideString;
item: WideString;
stringMatch16: Integer;
stringMatch17: Integer;
stringMatch18: Integer;
stringMatch19: Integer;
stringMatch20: Integer;
stringMatch21: Integer;
stringMatch22: Integer;
stringMatch23: Integer;
stringMatch24: Integer;
stringMatch25: Integer;
stringMatch26: Integer;
stringMatch27: Integer;
i: Integer;
remoteNumber: Integer;
stringMatch28: Integer;
stringMatch29: Integer;
stringMatch30: Integer;
stringMatch31: Integer;
stringMatch32: Integer;
stringMatch33: Integer;
stringMatch34: Integer;
part: TChilkatBinData;
concatenatedDigests: TChilkatBinData;
completion: TChilkatXml;
partIndex: Integer;
partChecksum: WideString;
partEtag: WideString;
partHash: WideString;
confirmed: WideString;
sizeText: WideString;
partNumberKey: WideString;
reuse: Integer;
stringMatch35: Integer;
stringMatch36: Integer;
stringMatch37: Integer;
stringMatch38: Integer;
stringMatch39: Integer;
stringMatch40: Integer;
finalSourceHash: WideString;
stringMatch41: Integer;
requestBody: WideString;
stringMatch42: Integer;
stringMatch43: Integer;
stringMatch44: Integer;
begin
success := 0;
stringCompare := TChilkatStringBuilder.Create(Self);
// 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 := TChilkatJsonObject.Create(Self);
credentials.Strict := 1;
success := credentials.LoadFile('qa_data/aws/s3.json');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load private S3 credentials.');
Exit;
end;
stringCompare.SetString(credentials.StringOf('access_key'));
stringMatch1 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('access_key') <> 1) or (stringMatch1 = 1)) then
begin
Memo1.Lines.Add('Missing or invalid access_key.');
Exit;
end;
stringCompare.SetString(credentials.StringOf('secret_key'));
stringMatch2 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('secret_key') <> 1) or (stringMatch2 = 1)) then
begin
Memo1.Lines.Add('Missing or invalid secret_key.');
Exit;
end;
http := TChilkatHttp.Create(Self);
http.AwsAccessKey := credentials.StringOf('access_key');
http.AwsSecretKey := credentials.StringOf('secret_key');
if (credentials.HasMember('session_token') = 1) then
begin
stringCompare.SetString(credentials.StringOf('session_token'));
stringMatch3 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('session_token') <> 1) or (stringMatch3 = 1)) then
begin
Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
Exit;
end;
http.AwsSessionToken := credentials.StringOf('session_token');
end;
// 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 := TChilkatStringBuilder.Create(Self);
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 := TChilkatHttpResponse.Create(Self);
signer := TChilkatCrypt2.Create(Self);
signer.Charset := 'utf-8';
signer.HashAlgorithm := 'sha256';
signer.EncodingMode := 'hexlower';
signer.MacAlgorithm := 'hmac';
now := TCkDateTime.Create(Self);
timestamp := TChilkatStringBuilder.Create(Self);
canonical := TChilkatStringBuilder.Create(Self);
canonicalHeaders := TChilkatStringBuilder.Create(Self);
signedHeaders := TChilkatStringBuilder.Create(Self);
scope := TChilkatStringBuilder.Create(Self);
stringToSign := TChilkatStringBuilder.Create(Self);
signingKey := TChilkatStringBuilder.Create(Self);
authorization := TChilkatStringBuilder.Create(Self);
url := TChilkatStringBuilder.Create(Self);
query := TChilkatStringBuilder.Create(Self);
number := TChilkatStringBuilder.Create(Self);
host := TChilkatStringBuilder.Create(Self);
uri := TChilkatStringBuilder.Create(Self);
xml := TChilkatXml.Create(Self);
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)) then
begin
Memo1.Lines.Add('Use a key without a leading slash or dot path segments for these examples.');
Exit;
end;
uri.Prepend('/');
files := TCkFileAccess.Create(Self);
filePath := 'qa_data/bin/archive.bin';
fileSize := files.FileSizeStr(filePath);
if (files.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not read source file size.');
Exit;
end;
digest := TChilkatCrypt2.Create(Self);
digest.HashAlgorithm := 'sha256';
digest.EncodingMode := 'hexlower';
sourceHash := digest.HashFileENC(filePath);
if (digest.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash source file.');
Exit;
end;
digest.EncodingMode := 'base64';
sourceChecksum := digest.HashFileENC(filePath);
if (digest.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not compute checksum.');
Exit;
end;
statePath := 'qa_output/s3-multipart/state.json';
pendingPath := 'qa_output/s3-multipart/completion.json';
receiptPath := 'qa_output/s3-multipart/completed.json';
state := TChilkatJsonObject.Create(Self);
state.Strict := 1;
pending := TChilkatJsonObject.Create(Self);
pending.Strict := 1;
success := files.OpenForRead(filePath);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not open immutable source file.');
Exit;
end;
partSize := 8388608;
numParts := files.GetNumBlocks(partSize);
if ((numParts < 1) or (numParts > 10000)) then
begin
Memo1.Lines.Add('Use a nonempty source of at most 10,000 fixed 8 MiB parts.');
Exit;
end;
remoteEtags := TChilkatHashtable.Create(Self);
remoteSizes := TChilkatHashtable.Create(Self);
remoteChecksums := TChilkatHashtable.Create(Self);
partNumbers := TChilkatHashtable.Create(Self);
partNumberText := TChilkatStringBuilder.Create(Self);
success := state.LoadFile(statePath);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not load multipart checkpoint.');
Exit;
end;
stringCompare.SetString(state.StringOf('schema'));
stringMatch4 := stringCompare.ContentsEqual('1',1);
if (stringMatch4 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('bucket'));
stringMatch5 := stringCompare.ContentsEqual(bucketName,1);
if (stringMatch5 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('key'));
stringMatch6 := stringCompare.ContentsEqual(objectKey,1);
if (stringMatch6 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('region'));
stringMatch7 := stringCompare.ContentsEqual(region,1);
if (stringMatch7 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('filePath'));
stringMatch8 := stringCompare.ContentsEqual(filePath,1);
if (stringMatch8 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('fileSize'));
stringMatch9 := stringCompare.ContentsEqual(fileSize,1);
if (stringMatch9 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('sourceHash'));
stringMatch10 := stringCompare.ContentsEqual(sourceHash,1);
if (stringMatch10 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
stringCompare.SetString(state.StringOf('partSize'));
stringMatch11 := stringCompare.ContentsEqual('8388608',1);
if (stringMatch11 <> 1) then
begin
Memo1.Lines.Add('Checkpoint/source identity differs. Do not resume another file or destination.');
Exit;
end;
uploadId := state.StringOf('uploadId');
uploadToken := state.StringOf('uploadToken');
stringCompare.SetString(uploadId);
stringMatch12 := stringCompare.ContentsEqual('',1);
stringCompare.SetString(uploadToken);
stringMatch13 := stringCompare.ContentsEqual('',1);
if ((stringMatch12 = 1) or (stringMatch13 = 1) or (state.JsonTypeOf('uploadId') <> 1) or (state.JsonTypeOf('uploadToken') <> 1)) then
begin
Memo1.Lines.Add('Checkpoint has no upload identity.');
Exit;
end;
if (files.FileExists(receiptPath) = 1) then
begin
success := pending.LoadFile(receiptPath);
if (success <> 1) then
begin
Memo1.Lines.Add('Invalid completion receipt.');
Exit;
end;
stringCompare.SetString(pending.StringOf('uploadId'));
stringMatch14 := stringCompare.ContentsEqual(uploadId,1);
stringCompare.SetString(pending.StringOf('sourceHash'));
stringMatch15 := stringCompare.ContentsEqual(sourceHash,1);
if ((stringMatch14 <> 1) or (stringMatch15 <> 1)) then
begin
Memo1.Lines.Add('Completion receipt belongs to another upload.');
Exit;
end;
Memo1.Lines.Add('Multipart upload already completed; receipt retained.');
Exit;
end;
seen := TChilkatHashtable.Create(Self);
more := 1;
page := 0;
marker := '';
while (more = 1) do
begin
if (page = 10000) then
begin
Memo1.Lines.Add('Page bound reached; results are incomplete.');
Exit;
end;
page := page + 1;
query.Clear();
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('max-parts=');
query.Append(http.UrlEncode('1000'));
stringCompare.SetString(marker);
stringMatch16 := stringCompare.ContentsEqual('',1);
if (stringMatch16 <> 1) then
begin
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('part-number-marker=');
query.Append(http.UrlEncode(marker));
end;
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('uploadId=');
query.Append(http.UrlEncode(uploadId));
http.ClearHeaders();
success := now.SetFromCurrentSystemTime();
if (success <> 1) then
begin
Memo1.Lines.Add('Could not read system time.');
Exit;
end;
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) then
begin
Memo1.Lines.Add('Could not hash payload.');
Exit;
end;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('host');
canonicalHeaders.Append('host:');
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append(#10);
http.SetRequestHeader('host',host.GetAsString());
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-content-sha256');
canonicalHeaders.Append('x-amz-content-sha256:');
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-content-sha256',payloadHash);
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-date');
canonicalHeaders.Append('x-amz-date:');
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-date',amzDate);
if (credentials.HasMember('session_token') = 1) then
begin
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-security-token');
canonicalHeaders.Append('x-amz-security-token:');
canonicalHeaders.Append(credentials.StringOf('session_token'));
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
end;
canonical.Clear();
canonical.Append('GET' + #10);
canonical.Append(uri.GetAsString());
canonical.Append(#10);
canonical.Append(query.GetAsString());
canonical.Append(#10);
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(signedHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(payloadHash);
canonicalHash := signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash canonical request.');
Exit;
end;
scope.Clear();
scope.Append(dateStamp);
scope.Append('/');
scope.Append(region);
scope.Append('/s3/aws4_request');
stringToSign.Clear();
stringToSign.Append('AWS4-HMAC-SHA256' + #10);
stringToSign.Append(amzDate);
stringToSign.Append(#10);
stringToSign.Append(scope.GetAsString());
stringToSign.Append(#10);
stringToSign.Append(canonicalHash);
signingKey.SetString('AWS4');
signingKey.Append(credentials.StringOf('secret_key'));
success := signer.SetMacKeyString(signingKey.GetAsString());
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(region);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('s3');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('aws4_request');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
signature := signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not sign request.');
Exit;
end;
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) then
begin
url.Append('?');
url.Append(query.GetAsString());
end;
success := http.HttpNoBody('GET',url.GetAsString(),response.ControlInterface);
if (response.StatusCode = 404) then
begin
success := xml.LoadXml(response.BodyStr);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not parse missing-upload response.');
Exit;
end;
stringCompare.SetString(xml.GetChildContent('Code'));
stringMatch17 := stringCompare.ContentsEqual('NoSuchUpload',1);
if (stringMatch17 <> 1) then
begin
Memo1.Lines.Add('404 was not NoSuchUpload; inspect target bucket/key.');
Exit;
end;
success := pending.LoadFile(pendingPath);
if (success <> 1) then
begin
Memo1.Lines.Add('Upload no longer exists. No valid pending completion record; inspect object state manually.');
Exit;
end;
stringCompare.SetString(pending.StringOf('uploadId'));
stringMatch18 := stringCompare.ContentsEqual(uploadId,1);
if (stringMatch18 <> 1) then
begin
Memo1.Lines.Add('Pending completion does not match this upload.');
Exit;
end;
stringCompare.SetString(pending.StringOf('sourceHash'));
stringMatch19 := stringCompare.ContentsEqual(sourceHash,1);
if (stringMatch19 <> 1) then
begin
Memo1.Lines.Add('Pending completion does not match this upload.');
Exit;
end;
stringCompare.SetString(pending.StringOf('uploadToken'));
stringMatch20 := stringCompare.ContentsEqual(uploadToken,1);
if (stringMatch20 <> 1) then
begin
Memo1.Lines.Add('Pending completion does not match this upload.');
Exit;
end;
compositeChecksum := pending.StringOf('checksum');
stringCompare.SetString(compositeChecksum);
stringMatch21 := stringCompare.ContentsEqual('',1);
if ((pending.LastMethodSuccess <> 1) or (stringMatch21 = 1)) then
begin
Memo1.Lines.Add('Missing pending checksum.');
Exit;
end;
query.Clear();
http.ClearHeaders();
success := now.SetFromCurrentSystemTime();
if (success <> 1) then
begin
Memo1.Lines.Add('Could not read system time.');
Exit;
end;
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) then
begin
Memo1.Lines.Add('Could not hash payload.');
Exit;
end;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('host');
canonicalHeaders.Append('host:');
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append(#10);
http.SetRequestHeader('host',host.GetAsString());
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-checksum-mode');
canonicalHeaders.Append('x-amz-checksum-mode:');
canonicalHeaders.Append('ENABLED');
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-checksum-mode','ENABLED');
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-content-sha256');
canonicalHeaders.Append('x-amz-content-sha256:');
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-content-sha256',payloadHash);
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-date');
canonicalHeaders.Append('x-amz-date:');
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-date',amzDate);
if (credentials.HasMember('session_token') = 1) then
begin
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-security-token');
canonicalHeaders.Append('x-amz-security-token:');
canonicalHeaders.Append(credentials.StringOf('session_token'));
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
end;
canonical.Clear();
canonical.Append('HEAD' + #10);
canonical.Append(uri.GetAsString());
canonical.Append(#10);
canonical.Append(query.GetAsString());
canonical.Append(#10);
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(signedHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(payloadHash);
canonicalHash := signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash canonical request.');
Exit;
end;
scope.Clear();
scope.Append(dateStamp);
scope.Append('/');
scope.Append(region);
scope.Append('/s3/aws4_request');
stringToSign.Clear();
stringToSign.Append('AWS4-HMAC-SHA256' + #10);
stringToSign.Append(amzDate);
stringToSign.Append(#10);
stringToSign.Append(scope.GetAsString());
stringToSign.Append(#10);
stringToSign.Append(canonicalHash);
signingKey.SetString('AWS4');
signingKey.Append(credentials.StringOf('secret_key'));
success := signer.SetMacKeyString(signingKey.GetAsString());
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(region);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('s3');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('aws4_request');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
signature := signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not sign request.');
Exit;
end;
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) then
begin
url.Append('?');
url.Append(query.GetAsString());
end;
success := http.HttpNoBody('HEAD',url.GetAsString(),response.ControlInterface);
if ((success <> 1) or (response.StatusCode <> 200)) then
begin
Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(response.StatusCode));
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit;
end;
stringCompare.SetString(response.GetHeaderField('x-amz-meta-upload-token'));
stringMatch22 := stringCompare.ContentsEqual(uploadToken,1);
if (stringMatch22 <> 1) then
begin
Memo1.Lines.Add('Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.');
Exit;
end;
stringCompare.SetString(response.GetHeaderField('x-amz-meta-source-sha256'));
stringMatch23 := stringCompare.ContentsEqual(sourceHash,1);
if (stringMatch23 <> 1) then
begin
Memo1.Lines.Add('Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.');
Exit;
end;
stringCompare.SetString(response.GetHeaderField('x-amz-checksum-sha256'));
stringMatch24 := stringCompare.ContentsEqual(compositeChecksum,1);
if (stringMatch24 <> 1) then
begin
Memo1.Lines.Add('Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.');
Exit;
end;
stringCompare.SetString(response.GetHeaderField('x-amz-checksum-type'));
stringMatch25 := stringCompare.ContentsEqual('COMPOSITE',1);
if (stringMatch25 <> 1) then
begin
Memo1.Lines.Add('Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.');
Exit;
end;
stringCompare.SetString(response.GetHeaderField('Content-Length'));
stringMatch26 := stringCompare.ContentsEqual(fileSize,1);
if (stringMatch26 <> 1) then
begin
Memo1.Lines.Add('Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.');
Exit;
end;
success := state.UpdateString('compositeChecksum',compositeChecksum);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save compositeChecksum.');
Exit;
end;
success := state.WriteFile('qa_output/s3-multipart/completed.json.tmp');
if (success <> 1) then
begin
Memo1.Lines.Add('Completion succeeded but receipt could not be saved; preserve the checkpoint.');
Exit;
end;
success := files.FileRename('qa_output/s3-multipart/completed.json.tmp',receiptPath);
if (success <> 1) then
begin
Memo1.Lines.Add('Completion receipt remains at its temporary path.');
Exit;
end;
Memo1.Lines.Add('Multipart upload completed and verified.');
Exit;
end;
if ((success <> 1) or (response.StatusCode <> 200)) then
begin
Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(response.StatusCode));
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit;
end;
success := xml.LoadXml(response.BodyStr);
if (success <> 1) then
begin
Memo1.Lines.Add('Invalid XML response.');
Exit;
end;
stringCompare.SetString(xml.Tag);
stringMatch27 := stringCompare.ContentsEqual('ListPartsResult',1);
if (stringMatch27 <> 1) then
begin
Memo1.Lines.Add('Unexpected XML result, possibly an embedded S3 error. Inspect privately.');
Exit;
end;
i := 0;
while (i < xml.NumChildrenHavingTag('Part')) do
begin
xml.I := i;
remoteNumber := xml.GetChildIntValue('Part[i]|PartNumber');
if ((xml.LastMethodSuccess <> 1) or (remoteNumber < 1) or (remoteNumber > numParts)) then
begin
Memo1.Lines.Add('Unexpected remote part number.');
Exit;
end;
partNumberText.Clear();
partNumberText.AppendInt(remoteNumber);
if (partNumbers.Contains(partNumberText.GetAsString()) = 1) then
begin
Memo1.Lines.Add('Duplicate remote part number.');
Exit;
end;
success := partNumbers.AddStr(partNumberText.GetAsString(),'seen');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not track remote part.');
Exit;
end;
item := xml.GetChildContent('Part[i]|ETag');
stringCompare.SetString(item);
stringMatch28 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch28 = 1)) then
begin
Memo1.Lines.Add('Missing required Part[i]|ETag.');
Exit;
end;
success := remoteEtags.AddStr(partNumberText.GetAsString(),item);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not retain part ETag.');
Exit;
end;
item := xml.GetChildContent('Part[i]|Size');
stringCompare.SetString(item);
stringMatch29 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch29 = 1)) then
begin
Memo1.Lines.Add('Missing required Part[i]|Size.');
Exit;
end;
success := remoteSizes.AddStr(partNumberText.GetAsString(),item);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not retain part size.');
Exit;
end;
item := xml.GetChildContent('Part[i]|ChecksumSHA256');
if (xml.LastMethodSuccess = 1) then
begin
success := remoteChecksums.AddStr(partNumberText.GetAsString(),item);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not retain part checksum.');
Exit;
end;
end;
i := i + 1;
end;
truncated := xml.GetChildContent('IsTruncated');
stringCompare.SetString(truncated);
stringMatch30 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch30 = 1)) then
begin
Memo1.Lines.Add('Missing required IsTruncated.');
Exit;
end;
stringCompare.SetString(truncated);
stringMatch31 := stringCompare.ContentsEqual('true',1);
stringCompare.SetString(truncated);
stringMatch32 := stringCompare.ContentsEqual('false',1);
if ((stringMatch31 <> 1) and (stringMatch32 <> 1)) then
begin
Memo1.Lines.Add('Invalid IsTruncated; results are incomplete.');
Exit;
end;
more := 0;
stringCompare.SetString(truncated);
stringMatch33 := stringCompare.ContentsEqual('true',1);
if (stringMatch33 = 1) then
begin
marker := xml.GetChildContent('NextPartNumberMarker');
stringCompare.SetString(marker);
stringMatch34 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch34 = 1)) then
begin
Memo1.Lines.Add('Missing required NextPartNumberMarker.');
Exit;
end;
if (seen.Contains(marker) = 1) then
begin
Memo1.Lines.Add('Repeated pagination marker; results are incomplete.');
Exit;
end;
success := seen.AddStr(marker,'seen');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not track marker.');
Exit;
end;
more := 1;
end;
end;
part := TChilkatBinData.Create(Self);
concatenatedDigests := TChilkatBinData.Create(Self);
completion := TChilkatXml.Create(Self);
completion.Tag := 'CompleteMultipartUpload';
completion.AddAttribute('xmlns','http://s3.amazonaws.com/doc/2006-03-01/');
partIndex := 0;
while (partIndex < numParts) do
begin
part.Clear();
success := files.ReadBlockBd(partIndex,partSize,part.ControlInterface);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not read source part; preserve checkpoint.');
Exit;
end;
if ((part.NumBytes = 0) or ((partIndex < numParts - 1) and (part.NumBytes <> partSize))) then
begin
Memo1.Lines.Add('Source changed or part read was incomplete.');
Exit;
end;
partChecksum := digest.HashBdENC(part.ControlInterface);
if (digest.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not checksum part.');
Exit;
end;
partHash := signer.HashBdENC(part.ControlInterface);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash part.');
Exit;
end;
success := concatenatedDigests.AppendEncoded(partChecksum,'base64');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not accumulate part digests.');
Exit;
end;
partNumberText.Clear();
partNumberText.AppendInt(partIndex + 1);
number.Clear();
number.AppendInt(part.NumBytes);
sizeText := number.GetAsString();
partNumberKey := partNumberText.GetAsString();
reuse := 0;
partEtag := '';
if (remoteChecksums.Contains(partNumberKey) = 1) then
begin
stringCompare.SetString(remoteChecksums.LookupStr(partNumberKey));
stringMatch35 := stringCompare.ContentsEqual(partChecksum,1);
stringCompare.SetString(remoteSizes.LookupStr(partNumberKey));
stringMatch36 := stringCompare.ContentsEqual(sizeText,1);
if ((stringMatch35 = 1) and (stringMatch36 = 1)) then
begin
partEtag := remoteEtags.LookupStr(partNumberKey);
stringCompare.SetString(partEtag);
stringMatch37 := stringCompare.ContentsEqual('',1);
if ((remoteEtags.LastMethodSuccess = 1) and (stringMatch37 <> 1)) then
begin
reuse := 1;
end;
end;
end;
if (reuse <> 1) then
begin
query.Clear();
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('partNumber=');
query.Append(http.UrlEncode(partNumberText.GetAsString()));
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('uploadId=');
query.Append(http.UrlEncode(uploadId));
http.ClearHeaders();
success := now.SetFromCurrentSystemTime();
if (success <> 1) then
begin
Memo1.Lines.Add('Could not read system time.');
Exit;
end;
timestamp.SetString(now.GetAsTimestamp(0));
replaceCount := timestamp.Replace('-','');
replaceCount := timestamp.Replace(':','');
amzDate := timestamp.GetAsString();
dateStamp := timestamp.GetRange(0,8,0);
payloadHash := partHash;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('host');
canonicalHeaders.Append('host:');
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append(#10);
http.SetRequestHeader('host',host.GetAsString());
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-checksum-sha256');
canonicalHeaders.Append('x-amz-checksum-sha256:');
canonicalHeaders.Append(partChecksum);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-checksum-sha256',partChecksum);
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-content-sha256');
canonicalHeaders.Append('x-amz-content-sha256:');
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-content-sha256',payloadHash);
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-date');
canonicalHeaders.Append('x-amz-date:');
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-date',amzDate);
if (credentials.HasMember('session_token') = 1) then
begin
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-security-token');
canonicalHeaders.Append('x-amz-security-token:');
canonicalHeaders.Append(credentials.StringOf('session_token'));
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
end;
canonical.Clear();
canonical.Append('PUT' + #10);
canonical.Append(uri.GetAsString());
canonical.Append(#10);
canonical.Append(query.GetAsString());
canonical.Append(#10);
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(signedHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(payloadHash);
canonicalHash := signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash canonical request.');
Exit;
end;
scope.Clear();
scope.Append(dateStamp);
scope.Append('/');
scope.Append(region);
scope.Append('/s3/aws4_request');
stringToSign.Clear();
stringToSign.Append('AWS4-HMAC-SHA256' + #10);
stringToSign.Append(amzDate);
stringToSign.Append(#10);
stringToSign.Append(scope.GetAsString());
stringToSign.Append(#10);
stringToSign.Append(canonicalHash);
signingKey.SetString('AWS4');
signingKey.Append(credentials.StringOf('secret_key'));
success := signer.SetMacKeyString(signingKey.GetAsString());
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(region);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('s3');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('aws4_request');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
signature := signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not sign request.');
Exit;
end;
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) then
begin
url.Append('?');
url.Append(query.GetAsString());
end;
success := http.HttpBd('PUT',url.GetAsString(),part.ControlInterface,'application/octet-stream',response.ControlInterface);
if ((success <> 1) or (response.StatusCode <> 200)) then
begin
Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(response.StatusCode));
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit;
end;
confirmed := response.GetHeaderField('x-amz-checksum-sha256');
stringCompare.SetString(confirmed);
stringMatch38 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch38 = 1)) then
begin
Memo1.Lines.Add('Missing required response header x-amz-checksum-sha256.');
Exit;
end;
stringCompare.SetString(confirmed);
stringMatch39 := stringCompare.ContentsEqual(partChecksum,1);
if (stringMatch39 <> 1) then
begin
Memo1.Lines.Add('Part checksum mismatch; preserve checkpoint.');
Exit;
end;
partEtag := response.GetHeaderField('ETag');
stringCompare.SetString(partEtag);
stringMatch40 := stringCompare.ContentsEqual('',1);
if ((response.LastMethodSuccess <> 1) or (stringMatch40 = 1)) then
begin
Memo1.Lines.Add('Missing required response header ETag.');
Exit;
end;
end
else
begin
Memo1.Lines.Add('Reusing verified remote part: ' + partNumberText.GetAsString());
end;
completion.I := partIndex;
completion.UpdateChildContent('Part[i]|PartNumber',partNumberText.GetAsString());
completion.UpdateChildContent('Part[i]|ETag',partEtag);
completion.UpdateChildContent('Part[i]|ChecksumSHA256',partChecksum);
partIndex := partIndex + 1;
end;
files.FileClose();
// Recheck the entire immutable source before committing its parts.
finalSourceHash := signer.HashFileENC(filePath);
stringCompare.SetString(finalSourceHash);
stringMatch41 := stringCompare.ContentsEqual(sourceHash,1);
if ((signer.LastMethodSuccess <> 1) or (stringMatch41 <> 1)) then
begin
Memo1.Lines.Add('Source changed; completion was not sent.');
Exit;
end;
compositeChecksum := digest.HashBdENC(concatenatedDigests.ControlInterface);
if (digest.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not compute composite checksum.');
Exit;
end;
number.SetString(compositeChecksum);
number.Append('-');
number.AppendInt(numParts);
compositeChecksum := number.GetAsString();
success := pending.UpdateString('uploadId',uploadId);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save uploadId.');
Exit;
end;
success := pending.UpdateString('sourceHash',sourceHash);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save sourceHash.');
Exit;
end;
success := pending.UpdateString('uploadToken',uploadToken);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save uploadToken.');
Exit;
end;
success := pending.UpdateString('checksum',compositeChecksum);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save checksum.');
Exit;
end;
success := pending.WriteFile(pendingPath);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save completion recovery record.');
Exit;
end;
requestBody := completion.GetXml();
query.Clear();
if (query.Length > 0) then
begin
query.Append('&');
end;
query.Append('uploadId=');
query.Append(http.UrlEncode(uploadId));
http.ClearHeaders();
success := now.SetFromCurrentSystemTime();
if (success <> 1) then
begin
Memo1.Lines.Add('Could not read system time.');
Exit;
end;
timestamp.SetString(now.GetAsTimestamp(0));
replaceCount := timestamp.Replace('-','');
replaceCount := timestamp.Replace(':','');
amzDate := timestamp.GetAsString();
dateStamp := timestamp.GetRange(0,8,0);
payloadHash := signer.HashStringENC(requestBody);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash payload.');
Exit;
end;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('host');
canonicalHeaders.Append('host:');
canonicalHeaders.Append(host.GetAsString());
canonicalHeaders.Append(#10);
http.SetRequestHeader('host',host.GetAsString());
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-checksum-type');
canonicalHeaders.Append('x-amz-checksum-type:');
canonicalHeaders.Append('COMPOSITE');
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-checksum-type','COMPOSITE');
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-content-sha256');
canonicalHeaders.Append('x-amz-content-sha256:');
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-content-sha256',payloadHash);
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-date');
canonicalHeaders.Append('x-amz-date:');
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-date',amzDate);
if (credentials.HasMember('session_token') = 1) then
begin
if (signedHeaders.Length > 0) then
begin
signedHeaders.Append(';');
end;
signedHeaders.Append('x-amz-security-token');
canonicalHeaders.Append('x-amz-security-token:');
canonicalHeaders.Append(credentials.StringOf('session_token'));
canonicalHeaders.Append(#10);
http.SetRequestHeader('x-amz-security-token',credentials.StringOf('session_token'));
end;
canonical.Clear();
canonical.Append('POST' + #10);
canonical.Append(uri.GetAsString());
canonical.Append(#10);
canonical.Append(query.GetAsString());
canonical.Append(#10);
canonical.Append(canonicalHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(signedHeaders.GetAsString());
canonical.Append(#10);
canonical.Append(payloadHash);
canonicalHash := signer.HashStringENC(canonical.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not hash canonical request.');
Exit;
end;
scope.Clear();
scope.Append(dateStamp);
scope.Append('/');
scope.Append(region);
scope.Append('/s3/aws4_request');
stringToSign.Clear();
stringToSign.Append('AWS4-HMAC-SHA256' + #10);
stringToSign.Append(amzDate);
stringToSign.Append(#10);
stringToSign.Append(scope.GetAsString());
stringToSign.Append(#10);
stringToSign.Append(canonicalHash);
signingKey.SetString('AWS4');
signingKey.Append(credentials.StringOf('secret_key'));
success := signer.SetMacKeyString(signingKey.GetAsString());
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(dateStamp);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC(region);
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('s3');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := signer.MacStringENC('aws4_request');
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := signer.SetMacKeyEncoded(derivedKey,'hex');
if (success <> 1) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
signature := signer.MacStringENC(stringToSign.GetAsString());
if (signer.LastMethodSuccess <> 1) then
begin
Memo1.Lines.Add('Could not sign request.');
Exit;
end;
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) then
begin
url.Append('?');
url.Append(query.GetAsString());
end;
success := http.HttpStr('POST',url.GetAsString(),requestBody,'utf-8','application/xml',response.ControlInterface);
if ((success <> 1) or (response.StatusCode <> 200)) then
begin
Memo1.Lines.Add('Request failed or returned unexpected HTTP status: ' + IntToStr(response.StatusCode));
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
Exit;
end;
success := xml.LoadXml(response.BodyStr);
if (success <> 1) then
begin
Memo1.Lines.Add('Invalid XML response.');
Exit;
end;
stringCompare.SetString(xml.Tag);
stringMatch42 := stringCompare.ContentsEqual('CompleteMultipartUploadResult',1);
if (stringMatch42 <> 1) then
begin
Memo1.Lines.Add('Unexpected XML result, possibly an embedded S3 error. Inspect privately.');
Exit;
end;
confirmed := xml.GetChildContent('ChecksumSHA256');
stringCompare.SetString(confirmed);
stringMatch43 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch43 = 1)) then
begin
Memo1.Lines.Add('Missing required ChecksumSHA256.');
Exit;
end;
stringCompare.SetString(confirmed);
stringMatch44 := stringCompare.ContentsEqual(compositeChecksum,1);
if (stringMatch44 <> 1) then
begin
Memo1.Lines.Add('Completion checksum differs; preserve checkpoint and inspect object.');
Exit;
end;
success := state.UpdateString('compositeChecksum',compositeChecksum);
if (success <> 1) then
begin
Memo1.Lines.Add('Could not save compositeChecksum.');
Exit;
end;
success := state.WriteFile('qa_output/s3-multipart/completed.json.tmp');
if (success <> 1) then
begin
Memo1.Lines.Add('Completion succeeded but receipt could not be saved; preserve the checkpoint.');
Exit;
end;
success := files.FileRename('qa_output/s3-multipart/completed.json.tmp',receiptPath);
if (success <> 1) then
begin
Memo1.Lines.Add('Completion receipt remains at its temporary path.');
Exit;
end;
Memo1.Lines.Add('Multipart upload completed and verified.');