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.

442 lines
12 KiB

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