s3api_bucket_handlers.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. package s3api
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
  8. "github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
  9. "github.com/seaweedfs/seaweedfs/weed/util"
  10. "math"
  11. "net/http"
  12. "time"
  13. "github.com/seaweedfs/seaweedfs/weed/filer"
  14. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  16. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  17. "github.com/aws/aws-sdk-go/aws"
  18. "github.com/aws/aws-sdk-go/service/s3"
  19. "github.com/seaweedfs/seaweedfs/weed/glog"
  20. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  21. )
  22. type ListAllMyBucketsResult struct {
  23. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListAllMyBucketsResult"`
  24. Owner *s3.Owner
  25. Buckets []*s3.Bucket `xml:"Buckets>Bucket"`
  26. }
  27. func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Request) {
  28. glog.V(3).Infof("ListBucketsHandler")
  29. var identity *Identity
  30. var s3Err s3err.ErrorCode
  31. if s3a.iam.isEnabled() {
  32. identity, s3Err = s3a.iam.authUser(r)
  33. if s3Err != s3err.ErrNone {
  34. s3err.WriteErrorResponse(w, r, s3Err)
  35. return
  36. }
  37. }
  38. var response ListAllMyBucketsResult
  39. entries, _, err := s3a.list(s3a.option.BucketsPath, "", "", false, math.MaxInt32)
  40. if err != nil {
  41. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  42. return
  43. }
  44. identityId := r.Header.Get(s3_constants.AmzIdentityId)
  45. var buckets []*s3.Bucket
  46. for _, entry := range entries {
  47. if entry.IsDirectory {
  48. if identity != nil && !identity.canDo(s3_constants.ACTION_LIST, entry.Name, "") {
  49. continue
  50. }
  51. buckets = append(buckets, &s3.Bucket{
  52. Name: aws.String(entry.Name),
  53. CreationDate: aws.Time(time.Unix(entry.Attributes.Crtime, 0).UTC()),
  54. })
  55. }
  56. }
  57. response = ListAllMyBucketsResult{
  58. Owner: &s3.Owner{
  59. ID: aws.String(identityId),
  60. DisplayName: aws.String(identityId),
  61. },
  62. Buckets: buckets,
  63. }
  64. writeSuccessResponseXML(w, r, response)
  65. }
  66. func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request) {
  67. bucket, _ := s3_constants.GetBucketAndObject(r)
  68. glog.V(3).Infof("PutBucketHandler %s", bucket)
  69. // validate the bucket name
  70. err := s3bucket.VerifyS3BucketName(bucket)
  71. if err != nil {
  72. glog.Errorf("put invalid bucket name: %v %v", bucket, err)
  73. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidBucketName)
  74. return
  75. }
  76. // avoid duplicated buckets
  77. errCode := s3err.ErrNone
  78. if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  79. if resp, err := client.CollectionList(context.Background(), &filer_pb.CollectionListRequest{
  80. IncludeEcVolumes: true,
  81. IncludeNormalVolumes: true,
  82. }); err != nil {
  83. glog.Errorf("list collection: %v", err)
  84. return fmt.Errorf("list collections: %v", err)
  85. } else {
  86. for _, c := range resp.Collections {
  87. if s3a.getCollectionName(bucket) == c.Name {
  88. errCode = s3err.ErrBucketAlreadyExists
  89. break
  90. }
  91. }
  92. }
  93. return nil
  94. }); err != nil {
  95. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  96. return
  97. }
  98. if exist, err := s3a.exists(s3a.option.BucketsPath, bucket, true); err == nil && exist {
  99. errCode = s3err.ErrBucketAlreadyExists
  100. }
  101. if errCode != s3err.ErrNone {
  102. s3err.WriteErrorResponse(w, r, errCode)
  103. return
  104. }
  105. if s3a.iam.isEnabled() {
  106. if _, errCode = s3a.iam.authRequest(r, s3_constants.ACTION_ADMIN); errCode != s3err.ErrNone {
  107. s3err.WriteErrorResponse(w, r, errCode)
  108. return
  109. }
  110. }
  111. fn := func(entry *filer_pb.Entry) {
  112. if identityId := r.Header.Get(s3_constants.AmzIdentityId); identityId != "" {
  113. if entry.Extended == nil {
  114. entry.Extended = make(map[string][]byte)
  115. }
  116. entry.Extended[s3_constants.AmzIdentityId] = []byte(identityId)
  117. }
  118. }
  119. // create the folder for bucket, but lazily create actual collection
  120. if err := s3a.mkdir(s3a.option.BucketsPath, bucket, fn); err != nil {
  121. glog.Errorf("PutBucketHandler mkdir: %v", err)
  122. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  123. return
  124. }
  125. w.Header().Set("Location", "/"+bucket)
  126. writeSuccessResponseEmpty(w, r)
  127. }
  128. func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Request) {
  129. bucket, _ := s3_constants.GetBucketAndObject(r)
  130. glog.V(3).Infof("DeleteBucketHandler %s", bucket)
  131. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  132. s3err.WriteErrorResponse(w, r, err)
  133. return
  134. }
  135. err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  136. if !s3a.option.AllowDeleteBucketNotEmpty {
  137. entries, _, err := s3a.list(s3a.option.BucketsPath+"/"+bucket, "", "", false, 2)
  138. if err != nil {
  139. return fmt.Errorf("failed to list bucket %s: %v", bucket, err)
  140. }
  141. for _, entry := range entries {
  142. if entry.Name != s3_constants.MultipartUploadsFolder {
  143. return errors.New(s3err.GetAPIError(s3err.ErrBucketNotEmpty).Code)
  144. }
  145. }
  146. }
  147. // delete collection
  148. deleteCollectionRequest := &filer_pb.DeleteCollectionRequest{
  149. Collection: s3a.getCollectionName(bucket),
  150. }
  151. glog.V(1).Infof("delete collection: %v", deleteCollectionRequest)
  152. if _, err := client.DeleteCollection(context.Background(), deleteCollectionRequest); err != nil {
  153. return fmt.Errorf("delete collection %s: %v", bucket, err)
  154. }
  155. return nil
  156. })
  157. if err != nil {
  158. s3ErrorCode := s3err.ErrInternalError
  159. if err.Error() == s3err.GetAPIError(s3err.ErrBucketNotEmpty).Code {
  160. s3ErrorCode = s3err.ErrBucketNotEmpty
  161. }
  162. s3err.WriteErrorResponse(w, r, s3ErrorCode)
  163. return
  164. }
  165. err = s3a.rm(s3a.option.BucketsPath, bucket, false, true)
  166. if err != nil {
  167. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  168. return
  169. }
  170. s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
  171. }
  172. func (s3a *S3ApiServer) HeadBucketHandler(w http.ResponseWriter, r *http.Request) {
  173. bucket, _ := s3_constants.GetBucketAndObject(r)
  174. glog.V(3).Infof("HeadBucketHandler %s", bucket)
  175. if entry, err := s3a.getEntry(s3a.option.BucketsPath, bucket); entry == nil || err == filer_pb.ErrNotFound {
  176. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  177. return
  178. }
  179. writeSuccessResponseEmpty(w, r)
  180. }
  181. func (s3a *S3ApiServer) checkBucket(r *http.Request, bucket string) s3err.ErrorCode {
  182. entry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  183. if entry == nil || err == filer_pb.ErrNotFound {
  184. return s3err.ErrNoSuchBucket
  185. }
  186. if !s3a.hasAccess(r, entry) {
  187. return s3err.ErrAccessDenied
  188. }
  189. return s3err.ErrNone
  190. }
  191. func (s3a *S3ApiServer) hasAccess(r *http.Request, entry *filer_pb.Entry) bool {
  192. isAdmin := r.Header.Get(s3_constants.AmzIsAdmin) != ""
  193. if isAdmin {
  194. return true
  195. }
  196. if entry.Extended == nil {
  197. return true
  198. }
  199. identityId := r.Header.Get(s3_constants.AmzIdentityId)
  200. if id, ok := entry.Extended[s3_constants.AmzIdentityId]; ok {
  201. if identityId != string(id) {
  202. return false
  203. }
  204. }
  205. return true
  206. }
  207. // GetBucketAclHandler Get Bucket ACL
  208. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAcl.html
  209. func (s3a *S3ApiServer) GetBucketAclHandler(w http.ResponseWriter, r *http.Request) {
  210. // collect parameters
  211. bucket, _ := s3_constants.GetBucketAndObject(r)
  212. glog.V(3).Infof("GetBucketAclHandler %s", bucket)
  213. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  214. s3err.WriteErrorResponse(w, r, err)
  215. return
  216. }
  217. amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
  218. amzDisplayName := s3a.iam.GetAccountNameById(amzAccountId)
  219. response := AccessControlPolicy{
  220. Owner: CanonicalUser{
  221. ID: amzAccountId,
  222. DisplayName: amzDisplayName,
  223. },
  224. }
  225. response.AccessControlList.Grant = append(response.AccessControlList.Grant, Grant{
  226. Grantee: Grantee{
  227. ID: amzAccountId,
  228. DisplayName: amzDisplayName,
  229. Type: "CanonicalUser",
  230. XMLXSI: "CanonicalUser",
  231. XMLNS: "http://www.w3.org/2001/XMLSchema-instance"},
  232. Permission: s3.PermissionFullControl,
  233. })
  234. writeSuccessResponseXML(w, r, response)
  235. }
  236. // PutBucketAclHandler Put bucket ACL only responds success if the ACL is private.
  237. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAcl.html //
  238. func (s3a *S3ApiServer) PutBucketAclHandler(w http.ResponseWriter, r *http.Request) {
  239. // collect parameters
  240. bucket, _ := s3_constants.GetBucketAndObject(r)
  241. glog.V(3).Infof("PutBucketAclHandler %s", bucket)
  242. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  243. s3err.WriteErrorResponse(w, r, err)
  244. return
  245. }
  246. cannedAcl := r.Header.Get(s3_constants.AmzCannedAcl)
  247. switch {
  248. case cannedAcl == "":
  249. acl := &s3.AccessControlPolicy{}
  250. if err := xmlDecoder(r.Body, acl, r.ContentLength); err != nil {
  251. glog.Errorf("PutBucketAclHandler: %s", err)
  252. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  253. return
  254. }
  255. if len(acl.Grants) == 1 && acl.Grants[0].Permission != nil && *acl.Grants[0].Permission == s3_constants.PermissionFullControl {
  256. writeSuccessResponseEmpty(w, r)
  257. return
  258. }
  259. case cannedAcl == s3_constants.CannedAclPrivate:
  260. writeSuccessResponseEmpty(w, r)
  261. return
  262. }
  263. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  264. }
  265. // GetBucketLifecycleConfigurationHandler Get Bucket Lifecycle configuration
  266. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html
  267. func (s3a *S3ApiServer) GetBucketLifecycleConfigurationHandler(w http.ResponseWriter, r *http.Request) {
  268. // collect parameters
  269. bucket, _ := s3_constants.GetBucketAndObject(r)
  270. glog.V(3).Infof("GetBucketLifecycleConfigurationHandler %s", bucket)
  271. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  272. s3err.WriteErrorResponse(w, r, err)
  273. return
  274. }
  275. fc, err := filer.ReadFilerConf(s3a.option.Filer, s3a.option.GrpcDialOption, nil)
  276. if err != nil {
  277. glog.Errorf("GetBucketLifecycleConfigurationHandler: %s", err)
  278. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  279. return
  280. }
  281. ttls := fc.GetCollectionTtls(s3a.getCollectionName(bucket))
  282. if len(ttls) == 0 {
  283. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchLifecycleConfiguration)
  284. return
  285. }
  286. response := Lifecycle{}
  287. for prefix, internalTtl := range ttls {
  288. ttl, _ := needle.ReadTTL(internalTtl)
  289. days := int(ttl.Minutes() / 60 / 24)
  290. if days == 0 {
  291. continue
  292. }
  293. response.Rules = append(response.Rules, Rule{
  294. Status: Enabled, Filter: Filter{
  295. Prefix: Prefix{string: prefix, set: true},
  296. set: true,
  297. },
  298. Expiration: Expiration{Days: days, set: true},
  299. })
  300. }
  301. writeSuccessResponseXML(w, r, response)
  302. }
  303. // PutBucketLifecycleConfigurationHandler Put Bucket Lifecycle configuration
  304. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html
  305. func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWriter, r *http.Request) {
  306. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  307. }
  308. // DeleteBucketMetricsConfiguration Delete Bucket Lifecycle
  309. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html
  310. func (s3a *S3ApiServer) DeleteBucketLifecycleHandler(w http.ResponseWriter, r *http.Request) {
  311. s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
  312. }
  313. // GetBucketLocationHandler Get bucket location
  314. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLocation.html
  315. func (s3a *S3ApiServer) GetBucketLocationHandler(w http.ResponseWriter, r *http.Request) {
  316. writeSuccessResponseXML(w, r, LocationConstraint{})
  317. }
  318. // GetBucketRequestPaymentHandler Get bucket location
  319. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketRequestPayment.html
  320. func (s3a *S3ApiServer) GetBucketRequestPaymentHandler(w http.ResponseWriter, r *http.Request) {
  321. writeSuccessResponseXML(w, r, RequestPaymentConfiguration{Payer: "BucketOwner"})
  322. }
  323. // PutBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketOwnershipControls.html
  324. func (s3a *S3ApiServer) PutBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  325. bucket, _ := s3_constants.GetBucketAndObject(r)
  326. glog.V(3).Infof("PutBucketOwnershipControls %s", bucket)
  327. errCode := s3a.checkAccessByOwnership(r, bucket)
  328. if errCode != s3err.ErrNone {
  329. s3err.WriteErrorResponse(w, r, errCode)
  330. return
  331. }
  332. if r.Body == nil || r.Body == http.NoBody {
  333. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  334. return
  335. }
  336. var v s3.OwnershipControls
  337. defer util.CloseRequest(r)
  338. err := xmlutil.UnmarshalXML(&v, xml.NewDecoder(r.Body), "")
  339. if err != nil {
  340. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  341. return
  342. }
  343. if len(v.Rules) != 1 {
  344. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  345. return
  346. }
  347. printOwnership := true
  348. ownership := *v.Rules[0].ObjectOwnership
  349. switch ownership {
  350. case s3_constants.OwnershipObjectWriter:
  351. case s3_constants.OwnershipBucketOwnerPreferred:
  352. case s3_constants.OwnershipBucketOwnerEnforced:
  353. printOwnership = false
  354. default:
  355. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  356. return
  357. }
  358. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  359. if err != nil {
  360. if err == filer_pb.ErrNotFound {
  361. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  362. return
  363. }
  364. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  365. return
  366. }
  367. oldOwnership, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  368. if !ok || string(oldOwnership) != ownership {
  369. if bucketEntry.Extended == nil {
  370. bucketEntry.Extended = make(map[string][]byte)
  371. }
  372. bucketEntry.Extended[s3_constants.ExtOwnershipKey] = []byte(ownership)
  373. err = s3a.updateEntry(s3a.option.BucketsPath, bucketEntry)
  374. if err != nil {
  375. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  376. return
  377. }
  378. }
  379. if printOwnership {
  380. result := &s3.PutBucketOwnershipControlsInput{
  381. OwnershipControls: &v,
  382. }
  383. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, result)
  384. } else {
  385. writeSuccessResponseEmpty(w, r)
  386. }
  387. }
  388. // GetBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketOwnershipControls.html
  389. func (s3a *S3ApiServer) GetBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  390. bucket, _ := s3_constants.GetBucketAndObject(r)
  391. glog.V(3).Infof("GetBucketOwnershipControls %s", bucket)
  392. errCode := s3a.checkAccessByOwnership(r, bucket)
  393. if errCode != s3err.ErrNone {
  394. s3err.WriteErrorResponse(w, r, errCode)
  395. return
  396. }
  397. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  398. if err != nil {
  399. if err == filer_pb.ErrNotFound {
  400. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  401. return
  402. }
  403. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  404. return
  405. }
  406. v, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  407. if !ok {
  408. s3err.WriteErrorResponse(w, r, s3err.OwnershipControlsNotFoundError)
  409. return
  410. }
  411. ownership := string(v)
  412. result := &s3.PutBucketOwnershipControlsInput{
  413. OwnershipControls: &s3.OwnershipControls{
  414. Rules: []*s3.OwnershipControlsRule{
  415. {
  416. ObjectOwnership: &ownership,
  417. },
  418. },
  419. },
  420. }
  421. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, result)
  422. }
  423. // DeleteBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketOwnershipControls.html
  424. func (s3a *S3ApiServer) DeleteBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  425. bucket, _ := s3_constants.GetBucketAndObject(r)
  426. glog.V(3).Infof("PutBucketOwnershipControls %s", bucket)
  427. errCode := s3a.checkAccessByOwnership(r, bucket)
  428. if errCode != s3err.ErrNone {
  429. s3err.WriteErrorResponse(w, r, errCode)
  430. return
  431. }
  432. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  433. if err != nil {
  434. if err == filer_pb.ErrNotFound {
  435. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  436. return
  437. }
  438. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  439. return
  440. }
  441. _, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  442. if !ok {
  443. s3err.WriteErrorResponse(w, r, s3err.OwnershipControlsNotFoundError)
  444. return
  445. }
  446. delete(bucketEntry.Extended, s3_constants.ExtOwnershipKey)
  447. err = s3a.updateEntry(s3a.option.BucketsPath, bucketEntry)
  448. if err != nil {
  449. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  450. return
  451. }
  452. emptyOwnershipControls := &s3.OwnershipControls{
  453. Rules: []*s3.OwnershipControlsRule{},
  454. }
  455. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, emptyOwnershipControls)
  456. }