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.

440 lines
12 KiB

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