s3api_object_handlers_list.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. package s3api
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "github.com/aws/aws-sdk-go/service/s3"
  12. "github.com/seaweedfs/seaweedfs/weed/glog"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  15. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  16. )
  17. type OptionalString struct {
  18. string
  19. set bool
  20. }
  21. func (o OptionalString) MarshalXML(e *xml.Encoder, startElement xml.StartElement) error {
  22. if !o.set {
  23. return nil
  24. }
  25. return e.EncodeElement(o.string, startElement)
  26. }
  27. type ListBucketResultV2 struct {
  28. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
  29. Name string `xml:"Name"`
  30. Prefix string `xml:"Prefix"`
  31. MaxKeys uint16 `xml:"MaxKeys"`
  32. Delimiter string `xml:"Delimiter,omitempty"`
  33. IsTruncated bool `xml:"IsTruncated"`
  34. Contents []ListEntry `xml:"Contents,omitempty"`
  35. CommonPrefixes []PrefixEntry `xml:"CommonPrefixes,omitempty"`
  36. ContinuationToken OptionalString `xml:"ContinuationToken,omitempty"`
  37. NextContinuationToken string `xml:"NextContinuationToken,omitempty"`
  38. EncodingType string `xml:"EncodingType,omitempty"`
  39. KeyCount int `xml:"KeyCount"`
  40. StartAfter string `xml:"StartAfter,omitempty"`
  41. }
  42. func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Request) {
  43. // https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html
  44. // collect parameters
  45. bucket, _ := s3_constants.GetBucketAndObject(r)
  46. glog.V(3).Infof("ListObjectsV2Handler %s", bucket)
  47. originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys, allowUnordered, errCode := getListObjectsV2Args(r.URL.Query())
  48. if errCode != s3err.ErrNone {
  49. s3err.WriteErrorResponse(w, r, errCode)
  50. return
  51. }
  52. if maxKeys < 0 {
  53. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  54. return
  55. }
  56. // AWS S3 compatibility: allow-unordered cannot be used with delimiter
  57. if allowUnordered && delimiter != "" {
  58. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidUnorderedWithDelimiter)
  59. return
  60. }
  61. marker := continuationToken.string
  62. if !continuationToken.set {
  63. marker = startAfter
  64. }
  65. // Adjust marker if it ends with delimiter to skip all entries with that prefix
  66. marker = adjustMarkerForDelimiter(marker, delimiter)
  67. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
  68. if err != nil {
  69. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  70. return
  71. }
  72. if len(response.Contents) == 0 {
  73. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  74. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  75. return
  76. }
  77. }
  78. responseV2 := &ListBucketResultV2{
  79. Name: response.Name,
  80. CommonPrefixes: response.CommonPrefixes,
  81. Contents: response.Contents,
  82. ContinuationToken: continuationToken,
  83. Delimiter: response.Delimiter,
  84. IsTruncated: response.IsTruncated,
  85. KeyCount: len(response.Contents) + len(response.CommonPrefixes),
  86. MaxKeys: uint16(response.MaxKeys),
  87. NextContinuationToken: response.NextMarker,
  88. Prefix: response.Prefix,
  89. StartAfter: startAfter,
  90. }
  91. if encodingTypeUrl {
  92. responseV2.EncodingType = s3.EncodingTypeUrl
  93. }
  94. writeSuccessResponseXML(w, r, responseV2)
  95. }
  96. func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Request) {
  97. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjects.html
  98. // collect parameters
  99. bucket, _ := s3_constants.GetBucketAndObject(r)
  100. glog.V(3).Infof("ListObjectsV1Handler %s", bucket)
  101. originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys, allowUnordered, errCode := getListObjectsV1Args(r.URL.Query())
  102. if errCode != s3err.ErrNone {
  103. s3err.WriteErrorResponse(w, r, errCode)
  104. return
  105. }
  106. if maxKeys < 0 {
  107. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  108. return
  109. }
  110. // AWS S3 compatibility: allow-unordered cannot be used with delimiter
  111. if allowUnordered && delimiter != "" {
  112. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidUnorderedWithDelimiter)
  113. return
  114. }
  115. // Adjust marker if it ends with delimiter to skip all entries with that prefix
  116. marker = adjustMarkerForDelimiter(marker, delimiter)
  117. response, err := s3a.listFilerEntries(bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
  118. if err != nil {
  119. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  120. return
  121. }
  122. if len(response.Contents) == 0 {
  123. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  124. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  125. return
  126. }
  127. }
  128. writeSuccessResponseXML(w, r, response)
  129. }
  130. func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
  131. // convert full path prefix into directory name and prefix for entry name
  132. requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
  133. bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
  134. reqDir := bucketPrefix[:len(bucketPrefix)-1]
  135. if requestDir != "" {
  136. reqDir = fmt.Sprintf("%s%s", bucketPrefix, requestDir)
  137. }
  138. var contents []ListEntry
  139. var commonPrefixes []PrefixEntry
  140. var doErr error
  141. var nextMarker string
  142. cursor := &ListingCursor{
  143. maxKeys: maxKeys,
  144. prefixEndsOnDelimiter: strings.HasSuffix(originalPrefix, "/") && len(originalMarker) == 0,
  145. }
  146. // Special case: when maxKeys = 0, return empty results immediately with IsTruncated=false
  147. if maxKeys == 0 {
  148. response = ListBucketResult{
  149. Name: bucket,
  150. Prefix: originalPrefix,
  151. Marker: originalMarker,
  152. NextMarker: "",
  153. MaxKeys: int(maxKeys),
  154. Delimiter: delimiter,
  155. IsTruncated: false,
  156. Contents: contents,
  157. CommonPrefixes: commonPrefixes,
  158. }
  159. if encodingTypeUrl {
  160. response.EncodingType = s3.EncodingTypeUrl
  161. }
  162. return
  163. }
  164. // check filer
  165. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  166. var lastEntryWasCommonPrefix bool
  167. var lastCommonPrefixName string
  168. for {
  169. empty := true
  170. nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, func(dir string, entry *filer_pb.Entry) {
  171. empty = false
  172. dirName, entryName, prefixName := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
  173. if entry.IsDirectory {
  174. // When delimiter is specified, apply delimiter logic to directory key objects too
  175. if delimiter != "" && entry.IsDirectoryKeyObject() {
  176. // Apply the same delimiter logic as for regular files
  177. var delimiterFound bool
  178. undelimitedPath := fmt.Sprintf("%s/%s/", dirName, entryName)[len(bucketPrefix):]
  179. // take into account a prefix if supplied while delimiting.
  180. undelimitedPath = strings.TrimPrefix(undelimitedPath, originalPrefix)
  181. delimitedPath := strings.SplitN(undelimitedPath, delimiter, 2)
  182. if len(delimitedPath) == 2 {
  183. // S3 clients expect the delimited prefix to contain the delimiter and prefix.
  184. delimitedPrefix := originalPrefix + delimitedPath[0] + delimiter
  185. for i := range commonPrefixes {
  186. if commonPrefixes[i].Prefix == delimitedPrefix {
  187. delimiterFound = true
  188. break
  189. }
  190. }
  191. if !delimiterFound {
  192. commonPrefixes = append(commonPrefixes, PrefixEntry{
  193. Prefix: delimitedPrefix,
  194. })
  195. cursor.maxKeys--
  196. delimiterFound = true
  197. lastEntryWasCommonPrefix = true
  198. lastCommonPrefixName = delimitedPath[0]
  199. } else {
  200. // This directory object belongs to an existing CommonPrefix, skip it
  201. delimiterFound = true
  202. }
  203. }
  204. // If no delimiter found in the directory object name, treat it as a regular key
  205. if !delimiterFound {
  206. contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, true, false, s3a.iam))
  207. cursor.maxKeys--
  208. lastEntryWasCommonPrefix = false
  209. }
  210. } else if entry.IsDirectoryKeyObject() {
  211. // No delimiter specified, or delimiter doesn't apply - treat as regular key
  212. contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, true, false, s3a.iam))
  213. cursor.maxKeys--
  214. lastEntryWasCommonPrefix = false
  215. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
  216. } else if delimiter == "/" { // A response can contain CommonPrefixes only if you specify a delimiter.
  217. commonPrefixes = append(commonPrefixes, PrefixEntry{
  218. Prefix: fmt.Sprintf("%s/%s/", dirName, prefixName)[len(bucketPrefix):],
  219. })
  220. //All of the keys (up to 1,000) rolled up into a common prefix count as a single return when calculating the number of returns.
  221. cursor.maxKeys--
  222. lastEntryWasCommonPrefix = true
  223. lastCommonPrefixName = entry.Name
  224. }
  225. } else {
  226. var delimiterFound bool
  227. if delimiter != "" {
  228. // keys that contain the same string between the prefix and the first occurrence of the delimiter are grouped together as a commonPrefix.
  229. // extract the string between the prefix and the delimiter and add it to the commonPrefixes if it's unique.
  230. undelimitedPath := fmt.Sprintf("%s/%s", dir, entry.Name)[len(bucketPrefix):]
  231. // take into account a prefix if supplied while delimiting.
  232. undelimitedPath = strings.TrimPrefix(undelimitedPath, originalPrefix)
  233. delimitedPath := strings.SplitN(undelimitedPath, delimiter, 2)
  234. if len(delimitedPath) == 2 {
  235. // S3 clients expect the delimited prefix to contain the delimiter and prefix.
  236. delimitedPrefix := originalPrefix + delimitedPath[0] + delimiter
  237. for i := range commonPrefixes {
  238. if commonPrefixes[i].Prefix == delimitedPrefix {
  239. delimiterFound = true
  240. break
  241. }
  242. }
  243. if !delimiterFound {
  244. commonPrefixes = append(commonPrefixes, PrefixEntry{
  245. Prefix: delimitedPrefix,
  246. })
  247. cursor.maxKeys--
  248. delimiterFound = true
  249. lastEntryWasCommonPrefix = true
  250. lastCommonPrefixName = delimitedPath[0]
  251. } else {
  252. // This object belongs to an existing CommonPrefix, skip it
  253. // but continue processing to maintain correct flow
  254. delimiterFound = true
  255. }
  256. }
  257. }
  258. if !delimiterFound {
  259. contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, false, false, s3a.iam))
  260. cursor.maxKeys--
  261. lastEntryWasCommonPrefix = false
  262. }
  263. }
  264. })
  265. if doErr != nil {
  266. return doErr
  267. }
  268. // Adjust nextMarker for CommonPrefixes to include trailing slash (AWS S3 compliance)
  269. if cursor.isTruncated && lastEntryWasCommonPrefix && lastCommonPrefixName != "" {
  270. // For CommonPrefixes, NextMarker should include the trailing slash
  271. if requestDir != "" {
  272. nextMarker = requestDir + "/" + lastCommonPrefixName + "/"
  273. } else {
  274. nextMarker = lastCommonPrefixName + "/"
  275. }
  276. } else if cursor.isTruncated {
  277. if requestDir != "" {
  278. nextMarker = requestDir + "/" + nextMarker
  279. }
  280. }
  281. if cursor.isTruncated {
  282. break
  283. } else if empty || strings.HasSuffix(originalPrefix, "/") {
  284. nextMarker = ""
  285. break
  286. } else {
  287. // start next loop
  288. marker = nextMarker
  289. }
  290. }
  291. response = ListBucketResult{
  292. Name: bucket,
  293. Prefix: originalPrefix,
  294. Marker: originalMarker,
  295. NextMarker: nextMarker,
  296. MaxKeys: int(maxKeys),
  297. Delimiter: delimiter,
  298. IsTruncated: cursor.isTruncated,
  299. Contents: contents,
  300. CommonPrefixes: commonPrefixes,
  301. }
  302. if encodingTypeUrl {
  303. // Todo used for pass test_bucket_listv2_encoding_basic
  304. // sort.Slice(response.CommonPrefixes, func(i, j int) bool { return response.CommonPrefixes[i].Prefix < response.CommonPrefixes[j].Prefix })
  305. response.EncodingType = s3.EncodingTypeUrl
  306. }
  307. return nil
  308. })
  309. return
  310. }
  311. type ListingCursor struct {
  312. maxKeys uint16
  313. isTruncated bool
  314. prefixEndsOnDelimiter bool
  315. }
  316. // the prefix and marker may be in different directories
  317. // normalizePrefixMarker ensures the prefix and marker both starts from the same directory
  318. func normalizePrefixMarker(prefix, marker string) (alignedDir, alignedPrefix, alignedMarker string) {
  319. // alignedDir should not end with "/"
  320. // alignedDir, alignedPrefix, alignedMarker should only have "/" in middle
  321. if len(marker) == 0 {
  322. prefix = strings.Trim(prefix, "/")
  323. } else {
  324. prefix = strings.TrimLeft(prefix, "/")
  325. }
  326. marker = strings.TrimLeft(marker, "/")
  327. if prefix == "" {
  328. return "", "", marker
  329. }
  330. if marker == "" {
  331. alignedDir, alignedPrefix = toDirAndName(prefix)
  332. return
  333. }
  334. if !strings.HasPrefix(marker, prefix) {
  335. // something wrong
  336. return "", prefix, marker
  337. }
  338. if strings.HasPrefix(marker, prefix+"/") {
  339. alignedDir = prefix
  340. alignedPrefix = ""
  341. alignedMarker = marker[len(alignedDir)+1:]
  342. return
  343. }
  344. alignedDir, alignedPrefix = toDirAndName(prefix)
  345. if alignedDir != "" {
  346. alignedMarker = marker[len(alignedDir)+1:]
  347. } else {
  348. alignedMarker = marker
  349. }
  350. return
  351. }
  352. func toDirAndName(dirAndName string) (dir, name string) {
  353. sepIndex := strings.LastIndex(dirAndName, "/")
  354. if sepIndex >= 0 {
  355. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  356. } else {
  357. name = dirAndName
  358. }
  359. return
  360. }
  361. func toParentAndDescendants(dirAndName string) (dir, name string) {
  362. sepIndex := strings.Index(dirAndName, "/")
  363. if sepIndex >= 0 {
  364. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  365. } else {
  366. name = dirAndName
  367. }
  368. return
  369. }
  370. func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
  371. // invariants
  372. // prefix and marker should be under dir, marker may contain "/"
  373. // maxKeys should be updated for each recursion
  374. // glog.V(4).Infof("doListFilerEntries dir: %s, prefix: %s, marker %s, maxKeys: %d, prefixEndsOnDelimiter: %+v", dir, prefix, marker, cursor.maxKeys, cursor.prefixEndsOnDelimiter)
  375. if prefix == "/" && delimiter == "/" {
  376. return
  377. }
  378. if cursor.maxKeys <= 0 {
  379. return // Don't set isTruncated here - let caller decide based on whether more entries exist
  380. }
  381. if strings.Contains(marker, "/") {
  382. subDir, subMarker := toParentAndDescendants(marker)
  383. // println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
  384. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, eachEntryFn)
  385. if subErr != nil {
  386. err = subErr
  387. return
  388. }
  389. nextMarker = subDir + "/" + subNextMarker
  390. // finished processing this subdirectory
  391. marker = subDir
  392. }
  393. if cursor.isTruncated {
  394. return
  395. }
  396. // now marker is also a direct child of dir
  397. request := &filer_pb.ListEntriesRequest{
  398. Directory: dir,
  399. Prefix: prefix,
  400. Limit: uint32(cursor.maxKeys + 2), // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
  401. StartFromFileName: marker,
  402. InclusiveStartFrom: inclusiveStartFrom,
  403. }
  404. if cursor.prefixEndsOnDelimiter {
  405. request.Limit = uint32(1)
  406. }
  407. ctx, cancel := context.WithCancel(context.Background())
  408. defer cancel()
  409. stream, listErr := client.ListEntries(ctx, request)
  410. if listErr != nil {
  411. err = fmt.Errorf("list entires %+v: %v", request, listErr)
  412. return
  413. }
  414. // Track .versions directories found in this directory for later processing
  415. var versionsDirs []string
  416. for {
  417. resp, recvErr := stream.Recv()
  418. if recvErr != nil {
  419. if recvErr == io.EOF {
  420. break
  421. } else {
  422. err = fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  423. return
  424. }
  425. }
  426. entry := resp.Entry
  427. if cursor.maxKeys <= 0 {
  428. cursor.isTruncated = true
  429. continue
  430. }
  431. // Set nextMarker only when we have quota to process this entry
  432. nextMarker = entry.Name
  433. if cursor.prefixEndsOnDelimiter {
  434. if entry.Name == prefix && entry.IsDirectory {
  435. if delimiter != "/" {
  436. cursor.prefixEndsOnDelimiter = false
  437. }
  438. } else {
  439. continue
  440. }
  441. }
  442. if entry.IsDirectory {
  443. // glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
  444. if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
  445. continue
  446. }
  447. // Skip .versions directories in regular list operations but track them for logical object creation
  448. if strings.HasSuffix(entry.Name, ".versions") {
  449. glog.V(4).Infof("Found .versions directory: %s", entry.Name)
  450. versionsDirs = append(versionsDirs, entry.Name)
  451. continue
  452. }
  453. if delimiter != "/" || cursor.prefixEndsOnDelimiter {
  454. if cursor.prefixEndsOnDelimiter {
  455. cursor.prefixEndsOnDelimiter = false
  456. if entry.IsDirectoryKeyObject() {
  457. eachEntryFn(dir, entry)
  458. }
  459. } else {
  460. eachEntryFn(dir, entry)
  461. }
  462. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, eachEntryFn)
  463. if subErr != nil {
  464. err = fmt.Errorf("doListFilerEntries2: %w", subErr)
  465. return
  466. }
  467. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
  468. nextMarker = entry.Name + "/" + subNextMarker
  469. if cursor.isTruncated {
  470. return
  471. }
  472. // println("doListFilerEntries2 nextMarker", nextMarker)
  473. } else {
  474. var isEmpty bool
  475. if !s3a.option.AllowEmptyFolder && entry.IsOlderDir() {
  476. //if isEmpty, err = s3a.ensureDirectoryAllEmpty(client, dir, entry.Name); err != nil {
  477. // glog.Errorf("check empty folder %s: %v", dir, err)
  478. //}
  479. }
  480. if !isEmpty {
  481. eachEntryFn(dir, entry)
  482. }
  483. }
  484. } else {
  485. eachEntryFn(dir, entry)
  486. // glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
  487. }
  488. if cursor.prefixEndsOnDelimiter {
  489. cursor.prefixEndsOnDelimiter = false
  490. }
  491. }
  492. // After processing all regular entries, handle versioned objects
  493. // Create logical entries for objects that have .versions directories
  494. for _, versionsDir := range versionsDirs {
  495. if cursor.maxKeys <= 0 {
  496. cursor.isTruncated = true
  497. break
  498. }
  499. // Extract object name from .versions directory name (remove .versions suffix)
  500. baseObjectName := strings.TrimSuffix(versionsDir, ".versions")
  501. // Construct full object path relative to bucket
  502. // dir is something like "/buckets/sea-test-1/Veeam/Backup/vbr/Config"
  503. // we need to get the path relative to bucket: "Veeam/Backup/vbr/Config/Owner"
  504. bucketPath := strings.TrimPrefix(dir, s3a.option.BucketsPath+"/")
  505. bucketName := strings.Split(bucketPath, "/")[0]
  506. // Remove bucket name from path to get directory within bucket
  507. bucketRelativePath := strings.Join(strings.Split(bucketPath, "/")[1:], "/")
  508. var fullObjectPath string
  509. if bucketRelativePath == "" {
  510. // Object is at bucket root
  511. fullObjectPath = baseObjectName
  512. } else {
  513. // Object is in subdirectory
  514. fullObjectPath = bucketRelativePath + "/" + baseObjectName
  515. }
  516. glog.V(4).Infof("Processing versioned object: baseObjectName=%s, bucketRelativePath=%s, fullObjectPath=%s",
  517. baseObjectName, bucketRelativePath, fullObjectPath)
  518. // Get the latest version information for this object
  519. if latestVersionEntry, latestVersionErr := s3a.getLatestVersionEntryForListOperation(bucketName, fullObjectPath); latestVersionErr == nil {
  520. glog.V(4).Infof("Creating logical entry for versioned object: %s", fullObjectPath)
  521. eachEntryFn(dir, latestVersionEntry)
  522. } else {
  523. glog.V(4).Infof("Failed to get latest version for %s: %v", fullObjectPath, latestVersionErr)
  524. }
  525. }
  526. return
  527. }
  528. func getListObjectsV2Args(values url.Values) (prefix, startAfter, delimiter string, token OptionalString, encodingTypeUrl bool, fetchOwner bool, maxkeys uint16, allowUnordered bool, errCode s3err.ErrorCode) {
  529. prefix = values.Get("prefix")
  530. token = OptionalString{set: values.Has("continuation-token"), string: values.Get("continuation-token")}
  531. startAfter = values.Get("start-after")
  532. delimiter = values.Get("delimiter")
  533. encodingTypeUrl = values.Get("encoding-type") == s3.EncodingTypeUrl
  534. if values.Get("max-keys") != "" {
  535. if maxKeys, err := strconv.ParseUint(values.Get("max-keys"), 10, 16); err == nil {
  536. maxkeys = uint16(maxKeys)
  537. } else {
  538. // Invalid max-keys value (non-numeric)
  539. errCode = s3err.ErrInvalidMaxKeys
  540. return
  541. }
  542. } else {
  543. maxkeys = maxObjectListSizeLimit
  544. }
  545. fetchOwner = values.Get("fetch-owner") == "true"
  546. allowUnordered = values.Get("allow-unordered") == "true"
  547. errCode = s3err.ErrNone
  548. return
  549. }
  550. func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string, encodingTypeUrl bool, maxkeys int16, allowUnordered bool, errCode s3err.ErrorCode) {
  551. prefix = values.Get("prefix")
  552. marker = values.Get("marker")
  553. delimiter = values.Get("delimiter")
  554. encodingTypeUrl = values.Get("encoding-type") == "url"
  555. if values.Get("max-keys") != "" {
  556. if maxKeys, err := strconv.ParseInt(values.Get("max-keys"), 10, 16); err == nil {
  557. maxkeys = int16(maxKeys)
  558. } else {
  559. // Invalid max-keys value (non-numeric)
  560. errCode = s3err.ErrInvalidMaxKeys
  561. return
  562. }
  563. } else {
  564. maxkeys = maxObjectListSizeLimit
  565. }
  566. allowUnordered = values.Get("allow-unordered") == "true"
  567. errCode = s3err.ErrNone
  568. return
  569. }
  570. func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFilerClient, parentDir, name string) (isEmpty bool, err error) {
  571. // println("+ ensureDirectoryAllEmpty", dir, name)
  572. glog.V(4).Infof("+ isEmpty %s/%s", parentDir, name)
  573. defer glog.V(4).Infof("- isEmpty %s/%s %v", parentDir, name, isEmpty)
  574. var fileCounter int
  575. var subDirs []string
  576. currentDir := parentDir + "/" + name
  577. var startFrom string
  578. var isExhausted bool
  579. var foundEntry bool
  580. for fileCounter == 0 && !isExhausted && err == nil {
  581. err = filer_pb.SeaweedList(context.Background(), filerClient, currentDir, "", func(entry *filer_pb.Entry, isLast bool) error {
  582. foundEntry = true
  583. if entry.IsOlderDir() {
  584. subDirs = append(subDirs, entry.Name)
  585. } else {
  586. fileCounter++
  587. }
  588. startFrom = entry.Name
  589. isExhausted = isExhausted || isLast
  590. glog.V(4).Infof(" * %s/%s isLast: %t", currentDir, startFrom, isLast)
  591. return nil
  592. }, startFrom, false, 8)
  593. if !foundEntry {
  594. break
  595. }
  596. }
  597. if err != nil {
  598. return false, err
  599. }
  600. if fileCounter > 0 {
  601. return false, nil
  602. }
  603. for _, subDir := range subDirs {
  604. isSubEmpty, subErr := s3a.ensureDirectoryAllEmpty(filerClient, currentDir, subDir)
  605. if subErr != nil {
  606. return false, subErr
  607. }
  608. if !isSubEmpty {
  609. return false, nil
  610. }
  611. }
  612. glog.V(1).Infof("deleting empty folder %s", currentDir)
  613. if err = doDeleteEntry(filerClient, parentDir, name, true, false); err != nil {
  614. return
  615. }
  616. return true, nil
  617. }
  618. // getLatestVersionEntryForListOperation gets the latest version of an object and creates a logical entry for list operations
  619. // This is used to show versioned objects as logical object names in regular list operations
  620. func (s3a *S3ApiServer) getLatestVersionEntryForListOperation(bucket, object string) (*filer_pb.Entry, error) {
  621. // Get the latest version entry
  622. latestVersionEntry, err := s3a.getLatestObjectVersion(bucket, object)
  623. if err != nil {
  624. return nil, fmt.Errorf("failed to get latest version: %w", err)
  625. }
  626. // Check if this is a delete marker (should not be shown in regular list)
  627. if latestVersionEntry.Extended != nil {
  628. if deleteMarker, exists := latestVersionEntry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
  629. return nil, fmt.Errorf("latest version is a delete marker")
  630. }
  631. }
  632. // Create a logical entry that appears to be stored at the object path (not the versioned path)
  633. // This allows the list operation to show the logical object name while preserving all metadata
  634. logicalEntry := &filer_pb.Entry{
  635. Name: strings.TrimPrefix(object, "/"),
  636. IsDirectory: false,
  637. Attributes: latestVersionEntry.Attributes,
  638. Extended: latestVersionEntry.Extended,
  639. Chunks: latestVersionEntry.Chunks,
  640. }
  641. return logicalEntry, nil
  642. }
  643. // adjustMarkerForDelimiter handles delimiter-ending markers by incrementing them to skip entries with that prefix.
  644. // For example, when continuation token is "boo/", this returns "boo~" to skip all "boo/*" entries
  645. // but still finds any "bop" or later entries. We add a high ASCII character rather than incrementing
  646. // the last character to avoid skipping potential directory entries.
  647. // This is essential for correct S3 list operations with delimiters and CommonPrefixes.
  648. func adjustMarkerForDelimiter(marker, delimiter string) string {
  649. if delimiter == "" || !strings.HasSuffix(marker, delimiter) {
  650. return marker
  651. }
  652. // Remove the trailing delimiter and append a high ASCII character
  653. // This ensures we skip all entries under the prefix but don't skip
  654. // potential directory entries that start with a similar prefix
  655. prefix := strings.TrimSuffix(marker, delimiter)
  656. if len(prefix) == 0 {
  657. return marker
  658. }
  659. // Use tilde (~) which has ASCII value 126, higher than most printable characters
  660. // This skips "prefix/*" entries but still finds "prefix" + any higher character
  661. return prefix + "~"
  662. }