handler.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 httpd
  15. import (
  16. "io"
  17. "net/http"
  18. "os"
  19. "path"
  20. "strings"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/drakkan/sftpgo/v2/internal/common"
  25. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  26. "github.com/drakkan/sftpgo/v2/internal/logger"
  27. "github.com/drakkan/sftpgo/v2/internal/util"
  28. "github.com/drakkan/sftpgo/v2/internal/vfs"
  29. )
  30. // Connection details for a HTTP connection used to inteact with an SFTPGo filesystem
  31. type Connection struct {
  32. *common.BaseConnection
  33. request *http.Request
  34. }
  35. // GetClientVersion returns the connected client's version.
  36. func (c *Connection) GetClientVersion() string {
  37. if c.request != nil {
  38. return c.request.UserAgent()
  39. }
  40. return ""
  41. }
  42. // GetLocalAddress returns local connection address
  43. func (c *Connection) GetLocalAddress() string {
  44. return util.GetHTTPLocalAddress(c.request)
  45. }
  46. // GetRemoteAddress returns the connected client's address
  47. func (c *Connection) GetRemoteAddress() string {
  48. if c.request != nil {
  49. return c.request.RemoteAddr
  50. }
  51. return ""
  52. }
  53. // Disconnect closes the active transfer
  54. func (c *Connection) Disconnect() (err error) {
  55. return c.SignalTransfersAbort()
  56. }
  57. // GetCommand returns the request method
  58. func (c *Connection) GetCommand() string {
  59. if c.request != nil {
  60. return strings.ToUpper(c.request.Method)
  61. }
  62. return ""
  63. }
  64. // Stat returns a FileInfo describing the named file/directory, or an error,
  65. // if any happens
  66. func (c *Connection) Stat(name string, mode int) (os.FileInfo, error) {
  67. c.UpdateLastActivity()
  68. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  69. return nil, c.GetPermissionDeniedError()
  70. }
  71. fi, err := c.DoStat(name, mode, true)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return fi, err
  76. }
  77. // ReadDir returns a list of directory entries
  78. func (c *Connection) ReadDir(name string) ([]os.FileInfo, error) {
  79. c.UpdateLastActivity()
  80. return c.ListDir(name)
  81. }
  82. func (c *Connection) getFileReader(name string, offset int64, method string) (io.ReadCloser, error) {
  83. c.UpdateLastActivity()
  84. transferQuota := c.GetTransferQuota()
  85. if !transferQuota.HasDownloadSpace() {
  86. c.Log(logger.LevelInfo, "denying file read due to quota limits")
  87. return nil, c.GetReadQuotaExceededError()
  88. }
  89. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(name)) {
  90. return nil, c.GetPermissionDeniedError()
  91. }
  92. if ok, policy := c.User.IsFileAllowed(name); !ok {
  93. c.Log(logger.LevelWarn, "reading file %q is not allowed", name)
  94. return nil, c.GetErrorForDeniedFile(policy)
  95. }
  96. fs, p, err := c.GetFsAndResolvedPath(name)
  97. if err != nil {
  98. return nil, err
  99. }
  100. if method != http.MethodHead {
  101. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreDownload, p, name, 0, 0); err != nil {
  102. c.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", name, err)
  103. return nil, c.GetPermissionDeniedError()
  104. }
  105. }
  106. file, r, cancelFn, err := fs.Open(p, offset)
  107. if err != nil {
  108. c.Log(logger.LevelError, "could not open file %q for reading: %+v", p, err)
  109. return nil, c.GetFsError(fs, err)
  110. }
  111. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, p, p, name, common.TransferDownload,
  112. 0, 0, 0, 0, false, fs, transferQuota)
  113. return newHTTPDFile(baseTransfer, nil, r), nil
  114. }
  115. func (c *Connection) getFileWriter(name string) (io.WriteCloser, error) {
  116. c.UpdateLastActivity()
  117. if ok, _ := c.User.IsFileAllowed(name); !ok {
  118. c.Log(logger.LevelWarn, "writing file %q is not allowed", name)
  119. return nil, c.GetPermissionDeniedError()
  120. }
  121. fs, p, err := c.GetFsAndResolvedPath(name)
  122. if err != nil {
  123. return nil, err
  124. }
  125. filePath := p
  126. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  127. filePath = fs.GetAtomicUploadPath(p)
  128. }
  129. stat, statErr := fs.Lstat(p)
  130. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  131. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(name)) {
  132. return nil, c.GetPermissionDeniedError()
  133. }
  134. return c.handleUploadFile(fs, p, filePath, name, true, 0)
  135. }
  136. if statErr != nil {
  137. c.Log(logger.LevelError, "error performing file stat %q: %+v", p, statErr)
  138. return nil, c.GetFsError(fs, statErr)
  139. }
  140. // This happen if we upload a file that has the same name of an existing directory
  141. if stat.IsDir() {
  142. c.Log(logger.LevelError, "attempted to open a directory for writing to: %q", p)
  143. return nil, c.GetOpUnsupportedError()
  144. }
  145. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(name)) {
  146. return nil, c.GetPermissionDeniedError()
  147. }
  148. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  149. _, _, err = fs.Rename(p, filePath)
  150. if err != nil {
  151. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %+v",
  152. p, filePath, err)
  153. return nil, c.GetFsError(fs, err)
  154. }
  155. }
  156. return c.handleUploadFile(fs, p, filePath, name, false, stat.Size())
  157. }
  158. func (c *Connection) handleUploadFile(fs vfs.Fs, resolvedPath, filePath, requestPath string, isNewFile bool, fileSize int64) (io.WriteCloser, error) {
  159. diskQuota, transferQuota := c.HasSpace(isNewFile, false, requestPath)
  160. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  161. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  162. return nil, common.ErrQuotaExceeded
  163. }
  164. _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, fileSize, os.O_TRUNC)
  165. if err != nil {
  166. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  167. return nil, c.GetPermissionDeniedError()
  168. }
  169. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  170. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  171. if err != nil {
  172. c.Log(logger.LevelError, "error opening existing file, source: %q, err: %+v", filePath, err)
  173. return nil, c.GetFsError(fs, err)
  174. }
  175. initialSize := int64(0)
  176. truncatedSize := int64(0) // bytes truncated and not included in quota
  177. if !isNewFile {
  178. if vfs.HasTruncateSupport(fs) {
  179. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  180. if err == nil {
  181. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  182. if vfolder.IsIncludedInUserQuota() {
  183. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  184. }
  185. } else {
  186. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  187. }
  188. } else {
  189. initialSize = fileSize
  190. truncatedSize = fileSize
  191. }
  192. if maxWriteSize > 0 {
  193. maxWriteSize += fileSize
  194. }
  195. }
  196. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  197. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  198. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, isNewFile, fs, transferQuota)
  199. return newHTTPDFile(baseTransfer, w, nil), nil
  200. }
  201. func newThrottledReader(r io.ReadCloser, limit int64, conn *Connection) *throttledReader {
  202. t := &throttledReader{
  203. id: conn.GetTransferID(),
  204. limit: limit,
  205. r: r,
  206. start: time.Now(),
  207. conn: conn,
  208. }
  209. t.bytesRead.Store(0)
  210. t.abortTransfer.Store(false)
  211. conn.AddTransfer(t)
  212. return t
  213. }
  214. type throttledReader struct {
  215. bytesRead atomic.Int64
  216. id int64
  217. limit int64
  218. r io.ReadCloser
  219. abortTransfer atomic.Bool
  220. start time.Time
  221. conn *Connection
  222. mu sync.Mutex
  223. errAbort error
  224. }
  225. func (t *throttledReader) GetID() int64 {
  226. return t.id
  227. }
  228. func (t *throttledReader) GetType() int {
  229. return common.TransferUpload
  230. }
  231. func (t *throttledReader) GetSize() int64 {
  232. return t.bytesRead.Load()
  233. }
  234. func (t *throttledReader) GetDownloadedSize() int64 {
  235. return 0
  236. }
  237. func (t *throttledReader) GetUploadedSize() int64 {
  238. return t.bytesRead.Load()
  239. }
  240. func (t *throttledReader) GetVirtualPath() string {
  241. return "**reading request body**"
  242. }
  243. func (t *throttledReader) GetStartTime() time.Time {
  244. return t.start
  245. }
  246. func (t *throttledReader) GetAbortError() error {
  247. t.mu.Lock()
  248. defer t.mu.Unlock()
  249. if t.errAbort != nil {
  250. return t.errAbort
  251. }
  252. return common.ErrTransferAborted
  253. }
  254. func (t *throttledReader) SignalClose(err error) {
  255. t.mu.Lock()
  256. t.errAbort = err
  257. t.mu.Unlock()
  258. t.abortTransfer.Store(true)
  259. }
  260. func (t *throttledReader) GetTruncatedSize() int64 {
  261. return 0
  262. }
  263. func (t *throttledReader) HasSizeLimit() bool {
  264. return false
  265. }
  266. func (t *throttledReader) Truncate(fsPath string, size int64) (int64, error) {
  267. return 0, vfs.ErrVfsUnsupported
  268. }
  269. func (t *throttledReader) GetRealFsPath(fsPath string) string {
  270. return ""
  271. }
  272. func (t *throttledReader) SetTimes(fsPath string, atime time.Time, mtime time.Time) bool {
  273. return false
  274. }
  275. func (t *throttledReader) Read(p []byte) (n int, err error) {
  276. if t.abortTransfer.Load() {
  277. return 0, t.GetAbortError()
  278. }
  279. t.conn.UpdateLastActivity()
  280. n, err = t.r.Read(p)
  281. if t.limit > 0 {
  282. t.bytesRead.Add(int64(n))
  283. trasferredBytes := t.bytesRead.Load()
  284. elapsed := time.Since(t.start).Nanoseconds() / 1000000
  285. wantedElapsed := 1000 * (trasferredBytes / 1024) / t.limit
  286. if wantedElapsed > elapsed {
  287. toSleep := time.Duration(wantedElapsed - elapsed)
  288. time.Sleep(toSleep * time.Millisecond)
  289. }
  290. }
  291. return
  292. }
  293. func (t *throttledReader) Close() error {
  294. return t.r.Close()
  295. }