You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 lines
16 KiB

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