This repository has been archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
request.c
1957 lines (1681 loc) · 69.3 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 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/>.
*
************************************************************************** **/
#include <ctype.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/utsname.h>
#include "request.h"
#include "request_context.h"
#include "response_headers_handler.h"
#include "util.h"
#include <openssl/sha.h>
#include <openssl/hmac.h>
#define USER_AGENT_SIZE 256
#define REQUEST_STACK_SIZE 32
static int verifyPeer;
static S3SignatureVersion signatureVersionG;
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];
char whichRegionIsHereG[S3_MAX_HOSTNAME_SIZE] = "us-east-1";
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];
// Canonicalized x-amz- headers
string_multibuffer(canonicalizedAmzHeaders,
COMPACTED_METADATA_BUFFER_SIZE + 256 + 1);
// URL-Encoded key
char urlEncodedKey[MAX_URLENCODED_KEY_SIZE + 1];
// Canonicalized resource
char canonicalizedResource[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];
// Date header (or empty)
char dateHeader [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[128];
// Host header
char hostHeader[128];
// Time stamp is ISO 8601 format: 'yyyymmddThhmmssZ'
char timestamp[32];
// The signed headers
char signedHeaders[COMPACTED_METADATA_BUFFER_SIZE];
} 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 procesed. 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);
}
// 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,
RequestComputedValues *values)
{
const S3PutProperties *properties = params->putProperties;
values->amzHeadersCount = 0;
values->amzHeadersRaw[0] = 0;
int len = 0;
// Append a header to amzHeaders, trimming whitespace from the end.
// Does NOT trim whitespace from the beginning.
#define headers_append(isNewHeader, format, ...) \
do { \
if (isNewHeader) { \
values->amzHeaders[values->amzHeadersCount++] = \
&(values->amzHeadersRaw[len]); \
} \
len += snprintf(&(values->amzHeadersRaw[len]), \
sizeof(values->amzHeadersRaw) - len, \
format, __VA_ARGS__); \
if (len >= (int) sizeof(values->amzHeadersRaw)) { \
return S3StatusMetaDataHeadersTooLong; \
} \
while ((len > 0) && (values->amzHeadersRaw[len - 1] == ' ')) { \
len--; \
} \
values->amzHeadersRaw[len++] = 0; \
} while (0)
#define header_name_tolower_copy(str, l) \
do { \
values->amzHeaders[values->amzHeadersCount++] = \
&(values->amzHeadersRaw[len]); \
if ((len + l) >= (int) sizeof(values->amzHeadersRaw)) { \
return S3StatusMetaDataHeadersTooLong; \
} \
int todo = l; \
while (todo--) { \
if ((*(str) >= 'A') && (*(str) <= 'Z')) { \
values->amzHeadersRaw[len++] = 'a' + (*(str) - 'A'); \
} \
else { \
values->amzHeadersRaw[len++] = *(str); \
} \
(str)++; \
} \
} while (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]);
char headerName[S3_MAX_METADATA_SIZE - sizeof(": v")];
int l = snprintf(headerName, sizeof(headerName),
S3_METADATA_HEADER_NAME_PREFIX "%s",
property->name);
char *hn = headerName;
header_name_tolower_copy(hn, l);
// Copy in the value
headers_append(0, ": %s", property->value);
}
// Add the x-amz-acl header, if necessary
const char *cannedAclString;
switch (properties->cannedAcl) {
case S3CannedAclPrivate:
cannedAclString = 0;
break;
case S3CannedAclPublicRead:
cannedAclString = "public-read";
break;
case S3CannedAclPublicReadWrite:
cannedAclString = "public-read-write";
break;
default: // S3CannedAclAuthenticatedRead
cannedAclString = "authenticated-read";
break;
}
if (cannedAclString) {
headers_append(1, "x-amz-acl: %s", cannedAclString);
}
// Add the x-amz-server-side-encryption header, if necessary
if (properties->useServerSideEncryption) {
headers_append(1, "x-amz-server-side-encryption: %s", "AES256");
}
}
// Add the x-amz-date header
time_t now = time(NULL);
char date[64];
struct tm gmt;
if (signatureVersionG == S3SignatureV2) {
strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S GMT",
gmtime_r(&now, &gmt));
} else {
// Auth version 4 requires ISO 8601 date time format
strftime(date, sizeof(date), "%Y%m%dT%H%M%SZ", gmtime_r(&now, &gmt));
memcpy(values->timestamp, date, sizeof(values->timestamp));
}
// Omit x-amz-date if required
if(params->bucketContext.stsDate != S3STSDateOnly) {
headers_append(1, "x-amz-date: %s", date);
}
if (signatureVersionG == S3SignatureV4) {
// Add the x-amz-content-sha256 header
if (properties && properties->md5 && properties->md5[0]) {
headers_append(1, "x-amz-content-sha256: %s", properties->md5);
} else {
headers_append(1, "%s", "x-amz-content-sha256: UNSIGNED-PAYLOAD");
}
}
// Capture the date for possible use in StringToSign
if (params->bucketContext.stsDate != S3STSAmzOnly) {
snprintf(values->dateHeader, sizeof(values->dateHeader),"Date: %s", date);
}
if (params->httpRequestType == HttpRequestTypeCOPY) {
// Add the x-amz-copy-source header
if (params->copySourceBucketName && params->copySourceBucketName[0] &&
params->copySourceKey && params->copySourceKey[0]) {
headers_append(1, "x-amz-copy-source: /%s/%s",
params->copySourceBucketName,
params->copySourceKey);
}
// If byteCount != 0 then we're just copying a range, add header
if (params->byteCount > 0) {
headers_append(1, "x-amz-copy-source-range: bytes=%lld-%lld",
(unsigned long long) params->startByte,
(unsigned long long) (params->startByte + params->byteCount) );
}
// And the x-amz-metadata-directive header
if (properties) {
headers_append(1, "%s", "x-amz-metadata-directive: REPLACE");
}
}
// Add the x-amz-security-token header if necessary
if (params->bucketContext.securityToken) {
headers_append(1, "x-amz-security-token: %s",
params->bucketContext.securityToken);
}
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 if (signatureVersionG == S3SignatureV4) {
const char *requestHostName = params->bucketContext.hostName
? params->bucketContext.hostName : defaultHostNameG;
snprintf(values->hostHeader, sizeof(values->hostHeader),
"Host: %s", requestHostName);
} else {
values->hostHeader[0] = 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 HTTP header names that are
// embedded within an HTTP header line, returning true if header1 comes
// before header2 alphabetically, false if not
static int headerle(const char *header1, const char *header2)
{
while (1) {
if (*header1 == ':') {
return (*header2 != ':');
}
else if (*header2 == ':') {
return 0;
}
else if (*header2 < *header1) {
return 0;
}
else if (*header2 > *header1) {
return 1;
}
header1++, header2++;
}
}
// 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 header_gnome_sort(const char **headers, int size)
{
int i = 0, last_highest = 0;
while (i < size) {
if ((i == 0) || headerle(headers[i - 1], headers[i])) {
i = ++last_highest;
}
else {
const char *tmp = headers[i];
headers[i] = headers[i - 1];
headers[--i] = tmp;
}
}
}
// Canonicalizes the x-amz- headers into the canonicalizedAmzHeaders buffer
static void canonicalize_amz_headers(RequestComputedValues *values)
{
// Make a copy of the headers that will be sorted
const char *sortedHeaders[S3_MAX_METADATA_COUNT];
memcpy(sortedHeaders, values->amzHeaders,
(values->amzHeadersCount * sizeof(sortedHeaders[0])));
// Now sort these
header_gnome_sort(sortedHeaders, values->amzHeadersCount);
// 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, i;
char *buffer = values->canonicalizedAmzHeaders;
for (i = 0; i < values->amzHeadersCount; i++) {
const char *header = sortedHeaders[i];
const char *c = header;
// 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 != ' ') {
*buffer++ = *c++;
}
// 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';
}
// Terminate the buffer
*buffer = 0;
}
// Canonicalizes the resource into params->canonicalizedResource
static void canonicalize_resource(const char *bucketName,
const char *subResource,
const char *urlEncodedKey,
char *buffer)
{
int len = 0;
*buffer = 0;
#define append(str) len += sprintf(&(buffer[len]), "%s", str)
if (bucketName && bucketName[0]) {
buffer[len++] = '/';
append(bucketName);
}
append("/");
if (urlEncodedKey && urlEncodedKey[0]) {
append(urlEncodedKey);
}
if (subResource && subResource[0]) {
append("?");
append(subResource);
}
}
// 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)
{
// We allow for:
// 17 bytes for HTTP-Verb + \n
// 129 bytes for Content-MD5 + \n
// 129 bytes for Content-Type + \n
// 129 bytes for Date + \n
// CanonicalizedAmzHeaders & CanonicalizedResource
char signbuf[17 + 129 + 129 + 129 +
(sizeof(values->canonicalizedAmzHeaders) - 1) +
(sizeof(values->canonicalizedResource) - 1) + 1];
int len = 0;
#define signbuf_append(format, ...) \
len += snprintf(&(signbuf[len]), sizeof(signbuf) - len, \
format, __VA_ARGS__)
signbuf_append
("%s\n", http_request_type_to_verb(params->httpRequestType));
// For MD5 and Content-Type, use the value in the actual header, because
// it's already been trimmed
signbuf_append("%s\n", values->md5Header[0] ?
&(values->md5Header[sizeof("Content-MD5: ") - 1]) : "");
signbuf_append
("%s\n", values->contentTypeHeader[0] ?
&(values->contentTypeHeader[sizeof("Content-Type: ") - 1]) : "");
// append the date header, if populated
signbuf_append("%s\n", values->dateHeader[0] ?
&(values->dateHeader[sizeof("Date: ") - 1]) : "");
signbuf_append("%s", values->canonicalizedAmzHeaders);
signbuf_append("%s", values->canonicalizedResource);
// Generate an HMAC-SHA-1 of the signbuf
unsigned char hmac[20];
HMAC_SHA1(hmac, (unsigned char *) params->bucketContext.secretAccessKey,
strlen(params->bucketContext.secretAccessKey),
(unsigned char *) signbuf, len);
// Now base-64 encode the results
char b64[((20 + 1) * 4) / 3];
int b64Len = base64Encode(hmac, 20, b64);
snprintf(values->authorizationHeader, sizeof(values->authorizationHeader),
"Authorization: AWS %s:%.*s", params->bucketContext.accessKeyId,
b64Len, b64);
return S3StatusOK;
}
// Compose the URI to use for the request given the request parameters
static S3Status compose_uri(char *buffer, int bufferSize,
const S3BucketContext *bucketContext,
const char *urlEncodedKey,
const char *subResource, const char *queryParams)
{
int len = 0;
#define uri_append(fmt, ...) \
do { \
len += snprintf(&(buffer[len]), bufferSize - len, fmt, __VA_ARGS__); \
if (len >= bufferSize) { \
return S3StatusUriTooLong; \
} \
} while (0)
uri_append("http%s://",
(bucketContext->protocol == S3ProtocolHTTP) ? "" : "s");
const char *hostName =
bucketContext->hostName ? bucketContext->hostName : defaultHostNameG;
if (bucketContext->bucketName &&
bucketContext->bucketName[0]) {
if (bucketContext->uriStyle == S3UriStyleVirtualHost) {
if (strchr(bucketContext->bucketName, '.') == NULL) {
uri_append("%s.%s", bucketContext->bucketName, hostName);
}
else {
// We'll use the hostName in the URL, and then explicitly set
// the Host header to match bucket.host so that host validation
// works.
uri_append("%s", hostName);
}
}
else {
uri_append("%s/%s", hostName, bucketContext->bucketName);
}
}
else {
uri_append("%s", hostName);
}
uri_append("%s", "/");
uri_append("%s", urlEncodedKey);
if (subResource && subResource[0]) {
uri_append("?%s", subResource);
}
if (queryParams) {
uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?",
queryParams);
}
return S3StatusOK;
}
static S3Status string_append_char(char *buf, int maxlen, int *plen, char c)
{
if (*plen >= maxlen - 1) return S3StatusUriTooLong;
buf[*plen] = c;
++(*plen);
return S3StatusOK;
}
#define string_appendf(buf, maxlen, plen, format, ...) do { \
*(plen) += snprintf(&((buf)[*(plen)]), \
(maxlen) - (*(plen)), \
format, __VA_ARGS__); \
} while (0)
static S3Status string_append_hex(char *buf, int maxlen, int *plen,
const char *data, int datalen)
{
int i;
for (i = 0; i < datalen; i++) {
string_appendf(buf, maxlen, plen, "%02x", (unsigned char)data[i]);
}
return S3StatusOK;
}
static S3Status string_append_params(char *buf, int maxlen, int *plen,
const char **params, unsigned int count)
{
unsigned int i;
for (i = 0; i < count; i++) {
const char *itr;
if (i > 0) {
if (string_append_char(buf, maxlen, plen, '&') != S3StatusOK)
return S3StatusQueryParamsTooLong;
}
int hasValue = 0;
for (itr = params[i]; *itr != '&' && *itr != '\0'; itr++) {
if (*itr == '=') hasValue = 1;
if (string_append_char(buf, maxlen, plen, *itr) != S3StatusOK)
return S3StatusQueryParamsTooLong;
}
if (!hasValue) {
if (string_append_char(buf, maxlen, plen, '=') != S3StatusOK)
return S3StatusQueryParamsTooLong;
}
}
return S3StatusOK;
}
// Simple comparison function for comparing two HTTP query parameters that are
// embedded within an HTTP URL, returning true if param1 comes
// before param2 alphabetically, false if not
static int paramle(const char *param1, const char *param2)
{
while (1) {
if (*param1 == '=' || *param1 == '&' || *param1 == '\0') {
return 1;
}
else if (*param2 == '=' || *param2 == '&' || *param2 == '\0') {
return 0;
}
else if (*param2 < *param1) {
return 0;
}
else if (*param2 > *param1) {
return 1;
}
param1++, param2++;
}
}
/**
* General gnome sort.
*/
typedef int (*less_func_t)(const char *p1, const char *p2);
static void general_gnome_sort(const char **params, int size,
less_func_t less)
{
int i = 0, last_highest = 0;
while (i < size) {
if ((i == 0) || less(params[i - 1], params[i])) {
i = ++last_highest;
}
else {
const char *tmp = params[i];
params[i] = params[i - 1];
params[--i] = tmp;
}
}
}
static S3Status canonicalize_query_params(char *buf, int maxlen, int *plen,
const char *querys)
{
const char *query_params[1024];
unsigned int count = 0;
const char *itr;
S3Status ret;
query_params[count] = querys; count++;
for (itr = querys; *itr != '\0'; itr++) {
if (*itr == '&') {
itr++;
if (*itr == '\0' || *itr == '&' || *itr == '=')
return S3StatusBadMetaData;
if (count >= sizeof(query_params))
return S3StatusQueryParamsTooLong;