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.

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