-
Notifications
You must be signed in to change notification settings - Fork 112
/
node.go
1361 lines (1205 loc) · 41.4 KB
/
node.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 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
package node
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/v2/internal/grpc/services/storageprovider"
"github.com/cs3org/reva/v2/pkg/appctx"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/errtypes"
"github.com/cs3org/reva/v2/pkg/mime"
"github.com/cs3org/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/cs3org/reva/v2/pkg/storage/utils/ace"
"github.com/cs3org/reva/v2/pkg/storage/utils/decomposedfs/metadata"
"github.com/cs3org/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes"
"github.com/cs3org/reva/v2/pkg/storage/utils/grants"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rogpeppe/go-internal/lockedfile"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
var tracer trace.Tracer
func init() {
tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/node")
}
// Define keys and values used in the node metadata
const (
LockdiscoveryKey = "lockdiscovery"
FavoriteKey = "http://owncloud.org/ns/favorite"
ShareTypesKey = "http://owncloud.org/ns/share-types"
ChecksumsKey = "http://owncloud.org/ns/checksums"
UserShareType = "0"
QuotaKey = "quota"
QuotaUnlimited = "0"
QuotaUncalculated = "-1"
QuotaUnknown = "-2"
// TrashIDDelimiter represents the characters used to separate the nodeid and the deletion time.
TrashIDDelimiter = ".T."
RevisionIDDelimiter = ".REV."
// RootID defines the root node's ID
RootID = "root"
// ProcessingStatus is the name of the status when processing a file
ProcessingStatus = "processing:"
)
// Tree is used to manage a tree hierarchy
type Tree interface {
Setup() error
GetMD(ctx context.Context, node *Node) (os.FileInfo, error)
ListFolder(ctx context.Context, node *Node) ([]*Node, error)
// CreateHome(owner *userpb.UserId) (n *Node, err error)
CreateDir(ctx context.Context, node *Node) (err error)
TouchFile(ctx context.Context, node *Node, markprocessing bool, mtime string) error
// CreateReference(ctx context.Context, node *Node, targetURI *url.URL) error
Move(ctx context.Context, oldNode *Node, newNode *Node) (err error)
Delete(ctx context.Context, node *Node) (err error)
RestoreRecycleItemFunc(ctx context.Context, spaceid, key, trashPath string, target *Node) (*Node, *Node, func() error, error)
PurgeRecycleItemFunc(ctx context.Context, spaceid, key, purgePath string) (*Node, func() error, error)
WriteBlob(node *Node, source string) error
ReadBlob(node *Node) (io.ReadCloser, error)
DeleteBlob(node *Node) error
Propagate(ctx context.Context, node *Node, sizeDiff int64) (err error)
}
// PathLookup defines the interface for the lookup component
type PathLookup interface {
NodeFromSpaceID(ctx context.Context, spaceID string) (n *Node, err error)
NodeFromResource(ctx context.Context, ref *provider.Reference) (*Node, error)
NodeFromID(ctx context.Context, id *provider.ResourceId) (n *Node, err error)
GenerateSpaceID(spaceType string, owner *userpb.User) (string, error)
InternalRoot() string
InternalPath(spaceID, nodeID string) string
Path(ctx context.Context, n *Node, hasPermission PermissionFunc) (path string, err error)
MetadataBackend() metadata.Backend
ReadBlobSizeAttr(ctx context.Context, path string) (int64, error)
ReadBlobIDAttr(ctx context.Context, path string) (string, error)
TypeFromPath(ctx context.Context, path string) provider.ResourceType
CopyMetadataWithSourceLock(ctx context.Context, sourcePath, targetPath string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), lockedSource *lockedfile.File, acquireTargetLock bool) (err error)
CopyMetadata(ctx context.Context, src, target string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), acquireTargetLock bool) (err error)
}
// Node represents a node in the tree and provides methods to get a Parent or Child instance
type Node struct {
SpaceID string
ParentID string
ID string
Name string
Blobsize int64
BlobID string
owner *userpb.UserId
Exists bool
SpaceRoot *Node
lu PathLookup
xattrsCache map[string][]byte
nodeType *provider.ResourceType
}
// New returns a new instance of Node
func New(spaceID, id, parentID, name string, blobsize int64, blobID string, t provider.ResourceType, owner *userpb.UserId, lu PathLookup) *Node {
if blobID == "" {
blobID = uuid.New().String()
}
return &Node{
SpaceID: spaceID,
ID: id,
ParentID: parentID,
Name: name,
Blobsize: blobsize,
owner: owner,
lu: lu,
BlobID: blobID,
nodeType: &t,
}
}
// Type returns the node's resource type
func (n *Node) Type(ctx context.Context) provider.ResourceType {
if n.nodeType != nil {
return *n.nodeType
}
t := provider.ResourceType_RESOURCE_TYPE_INVALID
// Try to read from xattrs
typeAttr, err := n.XattrInt32(ctx, prefixes.TypeAttr)
if err == nil {
t = provider.ResourceType(typeAttr)
n.nodeType = &t
return t
}
// Fall back to checking on disk
fi, err := os.Lstat(n.InternalPath())
if err != nil {
return t
}
switch {
case fi.IsDir():
if _, err = n.Xattr(ctx, prefixes.ReferenceAttr); err == nil {
t = provider.ResourceType_RESOURCE_TYPE_REFERENCE
} else {
t = provider.ResourceType_RESOURCE_TYPE_CONTAINER
}
case fi.Mode().IsRegular():
t = provider.ResourceType_RESOURCE_TYPE_FILE
case fi.Mode()&os.ModeSymlink != 0:
t = provider.ResourceType_RESOURCE_TYPE_SYMLINK
// TODO reference using ext attr on a symlink
// nodeType = provider.ResourceType_RESOURCE_TYPE_REFERENCE
}
n.nodeType = &t
return t
}
// SetType sets the type of the node.
func (n *Node) SetType(t provider.ResourceType) {
n.nodeType = &t
}
// NodeMetadata writes the Node metadata to disk and allows passing additional attributes
func (n *Node) NodeMetadata(ctx context.Context) Attributes {
attribs := Attributes{}
attribs.SetInt64(prefixes.TypeAttr, int64(n.Type(ctx)))
attribs.SetString(prefixes.ParentidAttr, n.ParentID)
attribs.SetString(prefixes.NameAttr, n.Name)
if n.Type(ctx) == provider.ResourceType_RESOURCE_TYPE_FILE {
attribs.SetString(prefixes.BlobIDAttr, n.BlobID)
attribs.SetInt64(prefixes.BlobsizeAttr, n.Blobsize)
}
return attribs
}
// SetOwner sets the space owner on the node
func (n *Node) SetOwner(owner *userpb.UserId) {
n.SpaceRoot.owner = owner
}
// SpaceOwnerOrManager returns the space owner of the space. If no owner is set
// one of the space managers is returned instead.
func (n *Node) SpaceOwnerOrManager(ctx context.Context) *userpb.UserId {
owner := n.Owner()
if owner != nil && owner.Type != userpb.UserType_USER_TYPE_SPACE_OWNER {
return owner
}
// We don't have an owner set. Find a manager instead.
grants, err := n.SpaceRoot.ListGrants(ctx)
if err != nil {
return nil
}
for _, grant := range grants {
if grant.Permissions.Stat && grant.Permissions.ListContainer && grant.Permissions.InitiateFileDownload {
return grant.GetGrantee().GetUserId()
}
}
return nil
}
// ReadNode creates a new instance from an id and checks if it exists
func ReadNode(ctx context.Context, lu PathLookup, spaceID, nodeID string, canListDisabledSpace bool, spaceRoot *Node, skipParentCheck bool) (*Node, error) {
ctx, span := tracer.Start(ctx, "ReadNode")
defer span.End()
var err error
if spaceRoot == nil {
// read space root
spaceRoot = &Node{
SpaceID: spaceID,
lu: lu,
ID: spaceID,
}
spaceRoot.SpaceRoot = spaceRoot
spaceRoot.owner, err = spaceRoot.readOwner(ctx)
switch {
case metadata.IsNotExist(err):
return spaceRoot, nil // swallow not found, the node defaults to exists = false
case err != nil:
return nil, err
}
spaceRoot.Exists = true
// lookup name in extended attributes
spaceRoot.Name, err = spaceRoot.XattrString(ctx, prefixes.NameAttr)
if err != nil {
return nil, err
}
}
// TODO ReadNode should not check permissions
if !canListDisabledSpace && spaceRoot.IsDisabled(ctx) {
// no permission = not found
return nil, errtypes.NotFound(spaceID)
}
// if current user cannot stat the root return not found?
// no for shares the root might be a different resource
// check if this is a space root
if spaceID == nodeID {
return spaceRoot, nil
}
// are we reading a revision?
revisionSuffix := ""
if strings.Contains(nodeID, RevisionIDDelimiter) {
// verify revision key format
kp := strings.SplitN(nodeID, RevisionIDDelimiter, 2)
if len(kp) == 2 {
// use the actual node for the metadata lookup
nodeID = kp[0]
// remember revision for blob metadata
revisionSuffix = RevisionIDDelimiter + kp[1]
}
}
// read node
n := &Node{
SpaceID: spaceID,
lu: lu,
ID: nodeID,
SpaceRoot: spaceRoot,
}
nodePath := n.InternalPath()
// append back revision to nodeid, even when returning a not existing node
defer func() {
// when returning errors n is nil
if n != nil {
n.ID += revisionSuffix
}
}()
attrs, err := n.Xattrs(ctx)
switch {
case metadata.IsNotExist(err):
return n, nil // swallow not found, the node defaults to exists = false
case err != nil:
return nil, err
}
n.Exists = true
n.Name = attrs.String(prefixes.NameAttr)
n.ParentID = attrs.String(prefixes.ParentidAttr)
if n.ParentID == "" {
d, _ := os.ReadFile(lu.MetadataBackend().MetadataPath(n.InternalPath()))
if _, ok := lu.MetadataBackend().(metadata.MessagePackBackend); ok {
appctx.GetLogger(ctx).Error().Str("path", n.InternalPath()).Str("nodeid", n.ID).Interface("attrs", attrs).Bytes("messagepack", d).Msg("missing parent id")
}
return nil, errtypes.InternalError("Missing parent ID on node")
}
if revisionSuffix == "" {
n.BlobID = attrs.String(prefixes.BlobIDAttr)
if n.BlobID != "" {
blobSize, err := attrs.Int64(prefixes.BlobsizeAttr)
if err != nil {
return nil, err
}
n.Blobsize = blobSize
}
} else {
n.BlobID, err = lu.ReadBlobIDAttr(ctx, nodePath+revisionSuffix)
if err != nil {
return nil, err
}
// Lookup blobsize
n.Blobsize, err = lu.ReadBlobSizeAttr(ctx, nodePath+revisionSuffix)
if err != nil {
return nil, err
}
}
return n, nil
}
// The os error is buried inside the fs.PathError error
func isNotDir(err error) bool {
if perr, ok := err.(*fs.PathError); ok {
if serr, ok2 := perr.Err.(syscall.Errno); ok2 {
return serr == syscall.ENOTDIR
}
}
return false
}
func readChildNodeFromLink(path string) (string, error) {
link, err := os.Readlink(path)
if err != nil {
return "", err
}
nodeID := strings.TrimLeft(link, "/.")
nodeID = strings.ReplaceAll(nodeID, "/", "")
return nodeID, nil
}
// Child returns the child node with the given name
func (n *Node) Child(ctx context.Context, name string) (*Node, error) {
ctx, span := tracer.Start(ctx, "Child")
defer span.End()
spaceID := n.SpaceID
if spaceID == "" && n.ParentID == "root" {
spaceID = n.ID
} else if n.SpaceRoot != nil {
spaceID = n.SpaceRoot.ID
}
nodeID, err := readChildNodeFromLink(filepath.Join(n.InternalPath(), name))
if err != nil {
if errors.Is(err, fs.ErrNotExist) || isNotDir(err) {
c := &Node{
SpaceID: spaceID,
lu: n.lu,
ParentID: n.ID,
Name: name,
SpaceRoot: n.SpaceRoot,
}
return c, nil // if the file does not exist we return a node that has Exists = false
}
return nil, errors.Wrap(err, "decomposedfs: Wrap: readlink error")
}
var c *Node
c, err = ReadNode(ctx, n.lu, spaceID, nodeID, false, n.SpaceRoot, true)
if err != nil {
return nil, errors.Wrap(err, "could not read child node")
}
return c, nil
}
// ParentWithReader returns the parent node
func (n *Node) ParentWithReader(ctx context.Context, r io.Reader) (*Node, error) {
if n.ParentID == "" {
return nil, fmt.Errorf("decomposedfs: root has no parent")
}
p := &Node{
SpaceID: n.SpaceID,
lu: n.lu,
ID: n.ParentID,
SpaceRoot: n.SpaceRoot,
}
// fill metadata cache using the reader
attrs, err := p.XattrsWithReader(ctx, r)
switch {
case metadata.IsNotExist(err):
return p, nil // swallow not found, the node defaults to exists = false
case err != nil:
return nil, err
}
p.Exists = true
p.Name = attrs.String(prefixes.NameAttr)
p.ParentID = attrs.String(prefixes.ParentidAttr)
return p, err
}
// Parent returns the parent node
func (n *Node) Parent(ctx context.Context) (p *Node, err error) {
return n.ParentWithReader(ctx, nil)
}
// Owner returns the space owner
func (n *Node) Owner() *userpb.UserId {
return n.SpaceRoot.owner
}
// readOwner reads the owner from the extended attributes of the space root
// in case either owner id or owner idp are unset we return an error and an empty owner object
func (n *Node) readOwner(ctx context.Context) (*userpb.UserId, error) {
owner := &userpb.UserId{}
// lookup parent id in extended attributes
var attr string
var err error
// lookup ID in extended attributes
attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerIDAttr)
switch {
case err == nil:
owner.OpaqueId = attr
case metadata.IsAttrUnset(err):
// ignore
default:
return nil, err
}
// lookup IDP in extended attributes
attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerIDPAttr)
switch {
case err == nil:
owner.Idp = attr
case metadata.IsAttrUnset(err):
// ignore
default:
return nil, err
}
// lookup type in extended attributes
attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerTypeAttr)
switch {
case err == nil:
owner.Type = utils.UserTypeMap(attr)
case metadata.IsAttrUnset(err):
// ignore
default:
return nil, err
}
// owner is an optional property
if owner.Idp == "" && owner.OpaqueId == "" {
return nil, nil
}
return owner, nil
}
// PermissionSet returns the permission set and an accessDenied flag
// for the current user
// the parent nodes are not taken into account
// accessDenied is separate from the resource permissions
// because we only support full denials
func (n *Node) PermissionSet(ctx context.Context) (provider.ResourcePermissions, bool) {
u, ok := ctxpkg.ContextGetUser(ctx)
if !ok {
appctx.GetLogger(ctx).Debug().Interface("node", n).Msg("no user in context, returning default permissions")
return NoPermissions(), false
}
if utils.UserEqual(u.Id, n.SpaceRoot.Owner()) {
return OwnerPermissions(), false
}
// read the permissions for the current user from the acls of the current node
if np, accessDenied, err := n.ReadUserPermissions(ctx, u); err == nil {
return np, accessDenied
}
// be defensive, we could have access via another grant
return NoPermissions(), true
}
// InternalPath returns the internal path of the Node
func (n *Node) InternalPath() string {
return n.lu.InternalPath(n.SpaceID, n.ID)
}
// ParentPath returns the internal path of the parent of the current node
func (n *Node) ParentPath() string {
return n.lu.InternalPath(n.SpaceID, n.ParentID)
}
// LockFilePath returns the internal path of the lock file of the node
func (n *Node) LockFilePath() string {
return n.InternalPath() + ".lock"
}
// CalculateEtag returns a hash of fileid + tmtime (or mtime)
func CalculateEtag(id string, tmTime time.Time) (string, error) {
h := md5.New()
if _, err := io.WriteString(h, id); err != nil {
return "", err
}
/* TODO we could strengthen the etag by adding the blobid, but then all etags would change. we would need a legacy etag check as well
if _, err := io.WriteString(h, n.BlobID); err != nil {
return "", err
}
*/
if tb, err := tmTime.UTC().MarshalBinary(); err == nil {
if _, err := h.Write(tb); err != nil {
return "", err
}
} else {
return "", err
}
return fmt.Sprintf(`"%x"`, h.Sum(nil)), nil
}
// SetMtimeString sets the mtime and atime of a node to the unixtime parsed from the given string
func (n *Node) SetMtimeString(ctx context.Context, mtime string) error {
mt, err := utils.MTimeToTime(mtime)
if err != nil {
return err
}
return n.SetMtime(ctx, &mt)
}
// SetMTime writes the UTC mtime to the extended attributes or removes the attribute if nil is passed
func (n *Node) SetMtime(ctx context.Context, t *time.Time) (err error) {
if t == nil {
return n.RemoveXattr(ctx, prefixes.MTimeAttr, true)
}
return n.SetXattrString(ctx, prefixes.MTimeAttr, t.UTC().Format(time.RFC3339Nano))
}
// SetEtag sets the temporary etag of a node if it differs from the current etag
func (n *Node) SetEtag(ctx context.Context, val string) (err error) {
sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger()
var tmTime time.Time
if tmTime, err = n.GetTMTime(ctx); err != nil {
return
}
var etag string
if etag, err = CalculateEtag(n.ID, tmTime); err != nil {
return
}
// sanitize etag
val = fmt.Sprintf("\"%s\"", strings.Trim(val, "\""))
if etag == val {
sublog.Debug().
Str("etag", val).
Msg("ignoring request to update identical etag")
return nil
}
// etag is only valid until the calculated etag changes, is part of propagation
return n.SetXattrString(ctx, prefixes.TmpEtagAttr, val)
}
// SetFavorite sets the favorite for the current user
// TODO we should not mess with the user here ... the favorites is now a user specific property for a file
// that cannot be mapped to extended attributes without leaking who has marked a file as a favorite
// it is a specific case of a tag, which is user individual as well
// TODO there are different types of tags
// 1. public that are managed by everyone
// 2. private tags that are only visible to the user
// 3. system tags that are only visible to the system
// 4. group tags that are only visible to a group ...
// urgh ... well this can be solved using different namespaces
// 1. public = p:
// 2. private = u:<uid>: for user specific
// 3. system = s: for system
// 4. group = g:<gid>:
// 5. app? = a:<aid>: for apps?
// obviously this only is secure when the u/s/g/a namespaces are not accessible by users in the filesystem
// public tags can be mapped to extended attributes
func (n *Node) SetFavorite(ctx context.Context, uid *userpb.UserId, val string) error {
// the favorite flag is specific to the user, so we need to incorporate the userid
fa := fmt.Sprintf("%s:%s:%s@%s", prefixes.FavPrefix, utils.UserTypeToString(uid.GetType()), uid.GetOpaqueId(), uid.GetIdp())
return n.SetXattrString(ctx, fa, val)
}
// IsDir returns true if the node is a directory
func (n *Node) IsDir(ctx context.Context) bool {
attr, _ := n.XattrInt32(ctx, prefixes.TypeAttr)
return attr == int32(provider.ResourceType_RESOURCE_TYPE_CONTAINER)
}
// AsResourceInfo return the node as CS3 ResourceInfo
func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissions, mdKeys, fieldMask []string, returnBasename bool) (ri *provider.ResourceInfo, err error) {
sublog := appctx.GetLogger(ctx).With().Interface("node", n.ID).Logger()
var fn string
nodeType := n.Type(ctx)
var target string
if nodeType == provider.ResourceType_RESOURCE_TYPE_REFERENCE {
target, _ = n.XattrString(ctx, prefixes.ReferenceAttr)
}
id := &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}
switch {
case n.IsSpaceRoot(ctx):
fn = "." // space roots do not have a path as they are referencing themselves
case returnBasename:
fn = n.Name
default:
fn, err = n.lu.Path(ctx, n, NoCheck)
if err != nil {
return nil, err
}
}
ri = &provider.ResourceInfo{
Id: id,
Path: fn,
Type: nodeType,
MimeType: mime.Detect(nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER, fn),
Size: uint64(n.Blobsize),
Target: target,
PermissionSet: rp,
Owner: n.Owner(),
ParentId: &provider.ResourceId{
SpaceId: n.SpaceID,
OpaqueId: n.ParentID,
},
Name: n.Name,
}
if n.IsProcessing(ctx) {
ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "status", "processing")
}
if nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
ts, err := n.GetTreeSize(ctx)
if err == nil {
ri.Size = ts
} else {
ri.Size = 0 // make dirs always return 0 if it is unknown
sublog.Debug().Err(err).Msg("could not read treesize")
}
}
// TODO make etag of files use fileid and checksum
var tmTime time.Time
if tmTime, err = n.GetTMTime(ctx); err != nil {
sublog.Debug().Err(err).Msg("could not get tmtime")
}
// use temporary etag if it is set
if b, err := n.XattrString(ctx, prefixes.TmpEtagAttr); err == nil && b != "" {
ri.Etag = fmt.Sprintf(`"%x"`, b)
} else if ri.Etag, err = CalculateEtag(n.ID, tmTime); err != nil {
sublog.Debug().Err(err).Msg("could not calculate etag")
}
// mtime uses tmtime if present
// TODO expose mtime and tmtime separately?
un := tmTime.UnixNano()
ri.Mtime = &types.Timestamp{
Seconds: uint64(un / 1000000000),
Nanos: uint32(un % 1000000000),
}
mdKeysMap := make(map[string]struct{})
for _, k := range mdKeys {
mdKeysMap[k] = struct{}{}
}
var returnAllMetadata bool
if _, ok := mdKeysMap["*"]; len(mdKeys) == 0 || ok {
returnAllMetadata = true
}
metadata := map[string]string{}
fieldMaskKeysMap := make(map[string]struct{})
for _, k := range fieldMask {
fieldMaskKeysMap[k] = struct{}{}
}
var returnAllFields bool
if _, ok := fieldMaskKeysMap["*"]; len(fieldMask) == 0 || ok {
returnAllFields = true
}
// read favorite flag for the current user
if _, ok := mdKeysMap[FavoriteKey]; returnAllMetadata || ok {
favorite := ""
if u, ok := ctxpkg.ContextGetUser(ctx); ok {
// the favorite flag is specific to the user, so we need to incorporate the userid
if uid := u.GetId(); uid != nil {
fa := fmt.Sprintf("%s:%s:%s@%s", prefixes.FavPrefix, utils.UserTypeToString(uid.GetType()), uid.GetOpaqueId(), uid.GetIdp())
if val, err := n.XattrString(ctx, fa); err == nil {
sublog.Debug().
Str("favorite", fa).
Msg("found favorite flag")
favorite = val
}
} else {
sublog.Error().Err(errtypes.UserRequired("userrequired")).Msg("user has no id")
}
} else {
sublog.Error().Err(errtypes.UserRequired("userrequired")).Msg("error getting user from ctx")
}
metadata[FavoriteKey] = favorite
}
// read locks
// FIXME move to fieldmask
if _, ok := mdKeysMap[LockdiscoveryKey]; returnAllMetadata || ok {
if n.hasLocks(ctx) {
err = readLocksIntoOpaque(ctx, n, ri)
if err != nil {
sublog.Debug().Err(errtypes.InternalError("lockfail"))
}
}
}
// share indicator
if _, ok := fieldMaskKeysMap["share-types"]; returnAllFields || ok {
granteeTypes := n.getGranteeTypes(ctx)
if len(granteeTypes) > 0 {
// TODO add optional property to CS3 ResourceInfo to transport grants?
var s strings.Builder
first := true
for _, t := range granteeTypes {
if !first {
s.WriteString(",")
} else {
first = false
}
s.WriteString(strconv.Itoa(int(t)))
}
ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "share-types", s.String())
}
}
// checksums
// FIXME move to fieldmask
if _, ok := mdKeysMap[ChecksumsKey]; (nodeType == provider.ResourceType_RESOURCE_TYPE_FILE) && (returnAllMetadata || ok) {
// TODO which checksum was requested? sha1 adler32 or md5? for now hardcode sha1?
// TODO make ResourceInfo carry multiple checksums
n.readChecksumIntoResourceChecksum(ctx, storageprovider.XSSHA1, ri)
n.readChecksumIntoOpaque(ctx, storageprovider.XSMD5, ri)
n.readChecksumIntoOpaque(ctx, storageprovider.XSAdler32, ri)
}
// quota
// FIXME move to fieldmask
if _, ok := mdKeysMap[QuotaKey]; (nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER) && returnAllMetadata || ok {
if n.SpaceRoot != nil && n.SpaceRoot.InternalPath() != "" {
n.SpaceRoot.readQuotaIntoOpaque(ctx, ri)
}
}
// only read the requested metadata attributes
attrs, err := n.Xattrs(ctx)
if err != nil {
sublog.Error().Err(err).Msg("error getting list of extended attributes")
} else {
for key, value := range attrs {
// filter out non-custom properties
if !strings.HasPrefix(key, prefixes.MetadataPrefix) {
continue
}
// only read when key was requested
k := key[len(prefixes.MetadataPrefix):]
if _, ok := mdKeysMap[k]; returnAllMetadata || ok {
metadata[k] = string(value)
}
}
}
ri.ArbitraryMetadata = &provider.ArbitraryMetadata{
Metadata: metadata,
}
// add virusscan information
if scanned, _, date := n.ScanData(ctx); scanned {
ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "scantime", date.Format(time.RFC3339Nano))
}
sublog.Debug().
Interface("ri", ri).
Msg("AsResourceInfo")
return ri, nil
}
func (n *Node) readChecksumIntoResourceChecksum(ctx context.Context, algo string, ri *provider.ResourceInfo) {
v, err := n.Xattr(ctx, prefixes.ChecksumPrefix+algo)
switch {
case err == nil:
ri.Checksum = &provider.ResourceChecksum{
Type: storageprovider.PKG2GRPCXS(algo),
Sum: hex.EncodeToString(v),
}
case metadata.IsAttrUnset(err):
appctx.GetLogger(ctx).Debug().Err(err).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("checksum not set")
default:
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("could not read checksum")
}
}
func (n *Node) readChecksumIntoOpaque(ctx context.Context, algo string, ri *provider.ResourceInfo) {
v, err := n.Xattr(ctx, prefixes.ChecksumPrefix+algo)
switch {
case err == nil:
if ri.Opaque == nil {
ri.Opaque = &types.Opaque{
Map: map[string]*types.OpaqueEntry{},
}
}
ri.Opaque.Map[algo] = &types.OpaqueEntry{
Decoder: "plain",
Value: []byte(hex.EncodeToString(v)),
}
case metadata.IsAttrUnset(err):
appctx.GetLogger(ctx).Debug().Err(err).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("checksum not set")
default:
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("could not read checksum")
}
}
// quota is always stored on the root node
func (n *Node) readQuotaIntoOpaque(ctx context.Context, ri *provider.ResourceInfo) {
v, err := n.XattrString(ctx, prefixes.QuotaAttr)
switch {
case err == nil:
// make sure we have a proper signed int
// we use the same magic numbers to indicate:
// -1 = uncalculated
// -2 = unknown
// -3 = unlimited
if _, err := strconv.ParseInt(v, 10, 64); err == nil {
if ri.Opaque == nil {
ri.Opaque = &types.Opaque{
Map: map[string]*types.OpaqueEntry{},
}
}
ri.Opaque.Map[QuotaKey] = &types.OpaqueEntry{
Decoder: "plain",
Value: []byte(v),
}
} else {
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Str("quota", v).Msg("malformed quota")
}
case metadata.IsAttrUnset(err):
appctx.GetLogger(ctx).Debug().Err(err).Str("nodepath", n.InternalPath()).Msg("quota not set")
default:
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Msg("could not read quota")
}
}
// HasPropagation checks if the propagation attribute exists and is set to "1"
func (n *Node) HasPropagation(ctx context.Context) (propagation bool) {
if b, err := n.XattrString(ctx, prefixes.PropagationAttr); err == nil {
return b == "1"
}
return false
}
// GetTMTime reads the tmtime from the extended attributes, falling back to GetMTime()
func (n *Node) GetTMTime(ctx context.Context) (time.Time, error) {
b, err := n.XattrString(ctx, prefixes.TreeMTimeAttr)
if err == nil {
return time.Parse(time.RFC3339Nano, b)
}
// no tmtime, use mtime
return n.GetMTime(ctx)
}
// GetMTime reads the mtime from the extended attributes, falling back to disk
func (n *Node) GetMTime(ctx context.Context) (time.Time, error) {
b, err := n.XattrString(ctx, prefixes.MTimeAttr)
if err != nil {
fi, err := os.Lstat(n.InternalPath())
if err != nil {
return time.Time{}, err
}
return fi.ModTime(), nil
}
return time.Parse(time.RFC3339Nano, b)
}
// SetTMTime writes the UTC tmtime to the extended attributes or removes the attribute if nil is passed
func (n *Node) SetTMTime(ctx context.Context, t *time.Time) (err error) {
if t == nil {
return n.RemoveXattr(ctx, prefixes.TreeMTimeAttr, true)
}
return n.SetXattrString(ctx, prefixes.TreeMTimeAttr, t.UTC().Format(time.RFC3339Nano))
}
// GetDTime reads the dtime from the extended attributes
func (n *Node) GetDTime(ctx context.Context) (tmTime time.Time, err error) {
b, err := n.XattrString(ctx, prefixes.DTimeAttr)
if err != nil {
return time.Time{}, err
}
return time.Parse(time.RFC3339Nano, b)
}
// SetDTime writes the UTC dtime to the extended attributes or removes the attribute if nil is passed
func (n *Node) SetDTime(ctx context.Context, t *time.Time) (err error) {
if t == nil {
return n.RemoveXattr(ctx, prefixes.DTimeAttr, true)
}
return n.SetXattrString(ctx, prefixes.DTimeAttr, t.UTC().Format(time.RFC3339Nano))
}
// IsDisabled returns true when the node has a dmtime attribute set
// only used to check if a space is disabled
// FIXME confusing with the trash logic
func (n *Node) IsDisabled(ctx context.Context) bool {
if _, err := n.GetDTime(ctx); err == nil {
return true
}
return false
}
// GetTreeSize reads the treesize from the extended attributes
func (n *Node) GetTreeSize(ctx context.Context) (treesize uint64, err error) {
ctx, span := tracer.Start(ctx, "GetTreeSize")
defer span.End()
s, err := n.XattrUint64(ctx, prefixes.TreesizeAttr)
if err != nil {
return 0, err
}
return s, nil
}
// SetTreeSize writes the treesize to the extended attributes
func (n *Node) SetTreeSize(ctx context.Context, ts uint64) (err error) {
return n.SetXattrString(ctx, prefixes.TreesizeAttr, strconv.FormatUint(ts, 10))
}
// GetBlobSize reads the blobsize from the extended attributes
func (n *Node) GetBlobSize(ctx context.Context) (treesize uint64, err error) {
s, err := n.XattrInt64(ctx, prefixes.BlobsizeAttr)
if err != nil {
return 0, err
}
return uint64(s), nil
}
// SetChecksum writes the checksum with the given checksum type to the extended attributes
func (n *Node) SetChecksum(ctx context.Context, csType string, h hash.Hash) (err error) {
return n.SetXattr(ctx, prefixes.ChecksumPrefix+csType, h.Sum(nil))
}
// UnsetTempEtag removes the temporary etag attribute