/
upload.go
339 lines (288 loc) · 9.16 KB
/
upload.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
// Copyright 2018-2023 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 main
import (
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
// TODO(labkode): this should not come from this package.
"github.com/cs3org/reva/v2/internal/grpc/services/storageprovider"
"github.com/cs3org/reva/v2/internal/http/services/datagateway"
"github.com/cs3org/reva/v2/pkg/crypto"
ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
"github.com/cs3org/reva/v2/pkg/errtypes"
"github.com/cs3org/reva/v2/pkg/rhttp"
"github.com/cs3org/reva/v2/pkg/utils"
"github.com/eventials/go-tus"
"github.com/eventials/go-tus/memorystore"
"github.com/pkg/errors"
"github.com/studio-b12/gowebdav"
)
func uploadCommand() *command {
cmd := newCommand("upload")
cmd.Description = func() string { return "upload a local file to the remote server" }
cmd.Usage = func() string { return "Usage: upload [-flags] <file_name> <remote_target>" }
protocolFlag := cmd.String("protocol", "tus", "the protocol to be used for uploads")
xsFlag := cmd.String("xs", "negotiate", "compute checksum")
cmd.ResetFlags = func() {
*protocolFlag, *xsFlag = "tus", "negotiate"
}
cmd.Action = func(w ...io.Writer) error {
ctx := getAuthContext()
if cmd.NArg() < 2 {
return errors.New("Invalid arguments: " + cmd.Usage())
}
fn := cmd.Args()[0]
target := cmd.Args()[1]
absPath, err := utils.ResolvePath(fn)
if err != nil {
return err
}
fd, err := os.Open(absPath)
if err != nil {
return err
}
defer fd.Close()
md, err := fd.Stat()
if err != nil {
return err
}
fmt.Printf("Local file size: %d bytes\n", md.Size())
gwc, err := getClient()
if err != nil {
return err
}
req := &provider.InitiateFileUploadRequest{
Ref: &provider.Reference{Path: target},
Opaque: &typespb.Opaque{
Map: map[string]*typespb.OpaqueEntry{
"Upload-Length": {
Decoder: "plain",
Value: []byte(strconv.FormatInt(md.Size(), 10)),
},
},
},
}
res, err := gwc.InitiateFileUpload(ctx, req)
if err != nil {
return err
}
if res.Status.Code != rpc.Code_CODE_OK {
return formatError(res.Status)
}
if err = checkUploadWebdavRef(res.Protocols, md, fd); err != nil {
if _, ok := err.(errtypes.IsNotSupported); !ok {
return err
}
} else {
return nil
}
p, err := getUploadProtocolInfo(res.Protocols, *protocolFlag)
if err != nil {
return err
}
fmt.Printf("Data server: %s\n", p.UploadEndpoint)
fmt.Printf("Allowed checksums: %+v\n", p.AvailableChecksums)
xsType, err := guessXS(*xsFlag, p.AvailableChecksums)
if err != nil {
return err
}
fmt.Printf("Checksum selected: %s\n", xsType)
xs, err := computeXS(xsType, fd)
if err != nil {
return err
}
fmt.Printf("Local XS: %s:%s\n", xsType, xs)
// seek back reader to 0
if _, err := fd.Seek(0, 0); err != nil {
return err
}
dataServerURL := p.UploadEndpoint
if *protocolFlag == "simple" {
httpReq, err := rhttp.NewRequest(ctx, http.MethodPut, dataServerURL, fd)
if err != nil {
return err
}
httpReq.Header.Set(datagateway.TokenTransportHeader, p.Token)
q := httpReq.URL.Query()
q.Add("xs", xs)
q.Add("xs_type", storageprovider.GRPC2PKGXS(xsType).String())
httpReq.URL.RawQuery = q.Encode()
httpRes, err := client.Do(httpReq)
if err != nil {
return err
}
defer httpRes.Body.Close()
if httpRes.StatusCode != http.StatusOK {
return errors.New("upload: PUT request returned " + httpRes.Status)
}
} else {
// create the tus client.
c := tus.DefaultConfig()
c.Resume = true
c.HttpClient = client
c.Store, err = memorystore.NewMemoryStore()
if err != nil {
return err
}
c.Header.Add(datagateway.TokenTransportHeader, p.Token)
tusc, err := tus.NewClient(dataServerURL, c)
if err != nil {
return err
}
metadata := map[string]string{
"filename": filepath.Base(target),
"dir": filepath.Dir(target),
"checksum": fmt.Sprintf("%s %s", storageprovider.GRPC2PKGXS(xsType).String(), xs),
}
fingerprint := fmt.Sprintf("%s-%d-%s-%s", md.Name(), md.Size(), md.ModTime(), xs)
// create an upload from a file.
upload := tus.NewUpload(fd, md.Size(), metadata, fingerprint)
// create the uploader.
c.Store.Set(upload.Fingerprint, dataServerURL)
uploader := tus.NewUploader(tusc, dataServerURL, upload, 0)
// start the uploading process.
err = uploader.Upload()
if err != nil {
return err
}
}
req2 := &provider.StatRequest{
Ref: &provider.Reference{Path: target},
}
res2, err := gwc.Stat(ctx, req2)
if err != nil {
return err
}
if res2.Status.Code != rpc.Code_CODE_OK {
return formatError(res2.Status)
}
info := res2.Info
fmt.Printf("File uploaded: %s:%s %d %s\n", info.Id.StorageId, info.Id.OpaqueId, info.Size, info.Path)
return nil
}
return cmd
}
func getUploadProtocolInfo(protocolInfos []*gateway.FileUploadProtocol, protocol string) (*gateway.FileUploadProtocol, error) {
for _, p := range protocolInfos {
if p.Protocol == protocol {
return p, nil
}
}
return nil, errtypes.NotFound(protocol)
}
func checkUploadWebdavRef(protocols []*gateway.FileUploadProtocol, md os.FileInfo, fd *os.File) error {
p, err := getUploadProtocolInfo(protocols, "simple")
if err != nil {
return err
}
if p.Opaque == nil {
return errtypes.NotSupported("opaque object not defined")
}
var token string
tokenOpaque, ok := p.Opaque.Map["webdav-token"]
if !ok {
return errtypes.NotSupported("webdav token not defined")
}
switch tokenOpaque.Decoder {
case "plain":
token = string(tokenOpaque.Value)
default:
return errors.New("opaque entry decoder not recognized: " + tokenOpaque.Decoder)
}
var filePath string
fileOpaque, ok := p.Opaque.Map["webdav-file-path"]
if !ok {
return errtypes.NotSupported("webdav file path not defined")
}
switch fileOpaque.Decoder {
case "plain":
filePath = string(fileOpaque.Value)
default:
return errors.New("opaque entry decoder not recognized: " + fileOpaque.Decoder)
}
c := gowebdav.NewClient(p.UploadEndpoint, "", "")
c.SetHeader(ctxpkg.TokenHeader, token)
c.SetHeader("Upload-Length", strconv.FormatInt(md.Size(), 10))
if err = c.WriteStream(filePath, fd, 0700); err != nil {
return err
}
fmt.Println("File uploaded")
return nil
}
func computeXS(t provider.ResourceChecksumType, r io.Reader) (string, error) {
switch t {
case provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_ADLER32:
return crypto.ComputeAdler32XS(r)
case provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_MD5:
return crypto.ComputeMD5XS(r)
case provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_SHA1:
return crypto.ComputeSHA1XS(r)
case provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_UNSET:
return "", nil
default:
return "", fmt.Errorf("invalid checksum: %s", t)
}
}
func guessXS(xsFlag string, availableXS []*provider.ResourceChecksumPriority) (provider.ResourceChecksumType, error) {
// force use of checksum if available server side.
if xsFlag != "negotiate" {
wanted := storageprovider.PKG2GRPCXS(xsFlag)
if wanted == provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_INVALID {
return provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_INVALID, fmt.Errorf("desired checksum is invalid: %s", xsFlag)
}
if isXSAvailable(wanted, availableXS) {
return wanted, nil
}
return provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_INVALID, fmt.Errorf("checksum not available server side: %s", xsFlag)
}
// negotiate the checksum type based on priority list from server-side.
if len(availableXS) == 0 {
return provider.ResourceChecksumType_RESOURCE_CHECKSUM_TYPE_INVALID, fmt.Errorf("no available xs for negotiating")
}
// pick the one with priority to the lower number.
desired := pickChecksumWithHighestPrio(availableXS)
return desired, nil
}
func pickChecksumWithHighestPrio(xss []*provider.ResourceChecksumPriority) provider.ResourceChecksumType {
var chosen provider.ResourceChecksumType
var maxPrio uint32 = math.MaxUint32
for _, xs := range xss {
if xs.Priority < maxPrio {
maxPrio = xs.Priority
chosen = xs.Type
}
}
return chosen
}
func isXSAvailable(t provider.ResourceChecksumType, available []*provider.ResourceChecksumPriority) bool {
for _, xsPrio := range available {
if xsPrio.Type == t {
return true
}
}
return false
}