s3api_bucket_handlers.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. identityId := r.Header.Get(s3_constants.AmzIdentityId)
  218. response := AccessControlPolicy{
  219. Owner: CanonicalUser{
  220. ID: identityId,
  221. DisplayName: identityId,
  222. },
  223. }
  224. response.AccessControlList.Grant = append(response.AccessControlList.Grant, Grant{
  225. Grantee: Grantee{
  226. ID: identityId,
  227. DisplayName: identityId,
  228. Type: "CanonicalUser",
  229. XMLXSI: "CanonicalUser",
  230. XMLNS: "http://www.w3.org/2001/XMLSchema-instance"},
  231. Permission: s3.PermissionFullControl,
  232. })
  233. writeSuccessResponseXML(w, r, response)
  234. }
  235. // PutBucketAclHandler Put bucket ACL only responds success if the ACL is private.
  236. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAcl.html //
  237. func (s3a *S3ApiServer) PutBucketAclHandler(w http.ResponseWriter, r *http.Request) {
  238. // collect parameters
  239. bucket, _ := s3_constants.GetBucketAndObject(r)
  240. glog.V(3).Infof("PutBucketAclHandler %s", bucket)
  241. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  242. s3err.WriteErrorResponse(w, r, err)
  243. return
  244. }
  245. cannedAcl := r.Header.Get(s3_constants.AmzCannedAcl)
  246. switch {
  247. case cannedAcl == "":
  248. acl := &s3.AccessControlPolicy{}
  249. if err := xmlDecoder(r.Body, acl, r.ContentLength); err != nil {
  250. glog.Errorf("PutBucketAclHandler: %s", err)
  251. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  252. return
  253. }
  254. if len(acl.Grants) == 1 && acl.Grants[0].Permission != nil && *acl.Grants[0].Permission == s3_constants.PermissionFullControl {
  255. writeSuccessResponseEmpty(w, r)
  256. return
  257. }
  258. case cannedAcl == s3_constants.CannedAclPrivate:
  259. writeSuccessResponseEmpty(w, r)
  260. return
  261. }
  262. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  263. }
  264. // GetBucketLifecycleConfigurationHandler Get Bucket Lifecycle configuration
  265. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html
  266. func (s3a *S3ApiServer) GetBucketLifecycleConfigurationHandler(w http.ResponseWriter, r *http.Request) {
  267. // collect parameters
  268. bucket, _ := s3_constants.GetBucketAndObject(r)
  269. glog.V(3).Infof("GetBucketLifecycleConfigurationHandler %s", bucket)
  270. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  271. s3err.WriteErrorResponse(w, r, err)
  272. return
  273. }
  274. fc, err := filer.ReadFilerConf(s3a.option.Filer, s3a.option.GrpcDialOption, nil)
  275. if err != nil {
  276. glog.Errorf("GetBucketLifecycleConfigurationHandler: %s", err)
  277. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  278. return
  279. }
  280. ttls := fc.GetCollectionTtls(s3a.getCollectionName(bucket))
  281. if len(ttls) == 0 {
  282. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchLifecycleConfiguration)
  283. return
  284. }
  285. response := Lifecycle{}
  286. for prefix, internalTtl := range ttls {
  287. ttl, _ := needle.ReadTTL(internalTtl)
  288. days := int(ttl.Minutes() / 60 / 24)
  289. if days == 0 {
  290. continue
  291. }
  292. response.Rules = append(response.Rules, Rule{
  293. Status: Enabled, Filter: Filter{
  294. Prefix: Prefix{string: prefix, set: true},
  295. set: true,
  296. },
  297. Expiration: Expiration{Days: days, set: true},
  298. })
  299. }
  300. writeSuccessResponseXML(w, r, response)
  301. }
  302. // PutBucketLifecycleConfigurationHandler Put Bucket Lifecycle configuration
  303. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html
  304. func (s3a *S3ApiServer) PutBucketLifecycleConfigurationHandler(w http.ResponseWriter, r *http.Request) {
  305. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  306. }
  307. // DeleteBucketMetricsConfiguration Delete Bucket Lifecycle
  308. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html
  309. func (s3a *S3ApiServer) DeleteBucketLifecycleHandler(w http.ResponseWriter, r *http.Request) {
  310. s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
  311. }
  312. // GetBucketLocationHandler Get bucket location
  313. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLocation.html
  314. func (s3a *S3ApiServer) GetBucketLocationHandler(w http.ResponseWriter, r *http.Request) {
  315. writeSuccessResponseXML(w, r, LocationConstraint{})
  316. }
  317. // GetBucketRequestPaymentHandler Get bucket location
  318. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketRequestPayment.html
  319. func (s3a *S3ApiServer) GetBucketRequestPaymentHandler(w http.ResponseWriter, r *http.Request) {
  320. writeSuccessResponseXML(w, r, RequestPaymentConfiguration{Payer: "BucketOwner"})
  321. }
  322. // PutBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketOwnershipControls.html
  323. func (s3a *S3ApiServer) PutBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  324. bucket, _ := s3_constants.GetBucketAndObject(r)
  325. glog.V(3).Infof("PutBucketOwnershipControls %s", bucket)
  326. errCode := s3a.checkAccessByOwnership(r, bucket)
  327. if errCode != s3err.ErrNone {
  328. s3err.WriteErrorResponse(w, r, errCode)
  329. return
  330. }
  331. if r.Body == nil || r.Body == http.NoBody {
  332. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  333. return
  334. }
  335. var v s3.OwnershipControls
  336. defer util.CloseRequest(r)
  337. err := xmlutil.UnmarshalXML(&v, xml.NewDecoder(r.Body), "")
  338. if err != nil {
  339. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  340. return
  341. }
  342. if len(v.Rules) != 1 {
  343. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  344. return
  345. }
  346. printOwnership := true
  347. ownership := *v.Rules[0].ObjectOwnership
  348. switch ownership {
  349. case s3_constants.OwnershipObjectWriter:
  350. case s3_constants.OwnershipBucketOwnerPreferred:
  351. case s3_constants.OwnershipBucketOwnerEnforced:
  352. printOwnership = false
  353. default:
  354. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
  355. return
  356. }
  357. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  358. if err != nil {
  359. if err == filer_pb.ErrNotFound {
  360. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  361. return
  362. }
  363. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  364. return
  365. }
  366. oldOwnership, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  367. if !ok || string(oldOwnership) != ownership {
  368. if bucketEntry.Extended == nil {
  369. bucketEntry.Extended = make(map[string][]byte)
  370. }
  371. bucketEntry.Extended[s3_constants.ExtOwnershipKey] = []byte(ownership)
  372. err = s3a.updateEntry(s3a.option.BucketsPath, bucketEntry)
  373. if err != nil {
  374. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  375. return
  376. }
  377. }
  378. if printOwnership {
  379. result := &s3.PutBucketOwnershipControlsInput{
  380. OwnershipControls: &v,
  381. }
  382. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, result)
  383. } else {
  384. writeSuccessResponseEmpty(w, r)
  385. }
  386. }
  387. // GetBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketOwnershipControls.html
  388. func (s3a *S3ApiServer) GetBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  389. bucket, _ := s3_constants.GetBucketAndObject(r)
  390. glog.V(3).Infof("GetBucketOwnershipControls %s", bucket)
  391. errCode := s3a.checkAccessByOwnership(r, bucket)
  392. if errCode != s3err.ErrNone {
  393. s3err.WriteErrorResponse(w, r, errCode)
  394. return
  395. }
  396. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  397. if err != nil {
  398. if err == filer_pb.ErrNotFound {
  399. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  400. return
  401. }
  402. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  403. return
  404. }
  405. v, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  406. if !ok {
  407. s3err.WriteErrorResponse(w, r, s3err.OwnershipControlsNotFoundError)
  408. return
  409. }
  410. ownership := string(v)
  411. result := &s3.PutBucketOwnershipControlsInput{
  412. OwnershipControls: &s3.OwnershipControls{
  413. Rules: []*s3.OwnershipControlsRule{
  414. {
  415. ObjectOwnership: &ownership,
  416. },
  417. },
  418. },
  419. }
  420. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, result)
  421. }
  422. // DeleteBucketOwnershipControls https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketOwnershipControls.html
  423. func (s3a *S3ApiServer) DeleteBucketOwnershipControls(w http.ResponseWriter, r *http.Request) {
  424. bucket, _ := s3_constants.GetBucketAndObject(r)
  425. glog.V(3).Infof("PutBucketOwnershipControls %s", bucket)
  426. errCode := s3a.checkAccessByOwnership(r, bucket)
  427. if errCode != s3err.ErrNone {
  428. s3err.WriteErrorResponse(w, r, errCode)
  429. return
  430. }
  431. bucketEntry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
  432. if err != nil {
  433. if err == filer_pb.ErrNotFound {
  434. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  435. return
  436. }
  437. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  438. return
  439. }
  440. _, ok := bucketEntry.Extended[s3_constants.ExtOwnershipKey]
  441. if !ok {
  442. s3err.WriteErrorResponse(w, r, s3err.OwnershipControlsNotFoundError)
  443. return
  444. }
  445. delete(bucketEntry.Extended, s3_constants.ExtOwnershipKey)
  446. err = s3a.updateEntry(s3a.option.BucketsPath, bucketEntry)
  447. if err != nil {
  448. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  449. return
  450. }
  451. emptyOwnershipControls := &s3.OwnershipControls{
  452. Rules: []*s3.OwnershipControlsRule{},
  453. }
  454. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, emptyOwnershipControls)
  455. }