-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplit_main.cpp
1989 lines (1897 loc) · 82 KB
/
split_main.cpp
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
#include <sstream>
#include <fstream>
#include <memory>
#include <cstring>
#include <sys/stat.h>
#include <filesystem>
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/std.h>
#include <fmt/printf.h>
#include <curl/curl.h>
#include <tmpfile/tmpfile.h>
#ifdef _WIN32
#include <windows.h>
#include <fileapi.h>
#include <synchapi.h>
#define usleep(ms) Sleep(ms)
#define sleep(s) usleep(s*1000)
#else
#include <unistd.h>
#include <sys/types.h>
#endif
uintmax_t SPLIT_SIZE;
std::string SPLIT_PREFIX;
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/std.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#define HUMAN_READABLE_MAX_WIDTH 7 /* "1024.0G" */
#define HUMAN_READABLE_MAX_WIDTH_STR "7"
std::string make_human_readable_str(unsigned long long val) {
if (val == 0) return "0";
if (val < 1000) {
return fmt::format("{}", val);
}
else if (val < 1024) {
unsigned long long remainder_ = (10 * val) / 1024;
return fmt::format("0.{}K", remainder_);
}
static const char unit_chars[] = {
'\0', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
};
int a = 0;
unsigned long long value;
unsigned long long remainder;
while (val >= 1024) {
value = val / 1024;
remainder = val % 1024;
val = value;
a++;
}
if (remainder < 100) {
return fmt::format("{}{}", value, unit_chars[a]);
}
else {
unsigned long long remainder_ = (10 * remainder) / 1024;
return fmt::format("{}.{}{}", value, remainder_, unit_chars[a]);
}
}
const char* bytes_to_human(const unsigned long long& size_in_bytes) {
fmt::print("size in [ human: {: >6}, bytes: {} ]\n", make_human_readable_str(size_in_bytes), size_in_bytes);
return nullptr;
}
int main2() {
bytes_to_human(1);
bytes_to_human(10);
bytes_to_human(100);
bytes_to_human(990);
bytes_to_human(1000);
bytes_to_human(1023);
bytes_to_human(1024);
bytes_to_human(1025);
bytes_to_human(1800);
bytes_to_human(1900);
bytes_to_human(2000);
bytes_to_human(2047);
bytes_to_human(2048);
bytes_to_human(2049);
bytes_to_human(2500);
bytes_to_human(10000);
bytes_to_human(100000);
bytes_to_human(1000000);
bytes_to_human(10000000);
bytes_to_human(100000000);
bytes_to_human(1000000000);
bytes_to_human(10000000000);
bytes_to_human(100000000000);
bytes_to_human(1000000000000);
bytes_to_human(10000000000000);
return 0;
}
bool is_ls = false;
bool is_split = false;
bool is_join = false;
bool command_selected = false;
bool dry_run = false;
bool remove_files = false;
bool verbose_files = false;
bool next_is_size = false;
bool next_is_name = false;
bool next_is_help = true;
int next_ret = -1; // zero if -h or --help was explicitly specified
std::string file;
std::string out_directory;
struct BinWriter {
FILE* bin = nullptr;
const char* name = nullptr;
enum TYPES : uint8_t {
U8, U16, U32, U64, STR
};
void create(const char* name) {
if (bin == nullptr) {
this->name = name;
bin = fopen(name, "wb");
if (bin == nullptr) {
auto se = errno;
std::string e = fmt::format("failed to create item {}\nerrno: -{} ({})\n", name, se, fmt::system_error(se, ""));
throw std::runtime_error(e);
}
fseek(bin, 0, SEEK_SET);
}
}
void close() {
if (bin != nullptr) {
fflush(bin);
fclose(bin);
bin = nullptr;
}
}
void write_u8(uint8_t value) {
uint8_t t = U8;
fwrite(&t, 1, 1, bin);
fwrite(&value, 1, 1, bin);
}
void write_u16(uint16_t value) {
uint8_t t = U16;
fwrite(&t, 1, 1, bin);
fwrite(&value, 1, 2, bin);
}
void write_u32(uint32_t value) {
uint8_t t = U32;
fwrite(&t, 1, 1, bin);
fwrite(&value, 1, 4, bin);
}
void write_u64(uint64_t value) {
uint8_t t = U64;
fwrite(&t, 1, 1, bin);
fwrite(&value, 1, 8, bin);
}
void write_string(const char* value) {
if (value == nullptr) {
value = "";
}
uint64_t size = (strlen(value)+1) * sizeof(char);
uint8_t t = STR;
fwrite(&t, 1, 1, bin);
fwrite(&size, 1, 8, bin);
fwrite(value, 1, size, bin);
}
};
struct BinReader {
FILE* bin = nullptr;
void open(const char* name) {
if (bin == nullptr) {
bin = fopen(name, "rb");
if (bin == nullptr) {
auto se = errno;
std::string e = fmt::format("failed to open item {}\nerrno: -{} ({})\n", name, se, fmt::system_error(se, ""));
throw std::runtime_error(e);
}
fseek(bin, 0, SEEK_SET);
}
}
void close() {
if (bin != nullptr) {
fclose(bin);
bin = nullptr;
}
}
uint8_t read_u8() {
uint8_t type;
fread(&type, 1, 1, bin);
if (type != BinWriter::U8) {
throw std::runtime_error("type was not U8");
}
fread(&type, 1, 1, bin);
return type;
}
uint16_t read_u16() {
uint8_t type;
fread(&type, 1, 1, bin);
if (type != BinWriter::U16) {
throw std::runtime_error("type was not U16");
}
uint16_t value;
fread(&value, 1, 2, bin);
return value;
}
uint32_t read_u32() {
uint8_t type;
fread(&type, 1, 1, bin);
if (type != BinWriter::U32) {
throw std::runtime_error("type was not U32");
}
uint32_t value;
fread(&value, 1, 4, bin);
return value;
}
uint64_t read_u64() {
uint8_t type;
fread(&type, 1, 1, bin);
if (type != BinWriter::U64) {
throw std::runtime_error("type was not U64");
}
uint64_t value;
fread(&value, 1, 8, bin);
return value;
}
const char * read_string() {
uint8_t type;
fread(&type, 1, 1, bin);
if (type != BinWriter::STR) {
throw std::runtime_error("type was not STR");
}
uint64_t size;
fread(&size, 1, 8, bin);
char* value = (char*)malloc(size);
if (value == nullptr) {
throw std::bad_alloc();
}
fread(value, 1, size, bin);
return value;
}
};
bool get_stats(const std::filesystem::path& path, struct stat& st) {
auto ps = std::filesystem::absolute(path).string();
auto s = ps.c_str();;
if (lstat(s, &st) == -1) {
auto se = errno;
fmt::print("failed to lstat {}\nerrno: -{} ({})\n", s, se, fmt::system_error(se, ""));
return false;
}
return true;
}
bool path_exists(const std::filesystem::path& path) {
struct stat st;
auto ps = std::filesystem::absolute(path).string();
auto s = ps.c_str();;
if (lstat(s, &st) == -1) {
auto se = errno;
if (se == ENOENT) return false;
fmt::print("failed to lstat {}\nerrno: -{} ({})\n", s, se, fmt::system_error(se, ""));
return false;
}
return true;
}
inline bool is_directory(const struct stat& st) {
return (st.st_mode & S_IFMT) == S_IFDIR;
}
inline bool is_reg(const struct stat& st) {
return (st.st_mode & S_IFMT) == S_IFREG;
}
inline bool is_symlink(const struct stat& st) {
return (st.st_mode & S_IFMT) == S_IFLNK;
}
bool is_symlink(const std::filesystem::path& path) {
struct stat st;
if (!get_stats(path, st)) return false;
return is_symlink(st);
}
std::string permissions_to_string(const struct stat& st) {
char s[11];
s[0] = is_directory(st) ? 'd' : is_symlink(st) ? 'l' : '-';
s[1] = (st.st_mode & S_IRUSR) == S_IRUSR ? 'r' : '-';
s[2] = (st.st_mode & S_IWUSR) == S_IWUSR ? 'w' : '-';
s[3] = (st.st_mode & S_IXUSR) == S_IXUSR ? 'x' : '-';
s[4] = (st.st_mode & S_IRGRP) == S_IRGRP ? 'r' : '-';
s[5] = (st.st_mode & S_IWGRP) == S_IWGRP ? 'w' : '-';
s[6] = (st.st_mode & S_IXGRP) == S_IXGRP ? 'x' : '-';
s[7] = (st.st_mode & S_IROTH) == S_IROTH ? 'r' : '-';
s[8] = (st.st_mode & S_IWOTH) == S_IWOTH ? 'w' : '-';
s[9] = (st.st_mode & S_IXOTH) == S_IXOTH ? 'x' : '-';
s[10] = '\0';
return s;
}
struct stat string_to_permissions(const char * s) {
struct stat st;
st.st_mode |= s[0] == 'd' ? S_IFDIR : s[0] == 'l' ? S_IFLNK : S_IFREG;
st.st_mode |= s[1] == 'r' ? S_IRUSR : 0;
st.st_mode |= s[2] == 'w' ? S_IWUSR : 0;
st.st_mode |= s[3] == 'x' ? S_IXUSR : 0;
st.st_mode |= s[4] == 'r' ? S_IRGRP : 0;
st.st_mode |= s[5] == 'w' ? S_IWGRP : 0;
st.st_mode |= s[6] == 'x' ? S_IXGRP : 0;
st.st_mode |= s[7] == 'r' ? S_IROTH : 0;
st.st_mode |= s[8] == 'w' ? S_IWOTH : 0;
st.st_mode |= s[9] == 'x' ? S_IXOTH : 0;
return st;
}
std::filesystem::perms permissions_to_filesystem(const struct stat& st) {
std::filesystem::perms s;
s |= (st.st_mode & S_IRUSR) == S_IRUSR ? std::filesystem::perms::owner_read : std::filesystem::perms::none;
s |= (st.st_mode & S_IWUSR) == S_IWUSR ? std::filesystem::perms::owner_write : std::filesystem::perms::none;
s |= (st.st_mode & S_IXUSR) == S_IXUSR ? std::filesystem::perms::owner_exec : std::filesystem::perms::none;
s |= (st.st_mode & S_IRGRP) == S_IRGRP ? std::filesystem::perms::group_read : std::filesystem::perms::none;
s |= (st.st_mode & S_IWGRP) == S_IWGRP ? std::filesystem::perms::group_write : std::filesystem::perms::none;
s |= (st.st_mode & S_IXGRP) == S_IXGRP ? std::filesystem::perms::group_exec : std::filesystem::perms::none;
s |= (st.st_mode & S_IROTH) == S_IROTH ? std::filesystem::perms::others_read : std::filesystem::perms::none;
s |= (st.st_mode & S_IWOTH) == S_IWOTH ? std::filesystem::perms::others_write : std::filesystem::perms::none;
s |= (st.st_mode & S_IXOTH) == S_IXOTH ? std::filesystem::perms::others_exec : std::filesystem::perms::none;
return s;
}
std::string get_symlink_dest(const std::filesystem::path& path, const struct stat & st) {
if ((st.st_mode & S_IFMT) == S_IFLNK) {
auto path_size = st.st_size + 1;
if (path_size == 1) return "";
auto s = path.string();
char* buf = (char*)malloc(path_size * sizeof(char));
if (readlink(s.c_str(), buf, path_size) == -1) {
auto se = errno;
fmt::print("failed to read content of symbolic link {}\nerrno: -{} ({})\n", s, se, fmt::system_error(se, ""));
free(buf);
return "";
}
buf[path_size - 1] = '\0';
std::string pstr = buf;
free(buf);
return pstr;
}
else {
return "";
}
}
std::string get_symlink_dest(const std::filesystem::path& path) {
struct stat st;
if (!get_stats(path, st)) return "";
return get_symlink_dest(path, st);
}
// the path converter is done, any path is now converted into a path relative to .
//
// [root] .. > .
// [child] ../foo > foo
// [child] ../foo/a > foo/a
// [root] ../dir > .
// [child] ../dir/a > a
// [root] / > .
// [child] /a/f/g > a/f/g
// [root] /a/ > .
// [child] /a/f/g > f/g
//
struct PathRecorder {
std::string trim = {};
BinWriter w = {};
BinReader r = {};
uint64_t unknowns = 0;
struct ChunkInfo {
uintmax_t split = 0;
uintmax_t offset = 0;
uintmax_t length = 0;
};
struct DirInfo {
std::filesystem::path path;
std::string perms;
std::filesystem::file_time_type::rep write_time;
};
struct FileInfo {
std::filesystem::path path;
std::string perms;
std::filesystem::file_time_type::rep write_time;
uintmax_t file_size;
std::vector<ChunkInfo> file_chunks;
};
struct SymlinkInfo {
std::filesystem::path path;
std::filesystem::path dest;
};
std::vector<DirInfo> bird_is_the_word_d = {};
std::vector<FileInfo> bird_is_the_word_f = {};
std::vector<SymlinkInfo> bird_is_the_word_s = {};
int split_number = 0;
bool first_split = true;
bool open = false;
uintmax_t current_chunk_size = 0;
uintmax_t chunk_size = SPLIT_SIZE;
uintmax_t total_chunk_count = 0;
uintmax_t max_file_chunks = 0;
uintmax_t total = 0;
uintmax_t totalc = 0;
std::string max_path = {};
uint64_t max_perms = 0;
std::string max_perms_str = {};
uintmax_t max_size = 0;
uintmax_t max_chunk = 0;
FILE* current_split_file = nullptr;
int _open() {
if (!open) {
if (first_split) {
first_split = false;
}
else {
split_number++;
}
if (dry_run) {
fmt::print("open {}split.{}\n", SPLIT_PREFIX, split_number);
}
else {
std::string split_f = fmt::format("{}split.{}", SPLIT_PREFIX, split_number);
current_split_file = fopen(split_f.c_str(), "wb");
if (current_split_file == nullptr) {
fmt::print("failed to create file: {}\n", split_f);
return -1;
}
}
open = true;
}
return 0;
}
void _close() {
if (open) {
if (dry_run) {
fmt::print("close {}split.{}\n", SPLIT_PREFIX, split_number);
}
else {
fflush(current_split_file);
fclose(current_split_file);
current_split_file = nullptr;
}
open = false;
}
}
int recordPath(const std::filesystem::path& path) {
struct stat st;
if (!get_stats(path, st)) {
return -1;
}
if (is_directory(st)) {
if (verbose_files) fmt::print("packing directory: {}\n", path);
DirInfo di;
di.path = path;
di.perms = permissions_to_string(st);
di.write_time = std::filesystem::last_write_time(path).time_since_epoch().count();
bird_is_the_word_d.emplace_back(di);
}
else if (is_reg(st)) {
if (verbose_files) fmt::print("packing file: {}\n", path);
std::vector<ChunkInfo> file_chunks;
uintmax_t s = std::filesystem::file_size(path);
total += s;
auto ps = path.string();
if (_open() == -1) return -1;
FILE* f;
if (dry_run) {
fmt::print("fopen()\n");
}
else {
f = fopen(ps.c_str(), "rb");
if (f == nullptr) {
fmt::print("failed to open file: {}\n", ps);
_close();
return -1;
}
}
while (s != 0) {
ChunkInfo chunk;
// see how much space we have available
uintmax_t avail = chunk_size - current_chunk_size;
if (avail == 0) {
// we have 0 bytes available, request a new chunk
_close();
if (_open() == -1) {
if (dry_run) {
fmt::print("fclose()\n");
}
else {
fclose(f);
f = nullptr;
}
return -1;
}
current_chunk_size = 0;
avail = chunk_size;
}
// we have x bytes available
chunk.split = split_number;
chunk.offset = current_chunk_size;
chunk.length = s <= avail ? s : avail;
current_chunk_size += chunk.length;
totalc += chunk.length;
s -= chunk.length;
if (dry_run) {
fmt::print("writing {} bytes ({} bytes left)\n", chunk.length, s);
fmt::print("malloc()\n");
fmt::print("fread()\n");
fmt::print("fwrite()\n");
fmt::print("free()\n");
}
else {
void* buffer = malloc(chunk.length);
if (buffer == nullptr) {
throw std::bad_alloc();
}
fread(buffer, 1, chunk.length, f);
fwrite(buffer, 1, chunk.length, current_split_file);
free(buffer);
}
file_chunks.emplace_back(chunk);
}
if (dry_run) {
fmt::print("fclose()\n");
}
else {
fclose(f);
f = nullptr;
}
total_chunk_count += file_chunks.size();
uint64_t current_file_chunks = file_chunks.size();
uint64_t current_file_size = std::filesystem::file_size(path);
if (current_file_size >= max_size) {
max_path = std::string(&ps[trim.length()]);
max_size = current_file_size;
max_chunk = current_file_chunks;
max_perms = st.st_mode;
max_perms_str = permissions_to_string(st);
}
auto file_time = std::filesystem::last_write_time(path).time_since_epoch().count();
if (remove_files) {
if (dry_run) {
fmt::print("rm -f {}\n", &ps[trim.length()]);
}
else {
try {
std::filesystem::remove(path);
}
catch (std::exception & e) {
fmt::print("failed to remove path: {}\n", &ps[trim.length()]);
}
}
}
FileInfo file_info;
file_info.path = path;
file_info.perms = permissions_to_string(st);
file_info.write_time = file_time;
file_info.file_size = current_file_size;
file_info.file_chunks = std::move(file_chunks);
bird_is_the_word_f.emplace_back(std::move(file_info));
}
else if (is_symlink(st)) {
if (verbose_files) fmt::print("packing symlink: {}\n", path);
auto dest = get_symlink_dest(path);
if (remove_files) {
if (dry_run) {
auto paths = path.string();
fmt::print("rm -f {}\n", &paths[trim.length()]);
}
else {
try {
std::filesystem::remove(path);
}
catch (std::exception& e) {
auto paths = path.string();
fmt::print("failed to remove path: {}\n", &paths[trim.length()]);
}
}
}
SymlinkInfo si;
si.path = path;
si.dest = dest;
bird_is_the_word_s.emplace_back(si);
}
else {
auto s = path.string();
fmt::print("unknown type: {}\n", &s[trim.length()]);
unknowns++;
}
return 0;
}
void recordPathDirectory(const DirInfo & dirInfo, const size_t& mfc) {
auto s = dirInfo.path.string();
const char* dir = &s[trim.length()];
if (verbose_files) {
auto sz = 0;
auto s = fmt::format("{: >{}} {}", sz, fmt::formatted_size("{}", max_size), sz >= 1000 ? fmt::format("({: >6})", make_human_readable_str(sz)) : " ");
fmt::print("recording directory: {} {} ({: >{}} chunks) {}\n", dirInfo.perms, s, 0, mfc, dir);
}
w.write_string(&s[trim.length()]);
w.write_string(dirInfo.perms.c_str());
w.write_u64(dirInfo.write_time);
}
void recordPathFile(const FileInfo & fileInfo, const size_t& mfc) {
auto s = fileInfo.path.string();
const char* file = &s[trim.length()];
uint64_t file_chunks = fileInfo.file_chunks.size();
if (verbose_files) {
auto sz = fileInfo.file_size;
auto s = fmt::format("{: >{}} {}", sz, fmt::formatted_size("{}", max_size), sz >= 1000 ? fmt::format("({: >6})", make_human_readable_str(sz)) : " ");
fmt::print("recording file: {} {} ({: >{}} chunks) {}\n", fileInfo.perms, s, file_chunks, mfc, file);
}
w.write_string(file);
w.write_string(fileInfo.perms.c_str());
w.write_u64(fileInfo.write_time);
w.write_u64(fileInfo.file_size);
w.write_u64(file_chunks);
for (const ChunkInfo& chunk : fileInfo.file_chunks) {
w.write_u64(chunk.split);
w.write_u64(chunk.offset);
w.write_u64(chunk.length);
}
}
void recordPathSymlink(const SymlinkInfo& symlinkInfo, const size_t& mfc) {
auto s = symlinkInfo.path.string();
const char* symlink = &s[trim.length()];
if (verbose_files) {
auto sz = 0;
auto s = fmt::format("{: >{}} {}", sz, fmt::formatted_size("{}", max_size), sz >= 1000 ? fmt::format("({: >6})", make_human_readable_str(sz)) : " ");
fmt::print("recording symlink: {} {} ({: >{}} chunks) {} -> {}\n", "lrwxrwxrwx", 0, s, mfc, symlink, symlinkInfo.dest);
}
w.write_string(symlink);
w.write_string(symlinkInfo.dest.c_str());
}
int record(const char* path) {
if (path[0] >= 'A' && path[0] <= 'Z' && path[1] == ':' && path[2] == '/' && path[3] == '\0') {
char x[5];
x[0] = path[0];
x[1] = ':';
x[2] = '\\';
x[3] = '\\';
x[4] = '\0';
return record(x);
}
std::filesystem::path p = std::filesystem::path(path);
if (::is_symlink(p)) {
auto split_map_name = fmt::format("{}split.map", SPLIT_PREFIX);
w.create(split_map_name.c_str());
w.write_string("BIN_WRITR_MGK");
{
std::filesystem::path copy = p;
trim = copy.remove_filename().string();
}
fmt::print("entering directory: {}\n", trim);
if (recordPath(p) == -1) {
_close();
return -1;
}
_close();
} else if (std::filesystem::is_directory(p)) {
auto split_map_name = fmt::format("{}split.map", SPLIT_PREFIX);
w.create(split_map_name.c_str());
w.write_string("BIN_WRITR_MGK");
trim = path;
if (trim[trim.length()] != '/') {
trim += "/";
} else {
trim += "/";
}
fmt::print("entering directory: {}\n", path);
std::filesystem::recursive_directory_iterator begin = std::filesystem::recursive_directory_iterator(p);
std::filesystem::recursive_directory_iterator end;
for (; begin != end; begin++) {
auto & fpath = *begin;
if (path_exists(fpath)) {
if (recordPath(fpath.path()) == -1) {
_close();
return -1;
}
}
else {
fmt::print("item does not exist: {}\n", fpath.path());
}
}
_close();
} else if (std::filesystem::is_regular_file(p)) {
auto split_map_name = fmt::format("{}split.map", SPLIT_PREFIX);
w.create(split_map_name.c_str());
w.write_string("BIN_WRITR_MGK");
{
std::filesystem::path copy = p;
trim = copy.remove_filename().string();
}
fmt::print("entering directory: {}\n", trim);
if (recordPath(p) == -1) {
_close();
return -1;
}
_close();
}
else {
fmt::print("unknown type: {}\n", &path[trim.length()]);
w.close();
return -1;
}
w.write_u64(SPLIT_SIZE);
w.write_string(SPLIT_PREFIX.c_str());
w.write_u64(bird_is_the_word_d.size());
w.write_u64(bird_is_the_word_f.size());
w.write_u64(total_chunk_count);
w.write_u64(max_file_chunks);
w.write_u64(split_number);
w.write_string(max_path.c_str());
w.write_string(max_perms_str.c_str());
w.write_u64(max_size);
w.write_u64(max_chunk);
size_t mfc = fmt::formatted_size("{}", max_file_chunks);
w.write_u64(bird_is_the_word_s.size());
if (remove_files) {
auto copy = bird_is_the_word_d;
std::reverse(copy.begin(), copy.end());
for (auto& d : copy) {
if (dry_run) {
auto paths = d.path.string();
fmt::print("rmdir {}\n", &paths[trim.length()]);
}
else {
try {
std::filesystem::remove(d.path);
}
catch (std::exception& e) {
auto paths = d.path.string();
fmt::print("failed to remove path: {}\n", &paths[trim.length()]);
}
}
}
}
for (auto& d : bird_is_the_word_d) {
recordPathDirectory(d, mfc);
}
for (auto& f : bird_is_the_word_f) {
recordPathFile(f, mfc);
}
for (auto& s : bird_is_the_word_s) {
recordPathSymlink(s, mfc);
}
w.close();
fmt::print("split size: {}\n", SPLIT_SIZE);
fmt::print("split prefix: {}\n", SPLIT_PREFIX);
fmt::print("directories recorded: {}\n", bird_is_the_word_d.size());
fmt::print("files recorded: {}\n", bird_is_the_word_f.size());
fmt::print("chunks recorded: {}\n", total_chunk_count);
fmt::print("split files recorded: {}\n", split_number+1);
fmt::print("symlinks recorded: {}\n", bird_is_the_word_s.size());
fmt::print("unknown types: {}\n", unknowns);
if (total >= 1000) {
fmt::print("total size of {: >{}} files: {: >{}} bytes ({})\n", bird_is_the_word_f.size(), fmt::formatted_size("{}", std::max(bird_is_the_word_f.size(), total_chunk_count)), total, fmt::formatted_size("{}", std::max(total, totalc)), make_human_readable_str(total));
} else {
fmt::print("total size of {: >{}} files: {: >{}} bytes\n", bird_is_the_word_f.size(), fmt::formatted_size("{}", std::max(bird_is_the_word_f.size(), total_chunk_count)), total, fmt::formatted_size("{}", std::max(total, totalc)));
}
if (totalc >= 1000) {
fmt::print("total size of {: >{}} chunks: {: >{}} bytes ({})\n", total_chunk_count, fmt::formatted_size("{}", std::max(bird_is_the_word_f.size(), total_chunk_count)), totalc, fmt::formatted_size("{}", std::max(total, totalc)), make_human_readable_str(totalc));
} else {
fmt::print("total size of {: >{}} chunks: {: >{}} bytes\n", total_chunk_count, fmt::formatted_size("{}", std::max(bird_is_the_word_f.size(), total_chunk_count)), totalc, fmt::formatted_size("{}", std::max(total, totalc)));
}
auto sz = max_size;
auto s = fmt::format("{: >{}} {}", sz, fmt::formatted_size("{}", max_size), sz >= 1000 ? fmt::format("({: >6})", make_human_readable_str(sz)) : " ");
fmt::print("largest file: {: >{}} {} {} ({: >{}} chunks) {}\n", "", fmt::formatted_size("{}", std::max(bird_is_the_word_f.size(), total_chunk_count)), max_perms_str, s, max_chunk, mfc, max_path);
return 0;
}
struct F {
FILE * f;
size_t size;
};
static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
F* file = (F*)userp;
size_t w = fwrite(contents, size, nmemb, file->f);
fflush(file->f);
file->size += w;
return w;
}
bool is_url(const char* url) {
return
strstr(url, "https://") == url ||
strstr(url, "http://") == url ||
strstr(url, "ftp://") == url ||
strstr(url, "ftps://") == url;
}
int download_url_(char* url, TempFileFILE & tmp) {
CURL* curl = nullptr;
char* location = strdup(url);
if (location == nullptr) {
throw std::bad_alloc();
}
char* locationNew = location;
long response_code = 0;
curl = curl_easy_init();
F f = { 0 };
f.f = tmp.get_handle();
if (curl) {
LOC:
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); // enable progress report
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); // fail on error
char errbuf[CURL_ERROR_SIZE] = { 0 };
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
#include "cacert.pem.h"
struct curl_blob pem_blob;
pem_blob.data = (void*)PEM.c_str();
pem_blob.len = PEM.length();
pem_blob.flags = CURL_BLOB_NOCOPY;
curl_easy_setopt(curl, CURLOPT_CAINFO, nullptr);
curl_easy_setopt(curl, CURLOPT_CAPATH, nullptr);
curl_easy_setopt(curl, CURLOPT_CAINFO_BLOB, &pem_blob);
curl_easy_setopt(curl, CURLOPT_URL, location);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&f);
/* some servers do not like requests that are made without a user-agent
field, so we provide one */
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
fflush(stdout);
fflush(stderr);
CURLcode res = curl_easy_perform(curl);
fflush(stdout);
fflush(stderr);
if (res != CURLE_OK) {
fmt::print("\ncurl_easy_perform() failed: {}\n{}\n", curl_easy_strerror(res), errbuf);
curl_easy_cleanup(curl);
free((void*)location);
return -1;
}
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (res != CURLE_OK) {
fmt::print("\ncurl_easy_getinfo(CURLINFO_RESPONSE_CODE) failed: {}\n{}\n", curl_easy_strerror(res), errbuf);
curl_easy_cleanup(curl);
free((void*)location);
return -1;
}
if ((response_code / 100) == 3) {
res = curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &locationNew);
if (res != CURLE_OK) {
fmt::print("\ncurl_easy_getinfo(CURLINFO_REDIRECT_URL) failed: {}\n{}\n", curl_easy_strerror(res), errbuf);
curl_easy_cleanup(curl);
free((void*)location);
return -1;
}
free((void*)location);
location = strdup(locationNew);
if (location == nullptr) {
throw std::bad_alloc();
}
goto LOC;
}
free((void*)location);
fmt::print("downloaded {} bytes -> {}\n", f.size, tmp.get_path());
fflush(stdout);
fflush(stderr);
}
else {
fmt::print("failed to initialize curl\n");
fflush(stdout);
fflush(stderr);
return -1;
}
fflush(stdout);
fflush(stderr);
return 0;
}
int download_url(const char * url, TempFileFILE & tmp) {
if (!is_url(url)) {
fmt::print("attempting to download a non-url\n");
return -1;
}
fmt::print("executing curl_global_init() ...\n");
CURLcode res = curl_global_init(CURL_GLOBAL_ALL);
if (res != CURLE_OK) {
fmt::print("curl_global_init() failed: {}\n", curl_easy_strerror(res));
return -1;
}
fmt::print("executed curl_global_init() ...\n");
char* p = strdup(url);
int r = download_url_(p, tmp);
free((void*)p);
fmt::print("executing curl_global_cleanup() ...\n");
curl_global_cleanup();
fmt::print("executed curl_global_cleanup() ...\n");
fflush(stdout);
fflush(stderr);
return r;
}
int playback_url(const char* url, bool join_files, bool list_chunks) {
if (!join_files) {
remove_files = true; // remove temporary downloaded temporary files if we are not joining them
}
if (join_files) {
if (path_exists(out_directory)) {
if (!dry_run) {
if (!std::filesystem::is_directory(out_directory)) {
fmt::print("cannot output to a non-directory: {}\n", out_directory);
return -1;
}
std::filesystem::directory_iterator begin = std::filesystem::directory_iterator(out_directory);
std::filesystem::directory_iterator end;
for (; begin != end; begin++) {
auto& fpath = *begin;
if (path_exists(fpath)) {
fmt::print("cannot output to a non-empty directory: {}\n", out_directory);
return -1;
}
}
}
}
else {
if (dry_run) {
fmt::print("mkdir {}\n", out_directory);
}
else {
fmt::print("creating output directory: {}\n", out_directory);
std::filesystem::create_directory(out_directory);
}
}
}
TempFileFILE tmp_split_map;
tmp_split_map.construct(TempFile::TempDir(), fmt::format("split.map.", TEMP_FILE_OPEN_MODE_READ | TEMP_FILE_OPEN_MODE_WRITE | TEMP_FILE_OPEN_MODE_BINARY), !remove_files);
const char* path = tmp_split_map.get_path().c_str();
fmt::print("downloading item: {}\n", url);
fmt::print("-> path: {}\n", path);
if (download_url(url, tmp_split_map) == -1) {
fmt::print("failed to download item: {}\n", url);
return -1;
}
fmt::print("downloaded item: {}\n", url);
fflush(stdout);
fflush(stderr);
fseek(tmp_split_map.get_handle(), 0, SEEK_SET);
auto parent = std::filesystem::canonical(std::filesystem::absolute(path));
if (!parent.has_parent_path()) {
fmt::print("cannot obtain parent directory of item: {}\n", parent);
return -1;
}