file.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package webdavd
  15. import (
  16. "context"
  17. "encoding/xml"
  18. "errors"
  19. "io"
  20. "mime"
  21. "net/http"
  22. "os"
  23. "path"
  24. "sync/atomic"
  25. "time"
  26. "github.com/drakkan/webdav"
  27. "github.com/eikenb/pipeat"
  28. "github.com/drakkan/sftpgo/v2/internal/common"
  29. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  30. "github.com/drakkan/sftpgo/v2/internal/logger"
  31. "github.com/drakkan/sftpgo/v2/internal/util"
  32. "github.com/drakkan/sftpgo/v2/internal/vfs"
  33. )
  34. var (
  35. errTransferAborted = errors.New("transfer aborted")
  36. lastModifiedProps = []string{"Win32LastModifiedTime", "getlastmodified"}
  37. )
  38. type webDavFile struct {
  39. *common.BaseTransfer
  40. writer io.WriteCloser
  41. reader io.ReadCloser
  42. info os.FileInfo
  43. startOffset int64
  44. isFinished bool
  45. readTried atomic.Bool
  46. }
  47. func newWebDavFile(baseTransfer *common.BaseTransfer, pipeWriter vfs.PipeWriter, pipeReader *pipeat.PipeReaderAt) *webDavFile {
  48. var writer io.WriteCloser
  49. var reader io.ReadCloser
  50. if baseTransfer.File != nil {
  51. writer = baseTransfer.File
  52. reader = baseTransfer.File
  53. } else if pipeWriter != nil {
  54. writer = pipeWriter
  55. } else if pipeReader != nil {
  56. reader = pipeReader
  57. }
  58. f := &webDavFile{
  59. BaseTransfer: baseTransfer,
  60. writer: writer,
  61. reader: reader,
  62. isFinished: false,
  63. startOffset: 0,
  64. info: nil,
  65. }
  66. f.readTried.Store(false)
  67. return f
  68. }
  69. type webDavFileInfo struct {
  70. os.FileInfo
  71. Fs vfs.Fs
  72. virtualPath string
  73. fsPath string
  74. }
  75. // ContentType implements webdav.ContentTyper interface
  76. func (fi *webDavFileInfo) ContentType(_ context.Context) (string, error) {
  77. extension := path.Ext(fi.virtualPath)
  78. if ctype, ok := customMimeTypeMapping[extension]; ok {
  79. return ctype, nil
  80. }
  81. if extension == "" || extension == ".dat" {
  82. return "application/octet-stream", nil
  83. }
  84. contentType := mime.TypeByExtension(extension)
  85. if contentType != "" {
  86. return contentType, nil
  87. }
  88. contentType = mimeTypeCache.getMimeFromCache(extension)
  89. if contentType != "" {
  90. return contentType, nil
  91. }
  92. contentType, err := fi.Fs.GetMimeType(fi.fsPath)
  93. if contentType != "" {
  94. mimeTypeCache.addMimeToCache(extension, contentType)
  95. return contentType, err
  96. }
  97. return "", webdav.ErrNotImplemented
  98. }
  99. // Readdir reads directory entries from the handle
  100. func (f *webDavFile) Readdir(_ int) ([]os.FileInfo, error) {
  101. return nil, webdav.ErrNotImplemented
  102. }
  103. // ReadDir implements the FileDirLister interface
  104. func (f *webDavFile) ReadDir() (webdav.DirLister, error) {
  105. if !f.Connection.User.HasPerm(dataprovider.PermListItems, f.GetVirtualPath()) {
  106. return nil, f.Connection.GetPermissionDeniedError()
  107. }
  108. lister, err := f.Connection.ListDir(f.GetVirtualPath())
  109. if err != nil {
  110. return nil, err
  111. }
  112. return &webDavDirLister{
  113. DirLister: lister,
  114. fs: f.Fs,
  115. virtualDirPath: f.GetVirtualPath(),
  116. fsDirPath: f.GetFsPath(),
  117. }, nil
  118. }
  119. // Stat the handle
  120. func (f *webDavFile) Stat() (os.FileInfo, error) {
  121. if f.GetType() == common.TransferDownload && !f.Connection.User.HasPerm(dataprovider.PermListItems, path.Dir(f.GetVirtualPath())) {
  122. return nil, f.Connection.GetPermissionDeniedError()
  123. }
  124. f.Lock()
  125. errUpload := f.ErrTransfer
  126. f.Unlock()
  127. if f.GetType() == common.TransferUpload && errUpload == nil {
  128. info := &webDavFileInfo{
  129. FileInfo: vfs.NewFileInfo(f.GetFsPath(), false, f.BytesReceived.Load(), time.Now(), false),
  130. Fs: f.Fs,
  131. virtualPath: f.GetVirtualPath(),
  132. fsPath: f.GetFsPath(),
  133. }
  134. return info, nil
  135. }
  136. info, err := f.Fs.Stat(f.GetFsPath())
  137. if err != nil {
  138. return nil, f.Connection.GetFsError(f.Fs, err)
  139. }
  140. if vfs.IsCryptOsFs(f.Fs) {
  141. info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
  142. }
  143. fi := &webDavFileInfo{
  144. FileInfo: info,
  145. Fs: f.Fs,
  146. virtualPath: f.GetVirtualPath(),
  147. fsPath: f.GetFsPath(),
  148. }
  149. return fi, nil
  150. }
  151. func (f *webDavFile) checkFirstRead() error {
  152. if !f.Connection.User.HasPerm(dataprovider.PermDownload, path.Dir(f.GetVirtualPath())) {
  153. return f.Connection.GetPermissionDeniedError()
  154. }
  155. transferQuota := f.BaseTransfer.GetTransferQuota()
  156. if !transferQuota.HasDownloadSpace() {
  157. f.Connection.Log(logger.LevelInfo, "denying file read due to quota limits")
  158. return f.Connection.GetReadQuotaExceededError()
  159. }
  160. if ok, policy := f.Connection.User.IsFileAllowed(f.GetVirtualPath()); !ok {
  161. f.Connection.Log(logger.LevelWarn, "reading file %q is not allowed", f.GetVirtualPath())
  162. return f.Connection.GetErrorForDeniedFile(policy)
  163. }
  164. _, err := common.ExecutePreAction(f.Connection, common.OperationPreDownload, f.GetFsPath(), f.GetVirtualPath(), 0, 0)
  165. if err != nil {
  166. f.Connection.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", f.GetVirtualPath(), err)
  167. return f.Connection.GetPermissionDeniedError()
  168. }
  169. f.readTried.Store(true)
  170. return nil
  171. }
  172. // Read reads the contents to downloads.
  173. func (f *webDavFile) Read(p []byte) (n int, err error) {
  174. if f.AbortTransfer.Load() {
  175. return 0, errTransferAborted
  176. }
  177. if !f.readTried.Load() {
  178. if err := f.checkFirstRead(); err != nil {
  179. return 0, err
  180. }
  181. }
  182. f.Connection.UpdateLastActivity()
  183. // the file is read sequentially we don't need to check for concurrent reads and so
  184. // lock the transfer while opening the remote file
  185. if f.reader == nil {
  186. if f.GetType() != common.TransferDownload {
  187. f.TransferError(common.ErrOpUnsupported)
  188. return 0, common.ErrOpUnsupported
  189. }
  190. file, r, cancelFn, e := f.Fs.Open(f.GetFsPath(), 0)
  191. f.Lock()
  192. if e == nil {
  193. if file != nil {
  194. f.File = file
  195. f.writer = f.File
  196. f.reader = f.File
  197. } else if r != nil {
  198. f.reader = r
  199. }
  200. f.BaseTransfer.SetCancelFn(cancelFn)
  201. }
  202. f.ErrTransfer = e
  203. f.startOffset = 0
  204. f.Unlock()
  205. if e != nil {
  206. return 0, f.Connection.GetFsError(f.Fs, e)
  207. }
  208. }
  209. n, err = f.reader.Read(p)
  210. f.BytesSent.Add(int64(n))
  211. if err == nil {
  212. err = f.CheckRead()
  213. }
  214. if err != nil && err != io.EOF {
  215. f.TransferError(err)
  216. err = f.ConvertError(err)
  217. return
  218. }
  219. f.HandleThrottle()
  220. return
  221. }
  222. // Write writes the uploaded contents.
  223. func (f *webDavFile) Write(p []byte) (n int, err error) {
  224. if f.AbortTransfer.Load() {
  225. return 0, errTransferAborted
  226. }
  227. f.Connection.UpdateLastActivity()
  228. n, err = f.writer.Write(p)
  229. f.BytesReceived.Add(int64(n))
  230. if err == nil {
  231. err = f.CheckWrite()
  232. }
  233. if err != nil {
  234. f.TransferError(err)
  235. err = f.ConvertError(err)
  236. return
  237. }
  238. f.HandleThrottle()
  239. return
  240. }
  241. func (f *webDavFile) updateStatInfo() error {
  242. if f.info != nil {
  243. return nil
  244. }
  245. info, err := f.Fs.Stat(f.GetFsPath())
  246. if err != nil {
  247. return err
  248. }
  249. if vfs.IsCryptOsFs(f.Fs) {
  250. info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
  251. }
  252. f.info = info
  253. return nil
  254. }
  255. func (f *webDavFile) updateTransferQuotaOnSeek() {
  256. transferQuota := f.GetTransferQuota()
  257. if transferQuota.HasSizeLimits() {
  258. go func(ulSize, dlSize int64, user dataprovider.User) {
  259. dataprovider.UpdateUserTransferQuota(&user, ulSize, dlSize, false) //nolint:errcheck
  260. }(f.BytesReceived.Load(), f.BytesSent.Load(), f.Connection.User)
  261. }
  262. }
  263. func (f *webDavFile) checkFile() error {
  264. if f.File == nil && vfs.FsOpenReturnsFile(f.Fs) {
  265. file, _, _, err := f.Fs.Open(f.GetFsPath(), 0)
  266. if err != nil {
  267. f.Connection.Log(logger.LevelWarn, "could not open file %q for seeking: %v",
  268. f.GetFsPath(), err)
  269. f.TransferError(err)
  270. return err
  271. }
  272. f.File = file
  273. f.reader = file
  274. f.writer = file
  275. }
  276. return nil
  277. }
  278. func (f *webDavFile) seekFile(offset int64, whence int) (int64, error) {
  279. ret, err := f.File.Seek(offset, whence)
  280. if err != nil {
  281. f.TransferError(err)
  282. }
  283. return ret, err
  284. }
  285. // Seek sets the offset for the next Read or Write on the writer to offset,
  286. // interpreted according to whence: 0 means relative to the origin of the file,
  287. // 1 means relative to the current offset, and 2 means relative to the end.
  288. // It returns the new offset and an error, if any.
  289. func (f *webDavFile) Seek(offset int64, whence int) (int64, error) {
  290. f.Connection.UpdateLastActivity()
  291. if err := f.checkFile(); err != nil {
  292. return 0, err
  293. }
  294. if f.File != nil {
  295. return f.seekFile(offset, whence)
  296. }
  297. if f.GetType() == common.TransferDownload {
  298. readOffset := f.startOffset + f.BytesSent.Load()
  299. if offset == 0 && readOffset == 0 {
  300. if whence == io.SeekStart {
  301. return 0, nil
  302. } else if whence == io.SeekEnd {
  303. if err := f.updateStatInfo(); err != nil {
  304. return 0, err
  305. }
  306. return f.info.Size(), nil
  307. }
  308. }
  309. // close the reader and create a new one at startByte
  310. if f.reader != nil {
  311. f.reader.Close() //nolint:errcheck
  312. f.reader = nil
  313. }
  314. startByte := int64(0)
  315. f.BytesReceived.Store(0)
  316. f.BytesSent.Store(0)
  317. f.updateTransferQuotaOnSeek()
  318. switch whence {
  319. case io.SeekStart:
  320. startByte = offset
  321. case io.SeekCurrent:
  322. startByte = readOffset + offset
  323. case io.SeekEnd:
  324. if err := f.updateStatInfo(); err != nil {
  325. f.TransferError(err)
  326. return 0, err
  327. }
  328. startByte = f.info.Size() - offset
  329. }
  330. _, r, cancelFn, err := f.Fs.Open(f.GetFsPath(), startByte)
  331. f.Lock()
  332. if err == nil {
  333. f.startOffset = startByte
  334. f.reader = r
  335. }
  336. f.ErrTransfer = err
  337. f.BaseTransfer.SetCancelFn(cancelFn)
  338. f.Unlock()
  339. return startByte, err
  340. }
  341. return 0, common.ErrOpUnsupported
  342. }
  343. // Close closes the open directory or the current transfer
  344. func (f *webDavFile) Close() error {
  345. if err := f.setFinished(); err != nil {
  346. return err
  347. }
  348. err := f.closeIO()
  349. if f.isTransfer() {
  350. errBaseClose := f.BaseTransfer.Close()
  351. if errBaseClose != nil {
  352. err = errBaseClose
  353. }
  354. } else {
  355. f.Connection.RemoveTransfer(f.BaseTransfer)
  356. }
  357. return f.Connection.GetFsError(f.Fs, err)
  358. }
  359. func (f *webDavFile) closeIO() error {
  360. var err error
  361. if f.File != nil {
  362. err = f.File.Close()
  363. } else if f.writer != nil {
  364. err = f.writer.Close()
  365. f.Lock()
  366. // we set ErrTransfer here so quota is not updated, in this case the uploads are atomic
  367. if err != nil && f.ErrTransfer == nil {
  368. f.ErrTransfer = err
  369. }
  370. f.Unlock()
  371. } else if f.reader != nil {
  372. err = f.reader.Close()
  373. if metadater, ok := f.reader.(vfs.Metadater); ok {
  374. f.BaseTransfer.SetMetadata(metadater.Metadata())
  375. }
  376. }
  377. return err
  378. }
  379. func (f *webDavFile) setFinished() error {
  380. f.Lock()
  381. defer f.Unlock()
  382. if f.isFinished {
  383. return common.ErrTransferClosed
  384. }
  385. f.isFinished = true
  386. return nil
  387. }
  388. func (f *webDavFile) isTransfer() bool {
  389. if f.GetType() == common.TransferDownload {
  390. return f.readTried.Load()
  391. }
  392. return true
  393. }
  394. // DeadProps returns a copy of the dead properties held.
  395. // We always return nil for now, we only support the last modification time
  396. // and it is already included in "live" properties
  397. func (f *webDavFile) DeadProps() (map[xml.Name]webdav.Property, error) {
  398. return nil, nil
  399. }
  400. // Patch patches the dead properties held.
  401. // In our minimal implementation we just support Win32LastModifiedTime and
  402. // getlastmodified to set the the modification time.
  403. // We ignore any other property and just return an OK response if the patch sets
  404. // the modification time, otherwise a Forbidden response
  405. func (f *webDavFile) Patch(patches []webdav.Proppatch) ([]webdav.Propstat, error) {
  406. resp := make([]webdav.Propstat, 0, len(patches))
  407. hasError := false
  408. for _, patch := range patches {
  409. status := http.StatusForbidden
  410. pstat := webdav.Propstat{}
  411. for _, p := range patch.Props {
  412. if status == http.StatusForbidden && !hasError {
  413. if !patch.Remove && util.Contains(lastModifiedProps, p.XMLName.Local) {
  414. parsed, err := parseTime(util.BytesToString(p.InnerXML))
  415. if err != nil {
  416. f.Connection.Log(logger.LevelWarn, "unsupported last modification time: %q, err: %v",
  417. util.BytesToString(p.InnerXML), err)
  418. hasError = true
  419. continue
  420. }
  421. attrs := &common.StatAttributes{
  422. Flags: common.StatAttrTimes,
  423. Atime: parsed,
  424. Mtime: parsed,
  425. }
  426. if err := f.Connection.SetStat(f.GetVirtualPath(), attrs); err != nil {
  427. f.Connection.Log(logger.LevelWarn, "unable to set modification time for %q, err :%v",
  428. f.GetVirtualPath(), err)
  429. hasError = true
  430. continue
  431. }
  432. status = http.StatusOK
  433. }
  434. }
  435. pstat.Props = append(pstat.Props, webdav.Property{XMLName: p.XMLName})
  436. }
  437. pstat.Status = status
  438. resp = append(resp, pstat)
  439. }
  440. return resp, nil
  441. }
  442. type webDavDirLister struct {
  443. vfs.DirLister
  444. fs vfs.Fs
  445. virtualDirPath string
  446. fsDirPath string
  447. }
  448. func (l *webDavDirLister) Next(limit int) ([]os.FileInfo, error) {
  449. files, err := l.DirLister.Next(limit)
  450. for idx := range files {
  451. info := files[idx]
  452. files[idx] = &webDavFileInfo{
  453. FileInfo: info,
  454. Fs: l.fs,
  455. virtualPath: path.Join(l.virtualDirPath, info.Name()),
  456. fsPath: l.fs.Join(l.fsDirPath, info.Name()),
  457. }
  458. }
  459. return files, err
  460. }