azblobfs.go 34 KB

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