filer_server_handlers_read.go 6.6 KB

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