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.

454 lines
12 KiB

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