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.

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