handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright (C) 2019 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) (vfs.DirLister, 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. if err := common.Connections.IsNewTransferAllowed(c.User.Username); err != nil {
  85. c.Log(logger.LevelInfo, "denying file read due to transfer count limits")
  86. return nil, util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  87. }
  88. transferQuota := c.GetTransferQuota()
  89. if !transferQuota.HasDownloadSpace() {
  90. c.Log(logger.LevelInfo, "denying file read due to quota limits")
  91. return nil, util.NewI18nError(c.GetReadQuotaExceededError(), util.I18nErrorQuotaRead)
  92. }
  93. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(name)) {
  94. return nil, util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  95. }
  96. if ok, policy := c.User.IsFileAllowed(name); !ok {
  97. c.Log(logger.LevelWarn, "reading file %q is not allowed", name)
  98. return nil, util.NewI18nError(c.GetErrorForDeniedFile(policy), util.I18nError403Message)
  99. }
  100. fs, p, err := c.GetFsAndResolvedPath(name)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if method != http.MethodHead {
  105. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreDownload, p, name, 0, 0); err != nil {
  106. c.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", name, err)
  107. return nil, util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  108. }
  109. }
  110. file, r, cancelFn, err := fs.Open(p, offset)
  111. if err != nil {
  112. c.Log(logger.LevelError, "could not open file %q for reading: %+v", p, err)
  113. return nil, c.GetFsError(fs, err)
  114. }
  115. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, p, p, name, common.TransferDownload,
  116. 0, 0, 0, 0, false, fs, transferQuota)
  117. return newHTTPDFile(baseTransfer, nil, r), nil
  118. }
  119. func (c *Connection) getFileWriter(name string) (io.WriteCloser, error) {
  120. c.UpdateLastActivity()
  121. if ok, _ := c.User.IsFileAllowed(name); !ok {
  122. c.Log(logger.LevelWarn, "writing file %q is not allowed", name)
  123. return nil, c.GetPermissionDeniedError()
  124. }
  125. fs, p, err := c.GetFsAndResolvedPath(name)
  126. if err != nil {
  127. return nil, err
  128. }
  129. filePath := p
  130. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  131. filePath = fs.GetAtomicUploadPath(p)
  132. }
  133. stat, statErr := fs.Lstat(p)
  134. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  135. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(name)) {
  136. return nil, c.GetPermissionDeniedError()
  137. }
  138. return c.handleUploadFile(fs, p, filePath, name, true, 0)
  139. }
  140. if statErr != nil {
  141. c.Log(logger.LevelError, "error performing file stat %q: %+v", p, statErr)
  142. return nil, c.GetFsError(fs, statErr)
  143. }
  144. // This happen if we upload a file that has the same name of an existing directory
  145. if stat.IsDir() {
  146. c.Log(logger.LevelError, "attempted to open a directory for writing to: %q", p)
  147. return nil, c.GetOpUnsupportedError()
  148. }
  149. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(name)) {
  150. return nil, c.GetPermissionDeniedError()
  151. }
  152. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  153. _, _, err = fs.Rename(p, filePath, 0)
  154. if err != nil {
  155. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %+v",
  156. p, filePath, err)
  157. return nil, c.GetFsError(fs, err)
  158. }
  159. }
  160. return c.handleUploadFile(fs, p, filePath, name, false, stat.Size())
  161. }
  162. func (c *Connection) handleUploadFile(fs vfs.Fs, resolvedPath, filePath, requestPath string, isNewFile bool, fileSize int64) (io.WriteCloser, error) {
  163. if err := common.Connections.IsNewTransferAllowed(c.User.Username); err != nil {
  164. c.Log(logger.LevelInfo, "denying file write due to transfer count limits")
  165. return nil, util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  166. }
  167. diskQuota, transferQuota := c.HasSpace(isNewFile, false, requestPath)
  168. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  169. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  170. return nil, common.ErrQuotaExceeded
  171. }
  172. _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, fileSize, os.O_TRUNC)
  173. if err != nil {
  174. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  175. return nil, c.GetPermissionDeniedError()
  176. }
  177. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  178. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.GetCreateChecks(requestPath, isNewFile, false))
  179. if err != nil {
  180. c.Log(logger.LevelError, "error opening existing file, source: %q, err: %+v", filePath, err)
  181. return nil, c.GetFsError(fs, err)
  182. }
  183. initialSize := int64(0)
  184. truncatedSize := int64(0) // bytes truncated and not included in quota
  185. if !isNewFile {
  186. if vfs.HasTruncateSupport(fs) {
  187. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  188. if err == nil {
  189. dataprovider.UpdateUserFolderQuota(&vfolder, &c.User, 0, -fileSize, false)
  190. } else {
  191. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  192. }
  193. } else {
  194. initialSize = fileSize
  195. truncatedSize = fileSize
  196. }
  197. if maxWriteSize > 0 {
  198. maxWriteSize += fileSize
  199. }
  200. }
  201. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  202. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  203. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, isNewFile, fs, transferQuota)
  204. return newHTTPDFile(baseTransfer, w, nil), nil
  205. }
  206. func newThrottledReader(r io.ReadCloser, limit int64, conn *Connection) *throttledReader {
  207. t := &throttledReader{
  208. id: conn.GetTransferID(),
  209. limit: limit,
  210. r: r,
  211. start: time.Now(),
  212. conn: conn,
  213. }
  214. t.bytesRead.Store(0)
  215. t.abortTransfer.Store(false)
  216. conn.AddTransfer(t)
  217. return t
  218. }
  219. type throttledReader struct {
  220. bytesRead atomic.Int64
  221. id int64
  222. limit int64
  223. r io.ReadCloser
  224. abortTransfer atomic.Bool
  225. start time.Time
  226. conn *Connection
  227. mu sync.Mutex
  228. errAbort error
  229. }
  230. func (t *throttledReader) GetID() int64 {
  231. return t.id
  232. }
  233. func (t *throttledReader) GetType() int {
  234. return common.TransferUpload
  235. }
  236. func (t *throttledReader) GetSize() int64 {
  237. return t.bytesRead.Load()
  238. }
  239. func (t *throttledReader) GetDownloadedSize() int64 {
  240. return 0
  241. }
  242. func (t *throttledReader) GetUploadedSize() int64 {
  243. return t.bytesRead.Load()
  244. }
  245. func (t *throttledReader) GetVirtualPath() string {
  246. return "**reading request body**"
  247. }
  248. func (t *throttledReader) GetStartTime() time.Time {
  249. return t.start
  250. }
  251. func (t *throttledReader) GetAbortError() error {
  252. t.mu.Lock()
  253. defer t.mu.Unlock()
  254. if t.errAbort != nil {
  255. return t.errAbort
  256. }
  257. return common.ErrTransferAborted
  258. }
  259. func (t *throttledReader) SignalClose(err error) {
  260. t.mu.Lock()
  261. t.errAbort = err
  262. t.mu.Unlock()
  263. t.abortTransfer.Store(true)
  264. }
  265. func (t *throttledReader) GetTruncatedSize() int64 {
  266. return 0
  267. }
  268. func (t *throttledReader) HasSizeLimit() bool {
  269. return false
  270. }
  271. func (t *throttledReader) Truncate(_ string, _ int64) (int64, error) {
  272. return 0, vfs.ErrVfsUnsupported
  273. }
  274. func (t *throttledReader) GetRealFsPath(_ string) string {
  275. return ""
  276. }
  277. func (t *throttledReader) SetTimes(_ string, _ time.Time, _ time.Time) bool {
  278. return false
  279. }
  280. func (t *throttledReader) Read(p []byte) (n int, err error) {
  281. if t.abortTransfer.Load() {
  282. return 0, t.GetAbortError()
  283. }
  284. t.conn.UpdateLastActivity()
  285. n, err = t.r.Read(p)
  286. if t.limit > 0 {
  287. t.bytesRead.Add(int64(n))
  288. trasferredBytes := t.bytesRead.Load()
  289. elapsed := time.Since(t.start).Nanoseconds() / 1000000
  290. wantedElapsed := 1000 * (trasferredBytes / 1024) / t.limit
  291. if wantedElapsed > elapsed {
  292. toSleep := time.Duration(wantedElapsed - elapsed)
  293. time.Sleep(toSleep * time.Millisecond)
  294. }
  295. }
  296. return
  297. }
  298. func (t *throttledReader) Close() error {
  299. return t.r.Close()
  300. }