httpfs.go 23 KB

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