forked from drakkan/sftpgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
468 lines (432 loc) · 12.2 KB
/
file.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
// Copyright (C) 2019-2022 Nicola Murino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package webdavd
import (
"context"
"encoding/xml"
"errors"
"io"
"mime"
"net/http"
"os"
"path"
"sync/atomic"
"time"
"github.com/aKardasz/webdav"
"github.com/eikenb/pipeat"
"github.com/aKardasz/sftpgo/v2/internal/common"
"github.com/aKardasz/sftpgo/v2/internal/dataprovider"
"github.com/aKardasz/sftpgo/v2/internal/logger"
"github.com/aKardasz/sftpgo/v2/internal/util"
"github.com/aKardasz/sftpgo/v2/internal/vfs"
)
var (
errTransferAborted = errors.New("transfer aborted")
lastModifiedProps = []string{"Win32LastModifiedTime", "getlastmodified"}
)
type webDavFile struct {
*common.BaseTransfer
writer io.WriteCloser
reader io.ReadCloser
info os.FileInfo
startOffset int64
isFinished bool
readTryed atomic.Bool
}
func newWebDavFile(baseTransfer *common.BaseTransfer, pipeWriter *vfs.PipeWriter, pipeReader *pipeat.PipeReaderAt) *webDavFile {
var writer io.WriteCloser
var reader io.ReadCloser
if baseTransfer.File != nil {
writer = baseTransfer.File
reader = baseTransfer.File
} else if pipeWriter != nil {
writer = pipeWriter
} else if pipeReader != nil {
reader = pipeReader
}
f := &webDavFile{
BaseTransfer: baseTransfer,
writer: writer,
reader: reader,
isFinished: false,
startOffset: 0,
info: nil,
}
f.readTryed.Store(false)
return f
}
type webDavFileInfo struct {
os.FileInfo
Fs vfs.Fs
virtualPath string
fsPath string
}
// ContentType implements webdav.ContentTyper interface
func (fi *webDavFileInfo) ContentType(ctx context.Context) (string, error) {
extension := path.Ext(fi.virtualPath)
if extension == "" || extension == ".dat" {
return "application/octet-stream", nil
}
contentType := mime.TypeByExtension(extension)
if contentType != "" {
return contentType, nil
}
contentType = mimeTypeCache.getMimeFromCache(extension)
if contentType != "" {
return contentType, nil
}
contentType, err := fi.Fs.GetMimeType(fi.fsPath)
if contentType != "" {
mimeTypeCache.addMimeToCache(extension, contentType)
return contentType, err
}
return "", webdav.ErrNotImplemented
}
// Readdir reads directory entries from the handle
func (f *webDavFile) Readdir(count int) ([]os.FileInfo, error) {
if !f.Connection.User.HasPerm(dataprovider.PermListItems, f.GetVirtualPath()) {
return nil, f.Connection.GetPermissionDeniedError()
}
entries, err := f.Connection.ListDir(f.GetVirtualPath())
if err != nil {
return nil, err
}
for idx, info := range entries {
entries[idx] = &webDavFileInfo{
FileInfo: info,
Fs: f.Fs,
virtualPath: path.Join(f.GetVirtualPath(), info.Name()),
fsPath: f.Fs.Join(f.GetFsPath(), info.Name()),
}
}
return entries, nil
}
// Stat the handle
func (f *webDavFile) Stat() (os.FileInfo, error) {
if f.GetType() == common.TransferDownload && !f.Connection.User.HasPerm(dataprovider.PermListItems, path.Dir(f.GetVirtualPath())) {
return nil, f.Connection.GetPermissionDeniedError()
}
f.Lock()
errUpload := f.ErrTransfer
f.Unlock()
if f.GetType() == common.TransferUpload && errUpload == nil {
info := &webDavFileInfo{
FileInfo: vfs.NewFileInfo(f.GetFsPath(), false, f.BytesReceived.Load(), time.Now(), false),
Fs: f.Fs,
virtualPath: f.GetVirtualPath(),
fsPath: f.GetFsPath(),
}
return info, nil
}
info, err := f.Fs.Stat(f.GetFsPath())
if err != nil {
return nil, err
}
if vfs.IsCryptOsFs(f.Fs) {
info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
}
fi := &webDavFileInfo{
FileInfo: info,
Fs: f.Fs,
virtualPath: f.GetVirtualPath(),
fsPath: f.GetFsPath(),
}
return fi, nil
}
func (f *webDavFile) checkFirstRead() error {
if !f.Connection.User.HasPerm(dataprovider.PermDownload, path.Dir(f.GetVirtualPath())) {
return f.Connection.GetPermissionDeniedError()
}
transferQuota := f.BaseTransfer.GetTransferQuota()
if !transferQuota.HasDownloadSpace() {
f.Connection.Log(logger.LevelInfo, "denying file read due to quota limits")
return f.Connection.GetReadQuotaExceededError()
}
if ok, policy := f.Connection.User.IsFileAllowed(f.GetVirtualPath()); !ok {
f.Connection.Log(logger.LevelWarn, "reading file %#v is not allowed", f.GetVirtualPath())
return f.Connection.GetErrorForDeniedFile(policy)
}
err := common.ExecutePreAction(f.Connection, common.OperationPreDownload, f.GetFsPath(), f.GetVirtualPath(), 0, 0)
if err != nil {
f.Connection.Log(logger.LevelDebug, "download for file %#v denied by pre action: %v", f.GetVirtualPath(), err)
return f.Connection.GetPermissionDeniedError()
}
f.readTryed.Store(true)
return nil
}
// Read reads the contents to downloads.
func (f *webDavFile) Read(p []byte) (n int, err error) {
if f.AbortTransfer.Load() {
return 0, errTransferAborted
}
if !f.readTryed.Load() {
if err := f.checkFirstRead(); err != nil {
return 0, err
}
}
f.Connection.UpdateLastActivity()
// the file is read sequentially we don't need to check for concurrent reads and so
// lock the transfer while opening the remote file
if f.reader == nil {
if f.GetType() != common.TransferDownload {
f.TransferError(common.ErrOpUnsupported)
return 0, common.ErrOpUnsupported
}
file, r, cancelFn, e := f.Fs.Open(f.GetFsPath(), 0)
f.Lock()
if e == nil {
if file != nil {
f.File = file
f.writer = f.File
f.reader = f.File
} else if r != nil {
f.reader = r
}
f.BaseTransfer.SetCancelFn(cancelFn)
}
f.ErrTransfer = e
f.startOffset = 0
f.Unlock()
if e != nil {
return 0, e
}
}
n, err = f.reader.Read(p)
f.BytesSent.Add(int64(n))
if err == nil {
err = f.CheckRead()
}
if err != nil && err != io.EOF {
f.TransferError(err)
return
}
f.HandleThrottle()
return
}
// Write writes the uploaded contents.
func (f *webDavFile) Write(p []byte) (n int, err error) {
if f.AbortTransfer.Load() {
return 0, errTransferAborted
}
f.Connection.UpdateLastActivity()
n, err = f.writer.Write(p)
f.BytesReceived.Add(int64(n))
if err == nil {
err = f.CheckWrite()
}
if err != nil {
f.TransferError(err)
return
}
f.HandleThrottle()
return
}
func (f *webDavFile) updateStatInfo() error {
if f.info != nil {
return nil
}
info, err := f.Fs.Stat(f.GetFsPath())
if err != nil {
return err
}
if vfs.IsCryptOsFs(f.Fs) {
info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
}
f.info = info
return nil
}
func (f *webDavFile) updateTransferQuotaOnSeek() {
transferQuota := f.GetTransferQuota()
if transferQuota.HasSizeLimits() {
go func(ulSize, dlSize int64, user dataprovider.User) {
dataprovider.UpdateUserTransferQuota(&user, ulSize, dlSize, false) //nolint:errcheck
}(f.BytesReceived.Load(), f.BytesSent.Load(), f.Connection.User)
}
}
func (f *webDavFile) checkFile() error {
if f.File == nil && vfs.IsLocalOrUnbufferedSFTPFs(f.Fs) {
file, _, _, err := f.Fs.Open(f.GetFsPath(), 0)
if err != nil {
f.Connection.Log(logger.LevelWarn, "could not open file %q for seeking: %v",
f.GetFsPath(), err)
f.TransferError(err)
return err
}
f.File = file
f.reader = file
f.writer = file
}
return nil
}
func (f *webDavFile) seekFile(offset int64, whence int) (int64, error) {
ret, err := f.File.Seek(offset, whence)
if err != nil {
f.TransferError(err)
}
return ret, err
}
// Seek sets the offset for the next Read or Write on the writer to offset,
// interpreted according to whence: 0 means relative to the origin of the file,
// 1 means relative to the current offset, and 2 means relative to the end.
// It returns the new offset and an error, if any.
func (f *webDavFile) Seek(offset int64, whence int) (int64, error) {
f.Connection.UpdateLastActivity()
if err := f.checkFile(); err != nil {
return 0, err
}
if f.File != nil {
return f.seekFile(offset, whence)
}
if f.GetType() == common.TransferDownload {
readOffset := f.startOffset + f.BytesSent.Load()
if offset == 0 && readOffset == 0 {
if whence == io.SeekStart {
return 0, nil
} else if whence == io.SeekEnd {
if err := f.updateStatInfo(); err != nil {
return 0, err
}
return f.info.Size(), nil
}
}
// close the reader and create a new one at startByte
if f.reader != nil {
f.reader.Close() //nolint:errcheck
f.reader = nil
}
startByte := int64(0)
f.BytesReceived.Store(0)
f.BytesSent.Store(0)
f.updateTransferQuotaOnSeek()
switch whence {
case io.SeekStart:
startByte = offset
case io.SeekCurrent:
startByte = readOffset + offset
case io.SeekEnd:
if err := f.updateStatInfo(); err != nil {
f.TransferError(err)
return 0, err
}
startByte = f.info.Size() - offset
}
_, r, cancelFn, err := f.Fs.Open(f.GetFsPath(), startByte)
f.Lock()
if err == nil {
f.startOffset = startByte
f.reader = r
}
f.ErrTransfer = err
f.BaseTransfer.SetCancelFn(cancelFn)
f.Unlock()
return startByte, err
}
return 0, common.ErrOpUnsupported
}
// Close closes the open directory or the current transfer
func (f *webDavFile) Close() error {
if err := f.setFinished(); err != nil {
return err
}
err := f.closeIO()
if f.isTransfer() {
errBaseClose := f.BaseTransfer.Close()
if errBaseClose != nil {
err = errBaseClose
}
} else {
f.Connection.RemoveTransfer(f.BaseTransfer)
}
return f.Connection.GetFsError(f.Fs, err)
}
func (f *webDavFile) closeIO() error {
var err error
if f.File != nil {
err = f.File.Close()
} else if f.writer != nil {
err = f.writer.Close()
f.Lock()
// we set ErrTransfer here so quota is not updated, in this case the uploads are atomic
if err != nil && f.ErrTransfer == nil {
f.ErrTransfer = err
}
f.Unlock()
} else if f.reader != nil {
err = f.reader.Close()
}
return err
}
func (f *webDavFile) setFinished() error {
f.Lock()
defer f.Unlock()
if f.isFinished {
return common.ErrTransferClosed
}
f.isFinished = true
return nil
}
func (f *webDavFile) isTransfer() bool {
if f.GetType() == common.TransferDownload {
return f.readTryed.Load()
}
return true
}
// DeadProps returns a copy of the dead properties held.
// We always return nil for now, we only support the last modification time
// and it is already included in "live" properties
func (f *webDavFile) DeadProps() (map[xml.Name]webdav.Property, error) {
return nil, nil
}
// Patch patches the dead properties held.
// In our minimal implementation we just support Win32LastModifiedTime and
// getlastmodified to set the the modification time.
// We ignore any other property and just return an OK response if the patch sets
// the modification time, otherwise a Forbidden response
func (f *webDavFile) Patch(patches []webdav.Proppatch) ([]webdav.Propstat, error) {
resp := make([]webdav.Propstat, 0, len(patches))
hasError := false
for _, patch := range patches {
status := http.StatusForbidden
pstat := webdav.Propstat{}
for _, p := range patch.Props {
if status == http.StatusForbidden && !hasError {
if !patch.Remove && util.Contains(lastModifiedProps, p.XMLName.Local) {
parsed, err := http.ParseTime(string(p.InnerXML))
if err != nil {
f.Connection.Log(logger.LevelWarn, "unsupported last modification time: %q, err: %v",
string(p.InnerXML), err)
hasError = true
continue
}
attrs := &common.StatAttributes{
Flags: common.StatAttrTimes,
Atime: parsed,
Mtime: parsed,
}
if err := f.Connection.SetStat(f.GetVirtualPath(), attrs); err != nil {
f.Connection.Log(logger.LevelWarn, "unable to set modification time for %q, err :%v",
f.GetVirtualPath(), err)
hasError = true
continue
}
status = http.StatusOK
}
}
pstat.Props = append(pstat.Props, webdav.Property{XMLName: p.XMLName})
}
pstat.Status = status
resp = append(resp, pstat)
}
return resp, nil
}