-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_io.c
2672 lines (2327 loc) · 92.4 KB
/
http_io.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
/*
* s3backer - FUSE-based single file backing store via Amazon S3
*
* Copyright 2008-2011 Archie L. Cobbs <archie@dellroad.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* $Id$
*/
#include "s3backer.h"
#include "block_part.h"
#include "http_io.h"
/* HTTP definitions */
#define HTTP_GET "GET"
#define HTTP_PUT "PUT"
#define HTTP_DELETE "DELETE"
#define HTTP_HEAD "HEAD"
#define HTTP_NOT_MODIFIED 304
#define HTTP_UNAUTHORIZED 401
#define HTTP_FORBIDDEN 403
#define HTTP_NOT_FOUND 404
#define HTTP_PRECONDITION_FAILED 412
#define AUTH_HEADER "Authorization"
#define CTYPE_HEADER "Content-Type"
#define CONTENT_ENCODING_HEADER "Content-Encoding"
#define ETAG_HEADER "ETag"
#define CONTENT_ENCODING_DEFLATE "deflate"
#define CONTENT_ENCODING_ENCRYPT "encrypt"
#define MD5_HEADER "Content-MD5"
#define ACL_HEADER "x-amz-acl"
#define CONTENT_SHA256_HEADER "x-amz-content-sha256"
#define STORAGE_CLASS_HEADER "x-amz-storage-class"
#define SCLASS_STANDARD "STANDARD"
#define SCLASS_REDUCED_REDUNDANCY "REDUCED_REDUNDANCY"
#define FILE_SIZE_HEADER "x-amz-meta-s3backer-filesize"
#define BLOCK_SIZE_HEADER "x-amz-meta-s3backer-blocksize"
#define HMAC_HEADER "x-amz-meta-s3backer-hmac"
#define IF_MATCH_HEADER "If-Match"
#define IF_NONE_MATCH_HEADER "If-None-Match"
/* MIME type for blocks */
#define CONTENT_TYPE "application/x-s3backer-block"
/* MIME type for mounted flag */
#define MOUNTED_FLAG_CONTENT_TYPE "text/plain"
/* Mounted file object name */
#define MOUNTED_FLAG "s3backer-mounted"
/* HTTP `Date' and `x-amz-date' header formats */
#define HTTP_DATE_HEADER "Date"
#define AWS_DATE_HEADER "x-amz-date"
#define HTTP_DATE_BUF_FMT "%a, %d %b %Y %H:%M:%S GMT"
#define AWS_DATE_BUF_FMT "%Y%m%dT%H%M%SZ"
#define DATE_BUF_SIZE 64
/* Size required for URL buffer */
#define URL_BUF_SIZE(config) (strlen((config)->baseURL) + strlen((config)->bucket) \
+ strlen((config)->prefix) + S3B_BLOCK_NUM_DIGITS + 2)
/* Bucket listing API constants */
#define LIST_PARAM_MARKER "marker"
#define LIST_PARAM_PREFIX "prefix"
#define LIST_PARAM_MAX_KEYS "max-keys"
#define LIST_ELEM_LIST_BUCKET_RESLT "ListBucketResult"
#define LIST_ELEM_IS_TRUNCATED "IsTruncated"
#define LIST_ELEM_CONTENTS "Contents"
#define LIST_ELEM_KEY "Key"
#define LIST_TRUE "true"
#define LIST_MAX_PATH (sizeof(LIST_ELEM_LIST_BUCKET_RESLT) \
+ sizeof(LIST_ELEM_CONTENTS) \
+ sizeof(LIST_ELEM_KEY) + 1)
/* How many blocks to list at a time */
#define LIST_BLOCKS_CHUNK 0x100
/* PBKDF2 key generation iterations */
#define PBKDF2_ITERATIONS 5000
/* Enable to debug encryption key stuff */
#define DEBUG_ENCRYPTION 0
/* Enable to debug authentication stuff */
#define DEBUG_AUTHENTICATION 0
/* Version 4 authentication stuff */
#define SIGNATURE_ALGORITHM "AWS4-HMAC-SHA256"
#define ACCESS_KEY_PREFIX "AWS4"
#define S3_SERVICE_NAME "s3"
#define SIGNATURE_TERMINATOR "aws4_request"
#define SECURITY_TOKEN_HEADER "x-amz-security-token"
/* EC2 IAM info URL */
#define EC2_IAM_META_DATA_URLBASE "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
#define EC2_IAM_META_DATA_ACCESSID "AccessKeyId"
#define EC2_IAM_META_DATA_ACCESSKEY "SecretAccessKey"
#define EC2_IAM_META_DATA_TOKEN "Token"
/* Misc */
#define WHITESPACE " \t\v\f\r\n"
/*
* HTTP-based implementation of s3backer_store.
*
* This implementation does no caching or consistency checking.
*/
/* Internal definitions */
struct curl_holder {
CURL *curl;
LIST_ENTRY(curl_holder) link;
};
/* Internal state */
struct http_io_private {
struct http_io_conf *config;
struct http_io_stats stats;
LIST_HEAD(, curl_holder) curls;
pthread_mutex_t mutex;
u_int *non_zero; // config->nonzero_bitmap is moved to here
pthread_t iam_thread; // IAM credentials refresh thread
u_char shutting_down;
/* Encryption info */
const EVP_CIPHER *cipher;
u_int keylen; // length of key and ivkey
u_char key[EVP_MAX_KEY_LENGTH]; // key used to encrypt data
u_char ivkey[EVP_MAX_KEY_LENGTH]; // key used to encrypt block number to get IV for data
};
/* I/O buffers */
struct http_io_bufs {
size_t rdremain;
size_t wrremain;
char *rddata;
const char *wrdata;
};
/* I/O state when reading/writing a block */
struct http_io {
// I/O buffers
struct http_io_bufs bufs;
// XML parser and bucket listing info
XML_Parser xml; // XML parser
int xml_error; // XML parse error (if any)
int xml_error_line; // XML parse error line
int xml_error_column; // XML parse error column
char *xml_path; // Current XML path
char *xml_text; // Current XML text
int xml_text_len; // # chars in 'xml_text' buffer
int xml_text_max; // max chars in 'xml_text' buffer
int list_truncated; // returned list was truncated
s3b_block_t last_block; // last dirty block listed
block_list_func_t *callback_func; // callback func for listing blocks
void *callback_arg; // callback arg for listing blocks
struct http_io_conf *config; // configuration
// Other info that needs to be passed around
const char *method; // HTTP method
const char *url; // HTTP URL
struct curl_slist *headers; // HTTP headers
void *dest; // Block data (when reading)
const void *src; // Block data (when writing)
s3b_block_t block_num; // The block we're reading/writing
u_int buf_size; // Size of data buffer
u_int *content_lengthp; // Returned Content-Length
uintmax_t file_size; // file size from "x-amz-meta-s3backer-filesize"
u_int block_size; // block size from "x-amz-meta-s3backer-blocksize"
u_int expect_304; // a verify request; expect a 304 response
u_char md5[MD5_DIGEST_LENGTH]; // parsed ETag header
u_char hmac[SHA_DIGEST_LENGTH];// parsed "x-amz-meta-s3backer-hmac" header
char content_encoding[32]; // received content encoding
check_cancel_t *check_cancel; // write check-for-cancel callback
void *check_cancel_arg; // write check-for-cancel callback argument
};
/* CURL prepper function type */
typedef void http_io_curl_prepper_t(CURL *curl, struct http_io *io);
/* s3backer_store functions */
static int http_io_meta_data(struct s3backer_store *s3b, off_t *file_sizep, u_int *block_sizep);
static int http_io_set_mounted(struct s3backer_store *s3b, int *old_valuep, int new_value);
static int http_io_read_block(struct s3backer_store *s3b, s3b_block_t block_num, void *dest,
u_char *actual_md5, const u_char *expect_md5, int strict);
static int http_io_write_block(struct s3backer_store *s3b, s3b_block_t block_num, const void *src, u_char *md5,
check_cancel_t *check_cancel, void *check_cancel_arg);
static int http_io_read_block_part(struct s3backer_store *s3b, s3b_block_t block_num, u_int off, u_int len, void *dest);
static int http_io_write_block_part(struct s3backer_store *s3b, s3b_block_t block_num, u_int off, u_int len, const void *src);
static int http_io_list_blocks(struct s3backer_store *s3b, block_list_func_t *callback, void *arg);
static int http_io_flush(struct s3backer_store *s3b);
static void http_io_destroy(struct s3backer_store *s3b);
/* Other functions */
static http_io_curl_prepper_t http_io_head_prepper;
static http_io_curl_prepper_t http_io_read_prepper;
static http_io_curl_prepper_t http_io_write_prepper;
static http_io_curl_prepper_t http_io_list_prepper;
static http_io_curl_prepper_t http_io_iamcreds_prepper;
/* S3 REST API functions */
static void http_io_get_block_url(char *buf, size_t bufsiz, struct http_io_conf *config, s3b_block_t block_num);
static void http_io_get_mounted_flag_url(char *buf, size_t bufsiz, struct http_io_conf *config);
static int http_io_add_auth(struct http_io_private *priv, struct http_io *io, time_t now, const void *payload, size_t plen);
static int http_io_add_auth2(struct http_io_private *priv, struct http_io *io, time_t now, const void *payload, size_t plen);
static int http_io_add_auth4(struct http_io_private *priv, struct http_io *io, time_t now, const void *payload, size_t plen);
/* EC2 IAM thread */
static void *update_iam_credentials_main(void *arg);
static int update_iam_credentials(struct http_io_private *priv);
static char *parse_json_field(struct http_io_private *priv, const char *json, const char *field);
/* Bucket listing functions */
static size_t http_io_curl_list_reader(const void *ptr, size_t size, size_t nmemb, void *stream);
static void http_io_list_elem_start(void *arg, const XML_Char *name, const XML_Char **atts);
static void http_io_list_elem_end(void *arg, const XML_Char *name);
static void http_io_list_text(void *arg, const XML_Char *s, int len);
/* HTTP and curl functions */
static int http_io_perform_io(struct http_io_private *priv, struct http_io *io, http_io_curl_prepper_t *prepper);
static size_t http_io_curl_reader(const void *ptr, size_t size, size_t nmemb, void *stream);
static size_t http_io_curl_writer(void *ptr, size_t size, size_t nmemb, void *stream);
static size_t http_io_curl_header(void *ptr, size_t size, size_t nmemb, void *stream);
static struct curl_slist *http_io_add_header(struct curl_slist *headers, const char *fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
static void http_io_add_date(struct http_io_private *priv, struct http_io *const io, time_t now);
static CURL *http_io_acquire_curl(struct http_io_private *priv, struct http_io *io);
static void http_io_release_curl(struct http_io_private *priv, CURL **curlp, int may_cache);
/* Misc */
static void http_io_openssl_locker(int mode, int i, const char *file, int line);
static u_long http_io_openssl_ider(void);
static void http_io_base64_encode(char *buf, size_t bufsiz, const void *data, size_t len);
static u_int http_io_crypt(struct http_io_private *priv, s3b_block_t block_num, int enc, const u_char *src, u_int len, u_char *dst);
static void http_io_authsig(struct http_io_private *priv, s3b_block_t block_num, const u_char *src, u_int len, u_char *hmac);
static void update_hmac_from_header(HMAC_CTX *ctx, struct http_io *io,
const char *name, int value_only, char *sigbuf, size_t sigbuflen);
static int http_io_is_zero_block(const void *data, u_int block_size);
static int http_io_parse_hex(const char *str, u_char *buf, u_int nbytes);
static void http_io_prhex(char *buf, const u_char *data, size_t len);
static int http_io_strcasecmp_ptr(const void *ptr1, const void *ptr2);
/* Internal variables */
static pthread_mutex_t *openssl_locks;
static int num_openssl_locks;
static u_char zero_md5[MD5_DIGEST_LENGTH];
static u_char zero_hmac[SHA_DIGEST_LENGTH];
/*
* Constructor
*
* On error, returns NULL and sets `errno'.
*/
struct s3backer_store *
http_io_create(struct http_io_conf *config)
{
struct s3backer_store *s3b;
struct http_io_private *priv;
struct curl_holder *holder;
int nlocks;
int r;
/* Sanity check: we can really only handle one instance */
if (openssl_locks != NULL) {
(*config->log)(LOG_ERR, "http_io_create() called twice");
r = EALREADY;
goto fail0;
}
/* Initialize structures */
if ((s3b = calloc(1, sizeof(*s3b))) == NULL) {
r = errno;
goto fail0;
}
s3b->meta_data = http_io_meta_data;
s3b->set_mounted = http_io_set_mounted;
s3b->read_block = http_io_read_block;
s3b->write_block = http_io_write_block;
s3b->read_block_part = http_io_read_block_part;
s3b->write_block_part = http_io_write_block_part;
s3b->list_blocks = http_io_list_blocks;
s3b->flush = http_io_flush;
s3b->destroy = http_io_destroy;
if ((priv = calloc(1, sizeof(*priv))) == NULL) {
r = errno;
goto fail1;
}
priv->config = config;
if ((r = pthread_mutex_init(&priv->mutex, NULL)) != 0)
goto fail2;
LIST_INIT(&priv->curls);
s3b->data = priv;
/* Initialize openssl */
num_openssl_locks = CRYPTO_num_locks();
if ((openssl_locks = malloc(num_openssl_locks * sizeof(*openssl_locks))) == NULL) {
r = errno;
goto fail3;
}
for (nlocks = 0; nlocks < num_openssl_locks; nlocks++) {
if ((r = pthread_mutex_init(&openssl_locks[nlocks], NULL)) != 0)
goto fail4;
}
CRYPTO_set_locking_callback(http_io_openssl_locker);
CRYPTO_set_id_callback(http_io_openssl_ider);
/* Initialize encryption */
if (config->encryption != NULL) {
char saltbuf[strlen(config->bucket) + 1 + strlen(config->prefix) + 1];
u_int cipher_key_len;
/* Sanity checks */
assert(config->password != NULL);
assert(config->block_size % EVP_MAX_IV_LENGTH == 0);
/* Find encryption algorithm */
OpenSSL_add_all_ciphers();
if ((priv->cipher = EVP_get_cipherbyname(config->encryption)) == NULL) {
(*config->log)(LOG_ERR, "unknown encryption cipher `%s'", config->encryption);
r = EINVAL;
goto fail4;
}
if (EVP_CIPHER_block_size(priv->cipher) != EVP_CIPHER_iv_length(priv->cipher)) {
(*config->log)(LOG_ERR, "invalid encryption cipher `%s': block size %d != IV length %d",
config->encryption, EVP_CIPHER_block_size(priv->cipher), EVP_CIPHER_iv_length(priv->cipher));
r = EINVAL;
goto fail4;
}
cipher_key_len = EVP_CIPHER_key_length(priv->cipher);
priv->keylen = config->key_length > 0 ? config->key_length : cipher_key_len;
if (priv->keylen < cipher_key_len || priv->keylen > sizeof(priv->key)) {
(*config->log)(LOG_ERR, "key length %u for cipher `%s' is out of range", priv->keylen, config->encryption);
r = EINVAL;
goto fail4;
}
/* Hash password to get bulk data encryption key */
snprintf(saltbuf, sizeof(saltbuf), "%s/%s", config->bucket, config->prefix);
if ((r = PKCS5_PBKDF2_HMAC_SHA1(config->password, strlen(config->password),
(u_char *)saltbuf, strlen(saltbuf), PBKDF2_ITERATIONS, priv->keylen, priv->key)) != 1) {
(*config->log)(LOG_ERR, "failed to create encryption key");
r = EINVAL;
goto fail4;
}
/* Hash the bulk encryption key to get the IV encryption key */
if ((r = PKCS5_PBKDF2_HMAC_SHA1((char *)priv->key, priv->keylen,
priv->key, priv->keylen, PBKDF2_ITERATIONS, priv->keylen, priv->ivkey)) != 1) {
(*config->log)(LOG_ERR, "failed to create encryption key");
r = EINVAL;
goto fail4;
}
/* Encryption debug */
#if DEBUG_ENCRYPTION
{
char keybuf[priv->keylen * 2 + 1];
char ivkeybuf[priv->keylen * 2 + 1];
http_io_prhex(keybuf, priv->key, priv->keylen);
http_io_prhex(ivkeybuf, priv->ivkey, priv->keylen);
(*config->log)(LOG_DEBUG, "ENCRYPTION INIT: cipher=\"%s\" pass=\"%s\" salt=\"%s\" key=0x%s ivkey=0x%s", config->encryption, config->password, saltbuf, keybuf, ivkeybuf);
}
#endif
}
/* Initialize cURL */
curl_global_init(CURL_GLOBAL_ALL);
/* Initialize IAM credentials and start updater thread */
if (config->ec2iam_role != NULL) {
if ((r = update_iam_credentials(priv)) != 0)
goto fail5;
if ((r = pthread_create(&priv->iam_thread, NULL, update_iam_credentials_main, priv)) != 0)
goto fail5;
}
/* Take ownership of non-zero block bitmap */
priv->non_zero = config->nonzero_bitmap;
config->nonzero_bitmap = NULL;
/* Done */
return s3b;
fail5:
while ((holder = LIST_FIRST(&priv->curls)) != NULL) {
curl_easy_cleanup(holder->curl);
LIST_REMOVE(holder, link);
free(holder);
}
curl_global_cleanup();
fail4:
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_id_callback(NULL);
while (nlocks > 0)
pthread_mutex_destroy(&openssl_locks[--nlocks]);
free(openssl_locks);
openssl_locks = NULL;
num_openssl_locks = 0;
fail3:
pthread_mutex_destroy(&priv->mutex);
fail2:
free(priv);
fail1:
free(s3b);
fail0:
(*config->log)(LOG_ERR, "http_io creation failed: %s", strerror(r));
errno = r;
return NULL;
}
/*
* Destructor
*/
static void
http_io_destroy(struct s3backer_store *const s3b)
{
struct http_io_private *const priv = s3b->data;
struct http_io_conf *const config = priv->config;
struct curl_holder *holder;
int r;
/* Shut down IAM thread */
priv->shutting_down = 1;
if (config->ec2iam_role != NULL) {
(*config->log)(LOG_DEBUG, "waiting for EC2 IAM thread to shutdown");
if ((r = pthread_cancel(priv->iam_thread)) != 0)
(*config->log)(LOG_ERR, "pthread_cancel: %s", strerror(r));
if ((r = pthread_join(priv->iam_thread, NULL)) != 0)
(*config->log)(LOG_ERR, "pthread_join: %s", strerror(r));
else
(*config->log)(LOG_DEBUG, "EC2 IAM thread successfully shutdown");
}
/* Clean up openssl */
while (num_openssl_locks > 0)
pthread_mutex_destroy(&openssl_locks[--num_openssl_locks]);
free(openssl_locks);
openssl_locks = NULL;
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_id_callback(NULL);
/* Clean up cURL */
while ((holder = LIST_FIRST(&priv->curls)) != NULL) {
curl_easy_cleanup(holder->curl);
LIST_REMOVE(holder, link);
free(holder);
}
curl_global_cleanup();
/* Free structures */
pthread_mutex_destroy(&priv->mutex);
free(priv->non_zero);
free(priv);
free(s3b);
}
static int
http_io_flush(struct s3backer_store *const s3b)
{
return 0;
}
void
http_io_get_stats(struct s3backer_store *s3b, struct http_io_stats *stats)
{
struct http_io_private *const priv = s3b->data;
pthread_mutex_lock(&priv->mutex);
memcpy(stats, &priv->stats, sizeof(*stats));
pthread_mutex_unlock(&priv->mutex);
}
static int
http_io_list_blocks(struct s3backer_store *s3b, block_list_func_t *callback, void *arg)
{
struct http_io_private *const priv = s3b->data;
struct http_io_conf *const config = priv->config;
char marker[sizeof("&marker=") + strlen(config->prefix) + S3B_BLOCK_NUM_DIGITS + 1];
char urlbuf[URL_BUF_SIZE(config) + sizeof(marker) + 32];
struct http_io io;
int r;
/* Initialize I/O info */
memset(&io, 0, sizeof(io));
io.url = urlbuf;
io.method = HTTP_GET;
io.config = config;
io.xml_error = XML_ERROR_NONE;
io.callback_func = callback;
io.callback_arg = arg;
/* Create XML parser */
if ((io.xml = XML_ParserCreate(NULL)) == NULL) {
(*config->log)(LOG_ERR, "failed to create XML parser");
return ENOMEM;
}
/* Allocate buffers for XML path and tag text content */
io.xml_text_max = strlen(config->prefix) + S3B_BLOCK_NUM_DIGITS + 10;
if ((io.xml_text = malloc(io.xml_text_max + 1)) == NULL) {
(*config->log)(LOG_ERR, "malloc: %s", strerror(errno));
goto oom;
}
if ((io.xml_path = calloc(1, 1)) == NULL) {
(*config->log)(LOG_ERR, "calloc: %s", strerror(errno));
goto oom;
}
/* List blocks */
do {
const time_t now = time(NULL);
/* Reset XML parser state */
XML_ParserReset(io.xml, NULL);
XML_SetUserData(io.xml, &io);
XML_SetElementHandler(io.xml, http_io_list_elem_start, http_io_list_elem_end);
XML_SetCharacterDataHandler(io.xml, http_io_list_text);
/* Format URL */
snprintf(urlbuf, sizeof(urlbuf), "%s%s?", config->baseURL, config->vhost ? "" : config->bucket);
/* Add URL parameters (note: must be in "canonical query string" format for proper authentication) */
if (io.list_truncated) {
snprintf(urlbuf + strlen(urlbuf), sizeof(urlbuf) - strlen(urlbuf), "%s=%s%0*jx&",
LIST_PARAM_MARKER, config->prefix, S3B_BLOCK_NUM_DIGITS, (uintmax_t)io.last_block);
}
snprintf(urlbuf + strlen(urlbuf), sizeof(urlbuf) - strlen(urlbuf), "%s=%u", LIST_PARAM_MAX_KEYS, LIST_BLOCKS_CHUNK);
snprintf(urlbuf + strlen(urlbuf), sizeof(urlbuf) - strlen(urlbuf), "&%s=%s", LIST_PARAM_PREFIX, config->prefix);
/* Add Date header */
http_io_add_date(priv, &io, now);
/* Add Authorization header */
if ((r = http_io_add_auth(priv, &io, now, NULL, 0)) != 0)
goto fail;
/* Perform operation */
r = http_io_perform_io(priv, &io, http_io_list_prepper);
/* Clean up headers */
curl_slist_free_all(io.headers);
io.headers = NULL;
/* Check for error */
if (r != 0)
goto fail;
/* Finalize parse */
if (XML_Parse(io.xml, NULL, 0, 1) != XML_STATUS_OK) {
io.xml_error = XML_GetErrorCode(io.xml);
io.xml_error_line = XML_GetCurrentLineNumber(io.xml);
io.xml_error_column = XML_GetCurrentColumnNumber(io.xml);
}
/* Check for XML error */
if (io.xml_error != XML_ERROR_NONE) {
(*config->log)(LOG_ERR, "XML parse error: line %d col %d: %s",
io.xml_error_line, io.xml_error_column, XML_ErrorString(io.xml_error));
r = EIO;
goto fail;
}
} while (io.list_truncated);
/* Done */
XML_ParserFree(io.xml);
free(io.xml_path);
free(io.xml_text);
return 0;
oom:
/* Update stats */
pthread_mutex_lock(&priv->mutex);
priv->stats.out_of_memory_errors++;
pthread_mutex_unlock(&priv->mutex);
r = ENOMEM;
fail:
/* Clean up after failure */
if (io.xml != NULL)
XML_ParserFree(io.xml);
free(io.xml_path);
free(io.xml_text);
return r;
}
static void
http_io_list_prepper(CURL *curl, struct http_io *io)
{
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_io_curl_list_reader);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, io);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, io->headers);
curl_easy_setopt(curl, CURLOPT_ENCODING, "");
curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, (long)1);
}
static size_t
http_io_curl_list_reader(const void *ptr, size_t size, size_t nmemb, void *stream)
{
struct http_io *const io = (struct http_io *)stream;
size_t total = size * nmemb;
if (io->xml_error != XML_ERROR_NONE)
return total;
if (XML_Parse(io->xml, ptr, total, 0) != XML_STATUS_OK) {
io->xml_error = XML_GetErrorCode(io->xml);
io->xml_error_line = XML_GetCurrentLineNumber(io->xml);
io->xml_error_column = XML_GetCurrentColumnNumber(io->xml);
}
return total;
}
static void
http_io_list_elem_start(void *arg, const XML_Char *name, const XML_Char **atts)
{
struct http_io *const io = (struct http_io *)arg;
const size_t plen = strlen(io->xml_path);
char *newbuf;
/* Update current path */
if ((newbuf = realloc(io->xml_path, plen + 1 + strlen(name) + 1)) == NULL) {
(*io->config->log)(LOG_DEBUG, "realloc: %s", strerror(errno));
io->xml_error = XML_ERROR_NO_MEMORY;
return;
}
io->xml_path = newbuf;
io->xml_path[plen] = '/';
strcpy(io->xml_path + plen + 1, name);
/* Reset buffer */
io->xml_text_len = 0;
io->xml_text[0] = '\0';
}
static void
http_io_list_elem_end(void *arg, const XML_Char *name)
{
struct http_io *const io = (struct http_io *)arg;
s3b_block_t block_num;
/* Handle <Truncated> tag */
if (strcmp(io->xml_path, "/" LIST_ELEM_LIST_BUCKET_RESLT "/" LIST_ELEM_IS_TRUNCATED) == 0)
io->list_truncated = strcmp(io->xml_text, LIST_TRUE) == 0;
/* Handle <Key> tag */
else if (strcmp(io->xml_path, "/" LIST_ELEM_LIST_BUCKET_RESLT "/" LIST_ELEM_CONTENTS "/" LIST_ELEM_KEY) == 0) {
if (http_io_parse_block(io->config, io->xml_text, &block_num) == 0) {
(*io->callback_func)(io->callback_arg, block_num);
io->last_block = block_num;
}
}
/* Update current XML path */
assert(strrchr(io->xml_path, '/') != NULL);
*strrchr(io->xml_path, '/') = '\0';
/* Reset buffer */
io->xml_text_len = 0;
io->xml_text[0] = '\0';
}
static void
http_io_list_text(void *arg, const XML_Char *s, int len)
{
struct http_io *const io = (struct http_io *)arg;
int avail;
/* Append text to buffer */
avail = io->xml_text_max - io->xml_text_len;
if (len > avail)
len = avail;
memcpy(io->xml_text + io->xml_text_len, s, len);
io->xml_text_len += len;
io->xml_text[io->xml_text_len] = '\0';
}
/*
* Parse a block's item name (including prefix) and set the corresponding bit in the bitmap.
*/
int
http_io_parse_block(struct http_io_conf *config, const char *name, s3b_block_t *block_nump)
{
const size_t plen = strlen(config->prefix);
s3b_block_t block_num = 0;
int i;
/* Check prefix */
if (strncmp(name, config->prefix, plen) != 0)
return -1;
name += plen;
/* Parse block number */
for (i = 0; i < S3B_BLOCK_NUM_DIGITS; i++) {
char ch = name[i];
if (!isxdigit(ch))
break;
block_num <<= 4;
block_num |= ch <= '9' ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Was parse successful? */
if (i != S3B_BLOCK_NUM_DIGITS || name[i] != '\0' || block_num >= config->num_blocks)
return -1;
/* Done */
*block_nump = block_num;
return 0;
}
static int
http_io_meta_data(struct s3backer_store *s3b, off_t *file_sizep, u_int *block_sizep)
{
struct http_io_private *const priv = s3b->data;
struct http_io_conf *const config = priv->config;
char urlbuf[URL_BUF_SIZE(config)];
const time_t now = time(NULL);
struct http_io io;
int r;
/* Initialize I/O info */
memset(&io, 0, sizeof(io));
io.url = urlbuf;
io.method = HTTP_HEAD;
/* Construct URL for the first block */
http_io_get_block_url(urlbuf, sizeof(urlbuf), config, 0);
/* Add Date header */
http_io_add_date(priv, &io, now);
/* Add Authorization header */
if ((r = http_io_add_auth(priv, &io, now, NULL, 0)) != 0)
goto done;
/* Perform operation */
if ((r = http_io_perform_io(priv, &io, http_io_head_prepper)) != 0)
goto done;
/* Extract filesystem sizing information */
if (io.file_size == 0 || io.block_size == 0) {
r = ENOENT;
goto done;
}
*file_sizep = (off_t)io.file_size;
*block_sizep = io.block_size;
done:
/* Clean up */
curl_slist_free_all(io.headers);
return r;
}
static void
http_io_head_prepper(CURL *curl, struct http_io *io)
{
memset(&io->bufs, 0, sizeof(io->bufs));
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_io_curl_reader);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, io);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, http_io_curl_header);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, io);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, io->headers);
}
static int
http_io_set_mounted(struct s3backer_store *s3b, int *old_valuep, int new_value)
{
struct http_io_private *const priv = s3b->data;
struct http_io_conf *const config = priv->config;
char urlbuf[URL_BUF_SIZE(config) + sizeof(MOUNTED_FLAG)];
const time_t now = time(NULL);
struct http_io io;
int r = 0;
/* Initialize I/O info */
memset(&io, 0, sizeof(io));
io.url = urlbuf;
io.method = HTTP_HEAD;
/* Construct URL for the mounted flag */
http_io_get_mounted_flag_url(urlbuf, sizeof(urlbuf), config);
/* Get old value */
if (old_valuep != NULL) {
/* Add Date header */
http_io_add_date(priv, &io, now);
/* Add Authorization header */
if ((r = http_io_add_auth(priv, &io, now, NULL, 0)) != 0)
goto done;
/* See if object exists */
switch ((r = http_io_perform_io(priv, &io, http_io_head_prepper))) {
case ENOENT:
*old_valuep = 0;
r = 0;
break;
case 0:
*old_valuep = 1;
break;
default:
goto done;
}
}
/* Set new value */
if (new_value != -1) {
char content[_POSIX_HOST_NAME_MAX + DATE_BUF_SIZE + 32];
u_char md5[MD5_DIGEST_LENGTH];
char md5buf[MD5_DIGEST_LENGTH * 2 + 1];
MD5_CTX ctx;
/* Reset I/O info */
curl_slist_free_all(io.headers);
memset(&io, 0, sizeof(io));
io.url = urlbuf;
io.method = new_value ? HTTP_PUT : HTTP_DELETE;
/* Add Date header */
http_io_add_date(priv, &io, now);
/* To set the flag PUT some content containing current date */
if (new_value) {
struct tm tm;
/* Create content for the mounted flag object (timestamp) */
gethostname(content, sizeof(content - 1));
content[sizeof(content) - 1] = '\0';
strftime(content + strlen(content), sizeof(content) - strlen(content), "\n" AWS_DATE_BUF_FMT "\n", gmtime_r(&now, &tm));
io.src = content;
io.buf_size = strlen(content);
MD5_Init(&ctx);
MD5_Update(&ctx, content, strlen(content));
MD5_Final(md5, &ctx);
/* Add Content-Type header */
io.headers = http_io_add_header(io.headers, "%s: %s", CTYPE_HEADER, MOUNTED_FLAG_CONTENT_TYPE);
/* Add Content-MD5 header */
http_io_base64_encode(md5buf, sizeof(md5buf), md5, MD5_DIGEST_LENGTH);
io.headers = http_io_add_header(io.headers, "%s: %s", MD5_HEADER, md5buf);
}
/* Add ACL header (PUT only) */
if (new_value)
io.headers = http_io_add_header(io.headers, "%s: %s", ACL_HEADER, config->accessType);
/* Add storage class header (if needed) */
if (config->rrs)
io.headers = http_io_add_header(io.headers, "%s: %s", STORAGE_CLASS_HEADER, SCLASS_REDUCED_REDUNDANCY);
/* Add Authorization header */
if ((r = http_io_add_auth(priv, &io, now, io.src, io.buf_size)) != 0)
goto done;
/* Perform operation to set or clear mounted flag */
r = http_io_perform_io(priv, &io, http_io_write_prepper);
}
done:
/* Clean up */
curl_slist_free_all(io.headers);
return r;
}
static int
update_iam_credentials(struct http_io_private *const priv)
{
struct http_io_conf *const config = priv->config;
char urlbuf[sizeof(EC2_IAM_META_DATA_URLBASE) + 128];
struct http_io io;
char buf[2048] = { '\0' };
char *access_id = NULL;
char *access_key = NULL;
char *iam_token = NULL;
size_t buflen;
int r;
/* Build URL */
snprintf(urlbuf, sizeof(urlbuf), "%s%s", EC2_IAM_META_DATA_URLBASE, config->ec2iam_role);
/* Initialize I/O info */
memset(&io, 0, sizeof(io));
io.url = urlbuf;
io.method = HTTP_GET;
io.dest = buf;
io.buf_size = sizeof(buf);
/* Perform operation */
(*config->log)(LOG_INFO, "acquiring EC2 IAM credentials from %s", io.url);
if ((r = http_io_perform_io(priv, &io, http_io_iamcreds_prepper)) != 0) {
(*config->log)(LOG_ERR, "failed to acquire EC2 IAM credentials from %s: %s", io.url, strerror(r));
return r;
}
/* Determine how many bytes we read */
buflen = io.buf_size - io.bufs.rdremain;
if (buflen > sizeof(buf) - 1)
buflen = sizeof(buf) - 1;
buf[buflen] = '\0';
/* Find credentials in JSON response */
if ((access_id = parse_json_field(priv, buf, EC2_IAM_META_DATA_ACCESSID)) == NULL
|| (access_key = parse_json_field(priv, buf, EC2_IAM_META_DATA_ACCESSKEY)) == NULL
|| (iam_token = parse_json_field(priv, buf, EC2_IAM_META_DATA_TOKEN)) == NULL) {
(*config->log)(LOG_ERR, "failed to extract EC2 IAM credentials from response: %s", strerror(errno));
free(access_id);
free(access_key);
return EINVAL;
}
/* Update credentials */
pthread_mutex_lock(&priv->mutex);
free(config->accessId);
free(config->accessKey);
free(config->iam_token);
config->accessId = access_id;
config->accessKey = access_key;
config->iam_token = iam_token;
pthread_mutex_unlock(&priv->mutex);
(*config->log)(LOG_INFO, "successfully updated EC2 IAM credentials from %s", io.url);
/* Done */
return 0;
}
static void *
update_iam_credentials_main(void *arg)
{
struct http_io_private *const priv = arg;
while (!priv->shutting_down) {
// Sleep for five minutes
sleep(300);
// Shutting down?
if (priv->shutting_down)
break;
// Attempt to update credentials
update_iam_credentials(priv);
}
// Done
return NULL;
}
static char *
parse_json_field(struct http_io_private *priv, const char *json, const char *field)
{
struct http_io_conf *const config = priv->config;
regmatch_t match[2];
regex_t regex;
char buf[128];
char *value;
size_t vlen;
int r;
snprintf(buf, sizeof(buf), "\"%s\"[[:space:]]*:[[:space:]]*\"([^\"]+)\"", field);
memset(®ex, 0, sizeof(regex));
if ((r = regcomp(®ex, buf, REG_EXTENDED)) != 0) {
regerror(r, ®ex, buf, sizeof(buf));
(*config->log)(LOG_INFO, "regex compilation failed: %s", buf);
errno = EINVAL;
return NULL;
}
if ((r = regexec(®ex, json, sizeof(match) / sizeof(*match), match, 0)) != 0) {
regerror(r, ®ex, buf, sizeof(buf));
(*config->log)(LOG_INFO, "failed to find JSON field \"%s\" in credentials response: %s", field, buf);
regfree(®ex);
errno = EINVAL;
return NULL;
}
regfree(®ex);
vlen = match[1].rm_eo - match[1].rm_so;
if ((value = malloc(vlen + 1)) == NULL) {
r = errno;
(*config->log)(LOG_INFO, "malloc: %s", strerror(r));
errno = r;
return NULL;