-
Notifications
You must be signed in to change notification settings - Fork 0
/
gdsnap.go
1277 lines (1192 loc) · 36.8 KB
/
gdsnap.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
package main
import (
"bufio"
"bytes"
"compress/flate"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
)
func usage() {
o := flag.CommandLine.Output()
fmt.Fprintln(o, `gdsnap: google drive snapshotter
usage: gdsnap [global flags...] subcommand [args...]
periodically snapshots the changed files of a directory to gdrive as a backup.
to use: set up the right -dir and -gdir flags (ideally in a config file),
then use the auth subcommand to authorize,
and then run the watch command as a daemon to back up data continuosly.
if you want to restore, use the restore subcommand.
you can alter the -dir flag for restore in case you want to restore files somewhere else.
subcommands:
auth: authorize a gdrive account for gdsnap.
cat: prints a file from the archive.
diff: diff the whole tree or specific files. the diff is between gdrive and the files on disk.
help: print help about a subcommand.
list: list gdrive metadata.
quota: print gdrive quota usage and limit.
restore: restores files from the backup (destructive operation!).
save: snapshot a specific file.
watch: watch target directory for changes and back them up.
config files:
gdsnap reads in ~/.gdsnap, ~/.config/gdsnap and finally ~/.cache/gdsnap config files.
each config line is either a comment line starting with # or of the following format:
[profile] [flagname] "[value in quotes]"
profile is usually the hostname on which the flag applies or * to apply to all profiles.
it allows using a single config file for configuring backups for multiple devices.
example:
* refreshtoken "abcdef"
* gdir "1234"
# work stuff goes somewhere else.
worklaptop dir "/home/myuser/work"
worklaptop gdir "5678"
the refreshtoken is sensitive piece of data, you might want to put that into the separate .cache/gdsnap file.
globs:
the globs can contain "*" or "**", other wildcards like "?" are not supported.
"**" matches / (the directory separator) too.
e.g. ".cache/**", say, for the -ignore means to ignore all files under the .cache directory.
cat/diff/list/restore accept globs as arguments.
globs starting with / are absolute globs and the root is relative to -dir.
the current relative path from dir is prepended for relative globs.
e.g. .gitignore will be translated to $(dir)/path/to/currentwd/.gitignore.
thanks to this cat/diff/list/restore are easy to use with files in the current directory.
signals:
during the watch command sigint (ctrl+c) triggers an early backup cycle.
use sigquit to quit (ctrl+/).
otherwise sigint is fine for cancelling all the other operations.
implementation details:
all the files are backed up to gdrive.
the contents are encrypted but the filenames are not to keep the system easy to debug.
gdrive tracks the last 100 revisions of each file so those can restored too.
use the -t flag to specify a revision other than the head revision.
some file metadata is stored in the mimetype of the revision:
- gdsnap/deleted: the file is non-existent at this revision.
if this is the head version, the file is also moved to the trash
which is then deleted after 30 days.
- gdsnap/symlink: the file is a symlink and the contents is the target file.
the contents of this is not encrypted.
- gdsnap/data???: ordinary file. ??? is an octal number of the permissions
that restore will use when restoring a file.
cleanup:
if you want to purge your data from gdrive
then move all the gdsnap related files (i.e. all files from your backup directory) to trash.
then empty your trash and the data is then irrevocably gone from gdrive.
global flags:`)
flag.PrintDefaults()
}
var (
cycledurFlag = flag.Duration("cycledur", 20*time.Minute, "the time to wait between backup cycles. relevant only for the watch subcommand.")
dirFlag = flag.String("dir", os.Getenv("PWD"), "the root directory under which to operate recursively.")
gdirFlag = flag.String("gdir", "", "the gdrive directory under which to to save the files.")
ignoreFlag = flag.String("ignore", "", "comma separated list of globs that save/watch ignores to upload.")
sizelimitmbFlag = flag.Int("sizelimitmb", 20, "size limit of the maximum file in megabytes. make sure to pick a limit that comfortably fits into memory.")
passwordFlag = flag.String("password", "", "the password to encrypt the files with. if empty, the files are encrypted with an empty password.")
profileFlag = flag.String("profile", hostname(), "flag defaults selector for the gdsnap config files.")
refreshtokenFlag = flag.String("refreshtoken", "", "the oauth2 refresh token needed for accessing gdrive. generate one with the auth subcommand.")
tFlag = flag.String("t", "", "time offset for cat/diff/restore operations. either a duration from now or an absolute utc time value. default is the head revision for each file.")
warncmdFlag = flag.String("warncmd", "", "run command on warning-level events. the command should notify you about the event. static flags can be specified, separate them with space.")
)
const (
oaClientID = "1076973936178-12a8rasuan6erslop5nkqe088cce31p8.apps.googleusercontent.com"
oaSecret = "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"
)
type fileinfo struct {
Name string
ID string
Size string
Trashed bool
MimeType string
ModifiedTime string
MD5Checksum string
}
type gdsnap struct {
accesstoken string
tokenbirth time.Time
files map[string]fileinfo
ignore []string
gcm cipher.AEAD
nonce []byte
}
func hostname() string {
h, err := os.Hostname()
if err != nil {
log.Fatalf("couldn't look up hostname: %v", err)
}
return h
}
// matchglob matches simple globs.
// only supports * and **.
// * matches everything except /, ** matches / too.
func matchglob(pattern, name string) bool {
laststar, lastdstar := -1, -1
p, n := 0, 0
for n < len(name) {
if p == len(pattern) {
if name[n] == '/' {
if lastdstar != -1 {
laststar = lastdstar
p = lastdstar
n++
continue
}
return false
}
if laststar != -1 {
p = laststar
n++
continue
}
return false
}
if pattern[p] == '*' {
stars := 0
for p < len(pattern) && pattern[p] == '*' {
p++
stars++
}
laststar = p
if stars >= 2 {
lastdstar = p
}
continue
}
if name[n] == '/' {
laststar = -1
}
if name[n] == pattern[p] {
n++
p++
} else {
if laststar != -1 {
p = laststar
} else if lastdstar != -1 {
laststar = lastdstar
p = lastdstar
} else {
return false
}
n++
}
}
for p < len(pattern) && pattern[p] == '*' {
p++
}
return p == len(pattern)
}
// fullglobs prepends the local directory to the relative globs from the args.
func fullglobs(args []string) []string {
cwd, err := os.Getwd()
if err != nil {
log.Fatalf("couldn't determine current working dir: %v", err)
}
pathprefix, err := filepath.Rel(*dirFlag, cwd)
if err != nil || strings.HasPrefix(pathprefix, "..") {
pathprefix = ""
}
globs := make([]string, len(args))
for i, a := range args {
if !strings.HasPrefix(a, "/") {
a = path.Join(pathprefix, a)
}
globs[i] = strings.TrimLeft(a, "/")
}
return globs
}
// filterfiles returns the list of filenames that match at least one of the globs.
// the current directory will be added to the relative entries in globs.
func filterfiles(files map[string]fileinfo, globs []string) []string {
globs = fullglobs(globs)
filelist := []string{}
for f := range files {
if len(globs) > 0 {
match := false
for _, glob := range globs {
if matchglob(glob, f) {
match = true
break
}
}
if !match {
continue
}
}
filelist = append(filelist, f)
}
sort.Strings(filelist)
return filelist
}
// watchdir streams the changed filenames on filech.
func watchdir(filech chan<- string) {
log.Printf("initializing inotify rooted at %q.", *dirFlag)
watches := map[int]string{}
ifd, err := syscall.InotifyInit()
if err != nil {
log.Fatal(err)
}
var watchpath func(string)
watchpath = func(dirpath string) {
var mask uint32
mask |= syscall.IN_CLOSE_WRITE
mask |= syscall.IN_CREATE
mask |= syscall.IN_DELETE
mask |= syscall.IN_MOVED_FROM
mask |= syscall.IN_MOVED_TO
mask |= syscall.IN_DONT_FOLLOW
mask |= syscall.IN_EXCL_UNLINK
mask |= syscall.IN_ONLYDIR
var wd int
if wd, err = syscall.InotifyAddWatch(ifd, dirpath, mask); err != nil {
log.Fatal(err)
}
watches[wd] = dirpath
walkfunc := func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Printf("[warning] can't walk %s: %v", path, err)
warn()
return nil
}
if !d.IsDir() {
filech <- path
return nil
}
if path == dirpath {
return nil
}
watchpath(path)
return fs.SkipDir
}
filepath.WalkDir(dirpath, walkfunc)
}
watchpath(*dirFlag)
log.Print("watching inotify events.")
for {
const bufsize = 16384
eventbuf := [bufsize]byte{}
n, err := syscall.Read(ifd, eventbuf[:])
if n <= 0 || err != nil {
log.Fatal(err)
}
for offset := 0; offset < n; {
if n-offset < syscall.SizeofInotifyEvent {
log.Fatalf("invalid inotify read: n:%d offset:%d.", n, offset)
}
event := (*syscall.InotifyEvent)(unsafe.Pointer(&eventbuf[offset]))
wd := int(event.Wd)
mask := int(event.Mask)
namelen := int(event.Len)
namebytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&eventbuf[offset+syscall.SizeofInotifyEvent]))
name := string(bytes.TrimRight(namebytes[0:namelen], "\000"))
dir, ok := watches[wd]
if !ok {
log.Fatalf("unknown watch descriptor %d.", wd)
}
name = path.Join(dir, name)
if mask&syscall.IN_IGNORED != 0 {
delete(watches, wd)
}
if mask&syscall.IN_CREATE != 0 || mask&syscall.IN_MOVED_TO != 0 {
fi, err := os.Stat(name)
if err == nil && fi.IsDir() {
watchpath(name)
}
}
filech <- name
offset += syscall.SizeofInotifyEvent + namelen
}
}
}
func warn() {
os.Stdout.WriteString("\a")
if len(*warncmdFlag) == 0 {
return
}
args := strings.Fields(*warncmdFlag)
cmd := exec.Command(args[0], args[1:]...)
if err := cmd.Run(); err != nil {
log.Printf("couldn't execute -warncmd: %v", err)
}
}
func (gs *gdsnap) listfiles() {
if len(gs.accesstoken) == 0 {
gs.gettoken()
}
files := map[string]fileinfo{}
type listResponseType struct {
IncompleteSearch bool
NextPageToken string
Files []fileinfo
}
// list existing files.
q := url.Values{}
q.Set("fields", "files(name,id,size,mimeType,modifiedTime,trashed,md5Checksum,properties),nextPageToken,incompleteSearch")
q.Set("pageSize", "1000")
q.Set("q", fmt.Sprintf("'%s' in parents and properties has {key='gdsnap.profile' and value='%s'}", *gdirFlag, *profileFlag))
for {
listreq, err := http.NewRequest("GET", "https://www.googleapis.com/drive/v3/files?"+q.Encode(), nil)
if err != nil {
log.Fatal(err)
}
listreq.Header.Set("Accept", "application/json")
listreq.Header.Set("Authorization", "Bearer "+gs.accesstoken)
listresp, err := http.DefaultClient.Do(listreq)
if err != nil {
log.Fatalf("error listing files: %v", err)
}
listbody, err := io.ReadAll(listresp.Body)
if err != nil {
log.Fatalf("couldn't list everything: %v", err)
}
var r listResponseType
if err = json.Unmarshal(listbody, &r); err != nil {
log.Fatalf("couldn't parse list response: %v\nbody:\n%s", err, listbody)
}
if r.IncompleteSearch {
log.Fatal("response was incomplete.")
}
for _, f := range r.Files {
files[f.Name] = f
}
if len(r.NextPageToken) == 0 {
break
}
q.Set("pageToken", r.NextPageToken)
}
gs.files = files
}
func (gs *gdsnap) init() {
if len(*ignoreFlag) > 0 {
gs.ignore = strings.Split(*ignoreFlag, ",")
}
key := sha256.Sum256([]byte("a long static string for salt;" + *passwordFlag))
c, err := aes.NewCipher(key[:])
if err != nil {
log.Fatalf("couldn't create encryption cipher: %v", err)
}
gs.gcm, err = cipher.NewGCM(c)
if err != nil {
log.Fatalf("couldn't create gcm cipher: %v", err)
}
// empty nonce so that md5sum checksumming works.
// ummm.... i guess aes is good enough on its own.
gs.nonce = make([]byte, gs.gcm.NonceSize())
}
type gfileProperties struct {
Name string `json:"name,omitempty"`
Parents []string `json:"parents,omitempty"`
Properties map[string]string `json:"properties,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty"`
Trashed *bool `json:"trashed,omitempty"`
}
func (gs *gdsnap) savepath(abspath string, verbose bool) {
if !strings.HasPrefix(abspath, *dirFlag) {
log.Printf("skipping %s because it's not under %s.", abspath, *dirFlag)
return
}
relpath := abspath[len(*dirFlag):]
for _, ign := range gs.ignore {
if matchglob(ign, relpath) {
return
}
}
fi, exist := gs.files[relpath]
finfo, err := os.Lstat(abspath)
if err != nil && (!exist || fi.Trashed) {
if verbose {
log.Printf("skipping %s because can't stat it and it's not on gdrive either: %v.", relpath, err)
}
return
}
var contents []byte
var needTrashing bool
var modtime string
newfi := fi
if err != nil {
needTrashing = true
newfi.Trashed = true
newfi.MimeType = "gdsnap/deleted"
} else {
newfi.Trashed = false
newfi.MimeType = fmt.Sprintf("gdsnap/data%03o", finfo.Mode().Perm())
// save all files under a directory if abspath is a directory.
if finfo.IsDir() {
walk := func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Printf("filepath.WalkDir(%s) error: %v", path, err)
}
if !d.IsDir() {
gs.savepath(path, verbose)
}
return nil
}
if err := filepath.WalkDir(abspath, walk); err != nil {
log.Printf("couldn't fully walk %s: %v", relpath, err)
}
return
}
modtime = finfo.ModTime().UTC().Format("2006-01-02T15:04:05.000Z")
newfi.ModifiedTime = modtime
if !fi.Trashed && modtime == fi.ModifiedTime {
return
}
if finfo.Mode().Type() == fs.ModeSymlink {
symlink, err := os.Readlink(abspath)
if err != nil {
log.Printf("skipping %s because couldn't read the symlink: %v", relpath, err)
}
newfi.MimeType = "gdsnap/symlink"
contents = []byte(symlink)
} else if !finfo.Mode().IsRegular() {
log.Printf("skipping %s because it's not a regular file.", relpath)
return
} else {
if finfo.Size() > int64(*sizelimitmbFlag)*1e6 {
log.Printf("[warning] skipping %s because it's too big (%d MB); bump --sizelimit or ignore.", relpath, finfo.Size()/1e6)
warn()
return
}
rawcontents, err := os.ReadFile(abspath)
if err != nil {
log.Printf("[warning] couldn't load %s: %v", relpath, err)
warn()
return
}
// compress and encrypt the file.
compressed := &bytes.Buffer{}
compressor, err := flate.NewWriter(compressed, 9)
if err != nil {
log.Fatalf("couldn't create compressor %s: %v", relpath, err)
}
if n, err := compressor.Write(rawcontents); n != len(rawcontents) || err != nil {
log.Fatalf("couldn't compress %s: %v", relpath, err)
}
if err := compressor.Close(); err != nil {
log.Fatalf("couldn't close compressor for %s: %v", relpath, err)
}
contents = gs.gcm.Seal(nil, gs.nonce, compressed.Bytes(), nil)
// skip if md5sum already matches.
md5sum := md5.Sum(contents)
md5str := hex.EncodeToString(md5sum[:])
newfi.Size = strconv.Itoa(len(contents))
newfi.MD5Checksum = md5str
if !fi.Trashed && newfi.Size == fi.Size && md5str == fi.MD5Checksum {
return
}
}
}
gs.gettoken()
ct := gfileProperties{}
if !exist {
ct = gfileProperties{
Name: relpath,
Parents: []string{*gdirFlag},
Properties: map[string]string{"gdsnap.profile": *profileFlag},
}
} else {
ct = gfileProperties{
Name: relpath,
Trashed: &needTrashing,
}
}
if !needTrashing {
ct.ModifiedTime = modtime
}
createData, err := json.Marshal(ct)
if err != nil {
log.Fatalf("couldn't create properties for %s: %v", relpath, err)
}
if len(contents) > 5e6 {
// large files must be uploaded using 2 separate requests.
var startReq *http.Request
if exist {
startReq, err = http.NewRequest("PATCH", "https://www.googleapis.com/upload/drive/v3/files/"+fi.ID+"?uploadType=resumable", bytes.NewReader(createData))
} else {
startReq, err = http.NewRequest("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable", bytes.NewReader(createData))
}
if err != nil {
log.Fatalf("couldn't create largefile upload request for %s: %v", relpath, err)
}
startReq.Header.Set("Authorization", "Bearer "+gs.accesstoken)
startReq.Header.Set("Content-Type", "application/json; charset=UTF-8")
startReq.Header.Set("X-Upload-Content-Type", newfi.MimeType)
startReq.Header.Set("X-Upload-Content-Length", strconv.Itoa(len(contents)))
startResp, err := http.DefaultClient.Do(startReq)
if err != nil {
log.Fatalf("largefile upload start for %s failed: %v", relpath, err)
}
if startResp.StatusCode != 200 {
body, _ := io.ReadAll(startResp.Body)
log.Fatalf("largefile upload start for %s returned error: %s\n%s", relpath, startResp.Status, body)
}
loc := startResp.Header.Get("Location")
if len(loc) == 0 {
log.Fatalf("missing upload location when uploading %s", relpath)
}
uploadReq, err := http.NewRequest("PUT", loc, bytes.NewReader(contents))
if err != nil {
log.Fatalf("couldn't create largefile upload start request for %s: %v.", relpath, err)
}
uploadResp, err := http.DefaultClient.Do(uploadReq)
if err != nil {
log.Fatalf("largefile upload for %s failed: %v.", relpath, err)
}
if startResp.StatusCode != 200 {
body, _ := io.ReadAll(startResp.Body)
log.Fatalf("largefile upload for %s returned error: %s\n%s", relpath, uploadResp.Status, body)
}
log.Printf("%s uploaded (was a large file).", relpath)
return
}
reqBuf := &bytes.Buffer{}
w := multipart.NewWriter(reqBuf)
mimeHeader := textproto.MIMEHeader{}
mimeHeader.Set("Content-Type", "application/json; charset=UTF-8")
metadataWriter, err := w.CreatePart(mimeHeader)
if err != nil {
log.Fatalf("failed %s because couldn't create metadata part: %v", relpath, err)
}
metadataWriter.Write(createData)
mimeHeader.Set("Content-Type", newfi.MimeType)
contentWriter, err := w.CreatePart(mimeHeader)
if err != nil {
log.Fatalf("failed %s because couldn't create content part: %v", relpath, err)
}
contentWriter.Write(contents)
w.Close()
var createReq *http.Request
if exist {
createReq, err = http.NewRequest("PATCH", "https://www.googleapis.com/upload/drive/v3/files/"+fi.ID+"?uploadType=multipart", bytes.NewReader(reqBuf.Bytes()))
} else {
createReq, err = http.NewRequest("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", bytes.NewReader(reqBuf.Bytes()))
}
if err != nil {
log.Fatalf("couldn't create upload/create request for %s: %v", relpath, err)
}
createReq.Header.Set("Authorization", "Bearer "+gs.accesstoken)
createReq.Header.Set("Accept", "application/json")
createReq.Header.Set("Content-Type", "multipart/related; boundary="+w.Boundary())
createResp, err := http.DefaultClient.Do(createReq)
if err != nil {
log.Fatalf("creation of %s failed: %v.", relpath, err)
}
createBody, err := io.ReadAll(createResp.Body)
if err != nil {
log.Fatalf("couldn't read create response for %s: %v", relpath, err)
}
if createResp.StatusCode != 200 {
log.Fatalf("creation of %s failed with %q:\n%s", relpath, createResp.Status, createBody)
}
gs.files[relpath] = newfi
log.Printf("%s updated.", relpath)
}
func (gs *gdsnap) subcommandWatch(args []string) {
if len(args) != 0 {
log.Fatalf("error: unexpected cmdline arguments.")
}
gs.gettoken()
gs.checkQuota()
log.Print("initial scan: updating/deleting files seen on gdrive.")
gs.listfiles()
for _, f := range gs.files {
if !f.Trashed {
gs.savepath(path.Join(*dirFlag, f.Name), true)
}
}
log.Print("initial scan: creating new files seen on disk.")
gs.savepath(*dirFlag, true)
filech := make(chan string, 1000)
go watchdir(filech)
// handle the initial scan from the inotify watch.
log.Print("waiting for the changes to subside for a moment.")
initloop:
for {
select {
case fn := <-filech:
gs.savepath(fn, true)
default:
select {
case fn := <-filech:
gs.savepath(fn, true)
case <-time.After(3 * time.Second):
break initloop
}
}
}
sigintch := make(chan os.Signal, 2)
signal.Notify(sigintch, syscall.SIGINT)
runtime.GC()
log.Print("main loop started: will track changed files and periodically upload them.")
timer := time.NewTimer(*cycledurFlag)
touched := map[string]bool{}
for {
wasSIGINT := false
select {
case fn := <-filech:
touched[fn] = true
continue
case <-timer.C:
case <-sigintch:
wasSIGINT = true
if len(touched) == 0 {
log.Printf("got a sigint but skipping backup cycle since nothing changed (use sigquit to quit).")
} else {
log.Printf("got a sigint, running a backup cycle for %d files (use sigquit to quit).", len(touched))
}
}
if len(touched) > 0 {
gs.gettoken()
gs.checkQuota()
gs.listfiles()
for fn := range touched {
delete(touched, fn)
gs.savepath(fn, false)
}
if wasSIGINT {
log.Printf("backup cycle done.")
}
// it's the perfect time to collect the garbage from this cycle.
runtime.GC()
}
timer.Stop()
timer.Reset(*cycledurFlag)
}
}
func (gs *gdsnap) subcommandAuth(args []string) {
if len(args) != 0 {
log.Fatalf("error: unexpected cmdline arguments.")
}
if len(*refreshtokenFlag) > 0 {
log.Fatal(`-refreshtoken already defined. use "gdsnap -refreshtoken= auth" to force auth regardless.`)
}
q := url.Values{}
q.Set("client_id", oaClientID)
q.Set("scope", "https://www.googleapis.com/auth/drive.file")
q.Set("response_type", "code")
q.Set("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
u := "https://accounts.google.com/o/oauth2/auth?" + q.Encode()
fmt.Printf("please visit %s and authorize. enter response code here:\n", u)
var authcode string
if _, err := fmt.Scan(&authcode); err != nil {
log.Fatalf("authcode parse error: %v", err)
}
q = url.Values{}
q.Set("code", authcode)
q.Set("client_id", oaClientID)
q.Set("client_secret", oaSecret)
q.Set("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
q.Set("grant_type", "authorization_code")
response, err := http.Post("https://oauth2.googleapis.com/token", "application/x-www-form-urlencoded", strings.NewReader(q.Encode()))
if err != nil {
log.Fatal(err)
}
responseBody, err := io.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
response.Body.Close()
var r map[string]interface{}
if err = json.Unmarshal(responseBody, &r); err != nil {
log.Fatal(err)
}
rt, ok := r["refresh_token"].(string)
if !ok {
log.Fatalf("couldn't parse refresh_token from response. full response:\n%s", string(responseBody))
}
fmt.Println("add the following to ~/.gdsnap, ~/.config/gdsnap, or ~/.cache/gdsnap (this is a sensitive token, don't share this!):")
fmt.Printf("* refreshtoken %q\n", rt)
}
func (gs *gdsnap) subcommandList(args []string) {
gs.listfiles()
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
q := url.Values{}
q.Set("fields", "revisions(originalFilename,id,size,modifiedTime,mimeType,md5Checksum)")
q.Set("pageSize", "1000")
for _, f := range filterfiles(gs.files, args) {
fi := gs.files[f]
fmt.Fprintf(out, "%+v\n", fi)
req, err := http.NewRequest("GET", "https://www.googleapis.com/drive/v3/files/"+fi.ID+"/revisions?"+q.Encode(), nil)
if err != nil {
log.Fatalf("couldn't create request for %s: %v", f, err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+gs.accesstoken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("error listing revisions for %s: %v", f, err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("error reading revisions for %s: %v", f, err)
}
fmt.Fprintln(out, string(body))
fmt.Fprintln(out)
}
}
func (gs *gdsnap) subcommandSave(args []string) {
if len(args) == 0 {
fmt.Println("usage: gdsnap [flags...] save [file...]")
return
}
gs.listfiles()
for _, f := range args {
fullpath, err := filepath.Abs(f)
if err != nil {
log.Fatalf("couldn't create absolute path for %s: %s", f, err)
}
if fullpath == (*dirFlag)[:len(*dirFlag)-1] {
fullpath += "/"
}
gs.savepath(fullpath, true)
}
}
func (gs *gdsnap) decrypt(fi *fileinfo, mime string, content []byte) (string, []byte) {
if !strings.HasPrefix(mime, "gdsnap/data") {
return mime, content
}
// decrypt and decompress the file.
compressed, err := gs.gcm.Open(nil, gs.nonce, content, nil)
if err != nil {
log.Printf("couldn't decrypt %s: %v", fi.Name, err)
return mime, content
}
decompressor := flate.NewReader(bytes.NewBuffer(compressed))
if content, err = io.ReadAll(decompressor); err != nil {
log.Printf("couldn't decompress %s: %v", fi.Name, err)
return mime, content
}
if err = decompressor.Close(); err != nil {
log.Printf("couldn't close the decompressor for %s: %v", fi.Name, err)
}
return mime, content
}
// revfetch fetches the content at a specific version.
// the content fetching is skipped if the revision's last modified time equals to skipDate.
func (gs *gdsnap) revfetch(fi *fileinfo, skipDate string) (mime string, content []byte) {
if len(*tFlag) == 0 || fi.ModifiedTime <= *tFlag {
if fi.ModifiedTime == skipDate {
return fi.MimeType, nil
}
getreq, err := http.NewRequest("GET", "https://www.googleapis.com/drive/v3/files/"+fi.ID+"?alt=media", nil)
if err != nil {
log.Fatal(err)
}
getreq.Header.Set("Authorization", "Bearer "+gs.accesstoken)
getresp, err := http.DefaultClient.Do(getreq)
if err != nil {
log.Fatalf("error fetching contents for %s: %v", fi.Name, err)
}
contents, err := io.ReadAll(getresp.Body)
if err != nil {
log.Fatalf("error reading contents for %s: %v", fi.Name, err)
}
return gs.decrypt(fi, fi.MimeType, contents)
}
type revinfo struct {
ID string
MimeType string
ModifiedTime string
}
q := url.Values{}
q.Set("fields", "revisions(originalFilename,id,size,modifiedTime,mimeType,md5Checksum)")
q.Set("pageSize", "1000")
req, err := http.NewRequest("GET", "https://www.googleapis.com/drive/v3/files/"+fi.ID+"/revisions?"+q.Encode(), nil)
if err != nil {
log.Fatalf("couldn't create request for %s: %v", fi.Name, err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+gs.accesstoken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("error listing revisions for %s: %v", fi.Name, err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("error reading revisions for %s: %v", fi.Name, err)
}
var revisionsResponse struct {
Revisions []revinfo
}
if err = json.Unmarshal(body, &revisionsResponse); err != nil {
log.Fatalf("couldn't parse revisions response: %v\nbody:\n%s", err, body)
}
var ri *revinfo
for i, r := range revisionsResponse.Revisions {
if r.ModifiedTime > *tFlag {
continue
}
if ri == nil || r.ModifiedTime > ri.ModifiedTime {
ri = &revisionsResponse.Revisions[i]
}
}
if ri == nil {
return "gdsnap/deleted", nil
}
if ri.ModifiedTime == skipDate {
return ri.MimeType, nil
}
getreq, err := http.NewRequest("GET", "https://www.googleapis.com/drive/v3/files/"+fi.ID+"/revisions/"+ri.ID+"?alt=media", nil)
if err != nil {
log.Fatal(err)
}
getreq.Header.Set("Authorization", "Bearer "+gs.accesstoken)
getresp, err := http.DefaultClient.Do(getreq)
if err != nil {
log.Fatalf("error fetching contents for %s: %v", fi.Name, err)
}
contents, err := io.ReadAll(getresp.Body)
if err != nil {
log.Fatalf("error reading contents for %s: %v", fi.Name, err)
}
return gs.decrypt(fi, ri.MimeType, contents)
}
func (gs *gdsnap) subcommandCat(args []string) {
gs.listfiles()
for _, relpath := range filterfiles(gs.files, args) {
fi := gs.files[relpath]
mime, contents := gs.revfetch(&fi, "")
switch mime {
case "gdsnap/deleted":
fmt.Printf("%s is deleted.", relpath)
case "gdsnap/symlink":
fmt.Printf("%s is a symlink to %s.", relpath, contents)
default:
os.Stdout.Write(contents)
}
}
}
func (gs *gdsnap) subcommandDiff(args []string) {
gs.listfiles()
for _, relpath := range filterfiles(gs.files, args) {
fi, ok := gs.files[relpath]
if !ok {
log.Fatalf("%s is not backed up.", relpath)
}
fullpath, err := filepath.Abs(filepath.Join(*dirFlag, relpath))
finfo, err := os.Lstat(fullpath)
if err != nil {
mime, _ := gs.revfetch(&fi, fi.ModifiedTime)
if mime != "gdsnap/deleted" {
fmt.Printf("skipping %s because can't stat it: %v.\n", relpath, err)
}
continue
}
const tLayout = "2006-01-02T15:04:05.000Z"
fileDate := finfo.ModTime().UTC().Format(tLayout)
mime, contents := gs.revfetch(&fi, fileDate)
if mime == "gdsnap/deleted" {
fmt.Printf("skipping %s because because it's trashed in the archive.\n", relpath)
continue
}
if contents == nil {
// revfetch returns nil if the revision's mod time is fileDate.
// it means there wasn't any diff so let's further diffing.
continue
}
filetype := "regular file"
if finfo.Mode().Type() == fs.ModeSymlink {
filetype = "symlink"
} else if !finfo.Mode().IsRegular() {
fmt.Printf("skipping %s because it's not a regular file.\n", relpath)
continue
}
backuptype := "regular file"
if mime == "gdsnap/symlink" {
backuptype = "symlink"
}
if filetype != backuptype {
fmt.Printf("%s differs in type: -%s vs +%s.\n", relpath, backuptype, filetype)
continue
}
if backuptype == "symlink" {
symlink, err := os.Readlink(fullpath)
if err != nil {
log.Printf("can't read symlink for %s: %v", relpath, err)
continue
}
strcontents := string(contents)
if strcontents != symlink {
fmt.Printf("--- archive/%s\n+++ archive/%s\n-%s\n+%s\n", relpath, relpath, strcontents, symlink)
}
continue
}