/
simplefs.go
3569 lines (3244 loc) · 99.1 KB
/
simplefs.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 2016-2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package simplefs
import (
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
stdpath "path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/adamwalz/keybase-client/go/kbfs/data"
"github.com/adamwalz/keybase-client/go/kbfs/env"
"github.com/adamwalz/keybase-client/go/kbfs/idutil"
"github.com/adamwalz/keybase-client/go/kbfs/kbfscrypto"
"github.com/adamwalz/keybase-client/go/kbfs/kbfsmd"
"github.com/adamwalz/keybase-client/go/kbfs/libcontext"
"github.com/adamwalz/keybase-client/go/kbfs/libfs"
"github.com/adamwalz/keybase-client/go/kbfs/libhttpserver"
"github.com/adamwalz/keybase-client/go/kbfs/libkbfs"
"github.com/adamwalz/keybase-client/go/kbfs/search"
"github.com/adamwalz/keybase-client/go/kbfs/tlf"
"github.com/adamwalz/keybase-client/go/kbfs/tlfhandle"
"github.com/adamwalz/keybase-client/go/libkb"
"github.com/adamwalz/keybase-client/go/logger"
"github.com/adamwalz/keybase-client/go/protocol/keybase1"
"github.com/adamwalz/keybase-client/go/runtimestats"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
billy "gopkg.in/src-d/go-billy.v4"
"gopkg.in/src-d/go-billy.v4/osfs"
)
const (
// CtxOpID is the display name for the unique operation SimpleFS ID tag.
ctxOpID = "SFSID"
)
// CtxTagKey is the type used for unique context tags
type ctxTagKey int
const (
// CtxIDKey is the type of the tag for unique operation IDs.
ctxIDKey ctxTagKey = iota
)
// simpleFSError wraps errors for SimpleFS
type simpleFSError struct {
reason string
code keybase1.StatusCode
}
// Error implements the error interface for simpleFSError
func (e simpleFSError) Error() string { return e.reason }
// ToStatus implements the keybase1.ToStatusAble interface for simpleFSError
func (e simpleFSError) ToStatus() keybase1.Status {
code := e.code
if code == 0 {
code = keybase1.StatusCode_SCGeneric
}
return keybase1.Status{
Name: e.reason,
Code: int(code),
Desc: e.Error(),
}
}
var errOnlyRemotePathSupported = simpleFSError{reason: "Only remote paths are supported for this operation"}
var errInvalidRemotePath = simpleFSError{reason: "Invalid remote path"}
var errNoSuchHandle = simpleFSError{reason: "No such handle"}
var errNoResult = simpleFSError{reason: "Async result not found"}
var errNameExists = simpleFSError{code: keybase1.StatusCode_SCSimpleFSNameExists, reason: "name exists"}
var errDirNotEmpty = simpleFSError{code: keybase1.StatusCode_SCSimpleFSDirNotEmpty, reason: "dir not empty"}
var errNotExist = simpleFSError{code: keybase1.StatusCode_SCSimpleFSNotExist, reason: "file or folder does not exist"}
var errNoAccess = simpleFSError{code: keybase1.StatusCode_SCSimpleFSNoAccess, reason: "no access to this file or folder"}
func translateErr(err error) error {
cause := errors.Cause(err)
switch {
case os.IsExist(cause):
return errNameExists
case os.IsNotExist(cause):
return errNotExist
case cause == os.ErrPermission:
return errNoAccess
}
switch cause.(type) {
case data.NameExistsError:
return errNameExists
case libkbfs.DirNotEmptyError:
return errDirNotEmpty
case idutil.BadTLFNameError, tlf.BadNameError, tlfhandle.ReadAccessError:
return errNoAccess
}
return err
}
type newFSFunc func(
context.Context, libkbfs.Config, *tlfhandle.Handle, data.BranchName,
string, bool) (billy.Filesystem, error)
func defaultNewFS(ctx context.Context, config libkbfs.Config,
tlfHandle *tlfhandle.Handle, branch data.BranchName, subdir string,
create bool) (
billy.Filesystem, error) {
maker := libfs.NewFS
if !create {
maker = libfs.NewFSIfExists
}
return maker(
ctx, config, tlfHandle, branch, subdir, "", keybase1.MDPriorityNormal)
}
// SimpleFS is the simple filesystem rpc layer implementation.
type SimpleFS struct {
// logs for logging - constant, do not need locking.
log logger.Logger
vlog *libkb.VDebugLog
// config for the fs - constant, does not need locking.
config libkbfs.Config
// The function to call for constructing a new KBFS file system.
// Overrideable for testing purposes.
newFS newFSFunc
// For dumping debug info to the logs.
idd *libkbfs.ImpatientDebugDumper
// Indexes synced TLFs.
indexer *search.Indexer
// lock protects handles and inProgress
lock sync.RWMutex
// handles contains handles opened by SimpleFSOpen,
// closed by SimpleFSClose (or SimpleFSCancel) and used
// by listing, reading and writing.
handles map[keybase1.OpID]*handle
// inProgress is for keeping state of operations in progress,
// values are removed by SimpleFSWait (or SimpleFSCancel).
inProgress map[keybase1.OpID]*inprogress
subscribeLock sync.RWMutex
subscribeCurrTlfPathFromGUI string
subscribeCurrFB data.FolderBranch
subscribeToEmptyTlf string
localHTTPServer *libhttpserver.Server
subscriptionNotifier libkbfs.SubscriptionNotifier
downloadManager *downloadManager
uploadManager *uploadManager
httpClient *http.Client
}
type inprogress struct {
desc keybase1.OpDescription
cancel context.CancelFunc
done chan error
progress keybase1.OpProgress
}
type handle struct {
file billy.File
async interface{}
path keybase1.Path
cancel context.CancelFunc
}
// make sure the interface is implemented
var _ keybase1.SimpleFSInterface = (*SimpleFS)(nil)
// We need this wrapper because at the time simpleFS is initialized
// KeybaseService is not initialized yet. So just save config here, and get
// the KeybaseService() later.
type subscriptionNotifier struct {
config libkbfs.Config
}
var _ libkbfs.SubscriptionNotifier = subscriptionNotifier{}
// OnNonPathChange implements the libkbfs.SubscriptionNotifier interface.
func (s subscriptionNotifier) OnPathChange(
clientID libkbfs.SubscriptionManagerClientID,
subscriptionIDs []libkbfs.SubscriptionID,
path string, topics []keybase1.PathSubscriptionTopic) {
ks := s.config.KeybaseService()
if ks == nil {
return
}
ks.OnPathChange(clientID, subscriptionIDs, path, topics)
}
// OnPathChange implements the libkbfs.SubscriptionNotifier interface.
func (s subscriptionNotifier) OnNonPathChange(
clientID libkbfs.SubscriptionManagerClientID,
subscriptionIDs []libkbfs.SubscriptionID,
topic keybase1.SubscriptionTopic) {
ks := s.config.KeybaseService()
if ks == nil {
return
}
ks.OnNonPathChange(clientID, subscriptionIDs, topic)
}
func newSimpleFS(appStateUpdater env.AppStateUpdater, config libkbfs.Config) *SimpleFS {
log := config.MakeLogger("simplefs")
var localHTTPServer *libhttpserver.Server
var err error
if config.Mode().LocalHTTPServerEnabled() {
localHTTPServer, err = libhttpserver.New(appStateUpdater, config)
if err != nil {
log.Fatalf("initializing localHTTPServer error: %v", err)
}
}
var indexer *search.Indexer
if config.Mode().IndexingEnabled() {
newIndexer, err := search.NewIndexer(config)
if err != nil {
log.Warning("Couldn't make indexer: %+v", err)
} else {
indexer = newIndexer
}
}
k := &SimpleFS{
config: config,
handles: map[keybase1.OpID]*handle{},
inProgress: map[keybase1.OpID]*inprogress{},
log: log,
vlog: config.MakeVLogger(log),
newFS: defaultNewFS,
idd: libkbfs.NewImpatientDebugDumperForForcedDumps(config),
indexer: indexer,
localHTTPServer: localHTTPServer,
subscriptionNotifier: subscriptionNotifier{config},
httpClient: &http.Client{},
}
k.downloadManager = newDownloadManager(k)
k.uploadManager = newUploadManager(k)
return k
}
// NewSimpleFS creates a new SimpleFS instance.
func NewSimpleFS(
appStateUpdater env.AppStateUpdater, config libkbfs.Config) (
iface keybase1.SimpleFSInterface,
shutdownFn func(context.Context) error) {
simpleFS := newSimpleFS(appStateUpdater, config)
return simpleFS, simpleFS.Shutdown
}
func (k *SimpleFS) makeContext(ctx context.Context) context.Context {
return libkbfs.CtxWithRandomIDReplayable(ctx, ctxIDKey, ctxOpID, k.log)
}
func (k *SimpleFS) makeContextWithIdentifyBehavior(ctx context.Context, identifyBehavior *keybase1.TLFIdentifyBehavior) (newCtx context.Context, err error) {
newCtx = libkbfs.CtxWithRandomIDReplayable(ctx, ctxIDKey, ctxOpID, k.log)
if identifyBehavior != nil {
newCtx, err = tlfhandle.MakeExtendedIdentify(newCtx, *identifyBehavior)
if err != nil {
return nil, err
}
}
return newCtx, nil
}
func getIdentifyBehaviorFromPath(path *keybase1.Path) (*keybase1.TLFIdentifyBehavior, error) {
if path == nil {
return nil, nil
}
pt, err := path.PathType()
if err != nil {
return nil, err
}
switch pt {
case keybase1.PathType_KBFS:
return path.Kbfs().IdentifyBehavior, nil
case keybase1.PathType_KBFS_ARCHIVED:
return path.KbfsArchived().IdentifyBehavior, nil
default:
return nil, nil
}
}
func populateIdentifyBehaviorIfNeeded(ctx context.Context, path1 *keybase1.Path, path2 *keybase1.Path) (context.Context, error) {
ib1, err := getIdentifyBehaviorFromPath(path1)
if err != nil {
return nil, err
}
ib2, err := getIdentifyBehaviorFromPath(path2)
if err != nil {
return nil, err
}
if ib1 == nil && ib2 == nil {
return ctx, nil
}
if ib1 == nil && ib2 != nil {
return tlfhandle.MakeExtendedIdentify(ctx, *ib2)
}
if ib1 != nil && ib2 == nil {
return tlfhandle.MakeExtendedIdentify(ctx, *ib1)
}
if *ib1 == *ib2 {
return tlfhandle.MakeExtendedIdentify(ctx, *ib1)
}
return nil, errors.New("inconsistent IdentifyBehavior set in both paths")
}
func rawPathFromKbfsPath(path keybase1.Path) (string, error) {
pt, err := path.PathType()
if err != nil {
return "", err
}
switch pt {
case keybase1.PathType_KBFS:
return stdpath.Clean(path.Kbfs().Path), nil
case keybase1.PathType_KBFS_ARCHIVED:
return stdpath.Clean(path.KbfsArchived().Path), nil
default:
return "", errOnlyRemotePathSupported
}
}
func splitPathFromKbfsPath(path keybase1.Path) ([]string, error) {
raw, err := rawPathFromKbfsPath(path)
if err != nil {
return nil, err
}
if stdpath.IsAbs(raw) {
raw = raw[1:]
}
return strings.Split(raw, `/`), nil
}
// remoteTlfAndPath decodes a remote path for us.
func remoteTlfAndPath(path keybase1.Path) (
t tlf.Type, tlfName, middlePath, finalElem string, err error) {
ps, err := splitPathFromKbfsPath(path)
if err != nil {
return tlf.Private, "", "", "", err
}
switch {
case len(ps) < 2:
return tlf.Private, "", "", "", errInvalidRemotePath
case ps[0] == `private`:
t = tlf.Private
case ps[0] == `public`:
t = tlf.Public
case ps[0] == `team`:
t = tlf.SingleTeam
default:
return tlf.Private, "", "", "", errInvalidRemotePath
}
if len(ps) >= 3 {
finalElem = ps[len(ps)-1]
middlePath = stdpath.Join(ps[2 : len(ps)-1]...)
}
return t, ps[1], middlePath, finalElem, nil
}
func (k *SimpleFS) branchNameFromPath(
ctx context.Context, tlfHandle *tlfhandle.Handle, path keybase1.Path) (
data.BranchName, error) {
pt, err := path.PathType()
if err != nil {
return "", err
}
switch pt {
case keybase1.PathType_KBFS:
if tlfHandle.IsLocalConflict() {
b, ok := data.MakeConflictBranchName(tlfHandle)
if ok {
return b, nil
}
}
return data.MasterBranch, nil
case keybase1.PathType_KBFS_ARCHIVED:
archivedParam := path.KbfsArchived().ArchivedParam
archivedType, err := archivedParam.KBFSArchivedType()
if err != nil {
return "", err
}
switch archivedType {
case keybase1.KBFSArchivedType_REVISION:
return data.MakeRevBranchName(
kbfsmd.Revision(archivedParam.Revision())), nil
case keybase1.KBFSArchivedType_TIME:
t := keybase1.FromTime(archivedParam.Time())
rev, err := libkbfs.GetMDRevisionByTime(ctx, k.config, tlfHandle, t)
if err != nil {
return "", err
}
return data.MakeRevBranchName(rev), nil
case keybase1.KBFSArchivedType_TIME_STRING:
t := archivedParam.TimeString()
rev, err := libfs.RevFromTimeString(ctx, k.config, tlfHandle, t)
if err != nil {
return "", err
}
return data.MakeRevBranchName(rev), nil
case keybase1.KBFSArchivedType_REL_TIME_STRING:
t := archivedParam.RelTimeString()
rev, err := libfs.RevFromRelativeTimeString(
ctx, k.config, tlfHandle, t)
if err != nil {
return "", err
}
return data.MakeRevBranchName(rev), nil
default:
return "", simpleFSError{reason: "Invalid archived type for branch name"}
}
default:
return "", simpleFSError{reason: "Invalid path type for branch name"}
}
}
func (k *SimpleFS) getKBPKI(ctx context.Context) (libkbfs.KBPKI, error) {
// Just make sure KBPKI exists before we try to use it. It
// actually gets created after SimpleFS registers as an RPC
// service..
kbpki := k.config.KBPKI()
for kbpki == nil {
t := time.NewTimer(250 * time.Millisecond)
select {
case <-t.C:
kbpki = k.config.KBPKI()
case <-ctx.Done():
_ = t.Stop()
return nil, ctx.Err()
}
}
return kbpki, nil
}
func (k *SimpleFS) getFSWithMaybeCreate(
ctx context.Context, path keybase1.Path, create bool) (
fs billy.Filesystem, finalElem string, err error) {
pt, err := path.PathType()
if err != nil {
return nil, "", err
}
switch pt {
case keybase1.PathType_KBFS, keybase1.PathType_KBFS_ARCHIVED:
// Check for the root FS first.
ps, err := splitPathFromKbfsPath(path)
if err != nil {
return nil, "", err
}
if len(ps) < 2 || len(ps) < 3 && strings.HasPrefix(ps[0], ".kbfs_") {
fs = libfs.NewRootFS(k.config)
if len(ps) == 1 {
finalElem = ps[0]
} else if len(ps) == 2 {
fs, err = fs.Chroot(ps[0])
if err != nil {
return nil, "", err
}
finalElem = ps[1]
}
return fs, finalElem, nil
}
t, tlfName, restOfPath, finalElem, err := remoteTlfAndPath(path)
if err != nil {
return nil, "", err
}
kbpki, err := k.getKBPKI(ctx)
if err != nil {
return nil, "", err
}
tlfHandle, err := libkbfs.GetHandleFromFolderNameAndType(
ctx, kbpki, k.config.MDOps(), k.config, tlfName, t)
if err != nil {
return nil, "", err
}
branch, err := k.branchNameFromPath(ctx, tlfHandle, path)
if err != nil {
return nil, "", err
}
fs, err := k.newFS(
ctx, k.config, tlfHandle, branch, restOfPath, create)
if err != nil {
if exitEarly, _ := libfs.FilterTLFEarlyExitError(
ctx, err, k.log, tlfHandle.GetCanonicalName()); exitEarly {
return nil, finalElem, libfs.TlfDoesNotExist{}
}
return nil, "", err
}
if create {
err = k.checkEmptySubscription(ctx, path)
if err != nil {
return nil, "", err
}
}
return fs, finalElem, nil
case keybase1.PathType_LOCAL:
fs = osfs.New(stdpath.Dir(path.Local()))
return fs, stdpath.Base(path.Local()), nil
default:
return nil, "", simpleFSError{reason: "Invalid path type"}
}
}
func (k *SimpleFS) getFS(
ctx context.Context, path keybase1.Path) (
fs billy.Filesystem, finalElem string, err error) {
return k.getFSWithMaybeCreate(ctx, path, true)
}
func (k *SimpleFS) getFSIfExists(
ctx context.Context, path keybase1.Path) (
fs billy.Filesystem, finalElem string, err error) {
return k.getFSWithMaybeCreate(ctx, path, false)
}
func deTy2Ty(et data.EntryType) keybase1.DirentType {
switch et {
case data.Exec:
return keybase1.DirentType_EXEC
case data.File:
return keybase1.DirentType_FILE
case data.Dir:
return keybase1.DirentType_DIR
case data.Sym:
return keybase1.DirentType_SYM
}
panic("deTy2Ty unreachable")
}
func (k *SimpleFS) favoriteList(ctx context.Context, path keybase1.Path, t tlf.Type) ([]keybase1.Dirent, error) {
kbpki, err := k.getKBPKI(ctx)
if err != nil {
return nil, err
}
session, err := idutil.GetCurrentSessionIfPossible(ctx, kbpki, true)
if err != nil {
return nil, err
}
// Return empty directory listing if we are not logged in.
if session.UID.IsNil() {
return nil, nil
}
k.config.GetPerfLog().CDebugf(ctx, "GetFavorites simplefs.favoriteList")
favs, err := k.config.KBFSOps().GetFavorites(ctx)
if err != nil {
return nil, err
}
res := make([]keybase1.Dirent, 0, len(favs))
for _, fav := range favs {
if fav.Type != t {
continue
}
pname, err := tlf.CanonicalToPreferredName(
session.Name, tlf.CanonicalName(fav.Name))
if err != nil {
k.log.Errorf("CanonicalToPreferredName: %q %v", fav.Name, err)
continue
}
res = append(res, keybase1.Dirent{})
res[len(res)-1].Name = string(pname)
res[len(res)-1].DirentType = deTy2Ty(data.Dir)
handle, err := tlfhandle.ParseHandlePreferredQuick(
ctx, kbpki, k.config, string(pname), t)
if err != nil {
k.log.Errorf("ParseTlfHandlePreferredQuick: %s %q %v", t, pname, err)
continue
}
res[len(res)-1].Writable, err = libfs.IsWriter(
ctx, kbpki, k.config, handle)
if err != nil {
k.log.Errorf("libfs.IsWriter: %q %+v", pname, err)
continue
}
}
return res, nil
}
func (k *SimpleFS) setStat(
de *keybase1.Dirent, fi os.FileInfo, linkFS billy.Filesystem) error {
de.Time = keybase1.ToTime(fi.ModTime())
de.Size = int(fi.Size()) // TODO: FIX protocol
t := data.File
switch {
case fi.IsDir():
t = data.Dir
case fi.Mode()&0100 != 0:
t = data.Exec
case fi.Mode()&os.ModeSymlink != 0:
t = data.Sym
link, err := linkFS.Readlink(fi.Name())
if err != nil {
return err
}
de.SymlinkTarget = link
}
de.DirentType = deTy2Ty(t)
de.Writable = (fi.Mode()&0222 != 0)
if lwg, ok := fi.Sys().(libfs.KBFSMetadataForSimpleFSGetter); ok {
md, err := lwg.KBFSMetadataForSimpleFS()
if err != nil {
return err
}
de.LastWriterUnverified = md.LastWriter
de.PrefetchStatus = md.PrefetchStatus
de.PrefetchProgress = md.PrefetchProgress.ToProtocolProgress(
k.config.Clock())
}
de.Name = fi.Name()
return nil
}
func (k *SimpleFS) setResult(opid keybase1.OpID, val interface{}) {
k.lock.Lock()
k.handles[opid] = &handle{async: val}
k.lock.Unlock()
}
func (k *SimpleFS) startOp(ctx context.Context, opid keybase1.OpID,
opType keybase1.AsyncOps, desc keybase1.OpDescription) (
_ context.Context, w *inprogress, err error) {
ctx = k.makeContext(ctx)
ctx, cancel := context.WithCancel(ctx)
w = &inprogress{
desc,
cancel,
make(chan error, 1),
keybase1.OpProgress{OpType: opType},
}
k.lock.Lock()
k.inProgress[opid] = w
k.lock.Unlock()
// ignore error, this is just for logging.
descBS, _ := json.Marshal(desc)
k.vlog.CLogf(ctx, libkb.VLog1, "start %X %s", opid, descBS)
newCtx, err := k.startOpWrapContext(ctx)
return newCtx, w, err
}
func (k *SimpleFS) doneOp(ctx context.Context, opid keybase1.OpID, w *inprogress, err error) {
// We aren't accessing w.progress directionly but w can still be in there
// so is still protected by the lock.
k.lock.Lock()
w.progress.EndEstimate = keybase1.ToTime(k.config.Clock().Now())
k.lock.Unlock()
w.done <- err
close(w.done)
k.log.CDebugf(ctx, "done op %X, status=%+v", opid, err)
if ctx != nil {
err := libcontext.CleanupCancellationDelayer(ctx)
if err != nil {
k.log.CDebugf(ctx, "Error cancelling delayer: %+v", err)
}
}
}
func (k *SimpleFS) startAsync(
ctx context.Context, opid keybase1.OpID, opType keybase1.AsyncOps,
desc keybase1.OpDescription,
path1ForIdentifyBehavior *keybase1.Path,
path2ForIdentifyBehavior *keybase1.Path,
callback func(context.Context) error) (err error) {
ctxAsync, w, e0 := k.startOp(context.Background(), opid, opType, desc)
if e0 != nil {
return e0
}
ctxAsync, err = populateIdentifyBehaviorIfNeeded(
ctxAsync, path1ForIdentifyBehavior, path2ForIdentifyBehavior)
if err != nil {
return err
}
// Bind the old context to the new context, for debugging purposes.
k.log.CDebugf(ctx, "Launching new async operation with SFSID=%s",
ctxAsync.Value(ctxIDKey))
go func() {
var err error
// Capture the inprogress reference here rather than let doneOp
// retrieve it when called, so that doneOp always has it when it's
// called. This is needed when SimpleFSCancel is called when a
// SimpleFSWait is already in the air. Since SimpleFSCancel deletes the
// inprogress object from k.inProgress, doneOp wouldn't be able to get
// the object when it's called. To make sure SimpleFSWait returns and
// returns the correct error, we just pass in the inprogress reference
// here.
defer func() { k.doneOp(ctxAsync, opid, w, err) }()
err = callback(ctxAsync)
if err != nil {
k.log.CDebugf(ctxAsync, "Error making async callback: %+v", err)
}
}()
return nil
}
func (k *SimpleFS) setProgressTotals(
opid keybase1.OpID, totalBytes, totalFiles int64) {
k.lock.Lock()
defer k.lock.Unlock()
w, ok := k.inProgress[opid]
if !ok {
return
}
w.progress.BytesTotal = totalBytes
w.progress.FilesTotal = totalFiles
w.progress.Start = keybase1.ToTime(k.config.Clock().Now())
}
func (k *SimpleFS) updateReadProgress(
opid keybase1.OpID, readBytes, readFiles int64) {
k.lock.Lock()
defer k.lock.Unlock()
w, ok := k.inProgress[opid]
if !ok {
return
}
w.progress.BytesRead += readBytes
if w.progress.BytesRead > w.progress.BytesTotal {
// Our original total was wrong or we didn't get one.
w.progress.BytesTotal = w.progress.BytesRead
}
w.progress.FilesRead += readFiles
if w.progress.FilesRead > w.progress.FilesTotal {
// Our original total was wrong or we didn't get one.
w.progress.FilesTotal = w.progress.FilesRead
}
}
func (k *SimpleFS) updateWriteProgress(
opid keybase1.OpID, wroteBytes, wroteFiles int64) {
k.lock.Lock()
defer k.lock.Unlock()
w, ok := k.inProgress[opid]
if !ok {
return
}
w.progress.BytesWritten += wroteBytes
if w.progress.BytesWritten > w.progress.BytesTotal {
// Our original total was wrong or we didn't get one.
w.progress.BytesTotal = w.progress.BytesWritten
}
w.progress.FilesWritten += wroteFiles
if w.progress.FilesWritten > w.progress.FilesTotal {
// Our original total was wrong or we didn't get one.
w.progress.FilesTotal = w.progress.FilesWritten
}
}
var filesToIgnore = map[string]bool{
".Trashes": true,
".fseventsd": true,
".DS_Store": true,
}
var prefixesToIgnore = []string{"._"}
func isFiltered(filter keybase1.ListFilter, name string) bool {
switch filter {
case keybase1.ListFilter_NO_FILTER:
return false
case keybase1.ListFilter_FILTER_ALL_HIDDEN:
return strings.HasPrefix(name, ".")
case keybase1.ListFilter_FILTER_SYSTEM_HIDDEN:
if filesToIgnore[name] {
return true
}
for _, prefix := range prefixesToIgnore {
if strings.HasPrefix(name, prefix) {
return true
}
}
return false
}
return false
}
func (k *SimpleFS) getFolderBranchFromPath(
ctx context.Context, path keybase1.Path) (
data.FolderBranch, string, error) {
t, tlfName, _, _, err := remoteTlfAndPath(path)
if err != nil {
return data.FolderBranch{}, "", err
}
kbpki, err := k.getKBPKI(ctx)
if err != nil {
return data.FolderBranch{}, "", err
}
tlfHandle, err := libkbfs.GetHandleFromFolderNameAndType(
ctx, kbpki, k.config.MDOps(), k.config, tlfName, t)
if err != nil {
return data.FolderBranch{}, "", err
}
// Get the root node first to initialize the TLF.
node, _, err := k.config.KBFSOps().GetRootNode(
ctx, tlfHandle, data.MasterBranch)
if err != nil {
return data.FolderBranch{}, "", err
}
if node == nil {
return data.FolderBranch{}, tlfHandle.GetCanonicalPath(), nil
}
return node.GetFolderBranch(), tlfHandle.GetCanonicalPath(), nil
}
func (k *SimpleFS) refreshSubscriptionLocked(
ctx context.Context, path keybase1.Path, tlfPathFromGUI string) error {
// TODO: when favorites caching is ready, handle folder-list paths
// like `/keybase/private` here.
fb, _, err := k.getFolderBranchFromPath(ctx, path)
if err != nil {
return err
}
if fb == (data.FolderBranch{}) {
k.log.CDebugf(
ctx, "Ignoring subscription for empty TLF %q", path)
k.subscribeToEmptyTlf = tlfPathFromGUI
return nil
}
if k.subscribeCurrFB == fb {
k.subscribeToEmptyTlf = ""
return nil
}
if k.subscribeCurrFB != (data.FolderBranch{}) {
err = k.config.Notifier().UnregisterFromChanges(
[]data.FolderBranch{k.subscribeCurrFB}, k)
if err != nil {
return err
}
}
k.log.CDebugf(ctx, "Subscribing to %s", tlfPathFromGUI)
err = k.config.Notifier().RegisterForChanges(
[]data.FolderBranch{fb}, k)
if err != nil {
return err
}
// We are subscribing on TLF level anyway, so just use TLF path when
// notifying GUI.
k.subscribeCurrTlfPathFromGUI = tlfPathFromGUI
k.subscribeCurrFB = fb
k.subscribeToEmptyTlf = ""
return nil
}
func tlfNameFromPath(path keybase1.Path) (string, error) {
pType, err := path.PathType()
if err != nil {
return "", err
}
if pType != keybase1.PathType_KBFS {
return "", nil
}
tlfType, tlfNameFromGUI, _, _, err := remoteTlfAndPath(path)
if err != nil {
return "", err
}
return tlfhandle.BuildCanonicalPathForTlfType(
tlfType, tlfNameFromGUI), nil
}
func (k *SimpleFS) refreshSubscription(
ctx context.Context, path keybase1.Path) error {
tlfPathFromGUI, err := tlfNameFromPath(path)
if err != nil {
return err
}
if tlfPathFromGUI == "" {
k.log.CDebugf(ctx, "Ignoring subscription for path %s", path)
return nil
}
k.subscribeLock.Lock()
defer k.subscribeLock.Unlock()
return k.refreshSubscriptionLocked(ctx, path, tlfPathFromGUI)
}
func (k *SimpleFS) checkEmptySubscription(
ctx context.Context, path keybase1.Path) error {
k.subscribeLock.Lock()
defer k.subscribeLock.Unlock()
if k.subscribeToEmptyTlf == "" {
// Fast path.
return nil
}
tlfPathFromGUI, err := tlfNameFromPath(path)
if err != nil {
return err
}
if tlfPathFromGUI == "" {
return nil
}
if k.subscribeToEmptyTlf != tlfPathFromGUI {
return nil
}
k.log.CDebugf(
ctx, "Trying to subscribe to %s, which was previously empty",
tlfPathFromGUI)
return k.refreshSubscriptionLocked(ctx, path, tlfPathFromGUI)
}
// SimpleFSList - Begin list of items in directory at path
// Retrieve results with readList()
// Cannot be a single file to get flags/status,
// must be a directory.
func (k *SimpleFS) SimpleFSList(ctx context.Context, arg keybase1.SimpleFSListArg) (err error) {
return k.startAsync(ctx, arg.OpID, keybase1.AsyncOps_LIST,
keybase1.NewOpDescriptionWithList(
keybase1.ListArgs{
OpID: arg.OpID, Path: arg.Path, Filter: arg.Filter,
}),
&arg.Path, nil,
func(ctx context.Context) (err error) {
defer func() { err = translateErr(err) }()
var res []keybase1.Dirent
rawPath, err := rawPathFromKbfsPath(arg.Path)
if err != nil {
return err
}
switch {
case rawPath == "/":
res = []keybase1.Dirent{
{Name: "private", DirentType: deTy2Ty(data.Dir)},
{Name: "public", DirentType: deTy2Ty(data.Dir)},
{Name: "team", DirentType: deTy2Ty(data.Dir)},
}
case rawPath == `/public`:
res, err = k.favoriteList(ctx, arg.Path, tlf.Public)
case rawPath == `/private`:
res, err = k.favoriteList(ctx, arg.Path, tlf.Private)
case rawPath == `/team`:
res, err = k.favoriteList(ctx, arg.Path, tlf.SingleTeam)
default:
fs, finalElem, err := k.getFSIfExists(ctx, arg.Path)
switch errors.Cause(err).(type) {
case nil:
case libfs.TlfDoesNotExist:
// TLF doesn't exist yet; just return an empty result.
k.setResult(arg.OpID, keybase1.SimpleFSListResult{})
return nil
default:
return err
}
if arg.RefreshSubscription {
// TODO: move this higher when we handle
// subscribing to the favorites list.
err = k.refreshSubscription(ctx, arg.Path)
if err != nil {
return err
}
}
// With listing, we don't know the totals ahead of time,
// so just start with a 0 total.
k.setProgressTotals(arg.OpID, 0, 0)
finalElemFI, err := fs.Lstat(finalElem)
if err != nil {
return err
}
var fis []os.FileInfo
linkFS := fs
if finalElemFI.IsDir() {
fis, err = fs.ReadDir(finalElem)
if err != nil {
return err
}
linkFS, err = fs.Chroot(finalElem)
if err != nil {
return err