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.

397 lines
10 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. "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 = s3a.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 (s3a *S3ApiServer) 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 parentDir == s3a.option.BucketsPath {
  186. continue
  187. }
  188. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  189. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  190. } else {
  191. newDirectoriesWithDeletion[parentDir]++
  192. }
  193. }
  194. return
  195. }
  196. var passThroughHeaders = []string{
  197. "response-cache-control",
  198. "response-content-disposition",
  199. "response-content-encoding",
  200. "response-content-language",
  201. "response-content-type",
  202. "response-expires",
  203. }
  204. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, responseFn func(proxyResponse *http.Response, w http.ResponseWriter)) {
  205. glog.V(2).Infof("s3 proxying %s to %s", r.Method, destUrl)
  206. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  207. if err != nil {
  208. glog.Errorf("NewRequest %s: %v", destUrl, err)
  209. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  210. return
  211. }
  212. proxyReq.Header.Set("Host", s3a.option.Filer)
  213. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  214. for header, values := range r.Header {
  215. // handle s3 related headers
  216. passed := false
  217. for _, h := range passThroughHeaders {
  218. if strings.ToLower(header) == h && len(values) > 0 {
  219. proxyReq.Header.Add(header[len("response-"):], values[0])
  220. passed = true
  221. break
  222. }
  223. }
  224. if passed {
  225. continue
  226. }
  227. // handle other headers
  228. for _, value := range values {
  229. proxyReq.Header.Add(header, value)
  230. }
  231. }
  232. resp, postErr := client.Do(proxyReq)
  233. if postErr != nil {
  234. glog.Errorf("post to filer: %v", postErr)
  235. writeErrorResponse(w, s3err.ErrInternalError, r.URL)
  236. return
  237. }
  238. defer util.CloseResponse(resp)
  239. if (resp.ContentLength == -1 || resp.StatusCode == 404) && !strings.HasSuffix(destUrl, "/") {
  240. if r.Method != "DELETE" {
  241. writeErrorResponse(w, s3err.ErrNoSuchKey, r.URL)
  242. return
  243. }
  244. }
  245. responseFn(resp, w)
  246. }
  247. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) {
  248. for k, v := range proxyResponse.Header {
  249. w.Header()[k] = v
  250. }
  251. w.WriteHeader(proxyResponse.StatusCode)
  252. io.Copy(w, proxyResponse.Body)
  253. }
  254. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code s3err.ErrorCode) {
  255. hash := md5.New()
  256. var body = io.TeeReader(dataReader, hash)
  257. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  258. if err != nil {
  259. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  260. return "", s3err.ErrInternalError
  261. }
  262. proxyReq.Header.Set("Host", s3a.option.Filer)
  263. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  264. for header, values := range r.Header {
  265. for _, value := range values {
  266. proxyReq.Header.Add(header, value)
  267. }
  268. }
  269. resp, postErr := client.Do(proxyReq)
  270. if postErr != nil {
  271. glog.Errorf("post to filer: %v", postErr)
  272. return "", s3err.ErrInternalError
  273. }
  274. defer resp.Body.Close()
  275. etag = fmt.Sprintf("%x", hash.Sum(nil))
  276. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  277. if ra_err != nil {
  278. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  279. return etag, s3err.ErrInternalError
  280. }
  281. var ret weed_server.FilerPostResult
  282. unmarshal_err := json.Unmarshal(resp_body, &ret)
  283. if unmarshal_err != nil {
  284. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  285. return "", s3err.ErrInternalError
  286. }
  287. if ret.Error != "" {
  288. glog.Errorf("upload to filer error: %v", ret.Error)
  289. return "", filerErrorToS3Error(ret.Error)
  290. }
  291. return etag, s3err.ErrNone
  292. }
  293. func setEtag(w http.ResponseWriter, etag string) {
  294. if etag != "" {
  295. if strings.HasPrefix(etag, "\"") {
  296. w.Header().Set("ETag", etag)
  297. } else {
  298. w.Header().Set("ETag", "\""+etag+"\"")
  299. }
  300. }
  301. }
  302. func getBucketAndObject(r *http.Request) (bucket, object string) {
  303. vars := mux.Vars(r)
  304. bucket = vars["bucket"]
  305. object = vars["object"]
  306. if !strings.HasPrefix(object, "/") {
  307. object = "/" + object
  308. }
  309. return
  310. }
  311. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  312. if strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory") {
  313. return s3err.ErrExistingObjectIsDirectory
  314. }
  315. return s3err.ErrInternalError
  316. }