-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathowncloudsql.go
2100 lines (1892 loc) · 63.3 KB
/
owncloudsql.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 owncloudsql
import (
"context"
"crypto/md5"
"crypto/sha1"
"database/sql"
"fmt"
"hash/adler32"
"io"
"net/url"
"os"
"path/filepath"
"regexp"
"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/v2/internal/grpc/services/storageprovider"
"github.com/cs3org/reva/v2/pkg/appctx"
"github.com/cs3org/reva/v2/pkg/conversions"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/errtypes"
"github.com/cs3org/reva/v2/pkg/events"
"github.com/cs3org/reva/v2/pkg/logger"
"github.com/cs3org/reva/v2/pkg/mime"
"github.com/cs3org/reva/v2/pkg/rgrpc/todo/pool"
"github.com/cs3org/reva/v2/pkg/sharedconf"
"github.com/cs3org/reva/v2/pkg/storage"
"github.com/cs3org/reva/v2/pkg/storage/fs/owncloudsql/filecache"
"github.com/cs3org/reva/v2/pkg/storage/fs/registry"
"github.com/cs3org/reva/v2/pkg/storage/utils/chunking"
"github.com/cs3org/reva/v2/pkg/storage/utils/templates"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/pkg/xattr"
"github.com/rs/zerolog/log"
)
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."
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
checksumsKey string = "http://owncloud.org/ns/checksums"
)
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,
DenyGrant: true,
}
func init() {
registry.Register("owncloudsql", 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"`
EnableHome bool `mapstructure:"enable_home"`
UserProviderEndpoint string `mapstructure:"userprovidersvc"`
DbUsername string `mapstructure:"dbusername"`
DbPassword string `mapstructure:"dbpassword"`
DbHost string `mapstructure:"dbhost"`
DbPort int `mapstructure:"dbport"`
DbName string `mapstructure:"dbname"`
}
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.UserLayout == "" {
c.UserLayout = "{{.Username}}"
}
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)
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{}, _ events.Stream) (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")
}
// use MySQL
// driver := "mysql"
// dbSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)
// Use PSql
driver := "postgres"
dbSource := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
c.DbHost, c.DbPort, c.DbUsername, c.DbPassword, c.DbName)
filecache, err := filecache.NewSqlConnect(driver, dbSource)
if err != nil {
return nil, err
}
return &owncloudsqlfs{
c: c,
chunkHandler: chunking.NewChunkHandler(c.UploadInfoDir),
filecache: filecache,
}, nil
}
type owncloudsqlfs struct {
c *config
chunkHandler *chunking.ChunkHandler
filecache *filecache.Cache
}
func (fs *owncloudsqlfs) Shutdown(ctx context.Context) error {
return nil
}
// owncloudsql 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 *owncloudsqlfs) toInternalPath(ctx context.Context, sp string) (ip string) {
if fs.c.EnableHome {
u := ctxpkg.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
}
// owncloudsql 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 *owncloudsqlfs) 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?
}
}
// owncloudsql stores trashed items in the files_trashbin subfolder of a users home
func (fs *owncloudsqlfs) getRecyclePath(ctx context.Context) (string, error) {
u, ok := ctxpkg.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 fs.getRecyclePathForUser(layout)
}
func (fs *owncloudsqlfs) getRecyclePathForUser(user string) (string, error) {
return filepath.Join(fs.c.DataDirectory, user, "files_trashbin/files"), nil
}
func (fs *owncloudsqlfs) getVersionRecyclePath(ctx context.Context) (string, error) {
u, ok := ctxpkg.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/versions"), nil
}
func (fs *owncloudsqlfs) toDatabasePath(ip string) string {
owner := fs.getOwner(ip)
trim := filepath.Join(fs.c.DataDirectory, owner)
p := strings.TrimPrefix(ip, trim)
p = strings.TrimPrefix(p, "/")
return p
}
func (fs *owncloudsqlfs) toStoragePath(ctx context.Context, ip string) (sp string) {
if fs.c.EnableHome {
u := ctxpkg.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", "owncloudsql").Str("ipath", ip).Str("spath", sp).Msg("toStoragePath")
return
}
// TODO the owner needs to come from a different place
func (fs *owncloudsqlfs) 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 *owncloudsqlfs) getUser(ctx context.Context, usernameOrID string) (id *userpb.User, err error) {
u := ctxpkg.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 by id. Trying by name")
var cres *userpb.GetUserByClaimResponse
cres, err = c.GetUserByClaim(ctx, &userpb.GetUserByClaimRequest{
Claim: "username",
Value: usernameOrID,
})
if err != nil {
appctx.GetLogger(ctx).
Error().Err(err).
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Msg("could not get user by username")
return nil, err
}
if cres.Status.Code == rpc.Code_CODE_NOT_FOUND {
appctx.GetLogger(ctx).
Error().
Str("userprovidersvc", fs.c.UserProviderEndpoint).
Str("usernameOrID", usernameOrID).
Interface("status", cres.Status).
Msg("user not found by username")
return nil, fmt.Errorf("user not found")
}
res.User = cres.User
res.Status = cres.Status
}
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 *owncloudsqlfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions {
if owner == nil {
return &provider.ResourcePermissions{
Stat: true,
}
}
u, ok := ctxpkg.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 *owncloudsqlfs) getStorage(ctx context.Context, ip string) (int, error) {
return fs.filecache.GetNumericStorageID(ctx, "home::"+fs.getOwner(ip))
}
func (fs *owncloudsqlfs) getUserStorage(ctx context.Context, user string) (int, error) {
id, err := fs.filecache.GetNumericStorageID(ctx, "home::"+user)
if err != nil {
id, err = fs.filecache.CreateStorage(ctx, "home::"+user)
}
return id, err
}
func (fs *owncloudsqlfs) convertToResourceInfo(ctx context.Context, entry *filecache.File, ip string, mdKeys []string) (*provider.ResourceInfo, error) {
mdKeysMap := make(map[string]struct{})
for _, k := range mdKeys {
mdKeysMap[k] = struct{}{}
}
var returnAllKeys bool
if _, ok := mdKeysMap["*"]; len(mdKeys) == 0 || ok {
returnAllKeys = true
}
isDir := entry.MimeTypeString == "httpd/unix-directory"
ri := &provider.ResourceInfo{
Id: &provider.ResourceId{
// return ownclouds numeric storage id as the space id!
SpaceId: strconv.Itoa(entry.Storage), OpaqueId: strconv.Itoa(entry.ID),
},
Path: filepath.Base(ip),
Type: getResourceType(isDir),
Etag: entry.Etag,
MimeType: entry.MimeTypeString,
Size: uint64(entry.Size),
Mtime: &types.Timestamp{
Seconds: uint64(entry.MTime),
},
ArbitraryMetadata: &provider.ArbitraryMetadata{
Metadata: map[string]string{}, // TODO aduffeck: which metadata needs to go in here?
},
}
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 !isDir {
if _, checksumRequested := mdKeysMap[checksumsKey]; returnAllKeys || checksumRequested {
// TODO which checksum was requested? sha1 adler32 or md5? for now hardcode sha1?
readChecksumIntoResourceChecksum(ctx, entry.Checksum, storageprovider.XSSHA1, ri)
readChecksumIntoOpaque(ctx, entry.Checksum, storageprovider.XSMD5, ri)
readChecksumIntoOpaque(ctx, ip, storageprovider.XSAdler32, ri)
}
}
return ri, nil
}
// GetPathByID returns the storage relative path for the file id, without the internal namespace
func (fs *owncloudsqlfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) {
ip, err := fs.resolve(ctx, &provider.Reference{ResourceId: 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, "owncloudsql: 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 *owncloudsqlfs) resolve(ctx context.Context, ref *provider.Reference) (string, error) {
if ref.GetResourceId() != nil {
p, err := fs.filecache.Path(ctx, ref.GetResourceId().OpaqueId)
if err != nil {
return "", err
}
p = strings.TrimPrefix(p, "files/")
if !fs.c.EnableHome {
owner, err := fs.filecache.GetStorageOwnerByFileID(ctx, ref.GetResourceId().OpaqueId)
if err != nil {
return "", err
}
p = filepath.Join(owner, p)
}
if ref.GetPath() != "" {
p = filepath.Join(p, ref.GetPath())
}
return fs.toInternalPath(ctx, p), nil
}
if ref.GetPath() != "" {
return fs.toInternalPath(ctx, ref.GetPath()), nil
}
// reference is invalid
return "", fmt.Errorf("invalid reference %+v", ref)
}
func (fs *owncloudsqlfs) DenyGrant(ctx context.Context, ref *provider.Reference, g *provider.Grantee) error {
return errtypes.NotSupported("owncloudsqlfs: deny grant not supported")
}
func (fs *owncloudsqlfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
return errtypes.NotSupported("owncloudsqlfs: add grant not supported")
}
func (fs *owncloudsqlfs) readPermissions(ctx context.Context, ip string) (p *provider.ResourcePermissions, err error) {
u, ok := ctxpkg.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
owner := fs.getOwner(ip)
if owner == u.Username {
appctx.GetLogger(ctx).Debug().Str("ipath", ip).Msg("user is owner, returning owner permissions")
return ownerPermissions, nil
}
// otherwise this is a share
ownerStorageID, err := fs.filecache.GetNumericStorageID(ctx, "home::"+owner)
if err != nil {
return nil, err
}
entry, err := fs.filecache.Get(ctx, ownerStorageID, fs.toDatabasePath(ip))
if err != nil {
return nil, err
}
perms, err := conversions.NewPermissions(entry.Permissions)
if err != nil {
return nil, err
}
return conversions.RoleFromOCSPermissions(perms, nil).CS3ResourcePermissions(), nil
}
// 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 *owncloudsqlfs) ListGrants(ctx context.Context, ref *provider.Reference) (grants []*provider.Grant, err error) {
return []*provider.Grant{}, nil // nop
}
func (fs *owncloudsqlfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) {
return nil // nop
}
func (fs *owncloudsqlfs) UpdateGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
return nil // nop
}
func (fs *owncloudsqlfs) CreateHome(ctx context.Context) error {
u, ok := ctxpkg.ContextGetUser(ctx)
if !ok {
err := errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx")
return err
}
return fs.createHomeForUser(ctx, templates.WithUser(u, fs.c.UserLayout))
}
func (fs *owncloudsqlfs) createHomeForUser(ctx context.Context, user string) error {
homePaths := []string{
filepath.Join(fs.c.DataDirectory, user),
filepath.Join(fs.c.DataDirectory, user, "files"),
filepath.Join(fs.c.DataDirectory, user, "files_trashbin"),
filepath.Join(fs.c.DataDirectory, user, "files_trashbin/files"),
filepath.Join(fs.c.DataDirectory, user, "files_trashbin/versions"),
filepath.Join(fs.c.DataDirectory, user, "uploads"),
}
storageID, err := fs.getUserStorage(ctx, user)
if err != nil {
return err
}
for _, v := range homePaths {
if err := os.MkdirAll(v, 0755); err != nil {
return errors.Wrap(err, "owncloudsql: error creating home path: "+v)
}
fi, err := os.Stat(v)
if err != nil {
return err
}
data := map[string]interface{}{
"path": fs.toDatabasePath(v),
"etag": calcEtag(ctx, fi),
"mimetype": "httpd/unix-directory",
"permissions": 31, // 1: READ, 2: UPDATE, 4: CREATE, 8: DELETE, 16: SHARE
}
allowEmptyParent := v == filepath.Join(fs.c.DataDirectory, user) // the root doesn't have a parent
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, allowEmptyParent)
if err != nil {
return err
}
}
return nil
}
// If home is enabled, the relative home is always the empty string
func (fs *owncloudsqlfs) GetHome(ctx context.Context) (string, error) {
if !fs.c.EnableHome {
return "", errtypes.NotSupported("owncloudsql: get home not supported")
}
return "", nil
}
func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) {
ip, err := fs.resolve(ctx, ref)
if err != nil {
return err
}
// check permissions of parent dir
if perm, err := fs.readPermissions(ctx, filepath.Dir(ip)); err == nil {
if !perm.CreateContainer {
return errtypes.PermissionDenied("")
}
} else {
if isNotFound(err) {
return errtypes.PreconditionFailed(ref.Path)
}
return errors.Wrap(err, "owncloudsql: error reading permissions")
}
if err = os.Mkdir(ip, 0700); err != nil {
if os.IsNotExist(err) {
return errtypes.PreconditionFailed(ref.Path)
}
if os.IsExist(err) {
return errtypes.AlreadyExists(ref.Path)
}
return errors.Wrap(err, "owncloudsql: error creating dir "+fs.toStoragePath(ctx, filepath.Dir(ip)))
}
fi, err := os.Stat(ip)
if err != nil {
return err
}
mtime := time.Now().Unix()
permissions := 31 // 1: READ, 2: UPDATE, 4: CREATE, 8: DELETE, 16: SHARE
if perm, err := fs.readPermissions(ctx, filepath.Dir(ip)); err == nil {
permissions = int(conversions.RoleFromResourcePermissions(perm, false).OCSPermissions()) // inherit permissions of parent
}
data := map[string]interface{}{
"path": fs.toDatabasePath(ip),
"etag": calcEtag(ctx, fi),
"mimetype": "httpd/unix-directory",
"permissions": permissions,
"mtime": mtime,
"storage_mtime": mtime,
}
storageID, err := fs.getStorage(ctx, ip)
if err != nil {
return err
}
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false)
if err != nil {
if err != nil {
return err
}
}
return fs.propagate(ctx, filepath.Dir(ip))
}
// TouchFile as defined in the storage.FS interface
func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
ip, err := fs.resolve(ctx, ref)
if err != nil {
return err
}
// check permissions of parent dir
parentPerms, err := fs.readPermissions(ctx, filepath.Dir(ip))
if err == nil {
if !parentPerms.InitiateFileUpload {
return errtypes.PermissionDenied("")
}
} else {
if isNotFound(err) {
return errtypes.NotFound(ref.Path)
}
return errors.Wrap(err, "owncloudsql: error reading permissions")
}
_, err = os.Create(ip)
if err != nil {
if os.IsNotExist(err) {
return errtypes.NotFound(ref.Path)
}
// FIXME we also need already exists error, webdav expects 405 MethodNotAllowed
return errors.Wrap(err, "owncloudsql: error creating file "+fs.toStoragePath(ctx, filepath.Dir(ip)))
}
if err = os.Chmod(ip, 0700); err != nil {
return errors.Wrap(err, "owncloudsql: error setting file permissions on "+fs.toStoragePath(ctx, filepath.Dir(ip)))
}
fi, err := os.Stat(ip)
if err != nil {
return err
}
storageMtime := time.Now().Unix()
mt := storageMtime
if mtime != "" {
t, err := strconv.Atoi(mtime)
if err != nil {
log.Info().
Str("owncloudsql", ip).
Msg("error mtime conversion. mtine set to system time")
}
mt = time.Unix(int64(t), 0).Unix()
}
data := map[string]interface{}{
"path": fs.toDatabasePath(ip),
"etag": calcEtag(ctx, fi),
"mimetype": mime.Detect(false, ip),
"permissions": int(conversions.RoleFromResourcePermissions(parentPerms, false).OCSPermissions()), // inherit permissions of parent
"mtime": mt,
"storage_mtime": storageMtime,
}
storageID, err := fs.getStorage(ctx, ip)
if err != nil {
return err
}
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false)
if err != nil {
return err
}
return fs.propagate(ctx, filepath.Dir(ip))
}
func (fs *owncloudsqlfs) CreateReference(ctx context.Context, sp string, targetURI *url.URL) error {
return errtypes.NotSupported("owncloudsql: operation not supported")
}
func (fs *owncloudsqlfs) setMtime(ctx context.Context, ip string, mtime string) error {
log := appctx.GetLogger(ctx)
if mt, err := parseMTime(mtime); err == nil {
// updating mtime also updates atime
if err := os.Chtimes(ip, mt, mt); err != nil {
log.Error().Err(err).
Str("ipath", ip).
Time("mtime", mt).
Msg("could not set mtime")
return errors.Wrap(err, "could not set mtime")
}
} else {
log.Error().Err(err).
Str("ipath", ip).
Str("mtime", mtime).
Msg("could not parse mtime")
return errors.Wrap(err, "could not parse mtime")
}
return nil
}
func (fs *owncloudsqlfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) (err error) {
log := appctx.GetLogger(ctx)
var ip string
if ip, err = fs.resolve(ctx, ref); err != nil {
return errors.Wrap(err, "owncloudsql: error resolving reference")
}
// check permissions
if perm, err := fs.readPermissions(ctx, ip); err == nil {
if !perm.InitiateFileUpload { // TODO add dedicated permission?
return errtypes.PermissionDenied("")
}
} else {
if isNotFound(err) {
return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip)))
}
return errors.Wrap(err, "owncloudsql: error reading permissions")
}
var fi os.FileInfo
fi, err = os.Stat(ip)
if err != nil {
if os.IsNotExist(err) {
return errtypes.NotFound(fs.toStoragePath(ctx, ip))
}
return errors.Wrap(err, "owncloudsql: error stating "+ip)
}
errs := []error{}
if md.Metadata != nil {
if val, ok := md.Metadata["mtime"]; ok {
err := fs.setMtime(ctx, ip, val)
if err != nil {
errs = append(errs, errors.Wrap(err, "could not set mtime"))
}
// remove from metadata
delete(md.Metadata, "mtime")
}
// TODO(jfd) special handling for atime?
// TODO(jfd) allow setting birth time (btime)?
// TODO(jfd) any other metadata that is interesting? fileid?
if val, ok := md.Metadata["etag"]; ok {
etag := calcEtag(ctx, fi)
val = fmt.Sprintf("\"%s\"", strings.Trim(val, "\""))
if etag == val {
log.Debug().
Str("ipath", ip).
Str("etag", val).
Msg("ignoring request to update identical etag")
} else
// etag is only valid until the calculated etag changes
// TODO(jfd) cleanup in a batch job
if err := xattr.Set(ip, etagPrefix+etag, []byte(val)); err != nil {
log.Error().Err(err).
Str("ipath", ip).
Str("calcetag", etag).
Str("etag", val).
Msg("could not set etag")
errs = append(errs, errors.Wrap(err, "could not set etag"))
}
delete(md.Metadata, "etag")
}
if val, ok := md.Metadata["http://owncloud.org/ns/favorite"]; ok {
// 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
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", favPrefix, uid.GetOpaqueId(), uid.GetIdp())
if err := xattr.Set(ip, fa, []byte(val)); err != nil {
log.Error().Err(err).
Str("ipath", ip).
Interface("user", u).
Str("key", fa).
Msg("could not set favorite flag")
errs = append(errs, errors.Wrap(err, "could not set favorite flag"))
}
} else {
log.Error().
Str("ipath", ip).
Interface("user", u).
Msg("user has no id")
errs = append(errs, errors.Wrap(errtypes.UserRequired("userrequired"), "user has no id"))
}
} else {
log.Error().
Str("ipath", ip).
Interface("user", u).