s3api_object_handlers.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. }