httpfs.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 vfs
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "io/fs"
  23. "mime"
  24. "net"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "path"
  29. "path/filepath"
  30. "strings"
  31. "time"
  32. "github.com/pkg/sftp"
  33. "github.com/sftpgo/sdk"
  34. "github.com/drakkan/sftpgo/v2/internal/kms"
  35. "github.com/drakkan/sftpgo/v2/internal/logger"
  36. "github.com/drakkan/sftpgo/v2/internal/metric"
  37. "github.com/drakkan/sftpgo/v2/internal/util"
  38. )
  39. const (
  40. // httpFsName is the name for the HTTP Fs implementation
  41. httpFsName = "httpfs"
  42. maxHTTPFsResponseSize = 1048576
  43. )
  44. var (
  45. supportedEndpointSchema = []string{"http://", "https://"}
  46. )
  47. // HTTPFsConfig defines the configuration for HTTP based filesystem
  48. type HTTPFsConfig struct {
  49. sdk.BaseHTTPFsConfig
  50. Password *kms.Secret `json:"password,omitempty"`
  51. APIKey *kms.Secret `json:"api_key,omitempty"`
  52. }
  53. func (c *HTTPFsConfig) isUnixDomainSocket() bool {
  54. return strings.HasPrefix(c.Endpoint, "http://unix") || strings.HasPrefix(c.Endpoint, "https://unix")
  55. }
  56. // HideConfidentialData hides confidential data
  57. func (c *HTTPFsConfig) HideConfidentialData() {
  58. if c.Password != nil {
  59. c.Password.Hide()
  60. }
  61. if c.APIKey != nil {
  62. c.APIKey.Hide()
  63. }
  64. }
  65. func (c *HTTPFsConfig) setNilSecretsIfEmpty() {
  66. if c.Password != nil && c.Password.IsEmpty() {
  67. c.Password = nil
  68. }
  69. if c.APIKey != nil && c.APIKey.IsEmpty() {
  70. c.APIKey = nil
  71. }
  72. }
  73. func (c *HTTPFsConfig) setEmptyCredentialsIfNil() {
  74. if c.Password == nil {
  75. c.Password = kms.NewEmptySecret()
  76. }
  77. if c.APIKey == nil {
  78. c.APIKey = kms.NewEmptySecret()
  79. }
  80. }
  81. func (c *HTTPFsConfig) isEqual(other HTTPFsConfig) bool {
  82. if c.Endpoint != other.Endpoint {
  83. return false
  84. }
  85. if c.Username != other.Username {
  86. return false
  87. }
  88. if c.SkipTLSVerify != other.SkipTLSVerify {
  89. return false
  90. }
  91. c.setEmptyCredentialsIfNil()
  92. other.setEmptyCredentialsIfNil()
  93. if !c.Password.IsEqual(other.Password) {
  94. return false
  95. }
  96. return c.APIKey.IsEqual(other.APIKey)
  97. }
  98. func (c *HTTPFsConfig) isSameResource(other HTTPFsConfig) bool {
  99. if c.EqualityCheckMode > 0 || other.EqualityCheckMode > 0 {
  100. if c.Username != other.Username {
  101. return false
  102. }
  103. }
  104. return c.Endpoint == other.Endpoint
  105. }
  106. // validate returns an error if the configuration is not valid
  107. func (c *HTTPFsConfig) validate() error {
  108. c.setEmptyCredentialsIfNil()
  109. if c.Endpoint == "" {
  110. return util.NewI18nError(errors.New("httpfs: endpoint cannot be empty"), util.I18nErrorEndpointRequired)
  111. }
  112. c.Endpoint = strings.TrimRight(c.Endpoint, "/")
  113. endpointURL, err := url.Parse(c.Endpoint)
  114. if err != nil {
  115. return util.NewI18nError(fmt.Errorf("httpfs: invalid endpoint: %w", err), util.I18nErrorEndpointInvalid)
  116. }
  117. if !util.IsStringPrefixInSlice(c.Endpoint, supportedEndpointSchema) {
  118. return util.NewI18nError(
  119. errors.New("httpfs: invalid endpoint schema: http and https are supported"),
  120. util.I18nErrorEndpointInvalid,
  121. )
  122. }
  123. if endpointURL.Host == "unix" {
  124. socketPath := endpointURL.Query().Get("socket_path")
  125. if !filepath.IsAbs(socketPath) {
  126. return util.NewI18nError(
  127. fmt.Errorf("httpfs: invalid unix domain socket path: %q", socketPath),
  128. util.I18nErrorEndpointInvalid,
  129. )
  130. }
  131. }
  132. if !isEqualityCheckModeValid(c.EqualityCheckMode) {
  133. return errors.New("invalid equality_check_mode")
  134. }
  135. if c.Password.IsEncrypted() && !c.Password.IsValid() {
  136. return errors.New("httpfs: invalid encrypted password")
  137. }
  138. if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
  139. return errors.New("httpfs: invalid password")
  140. }
  141. if c.APIKey.IsEncrypted() && !c.APIKey.IsValid() {
  142. return errors.New("httpfs: invalid encrypted API key")
  143. }
  144. if !c.APIKey.IsEmpty() && !c.APIKey.IsValidInput() {
  145. return errors.New("httpfs: invalid API key")
  146. }
  147. return nil
  148. }
  149. // ValidateAndEncryptCredentials validates the config and encrypts credentials if they are in plain text
  150. func (c *HTTPFsConfig) ValidateAndEncryptCredentials(additionalData string) error {
  151. err := c.validate()
  152. if err != nil {
  153. var errI18n *util.I18nError
  154. errValidation := util.NewValidationError(fmt.Sprintf("could not validate HTTP fs config: %v", err))
  155. if errors.As(err, &errI18n) {
  156. return util.NewI18nError(errValidation, errI18n.Message)
  157. }
  158. return util.NewI18nError(errValidation, util.I18nErrorFsValidation)
  159. }
  160. if c.Password.IsPlain() {
  161. c.Password.SetAdditionalData(additionalData)
  162. if err := c.Password.Encrypt(); err != nil {
  163. return util.NewI18nError(
  164. util.NewValidationError(fmt.Sprintf("could not encrypt HTTP fs password: %v", err)),
  165. util.I18nErrorFsValidation,
  166. )
  167. }
  168. }
  169. if c.APIKey.IsPlain() {
  170. c.APIKey.SetAdditionalData(additionalData)
  171. if err := c.APIKey.Encrypt(); err != nil {
  172. return util.NewI18nError(
  173. util.NewValidationError(fmt.Sprintf("could not encrypt HTTP fs API key: %v", err)),
  174. util.I18nErrorFsValidation,
  175. )
  176. }
  177. }
  178. return nil
  179. }
  180. // HTTPFs is a Fs implementation for the SFTPGo HTTP filesystem backend
  181. type HTTPFs struct {
  182. connectionID string
  183. localTempDir string
  184. // if not empty this fs is mouted as virtual folder in the specified path
  185. mountPath string
  186. config *HTTPFsConfig
  187. client *http.Client
  188. ctxTimeout time.Duration
  189. }
  190. // NewHTTPFs returns an HTTPFs object that allows to interact with SFTPGo HTTP filesystem backends
  191. func NewHTTPFs(connectionID, localTempDir, mountPath string, config HTTPFsConfig) (Fs, error) {
  192. if localTempDir == "" {
  193. localTempDir = getLocalTempDir()
  194. }
  195. config.setEmptyCredentialsIfNil()
  196. if !config.Password.IsEmpty() {
  197. if err := config.Password.TryDecrypt(); err != nil {
  198. return nil, err
  199. }
  200. }
  201. if !config.APIKey.IsEmpty() {
  202. if err := config.APIKey.TryDecrypt(); err != nil {
  203. return nil, err
  204. }
  205. }
  206. fs := &HTTPFs{
  207. connectionID: connectionID,
  208. localTempDir: localTempDir,
  209. mountPath: mountPath,
  210. config: &config,
  211. ctxTimeout: 30 * time.Second,
  212. }
  213. transport := http.DefaultTransport.(*http.Transport).Clone()
  214. transport.MaxResponseHeaderBytes = 1 << 16
  215. transport.WriteBufferSize = 1 << 16
  216. transport.ReadBufferSize = 1 << 16
  217. if fs.config.isUnixDomainSocket() {
  218. endpointURL, err := url.Parse(fs.config.Endpoint)
  219. if err != nil {
  220. return nil, err
  221. }
  222. if endpointURL.Host == "unix" {
  223. socketPath := endpointURL.Query().Get("socket_path")
  224. if !filepath.IsAbs(socketPath) {
  225. return nil, fmt.Errorf("httpfs: invalid unix domain socket path: %q", socketPath)
  226. }
  227. if endpointURL.Scheme == "https" {
  228. transport.DialTLSContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
  229. var tlsConfig *tls.Config
  230. var d tls.Dialer
  231. if config.SkipTLSVerify {
  232. tlsConfig = getInsecureTLSConfig()
  233. }
  234. d.Config = tlsConfig
  235. return d.DialContext(ctx, "unix", socketPath)
  236. }
  237. } else {
  238. transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
  239. var d net.Dialer
  240. return d.DialContext(ctx, "unix", socketPath)
  241. }
  242. }
  243. endpointURL.Path = path.Join(endpointURL.Path, endpointURL.Query().Get("api_prefix"))
  244. endpointURL.RawQuery = ""
  245. endpointURL.RawFragment = ""
  246. fs.config.Endpoint = endpointURL.String()
  247. }
  248. }
  249. if config.SkipTLSVerify {
  250. if transport.TLSClientConfig != nil {
  251. transport.TLSClientConfig.InsecureSkipVerify = true
  252. } else {
  253. transport.TLSClientConfig = getInsecureTLSConfig()
  254. }
  255. }
  256. fs.client = &http.Client{
  257. Transport: transport,
  258. }
  259. return fs, nil
  260. }
  261. // Name returns the name for the Fs implementation
  262. func (fs *HTTPFs) Name() string {
  263. return fmt.Sprintf("%v %q", httpFsName, fs.config.Endpoint)
  264. }
  265. // ConnectionID returns the connection ID associated to this Fs implementation
  266. func (fs *HTTPFs) ConnectionID() string {
  267. return fs.connectionID
  268. }
  269. // Stat returns a FileInfo describing the named file
  270. func (fs *HTTPFs) Stat(name string) (os.FileInfo, error) {
  271. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  272. defer cancelFn()
  273. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "stat", name, "", "", nil)
  274. if err != nil {
  275. return nil, err
  276. }
  277. defer resp.Body.Close()
  278. respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPFsResponseSize))
  279. if err != nil {
  280. return nil, err
  281. }
  282. var response statResponse
  283. err = json.Unmarshal(respBody, &response)
  284. if err != nil {
  285. return nil, err
  286. }
  287. return response.getFileInfo(), nil
  288. }
  289. // Lstat returns a FileInfo describing the named file
  290. func (fs *HTTPFs) Lstat(name string) (os.FileInfo, error) {
  291. return fs.Stat(name)
  292. }
  293. // Open opens the named file for reading
  294. func (fs *HTTPFs) Open(name string, offset int64) (File, PipeReader, func(), error) {
  295. r, w, err := createPipeFn(fs.localTempDir, 0)
  296. if err != nil {
  297. return nil, nil, nil, err
  298. }
  299. p := NewPipeReader(r)
  300. ctx, cancelFn := context.WithCancel(context.Background())
  301. var queryString string
  302. if offset > 0 {
  303. queryString = fmt.Sprintf("?offset=%d", offset)
  304. }
  305. go func() {
  306. defer cancelFn()
  307. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "open", name, queryString, "", nil)
  308. if err != nil {
  309. fsLog(fs, logger.LevelError, "download error, path %q, err: %v", name, err)
  310. w.CloseWithError(err) //nolint:errcheck
  311. metric.HTTPFsTransferCompleted(0, 1, err)
  312. return
  313. }
  314. defer resp.Body.Close()
  315. n, err := io.Copy(w, resp.Body)
  316. w.CloseWithError(err) //nolint:errcheck
  317. fsLog(fs, logger.LevelDebug, "download completed, path %q size: %v, err: %+v", name, n, err)
  318. metric.HTTPFsTransferCompleted(n, 1, err)
  319. }()
  320. return nil, p, cancelFn, nil
  321. }
  322. // Create creates or opens the named file for writing
  323. func (fs *HTTPFs) Create(name string, flag, checks int) (File, PipeWriter, func(), error) {
  324. r, w, err := createPipeFn(fs.localTempDir, 0)
  325. if err != nil {
  326. return nil, nil, nil, err
  327. }
  328. p := NewPipeWriter(w)
  329. ctx, cancelFn := context.WithCancel(context.Background())
  330. go func() {
  331. defer cancelFn()
  332. contentType := mime.TypeByExtension(path.Ext(name))
  333. queryString := fmt.Sprintf("?flags=%d&checks=%d", flag, checks)
  334. resp, err := fs.sendHTTPRequest(ctx, http.MethodPost, "create", name, queryString, contentType,
  335. &wrapReader{reader: r})
  336. if err != nil {
  337. fsLog(fs, logger.LevelError, "upload error, path %q, err: %v", name, err)
  338. r.CloseWithError(err) //nolint:errcheck
  339. p.Done(err)
  340. metric.HTTPFsTransferCompleted(0, 0, err)
  341. return
  342. }
  343. defer resp.Body.Close()
  344. r.CloseWithError(err) //nolint:errcheck
  345. p.Done(err)
  346. fsLog(fs, logger.LevelDebug, "upload completed, path: %q, readed bytes: %d", name, r.GetReadedBytes())
  347. metric.HTTPFsTransferCompleted(r.GetReadedBytes(), 0, err)
  348. }()
  349. return nil, p, cancelFn, nil
  350. }
  351. // Rename renames (moves) source to target.
  352. func (fs *HTTPFs) Rename(source, target string, checks int) (int, int64, error) {
  353. if source == target {
  354. return -1, -1, nil
  355. }
  356. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  357. defer cancelFn()
  358. queryString := fmt.Sprintf("?target=%s", url.QueryEscape(target))
  359. resp, err := fs.sendHTTPRequest(ctx, http.MethodPatch, "rename", source, queryString, "", nil)
  360. if err != nil {
  361. return -1, -1, err
  362. }
  363. defer resp.Body.Close()
  364. if checks&CheckUpdateModTime != 0 {
  365. fs.Chtimes(target, time.Now(), time.Now(), false) //nolint:errcheck
  366. }
  367. return -1, -1, nil
  368. }
  369. // Remove removes the named file or (empty) directory.
  370. func (fs *HTTPFs) Remove(name string, _ bool) error {
  371. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  372. defer cancelFn()
  373. resp, err := fs.sendHTTPRequest(ctx, http.MethodDelete, "remove", name, "", "", nil)
  374. if err != nil {
  375. return err
  376. }
  377. defer resp.Body.Close()
  378. return nil
  379. }
  380. // Mkdir creates a new directory with the specified name and default permissions
  381. func (fs *HTTPFs) Mkdir(name string) error {
  382. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  383. defer cancelFn()
  384. resp, err := fs.sendHTTPRequest(ctx, http.MethodPost, "mkdir", name, "", "", nil)
  385. if err != nil {
  386. return err
  387. }
  388. defer resp.Body.Close()
  389. return nil
  390. }
  391. // Symlink creates source as a symbolic link to target.
  392. func (*HTTPFs) Symlink(_, _ string) error {
  393. return ErrVfsUnsupported
  394. }
  395. // Readlink returns the destination of the named symbolic link
  396. func (*HTTPFs) Readlink(_ string) (string, error) {
  397. return "", ErrVfsUnsupported
  398. }
  399. // Chown changes the numeric uid and gid of the named file.
  400. func (fs *HTTPFs) Chown(_ string, _ int, _ int) error {
  401. return ErrVfsUnsupported
  402. }
  403. // Chmod changes the mode of the named file to mode.
  404. func (fs *HTTPFs) Chmod(name string, mode os.FileMode) error {
  405. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  406. defer cancelFn()
  407. queryString := fmt.Sprintf("?mode=%d", mode)
  408. resp, err := fs.sendHTTPRequest(ctx, http.MethodPatch, "chmod", name, queryString, "", nil)
  409. if err != nil {
  410. return err
  411. }
  412. defer resp.Body.Close()
  413. return nil
  414. }
  415. // Chtimes changes the access and modification times of the named file.
  416. func (fs *HTTPFs) Chtimes(name string, atime, mtime time.Time, _ bool) error {
  417. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  418. defer cancelFn()
  419. queryString := fmt.Sprintf("?access_time=%s&modification_time=%s", atime.UTC().Format(time.RFC3339),
  420. mtime.UTC().Format(time.RFC3339))
  421. resp, err := fs.sendHTTPRequest(ctx, http.MethodPatch, "chtimes", name, queryString, "", nil)
  422. if err != nil {
  423. return err
  424. }
  425. defer resp.Body.Close()
  426. return nil
  427. }
  428. // Truncate changes the size of the named file.
  429. // Truncate by path is not supported, while truncating an opened
  430. // file is handled inside base transfer
  431. func (fs *HTTPFs) Truncate(name string, size int64) error {
  432. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  433. defer cancelFn()
  434. queryString := fmt.Sprintf("?size=%d", size)
  435. resp, err := fs.sendHTTPRequest(ctx, http.MethodPatch, "truncate", name, queryString, "", nil)
  436. if err != nil {
  437. return err
  438. }
  439. defer resp.Body.Close()
  440. return nil
  441. }
  442. // ReadDir reads the directory named by dirname and returns
  443. // a list of directory entries.
  444. func (fs *HTTPFs) ReadDir(dirname string) (DirLister, error) {
  445. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  446. defer cancelFn()
  447. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "readdir", dirname, "", "", nil)
  448. if err != nil {
  449. return nil, err
  450. }
  451. defer resp.Body.Close()
  452. respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPFsResponseSize*10))
  453. if err != nil {
  454. return nil, err
  455. }
  456. var response []statResponse
  457. err = json.Unmarshal(respBody, &response)
  458. if err != nil {
  459. return nil, err
  460. }
  461. result := make([]os.FileInfo, 0, len(response))
  462. for _, stat := range response {
  463. result = append(result, stat.getFileInfo())
  464. }
  465. return &baseDirLister{result}, nil
  466. }
  467. // IsUploadResumeSupported returns true if resuming uploads is supported.
  468. func (*HTTPFs) IsUploadResumeSupported() bool {
  469. return false
  470. }
  471. // IsConditionalUploadResumeSupported returns if resuming uploads is supported
  472. // for the specified size
  473. func (*HTTPFs) IsConditionalUploadResumeSupported(_ int64) bool {
  474. return false
  475. }
  476. // IsAtomicUploadSupported returns true if atomic upload is supported.
  477. func (*HTTPFs) IsAtomicUploadSupported() bool {
  478. return false
  479. }
  480. // IsNotExist returns a boolean indicating whether the error is known to
  481. // report that a file or directory does not exist
  482. func (*HTTPFs) IsNotExist(err error) bool {
  483. return errors.Is(err, fs.ErrNotExist)
  484. }
  485. // IsPermission returns a boolean indicating whether the error is known to
  486. // report that permission is denied.
  487. func (*HTTPFs) IsPermission(err error) bool {
  488. return errors.Is(err, fs.ErrPermission)
  489. }
  490. // IsNotSupported returns true if the error indicate an unsupported operation
  491. func (*HTTPFs) IsNotSupported(err error) bool {
  492. if err == nil {
  493. return false
  494. }
  495. return err == ErrVfsUnsupported
  496. }
  497. // CheckRootPath creates the specified local root directory if it does not exists
  498. func (fs *HTTPFs) CheckRootPath(username string, uid int, gid int) bool {
  499. // we need a local directory for temporary files
  500. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "", nil)
  501. return osFs.CheckRootPath(username, uid, gid)
  502. }
  503. // ScanRootDirContents returns the number of files and their size
  504. func (fs *HTTPFs) ScanRootDirContents() (int, int64, error) {
  505. return fs.GetDirSize("/")
  506. }
  507. // CheckMetadata checks the metadata consistency
  508. func (*HTTPFs) CheckMetadata() error {
  509. return nil
  510. }
  511. // GetDirSize returns the number of files and the size for a folder
  512. // including any subfolders
  513. func (fs *HTTPFs) GetDirSize(dirname string) (int, int64, error) {
  514. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  515. defer cancelFn()
  516. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "dirsize", dirname, "", "", nil)
  517. if err != nil {
  518. return 0, 0, err
  519. }
  520. defer resp.Body.Close()
  521. respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPFsResponseSize))
  522. if err != nil {
  523. return 0, 0, err
  524. }
  525. var response dirSizeResponse
  526. err = json.Unmarshal(respBody, &response)
  527. if err != nil {
  528. return 0, 0, err
  529. }
  530. return response.Files, response.Size, nil
  531. }
  532. // GetAtomicUploadPath returns the path to use for an atomic upload.
  533. func (*HTTPFs) GetAtomicUploadPath(_ string) string {
  534. return ""
  535. }
  536. // GetRelativePath returns the path for a file relative to the user's home dir.
  537. // This is the path as seen by SFTPGo users
  538. func (fs *HTTPFs) GetRelativePath(name string) string {
  539. rel := path.Clean(name)
  540. if rel == "." {
  541. rel = ""
  542. }
  543. if !path.IsAbs(rel) {
  544. rel = "/" + rel
  545. }
  546. if fs.mountPath != "" {
  547. rel = path.Join(fs.mountPath, rel)
  548. }
  549. return rel
  550. }
  551. // Walk walks the file tree rooted at root, calling walkFn for each file or
  552. // directory in the tree, including root. The result are unordered
  553. func (fs *HTTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
  554. info, err := fs.Lstat(root)
  555. if err != nil {
  556. return walkFn(root, nil, err)
  557. }
  558. return fs.walk(root, info, walkFn)
  559. }
  560. // Join joins any number of path elements into a single path
  561. func (*HTTPFs) Join(elem ...string) string {
  562. return strings.TrimPrefix(path.Join(elem...), "/")
  563. }
  564. // HasVirtualFolders returns true if folders are emulated
  565. func (*HTTPFs) HasVirtualFolders() bool {
  566. return false
  567. }
  568. // ResolvePath returns the matching filesystem path for the specified virtual path
  569. func (fs *HTTPFs) ResolvePath(virtualPath string) (string, error) {
  570. if fs.mountPath != "" {
  571. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  572. }
  573. if !path.IsAbs(virtualPath) {
  574. virtualPath = path.Clean("/" + virtualPath)
  575. }
  576. return virtualPath, nil
  577. }
  578. // GetMimeType returns the content type
  579. func (fs *HTTPFs) GetMimeType(name string) (string, error) {
  580. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  581. defer cancelFn()
  582. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "stat", name, "", "", nil)
  583. if err != nil {
  584. return "", err
  585. }
  586. defer resp.Body.Close()
  587. respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPFsResponseSize))
  588. if err != nil {
  589. return "", err
  590. }
  591. var response mimeTypeResponse
  592. err = json.Unmarshal(respBody, &response)
  593. if err != nil {
  594. return "", err
  595. }
  596. return response.Mime, nil
  597. }
  598. // Close closes the fs
  599. func (fs *HTTPFs) Close() error {
  600. fs.client.CloseIdleConnections()
  601. return nil
  602. }
  603. // GetAvailableDiskSize returns the available size for the specified path
  604. func (fs *HTTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  605. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  606. defer cancelFn()
  607. resp, err := fs.sendHTTPRequest(ctx, http.MethodGet, "statvfs", dirName, "", "", nil)
  608. if err != nil {
  609. return nil, err
  610. }
  611. defer resp.Body.Close()
  612. respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPFsResponseSize))
  613. if err != nil {
  614. return nil, err
  615. }
  616. var response statVFSResponse
  617. err = json.Unmarshal(respBody, &response)
  618. if err != nil {
  619. return nil, err
  620. }
  621. return response.toSFTPStatVFS(), nil
  622. }
  623. func (fs *HTTPFs) sendHTTPRequest(ctx context.Context, method, base, name, queryString, contentType string,
  624. body io.Reader,
  625. ) (*http.Response, error) {
  626. url := fmt.Sprintf("%s/%s/%s%s", fs.config.Endpoint, base, url.PathEscape(name), queryString)
  627. req, err := http.NewRequest(method, url, body)
  628. if err != nil {
  629. return nil, err
  630. }
  631. if contentType != "" {
  632. req.Header.Set("Content-Type", contentType)
  633. }
  634. if fs.config.APIKey.GetPayload() != "" {
  635. req.Header.Set("X-API-KEY", fs.config.APIKey.GetPayload())
  636. }
  637. if fs.config.Username != "" || fs.config.Password.GetPayload() != "" {
  638. req.SetBasicAuth(fs.config.Username, fs.config.Password.GetPayload())
  639. }
  640. resp, err := fs.client.Do(req.WithContext(ctx))
  641. if err != nil {
  642. return nil, fmt.Errorf("unable to send HTTP request to URL %v: %w", url, err)
  643. }
  644. if err = getErrorFromResponseCode(resp.StatusCode); err != nil {
  645. resp.Body.Close()
  646. return nil, err
  647. }
  648. return resp, nil
  649. }
  650. // walk recursively descends path, calling walkFn.
  651. func (fs *HTTPFs) walk(filePath string, info fs.FileInfo, walkFn filepath.WalkFunc) error {
  652. if !info.IsDir() {
  653. return walkFn(filePath, info, nil)
  654. }
  655. lister, err := fs.ReadDir(filePath)
  656. err1 := walkFn(filePath, info, err)
  657. if err != nil || err1 != nil {
  658. if err == nil {
  659. lister.Close()
  660. }
  661. return err1
  662. }
  663. defer lister.Close()
  664. for {
  665. files, err := lister.Next(ListerBatchSize)
  666. finished := errors.Is(err, io.EOF)
  667. if err != nil && !finished {
  668. return err
  669. }
  670. for _, fi := range files {
  671. objName := path.Join(filePath, fi.Name())
  672. err = fs.walk(objName, fi, walkFn)
  673. if err != nil {
  674. return err
  675. }
  676. }
  677. if finished {
  678. return nil
  679. }
  680. }
  681. }
  682. func getErrorFromResponseCode(code int) error {
  683. switch code {
  684. case 401, 403:
  685. return os.ErrPermission
  686. case 404:
  687. return os.ErrNotExist
  688. case 501:
  689. return ErrVfsUnsupported
  690. case 200, 201:
  691. return nil
  692. default:
  693. return fmt.Errorf("unexpected response code: %v", code)
  694. }
  695. }
  696. func getInsecureTLSConfig() *tls.Config {
  697. return &tls.Config{
  698. InsecureSkipVerify: true,
  699. }
  700. }
  701. type wrapReader struct {
  702. reader io.Reader
  703. }
  704. func (r *wrapReader) Read(p []byte) (n int, err error) {
  705. return r.reader.Read(p)
  706. }
  707. type statResponse struct {
  708. Name string `json:"name"`
  709. Size int64 `json:"size"`
  710. Mode uint32 `json:"mode"`
  711. LastModified time.Time `json:"last_modified"`
  712. }
  713. func (s *statResponse) getFileInfo() os.FileInfo {
  714. info := NewFileInfo(s.Name, false, s.Size, s.LastModified, false)
  715. info.SetMode(fs.FileMode(s.Mode))
  716. return info
  717. }
  718. type dirSizeResponse struct {
  719. Files int `json:"files"`
  720. Size int64 `json:"size"`
  721. }
  722. type mimeTypeResponse struct {
  723. Mime string `json:"mime"`
  724. }
  725. type statVFSResponse struct {
  726. ID uint32 `json:"-"`
  727. Bsize uint64 `json:"bsize"`
  728. Frsize uint64 `json:"frsize"`
  729. Blocks uint64 `json:"blocks"`
  730. Bfree uint64 `json:"bfree"`
  731. Bavail uint64 `json:"bavail"`
  732. Files uint64 `json:"files"`
  733. Ffree uint64 `json:"ffree"`
  734. Favail uint64 `json:"favail"`
  735. Fsid uint64 `json:"fsid"`
  736. Flag uint64 `json:"flag"`
  737. Namemax uint64 `json:"namemax"`
  738. }
  739. func (s *statVFSResponse) toSFTPStatVFS() *sftp.StatVFS {
  740. return &sftp.StatVFS{
  741. Bsize: s.Bsize,
  742. Frsize: s.Frsize,
  743. Blocks: s.Blocks,
  744. Bfree: s.Bfree,
  745. Bavail: s.Bavail,
  746. Files: s.Files,
  747. Ffree: s.Ffree,
  748. Favail: s.Ffree,
  749. Flag: s.Flag,
  750. Namemax: s.Namemax,
  751. }
  752. }