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.

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