httpfs.go 22 KB

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