-
Notifications
You must be signed in to change notification settings - Fork 112
/
propfind.go
1700 lines (1560 loc) · 60.8 KB
/
propfind.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 propfind
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/cs3org/reva/v2/internal/grpc/services/storageprovider"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocdav/errors"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocdav/prop"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocdav/spacelookup"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocs/conversions"
"github.com/cs3org/reva/v2/pkg/appctx"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/publicshare"
rstatus "github.com/cs3org/reva/v2/pkg/rgrpc/status"
"github.com/cs3org/reva/v2/pkg/rhttp/router"
"github.com/cs3org/reva/v2/pkg/storagespace"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/fieldmaskpb"
)
const (
tracerName = "ocdav"
)
type countingReader struct {
n int
r io.Reader
}
// Props represents properties related to a resource
// http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for propfind)
type Props []xml.Name
// XML holds the xml representation of a propfind
// http://www.webdav.org/specs/rfc4918.html#ELEMENT_propfind
type XML struct {
XMLName xml.Name `xml:"DAV: propfind"`
Allprop *struct{} `xml:"DAV: allprop"`
Propname *struct{} `xml:"DAV: propname"`
Prop Props `xml:"DAV: prop"`
Include Props `xml:"DAV: include"`
}
// PropstatXML holds the xml representation of a propfind response
// http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat
type PropstatXML struct {
// Prop requires DAV: to be the default namespace in the enclosing
// XML. This is due to the standard encoding/xml package currently
// not honoring namespace declarations inside a xmltag with a
// parent element for anonymous slice elements.
// Use of multistatusWriter takes care of this.
Prop []prop.PropertyXML `xml:"d:prop>_ignored_"`
Status string `xml:"d:status"`
Error *errors.ErrorXML `xml:"d:error"`
ResponseDescription string `xml:"d:responsedescription,omitempty"`
}
// ResponseXML holds the xml representation of a propfind response
type ResponseXML struct {
XMLName xml.Name `xml:"d:response"`
Href string `xml:"d:href"`
Propstat []PropstatXML `xml:"d:propstat"`
Status string `xml:"d:status,omitempty"`
Error *errors.ErrorXML `xml:"d:error"`
ResponseDescription string `xml:"d:responsedescription,omitempty"`
}
// MultiStatusResponseXML holds the xml representation of a multistatus propfind response
type MultiStatusResponseXML struct {
XMLName xml.Name `xml:"d:multistatus"`
XmlnsS string `xml:"xmlns:s,attr,omitempty"`
XmlnsD string `xml:"xmlns:d,attr,omitempty"`
XmlnsOC string `xml:"xmlns:oc,attr,omitempty"`
Responses []*ResponseXML `xml:"d:response"`
}
// ResponseUnmarshalXML is a workaround for https://github.com/golang/go/issues/13400
type ResponseUnmarshalXML struct {
XMLName xml.Name `xml:"response"`
Href string `xml:"href"`
Propstat []PropstatUnmarshalXML `xml:"propstat"`
Status string `xml:"status,omitempty"`
Error *errors.ErrorXML `xml:"d:error"`
ResponseDescription string `xml:"responsedescription,omitempty"`
}
// MultiStatusResponseUnmarshalXML is a workaround for https://github.com/golang/go/issues/13400
type MultiStatusResponseUnmarshalXML struct {
XMLName xml.Name `xml:"multistatus"`
XmlnsS string `xml:"xmlns:s,attr,omitempty"`
XmlnsD string `xml:"xmlns:d,attr,omitempty"`
XmlnsOC string `xml:"xmlns:oc,attr,omitempty"`
Responses []*ResponseUnmarshalXML `xml:"response"`
}
// PropstatUnmarshalXML is a workaround for https://github.com/golang/go/issues/13400
type PropstatUnmarshalXML struct {
// Prop requires DAV: to be the default namespace in the enclosing
// XML. This is due to the standard encoding/xml package currently
// not honoring namespace declarations inside a xmltag with a
// parent element for anonymous slice elements.
// Use of multistatusWriter takes care of this.
Prop []*prop.PropertyXML `xml:"prop"`
Status string `xml:"status"`
Error *errors.ErrorXML `xml:"d:error"`
ResponseDescription string `xml:"responsedescription,omitempty"`
}
// spaceData is used to remember the space for a resource info
type spaceData struct {
Ref *provider.Reference
SpaceType string
}
// NewMultiStatusResponseXML returns a preconfigured instance of MultiStatusResponseXML
func NewMultiStatusResponseXML() *MultiStatusResponseXML {
return &MultiStatusResponseXML{
XmlnsD: "DAV:",
XmlnsS: "http://sabredav.org/ns",
XmlnsOC: "http://owncloud.org/ns",
}
}
// GetGatewayServiceClientFunc is a callback used to pass in a StorageProviderClient during testing
type GetGatewayServiceClientFunc func() (gateway.GatewayAPIClient, error)
// Handler handles propfind requests
type Handler struct {
PublicURL string
getClient GetGatewayServiceClientFunc
}
// NewHandler returns a new PropfindHandler instance
func NewHandler(publicURL string, getClientFunc GetGatewayServiceClientFunc) *Handler {
return &Handler{
PublicURL: publicURL,
getClient: getClientFunc,
}
}
// HandlePathPropfind handles a path based propfind request
// ns is the namespace that is prefixed to the path in the cs3 namespace
func (p *Handler) HandlePathPropfind(w http.ResponseWriter, r *http.Request, ns string) {
ctx, span := appctx.GetTracerProvider(r.Context()).Tracer(tracerName).Start(r.Context(), fmt.Sprintf("%s %v", r.Method, r.URL.Path))
defer span.End()
fn := path.Join(ns, r.URL.Path) // TODO do we still need to jail if we query the registry about the spaces?
sublog := appctx.GetLogger(ctx).With().Str("path", fn).Logger()
pf, status, err := ReadPropfind(r.Body)
if err != nil {
sublog.Debug().Err(err).Msg("error reading propfind request")
w.WriteHeader(status)
return
}
// retrieve a specific storage space
client, err := p.getClient()
if err != nil {
sublog.Error().Err(err).Msg("error retrieving a gateway service client")
w.WriteHeader(http.StatusInternalServerError)
return
}
// TODO look up all spaces and request the root_info in the field mask
spaces, rpcStatus, err := spacelookup.LookUpStorageSpacesForPathWithChildren(ctx, client, fn)
if err != nil {
sublog.Error().Err(err).Msg("error sending a grpc request")
w.WriteHeader(http.StatusInternalServerError)
return
}
if rpcStatus.Code != rpc.Code_CODE_OK {
errors.HandleErrorStatus(&sublog, w, rpcStatus)
return
}
resourceInfos, sendTusHeaders, ok := p.getResourceInfos(ctx, w, r, pf, spaces, fn, sublog)
if !ok {
// getResourceInfos handles responses in case of an error so we can just return here.
return
}
p.propfindResponse(ctx, w, r, ns, pf, sendTusHeaders, resourceInfos, sublog)
}
// HandleSpacesPropfind handles a spaces based propfind request
func (p *Handler) HandleSpacesPropfind(w http.ResponseWriter, r *http.Request, spaceID string) {
ctx, span := appctx.GetTracerProvider(r.Context()).Tracer(tracerName).Start(r.Context(), "spaces_propfind")
defer span.End()
sublog := appctx.GetLogger(ctx).With().Str("path", r.URL.Path).Str("spaceid", spaceID).Logger()
dh := r.Header.Get(net.HeaderDepth)
depth, err := net.ParseDepth(dh)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "Invalid Depth header value")
span.SetAttributes(semconv.HTTPStatusCodeKey.Int(http.StatusBadRequest))
sublog.Debug().Str("depth", dh).Msg(err.Error())
w.WriteHeader(http.StatusBadRequest)
m := fmt.Sprintf("Invalid Depth header value: %v", dh)
b, err := errors.Marshal(http.StatusBadRequest, m, "")
errors.HandleWebdavError(&sublog, w, b, err)
return
}
pf, status, err := ReadPropfind(r.Body)
if err != nil {
sublog.Debug().Err(err).Msg("error reading propfind request")
w.WriteHeader(status)
return
}
ref, err := spacelookup.MakeStorageSpaceReference(spaceID, r.URL.Path)
if err != nil {
sublog.Debug().Msg("invalid space id")
w.WriteHeader(http.StatusBadRequest)
m := fmt.Sprintf("Invalid space id: %v", spaceID)
b, err := errors.Marshal(http.StatusBadRequest, m, "")
errors.HandleWebdavError(&sublog, w, b, err)
return
}
client, err := p.getClient()
if err != nil {
sublog.Error().Err(err).Msg("error getting grpc client")
w.WriteHeader(http.StatusInternalServerError)
return
}
metadataKeys, _ := metadataKeys(pf)
// stat the reference and request the space in the field mask
res, err := client.Stat(ctx, &provider.StatRequest{
Ref: &ref,
ArbitraryMetadataKeys: metadataKeys,
FieldMask: &fieldmaskpb.FieldMask{Paths: []string{"*"}}, // TODO use more sophisticated filter? we don't need all space properties, afaict only the spacetype
})
if err != nil {
sublog.Error().Err(err).Msg("error getting grpc client")
w.WriteHeader(http.StatusInternalServerError)
return
}
if res.Status.Code != rpc.Code_CODE_OK {
status := rstatus.HTTPStatusFromCode(res.Status.Code)
if res.Status.Code == rpc.Code_CODE_ABORTED {
// aborted is used for etag an lock mismatches, which translates to 412
// in case a real Conflict response is needed, the calling code needs to send the header
status = http.StatusPreconditionFailed
}
m := res.Status.Message
if res.Status.Code == rpc.Code_CODE_PERMISSION_DENIED {
// check if user has access to resource
sRes, err := client.Stat(ctx, &provider.StatRequest{Ref: &provider.Reference{ResourceId: ref.GetResourceId()}})
if err != nil {
sublog.Error().Err(err).Msg("error performing stat grpc request")
w.WriteHeader(http.StatusInternalServerError)
return
}
if sRes.Status.Code != rpc.Code_CODE_OK {
// return not found error so we do not leak existence of a space
status = http.StatusNotFound
}
}
if status == http.StatusNotFound {
m = "Resource not found" // mimic the oc10 error message
}
w.WriteHeader(status)
b, err := errors.Marshal(status, m, "")
errors.HandleWebdavError(&sublog, w, b, err)
return
}
var space *provider.StorageSpace
if res.Info.Space == nil {
sublog.Debug().Msg("stat did not include a space, executing an additional lookup request")
// fake a space root
space = &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: spaceID},
Opaque: &typesv1beta1.Opaque{
Map: map[string]*typesv1beta1.OpaqueEntry{
"path": {
Decoder: "plain",
Value: []byte("/"),
},
},
},
Root: ref.ResourceId,
RootInfo: res.Info,
}
}
res.Info.Path = r.URL.Path
resourceInfos := []*provider.ResourceInfo{
res.Info,
}
if res.Info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER && depth != net.DepthZero {
childInfos, ok := p.getSpaceResourceInfos(ctx, w, r, pf, &ref, r.URL.Path, depth, sublog)
if !ok {
// getResourceInfos handles responses in case of an error so we can just return here.
return
}
resourceInfos = append(resourceInfos, childInfos...)
}
// prefix space id to paths
for i := range resourceInfos {
resourceInfos[i].Path = path.Join("/", spaceID, resourceInfos[i].Path)
// add space to info so propfindResponse can access space type
if resourceInfos[i].Space == nil {
resourceInfos[i].Space = space
}
}
sendTusHeaders := true
// let clients know this collection supports tus.io POST requests to start uploads
if res.Info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
if res.Info.Opaque != nil {
_, ok := res.Info.Opaque.Map["disable_tus"]
sendTusHeaders = !ok
}
}
p.propfindResponse(ctx, w, r, "", pf, sendTusHeaders, resourceInfos, sublog)
}
func (p *Handler) propfindResponse(ctx context.Context, w http.ResponseWriter, r *http.Request, namespace string, pf XML, sendTusHeaders bool, resourceInfos []*provider.ResourceInfo, log zerolog.Logger) {
ctx, span := appctx.GetTracerProvider(r.Context()).Tracer(tracerName).Start(ctx, "propfind_response")
defer span.End()
var linkshares map[string]struct{}
// public link access does not show share-types
// oc:share-type is not part of an allprops response
if namespace != "/public" {
// only fetch this if property was queried
for _, prop := range pf.Prop {
if prop.Space == net.NsOwncloud && (prop.Local == "share-types" || prop.Local == "permissions") {
filters := make([]*link.ListPublicSharesRequest_Filter, 0, len(resourceInfos))
for i := range resourceInfos {
// FIXME this is expensive
// the filters array grow by one for every file in a folder
// TODO store public links as grants on the storage, reassembling them here is too costly
// we can then add the filter if the file has share-types=3 in the opaque,
// same as user / group shares for share indicators
filters = append(filters, publicshare.ResourceIDFilter(resourceInfos[i].Id))
}
client, err := p.getClient()
if err != nil {
log.Error().Err(err).Msg("error getting grpc client")
w.WriteHeader(http.StatusInternalServerError)
return
}
listResp, err := client.ListPublicShares(ctx, &link.ListPublicSharesRequest{Filters: filters})
if err == nil {
linkshares = make(map[string]struct{}, len(listResp.Share))
for i := range listResp.Share {
linkshares[listResp.Share[i].ResourceId.OpaqueId] = struct{}{}
}
} else {
log.Error().Err(err).Msg("propfindResponse: couldn't list public shares")
span.SetStatus(codes.Error, err.Error())
}
break
}
}
}
prefer := net.ParsePrefer(r.Header.Get(net.HeaderPrefer))
returnMinimal := prefer[net.HeaderPreferReturn] == "minimal"
propRes, err := MultistatusResponse(ctx, &pf, resourceInfos, p.PublicURL, namespace, linkshares, returnMinimal)
if err != nil {
log.Error().Err(err).Msg("error formatting propfind")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set(net.HeaderDav, "1, 3, extended-mkcol")
w.Header().Set(net.HeaderContentType, "application/xml; charset=utf-8")
if sendTusHeaders {
w.Header().Add(net.HeaderAccessControlExposeHeaders, strings.Join([]string{net.HeaderTusResumable, net.HeaderTusVersion, net.HeaderTusExtension}, ", "))
w.Header().Set(net.HeaderTusResumable, "1.0.0")
w.Header().Set(net.HeaderTusVersion, "1.0.0")
w.Header().Set(net.HeaderTusExtension, "creation,creation-with-upload,checksum,expiration")
}
w.Header().Set(net.HeaderVary, net.HeaderPrefer)
if returnMinimal {
w.Header().Set(net.HeaderPreferenceApplied, "return=minimal")
}
w.WriteHeader(http.StatusMultiStatus)
if _, err := w.Write(propRes); err != nil {
log.Err(err).Msg("error writing response")
}
}
// TODO this is just a stat -> rename
func (p *Handler) statSpace(ctx context.Context, client gateway.GatewayAPIClient, ref *provider.Reference, metadataKeys, fieldMaskPaths []string) (*provider.ResourceInfo, *rpc.Status, error) {
req := &provider.StatRequest{
Ref: ref,
ArbitraryMetadataKeys: metadataKeys,
FieldMask: &fieldmaskpb.FieldMask{Paths: fieldMaskPaths},
}
res, err := client.Stat(ctx, req)
if err != nil {
return nil, nil, err
}
return res.GetInfo(), res.GetStatus(), nil
}
func (p *Handler) getResourceInfos(ctx context.Context, w http.ResponseWriter, r *http.Request, pf XML, spaces []*provider.StorageSpace, requestPath string, log zerolog.Logger) ([]*provider.ResourceInfo, bool, bool) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "get_resource_infos")
span.SetAttributes(attribute.KeyValue{Key: "requestPath", Value: attribute.StringValue(requestPath)})
defer span.End()
dh := r.Header.Get(net.HeaderDepth)
depth, err := net.ParseDepth(dh)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
m := fmt.Sprintf("Invalid Depth header value: %v", dh)
b, err := errors.Marshal(http.StatusBadRequest, m, "")
errors.HandleWebdavError(&log, w, b, err)
return nil, false, false
}
span.SetAttributes(attribute.KeyValue{Key: "depth", Value: attribute.StringValue(depth.String())})
client, err := p.getClient()
if err != nil {
log.Error().Err(err).Msg("error getting grpc client")
w.WriteHeader(http.StatusInternalServerError)
return nil, false, false
}
metadataKeys, fieldMaskPaths := metadataKeys(pf)
// we need to stat all spaces to aggregate the root etag, mtime and size
// TODO cache per space (hah, no longer per user + per space!)
var (
rootInfo *provider.ResourceInfo
mostRecentChildInfo *provider.ResourceInfo
aggregatedChildSize uint64
spaceMap = make(map[*provider.ResourceInfo]spaceData, len(spaces))
)
for _, space := range spaces {
spacePath := ""
if spacePath = utils.ReadPlainFromOpaque(space.Opaque, "path"); spacePath == "" {
continue // not mounted
}
if space.RootInfo == nil {
spaceRef, err := spacelookup.MakeStorageSpaceReference(space.Id.OpaqueId, ".")
if err != nil {
continue
}
info, status, err := p.statSpace(ctx, client, &spaceRef, metadataKeys, fieldMaskPaths)
if err != nil || status.GetCode() != rpc.Code_CODE_OK {
continue
}
space.RootInfo = info
}
// TODO separate stats to the path or to the children, after statting all children update the mtime/etag
// TODO get mtime, and size from space as well, so we no longer have to stat here? would require sending the requested metadata keys as well
// root should be a ResourceInfo so it can contain the full stat, not only the id ... do we even need spaces then?
// metadata keys could all be prefixed with "root." to indicate we want more than the root id ...
// TODO can we reuse the space.rootinfo?
spaceRef := spacelookup.MakeRelativeReference(space, requestPath, false)
var info *provider.ResourceInfo
if spaceRef.Path == "." && utils.ResourceIDEqual(spaceRef.ResourceId, space.Root) {
info = space.RootInfo
} else {
var status *rpc.Status
info, status, err = p.statSpace(ctx, client, spaceRef, metadataKeys, fieldMaskPaths)
if err != nil || status.GetCode() != rpc.Code_CODE_OK {
continue
}
}
// adjust path
info.Path = filepath.Join(spacePath, spaceRef.Path)
spaceMap[info] = spaceData{Ref: spaceRef, SpaceType: space.SpaceType}
if rootInfo == nil && requestPath == info.Path {
rootInfo = info
} else if requestPath != spacePath && strings.HasPrefix(spacePath, requestPath) { // Check if the space is a child of the requested path
// aggregate child metadata
aggregatedChildSize += info.Size
if mostRecentChildInfo == nil {
mostRecentChildInfo = info
continue
}
if mostRecentChildInfo.Mtime == nil || (info.Mtime != nil && utils.TSToUnixNano(info.Mtime) > utils.TSToUnixNano(mostRecentChildInfo.Mtime)) {
mostRecentChildInfo = info
}
}
}
if len(spaceMap) == 0 || rootInfo == nil {
// TODO if we have children invent node on the fly
w.WriteHeader(http.StatusNotFound)
m := "Resource not found"
b, err := errors.Marshal(http.StatusNotFound, m, "")
errors.HandleWebdavError(&log, w, b, err)
return nil, false, false
}
if mostRecentChildInfo != nil {
if rootInfo.Mtime == nil || (mostRecentChildInfo.Mtime != nil && utils.TSToUnixNano(mostRecentChildInfo.Mtime) > utils.TSToUnixNano(rootInfo.Mtime)) {
rootInfo.Mtime = mostRecentChildInfo.Mtime
if mostRecentChildInfo.Etag != "" {
rootInfo.Etag = mostRecentChildInfo.Etag
}
}
if rootInfo.Etag == "" {
rootInfo.Etag = mostRecentChildInfo.Etag
}
}
// add size of children
rootInfo.Size += aggregatedChildSize
resourceInfos := []*provider.ResourceInfo{
rootInfo, // PROPFIND always includes the root resource
}
if rootInfo.Type == provider.ResourceType_RESOURCE_TYPE_FILE || depth == net.DepthZero {
// If the resource is a file then it can't have any children so we can
// stop here.
return resourceInfos, true, true
}
childInfos := map[string]*provider.ResourceInfo{}
for spaceInfo, spaceData := range spaceMap {
switch {
case spaceInfo.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER && depth != net.DepthInfinity:
addChild(childInfos, spaceInfo, requestPath, rootInfo)
case spaceInfo.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER && depth == net.DepthOne:
switch {
case strings.HasPrefix(requestPath, spaceInfo.Path) && spaceData.SpaceType != "virtual":
req := &provider.ListContainerRequest{
Ref: spaceData.Ref,
ArbitraryMetadataKeys: metadataKeys,
}
res, err := client.ListContainer(ctx, req)
if err != nil {
log.Error().Err(err).Msg("error sending list container grpc request")
w.WriteHeader(http.StatusInternalServerError)
return nil, false, false
}
if res.Status.Code != rpc.Code_CODE_OK {
log.Debug().Interface("status", res.Status).Msg("List Container not ok, skipping")
continue
}
for _, info := range res.Infos {
info.Path = path.Join(requestPath, info.Path)
}
resourceInfos = append(resourceInfos, res.Infos...)
case strings.HasPrefix(spaceInfo.Path, requestPath): // space is a deep child of the requested path
addChild(childInfos, spaceInfo, requestPath, rootInfo)
}
case depth == net.DepthInfinity:
// use a stack to explore sub-containers breadth-first
if spaceInfo != rootInfo {
resourceInfos = append(resourceInfos, spaceInfo)
}
stack := []*provider.ResourceInfo{spaceInfo}
for len(stack) != 0 {
info := stack[0]
stack = stack[1:]
if info.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER || spaceData.SpaceType == "virtual" {
continue
}
req := &provider.ListContainerRequest{
Ref: &provider.Reference{
ResourceId: spaceInfo.Id,
// TODO here we cut of the path that we added after stating the space above
Path: utils.MakeRelativePath(strings.TrimPrefix(info.Path, spaceInfo.Path)),
},
ArbitraryMetadataKeys: metadataKeys,
}
res, err := client.ListContainer(ctx, req) // FIXME public link depth infinity -> "gateway: could not find provider: gateway: error calling ListStorageProviders: rpc error: code = PermissionDenied desc = auth: core access token is invalid"
if err != nil {
log.Error().Err(err).Interface("info", info).Msg("error sending list container grpc request")
w.WriteHeader(http.StatusInternalServerError)
return nil, false, false
}
if res.Status.Code != rpc.Code_CODE_OK {
log.Debug().Interface("status", res.Status).Msg("List Container not ok, skipping")
continue
}
// check sub-containers in reverse order and add them to the stack
// the reversed order here will produce a more logical sorting of results
for i := len(res.Infos) - 1; i >= 0; i-- {
// add path to resource
res.Infos[i].Path = filepath.Join(info.Path, res.Infos[i].Path)
if res.Infos[i].Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
stack = append(stack, res.Infos[i])
}
}
resourceInfos = append(resourceInfos, res.Infos...)
// TODO: stream response to avoid storing too many results in memory
// we can do that after having stated the root.
}
}
}
if rootInfo.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
// now add all aggregated child infos
for _, childInfo := range childInfos {
resourceInfos = append(resourceInfos, childInfo)
}
}
sendTusHeaders := true
// let clients know this collection supports tus.io POST requests to start uploads
if rootInfo.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
if rootInfo.Opaque != nil {
_, ok := rootInfo.Opaque.Map["disable_tus"]
sendTusHeaders = !ok
}
}
return resourceInfos, sendTusHeaders, true
}
func (p *Handler) getSpaceResourceInfos(ctx context.Context, w http.ResponseWriter, r *http.Request, pf XML, ref *provider.Reference, requestPath string, depth net.Depth, log zerolog.Logger) ([]*provider.ResourceInfo, bool) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "get_space_resource_infos")
span.SetAttributes(attribute.KeyValue{Key: "requestPath", Value: attribute.StringValue(requestPath)})
span.SetAttributes(attribute.KeyValue{Key: "depth", Value: attribute.StringValue(depth.String())})
defer span.End()
client, err := p.getClient()
if err != nil {
log.Error().Err(err).Msg("error getting grpc client")
w.WriteHeader(http.StatusInternalServerError)
return nil, false
}
metadataKeys, _ := metadataKeys(pf)
resourceInfos := []*provider.ResourceInfo{}
req := &provider.ListContainerRequest{
Ref: ref,
ArbitraryMetadataKeys: metadataKeys,
FieldMask: &fieldmaskpb.FieldMask{Paths: []string{"*"}}, // TODO use more sophisticated filter
}
res, err := client.ListContainer(ctx, req)
if err != nil {
log.Error().Err(err).Msg("error sending list container grpc request")
w.WriteHeader(http.StatusInternalServerError)
return nil, false
}
if res.Status.Code != rpc.Code_CODE_OK {
log.Debug().Interface("status", res.Status).Msg("List Container not ok, skipping")
w.WriteHeader(http.StatusInternalServerError)
return nil, false
}
for _, info := range res.Infos {
info.Path = path.Join(requestPath, info.Path)
}
resourceInfos = append(resourceInfos, res.Infos...)
if depth == net.DepthInfinity {
// use a stack to explore sub-containers breadth-first
stack := resourceInfos
for len(stack) != 0 {
info := stack[0]
stack = stack[1:]
if info.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER /*|| space.SpaceType == "virtual"*/ {
continue
}
req := &provider.ListContainerRequest{
Ref: &provider.Reference{
ResourceId: info.Id,
Path: ".",
},
ArbitraryMetadataKeys: metadataKeys,
}
res, err := client.ListContainer(ctx, req) // FIXME public link depth infinity -> "gateway: could not find provider: gateway: error calling ListStorageProviders: rpc error: code = PermissionDenied desc = auth: core access token is invalid"
if err != nil {
log.Error().Err(err).Interface("info", info).Msg("error sending list container grpc request")
w.WriteHeader(http.StatusInternalServerError)
return nil, false
}
if res.Status.Code != rpc.Code_CODE_OK {
log.Debug().Interface("status", res.Status).Msg("List Container not ok, skipping")
continue
}
// check sub-containers in reverse order and add them to the stack
// the reversed order here will produce a more logical sorting of results
for i := len(res.Infos) - 1; i >= 0; i-- {
// add path to resource
res.Infos[i].Path = filepath.Join(info.Path, res.Infos[i].Path)
res.Infos[i].Path = utils.MakeRelativePath(res.Infos[i].Path)
if res.Infos[i].Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
stack = append(stack, res.Infos[i])
}
}
resourceInfos = append(resourceInfos, res.Infos...)
// TODO: stream response to avoid storing too many results in memory
// we can do that after having stated the root.
}
}
return resourceInfos, true
}
// metadataKeys splits the propfind properties into arbitrary metadata and ResourceInfo field mask paths
func metadataKeys(pf XML) ([]string, []string) {
var metadataKeys []string
var fieldMaskKeys []string
if pf.Allprop != nil {
// TODO this changes the behavior and returns all properties if allprops has been set,
// but allprops should only return some default properties
// see https://tools.ietf.org/html/rfc4918#section-9.1
// the description of arbitrary_metadata_keys in https://cs3org.github.io/cs3apis/#cs3.storage.provider.v1beta1.ListContainerRequest an others may need clarification
// tracked in https://github.com/cs3org/cs3apis/issues/104
metadataKeys = append(metadataKeys, "*")
fieldMaskKeys = append(fieldMaskKeys, "*")
} else {
metadataKeys = make([]string, 0, len(pf.Prop))
fieldMaskKeys = make([]string, 0, len(pf.Prop))
for i := range pf.Prop {
if requiresExplicitFetching(&pf.Prop[i]) {
key := metadataKeyOf(&pf.Prop[i])
switch key {
case "share-types":
fieldMaskKeys = append(fieldMaskKeys, key)
default:
metadataKeys = append(metadataKeys, key)
}
}
}
}
return metadataKeys, fieldMaskKeys
}
func addChild(childInfos map[string]*provider.ResourceInfo,
spaceInfo *provider.ResourceInfo,
requestPath string,
rootInfo *provider.ResourceInfo,
) {
if spaceInfo == rootInfo {
return // already accounted for
}
childPath := strings.TrimPrefix(spaceInfo.Path, requestPath)
childName, tail := router.ShiftPath(childPath)
if tail != "/" {
spaceInfo.Type = provider.ResourceType_RESOURCE_TYPE_CONTAINER
spaceInfo.Checksum = nil
// TODO unset opaque checksum
}
spaceInfo.Path = path.Join(requestPath, childName)
if existingChild, ok := childInfos[childName]; ok {
// aggregate size
childInfos[childName].Size += spaceInfo.Size
// use most recent child
if existingChild.Mtime == nil || (spaceInfo.Mtime != nil && utils.TSToUnixNano(spaceInfo.Mtime) > utils.TSToUnixNano(existingChild.Mtime)) {
childInfos[childName].Mtime = spaceInfo.Mtime
childInfos[childName].Etag = spaceInfo.Etag
}
// only update fileid if the resource is a direct child
if tail == "/" {
childInfos[childName].Id = spaceInfo.Id
}
} else {
childInfos[childName] = spaceInfo
}
}
func requiresExplicitFetching(n *xml.Name) bool {
switch n.Space {
case net.NsDav:
switch n.Local {
case "quota-available-bytes", "quota-used-bytes":
// A <DAV:allprop> PROPFIND request SHOULD NOT return DAV:quota-available-bytes and DAV:quota-used-bytes
// from https://www.rfc-editor.org/rfc/rfc4331.html#section-2
return true
default:
return false
}
case net.NsOwncloud:
switch n.Local {
case "favorite", "share-types", "checksums", "size", "tags":
return true
default:
return false
}
case net.NsOCS:
return false
}
return true
}
// ReadPropfind extracts and parses the propfind XML information from a Reader
// from https://github.com/golang/net/blob/e514e69ffb8bc3c76a71ae40de0118d794855992/webdav/xml.go#L178-L205
func ReadPropfind(r io.Reader) (pf XML, status int, err error) {
c := countingReader{r: r}
if err = xml.NewDecoder(&c).Decode(&pf); err != nil {
if err == io.EOF {
if c.n == 0 {
// An empty body means to propfind allprop.
// http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
return XML{Allprop: new(struct{})}, 0, nil
}
err = errors.ErrInvalidPropfind
}
return XML{}, http.StatusBadRequest, err
}
if pf.Allprop == nil && pf.Include != nil {
return XML{}, http.StatusBadRequest, errors.ErrInvalidPropfind
}
if pf.Allprop != nil && (pf.Prop != nil || pf.Propname != nil) {
return XML{}, http.StatusBadRequest, errors.ErrInvalidPropfind
}
if pf.Prop != nil && pf.Propname != nil {
return XML{}, http.StatusBadRequest, errors.ErrInvalidPropfind
}
if pf.Propname == nil && pf.Allprop == nil && pf.Prop == nil {
// jfd: I think <d:prop></d:prop> is perfectly valid ... treat it as allprop
return XML{Allprop: new(struct{})}, 0, nil
}
return pf, 0, nil
}
// MultistatusResponse converts a list of resource infos into a multistatus response string
func MultistatusResponse(ctx context.Context, pf *XML, mds []*provider.ResourceInfo, publicURL, ns string, linkshares map[string]struct{}, returnMinimal bool) ([]byte, error) {
g, ctx := errgroup.WithContext(ctx)
type work struct {
position int
info *provider.ResourceInfo
}
type result struct {
position int
info *ResponseXML
}
workChan := make(chan work, len(mds))
resultChan := make(chan result, len(mds))
// Distribute work
g.Go(func() error {
defer close(workChan)
for i, md := range mds {
select {
case workChan <- work{position: i, info: md}:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
// Spawn workers that'll concurrently work the queue
numWorkers := 50
if len(mds) < numWorkers {
numWorkers = len(mds)
}
for i := 0; i < numWorkers; i++ {
g.Go(func() error {
for work := range workChan {
res, err := mdToPropResponse(ctx, pf, work.info, publicURL, ns, linkshares, returnMinimal)
if err != nil {
return err
}
select {
case resultChan <- result{position: work.position, info: res}:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
}
// Wait for things to settle down, then close results chan
go func() {
_ = g.Wait() // error is checked later
close(resultChan)
}()
if err := g.Wait(); err != nil {
return nil, err
}
responses := make([]*ResponseXML, len(mds))
for res := range resultChan {
responses[res.position] = res.info
}
msr := NewMultiStatusResponseXML()
msr.Responses = responses
msg, err := xml.Marshal(msr)
if err != nil {
return nil, err
}
return msg, nil
}
// mdToPropResponse converts the CS3 metadata into a webdav PropResponse
// ns is the CS3 namespace that needs to be removed from the CS3 path before
// prefixing it with the baseURI
func mdToPropResponse(ctx context.Context, pf *XML, md *provider.ResourceInfo, publicURL, ns string, linkshares map[string]struct{}, returnMinimal bool) (*ResponseXML, error) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "md_to_prop_response")
span.SetAttributes(attribute.KeyValue{Key: "publicURL", Value: attribute.StringValue(publicURL)})
span.SetAttributes(attribute.KeyValue{Key: "ns", Value: attribute.StringValue(ns)})
defer span.End()
sublog := appctx.GetLogger(ctx).With().Interface("md", md).Str("ns", ns).Logger()
id := md.Id
p := strings.TrimPrefix(md.Path, ns)
baseURI := ctx.Value(net.CtxKeyBaseURI).(string)
ref := path.Join(baseURI, p)
if md.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
ref += "/"
}
response := ResponseXML{
Href: net.EncodePath(ref),
Propstat: []PropstatXML{},
}
var ls *link.PublicShare
// -1 indicates uncalculated
// -2 indicates unknown (default)
// -3 indicates unlimited
quota := net.PropQuotaUnknown
size := strconv.FormatUint(md.Size, 10)
var lock *provider.Lock
shareTypes := ""
// TODO refactor helper functions: GetOpaqueJSONEncoded(opaque, key string, *struct) err, GetOpaquePlainEncoded(opaque, key) value, err
// or use ok like pattern and return bool?
if md.Opaque != nil && md.Opaque.Map != nil {
if md.Opaque.Map["link-share"] != nil && md.Opaque.Map["link-share"].Decoder == "json" {
ls = &link.PublicShare{}
err := json.Unmarshal(md.Opaque.Map["link-share"].Value, ls)
if err != nil {
sublog.Error().Err(err).Msg("could not unmarshal link json")
}
}
if quota = utils.ReadPlainFromOpaque(md.Opaque, "quota"); quota == "" {