/
duplicacy_main.go
2291 lines (1977 loc) · 65 KB
/
duplicacy_main.go
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
// Copyright (c) Acrosync LLC. All rights reserved.
// Free for personal use and commercial trial
// Commercial use requires per-user licenses available from https://duplicacy.com
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
_ "net/http/pprof"
"github.com/gilbertchen/cli"
"io/ioutil"
"github.com/gilbertchen/duplicacy/src"
)
const (
ArgumentExitCode = 3
)
var ScriptEnabled bool
var GitCommit = "unofficial"
func getRepositoryPreference(context *cli.Context, storageName string) (repository string,
preference *duplicacy.Preference) {
repository, err := os.Getwd()
if err != nil {
duplicacy.LOG_ERROR("REPOSITORY_PATH", "Failed to retrieve the current working directory: %v", err)
return "", nil
}
for {
stat, err := os.Stat(path.Join(repository, duplicacy.DUPLICACY_DIRECTORY)) //TOKEEP
if err != nil && !os.IsNotExist(err) {
duplicacy.LOG_ERROR("REPOSITORY_PATH", "Failed to retrieve the information about the directory %s: %v",
repository, err)
return "", nil
}
if stat != nil && (stat.IsDir() || stat.Mode().IsRegular()) {
break
}
parent := path.Dir(repository)
if parent == repository || parent == "" {
duplicacy.LOG_ERROR("REPOSITORY_PATH", "Repository has not been initialized")
return "", nil
}
repository = parent
}
duplicacy.LoadPreferences(repository)
preferencePath := duplicacy.GetDuplicacyPreferencePath()
duplicacy.SetKeyringFile(path.Join(preferencePath, "keyring"))
if storageName == "" {
storageName = context.String("storage")
}
if storageName == "" {
if duplicacy.Preferences[0].RepositoryPath != "" {
repository = duplicacy.Preferences[0].RepositoryPath
duplicacy.LOG_INFO("REPOSITORY_SET", "Repository set to %s", repository)
}
return repository, &duplicacy.Preferences[0]
}
preference = duplicacy.FindPreference(storageName)
if preference == nil {
duplicacy.LOG_ERROR("STORAGE_NONE", "No storage named '%s' is found", storageName)
return "", nil
}
if preference.RepositoryPath != "" {
repository = preference.RepositoryPath
duplicacy.LOG_INFO("REPOSITORY_SET", "Repository set to %s", repository)
}
return repository, preference
}
func getRevisions(context *cli.Context) (revisions []int) {
flags := context.StringSlice("r")
rangeRegex := regexp.MustCompile(`^([0-9]+)-([0-9]+)$`)
numberRegex := regexp.MustCompile(`^([0-9]+)$`)
for _, flag := range flags {
matched := rangeRegex.FindStringSubmatch(flag)
if matched != nil {
start, _ := strconv.Atoi(matched[1])
end, _ := strconv.Atoi(matched[2])
if end > start {
for r := start; r <= end; r++ {
revisions = append(revisions, r)
}
continue
}
}
matched = numberRegex.FindStringSubmatch(flag)
if matched != nil {
r, _ := strconv.Atoi(matched[1])
revisions = append(revisions, r)
continue
}
fmt.Fprintf(context.App.Writer, "Invalid revision: %s.\n\n", flag)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
return revisions
}
func setGlobalOptions(context *cli.Context) {
if context.GlobalBool("log") {
duplicacy.EnableLogHeader()
}
if context.GlobalBool("stack") {
duplicacy.EnableStackTrace()
}
if context.GlobalBool("verbose") {
duplicacy.SetLoggingLevel(duplicacy.TRACE)
}
if context.GlobalBool("debug") {
duplicacy.SetLoggingLevel(duplicacy.DEBUG)
}
if context.GlobalBool("print-memory-usage") {
go duplicacy.PrintMemoryUsage()
}
ScriptEnabled = true
if context.GlobalBool("no-script") {
ScriptEnabled = false
}
address := context.GlobalString("profile")
if address != "" {
go func() {
http.ListenAndServe(address, nil)
}()
}
for _, logID := range context.GlobalStringSlice("suppress") {
duplicacy.SuppressLog(logID)
}
duplicacy.RunInBackground = context.GlobalBool("background")
}
func runScript(context *cli.Context, storageName string, phase string) bool {
if !ScriptEnabled {
return false
}
preferencePath := duplicacy.GetDuplicacyPreferencePath()
scriptDir, _ := filepath.Abs(path.Join(preferencePath, "scripts"))
scriptNames := []string{phase + "-" + context.Command.Name,
storageName + "-" + phase + "-" + context.Command.Name}
script := ""
for _, scriptName := range scriptNames {
script = path.Join(scriptDir, scriptName)
if runtime.GOOS == "windows" {
script += ".bat"
}
if _, err := os.Stat(script); err == nil {
break
} else {
script = ""
}
}
if script == "" {
return false
}
duplicacy.LOG_INFO("SCRIPT_RUN", "Running script %s", script)
output, err := exec.Command(script, os.Args...).CombinedOutput()
for _, line := range strings.Split(string(output), "\n") {
line := strings.TrimSpace(line)
if line != "" {
duplicacy.LOG_INFO("SCRIPT_OUTPUT", line)
}
}
if err != nil {
duplicacy.LOG_ERROR("SCRIPT_ERROR", "Failed to run %s script: %v", script, err)
return false
}
return true
}
func loadRSAPrivateKey(keyFile string, passphrase string, preference *duplicacy.Preference, backupManager *duplicacy.BackupManager, resetPasswords bool) {
if keyFile == "" {
return
}
prompt := fmt.Sprintf("Enter the passphrase for %s:", keyFile)
if passphrase == "" {
passphrase = duplicacy.GetPassword(*preference, "rsa_passphrase", prompt, false, resetPasswords)
backupManager.LoadRSAPrivateKey(keyFile, passphrase)
duplicacy.SavePassword(*preference, "rsa_passphrase", passphrase)
} else {
backupManager.LoadRSAPrivateKey(keyFile, passphrase)
}
}
func initRepository(context *cli.Context) {
configRepository(context, true)
}
func addStorage(context *cli.Context) {
configRepository(context, false)
}
func configRepository(context *cli.Context, init bool) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
numberOfArgs := 3
if init {
numberOfArgs = 2
}
if len(context.Args()) != numberOfArgs {
fmt.Fprintf(context.App.Writer, "The %s command requires %d arguments.\n\n",
context.Command.Name, numberOfArgs)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
var storageName string
var snapshotID string
var storageURL string
if init {
storageName = context.String("storage-name")
if len(storageName) == 0 {
storageName = "default"
}
snapshotID = context.Args()[0]
storageURL = context.Args()[1]
} else {
storageName = context.Args()[0]
snapshotID = context.Args()[1]
storageURL = context.Args()[2]
if strings.ToLower(storageName) == "ssh" {
duplicacy.LOG_ERROR("PREFERENCE_INVALID", "'%s' is an invalid storage name", storageName)
return
}
}
snapshotIDRegex := regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
matched := snapshotIDRegex.FindStringSubmatch(snapshotID)
if matched == nil {
duplicacy.LOG_ERROR("PREFERENCE_INVALID", "'%s' is an invalid snapshot id", snapshotID)
return
}
var repository string
var err error
if init {
repository, err = os.Getwd()
if err != nil {
duplicacy.LOG_ERROR("REPOSITORY_PATH", "Failed to retrieve the current working directory: %v", err)
return
}
preferencePath := context.String("pref-dir")
if preferencePath == "" {
preferencePath = path.Join(repository, duplicacy.DUPLICACY_DIRECTORY) // TOKEEP
}
if stat, _ := os.Stat(path.Join(preferencePath, "preferences")); stat != nil {
duplicacy.LOG_ERROR("REPOSITORY_INIT", "The repository %s has already been initialized", repository)
return
}
err = os.Mkdir(preferencePath, 0744)
if err != nil && !os.IsExist(err) {
duplicacy.LOG_ERROR("REPOSITORY_INIT", "Failed to create the directory %s: %v",
preferencePath, err)
return
}
if context.String("pref-dir") != "" {
// out of tree preference file
// write real path into .duplicacy file inside repository
duplicacyFileName := path.Join(repository, duplicacy.DUPLICACY_FILE)
d1 := []byte(preferencePath)
err = ioutil.WriteFile(duplicacyFileName, d1, 0644)
if err != nil {
duplicacy.LOG_ERROR("REPOSITORY_PATH", "Failed to write %s file inside repository %v", duplicacyFileName, err)
return
}
}
duplicacy.SetDuplicacyPreferencePath(preferencePath)
duplicacy.SetKeyringFile(path.Join(preferencePath, "keyring"))
} else {
repository, _ = getRepositoryPreference(context, "")
if duplicacy.FindPreference(storageName) != nil {
duplicacy.LOG_ERROR("STORAGE_DUPLICATE", "There is already a storage named '%s'", storageName)
return
}
}
repositoryPath := ""
if context.String("repository") != "" {
repositoryPath = context.String("repository")
}
preference := duplicacy.Preference{
Name: storageName,
SnapshotID: snapshotID,
RepositoryPath: repositoryPath,
StorageURL: storageURL,
Encrypted: context.Bool("encrypt"),
}
storage := duplicacy.CreateStorage(preference, true, 1)
storagePassword := ""
if preference.Encrypted {
prompt := fmt.Sprintf("Enter storage password for %s:", preference.StorageURL)
storagePassword = duplicacy.GetPassword(preference, "password", prompt, false, true)
} else {
if context.String("key") != "" {
duplicacy.LOG_ERROR("STORAGE_CONFIG", "RSA encryption can't be enabled with an unencrypted storage")
return
}
}
existingConfig, _, err := duplicacy.DownloadConfig(storage, storagePassword)
if err != nil {
duplicacy.LOG_ERROR("STORAGE_CONFIG", "Failed to download the configuration file from the storage: %v", err)
return
}
if existingConfig != nil {
duplicacy.LOG_INFO("STORAGE_CONFIGURED",
"The storage '%s' has already been initialized", preference.StorageURL)
if existingConfig.CompressionLevel >= -1 && existingConfig.CompressionLevel <= 9 {
duplicacy.LOG_INFO("STORAGE_FORMAT", "This storage is configured to use the pre-1.2.0 format")
} else if existingConfig.CompressionLevel != 100 {
duplicacy.LOG_ERROR("STORAGE_COMPRESSION", "This storage is configured with an invalid compression level %d", existingConfig.CompressionLevel)
return
} else if existingConfig.CompressionLevel != duplicacy.DEFAULT_COMPRESSION_LEVEL {
duplicacy.LOG_INFO("STORAGE_COMPRESSION", "Compression level: %d", existingConfig.CompressionLevel)
}
// Don't print config in the background mode
if !duplicacy.RunInBackground {
existingConfig.Print()
}
} else {
averageChunkSize := duplicacy.AtoSize(context.String("chunk-size"))
if averageChunkSize == 0 {
fmt.Fprintf(context.App.Writer, "Invalid average chunk size: %s.\n\n", context.String("chunk-size"))
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
size := 1
for size*2 <= averageChunkSize {
size *= 2
}
if size != averageChunkSize {
fmt.Fprintf(context.App.Writer, "Invalid average chunk size: %d is not a power of 2.\n\n",
averageChunkSize)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
maximumChunkSize := 4 * averageChunkSize
minimumChunkSize := averageChunkSize / 4
if context.String("max-chunk-size") != "" {
maximumChunkSize = duplicacy.AtoSize(context.String("max-chunk-size"))
if maximumChunkSize < averageChunkSize {
fmt.Fprintf(context.App.Writer, "Invalid maximum chunk size: %s.\n\n",
context.String("max-chunk-size"))
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
}
if context.String("min-chunk-size") != "" {
minimumChunkSize = duplicacy.AtoSize(context.String("min-chunk-size"))
if minimumChunkSize > averageChunkSize || minimumChunkSize == 0 {
fmt.Fprintf(context.App.Writer, "Invalid minimum chunk size: %s.\n\n",
context.String("min-chunk-size"))
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
}
if preference.Encrypted {
repeatedPassword := duplicacy.GetPassword(preference, "password", "Re-enter storage password:",
false, true)
if repeatedPassword != storagePassword {
duplicacy.LOG_ERROR("STORAGE_PASSWORD", "Storage passwords do not match")
return
}
}
var otherConfig *duplicacy.Config
var bitCopy bool
if context.String("copy") != "" {
otherPreference := duplicacy.FindPreference(context.String("copy"))
if otherPreference == nil {
duplicacy.LOG_ERROR("STORAGE_NOTFOUND", "Storage '%s' can't be found", context.String("copy"))
return
}
otherStorage := duplicacy.CreateStorage(*otherPreference, false, 1)
otherPassword := ""
if otherPreference.Encrypted {
prompt := fmt.Sprintf("Enter storage password for %s:", otherPreference.StorageURL)
otherPassword = duplicacy.GetPassword(*otherPreference, "password", prompt, false, false)
}
otherConfig, _, err = duplicacy.DownloadConfig(otherStorage, otherPassword)
if err != nil {
duplicacy.LOG_ERROR("STORAGE_COPY", "Failed to download the configuration file from the storage: %v",
err)
return
}
if otherConfig == nil {
duplicacy.LOG_ERROR("STORAGE_NOT_CONFIGURED",
"The storage to copy the configuration from has not been initialized")
}
bitCopy = context.Bool("bit-identical")
}
iterations := context.Int("iterations")
if iterations == 0 {
iterations = duplicacy.CONFIG_DEFAULT_ITERATIONS
}
dataShards := 0
parityShards := 0
shards := context.String("erasure-coding")
if shards != "" {
shardsRegex := regexp.MustCompile(`^([0-9]+):([0-9]+)$`)
matched := shardsRegex.FindStringSubmatch(shards)
if matched == nil {
duplicacy.LOG_ERROR("STORAGE_ERASURECODE", "Invalid erasure coding parameters: %s", shards)
} else {
dataShards, _ = strconv.Atoi(matched[1])
parityShards, _ = strconv.Atoi(matched[2])
if dataShards == 0 || dataShards > 256 || parityShards == 0 || parityShards > dataShards {
duplicacy.LOG_ERROR("STORAGE_ERASURECODE", "Invalid erasure coding parameters: %s", shards)
}
}
}
compressionLevel := 100
zstdLevel := context.String("zstd-level")
if zstdLevel != "" {
if level, found := duplicacy.ZSTD_COMPRESSION_LEVELS[zstdLevel]; found {
compressionLevel = level
} else {
duplicacy.LOG_ERROR("STORAGE_COMPRESSION", "Invalid zstd compression level: %s", zstdLevel)
}
} else if context.Bool("zstd") {
compressionLevel = duplicacy.ZSTD_COMPRESSION_LEVEL_DEFAULT
}
duplicacy.ConfigStorage(storage, iterations, compressionLevel, averageChunkSize, maximumChunkSize,
minimumChunkSize, storagePassword, otherConfig, bitCopy, context.String("key"), dataShards, parityShards)
}
duplicacy.Preferences = append(duplicacy.Preferences, preference)
duplicacy.SavePreferences()
if repositoryPath == "" {
repositoryPath = repository
}
duplicacy.LOG_INFO("REPOSITORY_INIT", "%s will be backed up to %s with id %s",
repositoryPath, preference.StorageURL, preference.SnapshotID)
}
type TriBool struct {
Value int
}
func (triBool *TriBool) Set(value string) error {
value = strings.ToLower(value)
if value == "yes" || value == "true" || value == "1" {
triBool.Value = 2
return nil
} else if value == "no" || value == "false" || value == "0" {
triBool.Value = 1
return nil
} else if value == "" {
// Only set to true if it hasn't been set before. This is necessary because for 'encrypt, e' this may
// be called twice, the second time with a value of ""
if triBool.Value == 0 {
triBool.Value = 2
}
return nil
} else {
return fmt.Errorf("Invalid boolean value '%s'", value)
}
}
// IsBoolFlag implements the private interface flag.boolFlag to indicate that this is a bool flag so the argument
// is optional
func (triBool *TriBool) IsBoolFlag() bool { return true }
func (triBool *TriBool) String() string {
return ""
}
func (triBool *TriBool) IsSet() bool {
return triBool.Value != 0
}
func (triBool *TriBool) IsTrue() bool {
return triBool.Value == 2
}
func setPreference(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
if len(context.Args()) > 0 {
fmt.Fprintf(context.App.Writer, "The %s command takes no arguments.\n\n", context.Command.Name)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
storageName := context.String("storage")
repository, oldPreference := getRepositoryPreference(context, storageName)
if oldPreference == nil {
duplicacy.LOG_ERROR("STORAGE_SET", "The storage '%s' has not been added to the repository %s",
storageName, repository)
return
}
newPreference := *oldPreference
triBool := context.Generic("e").(*TriBool)
if triBool.IsSet() {
newPreference.Encrypted = triBool.IsTrue()
}
triBool = context.Generic("no-backup").(*TriBool)
if triBool.IsSet() {
newPreference.BackupProhibited = triBool.IsTrue()
}
triBool = context.Generic("no-restore").(*TriBool)
if triBool.IsSet() {
newPreference.RestoreProhibited = triBool.IsTrue()
}
triBool = context.Generic("no-save-password").(*TriBool)
if triBool.IsSet() {
newPreference.DoNotSavePassword = triBool.IsTrue()
}
if context.String("nobackup-file") != "" {
newPreference.NobackupFile = context.String("nobackup-file")
}
if context.String("filters") != "" {
newPreference.FiltersFile = context.String("filters")
}
triBool = context.Generic("exclude-by-attribute").(*TriBool)
if triBool.IsSet() {
newPreference.ExcludeByAttribute = triBool.IsTrue()
}
key := context.String("key")
value := context.String("value")
if len(key) > 0 {
// Make a deep copy of the keys otherwise we would be change both preferences at once.
newKeys := make(map[string]string)
for k, v := range newPreference.Keys {
newKeys[k] = v
}
newPreference.Keys = newKeys
if len(value) == 0 {
delete(newPreference.Keys, key)
} else {
if len(newPreference.Keys) == 0 {
newPreference.Keys = make(map[string]string)
}
newPreference.Keys[key] = value
}
}
if duplicacy.IsTracing() {
description, _ := json.MarshalIndent(newPreference, "", " ")
fmt.Printf("%s\n", description)
}
if newPreference.Equal(oldPreference) {
duplicacy.LOG_INFO("STORAGE_SET", "The options for storage %s have not been modified",
oldPreference.StorageURL)
} else {
*oldPreference = newPreference
duplicacy.SavePreferences()
duplicacy.LOG_INFO("STORAGE_SET", "New options for storage %s have been saved", oldPreference.StorageURL)
}
}
func changePassword(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
if len(context.Args()) != 0 {
fmt.Fprintf(context.App.Writer, "The %s command requires no arguments.\n\n",
context.Command.Name)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
_, preference := getRepositoryPreference(context, "")
storage := duplicacy.CreateStorage(*preference, false, 1)
if storage == nil {
return
}
password := ""
if preference.Encrypted {
password = duplicacy.GetPassword(*preference, "password",
fmt.Sprintf("Enter old password for storage %s:", preference.StorageURL),
false, true)
}
config, _, err := duplicacy.DownloadConfig(storage, password)
if err != nil {
duplicacy.LOG_ERROR("STORAGE_CONFIG", "Failed to download the configuration file from the storage: %v", err)
return
}
if config == nil {
duplicacy.LOG_ERROR("STORAGE_NOT_CONFIGURED", "The storage has not been initialized")
return
}
newPassword := duplicacy.GetPassword(*preference, "password", "Enter new storage password:", false, true)
repeatedPassword := duplicacy.GetPassword(*preference, "password", "Re-enter new storage password:", false, true)
if repeatedPassword != newPassword {
duplicacy.LOG_ERROR("PASSWORD_CHANGE", "The new passwords do not match")
return
}
if newPassword == password {
duplicacy.LOG_ERROR("PASSWORD_CHANGE", "The new password is the same as the old one")
return
}
iterations := context.Int("iterations")
if iterations == 0 {
iterations = duplicacy.CONFIG_DEFAULT_ITERATIONS
}
description, err := json.MarshalIndent(config, "", " ")
if err != nil {
duplicacy.LOG_ERROR("CONFIG_MARSHAL", "Failed to marshal the config: %v", err)
return
}
configPath := path.Join(duplicacy.GetDuplicacyPreferencePath(), "config")
err = ioutil.WriteFile(configPath, description, 0600)
if err != nil {
duplicacy.LOG_ERROR("CONFIG_SAVE", "Failed to save the old config to %s: %v", configPath, err)
return
}
duplicacy.LOG_INFO("CONFIG_SAVE", "The old config has been temporarily saved to %s", configPath)
removeLocalCopy := false
defer func() {
if removeLocalCopy {
err = os.Remove(configPath)
if err != nil {
duplicacy.LOG_WARN("CONFIG_CLEAN", "Failed to delete %s: %v", configPath, err)
} else {
duplicacy.LOG_INFO("CONFIG_CLEAN", "The local copy of the old config has been removed")
}
}
}()
err = storage.DeleteFile(0, "config")
if err != nil {
duplicacy.LOG_ERROR("CONFIG_DELETE", "Failed to delete the old config from the storage: %v", err)
return
}
duplicacy.UploadConfig(storage, config, newPassword, iterations)
duplicacy.SavePassword(*preference, "password", newPassword)
duplicacy.LOG_INFO("STORAGE_SET", "The password for storage %s has been changed", preference.StorageURL)
removeLocalCopy = true
}
func backupRepository(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
if len(context.Args()) != 0 {
fmt.Fprintf(context.App.Writer, "The %s command requires no arguments.\n\n", context.Command.Name)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
repository, preference := getRepositoryPreference(context, "")
if preference.BackupProhibited {
duplicacy.LOG_ERROR("BACKUP_DISABLED", "Backup from this repository to %s was disabled by the preference",
preference.StorageURL)
return
}
runScript(context, preference.Name, "pre")
threads := context.Int("threads")
if threads < 1 {
threads = 1
}
duplicacy.LOG_INFO("STORAGE_SET", "Storage set to %s", preference.StorageURL)
storage := duplicacy.CreateStorage(*preference, false, threads)
if storage == nil {
return
}
password := ""
if preference.Encrypted {
password = duplicacy.GetPassword(*preference, "password", "Enter storage password:", false, false)
}
quickMode := true
if context.Bool("hash") {
quickMode = false
}
showStatistics := context.Bool("stats")
enableVSS := context.Bool("vss")
vssTimeout := context.Int("vss-timeout")
dryRun := context.Bool("dry-run")
uploadRateLimit := context.Int("limit-rate")
enumOnly := context.Bool("enum-only")
storage.SetRateLimits(0, uploadRateLimit)
backupManager := duplicacy.CreateBackupManager(preference.SnapshotID, storage, repository, password, preference.NobackupFile, preference.FiltersFile, preference.ExcludeByAttribute)
duplicacy.SavePassword(*preference, "password", password)
backupManager.SetupSnapshotCache(preference.Name)
backupManager.SetDryRun(dryRun)
zstdLevel := context.String("zstd-level")
if zstdLevel != "" {
if level, found := duplicacy.ZSTD_COMPRESSION_LEVELS[zstdLevel]; found {
backupManager.SetCompressionLevel(level)
} else {
duplicacy.LOG_ERROR("STORAGE_COMPRESSION", "Invalid zstd compression level: %s", zstdLevel)
}
} else if context.Bool("zstd") {
backupManager.SetCompressionLevel(duplicacy.ZSTD_COMPRESSION_LEVEL_DEFAULT)
}
metadataChunkSize := context.Int("metadata-chunk-size")
maximumInMemoryEntries := context.Int("max-in-memory-entries")
backupManager.Backup(repository, quickMode, threads, context.String("t"), showStatistics, enableVSS, vssTimeout, enumOnly, metadataChunkSize, maximumInMemoryEntries)
runScript(context, preference.Name, "post")
}
func restoreRepository(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
revision := context.Int("r")
if revision <= 0 {
fmt.Fprintf(context.App.Writer, "The revision flag is not specified or invalid\n\n")
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
repository, preference := getRepositoryPreference(context, "")
if preference.RestoreProhibited {
duplicacy.LOG_ERROR("RESTORE_DISABLED", "Restore from %s to this repository was disabled by the preference",
preference.StorageURL)
return
}
runScript(context, preference.Name, "pre")
threads := context.Int("threads")
if threads < 1 {
threads = 1
}
duplicacy.LOG_INFO("STORAGE_SET", "Storage set to %s", preference.StorageURL)
storage := duplicacy.CreateStorage(*preference, false, threads)
if storage == nil {
return
}
password := ""
if preference.Encrypted {
password = duplicacy.GetPassword(*preference, "password", "Enter storage password:", false, false)
}
quickMode := !context.Bool("hash")
overwrite := context.Bool("overwrite")
deleteMode := context.Bool("delete")
setOwner := !context.Bool("ignore-owner")
showStatistics := context.Bool("stats")
persist := context.Bool("persist")
var patterns []string
for _, pattern := range context.Args() {
pattern = strings.TrimSpace(pattern)
for strings.HasPrefix(pattern, "--") {
pattern = pattern[1:]
}
for strings.HasPrefix(pattern, "++") {
pattern = pattern[1:]
}
patterns = append(patterns, pattern)
}
patterns = duplicacy.ProcessFilterLines(patterns, make([]string, 0))
duplicacy.LOG_DEBUG("REGEX_DEBUG", "There are %d compiled regular expressions stored", len(duplicacy.RegexMap))
duplicacy.LOG_INFO("SNAPSHOT_FILTER", "Loaded %d include/exclude pattern(s)", len(patterns))
storage.SetRateLimits(context.Int("limit-rate"), 0)
backupManager := duplicacy.CreateBackupManager(preference.SnapshotID, storage, repository, password, preference.NobackupFile, preference.FiltersFile, preference.ExcludeByAttribute)
duplicacy.SavePassword(*preference, "password", password)
loadRSAPrivateKey(context.String("key"), context.String("key-passphrase"), preference, backupManager, false)
backupManager.SetupSnapshotCache(preference.Name)
failed := backupManager.Restore(repository, revision, true, quickMode, threads, overwrite, deleteMode, setOwner, showStatistics, patterns, persist)
if failed > 0 {
duplicacy.LOG_ERROR("RESTORE_FAIL", "%d file(s) were not restored correctly", failed)
return
}
runScript(context, preference.Name, "post")
}
func listSnapshots(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
if len(context.Args()) != 0 {
fmt.Fprintf(context.App.Writer, "The %s command requires no arguments.\n\n", context.Command.Name)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
repository, preference := getRepositoryPreference(context, "")
duplicacy.LOG_INFO("STORAGE_SET", "Storage set to %s", preference.StorageURL)
runScript(context, preference.Name, "pre")
resetPassword := context.Bool("reset-passwords")
storage := duplicacy.CreateStorage(*preference, resetPassword, 1)
if storage == nil {
return
}
password := ""
if preference.Encrypted {
password = duplicacy.GetPassword(*preference, "password", "Enter storage password:",
false, resetPassword)
}
tag := context.String("t")
revisions := getRevisions(context)
backupManager := duplicacy.CreateBackupManager(preference.SnapshotID, storage, repository, password, "", "", preference.ExcludeByAttribute)
duplicacy.SavePassword(*preference, "password", password)
id := preference.SnapshotID
if context.Bool("all") {
id = ""
} else if context.String("id") != "" {
id = context.String("id")
}
showFiles := context.Bool("files")
showChunks := context.Bool("chunks")
// list doesn't need to decrypt file chunks; but we need -key here so we can reset the passphrase for the private key
loadRSAPrivateKey(context.String("key"), "", preference, backupManager, resetPassword)
backupManager.SetupSnapshotCache(preference.Name)
backupManager.SnapshotManager.ListSnapshots(id, revisions, tag, showFiles, showChunks)
runScript(context, preference.Name, "post")
}
func checkSnapshots(context *cli.Context) {
setGlobalOptions(context)
defer duplicacy.CatchLogException()
if len(context.Args()) != 0 {
fmt.Fprintf(context.App.Writer, "The %s command requires no arguments.\n\n", context.Command.Name)
cli.ShowCommandHelp(context, context.Command.Name)
os.Exit(ArgumentExitCode)
}
repository, preference := getRepositoryPreference(context, "")
duplicacy.LOG_INFO("STORAGE_SET", "Storage set to %s", preference.StorageURL)
runScript(context, preference.Name, "pre")
threads := context.Int("threads")
if threads < 1 {
threads = 1
}
storage := duplicacy.CreateStorage(*preference, false, threads)
if storage == nil {
return
}
password := ""
if preference.Encrypted {
password = duplicacy.GetPassword(*preference, "password", "Enter storage password:", false, false)
}
tag := context.String("t")
revisions := getRevisions(context)
backupManager := duplicacy.CreateBackupManager(preference.SnapshotID, storage, repository, password, "", "", false)
duplicacy.SavePassword(*preference, "password", password)
loadRSAPrivateKey(context.String("key"), context.String("key-passphrase"), preference, backupManager, false)
id := preference.SnapshotID
if context.Bool("all") {
id = ""
} else if context.String("id") != "" {
id = context.String("id")
}