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.

369 lines
9.6 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
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. response, _ := s3a.listFilerEntries(bucket, object, 1, "", "/")
  87. if len(response.Contents) != 0 && strings.HasSuffix(object, "/") {
  88. w.WriteHeader(http.StatusNoContent)
  89. return
  90. }
  91. destUrl := fmt.Sprintf("http://%s%s/%s%s?recursive=true",
  92. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  93. s3a.proxyToFiler(w, r, destUrl, func(proxyResponse *http.Response, w http.ResponseWriter) {
  94. for k, v := range proxyResponse.Header {
  95. w.Header()[k] = v
  96. }
  97. w.WriteHeader(http.StatusNoContent)
  98. })
  99. }
  100. // / ObjectIdentifier carries key name for the object to delete.
  101. type ObjectIdentifier struct {
  102. ObjectName string `xml:"Key"`
  103. }
  104. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  105. type DeleteObjectsRequest struct {
  106. // Element to enable quiet mode for the request
  107. Quiet bool
  108. // List of objects to be deleted
  109. Objects []ObjectIdentifier `xml:"Object"`
  110. }
  111. // DeleteError structure.
  112. type DeleteError struct {
  113. Code string
  114. Message string
  115. Key string
  116. }
  117. // DeleteObjectsResponse container for multiple object deletes.
  118. type DeleteObjectsResponse struct {
  119. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  120. // Collection of all deleted objects
  121. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  122. // Collection of errors deleting certain objects.
  123. Errors []DeleteError `xml:"Error,omitempty"`
  124. }
  125. // DeleteMultipleObjectsHandler - Delete multiple objects
  126. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  127. bucket, _ := getBucketAndObject(r)
  128. deleteXMLBytes, err := ioutil.ReadAll(r.Body)
  129. if err != nil {
  130. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  131. return
  132. }
  133. deleteObjects := &DeleteObjectsRequest{}
  134. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  135. writeErrorResponse(w, s3err.ErrMalformedXML, r.URL)
  136. return
  137. }
  138. var deletedObjects []ObjectIdentifier
  139. var deleteErrors []DeleteError
  140. s3a.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  141. for _, object := range deleteObjects.Objects {
  142. response, _ := s3a.listFilerEntries(bucket, object.ObjectName, 1, "", "/")
  143. if len(response.Contents) != 0 && strings.HasSuffix(object.ObjectName, "/") {
  144. continue
  145. }
  146. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  147. parentDirectoryPath, entryName, isDeleteData, isRecursive := "/", object.ObjectName, true, true
  148. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  149. entryName = object.ObjectName[lastSeparator+1:]
  150. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  151. }
  152. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  153. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  154. if err == nil {
  155. deletedObjects = append(deletedObjects, object)
  156. } else {
  157. deleteErrors = append(deleteErrors, DeleteError{
  158. Code: "",
  159. Message: err.Error(),
  160. Key: object.ObjectName,
  161. })
  162. }
  163. }
  164. return nil
  165. })
  166. deleteResp := DeleteObjectsResponse{}
  167. if !deleteObjects.Quiet {
  168. deleteResp.DeletedObjects = deletedObjects
  169. }
  170. deleteResp.Errors = deleteErrors
  171. writeSuccessResponseXML(w, encodeResponse(deleteResp))
  172. }
  173. var passThroughHeaders = []string{
  174. "response-cache-control",
  175. "response-content-disposition",
  176. "response-content-encoding",
  177. "response-content-language",
  178. "response-content-type",
  179. "response-expires",
  180. }
  181. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, responseFn func(proxyResponse *http.Response, w http.ResponseWriter)) {
  182. glog.V(2).Infof("s3 proxying %s to %s", r.Method, destUrl)
  183. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  184. if err != nil {
  185. glog.Errorf("NewRequest %s: %v", destUrl, err)
  186. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  187. return
  188. }
  189. proxyReq.Header.Set("Host", s3a.option.Filer)
  190. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  191. for header, values := range r.Header {
  192. // handle s3 related headers
  193. passed := false
  194. for _, h := range passThroughHeaders {
  195. if strings.ToLower(header) == h && len(values) > 0 {
  196. proxyReq.Header.Add(header[len("response-"):], values[0])
  197. passed = true
  198. break
  199. }
  200. }
  201. if passed {
  202. continue
  203. }
  204. // handle other headers
  205. for _, value := range values {
  206. proxyReq.Header.Add(header, value)
  207. }
  208. }
  209. resp, postErr := client.Do(proxyReq)
  210. if (resp.ContentLength == -1 || resp.StatusCode == 404) && !strings.HasSuffix(destUrl, "/") {
  211. writeErrorResponse(w, s3err.ErrNoSuchKey, r.URL)
  212. return
  213. }
  214. if postErr != nil {
  215. glog.Errorf("post to filer: %v", postErr)
  216. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  217. return
  218. }
  219. defer util.CloseResponse(resp)
  220. responseFn(resp, w)
  221. }
  222. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) {
  223. for k, v := range proxyResponse.Header {
  224. w.Header()[k] = v
  225. }
  226. w.WriteHeader(proxyResponse.StatusCode)
  227. io.Copy(w, proxyResponse.Body)
  228. }
  229. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code s3err.ErrorCode) {
  230. hash := md5.New()
  231. var body = io.TeeReader(dataReader, hash)
  232. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  233. if err != nil {
  234. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  235. return "", s3err.ErrInternalError
  236. }
  237. proxyReq.Header.Set("Host", s3a.option.Filer)
  238. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  239. for header, values := range r.Header {
  240. for _, value := range values {
  241. proxyReq.Header.Add(header, value)
  242. }
  243. }
  244. resp, postErr := client.Do(proxyReq)
  245. if postErr != nil {
  246. glog.Errorf("post to filer: %v", postErr)
  247. return "", s3err.ErrInternalError
  248. }
  249. defer resp.Body.Close()
  250. etag = fmt.Sprintf("%x", hash.Sum(nil))
  251. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  252. if ra_err != nil {
  253. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  254. return etag, s3err.ErrInternalError
  255. }
  256. var ret weed_server.FilerPostResult
  257. unmarshal_err := json.Unmarshal(resp_body, &ret)
  258. if unmarshal_err != nil {
  259. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  260. return "", s3err.ErrInternalError
  261. }
  262. if ret.Error != "" {
  263. glog.Errorf("upload to filer error: %v", ret.Error)
  264. return "", filerErrorToS3Error(ret.Error)
  265. }
  266. return etag, s3err.ErrNone
  267. }
  268. func setEtag(w http.ResponseWriter, etag string) {
  269. if etag != "" {
  270. if strings.HasPrefix(etag, "\"") {
  271. w.Header().Set("ETag", etag)
  272. } else {
  273. w.Header().Set("ETag", "\""+etag+"\"")
  274. }
  275. }
  276. }
  277. func getBucketAndObject(r *http.Request) (bucket, object string) {
  278. vars := mux.Vars(r)
  279. bucket = vars["bucket"]
  280. object = vars["object"]
  281. if !strings.HasPrefix(object, "/") {
  282. object = "/" + object
  283. }
  284. return
  285. }
  286. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  287. if strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory") {
  288. return s3err.ErrExistingObjectIsDirectory
  289. }
  290. return s3err.ErrInternalError
  291. }