forked from archiecobbs/s3backer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_io.c
3575 lines (3108 loc) · 127 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-2020 Archie L. Cobbs <archie.cobbs@gmail.com>
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations including
* the two.
*
* You must obey the GNU General Public License in all respects for all
* of the code used other than OpenSSL. If you modify file(s) with this
* exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do
* so, delete this exception statement from your version. If you delete
* this exception statement from all source files in the program, then
* also delete it here.
*/
#include "s3backer.h"
#include "http_io.h"
#include "compress.h"
#include "util.h"
// HTTP definitions
#define HTTP_GET "GET"
#define HTTP_PUT "PUT"
#define HTTP_DELETE "DELETE"
#define HTTP_HEAD "HEAD"
#define HTTP_POST "POST"
#define HTTP_MOVED_PERMANENTLY 301
#define HTTP_FOUND 302
#define HTTP_NOT_MODIFIED 304
#define HTTP_TEMPORARY_REDIRECT 307
#define HTTP_PERMANENT_REDIRECT 308
#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 ACCEPT_ENCODING_HEADER "Accept-Encoding"
#define ETAG_HEADER "ETag"
#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 SSE_HEADER "x-amz-server-side-encryption"
#define SSE_KEY_ID_HEADER "x-amz-server-side-encryption-aws-kms-key-id"
#define STORAGE_CLASS_HEADER "x-amz-storage-class"
#define FILE_SIZE_HEADER "x-amz-meta-s3backer-filesize"
#define BLOCK_SIZE_HEADER "x-amz-meta-s3backer-blocksize"
#define MOUNT_TOKEN_HEADER "x-amz-meta-s3backer-mount-token"
#define HMAC_HEADER "x-amz-meta-s3backer-hmac"
#define IF_MATCH_HEADER "If-Match"
#define IF_NONE_MATCH_HEADER "If-None-Match"
// Minumum HTTP status code we consider an error
#define HTTP_STATUS_ERROR_MINIMUM 300 // we don't support redirects
// MIME type for blocks
#define CONTENT_TYPE "application/x-s3backer-block"
// Mount token file
#define MOUNT_TOKEN_FILE "s3backer-mounted"
#define MOUNT_TOKEN_FILE_MIME_TYPE "text/plain"
// 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
// Upper bound on the length of an URL representing one block
#define URL_BUF_SIZE(config) (strlen((config)->baseURL) \
+ strlen((config)->bucket) + 1 \
+ strlen((config)->prefix) \
+ S3B_BLOCK_NUM_DIGITS \
+ strlen(BLOCK_HASH_PREFIX_SEPARATOR) \
+ S3B_BLOCK_NUM_DIGITS + 2)
// Separator string used when "--blockHashPrefix" is in effect
#define BLOCK_HASH_PREFIX_SEPARATOR "-"
// 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"
// Bulk Delete API constants
#define DELETE_ELEM_DELETE "Delete"
#define DELETE_ELEM_OBJECT "Object"
#define DELETE_ELEM_KEY "Key"
#define DELETE_ELEM_DELETE_RESULT "DeleteResult"
#define DELETE_ELEM_ERROR "Error"
#define DELETE_ELEM_CODE "Code"
#define DELETE_ELEM_MESSAGE "Message"
// How many blocks to list or delete at a time
#define LIST_BLOCKS_CHUNK 1000
#define DELETE_BLOCKS_CHUNK 1000
// Maximum error payload size in bytes
#define MAX_ERROR_PAYLOAD_SIZE 0x100000
// 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
// Enable to debug parsing block list response
#define DEBUG_BLOCK_LIST 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"
// TCP keep-alive
#define TCP_KEEP_ALIVE_IDLE 200
#define TCP_KEEP_ALIVE_INTERVAL 60
// Misc
#define WHITESPACE " \t\v\f\r\n"
#if MD5_DIGEST_LENGTH != 16
#error unexpected MD5_DIGEST_LENGTH
#endif
#if SHA_DIGEST_LENGTH != 20
#error unexpected MD5_DIGEST_LENGTH
#endif
/*
* 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;
};
// Block survey per-thread info
struct http_io_survey {
struct http_io_private *priv;
pthread_t thread;
s3b_block_t min_name;
s3b_block_t max_name;
block_list_func_t *callback;
void *callback_arg;
};
// 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;
bitmap_t *non_zero; // config->nonzero_bitmap is moved to here
pthread_t iam_thread; // IAM credentials refresh thread
u_char iam_thread_alive; // IAM thread was successfully created
u_char iam_thread_shutdown; // Flag to the IAM thread telling it to exit
// Block survey info
struct http_io_survey *survey_threads; // survey threads that are running now, if any
u_int num_survey_threads; // the number of survey threads that are still alive
u_int num_survey_threads_joinable; // the number of survey threads not yet joined
pthread_cond_t survey_done; // indicates last survey thread has finished
volatile int abort_survey; // set to 1 to abort block survey
int survey_error; // error from any survey thread
// 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;
// Configuration
struct http_io_conf *config; // configuration
// XML parser 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 handler_error; // error encountered during parsing
// Bucket object listing info
int list_truncated; // returned list was truncated
char *start_after; // where to start next round of listing
s3b_block_t min_name; // inclusive lower bound for block name/prefix
s3b_block_t max_name; // inclusive upper bound for block name/prefix
s3b_block_t *block_list; // the blocks we found this iteration
u_int num_blocks; // number of blocks in "block_list"
// Bulk delete info
char *bulk_delete_err_key;
char *bulk_delete_err_code;
char *bulk_delete_err_msg;
// Other info that needs to be passed around
CURL *curl; // back reference to CURL instance
const char *method; // HTTP method
const char *url; // HTTP URL
struct curl_slist *headers; // HTTP headers
const char *sse; // Server Side Encryption
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"
int32_t mount_token; // mount_token from "x-amz-meta-s3backer-mount-token"
u_int expect_304; // a verify request; expect a 304 response
u_char etag[MD5_DIGEST_LENGTH];// parsed ETag header (must look like an MD5 hash)
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
// Info used to capture error response payloads
long http_status; // response status, if known, else zero
char *error_payload; // payload of error response
size_t error_payload_len; // error response length
};
// CURL prepper function type
typedef void http_io_curl_prepper_t(CURL *curl, struct http_io *io);
// s3backer_store functions
static int http_io_create_threads(struct s3backer_store *s3b);
static int http_io_meta_data(struct s3backer_store *s3b, off_t *file_sizep, u_int *block_sizep);
static int http_io_set_mount_token(struct s3backer_store *s3b, int32_t *old_valuep, int32_t new_value);
static int http_io_read_block(struct s3backer_store *s3b, s3b_block_t block_num, void *dest,
u_char *actual_etag, const u_char *expect_etag, int strict);
static int http_io_write_block(struct s3backer_store *s3b, s3b_block_t block_num, const void *src, u_char *etag,
check_cancel_t *check_cancel, void *check_cancel_arg);
static int http_io_flush_blocks(struct s3backer_store *s3b, const s3b_block_t *block_nums, u_int num_blocks, long timeout);
static int http_io_bulk_zero(struct s3backer_store *const s3b, const s3b_block_t *block_nums, u_int num_blocks);
static int http_io_survey_non_zero(struct s3backer_store *s3b, block_list_func_t *callback, void *arg);
static int http_io_shutdown(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_xml_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_mount_token_file_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);
static size_t url_encode(const char *src, size_t len, char *dst, int buflen, int encode_slash);
static void digest_url_encoded(EVP_MD_CTX* hash_ctx, const char *data, size_t len, int encode_slash);
// 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);
// Block survey functions
static int http_io_list_blocks_range(struct http_io_private *priv,
s3b_block_t min, s3b_block_t max, block_list_func_t *callback, void *arg);
static void *http_io_list_blocks_worker_main(void *arg);
static void http_io_list_blocks_elem_end(void *arg, const XML_Char *name);
static block_list_func_t http_io_list_blocks_callback;
static void http_io_wait_for_survey_threads_to_exit(struct http_io_private *const priv);
// Bulk delete
static void http_io_bulk_delete_elem_end(void *arg, const XML_Char *name);
// XML query functions
static int http_io_xml_io_init(struct http_io_private *const priv, struct http_io *io, const char *method, char *url);
static int http_io_xml_io_exec(struct http_io_private *const priv, struct http_io *io,
void (*end_handler)(void *arg, const XML_Char *name));
static void http_io_xml_io_destroy(struct http_io_private *const priv, struct http_io *io);
static size_t http_io_curl_xml_reader(const void *ptr, size_t size, size_t nmemb, void *stream);
static void http_io_xml_elem_start(void *arg, const XML_Char *name, const XML_Char **atts);
static void http_io_xml_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 http_io_private *priv, struct curl_slist *headers, const char *fmt, ...)
__attribute__ ((__format__ (__printf__, 3, 4)));
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 int http_io_safe_to_cache_curl_handle(CURLcode curl_code, long http_code);
static void http_io_release_curl(struct http_io_private *priv, CURL **curlp, int may_cache);
static int http_io_reader_error_check(struct http_io *const io, const void *ptr, size_t len);
static void http_io_free_error_payload(struct http_io *const io);
static void http_io_log_error_payload(struct http_io *const io);
static int http_io_sockopt_callback(void *clientp, curl_socket_t curlfd, curlsocktype purpose);
// 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, u_int dmax);
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 s3b_block_t http_io_block_hash_prefix(s3b_block_t block_num);
static int http_io_parse_hex(const char *str, u_char *buf, u_int nbytes);
static int http_io_parse_hex_block_num(const char *string, s3b_block_t *block_nump);
static void http_io_prhex(char *buf, const u_char *data, size_t len);
static int http_io_header_name_sort(const void *ptr1, const void *ptr2);
static int http_io_parse_header(struct http_io *io, const char *input,
const char *header, int num_conversions, const char *fmt, ...);
static void http_io_init_io(struct http_io_private *priv, struct http_io *io, const char *method, const char *url);
static void http_io_curl_header_reset(struct http_io *const io);
static int http_io_verify_etag_provided(struct http_io *io);
// Internal variables
static pthread_mutex_t *openssl_locks;
static int num_openssl_locks;
static u_char zero_etag[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->create_threads = http_io_create_threads;
s3b->meta_data = http_io_meta_data;
s3b->set_mount_token = http_io_set_mount_token;
s3b->read_block = http_io_read_block;
s3b->write_block = http_io_write_block;
s3b->bulk_zero = http_io_bulk_zero;
s3b->flush_blocks = http_io_flush_blocks;
s3b->survey_non_zero = http_io_survey_non_zero;
s3b->shutdown = http_io_shutdown;
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;
if ((r = pthread_cond_init(&priv->survey_done, NULL)) != 0) {
goto fail3;
}
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 fail4;
}
for (nlocks = 0; nlocks < num_openssl_locks; nlocks++) {
if ((r = pthread_mutex_init(&openssl_locks[nlocks], NULL)) != 0)
goto fail5;
}
CRYPTO_set_locking_callback(http_io_openssl_locker);
CRYPTO_set_id_callback(http_io_openssl_ider);
// Avoid GCC unused-function warnings
(void)http_io_openssl_locker;
(void)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;
u_int cipher_block_size;
u_int cipher_iv_length;
// 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 fail5;
}
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 fail5;
}
// Sanity check cipher is a block cipher
cipher_block_size = EVP_CIPHER_block_size(priv->cipher);
cipher_iv_length = EVP_CIPHER_iv_length(priv->cipher);
if (cipher_block_size <= 1 || cipher_block_size != cipher_iv_length) {
(*config->log)(LOG_ERR, "invalid cipher `%s' (block size %u, IV length %u); only block ciphers are supported",
config->encryption, cipher_block_size, cipher_iv_length);
r = EINVAL;
goto fail5;
}
// Hash password to get bulk data encryption key
snvprintf(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 fail5;
}
// 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 fail5;
}
// 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
if (config->ec2iam_role != NULL && (r = update_iam_credentials(priv)) != 0)
goto fail6;
// Take ownership of non-zero block bitmap
priv->non_zero = config->nonzero_bitmap;
config->nonzero_bitmap = NULL;
// Done
return s3b;
fail6:
while ((holder = LIST_FIRST(&priv->curls)) != NULL) {
curl_easy_cleanup(holder->curl);
LIST_REMOVE(holder, link);
free(holder);
}
curl_global_cleanup();
fail5:
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;
fail4:
pthread_cond_destroy(&priv->survey_done);
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 curl_holder *holder;
// 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_cond_destroy(&priv->survey_done);
pthread_mutex_destroy(&priv->mutex);
bitmap_free(&priv->non_zero);
free(priv);
free(s3b);
}
static int
http_io_shutdown(struct s3backer_store *const s3b)
{
struct http_io_private *const priv = s3b->data;
struct http_io_conf *const config = priv->config;
int r;
// Signal survey threads to stop
priv->abort_survey = 1;
// Lock mutex
pthread_mutex_lock(&priv->mutex);
// Shut down IAM thread, if any
if (priv->iam_thread_alive) {
// Make IAM thread stop
priv->iam_thread_shutdown = 1;
if ((r = pthread_cancel(priv->iam_thread)) != 0)
(*config->log)(LOG_ERR, "pthread_cancel: %s", strerror(r));
priv->iam_thread_alive = 0;
// Reap IAM thread
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
(*config->log)(LOG_DEBUG, "waiting for EC2 IAM thread to shutdown");
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");
pthread_mutex_lock(&priv->mutex);
}
// Wait for block survey threads to exit, if any
http_io_wait_for_survey_threads_to_exit(priv);
// Unlock mutex
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
// Done
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));
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
}
void
http_io_clear_stats(struct s3backer_store *s3b)
{
struct http_io_private *const priv = s3b->data;
pthread_mutex_lock(&priv->mutex);
memset(&priv->stats, 0, sizeof(priv->stats));
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
}
static int
http_io_flush_blocks(struct s3backer_store *s3b, const s3b_block_t *block_nums, u_int num_blocks, long timeout)
{
return 0; // we are stateless, so there's nothing to flush
}
static int
http_io_survey_non_zero(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;
const int max_threads = config->list_blocks_threads;
s3b_block_t last_possible_name;
int r = 0;
// Determine the last possible block name we need to scan for
last_possible_name = config->blockHashPrefix ? ~(s3b_block_t)0 : config->num_blocks - 1;
// Lock mutex
pthread_mutex_lock(&priv->mutex);
assert(priv->num_survey_threads == 0);
assert(priv->num_survey_threads_joinable == 0);
// Allocate survey_threads array
if (priv->num_survey_threads != 0) {
r = EINPROGRESS;
goto done;
}
if ((priv->survey_threads = calloc(max_threads, sizeof(*priv->survey_threads))) == NULL) {
r = errno;
(*config->log)(LOG_ERR, "calloc: %s", strerror(r));
goto done;
}
// Initialize per-thread infos and start threads
priv->survey_error = 0;
while (priv->num_survey_threads < max_threads) {
const int thread_index = priv->num_survey_threads;
struct http_io_survey *const survey = &priv->survey_threads[thread_index];
// Configure this thread
survey->priv = priv;
survey->callback = callback;
survey->callback_arg = arg;
// Configure this thread's portion of the range, but being careful to handle weird corner cases
survey->min_name = thread_index > 0 ? survey[-1].max_name + 1 : (s3b_block_t)0;
if (survey->min_name > last_possible_name)
survey->min_name = last_possible_name;
if (thread_index == max_threads - 1)
survey->max_name = last_possible_name;
else {
survey->max_name = ((off_t)last_possible_name * (thread_index + 1)) / max_threads;
if (survey->max_name < survey->min_name)
survey->max_name = survey->min_name;
if (survey->max_name > last_possible_name)
survey->max_name = last_possible_name;
}
// Start this thread
if ((r = pthread_create(&survey->thread, NULL, http_io_list_blocks_worker_main, survey)) != 0) {
(*config->log)(LOG_ERR, "pthread_create: %s", strerror(r));
priv->abort_survey = 1;
break;
}
priv->num_survey_threads++;
}
priv->num_survey_threads_joinable = priv->num_survey_threads;
// Wait for survey threads to finish
http_io_wait_for_survey_threads_to_exit(priv);
if (r == 0)
r = priv->survey_error;
done:
// Done
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
return r;
}
// This assumes the mutex is locked
static void
http_io_wait_for_survey_threads_to_exit(struct http_io_private *const priv)
{
struct http_io_conf *const config = priv->config;
int r;
// Wait for all survey threads to finish
while (priv->num_survey_threads > 0)
pthread_cond_wait(&priv->survey_done, &priv->mutex);
// Join them
while (priv->num_survey_threads_joinable > 0) {
if ((r = pthread_join(priv->survey_threads[--priv->num_survey_threads_joinable].thread, NULL)) != 0)
(*config->log)(LOG_ERR, "pthread_join: %s", strerror(r));
}
// Reset state
free(priv->survey_threads);
priv->survey_threads = NULL;
}
static void *
http_io_list_blocks_worker_main(void *arg)
{
struct http_io_survey *const info = arg;
struct http_io_private *const priv = info->priv;
int r = 0;
// Scan my range (if non-empty)
if (info->min_name <= info->max_name)
r = http_io_list_blocks_range(priv, info->min_name, info->max_name, http_io_list_blocks_callback, info);
// Finish up
pthread_mutex_lock(&priv->mutex);
if (priv->survey_error == 0)
priv->survey_error = r;
if (priv->num_survey_threads > 0 && --priv->num_survey_threads == 0)
pthread_cond_broadcast(&priv->survey_done);
CHECK_RETURN(pthread_mutex_unlock(&priv->mutex));
return NULL;
}
static int
http_io_list_blocks_callback(void *arg, const s3b_block_t *block_nums, u_int num_blocks)
{
struct http_io_survey *const info = arg;
if (info->priv->abort_survey)
return ECANCELED;
return (*info->callback)(info->callback_arg, block_nums, num_blocks);
}
//
// Scan blocks in the range "min" (inclusive) to "max" (inclusive).
//
// Note "min" and "max" refer to the first S3B_BLOCK_NUM_DIGITS characters of the block's S3 object name (after any "--prefix"),
// not necessarily the block number; these are different things when "--blockHashPrefix" is used, otherwise they are the same.
//
static int
http_io_list_blocks_range(struct http_io_private *priv, s3b_block_t min, s3b_block_t max, block_list_func_t *callback, void *arg)
{
struct http_io_conf *const config = priv->config;
char last_possible_path[strlen(config->prefix) + S3B_BLOCK_NUM_DIGITS + 1];
s3b_block_t block_list[LIST_BLOCKS_CHUNK];
struct http_io io;
int r;
// Initialize XML query
if ((r = http_io_xml_io_init(priv, &io, HTTP_GET, NULL)) != 0) // "url" is set below
return r;
io.block_list = block_list;
io.min_name = min;
io.max_name = max;
// Determine the last possible valid block name (or block hash prefix) we want to search for
snvprintf(last_possible_path, sizeof(last_possible_path), "%s%0*jx", config->prefix, S3B_BLOCK_NUM_DIGITS, (uintmax_t)max);
// Initialize "io.start_after", which says where to continue listing names each time around the loop
if (min == (s3b_block_t)0)
r = asprintf(&io.start_after, "%s%0*jx%c", config->prefix, S3B_BLOCK_NUM_DIGITS - 1, (uintmax_t)0, '0' - 1);
else
r = asprintf(&io.start_after, "%s%0*jx", config->prefix, S3B_BLOCK_NUM_DIGITS, (uintmax_t)(min - 1));
if (r == -1) {
r = errno;
(*config->log)(LOG_ERR, "asprintf: %s", strerror(r));
io.start_after = NULL;
goto done;
}
// List blocks
while (1) {
char start_after_urlencoded[3 * strlen(io.start_after) + 1];
char urlbuf[strlen(config->baseURL)
+ strlen(config->bucket)
+ sizeof("?" LIST_PARAM_MARKER "=") + sizeof(start_after_urlencoded)
+ sizeof("&" LIST_PARAM_MAX_KEYS "=") + 16];
// Format URL (note: URL parameters must be in "canonical query string" format for proper authentication)
url_encode(io.start_after, strlen(io.start_after), start_after_urlencoded, sizeof(start_after_urlencoded), 1);
snvprintf(urlbuf, sizeof(urlbuf), "%s%s?%s=%s&%s=%u", config->baseURL, config->vhost ? "" : config->bucket,
LIST_PARAM_MARKER, start_after_urlencoded, LIST_PARAM_MAX_KEYS, LIST_BLOCKS_CHUNK);
io.url = urlbuf;
// Perform operation
assert(io.num_blocks == 0);
#if DEBUG_BLOCK_LIST
(*config->log)(LOG_DEBUG, "list: querying range [%0*jx, %0*jx] starting after \"%s\"",
S3B_BLOCK_NUM_DIGITS, (uintmax_t)min, S3B_BLOCK_NUM_DIGITS, (uintmax_t)max, io.start_after);
#endif
if ((r = http_io_xml_io_exec(priv, &io, http_io_list_blocks_elem_end)) != 0)
break;
// Invoke callback with the blocks we found
if (io.num_blocks > 0) {
if ((r = (*callback)(arg, block_list, io.num_blocks)) != 0)
break;
io.num_blocks = 0;
}
// Are we done?
if (!io.list_truncated || strcmp(io.start_after, last_possible_path) >= 0)
break;
}
done:
// Done
http_io_xml_io_destroy(priv, &io);
free(io.start_after);
return r;
}
static void
http_io_xml_prepper(CURL *curl, struct http_io *io)
{
if (io->bufs.wrdata != NULL) {
curl_easy_setopt(curl, CURLOPT_READFUNCTION, http_io_curl_writer);
curl_easy_setopt(curl, CURLOPT_READDATA, io);
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_io_curl_xml_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_xml_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;
// Check for error payload
if (http_io_reader_error_check(io, ptr, total))
return total;
// If we are in an error state, just bail
if (io->xml_error != XML_ERROR_NONE || io->handler_error != 0)
return total;
// Run new payload bytes through XML parser
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);
}
// Done
return total;
}
static void
http_io_xml_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;
// If we are in an error state, just bail
if (io->xml_error != XML_ERROR_NONE || io->handler_error != 0)
return;
// Update current path
if ((newbuf = realloc(io->xml_path, plen + 1 + strlen(name) + 1)) == NULL) {
io->handler_error = errno;
(*io->config->log)(LOG_ERR, "realloc: %s", strerror(errno));
return;
}
io->xml_path = newbuf;
io->xml_path[plen] = '/';
strcpy(io->xml_path + plen + 1, name);
// Reset text buffer
io->xml_text[0] = '\0';
#if DEBUG_BLOCK_LIST
// Debug
(*io->config->log)(LOG_DEBUG, "list: new path: \"%s\"", io->xml_path);
#endif
}
static void
http_io_list_blocks_elem_end(void *arg, const XML_Char *name)
{
struct http_io *const io = (struct http_io *)arg;
struct http_io_conf *const config = io->config;
// If we are in an error state, just bail
if (io->xml_error != XML_ERROR_NONE || io->handler_error != 0)
return;
// 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;
#if DEBUG_BLOCK_LIST
(*config->log)(LOG_DEBUG, "list: parsed truncated=%d", io->list_truncated);
#endif
goto done;
}
// Handle <Key> tag
if (strcmp(io->xml_path, "/" LIST_ELEM_LIST_BUCKET_RESLT "/" LIST_ELEM_CONTENTS "/" LIST_ELEM_KEY) == 0) {
s3b_block_t hash_value;
s3b_block_t block_num;
char *new_start_after;
#if DEBUG_BLOCK_LIST
(*config->log)(LOG_DEBUG, "list: key=\"%s\"", io->xml_text);
#endif
// Attempt to parse key as a block's object name and add to list if successful
if (http_io_parse_block(config->prefix, config->num_blocks,
config->blockHashPrefix, io->xml_text, &hash_value, &block_num) == 0) {
#if DEBUG_BLOCK_LIST
(*config->log)(LOG_DEBUG, "list: parsed key=\"%s\" -> hash=%0*jx block=%0*jx",
io->xml_text, S3B_BLOCK_NUM_DIGITS, (uintmax_t)hash_value, S3B_BLOCK_NUM_DIGITS, (uintmax_t)block_num);
#endif
if (hash_value >= io->min_name && hash_value <= io->max_name) { // avoid out-of-range callbacks
if (io->num_blocks < LIST_BLOCKS_CHUNK)
io->block_list[io->num_blocks++] = block_num;
else {
(*config->log)(LOG_ERR, "list: rec'd more than %d blocks?", LIST_BLOCKS_CHUNK);
io->handler_error = EINVAL;
}
}
}
#if DEBUG_BLOCK_LIST
else
(*config->log)(LOG_DEBUG, "list: can't parse key=\"%s\"", io->xml_text);
#endif
// Save the last name we see as the starting point for next time
if ((new_start_after = realloc(io->start_after, strlen(io->xml_text) + 1)) == NULL) {
io->handler_error = errno;
(*config->log)(LOG_ERR, "strdup: %s", strerror(errno));
} else {
io->start_after = new_start_after;
strcpy(io->start_after, io->xml_text);
}
}
done:
// Update current XML path
assert(strrchr(io->xml_path, '/') != NULL);
*strrchr(io->xml_path, '/') = '\0';
// Reset text buffer
io->xml_text[0] = '\0';
}