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.

394 lines
10 KiB

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