handler.go 9.1 KB

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