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