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.

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