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.

235 lines
6.7 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
3 years ago
3 years ago
5 years ago
  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. if r.URL.Query().Has("metadata") {
  109. writeJsonQuiet(w, r, http.StatusOK, entry)
  110. return
  111. }
  112. etag := filer.ETagEntry(entry)
  113. if checkPreconditions(w, r, entry) {
  114. return
  115. }
  116. w.Header().Set("Accept-Ranges", "bytes")
  117. // mime type
  118. mimeType := entry.Attr.Mime
  119. if mimeType == "" {
  120. if ext := filepath.Ext(entry.Name()); ext != "" {
  121. mimeType = mime.TypeByExtension(ext)
  122. }
  123. }
  124. if mimeType != "" {
  125. w.Header().Set("Content-Type", mimeType)
  126. }
  127. // print out the header from extended properties
  128. for k, v := range entry.Extended {
  129. if !strings.HasPrefix(k, "xattr-") {
  130. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  131. w.Header().Set(k, string(v))
  132. }
  133. }
  134. //Seaweed custom header are not visible to Vue or javascript
  135. seaweedHeaders := []string{}
  136. for header := range w.Header() {
  137. if strings.HasPrefix(header, "Seaweed-") {
  138. seaweedHeaders = append(seaweedHeaders, header)
  139. }
  140. }
  141. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  142. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  143. //set tag count
  144. tagCount := 0
  145. for k := range entry.Extended {
  146. if strings.HasPrefix(k, xhttp.AmzObjectTagging+"-") {
  147. tagCount++
  148. }
  149. }
  150. if tagCount > 0 {
  151. w.Header().Set(xhttp.AmzTagCount, strconv.Itoa(tagCount))
  152. }
  153. setEtag(w, etag)
  154. filename := entry.Name()
  155. adjustPassthroughHeaders(w, r, filename)
  156. totalSize := int64(entry.Size())
  157. if r.Method == "HEAD" {
  158. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  159. return
  160. }
  161. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  162. ext := filepath.Ext(filename)
  163. if len(ext) > 0 {
  164. ext = strings.ToLower(ext)
  165. }
  166. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  167. if shouldResize {
  168. data, err := filer.ReadAll(fs.filer.MasterClient, entry.Chunks)
  169. if err != nil {
  170. glog.Errorf("failed to read %s: %v", path, err)
  171. w.WriteHeader(http.StatusNotModified)
  172. return
  173. }
  174. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  175. io.Copy(w, rs)
  176. return
  177. }
  178. }
  179. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  180. if offset+size <= int64(len(entry.Content)) {
  181. _, err := writer.Write(entry.Content[offset : offset+size])
  182. if err != nil {
  183. stats.FilerRequestCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  184. glog.Errorf("failed to write entry content: %v", err)
  185. }
  186. return err
  187. }
  188. chunks := entry.Chunks
  189. if entry.IsInRemoteOnly() {
  190. dir, name := entry.FullPath.DirAndName()
  191. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  192. Directory: dir,
  193. Name: name,
  194. }); err != nil {
  195. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  196. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  197. return fmt.Errorf("cache %s: %v", entry.FullPath, err)
  198. } else {
  199. chunks = resp.Entry.Chunks
  200. }
  201. }
  202. err = filer.StreamContent(fs.filer.MasterClient, writer, chunks, offset, size)
  203. if err != nil {
  204. stats.FilerRequestCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  205. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  206. }
  207. return err
  208. })
  209. }