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.

247 lines
7.1 KiB

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