filer_server_handlers_read.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  7. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  8. "io"
  9. "math"
  10. "mime"
  11. "net/http"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "golang.org/x/exp/slices"
  17. "github.com/seaweedfs/seaweedfs/weed/filer"
  18. "github.com/seaweedfs/seaweedfs/weed/glog"
  19. "github.com/seaweedfs/seaweedfs/weed/images"
  20. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  21. "github.com/seaweedfs/seaweedfs/weed/stats"
  22. "github.com/seaweedfs/seaweedfs/weed/util"
  23. )
  24. // Validates the preconditions. Returns true if GET/HEAD operation should not proceed.
  25. // Preconditions supported are:
  26. //
  27. // If-Modified-Since
  28. // If-Unmodified-Since
  29. // If-Match
  30. // If-None-Match
  31. func checkPreconditions(w http.ResponseWriter, r *http.Request, entry *filer.Entry) bool {
  32. etag := filer.ETagEntry(entry)
  33. /// When more than one conditional request header field is present in a
  34. /// request, the order in which the fields are evaluated becomes
  35. /// important. In practice, the fields defined in this document are
  36. /// consistently implemented in a single, logical order, since "lost
  37. /// update" preconditions have more strict requirements than cache
  38. /// validation, a validated cache is more efficient than a partial
  39. /// response, and entity tags are presumed to be more accurate than date
  40. /// validators. https://tools.ietf.org/html/rfc7232#section-5
  41. if entry.Attr.Mtime.IsZero() {
  42. return false
  43. }
  44. w.Header().Set("Last-Modified", entry.Attr.Mtime.UTC().Format(http.TimeFormat))
  45. ifMatchETagHeader := r.Header.Get("If-Match")
  46. ifUnmodifiedSinceHeader := r.Header.Get("If-Unmodified-Since")
  47. if ifMatchETagHeader != "" {
  48. if util.CanonicalizeETag(etag) != util.CanonicalizeETag(ifMatchETagHeader) {
  49. w.WriteHeader(http.StatusPreconditionFailed)
  50. return true
  51. }
  52. } else if ifUnmodifiedSinceHeader != "" {
  53. if t, parseError := time.Parse(http.TimeFormat, ifUnmodifiedSinceHeader); parseError == nil {
  54. if t.Before(entry.Attr.Mtime) {
  55. w.WriteHeader(http.StatusPreconditionFailed)
  56. return true
  57. }
  58. }
  59. }
  60. ifNoneMatchETagHeader := r.Header.Get("If-None-Match")
  61. ifModifiedSinceHeader := r.Header.Get("If-Modified-Since")
  62. if ifNoneMatchETagHeader != "" {
  63. if util.CanonicalizeETag(etag) == util.CanonicalizeETag(ifNoneMatchETagHeader) {
  64. w.WriteHeader(http.StatusNotModified)
  65. return true
  66. }
  67. } else if ifModifiedSinceHeader != "" {
  68. if t, parseError := time.Parse(http.TimeFormat, ifModifiedSinceHeader); parseError == nil {
  69. if !t.Before(entry.Attr.Mtime) {
  70. w.WriteHeader(http.StatusNotModified)
  71. return true
  72. }
  73. }
  74. }
  75. return false
  76. }
  77. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  78. path := r.URL.Path
  79. isForDirectory := strings.HasSuffix(path, "/")
  80. if isForDirectory && len(path) > 1 {
  81. path = path[:len(path)-1]
  82. }
  83. entry, err := fs.filer.FindEntry(context.Background(), util.FullPath(path))
  84. if err != nil {
  85. if path == "/" {
  86. fs.listDirectoryHandler(w, r)
  87. return
  88. }
  89. if err == filer_pb.ErrNotFound {
  90. glog.V(2).Infof("Not found %s: %v", path, err)
  91. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadNotFound).Inc()
  92. w.WriteHeader(http.StatusNotFound)
  93. } else {
  94. glog.Errorf("Internal %s: %v", path, err)
  95. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  96. w.WriteHeader(http.StatusInternalServerError)
  97. }
  98. return
  99. }
  100. query := r.URL.Query()
  101. if entry.IsDirectory() {
  102. if fs.option.DisableDirListing {
  103. w.WriteHeader(http.StatusForbidden)
  104. return
  105. }
  106. if query.Get("metadata") == "true" {
  107. writeJsonQuiet(w, r, http.StatusOK, entry)
  108. return
  109. }
  110. if slices.Contains([]string{"httpd/unix-directory", ""}, entry.Attr.Mime) {
  111. fs.listDirectoryHandler(w, r)
  112. return
  113. }
  114. // inform S3 API this is a user created directory key object
  115. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  116. }
  117. if isForDirectory {
  118. w.WriteHeader(http.StatusNotFound)
  119. return
  120. }
  121. if query.Get("metadata") == "true" {
  122. if query.Get("resolveManifest") == "true" {
  123. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  124. fs.filer.MasterClient.GetLookupFileIdFunction(),
  125. entry.GetChunks(), 0, math.MaxInt64); err != nil {
  126. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  127. writeJsonError(w, r, http.StatusInternalServerError, err)
  128. }
  129. }
  130. writeJsonQuiet(w, r, http.StatusOK, entry)
  131. return
  132. }
  133. etag := filer.ETagEntry(entry)
  134. if checkPreconditions(w, r, entry) {
  135. return
  136. }
  137. w.Header().Set("Accept-Ranges", "bytes")
  138. // mime type
  139. mimeType := entry.Attr.Mime
  140. if mimeType == "" {
  141. if ext := filepath.Ext(entry.Name()); ext != "" {
  142. mimeType = mime.TypeByExtension(ext)
  143. }
  144. }
  145. if mimeType != "" {
  146. w.Header().Set("Content-Type", mimeType)
  147. } else {
  148. w.Header().Set("Content-Type", "application/octet-stream")
  149. }
  150. // print out the header from extended properties
  151. for k, v := range entry.Extended {
  152. if !strings.HasPrefix(k, "xattr-") {
  153. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  154. w.Header().Set(k, string(v))
  155. }
  156. }
  157. //Seaweed custom header are not visible to Vue or javascript
  158. seaweedHeaders := []string{}
  159. for header := range w.Header() {
  160. if strings.HasPrefix(header, "Seaweed-") {
  161. seaweedHeaders = append(seaweedHeaders, header)
  162. }
  163. }
  164. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  165. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  166. //set tag count
  167. tagCount := 0
  168. for k := range entry.Extended {
  169. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  170. tagCount++
  171. }
  172. }
  173. if tagCount > 0 {
  174. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  175. }
  176. setEtag(w, etag)
  177. filename := entry.Name()
  178. adjustPassthroughHeaders(w, r, filename)
  179. totalSize := int64(entry.Size())
  180. if r.Method == "HEAD" {
  181. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  182. return
  183. }
  184. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  185. ext := filepath.Ext(filename)
  186. if len(ext) > 0 {
  187. ext = strings.ToLower(ext)
  188. }
  189. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  190. if shouldResize {
  191. data := mem.Allocate(int(totalSize))
  192. defer mem.Free(data)
  193. err := filer.ReadAll(data, fs.filer.MasterClient, entry.GetChunks())
  194. if err != nil {
  195. glog.Errorf("failed to read %s: %v", path, err)
  196. w.WriteHeader(http.StatusInternalServerError)
  197. return
  198. }
  199. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  200. io.Copy(w, rs)
  201. return
  202. }
  203. }
  204. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  205. if offset+size <= int64(len(entry.Content)) {
  206. _, err := writer.Write(entry.Content[offset : offset+size])
  207. if err != nil {
  208. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  209. glog.Errorf("failed to write entry content: %v", err)
  210. }
  211. return err
  212. }
  213. chunks := entry.GetChunks()
  214. if entry.IsInRemoteOnly() {
  215. dir, name := entry.FullPath.DirAndName()
  216. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  217. Directory: dir,
  218. Name: name,
  219. }); err != nil {
  220. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  221. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  222. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  223. } else {
  224. chunks = resp.Entry.GetChunks()
  225. }
  226. }
  227. err = filer.StreamContentWithThrottler(fs.filer.MasterClient, writer, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  228. if err != nil {
  229. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  230. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  231. }
  232. return err
  233. })
  234. }