-
-
Notifications
You must be signed in to change notification settings - Fork 867
/
util.d
1476 lines (1264 loc) · 51.9 KB
/
util.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
// What is this module called?
module util;
// What does this module require to function?
import core.stdc.stdlib: EXIT_SUCCESS, EXIT_FAILURE, exit;
import std.base64;
import std.conv;
import std.digest.crc;
import std.digest.sha;
import std.net.curl;
import std.datetime;
import std.file;
import std.path;
import std.regex;
import std.socket;
import std.stdio;
import std.string;
import std.algorithm;
import std.uri;
import std.json;
import std.traits;
import std.utf;
import core.stdc.stdlib;
import core.thread;
import core.memory;
import std.math;
import std.format;
import std.random;
import std.array;
import std.ascii;
import std.range;
import std.exception;
import core.sys.posix.pwd;
import core.sys.posix.unistd;
import core.stdc.string;
import core.sys.posix.signal;
import etc.c.curl;
import std.process;
// What other modules that we have created do we need to import?
import log;
import config;
import qxor;
import curlEngine;
// Global variable for the device name
__gshared string deviceName;
// Global flag for SIGINT (CTRL-C) and SIGTERM (kill) state
__gshared bool exitHandlerTriggered = false;
// util module variable
ulong previousRSS;
shared static this() {
deviceName = Socket.hostName;
}
// Creates a safe backup of the given item, and only performs the function if not in a --dry-run scenario
void safeBackup(const(char)[] path, bool dryRun, bool bypassDataPreservation, out string renamedPath) {
// Do we actually perform a safe backup?
// Has the user configured to IGNORE local data protection rules?
if (bypassDataPreservation) {
// The user has configured to ignore data safety checks and overwrite local data rather than preserve & safeBackup
addLogEntry("WARNING: Local Data Protection has been disabled - not renaming local file. You may experience data loss on this file: " ~ to!string(path), ["info", "notify"]);
} else {
// configure variables
auto ext = extension(path);
auto newPath = path.chomp(ext) ~ "-" ~ deviceName ~ "-safeBackup-";
int n = 1;
// Limit to 1000 iterations .. 1000 file backups
while (exists(newPath ~ format("%04d", n) ~ ext) && n < 1000) {
n++;
}
// Check if unique file name was found
if (exists(newPath ~ format("%04d", n) ~ ext)) {
// On the 1000th backup of this file, this should be triggered
addLogEntry("Failed to backup " ~ to!string(path) ~ ": Unique file name could not be found after 1000 attempts", ["error"]);
return; // Exit function as a unique file name could not be found
}
// Configure the new name with zero-padded counter
newPath ~= format("%04d", n) ~ ext;
// Log that we are performing the backup by renaming the file
if (verboseLogging) {
addLogEntry("The local item is out-of-sync with OneDrive, renaming to preserve existing file and prevent local data loss: " ~ to!string(path) ~ " -> " ~ to!string(newPath), ["verbose"]);
}
if (!dryRun) {
// Not a --dry-run scenario - do the file rename
//
// There are 2 options to rename a file
// rename() - https://dlang.org/library/std/file/rename.html
// std.file.copy() - https://dlang.org/library/std/file/copy.html
//
// rename:
// It is not possible to rename a file across different mount points or drives. On POSIX, the operation is atomic. That means, if to already exists there will be no time period during the operation where to is missing.
//
// std.file.copy
// Copy file from to file to. File timestamps are preserved. File attributes are preserved, if preserve equals Yes.preserveAttributes
//
// Use rename() as Linux is POSIX compliant, we have an atomic operation where at no point in time the 'to' is missing.
try {
rename(path, newPath);
renamedPath = to!string(newPath);
} catch (Exception e) {
// Handle exceptions, e.g., log error
addLogEntry("Renaming of local file failed for " ~ to!string(path) ~ ": " ~ e.msg, ["error"]);
}
} else {
if (debugLogging) {
addLogEntry("DRY-RUN: Skipping renaming local file to preserve existing file and prevent data loss: " ~ to!string(path) ~ " -> " ~ to!string(newPath), ["debug"]);
}
}
}
}
// Rename the given item, and only performs the function if not in a --dry-run scenario
void safeRename(const(char)[] oldPath, const(char)[] newPath, bool dryRun) {
// Perform the rename
if (!dryRun) {
if (debugLogging) {addLogEntry("Calling rename(oldPath, newPath)", ["debug"]);}
// Use rename() as Linux is POSIX compliant, we have an atomic operation where at no point in time the 'to' is missing.
rename(oldPath, newPath);
} else {
if (debugLogging) {addLogEntry("DRY-RUN: Skipping local file rename", ["debug"]);}
}
}
// Deletes the specified file without throwing an exception if it does not exists
void safeRemove(const(char)[] path) {
if (exists(path)) remove(path);
}
// Returns the SHA1 hash hex string of a file
string computeSha1Hash(string path) {
SHA1 sha;
auto file = File(path, "rb");
scope(exit) file.close(); // Ensure file is closed post read
foreach (ubyte[] data; chunks(file, 4096)) {
sha.put(data);
}
// Store the hash in a local variable before converting to string
auto hashResult = sha.finish();
return toHexString(hashResult).idup; // Convert the hash to a hex string
}
// Returns the quickXorHash base64 string of a file
string computeQuickXorHash(string path) {
QuickXor qxor;
auto file = File(path, "rb");
scope(exit) file.close(); // Ensure file is closed post read
foreach (ubyte[] data; chunks(file, 4096)) {
qxor.put(data);
}
// Store the hash in a local variable before converting to string
auto hashResult = qxor.finish();
return Base64.encode(hashResult).idup; // Convert the hash to a base64 string
}
// Returns the SHA256 hex string of a file
string computeSHA256Hash(string path) {
SHA256 sha256;
auto file = File(path, "rb");
scope(exit) file.close(); // Ensure file is closed post read
foreach (ubyte[] data; chunks(file, 4096)) {
sha256.put(data);
}
// Store the hash in a local variable before converting to string
auto hashResult = sha256.finish();
return toHexString(hashResult).idup; // Convert the hash to a hex string
}
// Converts wildcards (*, ?) to regex
// The changes here need to be 100% regression tested before full release
Regex!char wild2regex(const(char)[] pattern) {
string str;
str.reserve(pattern.length + 2);
str ~= "^";
foreach (c; pattern) {
switch (c) {
case '*':
str ~= ".*"; // Changed to match any character. Was: str ~= "[^/]*";
break;
case '.':
str ~= "\\.";
break;
case '?':
str ~= "."; // Changed to match any single character. Was: str ~= "[^/]";
break;
case '|':
str ~= "$|^";
break;
case '+':
str ~= "\\+";
break;
case ' ':
str ~= "\\s"; // Changed to match exactly one whitespace. Was: str ~= "\\s+";
break;
case '/':
str ~= "\\/";
break;
case '(':
str ~= "\\(";
break;
case ')':
str ~= "\\)";
break;
default:
str ~= c;
break;
}
}
str ~= "$";
return regex(str, "i");
}
// Test Internet access to Microsoft OneDrive using a simple HTTP HEAD request
bool testInternetReachability(ApplicationConfig appConfig) {
HTTP http = HTTP();
http.url = "https://login.microsoftonline.com";
// Configure timeouts based on application configuration
http.dnsTimeout = dur!"seconds"(appConfig.getValueLong("dns_timeout"));
http.connectTimeout = dur!"seconds"(appConfig.getValueLong("connect_timeout"));
http.dataTimeout = dur!"seconds"(appConfig.getValueLong("data_timeout"));
http.operationTimeout = dur!"seconds"(appConfig.getValueLong("operation_timeout"));
// Set IP protocol version
http.handle.set(CurlOption.ipresolve, appConfig.getValueLong("ip_protocol_version"));
// Set HTTP method to HEAD for minimal data transfer
http.method = HTTP.Method.head;
// Exit scope to ensure cleanup
scope(exit) {
// Shut http down and destroy
http.shutdown();
object.destroy(http);
// Perform Garbage Collection
GC.collect();
// Return free memory to the OS
GC.minimize();
}
// Execute the request and handle exceptions
try {
addLogEntry("Attempting to contact Microsoft OneDrive Login Service");
http.perform();
// Check response for HTTP status code
if (http.statusLine.code >= 200 && http.statusLine.code < 400) {
addLogEntry("Successfully reached Microsoft OneDrive Login Service");
} else {
addLogEntry("Failed to reach Microsoft OneDrive Login Service. HTTP status code: " ~ to!string(http.statusLine.code));
throw new Exception("HTTP Request Failed with Status Code: " ~ to!string(http.statusLine.code));
}
return true;
} catch (SocketException e) {
addLogEntry("Cannot connect to Microsoft OneDrive Service - Socket Issue: " ~ e.msg);
displayOneDriveErrorMessage(e.msg, getFunctionName!({}));
return false;
} catch (CurlException e) {
addLogEntry("Cannot connect to Microsoft OneDrive Service - Network Connection Issue: " ~ e.msg);
displayOneDriveErrorMessage(e.msg, getFunctionName!({}));
return false;
} catch (Exception e) {
addLogEntry("Unexpected error occurred: " ~ e.toString());
displayOneDriveErrorMessage(e.toString(), getFunctionName!({}));
return false;
}
}
// Retry Internet access test to Microsoft OneDrive
bool retryInternetConnectivityTest(ApplicationConfig appConfig) {
int retryAttempts = 0;
int backoffInterval = 1; // initial backoff interval in seconds
int maxBackoffInterval = 3600; // maximum backoff interval in seconds
int maxRetryCount = 100; // max retry attempts, reduced for practicality
bool isOnline = false;
while (retryAttempts < maxRetryCount && !isOnline) {
if (backoffInterval < maxBackoffInterval) {
backoffInterval = min(backoffInterval * 2, maxBackoffInterval); // exponential increase
}
if (debugLogging) {
addLogEntry(" Retry Attempt: " ~ to!string(retryAttempts + 1), ["debug"]);
addLogEntry(" Retry In (seconds): " ~ to!string(backoffInterval), ["debug"]);
}
Thread.sleep(dur!"seconds"(backoffInterval));
isOnline = testInternetReachability(appConfig); // assuming this function is defined elsewhere
if (isOnline) {
addLogEntry("Internet connectivity to Microsoft OneDrive service has been restored");
}
retryAttempts++;
}
if (!isOnline) {
addLogEntry("ERROR: Was unable to reconnect to the Microsoft OneDrive service after " ~ to!string(maxRetryCount) ~ " attempts!");
}
// Return state
return isOnline;
}
// Can we read the local file - as a permissions issue or file corruption will cause a failure
// https://github.com/abraunegg/onedrive/issues/113
// returns true if file can be accessed
bool readLocalFile(string path) {
// What is the file size
if (getSize(path) != 0) {
try {
// Attempt to read up to the first 1 byte of the file
auto data = read(path, 1);
// Check if the read operation was successful
if (data.length != 1) {
// Read operation not successful
addLogEntry("Failed to read the required amount from the file: " ~ path);
return false;
}
} catch (std.file.FileException e) {
// Unable to read the file, log the error message
displayFileSystemErrorMessage(e.msg, getFunctionName!({}));
return false;
}
return true;
} else {
// zero byte files cannot be read, return true
return true;
}
}
// Calls globMatch for each string in pattern separated by '|'
bool multiGlobMatch(const(char)[] path, const(char)[] pattern) {
if (path.length == 0 || pattern.length == 0) {
return false;
}
if (!pattern.canFind('|')) {
return globMatch!(std.path.CaseSensitive.yes)(path, pattern);
}
foreach (glob; pattern.split('|')) {
if (globMatch!(std.path.CaseSensitive.yes)(path, glob)) {
return true;
}
}
return false;
}
// Does the path pass the Microsoft restriction and limitations about naming files and folders
bool isValidName(string path) {
// Restriction and limitations about windows naming files and folders
// https://msdn.microsoft.com/en-us/library/aa365247
// https://support.microsoft.com/en-us/help/3125202/restrictions-and-limitations-when-you-sync-files-and-folders
if (path == ".") {
return true;
}
string itemName = baseName(path).toLower(); // Ensure case-insensitivity
// Check for explicitly disallowed names
// https://support.microsoft.com/en-us/office/restrictions-and-limitations-in-onedrive-and-sharepoint-64883a5d-228e-48f5-b3d2-eb39e07630fa?ui=en-us&rs=en-us&ad=us#invalidfilefoldernames
string[] disallowedNames = [
".lock", "desktop.ini", "CON", "PRN", "AUX", "NUL",
"COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
];
// Creating an associative array for faster lookup
bool[string] disallowedSet;
foreach (name; disallowedNames) {
disallowedSet[name.toLower()] = true; // Normalise to lowercase
}
if (disallowedSet.get(itemName, false) || itemName.startsWith("~$") || canFind(itemName, "_vti_")) {
return false;
}
// Regular expression for invalid patterns
// https://support.microsoft.com/en-us/office/restrictions-and-limitations-in-onedrive-and-sharepoint-64883a5d-228e-48f5-b3d2-eb39e07630fa?ui=en-us&rs=en-us&ad=us#invalidcharacters
// Leading whitespace and trailing whitespace
// Invalid characters
// Trailing dot '.' (not documented above) , however see issue https://github.com/abraunegg/onedrive/issues/2678
//auto invalidNameReg = ctRegex!(`^\s.*|^.*[\s\.]$|.*[<>:"\|\?*/\\].*`); - original to remove at some point
auto invalidNameReg = ctRegex!(`^\s+|\s$|\.$|[<>:"\|\?*/\\]`); // revised 25/3/2024
// - ^\s+ matches one or more whitespace characters at the start of the string. The + ensures we match one or more whitespaces, making it more efficient than .* for detecting leading whitespaces.
// - \s$ matches a whitespace character at the end of the string. This is more precise than [\s\.]$ because we'll handle the dot separately.
// - \.$ specifically matches a dot character at the end of the string, addressing the requirement to catch trailing dots as invalid.
// - [<>:"\|\?*/\\] matches any single instance of the specified invalid characters: ", *, :, <, >, ?, /, \, |
auto matchResult = match(itemName, invalidNameReg);
if (!matchResult.empty) {
return false;
}
// Determine if the path is at the root level, if yes, check that 'forms' is not the first folder
auto segments = pathSplitter(path).array;
if (segments.length <= 2 && segments.back.toLower() == "forms") { // Check only the last segment, convert to lower as OneDrive is not POSIX compliant, easier to compare
return false;
}
return true;
}
// Does the path contain any bad whitespace characters
bool containsBadWhiteSpace(string path) {
// Check for null or empty string
if (path.length == 0) {
return false;
}
// Check for root item
if (path == ".") {
return false;
}
// https://github.com/abraunegg/onedrive/issues/35
// Issue #35 presented an interesting issue where the filename contained a newline item
// 'State-of-the-art, challenges, and open issues in the integration of Internet of'$'\n''Things and Cloud Computing.pdf'
// When the check to see if this file was present the GET request queries as follows:
// /v1.0/me/drive/root:/.%2FState-of-the-art%2C%20challenges%2C%20and%20open%20issues%20in%20the%20integration%20of%20Internet%20of%0AThings%20and%20Cloud%20Computing.pdf
// The '$'\n'' is translated to %0A which causes the OneDrive query to fail
// Check for the presence of '%0A' via regex
string itemName = encodeComponent(baseName(path));
// Check for encoded newline character
return itemName.indexOf("%0A") != -1;
}
// Does the path contain any ASCII HTML Codes
bool containsASCIIHTMLCodes(string path) {
// Check for null or empty string
if (path.length == 0) {
return false;
}
// Check for root item
if (path == ".") {
return false;
}
// https://github.com/abraunegg/onedrive/issues/151
// If a filename contains ASCII HTML codes, it generates an error when attempting to upload this to Microsoft OneDrive
// Check if the filename contains an ASCII HTML code sequence
// Check for the pattern &# followed by 1 to 4 digits and a semicolon
auto invalidASCIICode = ctRegex!(`&#[0-9]{1,4};`);
// Use match to search for ASCII HTML codes in the path
auto matchResult = match(path, invalidASCIICode);
// Return true if ASCII HTML codes are found
return !matchResult.empty;
}
// Does the path contain any ASCII Control Codes
bool containsASCIIControlCodes(string path) {
// Check for null or empty string
if (path.length == 0) {
return false;
}
// Check for root item
if (path == ".") {
return false;
}
// https://github.com/abraunegg/onedrive/discussions/2553#discussioncomment-7995254
// Define a ctRegex pattern for ASCII control codes and specific non-ASCII control characters
// This pattern includes the ASCII control range and common non-ASCII control characters
// Adjust the pattern as needed to include specific characters of concern
auto controlCodePattern = ctRegex!(`[\x00-\x1F\x7F]|\p{Cc}`); // Blocks ƒ†¯~‰ (#2553) , allows α (#2598)
// Use match to search for ASCII control codes in the path
auto matchResult = match(path, controlCodePattern);
// Return true if matchResult is not empty (indicating a control code was found)
return !matchResult.empty;
}
// Is the string a valid UTF-8 string?
bool isValidUTF8(string input) {
try {
auto it = input.byUTF!(char);
foreach (_; it) {
// Just iterate to check for valid UTF-8
}
return true;
} catch (UTFException) {
return false;
}
}
// Is the path a valid UTF-16 encoded path?
bool isValidUTF16(string path) {
// Check for null or empty string
if (path.length == 0) {
return true;
}
// Check for root item
if (path == ".") {
return true;
}
auto wpath = toUTF16(path); // Convert to UTF-16 encoding
auto it = wpath.byCodeUnit;
while (!it.empty) {
ushort current = it.front;
// Check for valid single unit
if (current <= 0xD7FF || (current >= 0xE000 && current <= 0xFFFF)) {
it.popFront();
}
// Check for valid surrogate pair
else if (current >= 0xD800 && current <= 0xDBFF) {
it.popFront();
if (it.empty || it.front < 0xDC00 || it.front > 0xDFFF) {
return false; // Invalid surrogate pair
}
it.popFront();
} else {
return false; // Invalid code unit
}
}
return true;
}
// Validate that the provided string is a valid date time stamp in UTC format
bool isValidUTCDateTime(string dateTimeString) {
// Regular expression for validating the string against UTC datetime format
// Allows for an optional fractional second part (e.g., .123 or .123456789)
auto pattern = regex(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$");
// Validate for UTF-8 first
if (!isValidUTF8(dateTimeString)) {
addLogEntry("BAD TIMESTAMP (UTF-8 FAIL): " ~ dateTimeString);
return false;
}
// First, check if the string matches the pattern
if (!match(dateTimeString, pattern)) {
addLogEntry("BAD TIMESTAMP (REGEX FAIL): " ~ dateTimeString);
return false;
}
// Attempt to parse the string into a DateTime object
try {
auto dt = SysTime.fromISOExtString(dateTimeString);
return true;
} catch (TimeException) {
addLogEntry("BAD TIMESTAMP (CONVERSION FAIL): " ~ dateTimeString);
return false;
}
}
// Does the path contain any HTML URL encoded items (e.g., '%20' for space)
bool containsURLEncodedItems(string path) {
// Check for null or empty string
if (path.length == 0) {
return false;
}
// Pattern for percent encoding: % followed by two hexadecimal digits
auto urlEncodedPattern = ctRegex!(`%[0-9a-fA-F]{2}`);
// Search for URL encoded items in the string
auto matchResult = match(path, urlEncodedPattern);
// Return true if URL encoded items are found
return !matchResult.empty;
}
// Parse and display error message received from OneDrive
void displayOneDriveErrorMessage(string message, string callingFunction) {
addLogEntry();
addLogEntry("ERROR: Microsoft OneDrive API returned an error with the following message:");
auto errorArray = splitLines(message);
addLogEntry(" Error Message: " ~ to!string(errorArray[0]));
// Extract 'message' as the reason
JSONValue errorMessage = parseJSON(replace(message, errorArray[0], ""));
// What is the reason for the error
if (errorMessage.type() == JSONType.object) {
// configure the error reason
string errorReason;
string errorCode;
string requestDate;
string requestId;
// set the reason for the error
try {
// Use error_description as reason
errorReason = errorMessage["error_description"].str;
} catch (JSONException e) {
// we dont want to do anything here
}
// set the reason for the error
try {
// Use ["error"]["message"] as reason
errorReason = errorMessage["error"]["message"].str;
} catch (JSONException e) {
// we dont want to do anything here
}
// Display the error reason
if (errorReason.startsWith("<!DOCTYPE")) {
// a HTML Error Reason was given
addLogEntry(" Error Reason: A HTML Error response was provided. Use debug logging (--verbose --verbose) to view this error");
if (debugLogging) {addLogEntry(errorReason, ["debug"]);}
} else {
// a non HTML Error Reason was given
addLogEntry(" Error Reason: " ~ errorReason);
}
// Get the error code if available
try {
// Use ["error"]["code"] as code
errorCode = errorMessage["error"]["code"].str;
} catch (JSONException e) {
// we dont want to do anything here
}
// Get the date of request if available
try {
// Use ["error"]["innerError"]["date"] as date
requestDate = errorMessage["error"]["innerError"]["date"].str;
} catch (JSONException e) {
// we dont want to do anything here
}
// Get the request-id if available
try {
// Use ["error"]["innerError"]["request-id"] as request-id
requestId = errorMessage["error"]["innerError"]["request-id"].str;
} catch (JSONException e) {
// we dont want to do anything here
}
// Display the error code, date and request id if available
if (errorCode != "") addLogEntry(" Error Code: " ~ errorCode);
if (requestDate != "") addLogEntry(" Error Timestamp: " ~ requestDate);
if (requestId != "") addLogEntry(" API Request ID: " ~ requestId);
}
// Where in the code was this error generated
if (verboseLogging) {addLogEntry(" Calling Function: " ~ callingFunction, ["verbose"]);}
// Extra Debug if we are using --verbose --verbose
if (debugLogging) {
addLogEntry("Raw Error Data: " ~ message, ["debug"]);
addLogEntry("JSON Message: " ~ to!string(errorMessage), ["debug"]);
}
// Close out logging with an empty line, so that in console output, and logging output this becomes clear
addLogEntry();
}
// Common code for handling when a client is unauthorised
void handleClientUnauthorised(int httpStatusCode, JSONValue errorMessage) {
// What httpStatusCode was received
if (httpStatusCode == 400) {
// bad request or a new auth token is needed
// configure the error reason
// Is there an error description?
if ("error_description" in errorMessage) {
// error_description to process
addLogEntry();
string[] errorReason = splitLines(errorMessage["error_description"].str);
addLogEntry(to!string(errorReason[0]), ["info", "notify"]);
addLogEntry();
addLogEntry("ERROR: You will need to issue a --reauth and re-authorise this client to obtain a fresh auth token.", ["info", "notify"]);
addLogEntry();
} else {
if ("code" in errorMessage["error"]) {
if (errorMessage["error"]["code"].str == "invalidRequest") {
addLogEntry();
addLogEntry("ERROR: Check your configuration as your existing refresh_token generated an invalid request. You may need to issue a --reauth and re-authorise this client.", ["info", "notify"]);
addLogEntry();
}
} else {
// no error_description
addLogEntry();
addLogEntry("ERROR: Check your configuration as it may be invalid. You will need to issue a --reauth and re-authorise this client to obtain a fresh auth token.", ["info", "notify"]);
addLogEntry();
}
}
} else {
// 401 error code
addLogEntry();
addLogEntry("ERROR: Check your configuration as your refresh_token may be empty or invalid. You may need to issue a --reauth and re-authorise this client.", ["info", "notify"]);
addLogEntry();
}
}
// Parse and display error message received from the local file system
void displayFileSystemErrorMessage(string message, string callingFunction) {
addLogEntry(); // used rather than writeln
addLogEntry("ERROR: The local file system returned an error with the following message:");
auto errorArray = splitLines(message);
// Safely get the error message
string errorMessage = errorArray.length > 0 ? to!string(errorArray[0]) : "No error message available";
addLogEntry(" Error Message: " ~ errorMessage);
// Log the calling function
addLogEntry(" Calling Function: " ~ callingFunction);
try {
// Safely check for disk space
ulong localActualFreeSpace = to!ulong(getAvailableDiskSpace("."));
if (localActualFreeSpace == 0) {
// Must force exit here, allow logging to be done
forceExit();
}
} catch (Exception e) {
// Handle exceptions from disk space check or type conversion
addLogEntry(" Exception in disk space check: " ~ e.msg);
}
}
// Display the POSIX Error Message
void displayPosixErrorMessage(string message) {
addLogEntry(); // used rather than writeln
addLogEntry("ERROR: Microsoft OneDrive API returned data that highlights a POSIX compliance issue:");
addLogEntry(" Error Message: " ~ message);
}
// Display the Error Message
void displayGeneralErrorMessage(Exception e, string callingFunction=__FUNCTION__, int lineno=__LINE__) {
addLogEntry(); // used rather than writeln
addLogEntry("ERROR: Encountered a " ~ e.classinfo.name ~ ":");
addLogEntry(" Error Message: " ~ e.msg);
addLogEntry(" Calling Function: " ~ callingFunction);
addLogEntry(" Line number: " ~ to!string(lineno));
}
// Get the function name that is being called to assist with identifying where an error is being generated
string getFunctionName(alias func)() {
return __traits(identifier, __traits(parent, func)) ~ "()\n";
}
JSONValue fetchOnlineURLContent(string url) {
// Function variables
char[] content;
JSONValue onlineContent;
// Setup HTTP request
HTTP http = HTTP();
// Exit scope to ensure cleanup
scope(exit) {
// Shut http down and destroy
http.shutdown();
object.destroy(http);
// Perform Garbage Collection
GC.collect();
// Return free memory to the OS
GC.minimize();
}
// Configure the URL to access
http.url = url;
// HTTP the connection method
http.method = HTTP.Method.get;
// Data receive handler
http.onReceive = (ubyte[] data) {
content ~= data; // Append data as it's received
return data.length;
};
// Perform HTTP request
http.perform();
// Parse Content
onlineContent = parseJSON(to!string(content));
// Return onlineResponse
return onlineContent;
}
// Get the latest release version from GitHub
JSONValue getLatestReleaseDetails() {
JSONValue githubLatest;
JSONValue versionDetails;
string latestTag;
string publishedDate;
// Query GitHub for the 'latest' release details
try {
githubLatest = fetchOnlineURLContent("https://api.github.com/repos/abraunegg/onedrive/releases/latest");
} catch (CurlException e) {
if (debugLogging) {addLogEntry("CurlException: Unable to query GitHub for latest release - " ~ e.msg, ["debug"]);}
} catch (JSONException e) {
if (debugLogging) {addLogEntry("JSONException: Unable to parse GitHub JSON response - " ~ e.msg, ["debug"]);}
}
// githubLatest has to be a valid JSON object
if (githubLatest.type() == JSONType.object){
// use the returned tag_name
if ("tag_name" in githubLatest) {
// use the provided tag
// "tag_name": "vA.B.CC" and strip 'v'
latestTag = strip(githubLatest["tag_name"].str, "v");
} else {
// set to latestTag zeros
if (debugLogging) {addLogEntry("'tag_name' unavailable in JSON response. Setting GitHub 'tag_name' release version to 0.0.0", ["debug"]);}
latestTag = "0.0.0";
}
// use the returned published_at date
if ("published_at" in githubLatest) {
// use the provided value
publishedDate = githubLatest["published_at"].str;
} else {
// set to v2.0.0 release date
if (debugLogging) {addLogEntry("'published_at' unavailable in JSON response. Setting GitHub 'published_at' date to 2018-07-18T18:00:00Z", ["debug"]);}
publishedDate = "2018-07-18T18:00:00Z";
}
} else {
// JSONValue is not an object
if (debugLogging) {addLogEntry("Invalid JSON Object response from GitHub. Setting GitHub 'tag_name' release version to 0.0.0", ["debug"]);}
latestTag = "0.0.0";
if (debugLogging) {addLogEntry("Invalid JSON Object. Setting GitHub 'published_at' date to 2018-07-18T18:00:00Z", ["debug"]);}
publishedDate = "2018-07-18T18:00:00Z";
}
// return the latest github version and published date as our own JSON
versionDetails = [
"latestTag": JSONValue(latestTag),
"publishedDate": JSONValue(publishedDate)
];
// return JSON
return versionDetails;
}
// Get the release details from the 'current' running version
JSONValue getCurrentVersionDetails(string thisVersion) {
JSONValue githubDetails;
JSONValue versionDetails;
string versionTag = "v" ~ thisVersion;
string publishedDate;
// Query GitHub for the release details to match the running version
try {
githubDetails = fetchOnlineURLContent("https://api.github.com/repos/abraunegg/onedrive/releases");
} catch (CurlException e) {
if (debugLogging) {addLogEntry("CurlException: Unable to query GitHub for release details - " ~ e.msg, ["debug"]);}
return parseJSON(`{"Error": "CurlException", "message": "` ~ e.msg ~ `"}`);
} catch (JSONException e) {
if (debugLogging) {addLogEntry("JSONException: Unable to parse GitHub JSON response - " ~ e.msg, ["debug"]);}
return parseJSON(`{"Error": "JSONException", "message": "` ~ e.msg ~ `"}`);
}
// githubDetails has to be a valid JSON array
if (githubDetails.type() == JSONType.array){
foreach (searchResult; githubDetails.array) {
// searchResult["tag_name"].str;
if (searchResult["tag_name"].str == versionTag) {
if (debugLogging) {
addLogEntry("MATCHED version", ["debug"]);
addLogEntry("tag_name: " ~ searchResult["tag_name"].str, ["debug"]);
addLogEntry("published_at: " ~ searchResult["published_at"].str, ["debug"]);
}
publishedDate = searchResult["published_at"].str;
}
}
if (publishedDate.empty) {
// empty .. no version match ?
// set to v2.0.0 release date
if (debugLogging) {addLogEntry("'published_at' unavailable in JSON response. Setting GitHub 'published_at' date to 2018-07-18T18:00:00Z", ["debug"]);}
publishedDate = "2018-07-18T18:00:00Z";
}
} else {
// JSONValue is not an Array
if (debugLogging) {addLogEntry("Invalid JSON Array. Setting GitHub 'published_at' date to 2018-07-18T18:00:00Z", ["debug"]);}
publishedDate = "2018-07-18T18:00:00Z";
}
// return the latest github version and published date as our own JSON
versionDetails = [
"versionTag": JSONValue(thisVersion),
"publishedDate": JSONValue(publishedDate)
];
// return JSON
return versionDetails;
}
// Check the application version versus GitHub latestTag
void checkApplicationVersion() {
// Get the latest details from GitHub
JSONValue latestVersionDetails = getLatestReleaseDetails();
string latestVersion = latestVersionDetails["latestTag"].str;
SysTime publishedDate = SysTime.fromISOExtString(latestVersionDetails["publishedDate"].str).toUTC();
SysTime releaseGracePeriod = publishedDate;
SysTime currentTime = Clock.currTime().toUTC();
// drop fraction seconds
publishedDate.fracSecs = Duration.zero;
currentTime.fracSecs = Duration.zero;
releaseGracePeriod.fracSecs = Duration.zero;
// roll the grace period forward to allow distributions to catch up based on their release cycles
releaseGracePeriod = releaseGracePeriod.add!"months"(1);
// what is this clients version?
auto currentVersionArray = strip(strip(import("version"), "v")).split("-");
string applicationVersion = currentVersionArray[0];
// debug output
if (debugLogging) {
addLogEntry("applicationVersion: " ~ applicationVersion, ["debug"]);
addLogEntry("latestVersion: " ~ latestVersion, ["debug"]);
addLogEntry("publishedDate: " ~ to!string(publishedDate), ["debug"]);
addLogEntry("currentTime: " ~ to!string(currentTime), ["debug"]);
addLogEntry("releaseGracePeriod: " ~ to!string(releaseGracePeriod), ["debug"]);
}
// display details if not current
// is application version is older than available on GitHub
if (applicationVersion != latestVersion) {
// application version is different
bool displayObsolete = false;
// what warning do we present?
if (applicationVersion < latestVersion) {
// go get this running version details
JSONValue thisVersionDetails = getCurrentVersionDetails(applicationVersion);
SysTime thisVersionPublishedDate = SysTime.fromISOExtString(thisVersionDetails["publishedDate"].str).toUTC();
thisVersionPublishedDate.fracSecs = Duration.zero;
if (debugLogging) {addLogEntry("thisVersionPublishedDate: " ~ to!string(thisVersionPublishedDate), ["debug"]);}
// the running version grace period is its release date + 1 month
SysTime thisVersionReleaseGracePeriod = thisVersionPublishedDate;
thisVersionReleaseGracePeriod = thisVersionReleaseGracePeriod.add!"months"(1);
if (debugLogging) {addLogEntry("thisVersionReleaseGracePeriod: " ~ to!string(thisVersionReleaseGracePeriod), ["debug"]);}
// Is this running version obsolete ?
if (!displayObsolete) {
// if releaseGracePeriod > currentTime
// display an information warning that there is a new release available
if (releaseGracePeriod.toUnixTime() > currentTime.toUnixTime()) {
// inside release grace period ... set flag to false
displayObsolete = false;
} else {
// outside grace period
displayObsolete = true;
}
}
// display version response
addLogEntry();
if (!displayObsolete) {
// display the new version is available message
addLogEntry("INFO: A new onedrive client version is available. Please upgrade your client version when possible.", ["info", "notify"]);
} else {
// display the obsolete message
addLogEntry("WARNING: Your onedrive client version is now obsolete and unsupported. Please upgrade your client version.", ["info", "notify"]);
}
addLogEntry("Current Application Version: " ~ applicationVersion);
addLogEntry("Version Available: " ~ latestVersion);
addLogEntry();
}
}
}
bool hasId(JSONValue item) {
return ("id" in item) != null;
}
bool hasMimeType(const ref JSONValue item) {
return ("mimeType" in item["file"]) != null;
}
bool hasQuota(JSONValue item) {
return ("quota" in item) != null;
}
bool isItemDeleted(JSONValue item) {
return ("deleted" in item) != null;
}
bool isItemRoot(JSONValue item) {
return ("root" in item) != null;
}