file.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // Copyright (C) 2019-2023 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. if !f.Connection.User.HasPerm(dataprovider.PermListItems, f.GetVirtualPath()) {
  102. return nil, f.Connection.GetPermissionDeniedError()
  103. }
  104. entries, err := f.Connection.ListDir(f.GetVirtualPath())
  105. if err != nil {
  106. return nil, err
  107. }
  108. for idx, info := range entries {
  109. entries[idx] = &webDavFileInfo{
  110. FileInfo: info,
  111. Fs: f.Fs,
  112. virtualPath: path.Join(f.GetVirtualPath(), info.Name()),
  113. fsPath: f.Fs.Join(f.GetFsPath(), info.Name()),
  114. }
  115. }
  116. return entries, nil
  117. }
  118. // Stat the handle
  119. func (f *webDavFile) Stat() (os.FileInfo, error) {
  120. if f.GetType() == common.TransferDownload && !f.Connection.User.HasPerm(dataprovider.PermListItems, path.Dir(f.GetVirtualPath())) {
  121. return nil, f.Connection.GetPermissionDeniedError()
  122. }
  123. f.Lock()
  124. errUpload := f.ErrTransfer
  125. f.Unlock()
  126. if f.GetType() == common.TransferUpload && errUpload == nil {
  127. info := &webDavFileInfo{
  128. FileInfo: vfs.NewFileInfo(f.GetFsPath(), false, f.BytesReceived.Load(), time.Now(), false),
  129. Fs: f.Fs,
  130. virtualPath: f.GetVirtualPath(),
  131. fsPath: f.GetFsPath(),
  132. }
  133. return info, nil
  134. }
  135. info, err := f.Fs.Stat(f.GetFsPath())
  136. if err != nil {
  137. return nil, f.Connection.GetFsError(f.Fs, err)
  138. }
  139. if vfs.IsCryptOsFs(f.Fs) {
  140. info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
  141. }
  142. fi := &webDavFileInfo{
  143. FileInfo: info,
  144. Fs: f.Fs,
  145. virtualPath: f.GetVirtualPath(),
  146. fsPath: f.GetFsPath(),
  147. }
  148. return fi, nil
  149. }
  150. func (f *webDavFile) checkFirstRead() error {
  151. if !f.Connection.User.HasPerm(dataprovider.PermDownload, path.Dir(f.GetVirtualPath())) {
  152. return f.Connection.GetPermissionDeniedError()
  153. }
  154. transferQuota := f.BaseTransfer.GetTransferQuota()
  155. if !transferQuota.HasDownloadSpace() {
  156. f.Connection.Log(logger.LevelInfo, "denying file read due to quota limits")
  157. return f.Connection.GetReadQuotaExceededError()
  158. }
  159. if ok, policy := f.Connection.User.IsFileAllowed(f.GetVirtualPath()); !ok {
  160. f.Connection.Log(logger.LevelWarn, "reading file %q is not allowed", f.GetVirtualPath())
  161. return f.Connection.GetErrorForDeniedFile(policy)
  162. }
  163. _, err := common.ExecutePreAction(f.Connection, common.OperationPreDownload, f.GetFsPath(), f.GetVirtualPath(), 0, 0)
  164. if err != nil {
  165. f.Connection.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", f.GetVirtualPath(), err)
  166. return f.Connection.GetPermissionDeniedError()
  167. }
  168. f.readTried.Store(true)
  169. return nil
  170. }
  171. // Read reads the contents to downloads.
  172. func (f *webDavFile) Read(p []byte) (n int, err error) {
  173. if f.AbortTransfer.Load() {
  174. return 0, errTransferAborted
  175. }
  176. if !f.readTried.Load() {
  177. if err := f.checkFirstRead(); err != nil {
  178. return 0, err
  179. }
  180. }
  181. f.Connection.UpdateLastActivity()
  182. // the file is read sequentially we don't need to check for concurrent reads and so
  183. // lock the transfer while opening the remote file
  184. if f.reader == nil {
  185. if f.GetType() != common.TransferDownload {
  186. f.TransferError(common.ErrOpUnsupported)
  187. return 0, common.ErrOpUnsupported
  188. }
  189. file, r, cancelFn, e := f.Fs.Open(f.GetFsPath(), 0)
  190. f.Lock()
  191. if e == nil {
  192. if file != nil {
  193. f.File = file
  194. f.writer = f.File
  195. f.reader = f.File
  196. } else if r != nil {
  197. f.reader = r
  198. }
  199. f.BaseTransfer.SetCancelFn(cancelFn)
  200. }
  201. f.ErrTransfer = e
  202. f.startOffset = 0
  203. f.Unlock()
  204. if e != nil {
  205. return 0, f.Connection.GetFsError(f.Fs, e)
  206. }
  207. }
  208. n, err = f.reader.Read(p)
  209. f.BytesSent.Add(int64(n))
  210. if err == nil {
  211. err = f.CheckRead()
  212. }
  213. if err != nil && err != io.EOF {
  214. f.TransferError(err)
  215. err = f.ConvertError(err)
  216. return
  217. }
  218. f.HandleThrottle()
  219. return
  220. }
  221. // Write writes the uploaded contents.
  222. func (f *webDavFile) Write(p []byte) (n int, err error) {
  223. if f.AbortTransfer.Load() {
  224. return 0, errTransferAborted
  225. }
  226. f.Connection.UpdateLastActivity()
  227. n, err = f.writer.Write(p)
  228. f.BytesReceived.Add(int64(n))
  229. if err == nil {
  230. err = f.CheckWrite()
  231. }
  232. if err != nil {
  233. f.TransferError(err)
  234. err = f.ConvertError(err)
  235. return
  236. }
  237. f.HandleThrottle()
  238. return
  239. }
  240. func (f *webDavFile) updateStatInfo() error {
  241. if f.info != nil {
  242. return nil
  243. }
  244. info, err := f.Fs.Stat(f.GetFsPath())
  245. if err != nil {
  246. return err
  247. }
  248. if vfs.IsCryptOsFs(f.Fs) {
  249. info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
  250. }
  251. f.info = info
  252. return nil
  253. }
  254. func (f *webDavFile) updateTransferQuotaOnSeek() {
  255. transferQuota := f.GetTransferQuota()
  256. if transferQuota.HasSizeLimits() {
  257. go func(ulSize, dlSize int64, user dataprovider.User) {
  258. dataprovider.UpdateUserTransferQuota(&user, ulSize, dlSize, false) //nolint:errcheck
  259. }(f.BytesReceived.Load(), f.BytesSent.Load(), f.Connection.User)
  260. }
  261. }
  262. func (f *webDavFile) checkFile() error {
  263. if f.File == nil && vfs.FsOpenReturnsFile(f.Fs) {
  264. file, _, _, err := f.Fs.Open(f.GetFsPath(), 0)
  265. if err != nil {
  266. f.Connection.Log(logger.LevelWarn, "could not open file %q for seeking: %v",
  267. f.GetFsPath(), err)
  268. f.TransferError(err)
  269. return err
  270. }
  271. f.File = file
  272. f.reader = file
  273. f.writer = file
  274. }
  275. return nil
  276. }
  277. func (f *webDavFile) seekFile(offset int64, whence int) (int64, error) {
  278. ret, err := f.File.Seek(offset, whence)
  279. if err != nil {
  280. f.TransferError(err)
  281. }
  282. return ret, err
  283. }
  284. // Seek sets the offset for the next Read or Write on the writer to offset,
  285. // interpreted according to whence: 0 means relative to the origin of the file,
  286. // 1 means relative to the current offset, and 2 means relative to the end.
  287. // It returns the new offset and an error, if any.
  288. func (f *webDavFile) Seek(offset int64, whence int) (int64, error) {
  289. f.Connection.UpdateLastActivity()
  290. if err := f.checkFile(); err != nil {
  291. return 0, err
  292. }
  293. if f.File != nil {
  294. return f.seekFile(offset, whence)
  295. }
  296. if f.GetType() == common.TransferDownload {
  297. readOffset := f.startOffset + f.BytesSent.Load()
  298. if offset == 0 && readOffset == 0 {
  299. if whence == io.SeekStart {
  300. return 0, nil
  301. } else if whence == io.SeekEnd {
  302. if err := f.updateStatInfo(); err != nil {
  303. return 0, err
  304. }
  305. return f.info.Size(), nil
  306. }
  307. }
  308. // close the reader and create a new one at startByte
  309. if f.reader != nil {
  310. f.reader.Close() //nolint:errcheck
  311. f.reader = nil
  312. }
  313. startByte := int64(0)
  314. f.BytesReceived.Store(0)
  315. f.BytesSent.Store(0)
  316. f.updateTransferQuotaOnSeek()
  317. switch whence {
  318. case io.SeekStart:
  319. startByte = offset
  320. case io.SeekCurrent:
  321. startByte = readOffset + offset
  322. case io.SeekEnd:
  323. if err := f.updateStatInfo(); err != nil {
  324. f.TransferError(err)
  325. return 0, err
  326. }
  327. startByte = f.info.Size() - offset
  328. }
  329. _, r, cancelFn, err := f.Fs.Open(f.GetFsPath(), startByte)
  330. f.Lock()
  331. if err == nil {
  332. f.startOffset = startByte
  333. f.reader = r
  334. }
  335. f.ErrTransfer = err
  336. f.BaseTransfer.SetCancelFn(cancelFn)
  337. f.Unlock()
  338. return startByte, err
  339. }
  340. return 0, common.ErrOpUnsupported
  341. }
  342. // Close closes the open directory or the current transfer
  343. func (f *webDavFile) Close() error {
  344. if err := f.setFinished(); err != nil {
  345. return err
  346. }
  347. err := f.closeIO()
  348. if f.isTransfer() {
  349. errBaseClose := f.BaseTransfer.Close()
  350. if errBaseClose != nil {
  351. err = errBaseClose
  352. }
  353. } else {
  354. f.Connection.RemoveTransfer(f.BaseTransfer)
  355. }
  356. return f.Connection.GetFsError(f.Fs, err)
  357. }
  358. func (f *webDavFile) closeIO() error {
  359. var err error
  360. if f.File != nil {
  361. err = f.File.Close()
  362. } else if f.writer != nil {
  363. err = f.writer.Close()
  364. f.Lock()
  365. // we set ErrTransfer here so quota is not updated, in this case the uploads are atomic
  366. if err != nil && f.ErrTransfer == nil {
  367. f.ErrTransfer = err
  368. }
  369. f.Unlock()
  370. } else if f.reader != nil {
  371. err = f.reader.Close()
  372. }
  373. return err
  374. }
  375. func (f *webDavFile) setFinished() error {
  376. f.Lock()
  377. defer f.Unlock()
  378. if f.isFinished {
  379. return common.ErrTransferClosed
  380. }
  381. f.isFinished = true
  382. return nil
  383. }
  384. func (f *webDavFile) isTransfer() bool {
  385. if f.GetType() == common.TransferDownload {
  386. return f.readTried.Load()
  387. }
  388. return true
  389. }
  390. // DeadProps returns a copy of the dead properties held.
  391. // We always return nil for now, we only support the last modification time
  392. // and it is already included in "live" properties
  393. func (f *webDavFile) DeadProps() (map[xml.Name]webdav.Property, error) {
  394. return nil, nil
  395. }
  396. // Patch patches the dead properties held.
  397. // In our minimal implementation we just support Win32LastModifiedTime and
  398. // getlastmodified to set the the modification time.
  399. // We ignore any other property and just return an OK response if the patch sets
  400. // the modification time, otherwise a Forbidden response
  401. func (f *webDavFile) Patch(patches []webdav.Proppatch) ([]webdav.Propstat, error) {
  402. resp := make([]webdav.Propstat, 0, len(patches))
  403. hasError := false
  404. for _, patch := range patches {
  405. status := http.StatusForbidden
  406. pstat := webdav.Propstat{}
  407. for _, p := range patch.Props {
  408. if status == http.StatusForbidden && !hasError {
  409. if !patch.Remove && util.Contains(lastModifiedProps, p.XMLName.Local) {
  410. parsed, err := parseTime(string(p.InnerXML))
  411. if err != nil {
  412. f.Connection.Log(logger.LevelWarn, "unsupported last modification time: %q, err: %v",
  413. string(p.InnerXML), err)
  414. hasError = true
  415. continue
  416. }
  417. attrs := &common.StatAttributes{
  418. Flags: common.StatAttrTimes,
  419. Atime: parsed,
  420. Mtime: parsed,
  421. }
  422. if err := f.Connection.SetStat(f.GetVirtualPath(), attrs); err != nil {
  423. f.Connection.Log(logger.LevelWarn, "unable to set modification time for %q, err :%v",
  424. f.GetVirtualPath(), err)
  425. hasError = true
  426. continue
  427. }
  428. status = http.StatusOK
  429. }
  430. }
  431. pstat.Props = append(pstat.Props, webdav.Property{XMLName: p.XMLName})
  432. }
  433. pstat.Status = status
  434. resp = append(resp, pstat)
  435. }
  436. return resp, nil
  437. }