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.

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