file.go 12 KB

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