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.

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