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.

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