-
-
Notifications
You must be signed in to change notification settings - Fork 859
/
main.d
2094 lines (1920 loc) · 88.5 KB
/
main.d
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
import core.stdc.stdlib: EXIT_SUCCESS, EXIT_FAILURE, exit;
import core.memory, core.time, core.thread;
import std.getopt, std.file, std.path, std.process, std.stdio, std.conv, std.algorithm.searching, std.string, std.regex;
import config, itemdb, monitor, onedrive, selective, sync, util;
import std.net.curl: CurlException;
import core.stdc.signal;
import std.traits, std.format;
import std.concurrency: receiveTimeout;
import std.datetime;
static import log;
OneDriveApi oneDrive;
ItemDatabase itemDb;
bool onedriveInitialised = false;
const int EXIT_UNAUTHORIZED = 3;
const int EXIT_RESYNC_REQUIRED = 126;
enum MONITOR_LOG_SILENT = 2;
enum MONITOR_LOG_QUIET = 1;
enum LOG_NORMAL = 0;
int main(string[] args)
{
// Disable buffering on stdout
stdout.setvbuf(0, _IONBF);
// main function variables
string confdirOption;
string configFilePath;
string syncListFilePath;
string databaseFilePath;
string businessSharedFolderFilePath;
string currentConfigHash;
string currentSyncListHash;
string previousConfigHash;
string previousSyncListHash;
string configHashFile;
string syncListHashFile;
string configBackupFile;
string syncDir;
string logOutputMessage;
string currentBusinessSharedFoldersHash;
string previousBusinessSharedFoldersHash;
string businessSharedFoldersHashFile;
string databaseFilePathDryRunGlobal;
bool configOptionsDifferent = false;
bool businessSharedFoldersDifferent = false;
bool syncListConfigured = false;
bool syncListDifferent = false;
bool syncDirDifferent = false;
bool skipFileDifferent = false;
bool skipDirDifferent = false;
bool online = false;
bool performSyncOK = false;
bool displayMemoryUsage = false;
bool displaySyncOptions = false;
bool cleanupLocalFilesGlobal = false;
bool synchronizeConfigured = false;
bool invalidSyncExit = false;
// start and finish messages
string startMessage = "Starting a sync with OneDrive";
string finishMessage = "Sync with OneDrive is complete";
string helpMessage = "Please use 'onedrive --help' for further assistance in regards to running this application.";
// hash file permission values
string hashPermissionValue = "600";
auto convertedPermissionValue = parse!long(hashPermissionValue, 8);
// Define scopes
scope(exit) {
// detail what scope was called
log.vdebug("Exit scope called");
if (synchronizeConfigured) {
log.log(finishMessage);
}
// Display memory details
if (displayMemoryUsage) {
log.displayMemoryUsagePreGC();
}
// if initialised, shut down the HTTP instance
if (onedriveInitialised) {
oneDrive.shutdown();
}
// was itemDb initialised?
if (itemDb !is null) {
// Make sure the .wal file is incorporated into the main db before we exit
if(!invalidSyncExit) {
itemDb.performVacuum();
}
destroy(itemDb);
}
// cleanup any dry-run data
cleanupDryRunDatabase(databaseFilePathDryRunGlobal);
// free API instance
if (oneDrive !is null) {
destroy(oneDrive);
}
// Perform Garbage Cleanup
GC.collect();
// Display memory details
if (displayMemoryUsage) {
log.displayMemoryUsagePostGC();
}
}
scope(failure) {
// detail what scope was called
log.vdebug("Failure scope called");
// Display memory details
if (displayMemoryUsage) {
log.displayMemoryUsagePreGC();
}
// if initialised, shut down the HTTP instance
if (onedriveInitialised) {
oneDrive.shutdown();
}
// was itemDb initialised?
if (itemDb !is null) {
// Make sure the .wal file is incorporated into the main db before we exit
if(!invalidSyncExit) {
itemDb.performVacuum();
}
destroy(itemDb);
}
// cleanup any dry-run data
cleanupDryRunDatabase(databaseFilePathDryRunGlobal);
// free API instance
if (oneDrive !is null) {
destroy(oneDrive);
}
// Perform Garbage Cleanup
GC.collect();
// Display memory details
if (displayMemoryUsage) {
log.displayMemoryUsagePostGC();
}
}
// read in application options as passed in
try {
bool printVersion = false;
auto opt = getopt(
args,
std.getopt.config.passThrough,
std.getopt.config.bundling,
std.getopt.config.caseSensitive,
"confdir", "Set the directory used to store the configuration files", &confdirOption,
"verbose|v+", "Print more details, useful for debugging (repeat for extra debugging)", &log.verbose,
"version", "Print the version and exit", &printVersion
);
// print help and exit
if (opt.helpWanted) {
args ~= "--help";
}
// print the version and exit
if (printVersion) {
writeln("onedrive ", strip(import("version")));
return EXIT_SUCCESS;
}
} catch (GetOptException e) {
// option errors
log.error(e.msg);
log.error("Try 'onedrive --help' for more information");
return EXIT_FAILURE;
} catch (Exception e) {
// generic error
log.error(e.msg);
log.error("Try 'onedrive --help' for more information");
return EXIT_FAILURE;
}
// confdirOption must be a directory, not a file
// - By default ~/.config/onedrive will be used
// - If the user is using --confdir , the confdirOption needs to be evaluated when trying to load any file
// load configuration file if available
auto cfg = new config.Config(confdirOption);
if (!cfg.initialize()) {
// There was an error loading the configuration
// Error message already printed
return EXIT_FAILURE;
}
// How was this application started - what options were passed in
log.vdebug("passed in options: ", args);
log.vdebug("note --confdir and --verbose not listed in args");
// set memory display
displayMemoryUsage = cfg.getValueBool("display_memory");
// set display sync options
displaySyncOptions = cfg.getValueBool("display_sync_options");
// update configuration from command line args
cfg.update_from_args(args);
// --resync should be a 'last resort item' .. the user needs to 'accept' to proceed
if ((cfg.getValueBool("resync")) && (!cfg.getValueBool("display_config"))) {
// what is the risk acceptance?
bool resyncRiskAcceptance = false;
if (!cfg.getValueBool("resync_auth")) {
// need to prompt user
char response;
// warning message
writeln("\nThe use of --resync will remove your local 'onedrive' client state, thus no record will exist regarding your current 'sync status'");
writeln("This has the potential to overwrite local versions of files with potentially older versions downloaded from OneDrive which can lead to data loss");
writeln("If in-doubt, backup your local data first before proceeding with --resync");
write("\nAre you sure you wish to proceed with --resync? [Y/N] ");
try {
// Attempt to read user response
readf(" %c\n", &response);
} catch (std.format.FormatException e) {
// Caught an error
return EXIT_FAILURE;
}
// Evaluate user repsonse
if ((to!string(response) == "y") || (to!string(response) == "Y")) {
// User has accepted --resync risk to proceed
resyncRiskAcceptance = true;
// Are you sure you wish .. does not use writeln();
write("\n");
}
} else {
// resync_auth is true
resyncRiskAcceptance = true;
}
// Action based on response
if (!resyncRiskAcceptance){
// --resync risk not accepted
return EXIT_FAILURE;
}
}
// Initialise normalised file paths
configFilePath = buildNormalizedPath(cfg.configDirName ~ "/config");
syncListFilePath = buildNormalizedPath(cfg.configDirName ~ "/sync_list");
databaseFilePath = buildNormalizedPath(cfg.configDirName ~ "/items.db");
businessSharedFolderFilePath = buildNormalizedPath(cfg.configDirName ~ "/business_shared_folders");
// Has any of our configuration that would require a --resync been changed?
// 1. sync_list file modification
// 2. config file modification - but only if sync_dir, skip_dir, skip_file or drive_id was modified
// 3. CLI input overriding configured config file option
configHashFile = buildNormalizedPath(cfg.configDirName ~ "/.config.hash");
syncListHashFile = buildNormalizedPath(cfg.configDirName ~ "/.sync_list.hash");
configBackupFile = buildNormalizedPath(cfg.configDirName ~ "/.config.backup");
businessSharedFoldersHashFile = buildNormalizedPath(cfg.configDirName ~ "/.business_shared_folders.hash");
// Does a 'config' file exist with a valid hash file
if (exists(configFilePath)) {
if (!exists(configHashFile)) {
// hash of config file needs to be created, but only if we are not in a --resync scenario
if (!cfg.getValueBool("resync")) {
std.file.write(configHashFile, "initial-hash");
// Hash file should only be readable by the user who created it - 0600 permissions needed
configHashFile.setAttributes(to!int(convertedPermissionValue));
}
}
} else {
// no 'config' file exists, application defaults being used, no hash file required
if (exists(configHashFile)) {
// remove the hash, but only if --resync was issued as now the application will use 'defaults' which 'may' be different
if (cfg.getValueBool("resync")) {
// resync issued, remove hash files
safeRemove(configHashFile);
safeRemove(configBackupFile);
}
}
}
// Does a 'sync_list' file exist with a valid hash file
if (exists(syncListFilePath)) {
if (!exists(syncListHashFile)) {
// hash of config file needs to be created, but only if we are not in a --resync scenario
if (!cfg.getValueBool("resync")) {
std.file.write(syncListHashFile, "initial-hash");
// Hash file should only be readable by the user who created it - 0600 permissions needed
syncListHashFile.setAttributes(to!int(convertedPermissionValue));
}
}
} else {
// no 'sync_list' file exists, no hash file required
if (exists(syncListHashFile)) {
// remove the hash, but only if --resync was issued as now the application will use 'defaults' which 'may' be different
if (cfg.getValueBool("resync")) {
// resync issued, remove hash files
safeRemove(syncListHashFile);
}
}
}
// Does a 'business_shared_folders' file exist with a valid hash file
if (exists(businessSharedFolderFilePath)) {
if (!exists(businessSharedFoldersHashFile)) {
// hash of config file needs to be created, but only if we are not in a --resync scenario
if (!cfg.getValueBool("resync")) {
std.file.write(businessSharedFoldersHashFile, "initial-hash");
// Hash file should only be readable by the user who created it - 0600 permissions needed
businessSharedFoldersHashFile.setAttributes(to!int(convertedPermissionValue));
}
}
} else {
// no 'business_shared_folders' file exists, no hash file required
if (exists(businessSharedFoldersHashFile)) {
// remove the hash, but only if --resync was issued as now the application will use 'defaults' which 'may' be different
if (cfg.getValueBool("resync")) {
// resync issued, remove hash files
safeRemove(businessSharedFoldersHashFile);
}
}
}
// Generate current hashes for the relevant configuration files if they exist
if (exists(configFilePath)) currentConfigHash = computeQuickXorHash(configFilePath);
if (exists(syncListFilePath)) currentSyncListHash = computeQuickXorHash(syncListFilePath);
if (exists(businessSharedFolderFilePath)) currentBusinessSharedFoldersHash = computeQuickXorHash(businessSharedFolderFilePath);
// read the existing hashes for each of the relevant configuration files if they exist
if (exists(configHashFile)) {
try {
previousConfigHash = readText(configHashFile);
} catch (std.file.FileException e) {
// Unable to access required file
log.error("ERROR: Unable to access ", e.msg);
// Use exit scopes to shutdown API
return EXIT_FAILURE;
}
}
if (exists(syncListHashFile)) {
try {
previousSyncListHash = readText(syncListHashFile);
} catch (std.file.FileException e) {
// Unable to access required file
log.error("ERROR: Unable to access ", e.msg);
// Use exit scopes to shutdown API
return EXIT_FAILURE;
}
}
if (exists(businessSharedFoldersHashFile)) {
try {
previousBusinessSharedFoldersHash = readText(businessSharedFoldersHashFile);
} catch (std.file.FileException e) {
// Unable to access required file
log.error("ERROR: Unable to access ", e.msg);
// Use exit scopes to shutdown API
return EXIT_FAILURE;
}
}
// Was sync_list file updated?
if (currentSyncListHash != previousSyncListHash) {
// Debugging output to assist what changed
log.vdebug("sync_list file has been updated, --resync needed");
syncListDifferent = true;
}
// Was business_shared_folders updated?
if (currentBusinessSharedFoldersHash != previousBusinessSharedFoldersHash) {
// Debugging output to assist what changed
log.vdebug("business_shared_folders file has been updated, --resync needed");
businessSharedFoldersDifferent = true;
}
// Was config file updated between last execution ang this execution?
if (currentConfigHash != previousConfigHash) {
// config file was updated, however we only want to trigger a --resync requirement if sync_dir, skip_dir, skip_file or drive_id was modified
if (!cfg.getValueBool("display_config")){
// only print this message if we are not using --display-config
log.log("config file has been updated, checking if --resync needed");
}
if (exists(configBackupFile)) {
// check backup config what has changed for these configuration options if anything
// # sync_dir = "~/OneDrive"
// # skip_file = "~*|.~*|*.tmp"
// # skip_dir = ""
// # drive_id = ""
string[string] stringValues;
stringValues["sync_dir"] = "";
stringValues["skip_file"] = "";
stringValues["skip_dir"] = "";
stringValues["drive_id"] = "";
auto configBackupFileHandle = File(configBackupFile, "r");
string lineBuffer;
auto range = configBackupFileHandle.byLine();
// read configBackupFile line by line
foreach (line; range) {
lineBuffer = stripLeft(line).to!string;
if (lineBuffer.length == 0 || lineBuffer[0] == ';' || lineBuffer[0] == '#') continue;
auto c = lineBuffer.matchFirst(cfg.configRegex);
if (!c.empty) {
c.popFront(); // skip the whole match
string key = c.front.dup;
auto p = key in stringValues;
if (p) {
c.popFront();
// compare this key
if ((key == "sync_dir") && (c.front.dup != cfg.getValueString("sync_dir"))) {
log.vdebug(key, " was modified since the last time the application was successfully run, --resync needed");
configOptionsDifferent = true;
}
if ((key == "skip_file") && (c.front.dup != cfg.getValueString("skip_file"))){
log.vdebug(key, " was modified since the last time the application was successfully run, --resync needed");
configOptionsDifferent = true;
}
if ((key == "skip_dir") && (c.front.dup != cfg.getValueString("skip_dir"))){
log.vdebug(key, " was modified since the last time the application was successfully run, --resync needed");
configOptionsDifferent = true;
}
if ((key == "drive_id") && (c.front.dup != cfg.getValueString("drive_id"))){
log.vdebug(key, " was modified since the last time the application was successfully run, --resync needed");
configOptionsDifferent = true;
}
}
}
}
// close file if open
if (configBackupFileHandle.isOpen()){
// close open file
configBackupFileHandle.close();
}
} else {
// no backup to check
log.vdebug("WARNING: no backup config file was found, unable to validate if any changes made");
}
// If there was a backup, any modified values we need to worry about would been detected
if (!cfg.getValueBool("display_config")) {
// we are not testing the configuration
if (!configOptionsDifferent) {
// no options are different
if (!cfg.getValueBool("dry_run")) {
// we are not in a dry-run scenario
// update config hash
log.vdebug("updating config hash as it is out of date");
std.file.write(configHashFile, computeQuickXorHash(configFilePath));
// Hash file should only be readable by the user who created it - 0600 permissions needed
configHashFile.setAttributes(to!int(convertedPermissionValue));
// create backup copy of current config file
log.vdebug("making backup of config file as it is out of date");
std.file.copy(configFilePath, configBackupFile);
// File Copy should only be readable by the user who created it - 0600 permissions needed
configBackupFile.setAttributes(to!int(convertedPermissionValue));
}
}
}
}
// Is there a backup of the config file if the config file exists?
if ((exists(configFilePath)) && (!exists(configBackupFile))) {
// create backup copy of current config file
std.file.copy(configFilePath, configBackupFile);
// File Copy should only be readable by the user who created it - 0600 permissions needed
configBackupFile.setAttributes(to!int(convertedPermissionValue));
}
// config file set options can be changed via CLI input, specifically these will impact sync and --resync will be needed:
// --syncdir ARG
// --skip-file ARG
// --skip-dir ARG
if (exists(configFilePath)) {
// config file exists
// was the sync_dir updated by CLI?
if (cfg.configFileSyncDir != "") {
// sync_dir was set in config file
if (cfg.configFileSyncDir != cfg.getValueString("sync_dir")) {
// config file was set and CLI input changed this
log.vdebug("sync_dir: CLI override of config file option, --resync needed");
syncDirDifferent = true;
}
}
// was the skip_file updated by CLI?
if (cfg.configFileSkipFile != "") {
// skip_file was set in config file
if (cfg.configFileSkipFile != cfg.getValueString("skip_file")) {
// config file was set and CLI input changed this
log.vdebug("skip_file: CLI override of config file option, --resync needed");
skipFileDifferent = true;
}
}
// was the skip_dir updated by CLI?
if (cfg.configFileSkipDir != "") {
// skip_dir was set in config file
if (cfg.configFileSkipDir != cfg.getValueString("skip_dir")) {
// config file was set and CLI input changed this
log.vdebug("skip_dir: CLI override of config file option, --resync needed");
skipDirDifferent = true;
}
}
}
// Has anything triggered a --resync requirement?
if (configOptionsDifferent || syncListDifferent || syncDirDifferent || skipFileDifferent || skipDirDifferent || businessSharedFoldersDifferent) {
// --resync needed, is the user performing any operation where a --resync is not required?
// flag to ignore --resync requirement
bool ignoreResyncRequirement = false;
// These flags do not need --resync as no sync operation is needed: --display-config, --list-shared-folders, --get-O365-drive-id, --get-file-link
if (cfg.getValueBool("display_config")) ignoreResyncRequirement = true;
if (cfg.getValueBool("list_business_shared_folders")) ignoreResyncRequirement = true;
if ((!cfg.getValueString("get_o365_drive_id").empty)) ignoreResyncRequirement = true;
if ((!cfg.getValueString("get_file_link").empty)) ignoreResyncRequirement = true;
// Do we need to ignore a --resync requirement?
if (!ignoreResyncRequirement) {
// We are not ignoring --requirement
if (!cfg.getValueBool("resync")) {
// --resync not issued, fail fast
log.error("An application configuration change has been detected where a --resync is required");
return EXIT_RESYNC_REQUIRED;
} else {
// --resync issued, update hashes of config files if they exist
if (!cfg.getValueBool("dry_run")) {
// not doing a dry run, update hash files if config & sync_list exist
if (exists(configFilePath)) {
// update hash
log.vdebug("updating config hash as --resync issued");
std.file.write(configHashFile, computeQuickXorHash(configFilePath));
// Hash file should only be readable by the user who created it - 0600 permissions needed
configHashFile.setAttributes(to!int(convertedPermissionValue));
// create backup copy of current config file
log.vdebug("making backup of config file as --resync issued");
std.file.copy(configFilePath, configBackupFile);
// File copy should only be readable by the user who created it - 0600 permissions needed
configBackupFile.setAttributes(to!int(convertedPermissionValue));
}
if (exists(syncListFilePath)) {
// update sync_list hash
log.vdebug("updating sync_list hash as --resync issued");
std.file.write(syncListHashFile, computeQuickXorHash(syncListFilePath));
// Hash file should only be readable by the user who created it - 0600 permissions needed
syncListHashFile.setAttributes(to!int(convertedPermissionValue));
}
if (exists(businessSharedFolderFilePath)) {
// update business_shared_folders hash
log.vdebug("updating business_shared_folders hash as --resync issued");
std.file.write(businessSharedFoldersHashFile, computeQuickXorHash(businessSharedFolderFilePath));
// Hash file should only be readable by the user who created it - 0600 permissions needed
businessSharedFoldersHashFile.setAttributes(to!int(convertedPermissionValue));
}
}
}
}
}
// --dry-run operation notification and database setup
// Are we performing any of the following operations?
// --dry-run, --list-shared-folders, --get-O365-drive-id, --get-file-link
if ((cfg.getValueBool("dry_run")) || (cfg.getValueBool("list_business_shared_folders")) || (!cfg.getValueString("get_o365_drive_id").empty) || (!cfg.getValueString("get_file_link").empty)) {
// is this a --list-shared-folders, --get-O365-drive-id, --get-file-link operation
if (cfg.getValueBool("dry_run")) {
// this is a --dry-run operation
log.log("DRY-RUN Configured. Output below shows what 'would' have occurred.");
} else {
// is this a --list-shared-folders, --get-O365-drive-id, --get-file-link operation
log.log("Using dry-run database copy for OneDrive API query");
}
// configure databaseFilePathDryRunGlobal
databaseFilePathDryRunGlobal = cfg.databaseFilePathDryRun;
string dryRunShmFile = databaseFilePathDryRunGlobal ~ "-shm";
string dryRunWalFile = databaseFilePathDryRunGlobal ~ "-wal";
// If the dry run database exists, clean this up
if (exists(databaseFilePathDryRunGlobal)) {
// remove the existing file
log.vdebug("Removing items-dryrun.sqlite3 as it still exists for some reason");
safeRemove(databaseFilePathDryRunGlobal);
}
// silent cleanup of shm and wal files if they exist
if (exists(dryRunShmFile)) {
// remove items-dryrun.sqlite3-shm
safeRemove(dryRunShmFile);
}
if (exists(dryRunWalFile)) {
// remove items-dryrun.sqlite3-wal
safeRemove(dryRunWalFile);
}
// Make a copy of the original items.sqlite3 for use as the dry run copy if it exists
if (exists(cfg.databaseFilePath)) {
// in a --dry-run --resync scenario, we should not copy the existing database file
if (!cfg.getValueBool("resync")) {
// copy the existing DB file to the dry-run copy
log.vdebug("Copying items.sqlite3 to items-dryrun.sqlite3 to use for dry run operations");
copy(cfg.databaseFilePath,databaseFilePathDryRunGlobal);
} else {
// no database copy due to --resync
log.vdebug("No database copy created for --dry-run due to --resync also being used");
}
}
}
// sync_dir environment handling to handle ~ expansion properly
bool shellEnvSet = false;
if ((environment.get("SHELL") == "") && (environment.get("USER") == "")){
log.vdebug("sync_dir: No SHELL or USER environment variable configuration detected");
// No shell or user set, so expandTilde() will fail - usually headless system running under init.d / systemd or potentially Docker
// Does the 'currently configured' sync_dir include a ~
if (canFind(cfg.getValueString("sync_dir"), "~")) {
// A ~ was found in sync_dir
log.vdebug("sync_dir: A '~' was found in sync_dir, using the calculated 'homePath' to replace '~' as no SHELL or USER environment variable set");
syncDir = cfg.homePath ~ strip(cfg.getValueString("sync_dir"), "~");
} else {
// No ~ found in sync_dir, use as is
log.vdebug("sync_dir: Getting syncDir from config value sync_dir");
syncDir = cfg.getValueString("sync_dir");
}
} else {
// A shell and user is set, expand any ~ as this will be expanded correctly if present
shellEnvSet = true;
log.vdebug("sync_dir: Getting syncDir from config value sync_dir");
if (canFind(cfg.getValueString("sync_dir"), "~")) {
log.vdebug("sync_dir: A '~' was found in configured sync_dir, automatically expanding as SHELL and USER environment variable is set");
syncDir = expandTilde(cfg.getValueString("sync_dir"));
} else {
syncDir = cfg.getValueString("sync_dir");
}
}
// vdebug syncDir as set and calculated
log.vdebug("syncDir: ", syncDir);
// Configure the logging directory if different from application default
// log_dir environment handling to handle ~ expansion properly
string logDir = cfg.getValueString("log_dir");
if (logDir != cfg.defaultLogFileDir) {
// user modified log_dir entry
// if 'log_dir' contains a '~' this needs to be expanded correctly
if (canFind(cfg.getValueString("log_dir"), "~")) {
// ~ needs to be expanded correctly
if (!shellEnvSet) {
// No shell or user set, so expandTilde() will fail - usually headless system running under init.d / systemd or potentially Docker
log.vdebug("log_dir: A '~' was found in log_dir, using the calculated 'homePath' to replace '~' as no SHELL or USER environment variable set");
logDir = cfg.homePath ~ strip(cfg.getValueString("log_dir"), "~");
} else {
// A shell and user is set, expand any ~ as this will be expanded correctly if present
log.vdebug("log_dir: A '~' was found in log_dir, using SHELL or USER environment variable to expand '~'");
logDir = expandTilde(cfg.getValueString("log_dir"));
}
} else {
// '~' not found in log_dir entry, use as is
logDir = cfg.getValueString("log_dir");
}
// update log_dir with normalised path, with '~' expanded correctly
cfg.setValueString("log_dir", logDir);
}
// Configure logging only if enabled
if (cfg.getValueBool("enable_logging")){
// Initialise using the configured logging directory
log.vlog("Using logfile dir: ", logDir);
log.init(logDir);
}
// Configure whether notifications are used
log.setNotifications(cfg.getValueBool("monitor") && !cfg.getValueBool("disable_notifications"));
// Application upgrades - skilion version etc
if (exists(databaseFilePath)) {
if (!cfg.getValueBool("dry_run")) {
safeRemove(databaseFilePath);
}
log.logAndNotify("Database schema changed, resync needed");
cfg.setValueBool("resync", true);
}
// Handle --logout as separate item, do not 'resync' on a --logout
if (cfg.getValueBool("logout")) {
log.vdebug("--logout requested");
log.log("Deleting the saved authentication status ...");
if (!cfg.getValueBool("dry_run")) {
safeRemove(cfg.refreshTokenFilePath);
}
// Exit
return EXIT_SUCCESS;
}
// Handle --reauth to re-authenticate the client
if (cfg.getValueBool("reauth")) {
log.vdebug("--reauth requested");
log.log("Deleting the saved authentication status ... re-authentication requested");
if (!cfg.getValueBool("dry_run")) {
safeRemove(cfg.refreshTokenFilePath);
}
}
// Display current application configuration
if ((cfg.getValueBool("display_config")) || (cfg.getValueBool("display_running_config"))) {
if (cfg.getValueBool("display_running_config")) {
writeln("--------------- Application Runtime Configuration ---------------");
}
// Display application version
writeln("onedrive version = ", strip(import("version")));
// Display all of the pertinent configuration options
writeln("Config path = ", cfg.configDirName);
// Does a config file exist or are we using application defaults
writeln("Config file found in config path = ", exists(configFilePath));
// Is config option drive_id configured?
if (cfg.getValueString("drive_id") != ""){
writeln("Config option 'drive_id' = ", cfg.getValueString("drive_id"));
}
// Config Options as per 'config' file
writeln("Config option 'sync_dir' = ", syncDir);
// logging and notifications
writeln("Config option 'enable_logging' = ", cfg.getValueBool("enable_logging"));
writeln("Config option 'log_dir' = ", cfg.getValueString("log_dir"));
writeln("Config option 'disable_notifications' = ", cfg.getValueBool("disable_notifications"));
writeln("Config option 'min_notify_changes' = ", cfg.getValueLong("min_notify_changes"));
// skip files and directory and 'matching' policy
writeln("Config option 'skip_dir' = ", cfg.getValueString("skip_dir"));
writeln("Config option 'skip_dir_strict_match' = ", cfg.getValueBool("skip_dir_strict_match"));
writeln("Config option 'skip_file' = ", cfg.getValueString("skip_file"));
writeln("Config option 'skip_dotfiles' = ", cfg.getValueBool("skip_dotfiles"));
writeln("Config option 'skip_symlinks' = ", cfg.getValueBool("skip_symlinks"));
// --monitor sync process options
writeln("Config option 'monitor_interval' = ", cfg.getValueLong("monitor_interval"));
writeln("Config option 'monitor_log_frequency' = ", cfg.getValueLong("monitor_log_frequency"));
writeln("Config option 'monitor_fullscan_frequency' = ", cfg.getValueLong("monitor_fullscan_frequency"));
// sync process and method
writeln("Config option 'read_only_auth_scope' = ", cfg.getValueBool("read_only_auth_scope"));
writeln("Config option 'dry_run' = ", cfg.getValueBool("dry_run"));
writeln("Config option 'upload_only' = ", cfg.getValueBool("upload_only"));
writeln("Config option 'download_only' = ", cfg.getValueBool("download_only"));
writeln("Config option 'local_first' = ", cfg.getValueBool("local_first"));
writeln("Config option 'check_nosync' = ", cfg.getValueBool("check_nosync"));
writeln("Config option 'check_nomount' = ", cfg.getValueBool("check_nomount"));
writeln("Config option 'resync' = ", cfg.getValueBool("resync"));
writeln("Config option 'resync_auth' = ", cfg.getValueBool("resync_auth"));
writeln("Config option 'cleanup_local_files' = ", cfg.getValueBool("cleanup_local_files"));
// data integrity
writeln("Config option 'classify_as_big_delete' = ", cfg.getValueLong("classify_as_big_delete"));
writeln("Config option 'disable_upload_validation' = ", cfg.getValueBool("disable_upload_validation"));
writeln("Config option 'bypass_data_preservation' = ", cfg.getValueBool("bypass_data_preservation"));
writeln("Config option 'no_remote_delete' = ", cfg.getValueBool("no_remote_delete"));
writeln("Config option 'remove_source_files' = ", cfg.getValueBool("remove_source_files"));
writeln("Config option 'sync_dir_permissions' = ", cfg.getValueLong("sync_dir_permissions"));
writeln("Config option 'sync_file_permissions' = ", cfg.getValueLong("sync_file_permissions"));
writeln("Config option 'space_reservation' = ", cfg.getValueLong("space_reservation"));
// curl operations
writeln("Config option 'application_id' = ", cfg.getValueString("application_id"));
writeln("Config option 'azure_ad_endpoint' = ", cfg.getValueString("azure_ad_endpoint"));
writeln("Config option 'azure_tenant_id' = ", cfg.getValueString("azure_tenant_id"));
writeln("Config option 'user_agent' = ", cfg.getValueString("user_agent"));
writeln("Config option 'force_http_11' = ", cfg.getValueBool("force_http_11"));
writeln("Config option 'debug_https' = ", cfg.getValueBool("debug_https"));
writeln("Config option 'rate_limit' = ", cfg.getValueLong("rate_limit"));
writeln("Config option 'operation_timeout' = ", cfg.getValueLong("operation_timeout"));
writeln("Config option 'dns_timeout' = ", cfg.getValueLong("dns_timeout"));
writeln("Config option 'connect_timeout' = ", cfg.getValueLong("connect_timeout"));
writeln("Config option 'data_timeout' = ", cfg.getValueLong("data_timeout"));
writeln("Config option 'ip_protocol_version' = ", cfg.getValueLong("ip_protocol_version"));
// Is sync_list configured ?
writeln("Config option 'sync_root_files' = ", cfg.getValueBool("sync_root_files"));
if (exists(syncListFilePath)){
writeln("Selective sync 'sync_list' configured = true");
writeln("sync_list contents:");
// Output the sync_list contents
auto syncListFile = File(syncListFilePath, "r");
auto range = syncListFile.byLine();
foreach (line; range)
{
writeln(line);
}
} else {
writeln("Selective sync 'sync_list' configured = false");
}
// Is business_shared_folders enabled and configured ?
writeln("Config option 'sync_business_shared_folders' = ", cfg.getValueBool("sync_business_shared_folders"));
if (exists(businessSharedFolderFilePath)){
writeln("Business Shared Folders configured = true");
writeln("business_shared_folders contents:");
// Output the business_shared_folders contents
auto businessSharedFolderFileList = File(businessSharedFolderFilePath, "r");
auto range = businessSharedFolderFileList.byLine();
foreach (line; range)
{
writeln(line);
}
} else {
writeln("Business Shared Folders configured = false");
}
// Are webhooks enabled?
writeln("Config option 'webhook_enabled' = ", cfg.getValueBool("webhook_enabled"));
if (cfg.getValueBool("webhook_enabled")) {
writeln("Config option 'webhook_public_url' = ", cfg.getValueString("webhook_public_url"));
writeln("Config option 'webhook_listening_host' = ", cfg.getValueString("webhook_listening_host"));
writeln("Config option 'webhook_listening_port' = ", cfg.getValueLong("webhook_listening_port"));
writeln("Config option 'webhook_expiration_interval' = ", cfg.getValueLong("webhook_expiration_interval"));
writeln("Config option 'webhook_renewal_interval' = ", cfg.getValueLong("webhook_renewal_interval"));
}
if (cfg.getValueBool("display_running_config")) {
writeln("-----------------------------------------------------------------");
}
// Do we exit? We only exit if --display-config has been used
if (cfg.getValueBool("display_config")) {
return EXIT_SUCCESS;
}
}
// --upload-only and --download-only are mutually exclusive and cannot be used together
if ((cfg.getValueBool("upload_only")) && (cfg.getValueBool("download_only"))) {
// both cannot be true at the same time
writeln("ERROR: --upload-only and --download-only are mutually exclusive and cannot be used together.\n");
return EXIT_FAILURE;
}
// Handle the actual --resync to remove local files
if (cfg.getValueBool("resync")) {
log.vdebug("--resync requested");
log.vdebug("Testing if we have exclusive access to local database file");
// Are we the only running instance? Test that we can open the database file path
itemDb = new ItemDatabase(cfg.databaseFilePath);
// did we successfully initialise the database class?
if (!itemDb.isDatabaseInitialised()) {
// no .. destroy class
itemDb = null;
// exit application
return EXIT_FAILURE;
}
// If we have exclusive access we will not have exited
// destroy access test
destroy(itemDb);
// delete application sync state
log.log("Deleting the saved application sync status ...");
if (!cfg.getValueBool("dry_run")) {
safeRemove(cfg.databaseFilePath);
safeRemove(cfg.deltaLinkFilePath);
safeRemove(cfg.uploadStateFilePath);
}
}
// Test if OneDrive service can be reached, exit if it cant be reached
log.vdebug("Testing network to ensure network connectivity to Microsoft OneDrive Service");
online = testNetwork(cfg);
if (!online) {
// Cant initialise the API as we are not online
if (!cfg.getValueBool("monitor")) {
// Running as --synchronize
log.error("Unable to reach Microsoft OneDrive API service, unable to initialize application\n");
return EXIT_FAILURE;
} else {
// Running as --monitor
log.error("Unable to reach Microsoft OneDrive API service at this point in time, re-trying network tests\n");
// re-try network connection to OneDrive
// https://github.com/abraunegg/onedrive/issues/1184
// Back off & retry with incremental delay
int retryCount = 10000;
int retryAttempts = 1;
int backoffInterval = 1;
int maxBackoffInterval = 3600;
bool retrySuccess = false;
while (!retrySuccess){
// retry to access OneDrive API
backoffInterval++;
int thisBackOffInterval = retryAttempts*backoffInterval;
log.vdebug(" Retry Attempt: ", retryAttempts);
if (thisBackOffInterval <= maxBackoffInterval) {
log.vdebug(" Retry In (seconds): ", thisBackOffInterval);
Thread.sleep(dur!"seconds"(thisBackOffInterval));
} else {
log.vdebug(" Retry In (seconds): ", maxBackoffInterval);
Thread.sleep(dur!"seconds"(maxBackoffInterval));
}
// perform the re-rty
online = testNetwork(cfg);
if (online) {
// We are now online
log.log("Internet connectivity to Microsoft OneDrive service has been restored");
retrySuccess = true;
} else {
// We are still offline
if (retryAttempts == retryCount) {
// we have attempted to re-connect X number of times
// false set this to true to break out of while loop
retrySuccess = true;
}
}
// Increment & loop around
retryAttempts++;
}
if (!online) {
// Not online after 1.2 years of trying
log.error("ERROR: Was unable to reconnect to the Microsoft OneDrive service after 10000 attempts lasting over 1.2 years!");
return EXIT_FAILURE;
}
}
}
// Check application version and Initialize OneDrive API, check for authorization
if (online) {
// Check Application Version
log.vlog("Checking Application Version ...");
checkApplicationVersion();
// we can only initialise if we are online
log.vlog("Initializing the OneDrive API ...");
oneDrive = new OneDriveApi(cfg);
onedriveInitialised = oneDrive.init();
oneDrive.printAccessToken = cfg.getValueBool("print_token");
}
if (!onedriveInitialised) {
log.error("Could not initialize the OneDrive API");
// Use exit scopes to shutdown API
return EXIT_UNAUTHORIZED;
}
// if --synchronize or --monitor not passed in, configure the flag to display help & exit
if (cfg.getValueBool("synchronize") || cfg.getValueBool("monitor")) {
performSyncOK = true;
}
// --source-directory must only be used with --destination-directory
// neither can (or should) be added individually as they have a no operational impact if they are
if (((cfg.getValueString("source_directory") == "") && (cfg.getValueString("destination_directory") != "")) || ((cfg.getValueString("source_directory") != "") && (cfg.getValueString("destination_directory") == ""))) {
// so either --source-directory or --destination-directory was passed in, without the other required item being passed in
// --source-directory or --destination-directory cannot be used with --synchronize or --monitor
writeln();
if (performSyncOK) {
// log an error
log.error("ERROR: --source-directory or --destination-directory cannot be used with --synchronize or --monitor");
} else {
// display issue with using these options
string emptyParameter;
string dataParameter;
if (cfg.getValueString("source_directory").empty) {
emptyParameter = "--source-directory";
dataParameter = "--destination-directory";
} else {
emptyParameter = "--destination-directory";
dataParameter = "--source-directory";
}
log.error("ERROR: " ~ dataParameter ~ " was passed in without also using " ~ emptyParameter);
}
// Use exit scopes to shutdown API
writeln();
log.error(helpMessage);
writeln();
return EXIT_FAILURE;
}
// --create-directory, --remove-directory, --source-directory, --destination-directory
// these are activities that dont perform a sync, so to not generate an error message for these items either
if (((cfg.getValueString("create_directory") != "") || (cfg.getValueString("remove_directory") != "")) || ((cfg.getValueString("source_directory") != "") && (cfg.getValueString("destination_directory") != "")) || (cfg.getValueString("get_file_link") != "") || (cfg.getValueString("modified_by") != "") || (cfg.getValueString("create_share_link") != "") || (cfg.getValueString("get_o365_drive_id") != "") || cfg.getValueBool("display_sync_status") || cfg.getValueBool("list_business_shared_folders")) {
performSyncOK = true;
}
// Were acceptable sync operations provided? Was --synchronize or --monitor passed in
if (!performSyncOK) {
// was the application just authorised?
if (cfg.applicationAuthorizeResponseUri) {
// Application was just authorised
if (exists(cfg.refreshTokenFilePath)) {
// OneDrive refresh token exists
log.log("\nApplication has been successfully authorised, however no additional command switches were provided.\n");
log.log(helpMessage);
writeln();
// Use exit scopes to shutdown API
return EXIT_SUCCESS;
} else {
// we just authorised, but refresh_token does not exist .. probably an auth error
log.log("\nApplication has not been successfully authorised. Please check your URI response entry and try again.\n");
return EXIT_FAILURE;
}
} else {
// Application was not just authorised
log.log("\n--synchronize or --monitor switches missing from your command line input. Please add one (not both) of these switches to your command line or use 'onedrive --help' for further assistance.\n");
log.log("No OneDrive sync will be performed without one of these two arguments being present.\n");
// Use exit scopes to shutdown API
invalidSyncExit = true;
return EXIT_FAILURE;
}
}