s3api_object_handlers.go 14 KB

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