file.go 12 KB

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