-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathaws4c.c
1299 lines (1042 loc) · 32 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 <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.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
\{
*/
static int debug = 0; /// <flag to control debugging options
static int useRrs = 0; /// <Use reduced redundancy storage
static char * ID = NULL; /// <Current ID
static char * awsKeyID = NULL; /// <AWS Key ID
static char * awsKey = NULL; /// <AWS Key Material
static char * S3Host = "s3.amazonaws.com"; /// <AWS S3 host
/// \todo Use SQSHost in SQS functions
static char * SQSHost = "queue.amazonaws.com"; /// <AWS SQS host
static char * Bucket = NULL;
static char * MimeType = NULL;
static char * AccessControl = NULL;
static void __debug ( char *fmt, ... ) ;
static char * __aws_get_iso_date ();
static char * __aws_get_httpdate ();
static FILE * __aws_getcfg ();
static int s3_do_get ( IOBuf *b, char * const signature,
char * const date, char * const resource );
static int s3_do_put ( IOBuf *b, char * const signature,
char * const date, char * const resource );
static int s3_do_delete ( IOBuf *b, char * const signature,
char * const date, char * const resource );
static char* __aws_sign ( char * const str );
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
/// \param str string
static void __chomp ( char * str )
{
if ( str[0] == 0 ) return;
int ln = strlen(str);
ln--;
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
static size_t writefunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
__debug ( "DATA RCVD %d items of size %d ", nmemb, size );
aws_iobuf_append ( stream, ptr, nmemb*size );
return nmemb * size;
}
/// Suppress outputs to stdout
static size_t writedummyfunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
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
static size_t readfunc ( void * ptr, size_t size, size_t nmemb, void * stream )
{
char * Ln = ptr;
int sz = aws_iobuf_getline ( stream, ptr, size*nmemb);
__debug ( "Sent[%3d] %s", sz, Ln );
return sz;
}
/// Process incming 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
static size_t header ( void * ptr, size_t size, size_t nmemb, void * stream )
{
IOBuf * b = stream;
if (!strncmp ( ptr, "HTTP/1.1", 8 ))
{
b->result = strdup ( ptr + 9 );
__chomp(b->result);
b->code = atoi ( ptr + 9 );
}
else if ( !strncmp ( ptr, "ETag: ", 6 ))
{
b->eTag = strdup ( ptr + 6 );
__chomp(b->eTag);
}
else if ( !strncmp ( ptr, "Last-Modified: ", 14 ))
{
b->lastMod = strdup ( ptr + 15 );
__chomp(b->lastMod);
}
else if ( !strncmp ( ptr, "Content-Length: ", 15 ))
{
b->contentLen = atoi ( ptr + 16 );
}
return nmemb * size;
}
/// Get Data for authentication of SQS request
/// \return date in ISO format
static char * __aws_get_iso_date ()
{
static char dTa[256];
time_t t = time(NULL);
struct tm * gTime = gmtime ( & t );
memset ( dTa, 0 , sizeof(dTa));
strftime ( dTa, sizeof(dTa), "%FT%H:%M:%SZ", gTime );
__debug ( "Request Time: %s", dTa );
return dTa;
}
#ifdef ENABLE_DUMP
/// Dump current state
/// \internal
static void Dump ()
{
printf ( "----------------------------------------\n");
printf ( "ID : %-40s \n", ID );
printf ( "KeyID : %-40s \n", awsKeyID );
printf ( "Key : %-40s \n", awsKey );
printf ( "S3 Host : %-40s \n", S3Host );
printf ( "SQS Host : %-40s \n", SQSHost );
printf ( "Bucket : %-40s \n", 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 );
}
/// Get Request Date
/// \internal
/// \return date in HTTP format
static char * __aws_get_httpdate ()
{
static char dTa[256];
time_t t = time(NULL);
struct tm * gTime = gmtime ( & t );
memset ( dTa, 0 , sizeof(dTa));
strftime ( dTa, sizeof(dTa), "%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];
/// Compose FileName and check
snprintf ( ConfigFile, sizeof(ConfigFile) - 3, "%s/.awsAuth",
getenv("HOME"));
__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 != getuid () )
{
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 resoruce buffer
/// \param date -- HTTP date
/// \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
static char * GetStringToSign ( char * resource, int resSize,
char ** date,
char * const method,
char * const bucket,
char * const file )
{
char reqToSign[2048];
char acl[32];
char rrs[64];
/// \todo Change the way RRS is handled. Need to pass it in
* date = __aws_get_httpdate();
memset ( resource,0,resSize);
if ( bucket != NULL )
snprintf ( resource, resSize,"%s/%s", bucket, file );
else
snprintf ( resource, resSize,"%s", file );
if (AccessControl)
snprintf( acl, sizeof(acl), "x-amz-acl:%s\n", AccessControl);
else
acl[0] = 0;
if (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",
method,
MimeType ? MimeType : "",
*date,
acl,
rrs,
resource );
// EU: If bucket is in virtual host name, remove bucket from path
if (bucket && strncmp(S3Host, bucket, strlen(bucket)) == 0)
snprintf ( resource, resSize,"%s", file );
return __aws_sign(reqToSign);
}
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 );
}
static int SQSRequest ( IOBuf *b, char * verb, char * const url )
{
CURL* ch = curl_easy_init( );
struct curl_slist *slist=NULL;
curl_easy_setopt ( ch, CURLOPT_URL, url );
curl_easy_setopt ( ch, CURLOPT_HEADERDATA, b );
curl_easy_setopt ( ch, CURLOPT_VERBOSE, debug );
curl_easy_setopt ( ch, CURLOPT_INFILESIZE, b->len );
curl_easy_setopt ( ch, CURLOPT_POST, 1 );
curl_easy_setopt ( ch, CURLOPT_POSTFIELDSIZE , 0 );
curl_easy_setopt ( ch, CURLOPT_HEADERFUNCTION, header );
curl_easy_setopt ( ch, CURLOPT_WRITEFUNCTION, writefunc );
curl_easy_setopt ( ch, CURLOPT_WRITEDATA, b );
curl_easy_setopt ( ch, CURLOPT_READFUNCTION, readfunc );
curl_easy_setopt ( ch, CURLOPT_READDATA, b );
int sc = curl_easy_perform(ch);
/** \todo check the return code */
__debug ( "Return Code: %d ", sc );
curl_slist_free_all(slist);
return sc;
}
static char * SQSSign ( char * str )
{
char RealSign[1024];
char * signature = __aws_sign(str);
__aws_urlencode ( signature, RealSign, sizeof(RealSign));
free ( signature );
return strdup(RealSign);
}
/*!
\}
*/
/*!
\defgroup conf Configuration Functions
\{
*/
/// Initialize the library
void aws_init () { curl_global_init (CURL_GLOBAL_ALL); }
/// Set debuging output
/// \param d when non-zero causes debugging output to be printed
void aws_set_debug (int d)
{
debug = d;
}
/// \brief Set AWS account ID to be read from .awsAuth file
/// \param id new account ID
void aws_set_id ( char * const id )
{ ID = id == NULL ? NULL : strdup(id); }
/// Set AWS account access key
/// \param key new AWS authentication key
void aws_set_key ( char * const key )
{ awsKey = key == NULL ? NULL : strdup(key); }
/// Set AWS account access key ID
/// \param keyid new AWS key ID
void aws_set_keyid ( char * const keyid )
{ 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)
{ useRrs = r; }
/// Read AWS authentication records
/// \param id user ID
int aws_read_config ( char * const id )
{
aws_set_id ( id );
aws_set_keyid ( NULL );
aws_set_key ( NULL );
/// Open File
/// Make sure that file permissions are set right
__debug ( "Reading Config File ID[%s]", ID );
FILE * f = __aws_getcfg();
if ( f == NULL ) { perror ("Error opening config file"); exit(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 );
exit(1);
}
*keyID = 0; keyID ++;
char * key = strchr(keyID,':');
if ( key == NULL )
{ printf ( "Syntax error in credentials file line %d, no key\n", ln );
exit(1);
}
*key = 0; key ++;
/// If the line is correct Set the IDs
if ( !strcmp(line,id))
{
aws_set_keyid ( keyID );
aws_set_key ( key );
break;
}
}
/// Return error if not found
if ( awsKeyID == NULL ) return -1;
return 0;
}
/*!
\}
*/
/*!
\defgroup s3 S3 Interface Functions
\{
*/
/// Select current S3 bucket
/// \param str bucket ID
void s3_set_bucket ( char * const str )
{ Bucket = str == NULL ? NULL : strdup(str); }
/// Set S3 host
void s3_set_host ( char * const str )
{ S3Host = str == NULL ? NULL : strdup(str); }
/// Set S3 MimeType
void s3_set_mime ( char * const str )
{ MimeType = str ? strdup(str) : NULL; }
/// Set S3 AccessControl
void s3_set_acl ( char * const str )
{ AccessControl = str ? strdup(str) : NULL; }
/// Upload the file into currently selected bucket
/// \param b I/O buffer
/// \param file filename
int s3_put ( IOBuf * b, char * const file )
{
char * const method = "PUT";
char resource [1024];
char * date = NULL;
char * signature = GetStringToSign ( resource, sizeof(resource),
&date, method, Bucket, file );
int sc = s3_do_put( b, signature, date, resource );
free ( signature );
return sc;
}
/// Download the file from the current bucket
/// \param b I/O buffer
/// \param file filename
int s3_get ( IOBuf * b, char * const file )
{
char * const method = "GET";
char resource [1024];
char * date = NULL;
char * signature = GetStringToSign ( resource, sizeof(resource),
&date, method, Bucket, file );
int sc = s3_do_get( b, signature, date, resource );
free ( signature );
return sc;
}
/// Delete the file from the currently selected bucket
/// \param file filename
int s3_delete ( IOBuf * b, char * const file )
{
char * const method = "DELETE";
char resource [1024];
char * date = NULL;
char * signature = GetStringToSign ( resource, sizeof(resource),
&date, method, Bucket, file );
int sc = s3_do_delete( b, signature, date, resource );
free ( signature );
return sc;
}
static int s3_do_put ( IOBuf *b, char * const signature,
char * const date, char * const resource )
{
char Buf[1024];
CURL* ch = curl_easy_init( );
struct curl_slist *slist=NULL;
if (MimeType) {
snprintf ( Buf, sizeof(Buf), "Content-Type: %s", MimeType );
slist = curl_slist_append(slist, Buf );
}
if (AccessControl) {
snprintf ( Buf, sizeof(Buf), "x-amz-acl: %s", AccessControl );
slist = curl_slist_append(slist, Buf );
}
if (useRrs) {
strncpy ( Buf, "x-amz-storage-class: REDUCED_REDUNDANCY", sizeof(Buf) );
slist = curl_slist_append(slist, Buf ); }
snprintf ( Buf, sizeof(Buf), "Date: %s", date );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "Authorization: AWS %s:%s", awsKeyID, signature );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "http://%s/%s", S3Host , resource );
curl_easy_setopt ( ch, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt ( ch, CURLOPT_URL, Buf );
curl_easy_setopt ( ch, CURLOPT_READDATA, b );
if (!debug)
curl_easy_setopt ( ch, CURLOPT_WRITEFUNCTION, writedummyfunc );
curl_easy_setopt ( ch, CURLOPT_READFUNCTION, readfunc );
curl_easy_setopt ( ch, CURLOPT_HEADERFUNCTION, header );
curl_easy_setopt ( ch, CURLOPT_HEADERDATA, b );
curl_easy_setopt ( ch, CURLOPT_VERBOSE, debug );
curl_easy_setopt ( ch, CURLOPT_UPLOAD, 1 );
curl_easy_setopt ( ch, CURLOPT_INFILESIZE, b->len );
curl_easy_setopt ( ch, CURLOPT_FOLLOWLOCATION, 1 );
int sc = curl_easy_perform(ch);
/** \todo check the return code */
__debug ( "Return Code: %d ", sc );
curl_slist_free_all(slist);
curl_easy_cleanup(ch);
return sc;
}
static int s3_do_get ( IOBuf *b, char * const signature,
char * const date, char * const resource )
{
char Buf[1024];
CURL* ch = curl_easy_init( );
struct curl_slist *slist=NULL;
slist = curl_slist_append(slist, "If-Modified-Since: Tue, 26 May 2009 18:58:55 GMT" );
slist = curl_slist_append(slist, "ETag: \"6ea58533db38eca2c2cc204b7550aab6\"");
snprintf ( Buf, sizeof(Buf), "Date: %s", date );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "Authorization: AWS %s:%s", awsKeyID, signature );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "http://%s/%s", S3Host, resource );
curl_easy_setopt ( ch, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt ( ch, CURLOPT_URL, Buf );
curl_easy_setopt ( ch, CURLOPT_WRITEFUNCTION, writefunc );
curl_easy_setopt ( ch, CURLOPT_WRITEDATA, b );
curl_easy_setopt ( ch, CURLOPT_HEADERFUNCTION, header );
curl_easy_setopt ( ch, CURLOPT_HEADERDATA, b );
curl_easy_setopt ( ch, CURLOPT_VERBOSE, debug );
int sc = curl_easy_perform(ch);
/** \todo check the return code */
__debug ( "Return Code: %d ", sc );
curl_slist_free_all(slist);
curl_easy_cleanup(ch);
return sc;
}
static int s3_do_delete ( IOBuf *b, char * const signature,
char * const date, char * const resource )
{
char Buf[1024];
CURL* ch = curl_easy_init( );
struct curl_slist *slist=NULL;
snprintf ( Buf, sizeof(Buf), "Date: %s", date );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "Authorization: AWS %s:%s", awsKeyID, signature );
slist = curl_slist_append(slist, Buf );
snprintf ( Buf, sizeof(Buf), "http://%s/%s", S3Host, resource );
curl_easy_setopt ( ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt ( ch, CURLOPT_HTTPHEADER, slist);
curl_easy_setopt ( ch, CURLOPT_URL, Buf );
curl_easy_setopt ( ch, CURLOPT_HEADERFUNCTION, header );
curl_easy_setopt ( ch, CURLOPT_HEADERDATA, b );
curl_easy_setopt ( ch, CURLOPT_VERBOSE, debug );
int sc = curl_easy_perform(ch);
/** \todo check the return code */
__debug ( "Return Code: %d ", sc );
curl_slist_free_all(slist);
curl_easy_cleanup(ch);
return sc;
}
static char* __aws_sign ( char * const str )
{
HMAC_CTX ctx;
unsigned char MD[256];
unsigned len;
__debug("StrToSign:%s", str );
HMAC_CTX_init(&ctx);
HMAC_Init(&ctx, awsKey, strlen(awsKey), EVP_sha1());
HMAC_Update(&ctx,(unsigned char*)str, strlen(str));
HMAC_Final(&ctx,(unsigned char*)MD,&len);
HMAC_CTX_cleanup(&ctx);
char * b64 = __b64_encode (MD,len);
__debug("Signature: %s", b64 );
return b64;
}
/*!
\}
*/
#define SQS_REQ_TAIL "&Signature=%s" "&SignatureVersion=1" "&Timestamp=%s" "&Version=2009-02-01"
/*!
\defgroup sqs SQS Interface Functions
\{
*/
/// Create SQS queue
/// \param b I/O buffer
/// \param name queue name
/// \return on success return 0, otherwise error code
int sqs_create_queue ( IOBuf *b, char * const name )
{
__debug ( "Creating Que: %s\n", name );
char resource [1024];
char customSign [1024];
char * date = NULL;
char * signature = NULL;
char * Req =
"http://%s/"
"?Action=CreateQueue"
"&QueueName=%s"
"&AWSAccessKeyId=%s"
SQS_REQ_TAIL ;
char * Sign = "ActionCreateQueue"
"AWSAccessKeyId%s"
"QueueName%s"
"SignatureVersion2"
"Timestamp%sVersion2009-02-01";
date = __aws_get_iso_date ();
snprintf ( customSign, sizeof(customSign), Sign, awsKeyID, name, date );
signature = SQSSign ( customSign );
snprintf ( resource, sizeof(resource), SQSHost, Req , name, awsKeyID, signature, date );
int sc = SQSRequest( b, "POST", resource );
free ( signature );
return sc;
}
/// Retrieve URL of the queue
/// \param b I/O buffer
/// \param prefix queue prefix. better use the whole name
/// \return on success return 0, otherwise error code
///
/// URL is placed into the I/O buffer. User get_line to retrieve it
int sqs_list_queues ( IOBuf *b, char * const prefix )
{
__debug ( "Listing Queues PFX: %s\n", prefix );
char resource [1024];
char customSign [1024];
char * date = NULL;
char * signature = NULL;
char * Req =
"http://%s/"
"?Action=ListQueues"
"&QueueNamePrefix=%s"
"&AWSAccessKeyId=%s"
SQS_REQ_TAIL ;
char * Sign = "ActionListQueues"
"AWSAccessKeyId%s"
"QueueNamePrefix%s"
"SignatureVersion1"
"Timestamp%sVersion2009-02-01";
date = __aws_get_iso_date ();
snprintf ( customSign, sizeof(customSign), Sign, awsKeyID, prefix, date );
signature = SQSSign ( customSign );
snprintf ( resource, sizeof(resource), Req , SQSHost , prefix, awsKeyID,
signature, date );
IOBuf *nb = aws_iobuf_new();
int sc = SQSRequest( nb, "POST", resource );
free ( signature );
if ( nb->result != NULL )
b-> result = strdup(nb->result);
b-> code = nb->code;
/// \todo This only retrieves just one line in the string..
/// make that all URLs are returned
if ( b->code == 200 )
{
/// Parse Out the List Of Queues
while(-1)
{
char Ln[1024];
aws_iobuf_getline ( nb, Ln, sizeof(Ln));
if ( Ln[0] == 0 ) break;
char *q = strstr ( Ln, "<QueueUrl>" );
if ( q != 0 )
{
q += 10;
char * end = NULL;
end = strstr ( q, "</QueueUrl>" );
if ( *end != 0 )
{
* end = 0;
aws_iobuf_append ( b, q, strlen(q ));
aws_iobuf_append ( b, "\n", 1 );
}
}
}
}
aws_iobuf_free ( nb );
return sc;
}
/// Retrieve queue attributes
/// \param b I/O buffer
/// \param url queue url. Use sqs_list_queues to retrieve
/// \param timeOut queue visibility timeout
/// \param nMesg approximate number of messages in the queue
/// \return on success return 0, otherwise error code
int sqs_get_queueattributes ( IOBuf *b, char * url, int *timeOut, int *nMesg )
{
__debug ( "Getting Que Attributes\n" );
char resource [1024];
char customSign [1024];
char * date = NULL;
char * signature = NULL;
char * Req =
"%s/"
"?Action=GetQueueAttributes"
"&AttributeName.1=VisibilityTimeout"
"&AttributeName.2=ApproximateNumberOfMessages"
"&AWSAccessKeyId=%s"
SQS_REQ_TAIL ;
char * Sign =
"ActionGetQueueAttributes"
"AttributeName.1VisibilityTimeout"
"AttributeName.2ApproximateNumberOfMessages"
"AWSAccessKeyId%s"
"SignatureVersion1"
"Timestamp%s"
"Version2009-02-01";
date = __aws_get_iso_date ();
snprintf ( customSign, sizeof(customSign), Sign, awsKeyID, date );
signature = SQSSign ( customSign );
snprintf ( resource, sizeof(resource), Req , url, awsKeyID, signature, date );
const char *pfxVisTO = "<Name>VisibilityTimeout</Name><Value>";
const char *pfxQLen = "<Name>ApproximateNumberOfMessages</Name><Value>";
int sc = SQSRequest( b, "POST", resource );
while(-1)
{
char Ln[1024];
aws_iobuf_getline ( b, Ln, sizeof(Ln));
if ( Ln[0] == 0 ) break;
char *q;
q = strstr ( Ln, pfxVisTO );
if ( q != 0 ) { *timeOut = atoi(q+strlen(pfxVisTO)); }
q = strstr ( Ln, pfxQLen );
if ( q != 0 ) { *nMesg = atoi(q+strlen(pfxQLen)); }
}
free ( signature );
return sc;
}
/// Set queue visibility timeout
/// \param b I/O buffer
/// \param url queue url. Use sqs_list_queues to retrieve
/// \param sec queue visibility timeout
/// \return on success return 0, otherwise error code
int sqs_set_queuevisibilitytimeout ( IOBuf *b, char * url, int sec )
{
__debug ( "Setting Visibility Timeout : %d\n", sec );
char resource [1024];
char customSign [1024];
char * date = NULL;
char * signature = NULL;
char * Req =
"%s/"
"?Action=SetQueueAttributes"
"&Attribute.1.Name=VisibilityTimeout"
"&Attribute.1.Value=%d"
"&AWSAccessKeyId=%s"
SQS_REQ_TAIL ;
char * Sign =
"ActionSetQueueAttributes"
"Attribute.1.NameVisibilityTimeout"
"Attribute.1.Value%d"
"AWSAccessKeyId%s"
"SignatureVersion1"
"Timestamp%s"
"Version2009-02-01";
date = __aws_get_iso_date ();
snprintf ( customSign, sizeof(customSign), Sign, sec, awsKeyID, date );
signature = SQSSign ( customSign );
snprintf ( resource, sizeof(resource), Req ,
url, sec, awsKeyID, signature, date );