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.

327 lines
8.2 KiB

6 years ago
7 years ago
7 years ago
7 years ago
4 years ago
4 years ago
6 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
  1. package s3api
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "github.com/gorilla/mux"
  12. "github.com/chrislusf/seaweedfs/weed/glog"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. weed_server "github.com/chrislusf/seaweedfs/weed/server"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. var (
  18. client *http.Client
  19. )
  20. func init() {
  21. client = &http.Client{Transport: &http.Transport{
  22. MaxIdleConnsPerHost: 1024,
  23. }}
  24. }
  25. func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) {
  26. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  27. bucket, object := getBucketAndObject(r)
  28. _, err := validateContentMd5(r.Header)
  29. if err != nil {
  30. writeErrorResponse(w, ErrInvalidDigest, r.URL)
  31. return
  32. }
  33. dataReader := r.Body
  34. if s3a.iam.isEnabled() {
  35. rAuthType := getRequestAuthType(r)
  36. var s3ErrCode ErrorCode
  37. switch rAuthType {
  38. case authTypeStreamingSigned:
  39. dataReader, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
  40. case authTypeSignedV2, authTypePresignedV2:
  41. _, s3ErrCode = s3a.iam.isReqAuthenticatedV2(r)
  42. case authTypePresigned, authTypeSigned:
  43. _, s3ErrCode = s3a.iam.reqSignatureV4Verify(r)
  44. }
  45. if s3ErrCode != ErrNone {
  46. writeErrorResponse(w, s3ErrCode, r.URL)
  47. return
  48. }
  49. }
  50. defer dataReader.Close()
  51. if strings.HasSuffix(object, "/") {
  52. if err := s3a.mkdir(s3a.option.BucketsPath, bucket+object, nil); err != nil {
  53. writeErrorResponse(w, ErrInternalError, r.URL)
  54. return
  55. }
  56. } else {
  57. uploadUrl := fmt.Sprintf("http://%s%s/%s%s", s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  58. etag, errCode := s3a.putToFiler(r, uploadUrl, dataReader)
  59. if errCode != ErrNone {
  60. writeErrorResponse(w, errCode, r.URL)
  61. return
  62. }
  63. setEtag(w, etag)
  64. }
  65. writeSuccessResponseEmpty(w)
  66. }
  67. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  68. bucket, object := getBucketAndObject(r)
  69. if strings.HasSuffix(r.URL.Path, "/") {
  70. writeErrorResponse(w, ErrNotImplemented, r.URL)
  71. return
  72. }
  73. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  74. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  75. s3a.proxyToFiler(w, r, destUrl, passThroughResponse)
  76. }
  77. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  78. bucket, object := getBucketAndObject(r)
  79. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  80. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  81. s3a.proxyToFiler(w, r, destUrl, passThroughResponse)
  82. }
  83. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  84. bucket, object := getBucketAndObject(r)
  85. destUrl := fmt.Sprintf("http://%s%s/%s%s?recursive=true",
  86. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  87. s3a.proxyToFiler(w, r, destUrl, func(proxyResponse *http.Response, w http.ResponseWriter) {
  88. for k, v := range proxyResponse.Header {
  89. w.Header()[k] = v
  90. }
  91. w.WriteHeader(http.StatusNoContent)
  92. })
  93. }
  94. // / ObjectIdentifier carries key name for the object to delete.
  95. type ObjectIdentifier struct {
  96. ObjectName string `xml:"Key"`
  97. }
  98. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  99. type DeleteObjectsRequest struct {
  100. // Element to enable quiet mode for the request
  101. Quiet bool
  102. // List of objects to be deleted
  103. Objects []ObjectIdentifier `xml:"Object"`
  104. }
  105. // DeleteError structure.
  106. type DeleteError struct {
  107. Code string
  108. Message string
  109. Key string
  110. }
  111. // DeleteObjectsResponse container for multiple object deletes.
  112. type DeleteObjectsResponse struct {
  113. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  114. // Collection of all deleted objects
  115. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  116. // Collection of errors deleting certain objects.
  117. Errors []DeleteError `xml:"Error,omitempty"`
  118. }
  119. // DeleteMultipleObjectsHandler - Delete multiple objects
  120. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  121. bucket, _ := getBucketAndObject(r)
  122. deleteXMLBytes, err := ioutil.ReadAll(r.Body)
  123. if err != nil {
  124. writeErrorResponse(w, ErrInternalError, r.URL)
  125. return
  126. }
  127. deleteObjects := &DeleteObjectsRequest{}
  128. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  129. writeErrorResponse(w, ErrMalformedXML, r.URL)
  130. return
  131. }
  132. var deletedObjects []ObjectIdentifier
  133. var deleteErrors []DeleteError
  134. s3a.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  135. for _, object := range deleteObjects.Objects {
  136. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  137. parentDirectoryPath, entryName, isDeleteData, isRecursive := "/", object.ObjectName, true, true
  138. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  139. entryName = object.ObjectName[lastSeparator+1:]
  140. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  141. }
  142. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  143. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  144. if err == nil {
  145. deletedObjects = append(deletedObjects, object)
  146. } else {
  147. deleteErrors = append(deleteErrors, DeleteError{
  148. Code: "",
  149. Message: err.Error(),
  150. Key: object.ObjectName,
  151. })
  152. }
  153. }
  154. return nil
  155. })
  156. deleteResp := DeleteObjectsResponse{}
  157. if !deleteObjects.Quiet {
  158. deleteResp.DeletedObjects = deletedObjects
  159. }
  160. deleteResp.Errors = deleteErrors
  161. writeSuccessResponseXML(w, encodeResponse(deleteResp))
  162. }
  163. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, responseFn func(proxyResponse *http.Response, w http.ResponseWriter)) {
  164. glog.V(2).Infof("s3 proxying %s to %s", r.Method, destUrl)
  165. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  166. if err != nil {
  167. glog.Errorf("NewRequest %s: %v", destUrl, err)
  168. writeErrorResponse(w, ErrInternalError, r.URL)
  169. return
  170. }
  171. proxyReq.Header.Set("Host", s3a.option.Filer)
  172. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  173. for header, values := range r.Header {
  174. for _, value := range values {
  175. proxyReq.Header.Add(header, value)
  176. }
  177. }
  178. resp, postErr := client.Do(proxyReq)
  179. if resp.ContentLength == -1 {
  180. writeErrorResponse(w, ErrNoSuchKey, r.URL)
  181. return
  182. }
  183. if postErr != nil {
  184. glog.Errorf("post to filer: %v", postErr)
  185. writeErrorResponse(w, ErrInternalError, r.URL)
  186. return
  187. }
  188. defer util.CloseResponse(resp)
  189. responseFn(resp, w)
  190. }
  191. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) {
  192. for k, v := range proxyResponse.Header {
  193. w.Header()[k] = v
  194. }
  195. w.WriteHeader(proxyResponse.StatusCode)
  196. io.Copy(w, proxyResponse.Body)
  197. }
  198. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code ErrorCode) {
  199. hash := md5.New()
  200. var body = io.TeeReader(dataReader, hash)
  201. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  202. if err != nil {
  203. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  204. return "", ErrInternalError
  205. }
  206. proxyReq.Header.Set("Host", s3a.option.Filer)
  207. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  208. for header, values := range r.Header {
  209. for _, value := range values {
  210. proxyReq.Header.Add(header, value)
  211. }
  212. }
  213. resp, postErr := client.Do(proxyReq)
  214. if postErr != nil {
  215. glog.Errorf("post to filer: %v", postErr)
  216. return "", ErrInternalError
  217. }
  218. defer resp.Body.Close()
  219. etag = fmt.Sprintf("%x", hash.Sum(nil))
  220. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  221. if ra_err != nil {
  222. glog.Errorf("upload to filer response read: %v", ra_err)
  223. return etag, ErrInternalError
  224. }
  225. var ret weed_server.FilerPostResult
  226. unmarshal_err := json.Unmarshal(resp_body, &ret)
  227. if unmarshal_err != nil {
  228. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  229. return "", ErrInternalError
  230. }
  231. if ret.Error != "" {
  232. glog.Errorf("upload to filer error: %v", ret.Error)
  233. return "", ErrInternalError
  234. }
  235. return etag, ErrNone
  236. }
  237. func setEtag(w http.ResponseWriter, etag string) {
  238. if etag != "" {
  239. if strings.HasPrefix(etag, "\"") {
  240. w.Header().Set("ETag", etag)
  241. } else {
  242. w.Header().Set("ETag", "\""+etag+"\"")
  243. }
  244. }
  245. }
  246. func getBucketAndObject(r *http.Request) (bucket, object string) {
  247. vars := mux.Vars(r)
  248. bucket = vars["bucket"]
  249. object = vars["object"]
  250. if !strings.HasPrefix(object, "/") {
  251. object = "/" + object
  252. }
  253. return
  254. }