-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathrequest.c
1792 lines (1506 loc) · 61.1 KB
/
request.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** **************************************************************************
* request.c
*
* Copyright 2008 Bryan Ischo <bryan@ischo.com>
*
* This file is part of libs3.
*
* libs3 is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, version 3 or above of the License. You can also
* redistribute and/or modify it under the terms of the GNU General Public
* License, version 2 or above of the License.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this library and its programs with the
* OpenSSL library, and distribute linked combinations including the two.
*
* libs3 is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with libs3, in a file named COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* You should also have received a copy of the GNU General Public License
* version 2 along with libs3, in a file named COPYING-GPLv2. If not, see
* <http://www.gnu.org/licenses/>.
*
************************************************************************** **/
#include <ctype.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/utsname.h>
#include <libxml/parser.h>
#include "request.h"
#include "request_context.h"
#include "response_headers_handler.h"
#ifdef __APPLE__
#include <CommonCrypto/CommonHMAC.h>
#define S3_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
#else
#include <openssl/hmac.h>
#include <openssl/sha.h>
#define S3_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
#endif
#define USER_AGENT_SIZE 256
#define REQUEST_STACK_SIZE 32
#define SIGNATURE_SCOPE_SIZE 64
//#define SIGNATURE_DEBUG
static int verifyPeer;
static char userAgentG[USER_AGENT_SIZE];
static pthread_mutex_t requestStackMutexG;
static Request *requestStackG[REQUEST_STACK_SIZE];
static int requestStackCountG;
char defaultHostNameG[S3_MAX_HOSTNAME_SIZE];
typedef struct RequestComputedValues
{
// All x-amz- headers, in normalized form (i.e. NAME: VALUE, no other ws)
char *amzHeaders[S3_MAX_METADATA_COUNT + 2]; // + 2 for acl and date
// The number of x-amz- headers
int amzHeadersCount;
// Storage for amzHeaders (the +256 is for x-amz-acl and x-amz-date)
char amzHeadersRaw[COMPACTED_METADATA_BUFFER_SIZE + 256 + 1];
// Length of populated data in raw buffer
int amzHeadersRawLength;
// Canonicalized headers for signature
string_multibuffer(canonicalizedSignatureHeaders,
COMPACTED_METADATA_BUFFER_SIZE + 256 + 1);
// Delimited list of header names used for signature
char signedHeaders[COMPACTED_METADATA_BUFFER_SIZE];
// URL-Encoded key
char urlEncodedKey[MAX_URLENCODED_KEY_SIZE + 1];
// Canonicalized resource
char canonicalURI[MAX_CANONICALIZED_RESOURCE_SIZE + 1];
// Canonical sub-resource & query string
char canonicalQueryString[MAX_CANONICALIZED_RESOURCE_SIZE + 1];
// Cache-Control header (or empty)
char cacheControlHeader[128];
// Content-Type header (or empty)
char contentTypeHeader[128];
// Content-MD5 header (or empty)
char md5Header[128];
// Content-Disposition header (or empty)
char contentDispositionHeader[128];
// Content-Encoding header (or empty)
char contentEncodingHeader[128];
// Expires header (or empty)
char expiresHeader[128];
// If-Modified-Since header
char ifModifiedSinceHeader[128];
// If-Unmodified-Since header
char ifUnmodifiedSinceHeader[128];
// If-Match header
char ifMatchHeader[128];
// If-None-Match header
char ifNoneMatchHeader[128];
// Range header
char rangeHeader[128];
// Authorization header
char authorizationHeader[4096];
// Request date stamp
char requestDateISO8601[64];
// Credential used for authorization signature
char authCredential[MAX_CREDENTIAL_SIZE + 1];
// Computed request signature (hex string)
char requestSignatureHex[S3_SHA256_DIGEST_LENGTH * 2 + 1];
// Host header
char hostHeader[128];
// Hex string of hash of request payload
char payloadHash[S3_SHA256_DIGEST_LENGTH * 2 + 1];
} RequestComputedValues;
// Called whenever we detect that the request headers have been completely
// processed; which happens either when we get our first read/write callback,
// or the request is finished being processed. Returns nonzero on success,
// zero on failure.
static void request_headers_done(Request *request)
{
if (request->propertiesCallbackMade) {
return;
}
request->propertiesCallbackMade = 1;
// Get the http response code
long httpResponseCode;
request->httpResponseCode = 0;
if (curl_easy_getinfo(request->curl, CURLINFO_RESPONSE_CODE,
&httpResponseCode) != CURLE_OK) {
// Not able to get the HTTP response code - error
request->status = S3StatusInternalError;
return;
}
else {
request->httpResponseCode = httpResponseCode;
}
response_headers_handler_done(&(request->responseHeadersHandler),
request->curl);
// Only make the callback if it was a successful request; otherwise we're
// returning information about the error response itself
if (request->propertiesCallback &&
(request->httpResponseCode >= 200) &&
(request->httpResponseCode <= 299)) {
request->status = (*(request->propertiesCallback))
(&(request->responseHeadersHandler.responseProperties),
request->callbackData);
}
}
static size_t curl_header_func(void *ptr, size_t size, size_t nmemb,
void *data)
{
Request *request = (Request *) data;
int len = size * nmemb;
response_headers_handler_add
(&(request->responseHeadersHandler), (char *) ptr, len);
return len;
}
static size_t curl_read_func(void *ptr, size_t size, size_t nmemb, void *data)
{
Request *request = (Request *) data;
int len = size * nmemb;
// CURL may call this function before response headers are available,
// so don't assume response headers are available and attempt to parse
// them. Leave that to curl_write_func, which is guaranteed to be called
// only after headers are available.
if (request->status != S3StatusOK) {
return CURL_READFUNC_ABORT;
}
// If there is no data callback, or the data callback has already returned
// contentLength bytes, return 0;
if (!request->toS3Callback || !request->toS3CallbackBytesRemaining) {
return 0;
}
// Don't tell the callback that we are willing to accept more data than we
// really are
if (len > request->toS3CallbackBytesRemaining) {
len = request->toS3CallbackBytesRemaining;
}
// Otherwise, make the data callback
int ret = (*(request->toS3Callback))
(len, (char *) ptr, request->callbackData);
if (ret < 0) {
request->status = S3StatusAbortedByCallback;
return CURL_READFUNC_ABORT;
}
else {
if (ret > request->toS3CallbackBytesRemaining) {
ret = request->toS3CallbackBytesRemaining;
}
request->toS3CallbackBytesRemaining -= ret;
return ret;
}
}
static size_t curl_write_func(void *ptr, size_t size, size_t nmemb,
void *data)
{
Request *request = (Request *) data;
int len = size * nmemb;
request_headers_done(request);
if (request->status != S3StatusOK) {
return 0;
}
// On HTTP error, we expect to parse an HTTP error response
if ((request->httpResponseCode < 200) ||
(request->httpResponseCode > 299)) {
request->status = error_parser_add
(&(request->errorParser), (char *) ptr, len);
}
// If there was a callback registered, make it
else if (request->fromS3Callback) {
request->status = (*(request->fromS3Callback))
(len, (char *) ptr, request->callbackData);
}
// Else, consider this an error - S3 has sent back data when it was not
// expected
else {
request->status = S3StatusInternalError;
}
return ((request->status == S3StatusOK) ? len : 0);
}
static S3Status append_amz_header(RequestComputedValues *values,
int addPrefix,
const char *headerName,
const char *headerValue)
{
int rawPos = values->amzHeadersRawLength + 1;
values->amzHeaders[values->amzHeadersCount++] = &(values->amzHeadersRaw[rawPos]);
const char *headerStr = headerName;
char headerNameWithPrefix[S3_MAX_METADATA_SIZE - sizeof(": v")];
if (addPrefix) {
snprintf(headerNameWithPrefix, sizeof(headerNameWithPrefix),
S3_METADATA_HEADER_NAME_PREFIX "%s", headerName);
headerStr = headerNameWithPrefix;
}
// Make sure the new header (plus ": " plus string terminator) will fit
// in the buffer.
if ((values->amzHeadersRawLength + strlen(headerStr) + strlen(headerValue)
+ 3) >= sizeof(values->amzHeadersRaw)) {
return S3StatusMetaDataHeadersTooLong;
}
unsigned long i = 0;
for (; i < strlen(headerStr); i++) {
values->amzHeadersRaw[rawPos++] = tolower(headerStr[i]);
}
snprintf(&(values->amzHeadersRaw[rawPos]), 3, ": ");
rawPos += 2;
for (i = 0; i < strlen(headerValue); i++) {
values->amzHeadersRaw[rawPos++] = headerValue[i];
}
rawPos--;
while (isblank(values->amzHeadersRaw[rawPos])) {
rawPos--;
}
values->amzHeadersRaw[++rawPos] = '\0';
values->amzHeadersRawLength = rawPos;
return S3StatusOK;
}
// This function 'normalizes' all x-amz-meta headers provided in
// params->requestHeaders, which means it removes all whitespace from
// them such that they all look exactly like this:
// x-amz-meta-${NAME}: ${VALUE}
// It also adds the x-amz-acl, x-amz-copy-source, x-amz-metadata-directive,
// and x-amz-server-side-encryption headers if necessary, and always adds the
// x-amz-date header. It copies the raw string values into
// params->amzHeadersRaw, and creates an array of string pointers representing
// these headers in params->amzHeaders (and also sets params->amzHeadersCount
// to be the count of the total number of x-amz- headers thus created).
static S3Status compose_amz_headers(const RequestParams *params,
int forceUnsignedPayload,
RequestComputedValues *values)
{
const S3PutProperties *properties = params->putProperties;
values->amzHeadersCount = 0;
values->amzHeadersRaw[0] = '\0';
values->amzHeadersRawLength = 0;
// Check and copy in the x-amz-meta headers
if (properties) {
int i;
for (i = 0; i < properties->metaDataCount; i++) {
const S3NameValue *property = &(properties->metaData[i]);
append_amz_header(values, 1, property->name, property->value);
}
// Add the x-amz-acl header, if necessary
const char *cannedAclString;
switch (properties->cannedAcl) {
case S3CannedAclPrivate:
cannedAclString = NULL;
break;
case S3CannedAclPublicRead:
cannedAclString = "public-read";
break;
case S3CannedAclPublicReadWrite:
cannedAclString = "public-read-write";
break;
case S3CannedAclBucketOwnerFullControl:
cannedAclString = "bucket-owner-full-control";
break;
default: // S3CannedAclAuthenticatedRead
cannedAclString = "authenticated-read";
break;
}
if (cannedAclString) {
append_amz_header(values, 0, "x-amz-acl", cannedAclString);
}
// Add the x-amz-server-side-encryption header, if necessary
if (properties->useServerSideEncryption) {
append_amz_header(values, 0, "x-amz-server-side-encryption",
"AES256");
}
}
// Add the x-amz-date header
append_amz_header(values, 0, "x-amz-date", values->requestDateISO8601);
if (params->httpRequestType == HttpRequestTypeCOPY) {
// Add the x-amz-copy-source header
if (params->copySourceBucketName && params->copySourceBucketName[0]
&& params->copySourceKey && params->copySourceKey[0]) {
char bucketKey[S3_MAX_METADATA_SIZE];
snprintf(bucketKey, sizeof(bucketKey), "/%s/%s",
params->copySourceBucketName, params->copySourceKey);
append_amz_header(values, 0, "x-amz-copy-source", bucketKey);
}
// If byteCount != 0 then we're just copying a range, add header
if (params->byteCount > 0) {
char byteRange[S3_MAX_METADATA_SIZE];
snprintf(byteRange, sizeof(byteRange), "bytes=%zd-%zd",
params->startByte, params->startByte + params->byteCount);
append_amz_header(values, 0, "x-amz-copy-source-range", byteRange);
}
// And the x-amz-metadata-directive header
if (properties) {
append_amz_header(values, 0, "x-amz-metadata-directive", "REPLACE");
}
}
// Add the x-amz-security-token header if necessary
if (params->bucketContext.securityToken) {
append_amz_header(values, 0, "x-amz-security-token",
params->bucketContext.securityToken);
}
if (!forceUnsignedPayload
&& (params->httpRequestType == HttpRequestTypeGET
|| params->httpRequestType == HttpRequestTypeCOPY
|| params->httpRequestType == HttpRequestTypeDELETE
|| params->httpRequestType == HttpRequestTypeHEAD)) {
// empty payload
unsigned char md[S3_SHA256_DIGEST_LENGTH];
#ifdef __APPLE__
CC_SHA256("", 0, md);
#else
SHA256((const unsigned char*) "", 0, md);
#endif
values->payloadHash[0] = '\0';
int i = 0;
for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
snprintf(&(values->payloadHash[i * 2]), 3, "%02x", md[i]);
}
}
else {
// TODO: figure out how to manage signed payloads
strcpy(values->payloadHash, "UNSIGNED-PAYLOAD");
}
append_amz_header(values, 0, "x-amz-content-sha256",
values->payloadHash);
return S3StatusOK;
}
// Composes the other headers
static S3Status compose_standard_headers(const RequestParams *params,
RequestComputedValues *values)
{
#define do_put_header(fmt, sourceField, destField, badError, tooLongError) \
do { \
if (params->putProperties && \
params->putProperties-> sourceField && \
params->putProperties-> sourceField[0]) { \
/* Skip whitespace at beginning of val */ \
const char *val = params->putProperties-> sourceField; \
while (*val && is_blank(*val)) { \
val++; \
} \
if (!*val) { \
return badError; \
} \
/* Compose header, make sure it all fit */ \
int len = snprintf(values-> destField, \
sizeof(values-> destField), fmt, val); \
if (len >= (int) sizeof(values-> destField)) { \
return tooLongError; \
} \
/* Now remove the whitespace at the end */ \
while (is_blank(values-> destField[len])) { \
len--; \
} \
values-> destField[len] = 0; \
} \
else { \
values-> destField[0] = 0; \
} \
} while (0)
#define do_get_header(fmt, sourceField, destField, badError, tooLongError) \
do { \
if (params->getConditions && \
params->getConditions-> sourceField && \
params->getConditions-> sourceField[0]) { \
/* Skip whitespace at beginning of val */ \
const char *val = params->getConditions-> sourceField; \
while (*val && is_blank(*val)) { \
val++; \
} \
if (!*val) { \
return badError; \
} \
/* Compose header, make sure it all fit */ \
int len = snprintf(values-> destField, \
sizeof(values-> destField), fmt, val); \
if (len >= (int) sizeof(values-> destField)) { \
return tooLongError; \
} \
/* Now remove the whitespace at the end */ \
while (is_blank(values-> destField[len])) { \
len--; \
} \
values-> destField[len] = 0; \
} \
else { \
values-> destField[0] = 0; \
} \
} while (0)
// Host
if (params->bucketContext.uriStyle == S3UriStyleVirtualHost) {
const char *requestHostName = params->bucketContext.hostName
? params->bucketContext.hostName : defaultHostNameG;
size_t len = snprintf(values->hostHeader, sizeof(values->hostHeader),
"Host: %s.%s", params->bucketContext.bucketName,
requestHostName);
if (len >= sizeof(values->hostHeader)) {
return S3StatusUriTooLong;
}
while (is_blank(values->hostHeader[len])) {
len--;
}
values->hostHeader[len] = 0;
}
else {
size_t len = snprintf(
values->hostHeader,
sizeof(values->hostHeader),
"Host: %s",
params->bucketContext.hostName ?
params->bucketContext.hostName : defaultHostNameG);
if (len >= sizeof(values->hostHeader)) {
return S3StatusUriTooLong;
}
while (is_blank(values->hostHeader[len])) {
len--;
}
values->hostHeader[len] = 0;
}
// Cache-Control
do_put_header("Cache-Control: %s", cacheControl, cacheControlHeader,
S3StatusBadCacheControl, S3StatusCacheControlTooLong);
// ContentType
do_put_header("Content-Type: %s", contentType, contentTypeHeader,
S3StatusBadContentType, S3StatusContentTypeTooLong);
// MD5
do_put_header("Content-MD5: %s", md5, md5Header, S3StatusBadMD5,
S3StatusMD5TooLong);
// Content-Disposition
do_put_header("Content-Disposition: attachment; filename=\"%s\"",
contentDispositionFilename, contentDispositionHeader,
S3StatusBadContentDispositionFilename,
S3StatusContentDispositionFilenameTooLong);
// ContentEncoding
do_put_header("Content-Encoding: %s", contentEncoding,
contentEncodingHeader, S3StatusBadContentEncoding,
S3StatusContentEncodingTooLong);
// Expires
if (params->putProperties && (params->putProperties->expires >= 0)) {
time_t t = (time_t) params->putProperties->expires;
struct tm gmt;
strftime(values->expiresHeader, sizeof(values->expiresHeader),
"Expires: %a, %d %b %Y %H:%M:%S UTC", gmtime_r(&t, &gmt));
}
else {
values->expiresHeader[0] = 0;
}
// If-Modified-Since
if (params->getConditions &&
(params->getConditions->ifModifiedSince >= 0)) {
time_t t = (time_t) params->getConditions->ifModifiedSince;
struct tm gmt;
strftime(values->ifModifiedSinceHeader,
sizeof(values->ifModifiedSinceHeader),
"If-Modified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime_r(&t, &gmt));
}
else {
values->ifModifiedSinceHeader[0] = 0;
}
// If-Unmodified-Since header
if (params->getConditions &&
(params->getConditions->ifNotModifiedSince >= 0)) {
time_t t = (time_t) params->getConditions->ifNotModifiedSince;
struct tm gmt;
strftime(values->ifUnmodifiedSinceHeader,
sizeof(values->ifUnmodifiedSinceHeader),
"If-Unmodified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime_r(&t, &gmt));
}
else {
values->ifUnmodifiedSinceHeader[0] = 0;
}
// If-Match header
do_get_header("If-Match: %s", ifMatchETag, ifMatchHeader,
S3StatusBadIfMatchETag, S3StatusIfMatchETagTooLong);
// If-None-Match header
do_get_header("If-None-Match: %s", ifNotMatchETag, ifNoneMatchHeader,
S3StatusBadIfNotMatchETag,
S3StatusIfNotMatchETagTooLong);
// Range header
if (params->startByte || params->byteCount) {
if (params->byteCount) {
snprintf(values->rangeHeader, sizeof(values->rangeHeader),
"Range: bytes=%llu-%llu",
(unsigned long long) params->startByte,
(unsigned long long) (params->startByte +
params->byteCount - 1));
}
else {
snprintf(values->rangeHeader, sizeof(values->rangeHeader),
"Range: bytes=%llu-",
(unsigned long long) params->startByte);
}
}
else {
values->rangeHeader[0] = 0;
}
return S3StatusOK;
}
// URL encodes the params->key value into params->urlEncodedKey
static S3Status encode_key(const RequestParams *params,
RequestComputedValues *values)
{
return (urlEncode(values->urlEncodedKey, params->key, S3_MAX_KEY_SIZE, 0) ?
S3StatusOK : S3StatusUriTooLong);
}
// Simple comparison function for comparing two "<key><delim><value>"
// delimited strings, returning true if the key of s1 comes
// before the key of s2 alphabetically, false if not
static int headerle(const char *s1, const char *s2, char delim)
{
while (1) {
if (*s1 == delim) {
return (*s2 != delim);
}
else if (*s2 == delim) {
return 0;
}
else if (*s2 < *s1) {
return 0;
}
else if (*s2 > *s1) {
return 1;
}
s1++, s2++;
}
return 0;
}
// Replace this with merge sort eventually, it's the best stable sort. But
// since typically the number of elements being sorted is small, it doesn't
// matter that much which sort is used, and gnome sort is the world's simplest
// stable sort. Added a slight twist to the standard gnome_sort - don't go
// forward +1, go forward to the last highest index considered. This saves
// all the string comparisons that would be done "going forward", and thus
// only does the necessary string comparisons to move values back into their
// sorted position.
static void kv_gnome_sort(const char **values, int size, char delim)
{
int i = 0, last_highest = 0;
while (i < size) {
if ((i == 0) || headerle(values[i - 1], values[i], delim)) {
i = ++last_highest;
}
else {
const char *tmp = values[i];
values[i] = values[i - 1];
values[--i] = tmp;
}
}
}
// Canonicalizes the signature headers into the canonicalizedSignatureHeaders buffer
static void canonicalize_signature_headers(RequestComputedValues *values)
{
// Make a copy of the headers that will be sorted
const char *sortedHeaders[S3_MAX_METADATA_COUNT + 3];
memcpy(sortedHeaders, values->amzHeaders,
(values->amzHeadersCount * sizeof(sortedHeaders[0])));
// add the content-type header and host header
int headerCount = values->amzHeadersCount;
if (values->contentTypeHeader[0]) {
sortedHeaders[headerCount++] = values->contentTypeHeader;
}
if (values->hostHeader[0]) {
sortedHeaders[headerCount++] = values->hostHeader;
}
if (values->rangeHeader[0]) {
sortedHeaders[headerCount++] = values->rangeHeader;
}
if (values->md5Header[0]) {
sortedHeaders[headerCount++] = values->md5Header;
}
// Now sort these
kv_gnome_sort(sortedHeaders, headerCount, ':');
// Now copy this sorted list into the buffer, all the while:
// - folding repeated headers into single lines, and
// - folding multiple lines
// - removing the space after the colon
int lastHeaderLen = 0;
char *buffer = values->canonicalizedSignatureHeaders;
char *hbuf = values->signedHeaders;
int i = 0;
for (; i < headerCount; i++) {
const char *header = sortedHeaders[i];
const char *c = header;
char v;
// If the header names are the same, append the next value
if ((i > 0) &&
!strncmp(header, sortedHeaders[i - 1], lastHeaderLen)) {
// Replacing the previous newline with a comma
*(buffer - 1) = ',';
// Skip the header name and space
c += (lastHeaderLen + 1);
}
// Else this is a new header
else {
// Copy in everything up to the space in the ": "
while (*c != ' ') {
v = tolower(*c++);
*buffer++ = v;
*hbuf++ = v;
}
// replace the ":" with a ";"
*(hbuf - 1) = ';';
// Save the header len since it's a new header
lastHeaderLen = c - header;
// Skip the space
c++;
}
// Now copy in the value, folding the lines
while (*c) {
// If c points to a \r\n[whitespace] sequence, then fold
// this newline out
if ((*c == '\r') && (*(c + 1) == '\n') && is_blank(*(c + 2))) {
c += 3;
while (is_blank(*c)) {
c++;
}
// Also, what has most recently been copied into buffer may
// have been whitespace, and since we're folding whitespace
// out around this newline sequence, back buffer up over
// any whitespace it contains
while (is_blank(*(buffer - 1))) {
buffer--;
}
continue;
}
*buffer++ = *c++;
}
// Finally, add the newline
*buffer++ = '\n';
}
// Remove the extra trailing semicolon from the header name list
// and terminate the string.
*(hbuf - 1) = '\0';
// Terminate the buffer
*buffer = 0;
}
// Canonicalizes the resource into params->canonicalizedResource
static void canonicalize_resource(const S3BucketContext *context,
const char *urlEncodedKey,
char *buffer, unsigned int buffer_max)
{
int len = 0;
*buffer = 0;
#define append(str) len += snprintf(&(buffer[len]), buffer_max - len, "%s", str)
if (context->uriStyle == S3UriStylePath) {
if (context->bucketName && context->bucketName[0]) {
buffer[len++] = '/';
append(context->bucketName);
}
}
append("/");
if (urlEncodedKey && urlEncodedKey[0]) {
append(urlEncodedKey);
}
#undef append
}
static void sort_query_string(const char *queryString, char *result,
unsigned int result_size)
{
#ifdef SIGNATURE_DEBUG
printf("\n--\nsort_and_urlencode\nqueryString: %s\n", queryString);
#endif
unsigned int numParams = 1;
const char *tmp = queryString;
while ((tmp = strchr(tmp, '&')) != NULL) {
numParams++;
tmp++;
}
const char* params[numParams];
// Where did strdup go?!??
int queryStringLen = strlen(queryString);
char *buf = (char *) malloc(queryStringLen + 1);
char *tok = buf;
strcpy(tok, queryString);
const char *token = NULL;
char *save = NULL;
unsigned int i = 0;
while ((token = strtok_r(tok, "&", &save)) != NULL) {
tok = NULL;
params[i++] = token;
}
kv_gnome_sort(params, numParams, '=');
#ifdef SIGNATURE_DEBUG
for (i = 0; i < numParams; i++) {
printf("%d: %s\n", i, params[i]);
}
#endif
// All params are urlEncoded
#define append(str) len += snprintf(&(result[len]), result_size - len, "%s", str)
unsigned int pi = 0;
unsigned int len = 0;
for (; pi < numParams; pi++) {
append(params[pi]);
append("&");
}
// Take off the extra '&'
if (len > 0) {
result[len - 1] = 0;
}
#undef append
free(buf);
}
// Canonicalize the query string part of the request into a buffer
static void canonicalize_query_string(const char *queryParams,
const char *subResource,
char *buffer, unsigned int buffer_size)
{
int len = 0;
*buffer = 0;
#define append(str) len += snprintf(&(buffer[len]), buffer_size - len, "%s", str)
if (queryParams && queryParams[0]) {
char sorted[strlen(queryParams) * 2];
sorted[0] = '\0';
sort_query_string(queryParams, sorted, sizeof(sorted));
append(sorted);
}
if (subResource && subResource[0]) {
if (queryParams && queryParams[0]) {
append("&");
}
append(subResource);
if (!strchr(subResource, '=')) {
append("=");
}
}
#undef append
}
static HttpRequestType http_request_method_to_type(const char *method)
{
if (!method) {
return HttpRequestTypeInvalid;
}
if (strcmp(method, "POST") == 0) {
return HttpRequestTypePOST;
}
else if (strcmp(method, "GET") == 0) {
return HttpRequestTypeGET;
}
else if (strcmp(method, "HEAD") == 0) {
return HttpRequestTypeHEAD;
}
else if (strcmp(method, "PUT") == 0) {
return HttpRequestTypePUT;
}
else if (strcmp(method, "COPY") == 0) {
return HttpRequestTypeCOPY;
}
else if (strcmp(method, "DELETE") == 0) {
return HttpRequestTypeDELETE;
}
return HttpRequestTypeInvalid;
}
// Convert an HttpRequestType to an HTTP Verb string
static const char *http_request_type_to_verb(HttpRequestType requestType)
{
switch (requestType) {
case HttpRequestTypePOST:
return "POST";
case HttpRequestTypeGET:
return "GET";
case HttpRequestTypeHEAD:
return "HEAD";
case HttpRequestTypePUT:
case HttpRequestTypeCOPY:
return "PUT";
default: // HttpRequestTypeDELETE
return "DELETE";
}
}
// Composes the Authorization header for the request
static S3Status compose_auth_header(const RequestParams *params,
RequestComputedValues *values)
{
const char *httpMethod = http_request_type_to_verb(params->httpRequestType);
int canonicalRequestLen = strlen(httpMethod) + 1 +
strlen(values->canonicalURI) + 1 +
strlen(values->canonicalQueryString) + 1 +
strlen(values->canonicalizedSignatureHeaders) + 1 +
strlen(values->signedHeaders) + 1 +
2 * S3_SHA256_DIGEST_LENGTH + 1; // 2 hex digits for each byte
int len = 0;
char canonicalRequest[canonicalRequestLen];
#define buf_append(buf, format, ...) \
len += snprintf(&(buf[len]), sizeof(buf) - len, \
format, __VA_ARGS__)
canonicalRequest[0] = '\0';
buf_append(canonicalRequest, "%s\n", httpMethod);
buf_append(canonicalRequest, "%s\n", values->canonicalURI);
buf_append(canonicalRequest, "%s\n", values->canonicalQueryString);
buf_append(canonicalRequest, "%s\n", values->canonicalizedSignatureHeaders);
buf_append(canonicalRequest, "%s\n", values->signedHeaders);
buf_append(canonicalRequest, "%s", values->payloadHash);
#ifdef SIGNATURE_DEBUG
printf("--\nCanonical Request:\n%s\n", canonicalRequest);
#endif
len = 0;
unsigned char canonicalRequestHash[S3_SHA256_DIGEST_LENGTH];
#ifdef __APPLE__
CC_SHA256(canonicalRequest, strlen(canonicalRequest), canonicalRequestHash);
#else
const unsigned char *rqstData = (const unsigned char*) canonicalRequest;
SHA256(rqstData, strlen(canonicalRequest), canonicalRequestHash);
#endif
char canonicalRequestHashHex[2 * S3_SHA256_DIGEST_LENGTH + 1];
canonicalRequestHashHex[0] = '\0';
int i = 0;
for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
buf_append(canonicalRequestHashHex, "%02x", canonicalRequestHash[i]);
}
const char *awsRegion = S3_DEFAULT_REGION;