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.

457 lines
12 KiB

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