forked from vladistan/aws4c
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaws4c.c
2989 lines (2444 loc) · 89.4 KB
/
aws4c.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
/**
*/
/*
*
* Copyright(c) 2009, Vlad Korolev, <vlad[@]v-lad.org >
*
* with contributions from Henry Nestler < Henry at BigFoot.de >
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://www.gnu.org/licenses/lgpl-3.0.txt
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*/
/*!
\mainpage
This is a small library that provides Amazon Web Services binding
for C programs.
The AWS4C leverages CURL and OPENSSL libraries for HTTP transfer and
cryptographic functions.
The \ref todo list is here.
The \ref bug list is here.
*/
/// \todo Include regression testing
/// \todo Run thing through valgrind
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include "aws4c.h"
/*!
\defgroup internal Internal Functions
\{
*/
// Masks for various AWSContext.flags
// S3Host and S3Proxy are initially static constants, but will be replaced
// with dynamically-allocated strings. The "_STATIC" flags let us know
// whether to free, or not.
typedef enum {
S3HOST_STATIC = 0x0001,
S3PROXY_STATIC = 0x0002,
AWS4C_CTE = 0x0004,
AWS4C_EMC_COMPAT = 0x0010,
AWS4C_SCALITY_COMPAT = 0x0020,
AWS4C_SPROXYD = 0x0040,
AWS4C_HTTPS = 0x0080,
AWS4C_HTTPS_INSECURE = 0x0100,
AWS4C_HTTP_DIGEST = 0x0200,
} AWS4C_FLAGS;
// This is the default context. It is used when you call the
// non-thread-safe parameter-setting functions (e.g. aws_set_id(), or
// s3_set_host()). The default context is used to generate requests only
// if you do not bind some other AWSContext to your IOBuf. In other words,
// if you want/need thread-safety, then use the re-entrant functions to set
// state (e.g. aws_set_id_r(), or s3_set_host_r()), and install that
// context into your IOBuf (i.e. with aws_iobuf_set_context()).
// NOTE: This is initialized in aws_init(), by a call to aws_context_reset_r()
static AWSContext default_ctx;
// <debug> is still global, for now. It would take some work to thread an
// AWSContext into all the places that call __debug()
//
static int debug = 0; /// <flag to control debugging options
// If you call aws_reuse_connections() with non-zero value, then we'll try
// to reuse connections, instead of calling curl_easy_init() /
// curl_easy_cleanup() in every function. aws_reset_connection() causes a
// one-time reset. (This is useful to eliminate client-side caching which
// may affect measure read bandwidth.)
static void aws_curl_enter();
static void aws_curl_exit();
static void __debug ( char *fmt, ... ) ;
static char * __aws_get_iso_date (char* date, size_t size, time_t* time);
static char * __aws_get_httpdate (char* date, size_t size, time_t* time);
static FILE * __aws_getcfg ();
static CURLcode s3_do_get ( IOBuf* b, char* const signature,
char* const date, char* const resource,
int head_p,
char* const dst_fname, IOBuf* repsonse );
static CURLcode s3_do_put_or_post( IOBuf* b, char* const signature,
char* const date, char* const resource,
int post_p,
char* const src_fname, IOBuf* response );
static CURLcode s3_do_delete ( IOBuf* b, char* const signature,
char* const date, char* const resource);
static void aws_iobuf_append_internal(IOBuf* B, char* d, size_t len,
int needs_alloc, int is_static);
static void aws_iobuf_extend_internal(IOBuf* B, char* d, size_t len,
int is_static);
static char* __aws_sign ( char* const str, AWSContext* ctx );
static void __chomp ( char * str );
#ifdef ENABLE_UNBASE64
/// Decode base64 into binary
/// \param input base64 text
/// \param length length of the input text
/// \return decoded data in newly allocated buffer
/// \internal
///
/// This function allocates a buffer of the same size as the input
/// buffer and then decodes the given base64 encoded text into
/// binary. The result is placed into the allocated buffer. It is
/// the caller's responsibility to free this buffer
static char *unbase64(unsigned char *input, int length)
{
BIO *b64, *bmem;
/// Allocate and zero the buffer
char *buffer = (char *)malloc(length);
memset(buffer, 0, length);
/// Decode the input into the newly allocated buffer
/// \todo Check for errors during decode
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, length);
bmem = BIO_push(b64, bmem);
BIO_read(bmem, buffer, length);
BIO_free_all(bmem);
/// Return the decoded text
return buffer;
}
#endif /* ENABLE_UNBASE64 */
/// Encode a binary into base64 buffer
/// \param input binary data text
/// \param length length of the input text
/// \internal
/// \return a newly allocated buffer with base64 encoded data
static char *__b64_encode(const unsigned char *input, int length)
{
BIO *bmem, *b64;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, length);
if(BIO_flush(b64)) ; /* make gcc 4.1.2 happy */
BIO_get_mem_ptr(b64, &bptr);
char *buff = (char *)malloc(bptr->length);
memcpy(buff, bptr->data, bptr->length-1);
buff[bptr->length-1] = 0;
BIO_free_all(b64);
return buff;
}
/// Chomp (remove the trailing '\n' from the string).
/// If there's a '\r' in the next-to-last position, remove that.
///
/// \param str string
///
static void __chomp ( char * str )
{
if ( str[0] == 0 )
return;
int ln = strlen(str) -1;
if ( str[ln] == '\n' ) {
str[ln] = 0;
if ( ln == 0 )
return ;
ln--;
if ( str[ln] == '\r' )
str[ln] = 0;
}
}
/// Handles reception of the data
/// \param ptr pointer to the incoming data
/// \param size size of the data member
/// \param nmemb number of data memebers
/// \param stream pointer to I/O buffer
/// \return number of bytes processed
size_t aws_writefunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
__debug ( "DATA RECV %d items of size %d ", nmemb, size );
aws_iobuf_append ( stream, ptr, nmemb*size );
return nmemb * size;
}
/// Suppress outputs to stdout
static size_t aws_writedummyfunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
__debug ( "writedummy -- stifling %d items of size %d ", nmemb, size );
return nmemb * size;
}
/// Handles sending of the data
/// \param ptr pointer to the incoming data
/// \param size size of the data member
/// \param nmemb number of data memebers
/// \param stream pointer to I/O buffer
/// \return number of bytes written
size_t aws_readfunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
// char * Ln = ptr;
size_t sz = aws_iobuf_get_raw ( stream, ptr, size*nmemb);
// __debug ( "Sent[%3lu] %s", sz, Ln );
__debug ( "Sent[%3lu]", sz );
return sz;
}
/// Process incoming header
/// \param ptr pointer to the incoming data
/// \param size size of the data member
/// \param nmemb number of data memebers
/// \param stream pointer to I/O buffer
/// \return number of bytes processed
size_t aws_headerfunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
// __debug("header -- reading %d * %d bytes from '%s'", nmemb, size, ptr);
IOBuf * b = stream;
if (!strncmp( ptr, "HTTP/1.1", 8 )) {
if (b->result)
free(b->result); /* don't leak memory */
b->result = strdup( ptr + 9 );
__chomp(b->result);
b->code = atoi( ptr + 9 );
}
else if ( !strncmp( ptr, "ETag: ", 6 )) {
if (b->eTag)
free(b->eTag); /* don't leak memory */
b->eTag = strdup( ptr + 6 );
__chomp(b->eTag);
}
else if ( !strncmp( ptr, "Last-Modified: ", 14 )) {
if (b->lastMod)
free(b->lastMod); /* don't leak memory */
b->lastMod = strdup( ptr + 15 );
__chomp(b->lastMod);
}
else if ( !strncmp( ptr, "Content-Length: ", 15 )) {
b->contentLen = strtoul( ptr + 16, NULL, 10 );
}
else if ( !strncmp( ptr, "x-amz-meta-", 11 )) {
char* key = ptr+11;
char* key_end = strchr(key, ':');
if (key_end) {
*key_end = 0;
char* value = key_end +2; /* skip ": " */
__chomp(value);
aws_metadata_set(&(b->meta), key, value);
}
}
return nmemb * size;
}
/// Get date for authentication of SQS request
/// Format request-date into provided buffer. Caller can provide
/// the timestamp. Thread-safe.
///
/// \internal
/// \param dTa buffer to receive formatted time
/// \param size size of dTa
/// \param time if non-null, use this time, instead of "now".
//
/// \return date in ISO format
static char * __aws_get_iso_date (char* dTa, size_t size, time_t* t_ptr)
{
// use GMT time
struct tm* gTime;
struct tm result;
if (t_ptr)
gTime = gmtime_r(t_ptr, &result);
else {
time_t t = time(NULL);
gTime = gmtime_r(&t, &result);
}
if (! gTime)
return NULL; /* error in gmtime_r() */
memset ( dTa, 0 , size);
strftime ( dTa, size, "%FT%H:%M:%SZ", gTime );
__debug ( "Request Time: %s", dTa );
return dTa;
}
#ifdef ENABLE_DUMP
/// Dump current state
/// \internal
static void Dump() {
Dump_r(&default_ctx);
}
static void Dump_r(AWSContext* ctx) {
printf ( "----------------------------------------\n");
printf ( "ID : %-40s \n", ctx->ID );
printf ( "KeyID : %-40s \n", ctx->awsKeyID );
printf ( "Key : %-40s \n", ctx->awsKey );
printf ( "S3 Host : %-40s \n", ctx->S3Host );
printf ( "S3 Proxy : %-40s \n", ctx->S3Proxy );
printf ( "SQS Host : %-40s \n", ctx->SQSHost );
printf ( "Bucket : %-40s \n", ctx->Bucket );
printf ( "----------------------------------------\n");
}
#endif /* ENABLE_DUMP */
/// Print debug output
/// \internal
/// \param fmt printf like formating string
static void __debug ( char *fmt, ... ) {
/// If debug flag is not set we won't print anything
if ( ! debug ) return ;
/// Otherwise process the arguments and print the result
va_list args;
va_start( args, fmt );
fprintf( stderr, "DBG: " );
vfprintf( stderr, fmt, args );
fprintf( stderr, "\n" );
va_end( args );
}
/// Format request-date into provided buffer. Caller can provide
/// the timestamp. Thread-safe.
///
/// \internal
/// \param dTa buffer to receive formatted time
/// \param size size of dTa
/// \param time if non-null, use this time, instead of "now".
//
/// \Return date in HTTP format
static char * __aws_get_httpdate (char* dTa, size_t size, time_t* t_ptr)
{
// use GMT time
struct tm* gTime;
struct tm result;
if (t_ptr)
gTime = gmtime_r(t_ptr, &result);
else {
time_t t = time(NULL);
gTime = gmtime_r(&t, &result);
}
if (! gTime)
return NULL; /* error in gmtime_r() */
memset ( dTa, 0 , size);
strftime ( dTa, size, "%a, %d %b %Y %H:%M:%S +0000", gTime );
__debug ( "Request Time: %s", dTa );
return dTa;
}
/// Internal function to get configuration file
static FILE * __aws_getcfg ()
{
int rv;
char ConfigFile[256];
struct passwd* pw;
/// Compose FileName and check
pw = getpwuid(geteuid());
snprintf ( ConfigFile, sizeof(ConfigFile) -3, "%s/.awsAuth", pw->pw_dir );
__debug ( "Config File %s", ConfigFile );
struct stat sBuf;
rv = stat ( ConfigFile, &sBuf );
if ( rv == -1 ) return NULL;
if ( sBuf.st_mode & 066 ||
sBuf.st_uid != geteuid () ) {
fprintf ( stderr, "I refuse to read your credentials from %s as this "
"file is readable by, writable by or owned by someone else."
"Try chmod 600 %s", ConfigFile, ConfigFile );
return NULL;
}
return fopen ( ConfigFile, "r" );
}
/// Get S3 Request signature
/// \internal
/// \param resource -- URI of the object
/// \param resSize -- size of the resource buffer
/// \param date -- struct containind HTTP date-buffer, and optional time_t*
/// \param method -- HTTP method
/// \param bucket -- bucket
/// \param file -- file
/// \return fills up resource and date parameters, also
/// returns request signature to be used with Authorization header
/// \todo Change the way RRS is handled. Need to pass it in
char* GetStringToSign ( char * resource,
int resSize,
DateConv* dateConv,
char * const method,
MetaNode* metadata,
// char * const bucket,
char * const file,
AWSContext* ctx)
{
char reqToSign[2048];
char acl[32];
char rrs[64];
const size_t MAX_META = 2048;
char meta[MAX_META];
MetaNode* pair;
__aws_get_httpdate((char*)dateConv->chars, DateConvStringSize, dateConv->time);
memset ( resource, 0, resSize);
if ( ctx->Bucket )
snprintf ( resource, resSize, "%s/%s", ctx->Bucket, file );
else
snprintf ( resource, resSize, "%s", file );
if (ctx->AccessControl)
snprintf( acl, sizeof(acl), "x-amz-acl:%s\n", ctx->AccessControl);
else
acl[0] = 0;
// print meta-data into meta[], until we run out of room
size_t offset=0;
size_t remain=MAX_META -1; /* assure there's room for final NULL */
for (pair=metadata; pair; pair=pair->next) {
size_t expect = strlen(pair->key) + strlen(pair->value) + 13;
if (expect > remain)
break; /* don't print partial key/value pairs */
int count = snprintf( &meta[offset], remain, "x-amz-meta-%s:%s\n",
pair->key, pair->value);
if (count != expect) {
fprintf(stderr, "Error computing meta-data size: expect=%ld actual=%d\n",
expect, count);
exit(1);
}
remain -= count;
offset += count;
}
meta[offset] = 0;
if (ctx->useRrs)
strncpy( rrs, "x-amz-storage-class:REDUCED_REDUNDANCY\n", sizeof(rrs));
else
rrs[0] = 0;
snprintf ( reqToSign, sizeof(reqToSign), "%s\n\n%s\n%s\n%s%s%s/%s",
method,
ctx->MimeType ? ctx->MimeType : "",
(char*)dateConv->chars,
acl,
meta,
rrs,
resource );
// EU: If bucket is in virtual host name, remove bucket from path
if (ctx->Bucket && strncmp(ctx->S3Host, ctx->Bucket, strlen(ctx->Bucket)) == 0)
snprintf ( resource, resSize, "%s", file );
// Scality sproxyd doesn't require an Authorization header in the request.
if (ctx->flags & AWS4C_SPROXYD)
return NULL;
return __aws_sign(reqToSign, ctx);
}
static void __aws_urlencode ( char * src, char * dest, int nDest )
{
int i;
int n;
memset ( dest, 0, nDest );
__debug ( "Encoding: %s", src );
const char * badChrs = " \n$&+,/:;=?@";
const char * hexDigit = "0123456789ABCDEF";
n = 0;
for ( i = 0 ; src[i] ; i ++ ) {
if ( n + 5 > nDest ) {
puts ( "URLEncode:: Dest buffer to small.. can't continue \n" );
exit(0);
}
if ( strchr ( badChrs, src[i] )) {
unsigned char c = src[i];
dest[n++] = '%';
dest[n++] = hexDigit [(c >> 4 ) & 0xF ];
dest[n++] = hexDigit [c & 0xF ];
}
else dest[n++] = src[i];
}
__debug ( "Encoded To: %s", dest );
}
// ---------------------------------------------------------------------------
// AWS Context
// ---------------------------------------------------------------------------
/*!
\}
*/
/*!
\defgroup conf AWSContext Functions (thread-safety)
\{
*/
// For internal consumption only. return an uninitialized new AWSContext.
static AWSContext* aws_context_new_internal() {
AWSContext* ctx = (AWSContext*)malloc(sizeof(AWSContext));
if (!ctx) {
fprintf(stderr, "aws_context_new_internal: malloc failed\n");
return NULL;
}
memset(ctx, 0, sizeof(AWSContext));
return ctx;
}
// reinstall default values
void aws_context_reset() { // reset the default context
aws_context_reset_r(&default_ctx);
}
// Restore original default settings in a context.
void aws_context_reset_r(AWSContext* ctx) {
// free any dynamically-allocated storage
aws_context_release_r(ctx);
// assign default values
*ctx = (AWSContext) {
.ch = NULL,
.reuse_connections = 0,
.reset_connection = 0,
.inside = 0,
// .debug = 0, /// <flag to control debugging options
.useRrs = 0, /// <Use reduced redundancy storage
.ID = NULL, /// <Current ID
.awsKeyID = NULL, /// <AWS Key ID
.awsKey = NULL, /// <AWS Key Material
/// \todo Use SQSHost in SQS functions
/// \todo NOTE: Unlike all other string-members, we allocate SQSHost statically
/// \todo That's because there's no set method for it, and context_clone() doesn't
// \todo strdup() it, and context_release() etc doesn't free it.
.SQSHost = DEFAULT_SQS_HOST, /// <AWS SQS host
.S3Host = DEFAULT_S3_HOST, /// <AWS S3 host
.S3Proxy = NULL,
.Bucket = NULL,
.MimeType = NULL,
.AccessControl = NULL,
.byte_range = {0, 0}, /* resets automatically, after next GET */
.content_length = 0, /* resets automatically, after next PUT/POST */
.flags = (S3HOST_STATIC | S3PROXY_STATIC), /* */
};
}
// allocate a new context, initialized to defaults
AWSContext* aws_context_new() {
AWSContext* ctx = aws_context_new_internal();
aws_context_reset_r(ctx);
return ctx;
}
// copy the (current state of) the default context. You could make some
// initializations to the default context, then use that as a
// starting-point for all your custom contexts.
//
// NOTE: We call aws_iobuf_reset(), because you obviously wouldn't want to
// duplicate any default IOBufNode context into your cloned structure.
AWSContext* aws_context_clone() {
return aws_context_clone_r(&default_ctx);
}
AWSContext* aws_context_clone_r(AWSContext* ctx) {
if (!ctx)
return NULL;
AWSContext* new_ctx = aws_context_new_internal();
// // DO NOT DO THIS. The curl handle needs to be cleaned up (which closes
// // any existing connection). We could do this explicitly, like
// // aws_reset_connection(), but we're already going to call
// // s3_set_host(NULL,ctx), which will also reset the connection, as long
// // as we haven't nulled it out, here.
//
// new_ctx->ch = NULL;
new_ctx->inside = 0; // don't want to match original this closely?
new_ctx->reset_connection = 0; // don't want to match original this closely?
aws_reuse_connections_r(ctx->reuse_connections, new_ctx);
// aws_set_debug_r(ctx->debug, new_ctx);
aws_set_rrs_r(ctx->useRrs, new_ctx);
aws_set_id_r(ctx->ID, new_ctx);
aws_set_keyid_r(ctx->awsKeyID, new_ctx);
aws_set_key_r(ctx->awsKey, new_ctx);
// we aren't maintaining this as dynamically allocated
new_ctx->SQSHost = DEFAULT_SQS_HOST; /// <AWS SQS host
s3_set_bucket_r(ctx->Bucket, new_ctx);
s3_set_host_r(ctx->S3Host, new_ctx);
s3_set_proxy_r(ctx->S3Proxy, new_ctx);
s3_set_mime_r(ctx->MimeType, new_ctx);
s3_set_acl_r(ctx->AccessControl, new_ctx);
new_ctx->byte_range.offset = 0;
new_ctx->byte_range.length = 0;
new_ctx->content_length = 0;
return new_ctx;
}
// free old storage
void aws_context_release() {
aws_context_release_r(&default_ctx);
}
void aws_context_release_r(AWSContext* ctx) {
if (ctx->ID)
free(ctx->ID);
aws_set_keyid_r(NULL, ctx);
aws_set_key_r(NULL, ctx);
s3_set_bucket_r(NULL, ctx);
s3_set_host_r(NULL, ctx);
s3_set_proxy_r(NULL, ctx);
s3_set_mime_r(NULL, ctx);
s3_set_acl_r(NULL, ctx);
}
void aws_context_free_r(AWSContext* ctx) {
aws_context_release_r(ctx);
free(ctx);
}
// ---------------------------------------------------------------------------
// Context get/set functions
// ---------------------------------------------------------------------------
/*!
\}
*/
/*!
\defgroup aws AWS-related Configuration Functions
\{
*/
// This affects whether AWS_CURL_ENTER() / AWS_CURL_EXIT() will use
// curl_easy_reset() or will entirely close the curl connection.
void aws_reuse_connections(int val) {
aws_reuse_connections_r(val, &default_ctx);
}
void aws_reuse_connections_r(int val, AWSContext* ctx) {
ctx->reuse_connections = val;
}
// This causes the next curl-request to reset the connection. It causes
// the connection to be reset only once. This is useful, for example, to
// drop client-side caches after writing, which may artificially enhance
// read-bandwidth. If reuse_connections is non-zero, connections will
// still be reused, after the one-time reset.
//
// NOTE: This will only take effect on the next entry()
void aws_reset_connection() {
aws_reset_connection_r(&default_ctx);
}
void aws_reset_connection_r(AWSContext* ctx) {
if (ctx->inside)
curl_easy_setopt(ctx->ch, CURLOPT_FORBID_REUSE, 1); /* current request */
else {
// ctx->reset_connection = 1; /* next request */
// Forcibly close the connection now. We might not ever use this
// connection again, and we don't want the corresponding
// file-descriptor to sit around in CLOSE_WAIT state. [Copied from
// aws_curl_enter().]
curl_easy_cleanup(ctx->ch);
ctx->ch = NULL; /* this is safe, after curl_easy_cleanup() */
}
}
/// Initialize the library.
///
/// NOTE: From the manpage:
///
/// This function is not thread safe. You must not call it when any
/// other thread in the program (i.e. a thread sharing the same memory)
/// is running. This doesn't just mean no other thread that is using
/// libcurl. Because curl_global_init() calls functions of other
/// libraries that are similarly thread unsafe, it could conflict with
/// any other thread that uses these other libraries.
///
CURLcode aws_init () {
CURLcode rc = curl_global_init(CURL_GLOBAL_ALL);
if (rc == CURLE_OK)
aws_context_reset_r(&default_ctx);
return rc;
}
void aws_cleanup () {
aws_context_reset_r(&default_ctx);
curl_global_cleanup();
}
/// Set debuging output
/// \param d when non-zero causes debugging output to be printed
void aws_set_debug (int d) {
debug = d;
}
// This is the first token in each colon-delimited line in the ~/.awsAuth
// file. It would typically correspond with a user's moniker, e.g. via
// getenv("USER"), but really it could be any token that serves to identify
// the rest of the line, which contains the user/pass for accessing the
// object-store.
//
/// \brief Set AWS account ID to be read from .awsAuth file
/// \param id new account ID
void aws_set_id ( char * const id ) {
aws_set_id_r(id, &default_ctx);
}
void aws_set_id_r ( char * const id, AWSContext* ctx ) {
if (ctx->ID)
free(ctx->ID);
ctx->ID = ((id == NULL) ? strdup(getenv("USER")) : strdup(id));
}
// This is the second token in each colon-delimited line in the ~/.awsAuth
// file.
//
// For AWS S3, the key is the "user", known to the object store, presented
// unencrypted along with the encrypted header. For CURL "digest" this is
// the "user", known to the object-store.
//
/// Set AWS account access key
/// \param key new AWS authentication key
void aws_set_key ( char * const key ) {
aws_set_key_r(key, &default_ctx);
}
void aws_set_key_r ( char * const key, AWSContext* ctx ) {
if (ctx->awsKey)
free(ctx->awsKey);
ctx->awsKey = ((key == NULL) ? NULL : strdup(key));
}
// This is the third token in each colon-delimited line in the ~/.awsAuth
// file. It represents the "password" (stored unencrypted), corresponding
// to the "user" (installed via aws_set_key[_r]()), recognized by the
// object-store.
//
// For AWS S3, the keyid is used to encrypt (aka "sign") the headers of
// requests. For CURL "digest" this is the password, encrypted by curl
// before transmission.
//
/// Set AWS account access key ID
/// \param keyid new AWS key ID
void aws_set_keyid ( char * const keyid ) {
aws_set_keyid_r(keyid, &default_ctx);
}
void aws_set_keyid_r ( char * const keyid, AWSContext* ctx ) {
if (ctx->awsKeyID)
free(ctx->awsKeyID);
ctx->awsKeyID = ((keyid == NULL) ? NULL : strdup(keyid));
}
/// Set reduced redundancy storage
/// \param r when non-zero causes puts to use RRS
void aws_set_rrs (int r) {
aws_set_rrs_r(r, &default_ctx);
}
void aws_set_rrs_r (int r, AWSContext* ctx) {
ctx->useRrs = r;
}
// Lines in ~/.awsAuth are of the form name:user:password
// where:
// name is any key to lookup user/password (e.g. UNIX moniker)
// user is a user-name known to the object-store
// pass is the password for user to access the object-store
//
// These are now used for both AWS S3 header-encryption, and curl "digest"
// mode.
//
/// Read AWS authentication records
/// \param id user ID
int aws_read_config ( char * const id ) {
return aws_read_config_r(id, &default_ctx);
}
int aws_read_config_r ( char * const id, AWSContext* ctx ) {
aws_set_id_r ( id, ctx );
aws_set_key_r ( NULL, ctx);
aws_set_keyid_r( NULL, ctx );
/// Open File
/// Make sure that file permissions are set right
__debug ( "Reading Config File ID[%s]", ctx->ID );
FILE* f = __aws_getcfg();
if ( f == NULL ) {
perror ("Error opening config file");
return -1;
}
/// Read Lines
char line[1024];
int ln = 0;
while ( !feof(f)) {
ln++;
memset (line,0,sizeof(line));
fgets ( line, sizeof(line), f );
/// Skip Comments
if ( line[0] == '#' ) continue;
if ( line[0] == 0 ) continue;
__chomp ( line );
/// Split the line on ':'
char * keyID = strchr(line,':');
if ( keyID == NULL ) {
printf ( "Syntax error in credentials file line %d, no keyid\n", ln );
fclose(f);
return -1;
}
*keyID = 0;
keyID ++;
char * key = strchr(keyID,':');
if ( key == NULL ) {
printf ( "Syntax error in credentials file line %d, no key\n", ln );
fclose(f);
return -1;
}
*key = 0;
key ++;
/// If the line is correct Set the IDs
if ( !strcmp(line, id)) {
aws_set_keyid_r ( keyID, ctx );
aws_set_key_r ( key, ctx );
break;
}
}
// always close the credentials file
fclose(f);
/// Return error if not found
if ( ctx->awsKeyID == NULL ) {
__debug("Didn't find user %s in config-file\n", id);
return -1;
}
return 0;
}
/*!
\}
*/
/*!
\defgroup s3 S3-related Configuration Functions
\{
*/
/// Set S3 host
void s3_set_host ( const char * const str ) {
s3_set_host_r(str, &default_ctx);
}
void s3_set_host_r ( const char * const str, AWSContext* ctx ) {
if (ctx->S3Host && str && !strcmp(str, ctx->S3Host))
return;
assert(!ctx->inside);
if (ctx->ch) {
curl_easy_cleanup(ctx->ch);
ctx->ch = NULL;
}
if (ctx->S3Host && !(ctx->flags & S3HOST_STATIC))
free(ctx->S3Host);
ctx->S3Host = ((str == NULL) ? NULL : strdup(str));
ctx->flags &= ~(S3HOST_STATIC);
}
/// Set S3 Proxy NOTE: libcurl allows separate specifications of proxy,
/// proxy_port, and proxy_type, but they aren't necesssary. You can put
/// them all into the proxy-name string (e.g. "socks5://xx.xx.xx:port".
/// Therefore, we only provide a way to set the proxy.
///
/// Set to NULL (the default), to stop using a proxy.
void s3_set_proxy ( const char * const str ) {
s3_set_proxy_r(str, &default_ctx);
}
void s3_set_proxy_r ( const char * const str, AWSContext* ctx ) {
if (ctx->S3Proxy && str && !strcmp(str, ctx->S3Proxy))
return;
assert(!ctx->inside);
if (ctx->ch) {
curl_easy_cleanup(ctx->ch);
ctx->ch = NULL;
}
if (ctx->S3Proxy && !(ctx->flags & S3PROXY_STATIC))
free(ctx->S3Proxy);
ctx->S3Proxy = ((str == NULL) ? NULL : strdup(str));
ctx->flags &= ~(S3PROXY_STATIC);
}
/// Select current S3 bucket
/// \param str bucket ID
void s3_set_bucket ( const char * const str ) {
s3_set_bucket_r(str, &default_ctx);
}
void s3_set_bucket_r ( const char * const str, AWSContext* ctx ) {
if (ctx->Bucket)
free(ctx->Bucket);
ctx->Bucket = ((str) ? strdup(str) : NULL);
}
/// Set S3 MimeType
void s3_set_mime ( const char * const str ) {
s3_set_mime_r(str, &default_ctx);
}
void s3_set_mime_r ( const char * const str, AWSContext* ctx ) {