-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathowncloud.go
2294 lines (2056 loc) · 69.2 KB
/
owncloud.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 owncloud
import (
"context"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/internal/grpc/services/storageprovider"
"github.com/cs3org/reva/pkg/appctx"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/logger"
"github.com/cs3org/reva/pkg/mime"
"github.com/cs3org/reva/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/pkg/sharedconf"
"github.com/cs3org/reva/pkg/storage"
"github.com/cs3org/reva/pkg/storage/fs/registry"
"github.com/cs3org/reva/pkg/storage/utils/ace"
"github.com/cs3org/reva/pkg/storage/utils/chunking"
"github.com/cs3org/reva/pkg/storage/utils/templates"
"github.com/cs3org/reva/pkg/user"
"github.com/gomodule/redigo/redis"
"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/pkg/xattr"
)
const (
// Currently,extended file attributes have four separated
// namespaces (user, trusted, security and system) followed by a dot.
// A non root user can only manipulate the user. namespace, which is what
// we will use to store ownCloud specific metadata. To prevent name
// collisions with other apps We are going to introduce a sub namespace
// "user.oc."
ocPrefix string = "user.oc."
// idAttribute is the name of the filesystem extended attribute that is used to store the uuid in
idAttribute string = ocPrefix + "id"
// SharePrefix is the prefix for sharing related extended attributes
sharePrefix string = ocPrefix + "grant." // grants are similar to acls, but they are not propagated down the tree when being changed
trashOriginPrefix string = ocPrefix + "o"
mdPrefix string = ocPrefix + "md." // arbitrary metadata
favPrefix string = ocPrefix + "fav." // favorite flag, per user
etagPrefix string = ocPrefix + "etag." // allow overriding a calculated etag with one from the extended attributes
checksumPrefix string = ocPrefix + "cs."
checksumsKey string = "http://owncloud.org/ns/checksums"
favoriteKey string = "http://owncloud.org/ns/favorite"
)
var defaultPermissions *provider.ResourcePermissions = &provider.ResourcePermissions{
// no permissions
}
var ownerPermissions *provider.ResourcePermissions = &provider.ResourcePermissions{
// all permissions
AddGrant: true,
CreateContainer: true,
Delete: true,
GetPath: true,
GetQuota: true,
InitiateFileDownload: true,
InitiateFileUpload: true,
ListContainer: true,
ListFileVersions: true,
ListGrants: true,
ListRecycle: true,
Move: true,
PurgeRecycle: true,
RemoveGrant: true,
RestoreFileVersion: true,
RestoreRecycleItem: true,
Stat: true,
UpdateGrant: true,
}
func init() {
registry.Register("owncloud", New)
}
type config struct {
DataDirectory string `mapstructure:"datadirectory"`
UploadInfoDir string `mapstructure:"upload_info_dir"`
DeprecatedShareDirectory string `mapstructure:"sharedirectory"`
ShareFolder string `mapstructure:"share_folder"`
UserLayout string `mapstructure:"user_layout"`
Redis string `mapstructure:"redis"`
EnableHome bool `mapstructure:"enable_home"`
Scan bool `mapstructure:"scan"`
UserProviderEndpoint string `mapstructure:"userprovidersvc"`
}
func parseConfig(m map[string]interface{}) (*config, error) {
c := &config{}
if err := mapstructure.Decode(m, c); err != nil {
err = errors.Wrap(err, "error decoding conf")
return nil, err
}
return c, nil
}
func (c *config) init(m map[string]interface{}) {
if c.Redis == "" {
c.Redis = ":6379"
}
if c.UserLayout == "" {
c.UserLayout = "{{.Id.OpaqueId}}"
}
if c.UploadInfoDir == "" {
c.UploadInfoDir = "/var/tmp/reva/uploadinfo"
}
// fallback for old config
if c.DeprecatedShareDirectory != "" {
c.ShareFolder = c.DeprecatedShareDirectory
}
if c.ShareFolder == "" {
c.ShareFolder = "/Shares"
}
// ensure share folder always starts with slash
c.ShareFolder = filepath.Join("/", c.ShareFolder)
// default to scanning if not configured
if _, ok := m["scan"]; !ok {
c.Scan = true
}
c.UserProviderEndpoint = sharedconf.GetGatewaySVC(c.UserProviderEndpoint)
}
// New returns an implementation to of the storage.FS interface that talk to
// a local filesystem.
func New(m map[string]interface{}) (storage.FS, error) {
c, err := parseConfig(m)
if err != nil {
return nil, err
}
c.init(m)
// c.DataDirectory should never end in / unless it is the root?
c.DataDirectory = filepath.Clean(c.DataDirectory)
// create datadir if it does not exist
err = os.MkdirAll(c.DataDirectory, 0700)
if err != nil {
logger.New().Error().Err(err).
Str("path", c.DataDirectory).
Msg("could not create datadir")
}
err = os.MkdirAll(c.UploadInfoDir, 0700)
if err != nil {
logger.New().Error().Err(err).
Str("path", c.UploadInfoDir).
Msg("could not create uploadinfo dir")
}
pool := &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", c.Redis)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
return &ocfs{
c: c,
pool: pool,
chunkHandler: chunking.NewChunkHandler(c.UploadInfoDir),
}, nil
}
type ocfs struct {
c *config
pool *redis.Pool
chunkHandler *chunking.ChunkHandler
}
func (fs *ocfs) Shutdown(ctx context.Context) error {
return fs.pool.Close()
}
// scan files and add uuid to path mapping to kv store
func (fs *ocfs) scanFiles(ctx context.Context, conn redis.Conn) {
if fs.c.Scan {
fs.c.Scan = false // TODO ... in progress use mutex ?
log := appctx.GetLogger(ctx)
log.Debug().Str("path", fs.c.DataDirectory).Msg("scanning data directory")
err := filepath.Walk(fs.c.DataDirectory, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Error().Str("path", path).Err(err).Msg("error accessing path")
return filepath.SkipDir
}
// TODO(jfd) skip versions folder only if direct in users home dir
// we need to skip versions, otherwise a lookup by id might resolve to a version
if strings.Contains(path, "files_versions") {
log.Debug().Str("path", path).Err(err).Msg("skipping versions")
return filepath.SkipDir
}
// reuse connection to store file ids
id := readOrCreateID(context.Background(), path, nil)
_, err = conn.Do("SET", id, path)
if err != nil {
log.Error().Str("path", path).Err(err).Msg("error caching id")
// continue scanning
return nil
}
log.Debug().Str("path", path).Str("id", id).Msg("scanned path")
return nil
})
if err != nil {
log.Error().Err(err).Str("path", fs.c.DataDirectory).Msg("error scanning data directory")
}
}
}
// owncloud stores files in the files subfolder
// the incoming path starts with /<username>, so we need to insert the files subfolder into the path
// and prefix the data directory
// TODO the path handed to a storage provider should not contain the username
func (fs *ocfs) toInternalPath(ctx context.Context, sp string) (ip string) {
if fs.c.EnableHome {
u := user.ContextMustGetUser(ctx)
layout := templates.WithUser(u, fs.c.UserLayout)
ip = filepath.Join(fs.c.DataDirectory, layout, "files", sp)
} else {
// trim all /
sp = strings.Trim(sp, "/")
// p = "" or
// p = <username> or
// p = <username>/foo/bar.txt
segments := strings.SplitN(sp, "/", 2)
if len(segments) == 1 && segments[0] == "" {
ip = fs.c.DataDirectory
return
}
// parts[0] contains the username or userid.
u, err := fs.getUser(ctx, segments[0])
if err != nil {
// TODO return invalid internal path?
return
}
layout := templates.WithUser(u, fs.c.UserLayout)
if len(segments) == 1 {
// parts = "<username>"
ip = filepath.Join(fs.c.DataDirectory, layout, "files")
} else {
// parts = "<username>", "foo/bar.txt"
ip = filepath.Join(fs.c.DataDirectory, layout, "files", segments[1])
}
}
return
}
func (fs *ocfs) toInternalShadowPath(ctx context.Context, sp string) (internal string) {
if fs.c.EnableHome {
u := user.ContextMustGetUser(ctx)
layout := templates.WithUser(u, fs.c.UserLayout)
internal = filepath.Join(fs.c.DataDirectory, layout, "shadow_files", sp)
} else {
// trim all /
sp = strings.Trim(sp, "/")
// p = "" or
// p = <username> or
// p = <username>/foo/bar.txt
segments := strings.SplitN(sp, "/", 2)
if len(segments) == 1 && segments[0] == "" {
internal = fs.c.DataDirectory
return
}
// parts[0] contains the username or userid.
u, err := fs.getUser(ctx, segments[0])
if err != nil {
// TODO return invalid internal path?
return
}
layout := templates.WithUser(u, fs.c.UserLayout)
if len(segments) == 1 {
// parts = "<username>"
internal = filepath.Join(fs.c.DataDirectory, layout, "shadow_files")
} else {
// parts = "<username>", "foo/bar.txt"
internal = filepath.Join(fs.c.DataDirectory, layout, "shadow_files", segments[1])
}
}
return
}
// ownloud stores versions in the files_versions subfolder
// the incoming path starts with /<username>, so we need to insert the files subfolder into the path
// and prefix the data directory
// TODO the path handed to a storage provider should not contain the username
func (fs *ocfs) getVersionsPath(ctx context.Context, ip string) string {
// ip = /path/to/data/<username>/files/foo/bar.txt
// remove data dir
if fs.c.DataDirectory != "/" {
// fs.c.DataDirectory is a clean path, so it never ends in /
ip = strings.TrimPrefix(ip, fs.c.DataDirectory)
}
// ip = /<username>/files/foo/bar.txt
parts := strings.SplitN(ip, "/", 4)
// parts[1] contains the username or userid.
u, err := fs.getUser(ctx, parts[1])
if err != nil {
// TODO return invalid internal path?
return ""
}
layout := templates.WithUser(u, fs.c.UserLayout)
switch len(parts) {
case 3:
// parts = "", "<username>"
return filepath.Join(fs.c.DataDirectory, layout, "files_versions")
case 4:
// parts = "", "<username>", "foo/bar.txt"
return filepath.Join(fs.c.DataDirectory, layout, "files_versions", parts[3])
default:
return "" // TODO Must not happen?
}
}
// owncloud stores trashed items in the files_trashbin subfolder of a users home
func (fs *ocfs) getRecyclePath(ctx context.Context) (string, error) {
u, ok := user.ContextGetUser(ctx)
if !ok {
err := errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx")
return "", err
}
layout := templates.WithUser(u, fs.c.UserLayout)
return filepath.Join(fs.c.DataDirectory, layout, "files_trashbin/files"), nil
}
func (fs *ocfs) getVersionRecyclePath(ctx context.Context) (string, error) {
u, ok := user.ContextGetUser(ctx)
if !ok {
err := errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx")
return "", err
}
layout := templates.WithUser(u, fs.c.UserLayout)
return filepath.Join(fs.c.DataDirectory, layout, "files_trashbin/files_versions"), nil
}
func (fs *ocfs) toStoragePath(ctx context.Context, ip string) (sp string) {
if fs.c.EnableHome {
u := user.ContextMustGetUser(ctx)
layout := templates.WithUser(u, fs.c.UserLayout)
trim := filepath.Join(fs.c.DataDirectory, layout, "files")
sp = strings.TrimPrefix(ip, trim)
// root directory
if sp == "" {
sp = "/"
}
} else {
// ip = /data/<username>/files/foo/bar.txt
// remove data dir
if fs.c.DataDirectory != "/" {
// fs.c.DataDirectory is a clean path, so it never ends in /
ip = strings.TrimPrefix(ip, fs.c.DataDirectory)
// ip = /<username>/files/foo/bar.txt
}
segments := strings.SplitN(ip, "/", 4)
// parts = "", "<username>", "files", "foo/bar.txt"
switch len(segments) {
case 1:
sp = "/"
case 2:
sp = filepath.Join("/", segments[1])
case 3:
sp = filepath.Join("/", segments[1])
default:
sp = filepath.Join("/", segments[1], segments[3])
}
}
log := appctx.GetLogger(ctx)
log.Debug().Str("driver", "ocfs").Str("ipath", ip).Str("spath", sp).Msg("toStoragePath")
return
}
func (fs *ocfs) toStorageShadowPath(ctx context.Context, ip string) (sp string) {
if fs.c.EnableHome {
u := user.ContextMustGetUser(ctx)
layout := templates.WithUser(u, fs.c.UserLayout)
trim := filepath.Join(fs.c.DataDirectory, layout, "shadow_files")
sp = strings.TrimPrefix(ip, trim)
} else {
// ip = /data/<username>/shadow_files/foo/bar.txt
// remove data dir
if fs.c.DataDirectory != "/" {
// fs.c.DataDirectory is a clean path, so it never ends in /
ip = strings.TrimPrefix(ip, fs.c.DataDirectory)
// ip = /<username>/shadow_files/foo/bar.txt
}
segments := strings.SplitN(ip, "/", 4)
// parts = "", "<username>", "shadow_files", "foo/bar.txt"
switch len(segments) {
case 1:
sp = "/"
case 2:
sp = filepath.Join("/", segments[1])
case 3:
sp = filepath.Join("/", segments[1])
default:
sp = filepath.Join("/", segments[1], segments[3])
}
}
appctx.GetLogger(ctx).Debug().Str("driver", "ocfs").Str("ipath", ip).Str("spath", sp).Msg("toStorageShadowPath")
return
}
// TODO the owner needs to come from a different place
func (fs *ocfs) getOwner(ip string) string {
ip = strings.TrimPrefix(ip, fs.c.DataDirectory)
parts := strings.SplitN(ip, "/", 3)
if len(parts) > 1 {
return parts[1]
}
return ""
}
// TODO cache user lookup
func (fs *ocfs) getUser(ctx context.Context, usernameOrID string) (id *userpb.User, err error) {
u := user.ContextMustGetUser(ctx)
// check if username matches and id is set
if u.Username == usernameOrID && u.Id != nil && u.Id.OpaqueId != "" {
return u, nil
}
// check if userid matches and username is set
if u.Id != nil && u.Id.OpaqueId == usernameOrID && u.Username != "" {
return u, nil
}
// look up at the userprovider
// parts[0] contains the username or userid. use user service to look up id
c, err := pool.GetUserProviderServiceClient(fs.c.UserProviderEndpoint)
if err != nil {
appctx.GetLogger(ctx).
Error().Err(err).
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Msg("could not get user provider client")
return nil, err
}
res, err := c.GetUser(ctx, &userpb.GetUserRequest{
UserId: &userpb.UserId{OpaqueId: usernameOrID},
})
if err != nil {
appctx.GetLogger(ctx).
Error().Err(err).
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Msg("could not get user")
return nil, err
}
if res.Status.Code == rpc.Code_CODE_NOT_FOUND {
appctx.GetLogger(ctx).
Error().
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Interface("status", res.Status).
Msg("user not found")
return nil, fmt.Errorf("user not found")
}
if res.Status.Code != rpc.Code_CODE_OK {
appctx.GetLogger(ctx).
Error().
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Interface("status", res.Status).
Msg("user lookup failed")
return nil, fmt.Errorf("user lookup failed")
}
return res.User, nil
}
// permissionSet returns the permission set for the current user
func (fs *ocfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions {
if owner == nil {
return &provider.ResourcePermissions{
Stat: true,
}
}
u, ok := user.ContextGetUser(ctx)
if !ok {
return &provider.ResourcePermissions{
// no permissions
}
}
if u.Id == nil {
return &provider.ResourcePermissions{
// no permissions
}
}
if u.Id.OpaqueId == owner.OpaqueId && u.Id.Idp == owner.Idp {
return &provider.ResourcePermissions{
// owner has all permissions
AddGrant: true,
CreateContainer: true,
Delete: true,
GetPath: true,
GetQuota: true,
InitiateFileDownload: true,
InitiateFileUpload: true,
ListContainer: true,
ListFileVersions: true,
ListGrants: true,
ListRecycle: true,
Move: true,
PurgeRecycle: true,
RemoveGrant: true,
RestoreFileVersion: true,
RestoreRecycleItem: true,
Stat: true,
UpdateGrant: true,
}
}
// TODO fix permissions for share recipients by traversing reading acls up to the root? cache acls for the parent node and reuse it
return &provider.ResourcePermissions{
AddGrant: true,
CreateContainer: true,
Delete: true,
GetPath: true,
GetQuota: true,
InitiateFileDownload: true,
InitiateFileUpload: true,
ListContainer: true,
ListFileVersions: true,
ListGrants: true,
ListRecycle: true,
Move: true,
PurgeRecycle: true,
RemoveGrant: true,
RestoreFileVersion: true,
RestoreRecycleItem: true,
Stat: true,
UpdateGrant: true,
}
}
func (fs *ocfs) convertToResourceInfo(ctx context.Context, fi os.FileInfo, ip string, sp string, c redis.Conn, mdKeys []string) *provider.ResourceInfo {
id := readOrCreateID(ctx, ip, c)
etag := calcEtag(ctx, fi)
if val, err := xattr.Get(ip, etagPrefix+etag); err == nil {
appctx.GetLogger(ctx).Debug().
Str("ipath", ip).
Str("calcetag", etag).
Str("etag", string(val)).
Msg("overriding calculated etag")
etag = string(val)
}
mdKeysMap := make(map[string]struct{})
for _, k := range mdKeys {
mdKeysMap[k] = struct{}{}
}
var returnAllKeys bool
if _, ok := mdKeysMap["*"]; len(mdKeys) == 0 || ok {
returnAllKeys = true
}
metadata := map[string]string{}
if _, ok := mdKeysMap[favoriteKey]; returnAllKeys || ok {
favorite := ""
if u, ok := user.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", favPrefix, uid.GetOpaqueId(), uid.GetIdp())
if val, err := xattr.Get(ip, fa); err == nil {
appctx.GetLogger(ctx).Debug().
Str("ipath", ip).
Str("favorite", string(val)).
Str("username", u.GetUsername()).
Msg("found favorite flag")
favorite = string(val)
}
} else {
appctx.GetLogger(ctx).Error().Err(errtypes.UserRequired("userrequired")).Msg("user has no id")
}
} else {
appctx.GetLogger(ctx).Error().Err(errtypes.UserRequired("userrequired")).Msg("error getting user from ctx")
}
metadata[favoriteKey] = favorite
}
list, err := xattr.List(ip)
if err == nil {
for _, entry := range list {
// filter out non-custom properties
if !strings.HasPrefix(entry, mdPrefix) {
continue
}
if val, err := xattr.Get(ip, entry); err == nil {
k := entry[len(mdPrefix):]
if _, ok := mdKeysMap[k]; returnAllKeys || ok {
metadata[k] = string(val)
}
} else {
appctx.GetLogger(ctx).Error().Err(err).
Str("entry", entry).
Msg("error retrieving xattr metadata")
}
}
} else {
appctx.GetLogger(ctx).Error().Err(err).Msg("error getting list of extended attributes")
}
ri := &provider.ResourceInfo{
Id: &provider.ResourceId{OpaqueId: id},
Path: sp,
Type: getResourceType(fi.IsDir()),
Etag: etag,
MimeType: mime.Detect(fi.IsDir(), ip),
Size: uint64(fi.Size()),
Mtime: &types.Timestamp{
Seconds: uint64(fi.ModTime().Unix()),
// TODO read nanos from where? Nanos: fi.MTimeNanos,
},
ArbitraryMetadata: &provider.ArbitraryMetadata{
Metadata: metadata,
},
}
if owner, err := fs.getUser(ctx, fs.getOwner(ip)); err == nil {
ri.Owner = owner.Id
} else {
appctx.GetLogger(ctx).Error().Err(err).Msg("error getting owner")
}
ri.PermissionSet = fs.permissionSet(ctx, ri.Owner)
// checksums
if !fi.IsDir() {
if _, checksumRequested := mdKeysMap[checksumsKey]; returnAllKeys || checksumRequested {
// TODO which checksum was requested? sha1 adler32 or md5? for now hardcode sha1?
readChecksumIntoResourceChecksum(ctx, ip, storageprovider.XSSHA1, ri)
readChecksumIntoOpaque(ctx, ip, storageprovider.XSMD5, ri)
readChecksumIntoOpaque(ctx, ip, storageprovider.XSAdler32, ri)
}
}
return ri
}
func getResourceType(isDir bool) provider.ResourceType {
if isDir {
return provider.ResourceType_RESOURCE_TYPE_CONTAINER
}
return provider.ResourceType_RESOURCE_TYPE_FILE
}
func readOrCreateID(ctx context.Context, ip string, conn redis.Conn) string {
log := appctx.GetLogger(ctx)
// read extended file attribute for id
// generate if not present
var id []byte
var err error
if id, err = xattr.Get(ip, idAttribute); err != nil {
log.Warn().Err(err).Str("driver", "owncloud").Str("ipath", ip).Msg("error reading file id")
uuid := uuid.New()
// store uuid
id = uuid[:]
if err := xattr.Set(ip, idAttribute, id); err != nil {
log.Error().Err(err).Str("driver", "owncloud").Str("ipath", ip).Msg("error storing file id")
}
// TODO cache path for uuid in redis
// TODO reuse conn?
if conn != nil {
_, err := conn.Do("SET", uuid.String(), ip)
if err != nil {
log.Error().Err(err).Str("driver", "owncloud").Str("ipath", ip).Msg("error caching id")
// continue
}
}
}
// todo sign metadata
var uid uuid.UUID
if uid, err = uuid.FromBytes(id); err != nil {
log.Error().Err(err).Msg("error parsing uuid")
return ""
}
return uid.String()
}
func (fs *ocfs) getPath(ctx context.Context, id *provider.ResourceId) (string, error) {
log := appctx.GetLogger(ctx)
c := fs.pool.Get()
defer c.Close()
fs.scanFiles(ctx, c)
ip, err := redis.String(c.Do("GET", id.OpaqueId))
if err != nil {
return "", errtypes.NotFound(id.OpaqueId)
}
idFromXattr, err := xattr.Get(ip, idAttribute)
if err != nil {
return "", errtypes.NotFound(id.OpaqueId)
}
uid, err := uuid.FromBytes(idFromXattr)
if err != nil {
log.Error().Err(err).Msg("error parsing uuid")
}
if uid.String() != id.OpaqueId {
if _, err := c.Do("DEL", id.OpaqueId); err != nil {
return "", err
}
return "", errtypes.NotFound(id.OpaqueId)
}
return ip, nil
}
// GetPathByID returns the storage relative path for the file id, without the internal namespace
func (fs *ocfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) {
ip, err := fs.getPath(ctx, id)
if err != nil {
return "", err
}
// check permissions
if perm, err := fs.readPermissions(ctx, ip); err == nil {
if !perm.GetPath {
return "", errtypes.PermissionDenied("")
}
} else {
if isNotFound(err) {
return "", errtypes.NotFound(fs.toStoragePath(ctx, ip))
}
return "", errors.Wrap(err, "ocfs: error reading permissions")
}
return fs.toStoragePath(ctx, ip), nil
}
// resolve takes in a request path or request id and converts it to an internal path.
func (fs *ocfs) resolve(ctx context.Context, ref *provider.Reference) (string, error) {
if ref.GetPath() != "" {
return fs.toInternalPath(ctx, ref.GetPath()), nil
}
if ref.GetId() != nil {
ip, err := fs.getPath(ctx, ref.GetId())
if err != nil {
return "", err
}
return ip, nil
}
// reference is invalid
return "", fmt.Errorf("invalid reference %+v", ref)
}
func (fs *ocfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
ip, err := fs.resolve(ctx, ref)
if err != nil {
return errors.Wrap(err, "ocfs: error resolving reference")
}
// check permissions
if perm, err := fs.readPermissions(ctx, ip); err == nil {
if !perm.AddGrant {
return errtypes.PermissionDenied("")
}
} else {
if isNotFound(err) {
return errtypes.NotFound(fs.toStoragePath(ctx, ip))
}
return errors.Wrap(err, "ocfs: error reading permissions")
}
e := ace.FromGrant(g)
principal, value := e.Marshal()
if err := xattr.Set(ip, sharePrefix+principal, value); err != nil {
return err
}
return fs.propagate(ctx, ip)
}
// extractACEsFromAttrs reads ACEs in the list of attrs from the file
func extractACEsFromAttrs(ctx context.Context, ip string, attrs []string) (entries []*ace.ACE) {
log := appctx.GetLogger(ctx)
entries = []*ace.ACE{}
for i := range attrs {
if strings.HasPrefix(attrs[i], sharePrefix) {
var value []byte
var err error
if value, err = xattr.Get(ip, attrs[i]); err != nil {
log.Error().Err(err).Str("attr", attrs[i]).Msg("could not read attribute")
continue
}
var e *ace.ACE
principal := attrs[i][len(sharePrefix):]
if e, err = ace.Unmarshal(principal, value); err != nil {
log.Error().Err(err).Str("principal", principal).Str("attr", attrs[i]).Msg("could not unmarshal ace")
continue
}
entries = append(entries, e)
}
}
return
}
// TODO if user is owner but no acls found he can do everything?
// The owncloud driver does not integrate with the os so, for now, the owner can do everything, see ownerPermissions.
// Should this change we can store an acl for the owner in every node.
// We could also add default acls that can only the admin can set, eg for a read only storage?
// Someone needs to write to provide the content that should be read only, so this would likely be an acl for a group anyway.
// We need the storage relative path so we can calculate the permissions
// for the node based on all acls in the tree up to the root
func (fs *ocfs) readPermissions(ctx context.Context, ip string) (p *provider.ResourcePermissions, err error) {
u, ok := user.ContextGetUser(ctx)
if !ok {
appctx.GetLogger(ctx).Debug().Str("ipath", ip).Msg("no user in context, returning default permissions")
return defaultPermissions, nil
}
// check if the current user is the owner
if fs.getOwner(ip) == u.Id.OpaqueId {
appctx.GetLogger(ctx).Debug().Str("ipath", ip).Msg("user is owner, returning owner permissions")
return ownerPermissions, nil
}
// for non owners this is a little more complicated:
aggregatedPermissions := &provider.ResourcePermissions{}
// add default permissions
addPermissions(aggregatedPermissions, defaultPermissions)
// determine root
rp := fs.toInternalPath(ctx, "")
// TODO rp will be the datadir ... be we don't want to go up that high. The users home is far enough
np := ip
// for an efficient group lookup convert the list of groups to a map
// groups are just strings ... groupnames ... or group ids ??? AAARGH !!!
groupsMap := make(map[string]bool, len(u.Groups))
for i := range u.Groups {
groupsMap[u.Groups[i]] = true
}
var e *ace.ACE
// for all segments, starting at the leaf
for np != rp {
var attrs []string
if attrs, err = xattr.List(np); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("ipath", np).Msg("error listing attributes")
return nil, err
}
userace := sharePrefix + "u:" + u.Id.OpaqueId
userFound := false
for i := range attrs {
// we only need the find the user once per node
switch {
case !userFound && attrs[i] == userace:
e, err = fs.readACE(ctx, np, "u:"+u.Id.OpaqueId)
case strings.HasPrefix(attrs[i], sharePrefix+"g:"):
g := strings.TrimPrefix(attrs[i], sharePrefix+"g:")
if groupsMap[g] {
e, err = fs.readACE(ctx, np, "g:"+g)
} else {
// no need to check attribute
continue
}
default:
// no need to check attribute
continue
}
switch {
case err == nil:
addPermissions(aggregatedPermissions, e.Grant().GetPermissions())
appctx.GetLogger(ctx).Debug().Str("ipath", np).Str("principal", strings.TrimPrefix(attrs[i], sharePrefix)).Interface("permissions", aggregatedPermissions).Msg("adding permissions")
case isNoData(err):
err = nil
appctx.GetLogger(ctx).Error().Str("ipath", np).Str("principal", strings.TrimPrefix(attrs[i], sharePrefix)).Interface("attrs", attrs).Msg("no permissions found on node, but they were listed")
default:
appctx.GetLogger(ctx).Error().Err(err).Str("ipath", np).Str("principal", strings.TrimPrefix(attrs[i], sharePrefix)).Msg("error reading permissions")
return nil, err
}
}
np = filepath.Dir(np)
}
// 3. read user permissions until one is found?
// what if, when checking /a/b/c/d, /a/b has write permission, but /a/b/c has not?
// those are two shares one read only, and a higher one rw,
// should the higher one be used?
// or, since we did find a matching ace in a lower node use that because it matches the principal?
// this would allow ai user to share a folder rm but take away the write capability for eg a docs folder inside it.
// 4. read group permissions until all groups of the user are matched?
// same as for user permission, but we need to keep going further up the tree until all groups of the user were matched.
// what if a user has thousands of groups?
// we will always have to walk to the root.
// but the same problem occurs for a user with 2 groups but where only one group was used to share.
// in any case we need to iterate the aces, not the number of groups of the user.
// listing the aces can be used to match the principals, we do not need to fully real all aces
// what if, when checking /a/b/c/d, /a/b has write permission for group g, but /a/b/c has an ace for another group h the user is also a member of?
// it would allow restricting a users permissions by resharing something with him with lower permission?
// so if you have reshare permissions you could accidentially restrict users access to a subfolder of a rw share to ro by sharing it to another group as ro when they are part of both groups
// it makes more sense to have explicit negative permissions
// TODO we need to read all parents ... until we find a matching ace?
appctx.GetLogger(ctx).Debug().Interface("permissions", aggregatedPermissions).Str("ipath", ip).Msg("returning aggregated permissions")
return aggregatedPermissions, nil
}
func isNoData(err error) bool {
if xerr, ok := err.(*xattr.Error); ok {
if serr, ok2 := xerr.Err.(syscall.Errno); ok2 {
return serr == syscall.ENODATA
}
}
return false
}
// The os not exists error is buried inside the xattr error,
// so we cannot just use os.IsNotExists().
func isNotFound(err error) bool {
if xerr, ok := err.(*xattr.Error); ok {
if serr, ok2 := xerr.Err.(syscall.Errno); ok2 {
return serr == syscall.ENOENT
}
}
return false
}
func (fs *ocfs) readACE(ctx context.Context, ip string, principal string) (e *ace.ACE, err error) {
var b []byte
if b, err = xattr.Get(ip, sharePrefix+principal); err != nil {
return nil, err
}
if e, err = ace.Unmarshal(principal, b); err != nil {
return nil, err
}
return
}
// additive merging of permissions only
func addPermissions(p1 *provider.ResourcePermissions, p2 *provider.ResourcePermissions) {
p1.AddGrant = p1.AddGrant || p2.AddGrant