handler.go 9.2 KB

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