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.

320 lines
9.9 KiB

9 years ago
9 years ago
9 years ago
9 years ago
6 months ago
9 years ago
8 months ago
8 months ago
5 years ago
6 months ago
6 months ago
8 months ago
8 months ago
8 months ago
4 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  10. "github.com/seaweedfs/seaweedfs/weed/s3api/s3acl"
  11. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  12. "io"
  13. "math"
  14. "mime"
  15. "net/http"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/seaweedfs/seaweedfs/weed/filer"
  21. "github.com/seaweedfs/seaweedfs/weed/glog"
  22. "github.com/seaweedfs/seaweedfs/weed/images"
  23. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  24. "github.com/seaweedfs/seaweedfs/weed/security"
  25. "github.com/seaweedfs/seaweedfs/weed/stats"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. )
  28. // Validates the preconditions. Returns true if GET/HEAD operation should not proceed.
  29. // Preconditions supported are:
  30. //
  31. // If-Modified-Since
  32. // If-Unmodified-Since
  33. // If-Match
  34. // If-None-Match
  35. func checkPreconditions(w http.ResponseWriter, r *http.Request, entry *filer.Entry) bool {
  36. etag := filer.ETagEntry(entry)
  37. /// When more than one conditional request header field is present in a
  38. /// request, the order in which the fields are evaluated becomes
  39. /// important. In practice, the fields defined in this document are
  40. /// consistently implemented in a single, logical order, since "lost
  41. /// update" preconditions have more strict requirements than cache
  42. /// validation, a validated cache is more efficient than a partial
  43. /// response, and entity tags are presumed to be more accurate than date
  44. /// validators. https://tools.ietf.org/html/rfc7232#section-5
  45. if entry.Attr.Mtime.IsZero() {
  46. return false
  47. }
  48. w.Header().Set("Last-Modified", entry.Attr.Mtime.UTC().Format(http.TimeFormat))
  49. ifMatchETagHeader := r.Header.Get("If-Match")
  50. ifUnmodifiedSinceHeader := r.Header.Get("If-Unmodified-Since")
  51. if ifMatchETagHeader != "" {
  52. if util.CanonicalizeETag(etag) != util.CanonicalizeETag(ifMatchETagHeader) {
  53. w.WriteHeader(http.StatusPreconditionFailed)
  54. return true
  55. }
  56. } else if ifUnmodifiedSinceHeader != "" {
  57. if t, parseError := time.Parse(http.TimeFormat, ifUnmodifiedSinceHeader); parseError == nil {
  58. if t.Before(entry.Attr.Mtime) {
  59. w.WriteHeader(http.StatusPreconditionFailed)
  60. return true
  61. }
  62. }
  63. }
  64. ifNoneMatchETagHeader := r.Header.Get("If-None-Match")
  65. ifModifiedSinceHeader := r.Header.Get("If-Modified-Since")
  66. if ifNoneMatchETagHeader != "" {
  67. if util.CanonicalizeETag(etag) == util.CanonicalizeETag(ifNoneMatchETagHeader) {
  68. SetEtag(w, etag)
  69. w.WriteHeader(http.StatusNotModified)
  70. return true
  71. }
  72. } else if ifModifiedSinceHeader != "" {
  73. if t, parseError := time.Parse(http.TimeFormat, ifModifiedSinceHeader); parseError == nil {
  74. if !t.Before(entry.Attr.Mtime) {
  75. SetEtag(w, etag)
  76. w.WriteHeader(http.StatusNotModified)
  77. return true
  78. }
  79. }
  80. }
  81. return false
  82. }
  83. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  84. path := r.URL.Path
  85. isForDirectory := strings.HasSuffix(path, "/")
  86. if isForDirectory && len(path) > 1 {
  87. path = path[:len(path)-1]
  88. }
  89. entry, err := fs.filer.FindEntry(context.Background(), util.FullPath(path))
  90. if err != nil {
  91. if path == "/" {
  92. fs.listDirectoryHandler(w, r)
  93. return
  94. }
  95. if err == filer_pb.ErrNotFound {
  96. glog.V(2).Infof("Not found %s: %v", path, err)
  97. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadNotFound).Inc()
  98. if r.Header.Get(s3_constants.XAmzBucketAccessDenied) == "true" {
  99. w.WriteHeader(http.StatusForbidden)
  100. } else {
  101. w.WriteHeader(http.StatusNotFound)
  102. }
  103. } else {
  104. glog.Errorf("Internal %s: %v", path, err)
  105. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  106. w.WriteHeader(http.StatusInternalServerError)
  107. }
  108. return
  109. }
  110. //s3 acl offload to filer
  111. offloadHeaderBucketOwner := r.Header.Get(s3_constants.XAmzBucketOwnerId)
  112. if len(offloadHeaderBucketOwner) > 0 {
  113. if statusCode, ok := s3acl.CheckObjectAccessForReadObject(r, w, entry, offloadHeaderBucketOwner); !ok {
  114. w.WriteHeader(statusCode)
  115. return
  116. }
  117. }
  118. query := r.URL.Query()
  119. if entry.IsDirectory() {
  120. if fs.option.DisableDirListing {
  121. w.WriteHeader(http.StatusForbidden)
  122. return
  123. }
  124. if query.Get("metadata") == "true" {
  125. writeJsonQuiet(w, r, http.StatusOK, entry)
  126. return
  127. }
  128. if entry.Attr.Mime == "" || (entry.Attr.Mime == s3_constants.FolderMimeType && r.Header.Get(s3_constants.AmzIdentityId) == "") {
  129. // Don't return directory meta if config value is set to true
  130. if fs.option.ExposeDirectoryData == false {
  131. writeJsonError(w, r, http.StatusForbidden, errors.New("directory listing is disabled"))
  132. return
  133. }
  134. // return index of directory for non s3 gateway
  135. fs.listDirectoryHandler(w, r)
  136. return
  137. }
  138. // inform S3 API this is a user created directory key object
  139. w.Header().Set(s3_constants.SeaweedFSIsDirectoryKey, "true")
  140. }
  141. if isForDirectory && entry.Attr.Mime != s3_constants.FolderMimeType {
  142. w.WriteHeader(http.StatusNotFound)
  143. return
  144. }
  145. if query.Get("metadata") == "true" {
  146. if query.Get("resolveManifest") == "true" {
  147. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  148. fs.filer.MasterClient.GetLookupFileIdFunction(),
  149. entry.GetChunks(), 0, math.MaxInt64); err != nil {
  150. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  151. writeJsonError(w, r, http.StatusInternalServerError, err)
  152. return
  153. }
  154. }
  155. writeJsonQuiet(w, r, http.StatusOK, entry)
  156. return
  157. }
  158. if checkPreconditions(w, r, entry) {
  159. return
  160. }
  161. var etag string
  162. if partNumber, errNum := strconv.Atoi(r.Header.Get(s3_constants.SeaweedFSPartNumber)); errNum == nil {
  163. if len(entry.Chunks) < partNumber {
  164. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadChunk).Inc()
  165. w.WriteHeader(http.StatusBadRequest)
  166. w.Write([]byte("InvalidPart"))
  167. return
  168. }
  169. w.Header().Set(s3_constants.AmzMpPartsCount, strconv.Itoa(len(entry.Chunks)))
  170. partChunk := entry.GetChunks()[partNumber-1]
  171. md5, _ := base64.StdEncoding.DecodeString(partChunk.ETag)
  172. etag = hex.EncodeToString(md5)
  173. r.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", partChunk.Offset, uint64(partChunk.Offset)+partChunk.Size-1))
  174. } else {
  175. etag = filer.ETagEntry(entry)
  176. }
  177. w.Header().Set("Accept-Ranges", "bytes")
  178. // mime type
  179. mimeType := entry.Attr.Mime
  180. if mimeType == "" {
  181. if ext := filepath.Ext(entry.Name()); ext != "" {
  182. mimeType = mime.TypeByExtension(ext)
  183. }
  184. }
  185. if mimeType != "" {
  186. w.Header().Set("Content-Type", mimeType)
  187. } else {
  188. w.Header().Set("Content-Type", "application/octet-stream")
  189. }
  190. // print out the header from extended properties
  191. for k, v := range entry.Extended {
  192. if strings.HasPrefix(k, "xattr-") {
  193. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  194. continue
  195. }
  196. if strings.HasPrefix(k, "Seaweed-X-") {
  197. // key with "Seaweed-X-" prefix is builtin and should not expose to user
  198. continue
  199. }
  200. w.Header().Set(k, string(v))
  201. }
  202. //Seaweed custom header are not visible to Vue or javascript
  203. seaweedHeaders := []string{}
  204. for header := range w.Header() {
  205. if strings.HasPrefix(header, "Seaweed-") {
  206. seaweedHeaders = append(seaweedHeaders, header)
  207. }
  208. }
  209. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  210. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  211. //set tag count
  212. tagCount := 0
  213. for k := range entry.Extended {
  214. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  215. tagCount++
  216. }
  217. }
  218. if tagCount > 0 {
  219. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  220. }
  221. SetEtag(w, etag)
  222. filename := entry.Name()
  223. AdjustPassthroughHeaders(w, r, filename)
  224. totalSize := int64(entry.Size())
  225. if r.Method == http.MethodHead {
  226. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  227. return
  228. }
  229. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  230. ext := filepath.Ext(filename)
  231. if len(ext) > 0 {
  232. ext = strings.ToLower(ext)
  233. }
  234. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  235. if shouldResize {
  236. data := mem.Allocate(int(totalSize))
  237. defer mem.Free(data)
  238. err := filer.ReadAll(data, fs.filer.MasterClient, entry.GetChunks())
  239. if err != nil {
  240. glog.Errorf("failed to read %s: %v", path, err)
  241. w.WriteHeader(http.StatusInternalServerError)
  242. return
  243. }
  244. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  245. io.Copy(w, rs)
  246. return
  247. }
  248. }
  249. ProcessRangeRequest(r, w, totalSize, mimeType, func(offset int64, size int64) (filer.DoStreamContent, error) {
  250. if offset+size <= int64(len(entry.Content)) {
  251. return func(writer io.Writer) error {
  252. _, err := writer.Write(entry.Content[offset : offset+size])
  253. if err != nil {
  254. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  255. glog.Errorf("failed to write entry content: %v", err)
  256. }
  257. return err
  258. }, nil
  259. }
  260. chunks := entry.GetChunks()
  261. if entry.IsInRemoteOnly() {
  262. dir, name := entry.FullPath.DirAndName()
  263. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  264. Directory: dir,
  265. Name: name,
  266. }); err != nil {
  267. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  268. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  269. return nil, fmt.Errorf("cache %s: %v", entry.FullPath, err)
  270. } else {
  271. chunks = resp.Entry.GetChunks()
  272. }
  273. }
  274. streamFn, err := filer.PrepareStreamContentWithThrottler(fs.filer.MasterClient, fs.maybeGetVolumeReadJwtAuthorizationToken, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  275. if err != nil {
  276. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  277. glog.Errorf("failed to prepare stream content %s: %v", r.URL, err)
  278. return nil, err
  279. }
  280. return func(writer io.Writer) error {
  281. err := streamFn(writer)
  282. if err != nil {
  283. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  284. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  285. }
  286. return err
  287. }, nil
  288. })
  289. }
  290. func (fs *FilerServer) maybeGetVolumeReadJwtAuthorizationToken(fileId string) string {
  291. return string(security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey, fs.volumeGuard.ReadExpiresAfterSec, fileId))
  292. }