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.

328 lines
8.4 KiB

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