forked from TurboGit/hubicfuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudfsapi.c
1701 lines (1557 loc) · 58.2 KB
/
cloudfsapi.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
#define _GNU_SOURCE
#include <stdio.h>
#include <magic.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef __linux__
#include <alloca.h>
#endif
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <libxml/tree.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <json.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include "commonfs.h"
#include "cloudfsapi.h"
#include "config.h"
#include <fuse.h>
#define RHEL5_LIBCURL_VERSION 462597
#define RHEL5_CERTIFICATE_FILE "/etc/pki/tls/certs/ca-bundle.crt"
#define REQUEST_RETRIES 3
#define MAX_FILES 10000
// size of buffer for writing to disk look at ioblksize.h in coreutils
// and try some values on your own system if you want the best performance
#define DISK_BUFF_SIZE 32768
static char storage_url[MAX_URL_SIZE];
static char storage_token[MAX_HEADER_SIZE];
static pthread_mutex_t pool_mut;
static CURL* curl_pool[1024];
static int curl_pool_count = 0;
extern int debug;
extern int verify_ssl;
extern bool option_get_extended_metadata;
extern bool option_curl_verbose;
extern int option_curl_progress_state;
extern int option_cache_statfs_timeout;
extern bool option_extensive_debug;
extern bool option_enable_chown;
extern bool option_enable_chmod;
static int rhel5_mode = 0;
static struct statvfs statcache =
{
.f_bsize = 4096,
.f_frsize = 4096,
.f_blocks = INT_MAX,
.f_bfree = INT_MAX,
.f_bavail = INT_MAX,
.f_files = MAX_FILES,
.f_ffree = 0,
.f_favail = 0,
.f_namemax = INT_MAX
};
//used to compute statfs cache interval
static time_t last_stat_read_time = 0;
extern FuseOptions options;
struct MemoryStruct
{
char* memory;
size_t size;
};
#ifdef HAVE_OPENSSL
#include <openssl/crypto.h>
static pthread_mutex_t* ssl_lockarray;
static void lock_callback(int mode, int type, char* file, int line)
{
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&(ssl_lockarray[type]));
else
pthread_mutex_unlock(&(ssl_lockarray[type]));
}
static unsigned long thread_id()
{
return (unsigned long)pthread_self();
}
#endif
static size_t xml_dispatch(void* ptr, size_t size, size_t nmemb, void* stream)
{
xmlParseChunk((xmlParserCtxtPtr)stream, (char*)ptr, size * nmemb, 0);
return size * nmemb;
}
static CURL* get_connection(const char* path)
{
pthread_mutex_lock(&pool_mut);
CURL* curl = curl_pool_count ? curl_pool[--curl_pool_count] : curl_easy_init();
if (!curl)
{
debugf(DBG_LEVEL_NORM, KRED"curl alloc failed");
abort();
}
pthread_mutex_unlock(&pool_mut);
return curl;
}
static void return_connection(CURL* curl)
{
pthread_mutex_lock(&pool_mut);
curl_pool[curl_pool_count++] = curl;
pthread_mutex_unlock(&pool_mut);
}
static void add_header(curl_slist** headers, const char* name,
const char* value)
{
char x_header[MAX_HEADER_SIZE];
char safe_value[256];
const char* value_ptr;
debugf(DBG_LEVEL_EXT, "add_header(%s:%s)", name, value);
if (strlen(value) > 256)
{
debugf(DBG_LEVEL_NORM, KRED"add_header: warning, value size > 256 (%s:%s) ",
name, value);
//hubic will throw an HTTP 400 error on X-Copy-To operation if X-Object-Meta-FilePath header value is larger than 256 chars
//fix for issue #95 https://github.com/TurboGit/hubicfuse/issues/95
if (!strcasecmp(name, "X-Object-Meta-FilePath"))
{
debugf(DBG_LEVEL_NORM,
KRED"add_header: trimming header (%s) value to max allowed", name);
//trim header size to max allowed
strncpy(safe_value, value, 256 - 1);
safe_value[255] = '\0';
value_ptr = safe_value;
}
else
value_ptr = value;
}
else
value_ptr = value;
snprintf(x_header, sizeof(x_header), "%s: %s", name, value_ptr);
*headers = curl_slist_append(*headers, x_header);
}
static size_t header_dispatch(void* ptr, size_t size, size_t nmemb,
void* dir_entry)
{
char* header = (char*)alloca(size * nmemb + 1);
char* head = (char*)alloca(size * nmemb + 1);
char* value = (char*)alloca(size * nmemb + 1);
memcpy(header, (char*)ptr, size * nmemb);
header[size * nmemb] = '\0';
if (sscanf(header, "%[^:]: %[^\r\n]", head, value) == 2)
{
if (!strncasecmp(head, "x-auth-token", size * nmemb))
strncpy(storage_token, value, sizeof(storage_token));
if (!strncasecmp(head, "x-storage-url", size * nmemb))
strncpy(storage_url, value, sizeof(storage_url));
if (!strncasecmp(head, "x-account-meta-quota", size * nmemb))
statcache.f_blocks = (unsigned long) (strtoull(value, NULL,
10) / statcache.f_frsize);
if (!strncasecmp(head, "x-account-bytes-used", size * nmemb))
statcache.f_bfree = statcache.f_bavail = statcache.f_blocks - (unsigned long) (
strtoull(value, NULL, 10) / statcache.f_frsize);
if (!strncasecmp(head, "x-account-object-count", size * nmemb))
{
unsigned long object_count = strtoul(value, NULL, 10);
statcache.f_ffree = MAX_FILES - object_count;
statcache.f_favail = MAX_FILES - object_count;
}
}
return size * nmemb;
}
static void header_set_time_from_str(char* time_str,
struct timespec* time_entry)
{
char sec_value[TIME_CHARS] = { 0 };
char nsec_value[TIME_CHARS] = { 0 };
time_t sec;
long nsec;
sscanf(time_str, "%[^.].%[^\n]", sec_value, nsec_value);
sec = strtoll(sec_value, NULL, 10);//to allow for larger numbers
nsec = atol(nsec_value);
debugf(DBG_LEVEL_EXTALL, "Received time=%s.%s / %li.%li, existing=%li.%li",
sec_value, nsec_value, sec, nsec, time_entry->tv_sec, time_entry->tv_nsec);
if (sec != time_entry->tv_sec || nsec != time_entry->tv_nsec)
{
debugf(DBG_LEVEL_EXTALL,
"Time changed, setting new time=%li.%li, existing was=%li.%li",
sec, nsec, time_entry->tv_sec, time_entry->tv_nsec);
time_entry->tv_sec = sec;
time_entry->tv_nsec = nsec;
char time_str_local[TIME_CHARS] = "";
get_time_as_string((time_t)sec, nsec, time_str_local, sizeof(time_str_local));
debugf(DBG_LEVEL_EXTALL, "header_set_time_from_str received time=[%s]",
time_str_local);
get_timespec_as_str(time_entry, time_str_local, sizeof(time_str_local));
debugf(DBG_LEVEL_EXTALL, "header_set_time_from_str set time=[%s]",
time_str_local);
}
}
static size_t header_get_meta_dispatch(void* ptr, size_t size, size_t nmemb,
void* userdata)
{
char* header = (char*)alloca(size * nmemb + 1);
char* head = (char*)alloca(size * nmemb + 1);
char* value = (char*)alloca(size * nmemb + 1);
memcpy(header, (char*)ptr, size * nmemb);
header[size * nmemb] = '\0';
static char storage[MAX_HEADER_SIZE];
if (sscanf(header, "%[^:]: %[^\r\n]", head, value) == 2)
{
strncpy(storage, head, sizeof(storage));
dir_entry* de = (dir_entry*)userdata;
if (de != NULL)
{
if (!strncasecmp(head, HEADER_TEXT_ATIME, size * nmemb))
header_set_time_from_str(value, &de->atime);
if (!strncasecmp(head, HEADER_TEXT_CTIME, size * nmemb))
header_set_time_from_str(value, &de->ctime);
if (!strncasecmp(head, HEADER_TEXT_MTIME, size * nmemb))
header_set_time_from_str(value, &de->mtime);
if (!strncasecmp(head, HEADER_TEXT_CHMOD, size * nmemb))
de->chmod = atoi(value);
if (!strncasecmp(head, HEADER_TEXT_GID, size * nmemb))
de->gid = atoi(value);
if (!strncasecmp(head, HEADER_TEXT_UID, size * nmemb))
de->uid = atoi(value);
}
else
debugf(DBG_LEVEL_EXT,
"Unexpected NULL dir_entry on header(%s), file should be in cache already",
storage);
}
else
{
//debugf(DBG_LEVEL_NORM, "Received unexpected header line");
}
return size * nmemb;
}
static size_t rw_callback(size_t (*rw)(void*, size_t, size_t, FILE*),
void* ptr,
size_t size, size_t nmemb, void* userp)
{
struct segment_info* info = (struct segment_info*)userp;
size_t mem = size * nmemb;
if (mem < 1 || info->size < 1)
return 0;
size_t amt_read = rw(ptr, 1, info->size < mem ? info->size : mem, info->fp);
info->size -= amt_read;
return amt_read;
}
size_t fwrite2(void* ptr, size_t size, size_t nmemb, FILE* filep)
{
return fwrite((const void*)ptr, size, nmemb, filep);
}
static size_t read_callback(void* ptr, size_t size, size_t nmemb, void* userp)
{
return rw_callback(fread, ptr, size, nmemb, userp);
}
static size_t write_callback(void* ptr, size_t size, size_t nmemb, void* userp)
{
return rw_callback(fwrite2, ptr, size, nmemb, userp);
}
//http://curl.haxx.se/libcurl/c/CURLOPT_XFERINFOFUNCTION.html
int progress_callback_xfer(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
struct curl_progress* myp = (struct curl_progress*)clientp;
CURL* curl = myp->curl;
double curtime = 0;
double dspeed = 0, uspeed = 0;
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime);
curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &dspeed);
curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &uspeed);
/* under certain circumstances it may be desirable for certain functionality
to only run every N seconds, in order to do this the transaction time can
be used */
//http://curl.haxx.se/cvssource/src/tool_cb_prg.c
if ((curtime - myp->lastruntime) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL)
{
myp->lastruntime = curtime;
curl_off_t total;
curl_off_t point;
double frac, percent;
total = dltotal + ultotal;
point = dlnow + ulnow;
frac = (double)point / (double)total;
percent = frac * 100.0f;
debugf(DBG_LEVEL_EXT, "TOTAL TIME: %.0f sec Down=%.0f Kbps UP=%.0f Kbps",
curtime, dspeed / 1024, uspeed / 1024);
debugf(DBG_LEVEL_EXT, "UP: %lld of %lld DOWN: %lld/%lld Completion %.1f %%",
ulnow, ultotal, dlnow, dltotal, percent);
}
return 0;
}
//http://curl.haxx.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
int progress_callback(void* clientp, double dltotal, double dlnow,
double ultotal, double ulnow)
{
return progress_callback_xfer(clientp, (curl_off_t)dltotal, (curl_off_t)dlnow,
(curl_off_t)ultotal, (curl_off_t)ulnow);
}
//get the response from HTTP requests, mostly for debug purposes
// http://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string
// http://curl.haxx.se/libcurl/c/getinmemory.html
size_t writefunc_callback(void* contents, size_t size, size_t nmemb,
void* userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct* mem = (struct MemoryStruct*)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL)
{
/* out of memory! */
debugf(DBG_LEVEL_NORM, KRED"writefunc_callback: realloc() failed");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
// de_cached_entry must be NULL when the file is already in global cache
// otherwise point to a new dir_entry that will be added to the cache (usually happens on first dir load)
static int send_request_size(const char* method, const char* path, void* fp,
xmlParserCtxtPtr xmlctx, curl_slist* extra_headers,
off_t file_size, int is_segment,
dir_entry* de_cached_entry, const char* unencoded_path)
{
debugf(DBG_LEVEL_EXT, "send_request_size(%s) (%s)", method, path);
char url[MAX_URL_SIZE];
char orig_path[MAX_URL_SIZE];
char header_data[MAX_HEADER_SIZE];
char* slash;
long response = -1;
int tries = 0;
//needed to keep the response data, for debug purposes
struct MemoryStruct chunk;
if (!storage_url[0])
{
debugf(DBG_LEVEL_NORM, KRED"send_request with no storage_url?");
abort();
}
//char *encoded_path = curl_escape(path, 0);
while ((slash = strstr(path, "%2F")) || (slash = strstr(path, "%2f")))
{
*slash = '/';
memmove(slash + 1, slash + 3, strlen(slash + 3) + 1);
}
while (*path == '/')
path++;
snprintf(url, sizeof(url), "%s/%s", storage_url, path);
snprintf(orig_path, sizeof(orig_path), "/%s", path);
// retry on failures
for (tries = 0; tries < REQUEST_RETRIES; tries++)
{
chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
CURL* curl = get_connection(path);
if (rhel5_mode)
curl_easy_setopt(curl, CURLOPT_CAINFO, RHEL5_CERTIFICATE_FILE);
curl_slist* headers = NULL;
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
//reversed logic, 0=to enable curl progress
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, option_curl_progress_state ? 0 : 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, verify_ssl ? 1 : 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_easy_setopt(curl, CURLOPT_VERBOSE, option_curl_verbose ? 1 : 0);
add_header(&headers, "X-Auth-Token", storage_token);
dir_entry* de;
if (de_cached_entry == NULL)
de = check_path_info(unencoded_path);
else
{
// updating metadata on a file about to be added to cache (for x-copy, dest meta = src meta)
de = de_cached_entry;
debugf(DBG_LEVEL_EXTALL, "send_request_size: using param dir_entry(%s)",
orig_path);
}
if (!de)
debugf(DBG_LEVEL_EXTALL,
"send_request_size: "KYEL"file not in cache (%s)(%s)(%s)", orig_path, path,
unencoded_path);
else
{
// add headers to save utimens attribs only on upload
if (!strcasecmp(method, "PUT") || !strcasecmp(method, "MKDIR"))
{
debugf(DBG_LEVEL_EXTALL, "send_request_size: Saving utimens for file %s",
orig_path);
debugf(DBG_LEVEL_EXTALL,
"send_request_size: Cached utime for path=%s ctime=%li.%li mtime=%li.%li atime=%li.%li",
orig_path,
de->ctime.tv_sec, de->ctime.tv_nsec, de->mtime.tv_sec, de->mtime.tv_nsec,
de->atime.tv_sec, de->atime.tv_nsec);
char atime_str_nice[TIME_CHARS] = "", mtime_str_nice[TIME_CHARS] = "",
ctime_str_nice[TIME_CHARS] = "";
get_timespec_as_str(&(de->atime), atime_str_nice, sizeof(atime_str_nice));
debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: atime=[%s]", atime_str_nice);
get_timespec_as_str(&(de->mtime), mtime_str_nice, sizeof(mtime_str_nice));
debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: mtime=[%s]", mtime_str_nice);
get_timespec_as_str(&(de->ctime), ctime_str_nice, sizeof(ctime_str_nice));
debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: ctime=[%s]", ctime_str_nice);
char mtime_str[TIME_CHARS], atime_str[TIME_CHARS], ctime_str[TIME_CHARS];
char string_float[TIME_CHARS];
snprintf(mtime_str, TIME_CHARS, "%lu.%lu", de->mtime.tv_sec,
de->mtime.tv_nsec);
snprintf(atime_str, TIME_CHARS, "%lu.%lu", de->atime.tv_sec,
de->atime.tv_nsec);
snprintf(ctime_str, TIME_CHARS, "%lu.%lu", de->ctime.tv_sec,
de->ctime.tv_nsec);
add_header(&headers, HEADER_TEXT_FILEPATH, orig_path);
add_header(&headers, HEADER_TEXT_MTIME, mtime_str);
add_header(&headers, HEADER_TEXT_ATIME, atime_str);
add_header(&headers, HEADER_TEXT_CTIME, ctime_str);
add_header(&headers, HEADER_TEXT_MTIME_DISPLAY, mtime_str_nice);
add_header(&headers, HEADER_TEXT_ATIME_DISPLAY, atime_str_nice);
add_header(&headers, HEADER_TEXT_CTIME_DISPLAY, ctime_str_nice);
char gid_str[INT_CHAR_LEN], uid_str[INT_CHAR_LEN], chmod_str[INT_CHAR_LEN];
snprintf(gid_str, INT_CHAR_LEN, "%d", de->gid);
snprintf(uid_str, INT_CHAR_LEN, "%d", de->uid);
snprintf(chmod_str, INT_CHAR_LEN, "%d", de->chmod);
add_header(&headers, HEADER_TEXT_GID, gid_str);
add_header(&headers, HEADER_TEXT_UID, uid_str);
add_header(&headers, HEADER_TEXT_CHMOD, chmod_str);
}
else
debugf(DBG_LEVEL_EXTALL, "send_request_size: not setting utimes (%s)",
orig_path);
}
if (!strcasecmp(method, "MKDIR"))
{
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
add_header(&headers, "Content-Type", "application/directory");
}
else if (!strcasecmp(method, "MKLINK") && fp)
{
rewind(fp);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size);
curl_easy_setopt(curl, CURLOPT_READDATA, fp);
add_header(&headers, "Content-Type", "application/link");
}
else if (!strcasecmp(method, "PUT"))
{
//http://blog.chmouel.com/2012/02/06/anatomy-of-a-swift-put-query-to-object-server/
debugf(DBG_LEVEL_EXT, "send_request_size: PUT (%s)", orig_path);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
if (fp)
{
curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size);
curl_easy_setopt(curl, CURLOPT_READDATA, fp);
}
else
curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
if (is_segment)
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
//enable progress reporting
//http://curl.haxx.se/libcurl/c/progressfunc.html
struct curl_progress prog;
prog.lastruntime = 0;
prog.curl = curl;
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
/* pass the struct pointer into the progress function */
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog);
//get the response for debug purposes
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
}
else if (!strcasecmp(method, "GET"))
{
if (is_segment)
{
debugf(DBG_LEVEL_EXT, "send_request_size: GET SEGMENT (%s)", orig_path);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
}
else if (fp)
{
debugf(DBG_LEVEL_EXT, "send_request_size: GET FP (%s)", orig_path);
rewind(fp); // make sure the file is ready for a-writin'
fflush(fp);
if (ftruncate(fileno(fp), 0) < 0)
{
debugf(DBG_LEVEL_NORM,
KRED"ftruncate failed. I don't know what to do about that.");
abort();
}
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_get_meta_dispatch);
// sample by UThreadCurl.cpp, https://bitbucket.org/pamungkas5/bcbcurl/src
// and http://www.codeproject.com/Articles/838366/BCBCurl-a-LibCurl-based-download-manager
curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)de);
struct curl_progress prog;
prog.lastruntime = 0;
prog.curl = curl;
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog);
}
else if (xmlctx)
{
debugf(DBG_LEVEL_EXT, "send_request_size: GET XML (%s)", orig_path);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
}
else
{
//asumming retrieval of headers only
debugf(DBG_LEVEL_EXT, "send_request_size: GET HEADERS only(%s)");
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_get_meta_dispatch);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)de);
curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
}
}
else
{
debugf(DBG_LEVEL_EXT, "send_request_size: catch_all (%s)");
// this posts an HEAD request (e.g. for statfs)
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_dispatch);
}
/* add the headers from extra_headers if any */
curl_slist* extra;
for (extra = extra_headers; extra; extra = extra->next)
{
debugf(DBG_LEVEL_EXT, "adding header: %s", extra->data);
headers = curl_slist_append(headers, extra->data);
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
debugf(DBG_LEVEL_EXT, "status: send_request_size(%s) started HTTP REQ:%s",
orig_path, url);
curl_easy_perform(curl);
double total_time;
char* effective_url;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
debugf(DBG_LEVEL_EXT,
"status: send_request_size(%s) completed HTTP REQ:%s total_time=%.1f seconds",
orig_path, effective_url, total_time);
curl_slist_free_all(headers);
curl_easy_reset(curl);
return_connection(curl);
if (response != 404 && (response >= 400 || response < 200))
{
/*
Now, our chunk.memory points to a memory block that is chunk.size
bytes big and contains the remote file.
*/
debugf(DBG_LEVEL_NORM,
KRED"send_request_size: error message, size=%lu, [HTTP %d] (%s)(%s)",
(long)chunk.size, response, method, path);
debugf(DBG_LEVEL_NORM, KRED"send_request_size: error message=[%s]",
chunk.memory);
}
free(chunk.memory);
if ((response >= 200 && response < 400) || (!strcasecmp(method, "DELETE")
&& response == 409))
{
debugf(DBG_LEVEL_NORM,
"exit 0: send_request_size(%s) speed=%.1f sec "KCYN"(%s) "KGRN"[HTTP OK]",
orig_path, total_time, method);
return response;
}
//handle cases when file is not found, no point in retrying, will exit
if (response == 404)
{
debugf(DBG_LEVEL_NORM,
"send_request_size: not found error for (%s)(%s), ignored "KYEL"[HTTP 404].",
method, path);
return response;
}
else
{
debugf(DBG_LEVEL_NORM,
"send_request_size: httpcode=%d (%s)(%s), retrying "KRED"[HTTP ERR]", response,
method, path);
//todo: try to list response content for debug purposes
sleep(8 << tries); // backoff
}
if (response == 401 && !cloudfs_connect())
{
// re-authenticate on 401s
debugf(DBG_LEVEL_NORM, KYEL"exit 1: send_request_size(%s) (%s) [HTTP REAUTH]",
path, method);
return response;
}
if (xmlctx)
xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL);
}
debugf(DBG_LEVEL_NORM, "exit 2: send_request_size(%s)"KCYN"(%s) response=%d",
path, method, response);
return response;
}
int send_request(char* method, const char* path, FILE* fp,
xmlParserCtxtPtr xmlctx, curl_slist* extra_headers, dir_entry* de_cached_entry,
const char* unencoded_path)
{
long flen = 0;
if (fp)
{
// if we don't flush the size will probably be zero
fflush(fp);
flen = cloudfs_file_size(fileno(fp));
}
return send_request_size(method, path, fp, xmlctx, extra_headers, flen, 0,
de_cached_entry, unencoded_path);
}
//thread that downloads or uploads large file segments
void* upload_segment(void* seginfo)
{
struct segment_info* info = (struct segment_info*)seginfo;
char seg_path[MAX_URL_SIZE] = { 0 };
//set pointer to the segment start index in the complete large file (several threads will write to same large file)
fseek(info->fp, info->part * info->segment_size, SEEK_SET);
setvbuf(info->fp, NULL, _IOFBF, DISK_BUFF_SIZE);
snprintf(seg_path, MAX_URL_SIZE, "%s%08i", info->seg_base, info->part);
char* encoded = curl_escape(seg_path, 0);
debugf(DBG_LEVEL_EXT, KCYN"upload_segment(%s) part=%d size=%d seg_size=%d %s",
info->method, info->part, info->size, info->segment_size, seg_path);
int response = send_request_size(info->method, encoded, info, NULL, NULL,
info->size, 1, NULL, seg_path);
if (!(response >= 200 && response < 300))
fprintf(stderr, "Segment upload %s failed with response %d", seg_path,
response);
curl_free(encoded);
fclose(info->fp);
pthread_exit(NULL);
}
// segment_size is the globabl config variable and size_of_segment is local
//TODO: return whether the upload/download failed or not
void run_segment_threads(const char* method, int segments, int full_segments,
int remaining,
FILE* fp, char* seg_base, int size_of_segments)
{
debugf(DBG_LEVEL_EXT, "run_segment_threads(%s)", method);
char file_path[PATH_MAX] = { 0 };
struct segment_info* info = (struct segment_info*)
malloc(segments * sizeof(struct segment_info));
pthread_t* threads = (pthread_t*)malloc(segments * sizeof(pthread_t));
#ifdef __linux__
snprintf(file_path, PATH_MAX, "/proc/self/fd/%d", fileno(fp));
debugf(DBG_LEVEL_NORM, "On run segment filepath=%s", file_path);
#else
//TODO: I haven't actually tested this
if (fcntl(fileno(fp), F_GETPATH, file_path) == -1)
fprintf(stderr, "couldn't get the path name\n");
#endif
int i, ret;
for (i = 0; i < segments; i++)
{
info[i].method = method;
info[i].fp = fopen(file_path, method[0] == 'G' ? "r+" : "r");
info[i].part = i;
info[i].segment_size = size_of_segments;
info[i].size = i < full_segments ? size_of_segments : remaining;
info[i].seg_base = seg_base;
pthread_create(&threads[i], NULL, upload_segment, (void*) & (info[i]));
}
for (i = 0; i < segments; i++)
{
if ((ret = pthread_join(threads[i], NULL)) != 0)
fprintf(stderr, "error waiting for thread %d, status = %d\n", i, ret);
}
free(info);
free(threads);
debugf(DBG_LEVEL_EXT, "exit: run_segment_threads(%s)", method);
}
void split_path(const char* path, char* seg_base, char* container,
char* object)
{
char* string = strdup(path);
snprintf(seg_base, MAX_URL_SIZE, "%s", strsep(&string, "/"));
strncat(container, strsep(&string, "/"),
MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE));
char* _object = strsep(&string, "/");
char* remstr;
while (remstr = strsep(&string, "/"))
{
strncat(container, "/",
MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE));
strncat(container, _object,
MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE));
_object = remstr;
}
//fixed: when removing root folders this will generate a segfault
//issue #83, https://github.com/TurboGit/hubicfuse/issues/83
if (_object == NULL)
_object = object;
else
strncpy(object, _object, MAX_URL_SIZE);
free(string);
}
//checks on the cloud if this file (seg_path) have an associated segment folder
int internal_is_segmented(const char* seg_path, const char* object,
const char* parent_path)
{
debugf(DBG_LEVEL_EXT, "internal_is_segmented(%s)", seg_path);
//try to avoid an additional http request for small files
bool potentially_segmented;
dir_entry* de = check_path_info(parent_path);
if (!de)
{
//when files in folders are first loaded the path will not be yet in cache, so need
//to force segment meta download for segmented files
potentially_segmented = true;
}
else
{
//potentially segmented, assumption is that 0 size files are potentially segmented
//while size>0 is for sure not segmented, so no point in making an expensive HTTP GET call
potentially_segmented = (de->size == 0 && !de->isdir) ? true : false;
}
debugf(DBG_LEVEL_EXT, "internal_is_segmented: potentially segmented=%d",
potentially_segmented);
dir_entry* seg_dir;
if (potentially_segmented && cloudfs_list_directory(seg_path, &seg_dir))
{
if (seg_dir && seg_dir->isdir)
{
do
{
if (!strncmp(seg_dir->name, object, MAX_URL_SIZE))
{
debugf(DBG_LEVEL_EXT, "exit 0: internal_is_segmented(%s) "KGRN"TRUE",
seg_path);
return 1;
}
}
while ((seg_dir = seg_dir->next));
}
}
debugf(DBG_LEVEL_EXT, "exit 1: internal_is_segmented(%s) "KYEL"FALSE",
seg_path);
return 0;
}
int is_segmented(const char* path)
{
debugf(DBG_LEVEL_EXT, "is_segmented(%s)", path);
char container[MAX_URL_SIZE] = { 0 };
char object[MAX_URL_SIZE] = { 0 };
char seg_base[MAX_URL_SIZE] = { 0 };
split_path(path, seg_base, container, object);
char seg_path[MAX_URL_SIZE];
snprintf(seg_path, MAX_URL_SIZE, "%s/%s_segments", seg_base, container);
return internal_is_segmented(seg_path, object, path);
}
//returns segmented file properties by parsing and retrieving the folder structure on the cloud
//added totalsize as parameter to return the file size on list directory for segmented files
//old implementation returns file size=0 (issue #91)
int format_segments(const char* path, char* seg_base, long* segments,
long* full_segments, long* remaining, long* size_of_segments, long* total_size)
{
debugf(DBG_LEVEL_EXT, "format_segments(%s)", path);
char container[MAX_URL_SIZE] = "";
char object[MAX_URL_SIZE] = "";
split_path(path, seg_base, container, object);
char seg_path[MAX_URL_SIZE];
snprintf(seg_path, MAX_URL_SIZE, "%s/%s_segments", seg_base, container);
if (internal_is_segmented(seg_path, object, path))
{
char manifest[MAX_URL_SIZE];
dir_entry* seg_dir;
snprintf(manifest, MAX_URL_SIZE, "%s/%s", seg_path, object);
debugf(DBG_LEVEL_EXT, KMAG"format_segments manifest(%s)", manifest);
if (!cloudfs_list_directory(manifest, &seg_dir))
{
debugf(DBG_LEVEL_EXT, "exit 0: format_segments(%s)", path);
return 0;
}
// snprintf seesaw between manifest and seg_path to get
// the total_size and the segment size as well as the actual objects
char* timestamp = seg_dir->name;
snprintf(seg_path, MAX_URL_SIZE, "%s/%s", manifest, timestamp);
debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_path(%s)", seg_path);
if (!cloudfs_list_directory(seg_path, &seg_dir))
{
debugf(DBG_LEVEL_EXT, "exit 1: format_segments(%s)", path);
return 0;
}
char* str_size = seg_dir->name;
snprintf(manifest, MAX_URL_SIZE, "%s/%s", seg_path, str_size);
debugf(DBG_LEVEL_EXT, KMAG"format_segments manifest2(%s) size=%s", manifest,
str_size);
if (!cloudfs_list_directory(manifest, &seg_dir))
{
debugf(DBG_LEVEL_EXT, "exit 2: format_segments(%s)", path);
return 0;
}
//following folder name actually represents the parent file size
char* str_segment = seg_dir->name;
snprintf(seg_path, MAX_URL_SIZE, "%s/%s", manifest, str_segment);
debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_path2(%s)", seg_path);
//here is where we get a list with all segment files composing the parent large file
if (!cloudfs_list_directory(seg_path, &seg_dir))
{
debugf(DBG_LEVEL_EXT, "exit 3: format_segments(%s)", path);
return 0;
}
*total_size = strtoll(str_size, NULL, 10);
*size_of_segments = strtoll(str_segment, NULL, 10);
*remaining = *total_size % *size_of_segments;
*full_segments = *total_size / *size_of_segments;
*segments = *full_segments + (*remaining > 0);
snprintf(manifest, MAX_URL_SIZE, "%s_segments/%s/%s/%s/%s/",
container, object, timestamp, str_size, str_segment);
char tmp[MAX_URL_SIZE];
strncpy(tmp, seg_base, MAX_URL_SIZE);
snprintf(seg_base, MAX_URL_SIZE, "%s/%s", tmp, manifest);
debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_base(%s)", seg_base);
debugf(DBG_LEVEL_EXT,
KMAG"exit 4: format_segments(%s) total=%d size_of_segments=%d remaining=%d, full_segments=%d segments=%d",
path, &total_size, &size_of_segments, &remaining, &full_segments, &segments);
return 1;
}
else
{
debugf(DBG_LEVEL_EXT, KMAG"exit 5: format_segments(%s) not segmented?", path);
return 0;
}
}
/*
Public interface
*/
void cloudfs_init()
{
LIBXML_TEST_VERSION
xmlXPathInit();
curl_global_init(CURL_GLOBAL_ALL);
pthread_mutex_init(&pool_mut, NULL);
curl_version_info_data* cvid = curl_version_info(CURLVERSION_NOW);
// CentOS/RHEL 5 get stupid mode, because they have a broken libcurl
if (cvid->version_num == RHEL5_LIBCURL_VERSION)
{
debugf(DBG_LEVEL_NORM, "RHEL5 mode enabled.");
rhel5_mode = 1;
}
if (!strncasecmp(cvid->ssl_version, "openssl", 7))
{
#ifdef HAVE_OPENSSL
int i;
ssl_lockarray = (pthread_mutex_t*)OPENSSL_malloc(CRYPTO_num_locks() *
sizeof(pthread_mutex_t));
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_init(&(ssl_lockarray[i]), NULL);
CRYPTO_set_id_callback((unsigned long (*)())thread_id);
CRYPTO_set_locking_callback((void (*)())lock_callback);
#endif
}
else if (!strncasecmp(cvid->ssl_version, "nss", 3))
{
// allow https to continue working after forking (for RHEL/CentOS 6)
setenv("NSS_STRICT_NOFORK", "DISABLED", 1);
}
}
void cloudfs_free()
{
debugf(DBG_LEVEL_EXT, "Destroy mutex");
pthread_mutex_destroy(&pool_mut);
int n;
for (n = 0; n < curl_pool_count; ++n)
{
debugf(DBG_LEVEL_EXT, "Cleaning curl conn %d", n);
curl_easy_cleanup(curl_pool[n]);
}
}
int file_is_readable(const char* fname)
{
FILE* file;
if ( file = fopen( fname, "r" ) )
{
fclose( file );
return 1;
}
return 0;
}
const char* get_file_mimetype ( const char* path )
{
if ( file_is_readable( path ) == 1 )
{
magic_t magic;
const char* mime;
magic = magic_open( MAGIC_MIME_TYPE );
magic_load( magic, NULL );
magic_compile( magic, NULL );
mime = magic_file( magic, path );
magic_close( magic );
return mime;
}
const char* error = "application/octet-stream";
return error;
}
int cloudfs_object_read_fp(const char* path, FILE* fp)
{
debugf(DBG_LEVEL_EXT, "cloudfs_object_read_fp(%s)", path);
long flen;
fflush(fp);
const char* filemimetype = get_file_mimetype( path );
// determine the size of the file and segment if it is above the threshhold
fseek(fp, 0, SEEK_END);
flen = ftell(fp);
// delete the previously uploaded segments
if (is_segmented(path))
{
if (!cloudfs_delete_object(path))
debugf(DBG_LEVEL_NORM,
KRED"cloudfs_object_read_fp: couldn't delete existing file");
else
debugf(DBG_LEVEL_EXT, KYEL"cloudfs_object_read_fp: deleted existing file");
}
struct timespec now;
if (flen >= segment_above)
{
int i;
long remaining = flen % segment_size;
int full_segments = flen / segment_size;
int segments = full_segments + (remaining > 0);
// The best we can do here is to get the current time that way tools that
// use the mtime can at least check if the file was changing after now