file.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. readTryed 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.readTryed.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, 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.readTryed.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.readTryed.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, 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. return
  216. }
  217. f.HandleThrottle()
  218. return
  219. }
  220. // Write writes the uploaded contents.
  221. func (f *webDavFile) Write(p []byte) (n int, err error) {
  222. if f.AbortTransfer.Load() {
  223. return 0, errTransferAborted
  224. }
  225. f.Connection.UpdateLastActivity()
  226. n, err = f.writer.Write(p)
  227. f.BytesReceived.Add(int64(n))
  228. if err == nil {
  229. err = f.CheckWrite()
  230. }
  231. if err != nil {
  232. f.TransferError(err)
  233. return
  234. }
  235. f.HandleThrottle()
  236. return
  237. }
  238. func (f *webDavFile) updateStatInfo() error {
  239. if f.info != nil {
  240. return nil
  241. }
  242. info, err := f.Fs.Stat(f.GetFsPath())
  243. if err != nil {
  244. return err
  245. }
  246. if vfs.IsCryptOsFs(f.Fs) {
  247. info = f.Fs.(*vfs.CryptFs).ConvertFileInfo(info)
  248. }
  249. f.info = info
  250. return nil
  251. }
  252. func (f *webDavFile) updateTransferQuotaOnSeek() {
  253. transferQuota := f.GetTransferQuota()
  254. if transferQuota.HasSizeLimits() {
  255. go func(ulSize, dlSize int64, user dataprovider.User) {
  256. dataprovider.UpdateUserTransferQuota(&user, ulSize, dlSize, false) //nolint:errcheck
  257. }(f.BytesReceived.Load(), f.BytesSent.Load(), f.Connection.User)
  258. }
  259. }
  260. func (f *webDavFile) checkFile() error {
  261. if f.File == nil && vfs.IsLocalOrUnbufferedSFTPFs(f.Fs) {
  262. file, _, _, err := f.Fs.Open(f.GetFsPath(), 0)
  263. if err != nil {
  264. f.Connection.Log(logger.LevelWarn, "could not open file %q for seeking: %v",
  265. f.GetFsPath(), err)
  266. f.TransferError(err)
  267. return err
  268. }
  269. f.File = file
  270. f.reader = file
  271. f.writer = file
  272. }
  273. return nil
  274. }
  275. func (f *webDavFile) seekFile(offset int64, whence int) (int64, error) {
  276. ret, err := f.File.Seek(offset, whence)
  277. if err != nil {
  278. f.TransferError(err)
  279. }
  280. return ret, err
  281. }
  282. // Seek sets the offset for the next Read or Write on the writer to offset,
  283. // interpreted according to whence: 0 means relative to the origin of the file,
  284. // 1 means relative to the current offset, and 2 means relative to the end.
  285. // It returns the new offset and an error, if any.
  286. func (f *webDavFile) Seek(offset int64, whence int) (int64, error) {
  287. f.Connection.UpdateLastActivity()
  288. if err := f.checkFile(); err != nil {
  289. return 0, err
  290. }
  291. if f.File != nil {
  292. return f.seekFile(offset, whence)
  293. }
  294. if f.GetType() == common.TransferDownload {
  295. readOffset := f.startOffset + f.BytesSent.Load()
  296. if offset == 0 && readOffset == 0 {
  297. if whence == io.SeekStart {
  298. return 0, nil
  299. } else if whence == io.SeekEnd {
  300. if err := f.updateStatInfo(); err != nil {
  301. return 0, err
  302. }
  303. return f.info.Size(), nil
  304. }
  305. }
  306. // close the reader and create a new one at startByte
  307. if f.reader != nil {
  308. f.reader.Close() //nolint:errcheck
  309. f.reader = nil
  310. }
  311. startByte := int64(0)
  312. f.BytesReceived.Store(0)
  313. f.BytesSent.Store(0)
  314. f.updateTransferQuotaOnSeek()
  315. switch whence {
  316. case io.SeekStart:
  317. startByte = offset
  318. case io.SeekCurrent:
  319. startByte = readOffset + offset
  320. case io.SeekEnd:
  321. if err := f.updateStatInfo(); err != nil {
  322. f.TransferError(err)
  323. return 0, err
  324. }
  325. startByte = f.info.Size() - offset
  326. }
  327. _, r, cancelFn, err := f.Fs.Open(f.GetFsPath(), startByte)
  328. f.Lock()
  329. if err == nil {
  330. f.startOffset = startByte
  331. f.reader = r
  332. }
  333. f.ErrTransfer = err
  334. f.BaseTransfer.SetCancelFn(cancelFn)
  335. f.Unlock()
  336. return startByte, err
  337. }
  338. return 0, common.ErrOpUnsupported
  339. }
  340. // Close closes the open directory or the current transfer
  341. func (f *webDavFile) Close() error {
  342. if err := f.setFinished(); err != nil {
  343. return err
  344. }
  345. err := f.closeIO()
  346. if f.isTransfer() {
  347. errBaseClose := f.BaseTransfer.Close()
  348. if errBaseClose != nil {
  349. err = errBaseClose
  350. }
  351. } else {
  352. f.Connection.RemoveTransfer(f.BaseTransfer)
  353. }
  354. return f.Connection.GetFsError(f.Fs, err)
  355. }
  356. func (f *webDavFile) closeIO() error {
  357. var err error
  358. if f.File != nil {
  359. err = f.File.Close()
  360. } else if f.writer != nil {
  361. err = f.writer.Close()
  362. f.Lock()
  363. // we set ErrTransfer here so quota is not updated, in this case the uploads are atomic
  364. if err != nil && f.ErrTransfer == nil {
  365. f.ErrTransfer = err
  366. }
  367. f.Unlock()
  368. } else if f.reader != nil {
  369. err = f.reader.Close()
  370. }
  371. return err
  372. }
  373. func (f *webDavFile) setFinished() error {
  374. f.Lock()
  375. defer f.Unlock()
  376. if f.isFinished {
  377. return common.ErrTransferClosed
  378. }
  379. f.isFinished = true
  380. return nil
  381. }
  382. func (f *webDavFile) isTransfer() bool {
  383. if f.GetType() == common.TransferDownload {
  384. return f.readTryed.Load()
  385. }
  386. return true
  387. }
  388. // DeadProps returns a copy of the dead properties held.
  389. // We always return nil for now, we only support the last modification time
  390. // and it is already included in "live" properties
  391. func (f *webDavFile) DeadProps() (map[xml.Name]webdav.Property, error) {
  392. return nil, nil
  393. }
  394. // Patch patches the dead properties held.
  395. // In our minimal implementation we just support Win32LastModifiedTime and
  396. // getlastmodified to set the the modification time.
  397. // We ignore any other property and just return an OK response if the patch sets
  398. // the modification time, otherwise a Forbidden response
  399. func (f *webDavFile) Patch(patches []webdav.Proppatch) ([]webdav.Propstat, error) {
  400. resp := make([]webdav.Propstat, 0, len(patches))
  401. hasError := false
  402. for _, patch := range patches {
  403. status := http.StatusForbidden
  404. pstat := webdav.Propstat{}
  405. for _, p := range patch.Props {
  406. if status == http.StatusForbidden && !hasError {
  407. if !patch.Remove && util.Contains(lastModifiedProps, p.XMLName.Local) {
  408. parsed, err := http.ParseTime(string(p.InnerXML))
  409. if err != nil {
  410. f.Connection.Log(logger.LevelWarn, "unsupported last modification time: %q, err: %v",
  411. string(p.InnerXML), err)
  412. hasError = true
  413. continue
  414. }
  415. attrs := &common.StatAttributes{
  416. Flags: common.StatAttrTimes,
  417. Atime: parsed,
  418. Mtime: parsed,
  419. }
  420. if err := f.Connection.SetStat(f.GetVirtualPath(), attrs); err != nil {
  421. f.Connection.Log(logger.LevelWarn, "unable to set modification time for %q, err :%v",
  422. f.GetVirtualPath(), err)
  423. hasError = true
  424. continue
  425. }
  426. status = http.StatusOK
  427. }
  428. }
  429. pstat.Props = append(pstat.Props, webdav.Property{XMLName: p.XMLName})
  430. }
  431. pstat.Status = status
  432. resp = append(resp, pstat)
  433. }
  434. return resp, nil
  435. }