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.

363 lines
9.4 KiB

6 years ago
7 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
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. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  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. response, _ := s3a.listFilerEntries(bucket, object.ObjectName, 1, "", "/")
  138. if len(response.Contents) != 0 && strings.HasSuffix(object.ObjectName, "/") {
  139. continue
  140. }
  141. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  142. parentDirectoryPath, entryName, isDeleteData, isRecursive := "/", object.ObjectName, true, true
  143. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  144. entryName = object.ObjectName[lastSeparator+1:]
  145. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  146. }
  147. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  148. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  149. if err == nil {
  150. deletedObjects = append(deletedObjects, object)
  151. } else {
  152. deleteErrors = append(deleteErrors, DeleteError{
  153. Code: "",
  154. Message: err.Error(),
  155. Key: object.ObjectName,
  156. })
  157. }
  158. }
  159. return nil
  160. })
  161. deleteResp := DeleteObjectsResponse{}
  162. if !deleteObjects.Quiet {
  163. deleteResp.DeletedObjects = deletedObjects
  164. }
  165. deleteResp.Errors = deleteErrors
  166. writeSuccessResponseXML(w, encodeResponse(deleteResp))
  167. }
  168. var passThroughHeaders = []string{
  169. "response-cache-control",
  170. "response-content-disposition",
  171. "response-content-encoding",
  172. "response-content-language",
  173. "response-content-type",
  174. "response-expires",
  175. }
  176. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, responseFn func(proxyResponse *http.Response, w http.ResponseWriter)) {
  177. glog.V(2).Infof("s3 proxying %s to %s", r.Method, destUrl)
  178. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  179. if err != nil {
  180. glog.Errorf("NewRequest %s: %v", destUrl, err)
  181. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  182. return
  183. }
  184. proxyReq.Header.Set("Host", s3a.option.Filer)
  185. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  186. for header, values := range r.Header {
  187. // handle s3 related headers
  188. passed := false
  189. for _, h := range passThroughHeaders {
  190. if strings.ToLower(header) == h && len(values) > 0 {
  191. proxyReq.Header.Add(header[len("response-"):], values[0])
  192. passed = true
  193. break
  194. }
  195. }
  196. if passed {
  197. continue
  198. }
  199. // handle other headers
  200. for _, value := range values {
  201. proxyReq.Header.Add(header, value)
  202. }
  203. }
  204. resp, postErr := client.Do(proxyReq)
  205. if postErr != nil {
  206. glog.Errorf("post to filer: %v", postErr)
  207. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  208. return
  209. }
  210. defer util.CloseResponse(resp)
  211. if (resp.ContentLength == -1 || resp.StatusCode == 404) && !strings.HasSuffix(destUrl, "/") {
  212. writeErrorResponse(w, s3err.ErrNoSuchKey, r.URL)
  213. return
  214. }
  215. responseFn(resp, w)
  216. }
  217. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) {
  218. for k, v := range proxyResponse.Header {
  219. w.Header()[k] = v
  220. }
  221. w.WriteHeader(proxyResponse.StatusCode)
  222. io.Copy(w, proxyResponse.Body)
  223. }
  224. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code s3err.ErrorCode) {
  225. hash := md5.New()
  226. var body = io.TeeReader(dataReader, hash)
  227. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  228. if err != nil {
  229. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  230. return "", s3err.ErrInternalError
  231. }
  232. proxyReq.Header.Set("Host", s3a.option.Filer)
  233. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  234. for header, values := range r.Header {
  235. for _, value := range values {
  236. proxyReq.Header.Add(header, value)
  237. }
  238. }
  239. resp, postErr := client.Do(proxyReq)
  240. if postErr != nil {
  241. glog.Errorf("post to filer: %v", postErr)
  242. return "", s3err.ErrInternalError
  243. }
  244. defer resp.Body.Close()
  245. etag = fmt.Sprintf("%x", hash.Sum(nil))
  246. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  247. if ra_err != nil {
  248. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  249. return etag, s3err.ErrInternalError
  250. }
  251. var ret weed_server.FilerPostResult
  252. unmarshal_err := json.Unmarshal(resp_body, &ret)
  253. if unmarshal_err != nil {
  254. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  255. return "", s3err.ErrInternalError
  256. }
  257. if ret.Error != "" {
  258. glog.Errorf("upload to filer error: %v", ret.Error)
  259. return "", filerErrorToS3Error(ret.Error)
  260. }
  261. return etag, s3err.ErrNone
  262. }
  263. func setEtag(w http.ResponseWriter, etag string) {
  264. if etag != "" {
  265. if strings.HasPrefix(etag, "\"") {
  266. w.Header().Set("ETag", etag)
  267. } else {
  268. w.Header().Set("ETag", "\""+etag+"\"")
  269. }
  270. }
  271. }
  272. func getBucketAndObject(r *http.Request) (bucket, object string) {
  273. vars := mux.Vars(r)
  274. bucket = vars["bucket"]
  275. object = vars["object"]
  276. if !strings.HasPrefix(object, "/") {
  277. object = "/" + object
  278. }
  279. return
  280. }
  281. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  282. if strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory") {
  283. return s3err.ErrExistingObjectIsDirectory
  284. }
  285. return s3err.ErrInternalError
  286. }