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.

553 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
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. 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. }
  457. // GetBucketVersioningHandler Get Bucket Versioning status
  458. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketVersioning.html
  459. func (s3a *S3ApiServer) GetBucketVersioningHandler(w http.ResponseWriter, r *http.Request) {
  460. bucket, _ := s3_constants.GetBucketAndObject(r)
  461. glog.V(3).Infof("GetBucketVersioning %s", bucket)
  462. if err := s3a.checkBucket(r, bucket); err != s3err.ErrNone {
  463. s3err.WriteErrorResponse(w, r, err)
  464. return
  465. }
  466. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, &s3.PutBucketVersioningInput{
  467. VersioningConfiguration: &s3.VersioningConfiguration{
  468. Status: aws.String(s3.BucketVersioningStatusSuspended),
  469. },
  470. })
  471. }