S3 Http: Multipart Upload with Checksums and Checkpoint
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.
Starts, transfers and completes one upload. Saves state before parts and a pending completion record before completion. Run the resume companion after interruptions; do not rerun start against an existing cache. Metadata binds an uncertain completion to a random upload identity.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkCrypt2W.h>
#include <CkDateTimeW.h>
#include <CkXmlW.h>
#include <CkFileAccessW.h>
#include <CkHashtableW.h>
#include <CkDirTreeW.h>
#include <CkPrngW.h>
#include <CkBinDataW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load private credentials; never put access keys or session tokens in source.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/s3.json");
if (success != true) {
wprintf(L"Could not load private S3 credentials.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"access_key"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
CkHttpW http;
http.put_AwsAccessKey(credentials.stringOf(L"access_key"));
http.put_AwsSecretKey(credentials.stringOf(L"secret_key"));
if (credentials.HasMember(L"session_token") == true) {
stringCompare.SetString(credentials.stringOf(L"session_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
wprintf(L"session_token must be a nonempty string when supplied.\n");
return;
}
http.put_AwsSessionToken(credentials.stringOf(L"session_token"));
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
const wchar_t *region = L"us-west-2";
http.put_AwsRegion(region);
CkStringBuilderW endpoint;
endpoint.Append(L"s3.");
endpoint.Append(region);
endpoint.Append(L".amazonaws.com");
http.put_AwsEndpoint(endpoint.getAsString());
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
// A region redirect is not success. Correct the endpoint and signing region.
const wchar_t *bucketName = L"your-bucket-name";
const wchar_t *objectKey = L"examples/archive.bin";
CkHttpResponseW response;
CkCrypt2W signer;
signer.put_Charset(L"utf-8");
signer.put_HashAlgorithm(L"sha256");
signer.put_EncodingMode(L"hexlower");
signer.put_MacAlgorithm(L"hmac");
CkDateTimeW now;
CkStringBuilderW timestamp;
CkStringBuilderW canonical;
CkStringBuilderW canonicalHeaders;
CkStringBuilderW signedHeaders;
CkStringBuilderW scope;
CkStringBuilderW stringToSign;
CkStringBuilderW signingKey;
CkStringBuilderW authorization;
CkStringBuilderW url;
CkStringBuilderW query;
CkStringBuilderW number;
CkStringBuilderW host;
CkStringBuilderW uri;
CkXmlW xml;
const wchar_t *amzDate = 0;
const wchar_t *dateStamp = 0;
const wchar_t *payloadHash = 0;
const wchar_t *canonicalHash = 0;
const wchar_t *derivedKey = 0;
const wchar_t *signature = 0;
int replaceCount;
host.Append(bucketName);
host.Append(L".");
host.Append(endpoint.getAsString());
// Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.urlEncode(objectKey));
replaceCount = uri.ReplaceNoCase(L"%2f",L"/");
if ((uri.StartsWith(L"/",true) == true) || (uri.Contains(L"/../",true) == true) || (uri.Contains(L"/./",true) == true)) {
wprintf(L"Use a key without a leading slash or dot path segments for these examples.\n");
return;
}
uri.Prepend(L"/");
CkFileAccessW files;
const wchar_t *filePath = L"qa_data/bin/archive.bin";
const wchar_t *fileSize = files.fileSizeStr(filePath);
if (files.get_LastMethodSuccess() != true) {
wprintf(L"Could not read source file size.\n");
return;
}
CkCrypt2W digest;
digest.put_HashAlgorithm(L"sha256");
digest.put_EncodingMode(L"hexlower");
const wchar_t *sourceHash = digest.hashFileENC(filePath);
if (digest.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash source file.\n");
return;
}
digest.put_EncodingMode(L"base64");
const wchar_t *sourceChecksum = digest.hashFileENC(filePath);
if (digest.get_LastMethodSuccess() != true) {
wprintf(L"Could not compute checksum.\n");
return;
}
const wchar_t *cacheDir = L"qa_output/s3-multipart";
const wchar_t *statePath = L"qa_output/s3-multipart/state.json";
const wchar_t *pendingPath = L"qa_output/s3-multipart/completion.json";
const wchar_t *receiptPath = L"qa_output/s3-multipart/completed.json";
CkJsonObjectW state;
state.put_Strict(true);
CkJsonObjectW pending;
pending.put_Strict(true);
const wchar_t *uploadId = 0;
const wchar_t *uploadToken = 0;
const wchar_t *compositeChecksum = 0;
success = files.OpenForRead(filePath);
if (success != true) {
wprintf(L"Could not open immutable source file.\n");
return;
}
int partSize = 8388608;
int numParts = files.GetNumBlocks(partSize);
if ((numParts < 1) || (numParts > 10000)) {
wprintf(L"Use a nonempty source of at most 10,000 fixed 8 MiB parts.\n");
return;
}
CkHashtableW remoteEtags;
CkHashtableW remoteSizes;
CkHashtableW remoteChecksums;
CkHashtableW partNumbers;
CkStringBuilderW partNumberText;
success = files.DirEnsureExists(cacheDir);
if (success != true) {
wprintf(L"Could not create private checkpoint directory.\n");
return;
}
CkDirTreeW entries;
entries.put_BaseDir(cacheDir);
entries.put_Recurse(false);
success = entries.BeginIterate();
if ((success == true) || (entries.get_DoneIterating() != true)) {
wprintf(L"Start requires an empty checkpoint directory; use resume for an existing upload.\n");
return;
}
CkPrngW random;
uploadToken = random.genRandom(16,L"hex");
if (random.get_LastMethodSuccess() != true) {
wprintf(L"Could not create upload identity.\n");
return;
}
query.Clear();
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"uploads=");
query.Append(http.urlEncode(L""));
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(L"");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-algorithm");
canonicalHeaders.Append(L"x-amz-checksum-algorithm:");
canonicalHeaders.Append(L"SHA256");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-algorithm",L"SHA256");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-type");
canonicalHeaders.Append(L"x-amz-checksum-type:");
canonicalHeaders.Append(L"COMPOSITE");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-type",L"COMPOSITE");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-meta-source-sha256");
canonicalHeaders.Append(L"x-amz-meta-source-sha256:");
canonicalHeaders.Append(sourceHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-meta-source-sha256",sourceHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-meta-upload-token");
canonicalHeaders.Append(L"x-amz-meta-upload-token:");
canonicalHeaders.Append(uploadToken);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-meta-upload-token",uploadToken);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"POST\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.HttpNoBody(L"POST",url.getAsString(),response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",response.get_StatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
success = xml.LoadXml(response.bodyStr());
if (success != true) {
wprintf(L"Invalid XML response.\n");
return;
}
stringCompare.SetString(xml.tag());
bool stringMatch4 = stringCompare.ContentsEqual(L"InitiateMultipartUploadResult",true);
if (stringMatch4 != true) {
wprintf(L"Unexpected XML result, possibly an embedded S3 error. Inspect privately.\n");
return;
}
uploadId = xml.getChildContent(L"UploadId");
stringCompare.SetString(uploadId);
bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
wprintf(L"Missing required UploadId.\n");
return;
}
wprintf(L"Created upload ID: %s\n",uploadId);
// Save the upload ID before sending parts. If saving fails, retain the printed ID.
success = state.UpdateString(L"schema",L"1");
if (success != true) {
wprintf(L"Could not save schema.\n");
return;
}
success = state.UpdateString(L"bucket",bucketName);
if (success != true) {
wprintf(L"Could not save bucket.\n");
return;
}
success = state.UpdateString(L"key",objectKey);
if (success != true) {
wprintf(L"Could not save key.\n");
return;
}
success = state.UpdateString(L"region",region);
if (success != true) {
wprintf(L"Could not save region.\n");
return;
}
success = state.UpdateString(L"filePath",filePath);
if (success != true) {
wprintf(L"Could not save filePath.\n");
return;
}
success = state.UpdateString(L"fileSize",fileSize);
if (success != true) {
wprintf(L"Could not save fileSize.\n");
return;
}
success = state.UpdateString(L"sourceHash",sourceHash);
if (success != true) {
wprintf(L"Could not save sourceHash.\n");
return;
}
success = state.UpdateString(L"partSize",L"8388608");
if (success != true) {
wprintf(L"Could not save partSize.\n");
return;
}
success = state.UpdateString(L"uploadId",uploadId);
if (success != true) {
wprintf(L"Could not save uploadId.\n");
return;
}
success = state.UpdateString(L"uploadToken",uploadToken);
if (success != true) {
wprintf(L"Could not save uploadToken.\n");
return;
}
success = state.WriteFile(L"qa_output/s3-multipart/state.json.tmp");
if (success != true) {
wprintf(L"Upload was initiated but checkpoint could not be saved; retain its ID.\n");
return;
}
success = files.FileRename(L"qa_output/s3-multipart/state.json.tmp",statePath);
if (success != true) {
wprintf(L"Checkpoint rename failed; preserve the temporary checkpoint and upload ID.\n");
return;
}
CkBinDataW part;
CkBinDataW concatenatedDigests;
CkXmlW completion;
completion.put_Tag(L"CompleteMultipartUpload");
completion.AddAttribute(L"xmlns",L"http://s3.amazonaws.com/doc/2006-03-01/");
int partIndex = 0;
const wchar_t *partChecksum = 0;
const wchar_t *partEtag = 0;
const wchar_t *partHash = 0;
const wchar_t *confirmed = 0;
const wchar_t *sizeText = 0;
while ((partIndex < numParts)) {
part.Clear();
success = files.ReadBlockBd(partIndex,partSize,part);
if (success != true) {
wprintf(L"Could not read source part; preserve checkpoint.\n");
return;
}
if ((part.get_NumBytes() == 0) || ((partIndex < numParts - 1) && (part.get_NumBytes() != partSize))) {
wprintf(L"Source changed or part read was incomplete.\n");
return;
}
partChecksum = digest.hashBdENC(part);
if (digest.get_LastMethodSuccess() != true) {
wprintf(L"Could not checksum part.\n");
return;
}
partHash = signer.hashBdENC(part);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash part.\n");
return;
}
success = concatenatedDigests.AppendEncoded(partChecksum,L"base64");
if (success != true) {
wprintf(L"Could not accumulate part digests.\n");
return;
}
partNumberText.Clear();
partNumberText.AppendInt(partIndex + 1);
number.Clear();
number.AppendInt(part.get_NumBytes());
sizeText = number.getAsString();
const wchar_t *partNumberKey = partNumberText.getAsString();
bool reuse = false;
partEtag = L"";
if (remoteChecksums.Contains(partNumberKey) == true) {
stringCompare.SetString(remoteChecksums.lookupStr(partNumberKey));
bool stringMatch6 = stringCompare.ContentsEqual(partChecksum,true);
stringCompare.SetString(remoteSizes.lookupStr(partNumberKey));
bool stringMatch7 = stringCompare.ContentsEqual(sizeText,true);
if ((stringMatch6 == true) && (stringMatch7 == true)) {
partEtag = remoteEtags.lookupStr(partNumberKey);
stringCompare.SetString(partEtag);
bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
if ((remoteEtags.get_LastMethodSuccess() == true) && (stringMatch8 != true)) {
reuse = true;
}
}
}
if (reuse != true) {
query.Clear();
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"partNumber=");
query.Append(http.urlEncode(partNumberText.getAsString()));
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"uploadId=");
query.Append(http.urlEncode(uploadId));
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = partHash;
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-sha256");
canonicalHeaders.Append(L"x-amz-checksum-sha256:");
canonicalHeaders.Append(partChecksum);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-sha256",partChecksum);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"PUT\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.HttpBd(L"PUT",url.getAsString(),part,L"application/octet-stream",response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",response.get_StatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
confirmed = response.getHeaderField(L"x-amz-checksum-sha256");
stringCompare.SetString(confirmed);
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
wprintf(L"Missing required response header x-amz-checksum-sha256.\n");
return;
}
stringCompare.SetString(confirmed);
bool stringMatch10 = stringCompare.ContentsEqual(partChecksum,true);
if (stringMatch10 != true) {
wprintf(L"Part checksum mismatch; preserve checkpoint.\n");
return;
}
partEtag = response.getHeaderField(L"ETag");
stringCompare.SetString(partEtag);
bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
if ((response.get_LastMethodSuccess() != true) || (stringMatch11 == true)) {
wprintf(L"Missing required response header ETag.\n");
return;
}
}
else {
wprintf(L"Reusing verified remote part: %s\n",partNumberText.getAsString());
}
completion.put_I(partIndex);
completion.UpdateChildContent(L"Part[i]|PartNumber",partNumberText.getAsString());
completion.UpdateChildContent(L"Part[i]|ETag",partEtag);
completion.UpdateChildContent(L"Part[i]|ChecksumSHA256",partChecksum);
partIndex = partIndex + 1;
}
files.FileClose();
// Recheck the entire immutable source before committing its parts.
const wchar_t *finalSourceHash = signer.hashFileENC(filePath);
stringCompare.SetString(finalSourceHash);
bool stringMatch12 = stringCompare.ContentsEqual(sourceHash,true);
if ((signer.get_LastMethodSuccess() != true) || (stringMatch12 != true)) {
wprintf(L"Source changed; completion was not sent.\n");
return;
}
compositeChecksum = digest.hashBdENC(concatenatedDigests);
if (digest.get_LastMethodSuccess() != true) {
wprintf(L"Could not compute composite checksum.\n");
return;
}
number.SetString(compositeChecksum);
number.Append(L"-");
number.AppendInt(numParts);
compositeChecksum = number.getAsString();
success = pending.UpdateString(L"uploadId",uploadId);
if (success != true) {
wprintf(L"Could not save uploadId.\n");
return;
}
success = pending.UpdateString(L"sourceHash",sourceHash);
if (success != true) {
wprintf(L"Could not save sourceHash.\n");
return;
}
success = pending.UpdateString(L"uploadToken",uploadToken);
if (success != true) {
wprintf(L"Could not save uploadToken.\n");
return;
}
success = pending.UpdateString(L"checksum",compositeChecksum);
if (success != true) {
wprintf(L"Could not save checksum.\n");
return;
}
success = pending.WriteFile(pendingPath);
if (success != true) {
wprintf(L"Could not save completion recovery record.\n");
return;
}
const wchar_t *requestBody = completion.getXml();
query.Clear();
if (query.get_Length() > 0) {
query.Append(L"&");
}
query.Append(L"uploadId=");
query.Append(http.urlEncode(uploadId));
http.ClearHeaders();
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read system time.\n");
return;
}
timestamp.SetString(now.getAsTimestamp(false));
replaceCount = timestamp.Replace(L"-",L"");
replaceCount = timestamp.Replace(L":",L"");
amzDate = timestamp.getAsString();
dateStamp = timestamp.getRange(0,8,false);
payloadHash = signer.hashStringENC(requestBody);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash payload.\n");
return;
}
canonicalHeaders.Clear();
signedHeaders.Clear();
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"host");
canonicalHeaders.Append(L"host:");
canonicalHeaders.Append(host.getAsString());
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"host",host.getAsString());
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-checksum-type");
canonicalHeaders.Append(L"x-amz-checksum-type:");
canonicalHeaders.Append(L"COMPOSITE");
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-checksum-type",L"COMPOSITE");
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-content-sha256");
canonicalHeaders.Append(L"x-amz-content-sha256:");
canonicalHeaders.Append(payloadHash);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-date");
canonicalHeaders.Append(L"x-amz-date:");
canonicalHeaders.Append(amzDate);
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-date",amzDate);
if (credentials.HasMember(L"session_token") == true) {
if (signedHeaders.get_Length() > 0) {
signedHeaders.Append(L";");
}
signedHeaders.Append(L"x-amz-security-token");
canonicalHeaders.Append(L"x-amz-security-token:");
canonicalHeaders.Append(credentials.stringOf(L"session_token"));
canonicalHeaders.Append(L"\n");
http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
}
canonical.Clear();
canonical.Append(L"POST\n");
canonical.Append(uri.getAsString());
canonical.Append(L"\n");
canonical.Append(query.getAsString());
canonical.Append(L"\n");
canonical.Append(canonicalHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(signedHeaders.getAsString());
canonical.Append(L"\n");
canonical.Append(payloadHash);
canonicalHash = signer.hashStringENC(canonical.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not hash canonical request.\n");
return;
}
scope.Clear();
scope.Append(dateStamp);
scope.Append(L"/");
scope.Append(region);
scope.Append(L"/s3/aws4_request");
stringToSign.Clear();
stringToSign.Append(L"AWS4-HMAC-SHA256\n");
stringToSign.Append(amzDate);
stringToSign.Append(L"\n");
stringToSign.Append(scope.getAsString());
stringToSign.Append(L"\n");
stringToSign.Append(canonicalHash);
signingKey.SetString(L"AWS4");
signingKey.Append(credentials.stringOf(L"secret_key"));
success = signer.SetMacKeyString(signingKey.getAsString());
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(dateStamp);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(region);
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"s3");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
derivedKey = signer.macStringENC(L"aws4_request");
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not derive signing key.\n");
return;
}
success = signer.SetMacKeyEncoded(derivedKey,L"hex");
if (success != true) {
wprintf(L"Could not set signing key.\n");
return;
}
signature = signer.macStringENC(stringToSign.getAsString());
if (signer.get_LastMethodSuccess() != true) {
wprintf(L"Could not sign request.\n");
return;
}
authorization.Clear();
authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
authorization.Append(credentials.stringOf(L"access_key"));
authorization.Append(L"/");
authorization.Append(scope.getAsString());
authorization.Append(L", SignedHeaders=");
authorization.Append(signedHeaders.getAsString());
authorization.Append(L", Signature=");
authorization.Append(signature);
http.SetRequestHeader(L"Authorization",authorization.getAsString());
url.SetString(L"https://");
url.Append(host.getAsString());
url.Append(uri.getAsString());
if (query.get_Length() > 0) {
url.Append(L"?");
url.Append(query.getAsString());
}
success = http.HttpStr(L"POST",url.getAsString(),requestBody,L"utf-8",L"application/xml",response);
if ((success != true) || (response.get_StatusCode() != 200)) {
wprintf(L"Request failed or returned unexpected HTTP status: %d\n",response.get_StatusCode());
// Preserve progress. Inspect full diagnostics privately; do not log secrets.
return;
}
success = xml.LoadXml(response.bodyStr());
if (success != true) {
wprintf(L"Invalid XML response.\n");
return;
}
stringCompare.SetString(xml.tag());
bool stringMatch13 = stringCompare.ContentsEqual(L"CompleteMultipartUploadResult",true);
if (stringMatch13 != true) {
wprintf(L"Unexpected XML result, possibly an embedded S3 error. Inspect privately.\n");
return;
}
confirmed = xml.getChildContent(L"ChecksumSHA256");
stringCompare.SetString(confirmed);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch14 == true)) {
wprintf(L"Missing required ChecksumSHA256.\n");
return;
}
stringCompare.SetString(confirmed);
bool stringMatch15 = stringCompare.ContentsEqual(compositeChecksum,true);
if (stringMatch15 != true) {
wprintf(L"Completion checksum differs; preserve checkpoint and inspect object.\n");
return;
}
success = state.UpdateString(L"compositeChecksum",compositeChecksum);
if (success != true) {
wprintf(L"Could not save compositeChecksum.\n");
return;
}
success = state.WriteFile(L"qa_output/s3-multipart/completed.json.tmp");
if (success != true) {
wprintf(L"Completion succeeded but receipt could not be saved; preserve the checkpoint.\n");
return;
}
success = files.FileRename(L"qa_output/s3-multipart/completed.json.tmp",receiptPath);
if (success != true) {
wprintf(L"Completion receipt remains at its temporary path.\n");
return;
}
wprintf(L"Multipart upload completed and verified.\n");
}