azblobfs.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. // Copyright (C) 2019-2022 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. //go:build !noazblob
  15. // +build !noazblob
  16. package vfs
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/base64"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "mime"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "path"
  29. "path/filepath"
  30. "strings"
  31. "sync"
  32. "sync/atomic"
  33. "time"
  34. "github.com/Azure/azure-sdk-for-go/sdk/azcore"
  35. "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
  36. "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
  37. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
  38. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
  39. "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
  40. "github.com/eikenb/pipeat"
  41. "github.com/google/uuid"
  42. "github.com/pkg/sftp"
  43. "github.com/drakkan/sftpgo/v2/internal/logger"
  44. "github.com/drakkan/sftpgo/v2/internal/metric"
  45. "github.com/drakkan/sftpgo/v2/internal/plugin"
  46. "github.com/drakkan/sftpgo/v2/internal/util"
  47. "github.com/drakkan/sftpgo/v2/internal/version"
  48. )
  49. const (
  50. azureDefaultEndpoint = "blob.core.windows.net"
  51. azBlobFsName = "AzureBlobFs"
  52. azFolderKey = "hdi_isfolder"
  53. )
  54. // AzureBlobFs is a Fs implementation for Azure Blob storage.
  55. type AzureBlobFs struct {
  56. connectionID string
  57. localTempDir string
  58. // if not empty this fs is mouted as virtual folder in the specified path
  59. mountPath string
  60. config *AzBlobFsConfig
  61. containerClient *container.Client
  62. ctxTimeout time.Duration
  63. ctxLongTimeout time.Duration
  64. }
  65. func init() {
  66. version.AddFeature("+azblob")
  67. }
  68. // NewAzBlobFs returns an AzBlobFs object that allows to interact with Azure Blob storage
  69. func NewAzBlobFs(connectionID, localTempDir, mountPath string, config AzBlobFsConfig) (Fs, error) {
  70. if localTempDir == "" {
  71. if tempPath != "" {
  72. localTempDir = tempPath
  73. } else {
  74. localTempDir = filepath.Clean(os.TempDir())
  75. }
  76. }
  77. fs := &AzureBlobFs{
  78. connectionID: connectionID,
  79. localTempDir: localTempDir,
  80. mountPath: getMountPath(mountPath),
  81. config: &config,
  82. ctxTimeout: 30 * time.Second,
  83. ctxLongTimeout: 90 * time.Second,
  84. }
  85. if err := fs.config.validate(); err != nil {
  86. return fs, err
  87. }
  88. if err := fs.config.tryDecrypt(); err != nil {
  89. return fs, err
  90. }
  91. fs.setConfigDefaults()
  92. if fs.config.SASURL.GetPayload() != "" {
  93. return fs.initFromSASURL()
  94. }
  95. credential, err := blob.NewSharedKeyCredential(fs.config.AccountName, fs.config.AccountKey.GetPayload())
  96. if err != nil {
  97. return fs, fmt.Errorf("invalid credentials: %v", err)
  98. }
  99. var endpoint string
  100. if fs.config.UseEmulator {
  101. endpoint = fmt.Sprintf("%s/%s", fs.config.Endpoint, fs.config.AccountName)
  102. } else {
  103. endpoint = fmt.Sprintf("https://%s.%s/", fs.config.AccountName, fs.config.Endpoint)
  104. }
  105. containerURL := runtime.JoinPaths(endpoint, fs.config.Container)
  106. svc, err := container.NewClientWithSharedKeyCredential(containerURL, credential, getAzContainerClientOptions())
  107. if err != nil {
  108. return fs, fmt.Errorf("invalid credentials: %v", err)
  109. }
  110. fs.containerClient = svc
  111. return fs, err
  112. }
  113. func (fs *AzureBlobFs) initFromSASURL() (Fs, error) {
  114. parts, err := blob.ParseURL(fs.config.SASURL.GetPayload())
  115. if err != nil {
  116. return fs, fmt.Errorf("invalid SAS URL: %w", err)
  117. }
  118. if parts.BlobName != "" {
  119. return fs, fmt.Errorf("SAS URL with blob name not supported")
  120. }
  121. if parts.ContainerName != "" {
  122. if fs.config.Container != "" && fs.config.Container != parts.ContainerName {
  123. return fs, fmt.Errorf("container name in SAS URL %q and container provided %q do not match",
  124. parts.ContainerName, fs.config.Container)
  125. }
  126. svc, err := container.NewClientWithNoCredential(fs.config.SASURL.GetPayload(), getAzContainerClientOptions())
  127. if err != nil {
  128. return fs, fmt.Errorf("invalid credentials: %v", err)
  129. }
  130. fs.config.Container = parts.ContainerName
  131. fs.containerClient = svc
  132. return fs, nil
  133. }
  134. if fs.config.Container == "" {
  135. return fs, errors.New("container is required with this SAS URL")
  136. }
  137. sasURL := runtime.JoinPaths(fs.config.SASURL.GetPayload(), fs.config.Container)
  138. svc, err := container.NewClientWithNoCredential(sasURL, getAzContainerClientOptions())
  139. if err != nil {
  140. return fs, fmt.Errorf("invalid credentials: %v", err)
  141. }
  142. fs.containerClient = svc
  143. return fs, nil
  144. }
  145. // Name returns the name for the Fs implementation
  146. func (fs *AzureBlobFs) Name() string {
  147. if !fs.config.SASURL.IsEmpty() {
  148. return fmt.Sprintf("%s with SAS URL, container %q", azBlobFsName, fs.config.Container)
  149. }
  150. return fmt.Sprintf("%s container %q", azBlobFsName, fs.config.Container)
  151. }
  152. // ConnectionID returns the connection ID associated to this Fs implementation
  153. func (fs *AzureBlobFs) ConnectionID() string {
  154. return fs.connectionID
  155. }
  156. // Stat returns a FileInfo describing the named file
  157. func (fs *AzureBlobFs) Stat(name string) (os.FileInfo, error) {
  158. if name == "" || name == "/" || name == "." {
  159. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  160. }
  161. if fs.config.KeyPrefix == name+"/" {
  162. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  163. }
  164. attrs, err := fs.headObject(name)
  165. if err == nil {
  166. contentType := util.GetStringFromPointer(attrs.ContentType)
  167. isDir := contentType == dirMimeType
  168. if !isDir {
  169. for k, v := range attrs.Metadata {
  170. if strings.ToLower(k) == azFolderKey {
  171. isDir = (v == "true")
  172. break
  173. }
  174. }
  175. }
  176. metric.AZListObjectsCompleted(nil)
  177. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, isDir,
  178. util.GetIntFromPointer(attrs.ContentLength),
  179. util.GetTimeFromPointer(attrs.LastModified), false))
  180. }
  181. if !fs.IsNotExist(err) {
  182. return nil, err
  183. }
  184. // now check if this is a prefix (virtual directory)
  185. hasContents, err := fs.hasContents(name)
  186. if err != nil {
  187. return nil, err
  188. }
  189. if hasContents {
  190. return updateFileInfoModTime(fs.getStorageID(), name, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  191. }
  192. return nil, os.ErrNotExist
  193. }
  194. // Lstat returns a FileInfo describing the named file
  195. func (fs *AzureBlobFs) Lstat(name string) (os.FileInfo, error) {
  196. return fs.Stat(name)
  197. }
  198. // Open opens the named file for reading
  199. func (fs *AzureBlobFs) Open(name string, offset int64) (File, *pipeat.PipeReaderAt, func(), error) {
  200. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  201. if err != nil {
  202. return nil, nil, nil, err
  203. }
  204. ctx, cancelFn := context.WithCancel(context.Background())
  205. go func() {
  206. defer cancelFn()
  207. blockBlob := fs.containerClient.NewBlockBlobClient(url.PathEscape(name))
  208. err := fs.handleMultipartDownload(ctx, blockBlob, offset, w)
  209. w.CloseWithError(err) //nolint:errcheck
  210. fsLog(fs, logger.LevelDebug, "download completed, path: %#v size: %v, err: %+v", name, w.GetWrittenBytes(), err)
  211. metric.AZTransferCompleted(w.GetWrittenBytes(), 1, err)
  212. }()
  213. return nil, r, cancelFn, nil
  214. }
  215. // Create creates or opens the named file for writing
  216. func (fs *AzureBlobFs) Create(name string, flag int) (File, *PipeWriter, func(), error) {
  217. r, w, err := pipeat.PipeInDir(fs.localTempDir)
  218. if err != nil {
  219. return nil, nil, nil, err
  220. }
  221. ctx, cancelFn := context.WithCancel(context.Background())
  222. p := NewPipeWriter(w)
  223. headers := blob.HTTPHeaders{}
  224. var contentType string
  225. var metadata map[string]string
  226. if flag == -1 {
  227. contentType = dirMimeType
  228. metadata = map[string]string{
  229. azFolderKey: "true",
  230. }
  231. } else {
  232. contentType = mime.TypeByExtension(path.Ext(name))
  233. }
  234. if contentType != "" {
  235. headers.BlobContentType = &contentType
  236. }
  237. go func() {
  238. defer cancelFn()
  239. blockBlob := fs.containerClient.NewBlockBlobClient(url.PathEscape(name))
  240. err := fs.handleMultipartUpload(ctx, r, blockBlob, &headers, metadata)
  241. r.CloseWithError(err) //nolint:errcheck
  242. p.Done(err)
  243. fsLog(fs, logger.LevelDebug, "upload completed, path: %#v, readed bytes: %v, err: %+v", name, r.GetReadedBytes(), err)
  244. metric.AZTransferCompleted(r.GetReadedBytes(), 0, err)
  245. }()
  246. return nil, p, cancelFn, nil
  247. }
  248. // Rename renames (moves) source to target.
  249. // We don't support renaming non empty directories since we should
  250. // rename all the contents too and this could take long time: think
  251. // about directories with thousands of files, for each file we should
  252. // execute a StartCopyFromURL call.
  253. func (fs *AzureBlobFs) Rename(source, target string) error {
  254. if source == target {
  255. return nil
  256. }
  257. fi, err := fs.Stat(source)
  258. if err != nil {
  259. return err
  260. }
  261. if fi.IsDir() {
  262. hasContents, err := fs.hasContents(source)
  263. if err != nil {
  264. return err
  265. }
  266. if hasContents {
  267. return fmt.Errorf("cannot rename non empty directory: %#v", source)
  268. }
  269. if err := fs.mkdirInternal(target); err != nil {
  270. return err
  271. }
  272. } else {
  273. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxLongTimeout))
  274. defer cancelFn()
  275. srcBlob := fs.containerClient.NewBlockBlobClient(url.PathEscape(source))
  276. dstBlob := fs.containerClient.NewBlockBlobClient(url.PathEscape(target))
  277. resp, err := dstBlob.StartCopyFromURL(ctx, srcBlob.URL(), fs.getCopyOptions())
  278. if err != nil {
  279. metric.AZCopyObjectCompleted(err)
  280. return err
  281. }
  282. copyStatus := blob.CopyStatusType(util.GetStringFromPointer((*string)(resp.CopyStatus)))
  283. nErrors := 0
  284. for copyStatus == blob.CopyStatusTypePending {
  285. // Poll until the copy is complete.
  286. time.Sleep(500 * time.Millisecond)
  287. resp, err := dstBlob.GetProperties(ctx, &blob.GetPropertiesOptions{})
  288. if err != nil {
  289. // A GetProperties failure may be transient, so allow a couple
  290. // of them before giving up.
  291. nErrors++
  292. if ctx.Err() != nil || nErrors == 3 {
  293. metric.AZCopyObjectCompleted(err)
  294. return err
  295. }
  296. } else {
  297. copyStatus = blob.CopyStatusType(util.GetStringFromPointer((*string)(resp.CopyStatus)))
  298. }
  299. }
  300. if copyStatus != blob.CopyStatusTypeSuccess {
  301. err := fmt.Errorf("copy failed with status: %s", copyStatus)
  302. metric.AZCopyObjectCompleted(err)
  303. return err
  304. }
  305. metric.AZCopyObjectCompleted(nil)
  306. fs.preserveModificationTime(source, target, fi)
  307. }
  308. return fs.Remove(source, fi.IsDir())
  309. }
  310. // Remove removes the named file or (empty) directory.
  311. func (fs *AzureBlobFs) Remove(name string, isDir bool) error {
  312. if isDir {
  313. hasContents, err := fs.hasContents(name)
  314. if err != nil {
  315. return err
  316. }
  317. if hasContents {
  318. return fmt.Errorf("cannot remove non empty directory: %#v", name)
  319. }
  320. }
  321. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  322. defer cancelFn()
  323. blobBlock := fs.containerClient.NewBlockBlobClient(url.PathEscape(name))
  324. var deletSnapshots blob.DeleteSnapshotsOptionType
  325. if !isDir {
  326. deletSnapshots = blob.DeleteSnapshotsOptionTypeInclude
  327. }
  328. _, err := blobBlock.Delete(ctx, &blob.DeleteOptions{
  329. DeleteSnapshots: &deletSnapshots,
  330. })
  331. if err != nil && isDir {
  332. if fs.isBadRequestError(err) {
  333. deletSnapshots = blob.DeleteSnapshotsOptionTypeInclude
  334. _, err = blobBlock.Delete(ctx, &blob.DeleteOptions{
  335. DeleteSnapshots: &deletSnapshots,
  336. })
  337. }
  338. }
  339. metric.AZDeleteObjectCompleted(err)
  340. if plugin.Handler.HasMetadater() && err == nil && !isDir {
  341. if errMetadata := plugin.Handler.RemoveMetadata(fs.getStorageID(), ensureAbsPath(name)); errMetadata != nil {
  342. fsLog(fs, logger.LevelWarn, "unable to remove metadata for path %#v: %+v", name, errMetadata)
  343. }
  344. }
  345. return err
  346. }
  347. // Mkdir creates a new directory with the specified name and default permissions
  348. func (fs *AzureBlobFs) Mkdir(name string) error {
  349. _, err := fs.Stat(name)
  350. if !fs.IsNotExist(err) {
  351. return err
  352. }
  353. return fs.mkdirInternal(name)
  354. }
  355. // Symlink creates source as a symbolic link to target.
  356. func (*AzureBlobFs) Symlink(source, target string) error {
  357. return ErrVfsUnsupported
  358. }
  359. // Readlink returns the destination of the named symbolic link
  360. func (*AzureBlobFs) Readlink(name string) (string, error) {
  361. return "", ErrVfsUnsupported
  362. }
  363. // Chown changes the numeric uid and gid of the named file.
  364. func (*AzureBlobFs) Chown(name string, uid int, gid int) error {
  365. return ErrVfsUnsupported
  366. }
  367. // Chmod changes the mode of the named file to mode.
  368. func (*AzureBlobFs) Chmod(name string, mode os.FileMode) error {
  369. return ErrVfsUnsupported
  370. }
  371. // Chtimes changes the access and modification times of the named file.
  372. func (fs *AzureBlobFs) Chtimes(name string, atime, mtime time.Time, isUploading bool) error {
  373. if !plugin.Handler.HasMetadater() {
  374. return ErrVfsUnsupported
  375. }
  376. if !isUploading {
  377. info, err := fs.Stat(name)
  378. if err != nil {
  379. return err
  380. }
  381. if info.IsDir() {
  382. return ErrVfsUnsupported
  383. }
  384. }
  385. return plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(name),
  386. util.GetTimeAsMsSinceEpoch(mtime))
  387. }
  388. // Truncate changes the size of the named file.
  389. // Truncate by path is not supported, while truncating an opened
  390. // file is handled inside base transfer
  391. func (*AzureBlobFs) Truncate(name string, size int64) error {
  392. return ErrVfsUnsupported
  393. }
  394. // ReadDir reads the directory named by dirname and returns
  395. // a list of directory entries.
  396. func (fs *AzureBlobFs) ReadDir(dirname string) ([]os.FileInfo, error) {
  397. var result []os.FileInfo
  398. // dirname must be already cleaned
  399. prefix := fs.getPrefix(dirname)
  400. modTimes, err := getFolderModTimes(fs.getStorageID(), dirname)
  401. if err != nil {
  402. return result, err
  403. }
  404. prefixes := make(map[string]bool)
  405. pager := fs.containerClient.NewListBlobsHierarchyPager("/", &container.ListBlobsHierarchyOptions{
  406. Include: container.ListBlobsInclude{
  407. //Metadata: true,
  408. },
  409. Prefix: &prefix,
  410. })
  411. for pager.More() {
  412. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  413. defer cancelFn()
  414. resp, err := pager.NextPage(ctx)
  415. if err != nil {
  416. metric.AZListObjectsCompleted(err)
  417. return result, err
  418. }
  419. for _, blobPrefix := range resp.ListBlobsHierarchySegmentResponse.Segment.BlobPrefixes {
  420. name := util.GetStringFromPointer(blobPrefix.Name)
  421. // we don't support prefixes == "/" this will be sent if a key starts with "/"
  422. if name == "" || name == "/" {
  423. continue
  424. }
  425. // sometime we have duplicate prefixes, maybe an Azurite bug
  426. name = strings.TrimPrefix(name, prefix)
  427. if _, ok := prefixes[strings.TrimSuffix(name, "/")]; ok {
  428. continue
  429. }
  430. result = append(result, NewFileInfo(name, true, 0, time.Unix(0, 0), false))
  431. prefixes[strings.TrimSuffix(name, "/")] = true
  432. }
  433. for _, blobItem := range resp.ListBlobsHierarchySegmentResponse.Segment.BlobItems {
  434. name := util.GetStringFromPointer(blobItem.Name)
  435. name = strings.TrimPrefix(name, prefix)
  436. size := int64(0)
  437. isDir := false
  438. modTime := time.Unix(0, 0)
  439. if blobItem.Properties != nil {
  440. size = util.GetIntFromPointer(blobItem.Properties.ContentLength)
  441. modTime = util.GetTimeFromPointer(blobItem.Properties.LastModified)
  442. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  443. isDir = checkDirectoryMarkers(contentType, blobItem.Metadata)
  444. if isDir {
  445. // check if the dir is already included, it will be sent as blob prefix if it contains at least one item
  446. if _, ok := prefixes[name]; ok {
  447. continue
  448. }
  449. prefixes[name] = true
  450. }
  451. }
  452. if t, ok := modTimes[name]; ok {
  453. modTime = util.GetTimeFromMsecSinceEpoch(t)
  454. }
  455. result = append(result, NewFileInfo(name, isDir, size, modTime, false))
  456. }
  457. }
  458. metric.AZListObjectsCompleted(nil)
  459. return result, nil
  460. }
  461. // IsUploadResumeSupported returns true if resuming uploads is supported.
  462. // Resuming uploads is not supported on Azure Blob
  463. func (*AzureBlobFs) IsUploadResumeSupported() bool {
  464. return false
  465. }
  466. // IsAtomicUploadSupported returns true if atomic upload is supported.
  467. // Azure Blob uploads are already atomic, we don't need to upload to a temporary
  468. // file
  469. func (*AzureBlobFs) IsAtomicUploadSupported() bool {
  470. return false
  471. }
  472. // IsNotExist returns a boolean indicating whether the error is known to
  473. // report that a file or directory does not exist
  474. func (*AzureBlobFs) IsNotExist(err error) bool {
  475. if err == nil {
  476. return false
  477. }
  478. var respErr *azcore.ResponseError
  479. if errors.As(err, &respErr) {
  480. return respErr.StatusCode == http.StatusNotFound
  481. }
  482. // os.ErrNotExist can be returned internally by fs.Stat
  483. return errors.Is(err, os.ErrNotExist)
  484. }
  485. // IsPermission returns a boolean indicating whether the error is known to
  486. // report that permission is denied.
  487. func (*AzureBlobFs) IsPermission(err error) bool {
  488. if err == nil {
  489. return false
  490. }
  491. var respErr *azcore.ResponseError
  492. if errors.As(err, &respErr) {
  493. return respErr.StatusCode == http.StatusForbidden || respErr.StatusCode == http.StatusUnauthorized
  494. }
  495. return false
  496. }
  497. // IsNotSupported returns true if the error indicate an unsupported operation
  498. func (*AzureBlobFs) IsNotSupported(err error) bool {
  499. if err == nil {
  500. return false
  501. }
  502. return err == ErrVfsUnsupported
  503. }
  504. func (*AzureBlobFs) isBadRequestError(err error) bool {
  505. if err == nil {
  506. return false
  507. }
  508. var respErr *azcore.ResponseError
  509. if errors.As(err, &respErr) {
  510. return respErr.StatusCode == http.StatusBadRequest
  511. }
  512. return false
  513. }
  514. // CheckRootPath creates the specified local root directory if it does not exists
  515. func (fs *AzureBlobFs) CheckRootPath(username string, uid int, gid int) bool {
  516. // we need a local directory for temporary files
  517. osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "")
  518. return osFs.CheckRootPath(username, uid, gid)
  519. }
  520. // ScanRootDirContents returns the number of files contained in the bucket,
  521. // and their size
  522. func (fs *AzureBlobFs) ScanRootDirContents() (int, int64, error) {
  523. numFiles := 0
  524. size := int64(0)
  525. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  526. Include: container.ListBlobsInclude{
  527. Metadata: true,
  528. },
  529. Prefix: &fs.config.KeyPrefix,
  530. })
  531. for pager.More() {
  532. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  533. defer cancelFn()
  534. resp, err := pager.NextPage(ctx)
  535. if err != nil {
  536. metric.AZListObjectsCompleted(err)
  537. return numFiles, size, err
  538. }
  539. for _, blobItem := range resp.ListBlobsFlatSegmentResponse.Segment.BlobItems {
  540. if blobItem.Properties != nil {
  541. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  542. isDir := checkDirectoryMarkers(contentType, blobItem.Metadata)
  543. blobSize := util.GetIntFromPointer(blobItem.Properties.ContentLength)
  544. if isDir && blobSize == 0 {
  545. continue
  546. }
  547. numFiles++
  548. size += blobSize
  549. if numFiles%1000 == 0 {
  550. fsLog(fs, logger.LevelDebug, "root dir scan in progress, files: %d, size: %d", numFiles, size)
  551. }
  552. }
  553. }
  554. }
  555. metric.AZListObjectsCompleted(nil)
  556. return numFiles, size, nil
  557. }
  558. func (fs *AzureBlobFs) getFileNamesInPrefix(fsPrefix string) (map[string]bool, error) {
  559. fileNames := make(map[string]bool)
  560. prefix := ""
  561. if fsPrefix != "/" {
  562. prefix = strings.TrimPrefix(fsPrefix, "/")
  563. }
  564. pager := fs.containerClient.NewListBlobsHierarchyPager("/", &container.ListBlobsHierarchyOptions{
  565. Include: container.ListBlobsInclude{
  566. //Metadata: true,
  567. },
  568. Prefix: &prefix,
  569. })
  570. for pager.More() {
  571. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  572. defer cancelFn()
  573. resp, err := pager.NextPage(ctx)
  574. if err != nil {
  575. metric.AZListObjectsCompleted(err)
  576. return fileNames, err
  577. }
  578. for _, blobItem := range resp.ListBlobsHierarchySegmentResponse.Segment.BlobItems {
  579. name := util.GetStringFromPointer(blobItem.Name)
  580. name = strings.TrimPrefix(name, prefix)
  581. if blobItem.Properties != nil {
  582. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  583. isDir := checkDirectoryMarkers(contentType, blobItem.Metadata)
  584. if isDir {
  585. continue
  586. }
  587. fileNames[name] = true
  588. }
  589. }
  590. }
  591. metric.AZListObjectsCompleted(nil)
  592. return fileNames, nil
  593. }
  594. // CheckMetadata checks the metadata consistency
  595. func (fs *AzureBlobFs) CheckMetadata() error {
  596. return fsMetadataCheck(fs, fs.getStorageID(), fs.config.KeyPrefix)
  597. }
  598. // GetDirSize returns the number of files and the size for a folder
  599. // including any subfolders
  600. func (*AzureBlobFs) GetDirSize(dirname string) (int, int64, error) {
  601. return 0, 0, ErrVfsUnsupported
  602. }
  603. // GetAtomicUploadPath returns the path to use for an atomic upload.
  604. // Azure Blob Storage uploads are already atomic, we never call this method
  605. func (*AzureBlobFs) GetAtomicUploadPath(name string) string {
  606. return ""
  607. }
  608. // GetRelativePath returns the path for a file relative to the user's home dir.
  609. // This is the path as seen by SFTPGo users
  610. func (fs *AzureBlobFs) GetRelativePath(name string) string {
  611. rel := path.Clean(name)
  612. if rel == "." {
  613. rel = ""
  614. }
  615. if !path.IsAbs(rel) {
  616. rel = "/" + rel
  617. }
  618. if fs.config.KeyPrefix != "" {
  619. if !strings.HasPrefix(rel, "/"+fs.config.KeyPrefix) {
  620. rel = "/"
  621. }
  622. rel = path.Clean("/" + strings.TrimPrefix(rel, "/"+fs.config.KeyPrefix))
  623. }
  624. if fs.mountPath != "" {
  625. rel = path.Join(fs.mountPath, rel)
  626. }
  627. return rel
  628. }
  629. // Walk walks the file tree rooted at root, calling walkFn for each file or
  630. // directory in the tree, including root
  631. func (fs *AzureBlobFs) Walk(root string, walkFn filepath.WalkFunc) error {
  632. prefix := fs.getPrefix(root)
  633. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  634. Include: container.ListBlobsInclude{
  635. Metadata: true,
  636. },
  637. Prefix: &prefix,
  638. })
  639. for pager.More() {
  640. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  641. defer cancelFn()
  642. resp, err := pager.NextPage(ctx)
  643. if err != nil {
  644. metric.AZListObjectsCompleted(err)
  645. return err
  646. }
  647. for _, blobItem := range resp.ListBlobsFlatSegmentResponse.Segment.BlobItems {
  648. name := util.GetStringFromPointer(blobItem.Name)
  649. if fs.isEqual(name, prefix) {
  650. continue
  651. }
  652. blobSize := int64(0)
  653. lastModified := time.Unix(0, 0)
  654. isDir := false
  655. if blobItem.Properties != nil {
  656. contentType := util.GetStringFromPointer(blobItem.Properties.ContentType)
  657. isDir = checkDirectoryMarkers(contentType, blobItem.Metadata)
  658. blobSize = util.GetIntFromPointer(blobItem.Properties.ContentLength)
  659. lastModified = util.GetTimeFromPointer(blobItem.Properties.LastModified)
  660. }
  661. err := walkFn(name, NewFileInfo(name, isDir, blobSize, lastModified, false), nil)
  662. if err != nil {
  663. return err
  664. }
  665. }
  666. }
  667. metric.AZListObjectsCompleted(nil)
  668. return walkFn(root, NewFileInfo(root, true, 0, time.Unix(0, 0), false), nil)
  669. }
  670. // Join joins any number of path elements into a single path
  671. func (*AzureBlobFs) Join(elem ...string) string {
  672. return strings.TrimPrefix(path.Join(elem...), "/")
  673. }
  674. // HasVirtualFolders returns true if folders are emulated
  675. func (*AzureBlobFs) HasVirtualFolders() bool {
  676. return true
  677. }
  678. // ResolvePath returns the matching filesystem path for the specified sftp path
  679. func (fs *AzureBlobFs) ResolvePath(virtualPath string) (string, error) {
  680. if fs.mountPath != "" {
  681. virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
  682. }
  683. if !path.IsAbs(virtualPath) {
  684. virtualPath = path.Clean("/" + virtualPath)
  685. }
  686. return fs.Join(fs.config.KeyPrefix, strings.TrimPrefix(virtualPath, "/")), nil
  687. }
  688. func (fs *AzureBlobFs) headObject(name string) (blob.GetPropertiesResponse, error) {
  689. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  690. defer cancelFn()
  691. resp, err := fs.containerClient.NewBlockBlobClient(url.PathEscape(name)).GetProperties(ctx, &blob.GetPropertiesOptions{})
  692. metric.AZHeadObjectCompleted(err)
  693. return resp, err
  694. }
  695. // GetMimeType returns the content type
  696. func (fs *AzureBlobFs) GetMimeType(name string) (string, error) {
  697. response, err := fs.headObject(name)
  698. if err != nil {
  699. return "", err
  700. }
  701. return util.GetStringFromPointer(response.ContentType), nil
  702. }
  703. // Close closes the fs
  704. func (*AzureBlobFs) Close() error {
  705. return nil
  706. }
  707. // GetAvailableDiskSize returns the available size for the specified path
  708. func (*AzureBlobFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
  709. return nil, ErrStorageSizeUnavailable
  710. }
  711. func (*AzureBlobFs) getPrefix(name string) string {
  712. prefix := ""
  713. if name != "" && name != "." {
  714. prefix = strings.TrimPrefix(name, "/")
  715. if !strings.HasSuffix(prefix, "/") {
  716. prefix += "/"
  717. }
  718. }
  719. return prefix
  720. }
  721. func (fs *AzureBlobFs) isEqual(key string, virtualName string) bool {
  722. if key == virtualName {
  723. return true
  724. }
  725. if key == virtualName+"/" {
  726. return true
  727. }
  728. if key+"/" == virtualName {
  729. return true
  730. }
  731. return false
  732. }
  733. func (fs *AzureBlobFs) setConfigDefaults() {
  734. if fs.config.Endpoint == "" {
  735. fs.config.Endpoint = azureDefaultEndpoint
  736. }
  737. if fs.config.UploadPartSize == 0 {
  738. fs.config.UploadPartSize = 5
  739. }
  740. if fs.config.UploadPartSize < 1024*1024 {
  741. fs.config.UploadPartSize *= 1024 * 1024
  742. }
  743. if fs.config.UploadConcurrency == 0 {
  744. fs.config.UploadConcurrency = 5
  745. }
  746. if fs.config.DownloadPartSize == 0 {
  747. fs.config.DownloadPartSize = 5
  748. }
  749. if fs.config.DownloadPartSize < 1024*1024 {
  750. fs.config.DownloadPartSize *= 1024 * 1024
  751. }
  752. if fs.config.DownloadConcurrency == 0 {
  753. fs.config.DownloadConcurrency = 5
  754. }
  755. }
  756. func (fs *AzureBlobFs) mkdirInternal(name string) error {
  757. _, w, _, err := fs.Create(name, -1)
  758. if err != nil {
  759. return err
  760. }
  761. return w.Close()
  762. }
  763. func (fs *AzureBlobFs) hasContents(name string) (bool, error) {
  764. result := false
  765. prefix := fs.getPrefix(name)
  766. maxResults := int32(1)
  767. pager := fs.containerClient.NewListBlobsFlatPager(&container.ListBlobsFlatOptions{
  768. MaxResults: &maxResults,
  769. Prefix: &prefix,
  770. })
  771. if pager.More() {
  772. ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(fs.ctxTimeout))
  773. defer cancelFn()
  774. resp, err := pager.NextPage(ctx)
  775. if err != nil {
  776. metric.AZListObjectsCompleted(err)
  777. return result, err
  778. }
  779. result = len(resp.ListBlobsFlatSegmentResponse.Segment.BlobItems) > 0
  780. }
  781. metric.AZListObjectsCompleted(nil)
  782. return result, nil
  783. }
  784. func (fs *AzureBlobFs) downloadPart(ctx context.Context, blockBlob *blockblob.Client, buf []byte,
  785. w io.WriterAt, offset, count, writeOffset int64,
  786. ) error {
  787. if count == 0 {
  788. return nil
  789. }
  790. resp, err := blockBlob.DownloadStream(ctx, &blob.DownloadStreamOptions{
  791. Range: blob.HTTPRange{
  792. Offset: offset,
  793. Count: count,
  794. },
  795. })
  796. if err != nil {
  797. return err
  798. }
  799. defer resp.BlobClientDownloadResponse.Body.Close()
  800. _, err = io.ReadAtLeast(resp.BlobClientDownloadResponse.Body, buf, int(count))
  801. if err != nil {
  802. return err
  803. }
  804. _, err = fs.writeAtFull(w, buf, writeOffset, int(count))
  805. return err
  806. }
  807. func (fs *AzureBlobFs) handleMultipartDownload(ctx context.Context, blockBlob *blockblob.Client,
  808. offset int64, writer io.WriterAt,
  809. ) error {
  810. props, err := blockBlob.GetProperties(ctx, &blob.GetPropertiesOptions{})
  811. if err != nil {
  812. fsLog(fs, logger.LevelError, "unable to get blob properties, download aborted: %+v", err)
  813. return err
  814. }
  815. contentLength := util.GetIntFromPointer(props.ContentLength)
  816. sizeToDownload := contentLength - offset
  817. if sizeToDownload < 0 {
  818. fsLog(fs, logger.LevelError, "invalid multipart download size or offset, size: %v, offset: %v, size to download: %v",
  819. contentLength, offset, sizeToDownload)
  820. return errors.New("the requested offset exceeds the file size")
  821. }
  822. if sizeToDownload == 0 {
  823. fsLog(fs, logger.LevelDebug, "nothing to download, offset %v, content length %v", offset, contentLength)
  824. return nil
  825. }
  826. partSize := fs.config.DownloadPartSize
  827. guard := make(chan struct{}, fs.config.DownloadConcurrency)
  828. blockCtxTimeout := time.Duration(fs.config.DownloadPartSize/(1024*1024)) * time.Minute
  829. pool := newBufferAllocator(int(partSize))
  830. finished := false
  831. var wg sync.WaitGroup
  832. var errOnce sync.Once
  833. var hasError atomic.Bool
  834. var poolError error
  835. poolCtx, poolCancel := context.WithCancel(ctx)
  836. defer poolCancel()
  837. for part := 0; !finished; part++ {
  838. start := offset
  839. end := offset + partSize
  840. if end >= contentLength {
  841. end = contentLength
  842. finished = true
  843. }
  844. writeOffset := int64(part) * partSize
  845. offset = end
  846. guard <- struct{}{}
  847. if hasError.Load() {
  848. fsLog(fs, logger.LevelDebug, "pool error, download for part %v not started", part)
  849. break
  850. }
  851. buf := pool.getBuffer()
  852. wg.Add(1)
  853. go func(start, end, writeOffset int64, buf []byte) {
  854. defer func() {
  855. pool.releaseBuffer(buf)
  856. <-guard
  857. wg.Done()
  858. }()
  859. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  860. defer cancelFn()
  861. count := end - start
  862. err := fs.downloadPart(innerCtx, blockBlob, buf, writer, start, count, writeOffset)
  863. if err != nil {
  864. errOnce.Do(func() {
  865. fsLog(fs, logger.LevelError, "multipart download error: %+v", err)
  866. hasError.Store(true)
  867. poolError = fmt.Errorf("multipart download error: %w", err)
  868. poolCancel()
  869. })
  870. }
  871. }(start, end, writeOffset, buf)
  872. }
  873. wg.Wait()
  874. close(guard)
  875. pool.free()
  876. return poolError
  877. }
  878. func (fs *AzureBlobFs) handleMultipartUpload(ctx context.Context, reader io.Reader,
  879. blockBlob *blockblob.Client, httpHeaders *blob.HTTPHeaders, metadata map[string]string,
  880. ) error {
  881. partSize := fs.config.UploadPartSize
  882. guard := make(chan struct{}, fs.config.UploadConcurrency)
  883. blockCtxTimeout := time.Duration(fs.config.UploadPartSize/(1024*1024)) * time.Minute
  884. // sync.Pool seems to use a lot of memory so prefer our own, very simple, allocator
  885. // we only need to recycle few byte slices
  886. pool := newBufferAllocator(int(partSize))
  887. finished := false
  888. var blocks []string
  889. var wg sync.WaitGroup
  890. var errOnce sync.Once
  891. var hasError atomic.Bool
  892. var poolError error
  893. poolCtx, poolCancel := context.WithCancel(ctx)
  894. defer poolCancel()
  895. for part := 0; !finished; part++ {
  896. buf := pool.getBuffer()
  897. n, err := fs.readFill(reader, buf)
  898. if err == io.EOF {
  899. // read finished, if n > 0 we need to process the last data chunck
  900. if n == 0 {
  901. pool.releaseBuffer(buf)
  902. break
  903. }
  904. finished = true
  905. } else if err != nil {
  906. pool.releaseBuffer(buf)
  907. pool.free()
  908. return err
  909. }
  910. // Block IDs are unique values to avoid issue if 2+ clients are uploading blocks
  911. // at the same time causing CommitBlockList to get a mix of blocks from all the clients.
  912. generatedUUID, err := uuid.NewRandom()
  913. if err != nil {
  914. pool.releaseBuffer(buf)
  915. pool.free()
  916. return fmt.Errorf("unable to generate block ID: %w", err)
  917. }
  918. blockID := base64.StdEncoding.EncodeToString([]byte(generatedUUID.String()))
  919. blocks = append(blocks, blockID)
  920. guard <- struct{}{}
  921. if hasError.Load() {
  922. fsLog(fs, logger.LevelError, "pool error, upload for part %d not started", part)
  923. pool.releaseBuffer(buf)
  924. break
  925. }
  926. wg.Add(1)
  927. go func(blockID string, buf []byte, bufSize int) {
  928. defer func() {
  929. pool.releaseBuffer(buf)
  930. <-guard
  931. wg.Done()
  932. }()
  933. bufferReader := &bytesReaderWrapper{
  934. Reader: bytes.NewReader(buf[:bufSize]),
  935. }
  936. innerCtx, cancelFn := context.WithDeadline(poolCtx, time.Now().Add(blockCtxTimeout))
  937. defer cancelFn()
  938. _, err := blockBlob.StageBlock(innerCtx, blockID, bufferReader, &blockblob.StageBlockOptions{})
  939. if err != nil {
  940. errOnce.Do(func() {
  941. fsLog(fs, logger.LevelDebug, "multipart upload error: %+v", err)
  942. hasError.Store(true)
  943. poolError = fmt.Errorf("multipart upload error: %w", err)
  944. poolCancel()
  945. })
  946. }
  947. }(blockID, buf, n)
  948. }
  949. wg.Wait()
  950. close(guard)
  951. pool.free()
  952. if poolError != nil {
  953. return poolError
  954. }
  955. commitOptions := blockblob.CommitBlockListOptions{
  956. HTTPHeaders: httpHeaders,
  957. Metadata: metadata,
  958. }
  959. if fs.config.AccessTier != "" {
  960. commitOptions.Tier = (*blob.AccessTier)(&fs.config.AccessTier)
  961. }
  962. _, err := blockBlob.CommitBlockList(ctx, blocks, &commitOptions)
  963. return err
  964. }
  965. func (*AzureBlobFs) writeAtFull(w io.WriterAt, buf []byte, offset int64, count int) (int, error) {
  966. written := 0
  967. for written < count {
  968. n, err := w.WriteAt(buf[written:count], offset+int64(written))
  969. written += n
  970. if err != nil {
  971. return written, err
  972. }
  973. }
  974. return written, nil
  975. }
  976. // copied from rclone
  977. func (*AzureBlobFs) readFill(r io.Reader, buf []byte) (n int, err error) {
  978. var nn int
  979. for n < len(buf) && err == nil {
  980. nn, err = r.Read(buf[n:])
  981. n += nn
  982. }
  983. return n, err
  984. }
  985. func (fs *AzureBlobFs) preserveModificationTime(source, target string, fi os.FileInfo) {
  986. if plugin.Handler.HasMetadater() {
  987. if !fi.IsDir() {
  988. err := plugin.Handler.SetModificationTime(fs.getStorageID(), ensureAbsPath(target),
  989. util.GetTimeAsMsSinceEpoch(fi.ModTime()))
  990. if err != nil {
  991. fsLog(fs, logger.LevelWarn, "unable to preserve modification time after renaming %#v -> %#v: %+v",
  992. source, target, err)
  993. }
  994. }
  995. }
  996. }
  997. func (fs *AzureBlobFs) getCopyOptions() *blob.StartCopyFromURLOptions {
  998. copyOptions := &blob.StartCopyFromURLOptions{}
  999. if fs.config.AccessTier != "" {
  1000. copyOptions.Tier = (*blob.AccessTier)(&fs.config.AccessTier)
  1001. }
  1002. return copyOptions
  1003. }
  1004. func (fs *AzureBlobFs) getStorageID() string {
  1005. if fs.config.Endpoint != "" {
  1006. if !strings.HasSuffix(fs.config.Endpoint, "/") {
  1007. return fmt.Sprintf("azblob://%v/%v", fs.config.Endpoint, fs.config.Container)
  1008. }
  1009. return fmt.Sprintf("azblob://%v%v", fs.config.Endpoint, fs.config.Container)
  1010. }
  1011. return fmt.Sprintf("azblob://%v", fs.config.Container)
  1012. }
  1013. func checkDirectoryMarkers(contentType string, metadata map[string]*string) bool {
  1014. if contentType == dirMimeType {
  1015. return true
  1016. }
  1017. for k, v := range metadata {
  1018. if strings.ToLower(k) == azFolderKey {
  1019. return util.GetStringFromPointer(v) == "true"
  1020. }
  1021. }
  1022. return false
  1023. }
  1024. func getAzContainerClientOptions() *container.ClientOptions {
  1025. version := version.Get()
  1026. return &container.ClientOptions{
  1027. ClientOptions: azcore.ClientOptions{
  1028. Telemetry: policy.TelemetryOptions{
  1029. ApplicationID: fmt.Sprintf("SFTPGo-%v_%v", version.Version, version.CommitHash),
  1030. },
  1031. },
  1032. }
  1033. }
  1034. type bytesReaderWrapper struct {
  1035. *bytes.Reader
  1036. }
  1037. func (b *bytesReaderWrapper) Close() error {
  1038. return nil
  1039. }
  1040. type bufferAllocator struct {
  1041. sync.Mutex
  1042. available [][]byte
  1043. bufferSize int
  1044. finalized bool
  1045. }
  1046. func newBufferAllocator(size int) *bufferAllocator {
  1047. return &bufferAllocator{
  1048. bufferSize: size,
  1049. finalized: false,
  1050. }
  1051. }
  1052. func (b *bufferAllocator) getBuffer() []byte {
  1053. b.Lock()
  1054. defer b.Unlock()
  1055. if len(b.available) > 0 {
  1056. var result []byte
  1057. truncLength := len(b.available) - 1
  1058. result = b.available[truncLength]
  1059. b.available[truncLength] = nil
  1060. b.available = b.available[:truncLength]
  1061. return result
  1062. }
  1063. return make([]byte, b.bufferSize)
  1064. }
  1065. func (b *bufferAllocator) releaseBuffer(buf []byte) {
  1066. b.Lock()
  1067. defer b.Unlock()
  1068. if b.finalized || len(buf) != b.bufferSize {
  1069. return
  1070. }
  1071. b.available = append(b.available, buf)
  1072. }
  1073. func (b *bufferAllocator) free() {
  1074. b.Lock()
  1075. defer b.Unlock()
  1076. b.available = nil
  1077. b.finalized = true
  1078. }