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.

279 lines
8.3 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
5 years ago
3 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "mime"
  10. "net/http"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  16. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  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. setEtag(w, etag)
  65. w.WriteHeader(http.StatusNotModified)
  66. return true
  67. }
  68. } else if ifModifiedSinceHeader != "" {
  69. if t, parseError := time.Parse(http.TimeFormat, ifModifiedSinceHeader); parseError == nil {
  70. if !t.Before(entry.Attr.Mtime) {
  71. setEtag(w, etag)
  72. w.WriteHeader(http.StatusNotModified)
  73. return true
  74. }
  75. }
  76. }
  77. return false
  78. }
  79. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  80. path := r.URL.Path
  81. isForDirectory := strings.HasSuffix(path, "/")
  82. if isForDirectory && len(path) > 1 {
  83. path = path[:len(path)-1]
  84. }
  85. entry, err := fs.filer.FindEntry(context.Background(), util.FullPath(path))
  86. if err != nil {
  87. if path == "/" {
  88. fs.listDirectoryHandler(w, r)
  89. return
  90. }
  91. if err == filer_pb.ErrNotFound {
  92. glog.V(2).Infof("Not found %s: %v", path, err)
  93. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadNotFound).Inc()
  94. w.WriteHeader(http.StatusNotFound)
  95. } else {
  96. glog.Errorf("Internal %s: %v", path, err)
  97. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadInternal).Inc()
  98. w.WriteHeader(http.StatusInternalServerError)
  99. }
  100. return
  101. }
  102. query := r.URL.Query()
  103. if entry.IsDirectory() {
  104. if fs.option.DisableDirListing {
  105. w.WriteHeader(http.StatusForbidden)
  106. return
  107. }
  108. if query.Get("metadata") == "true" {
  109. // Don't return directory meta if config value is set to true
  110. if fs.option.ExposeDirectoryData == false {
  111. writeJsonError(w, r, http.StatusForbidden, errors.New("directory listing is disabled"))
  112. return
  113. }
  114. }
  115. if entry.Attr.Mime == "" || (entry.Attr.Mime == s3_constants.FolderMimeType && r.Header.Get(s3_constants.AmzIdentityId) == "") {
  116. // return index of directory for non s3 gateway
  117. fs.listDirectoryHandler(w, r)
  118. return
  119. }
  120. // inform S3 API this is a user created directory key object
  121. w.Header().Set(s3_constants.X_SeaweedFS_Header_Directory_Key, "true")
  122. }
  123. if isForDirectory && entry.Attr.Mime != s3_constants.FolderMimeType {
  124. w.WriteHeader(http.StatusNotFound)
  125. return
  126. }
  127. if query.Get("metadata") == "true" {
  128. if query.Get("resolveManifest") == "true" {
  129. if entry.Chunks, _, err = filer.ResolveChunkManifest(
  130. fs.filer.MasterClient.GetLookupFileIdFunction(),
  131. entry.GetChunks(), 0, math.MaxInt64); err != nil {
  132. err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error())
  133. writeJsonError(w, r, http.StatusInternalServerError, err)
  134. return
  135. }
  136. }
  137. writeJsonQuiet(w, r, http.StatusOK, entry)
  138. return
  139. }
  140. if checkPreconditions(w, r, entry) {
  141. return
  142. }
  143. etag := filer.ETagEntry(entry)
  144. w.Header().Set("Accept-Ranges", "bytes")
  145. // mime type
  146. mimeType := entry.Attr.Mime
  147. if mimeType == "" {
  148. if ext := filepath.Ext(entry.Name()); ext != "" {
  149. mimeType = mime.TypeByExtension(ext)
  150. }
  151. }
  152. if mimeType != "" {
  153. w.Header().Set("Content-Type", mimeType)
  154. } else {
  155. w.Header().Set("Content-Type", "application/octet-stream")
  156. }
  157. // print out the header from extended properties
  158. for k, v := range entry.Extended {
  159. if !strings.HasPrefix(k, "xattr-") {
  160. // "xattr-" prefix is set in filesys.XATTR_PREFIX
  161. w.Header().Set(k, string(v))
  162. }
  163. }
  164. //Seaweed custom header are not visible to Vue or javascript
  165. seaweedHeaders := []string{}
  166. for header := range w.Header() {
  167. if strings.HasPrefix(header, "Seaweed-") {
  168. seaweedHeaders = append(seaweedHeaders, header)
  169. }
  170. }
  171. seaweedHeaders = append(seaweedHeaders, "Content-Disposition")
  172. w.Header().Set("Access-Control-Expose-Headers", strings.Join(seaweedHeaders, ","))
  173. //set tag count
  174. tagCount := 0
  175. for k := range entry.Extended {
  176. if strings.HasPrefix(k, s3_constants.AmzObjectTagging+"-") {
  177. tagCount++
  178. }
  179. }
  180. if tagCount > 0 {
  181. w.Header().Set(s3_constants.AmzTagCount, strconv.Itoa(tagCount))
  182. }
  183. setEtag(w, etag)
  184. filename := entry.Name()
  185. adjustPassthroughHeaders(w, r, filename)
  186. totalSize := int64(entry.Size())
  187. if r.Method == "HEAD" {
  188. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  189. return
  190. }
  191. if rangeReq := r.Header.Get("Range"); rangeReq == "" {
  192. ext := filepath.Ext(filename)
  193. if len(ext) > 0 {
  194. ext = strings.ToLower(ext)
  195. }
  196. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  197. if shouldResize {
  198. data := mem.Allocate(int(totalSize))
  199. defer mem.Free(data)
  200. err := filer.ReadAll(data, fs.filer.MasterClient, entry.GetChunks())
  201. if err != nil {
  202. glog.Errorf("failed to read %s: %v", path, err)
  203. w.WriteHeader(http.StatusInternalServerError)
  204. return
  205. }
  206. rs, _, _ := images.Resized(ext, bytes.NewReader(data), width, height, mode)
  207. io.Copy(w, rs)
  208. return
  209. }
  210. }
  211. processRangeRequest(r, w, totalSize, mimeType, func(offset int64, size int64) (filer.DoStreamContent, error) {
  212. if offset+size <= int64(len(entry.Content)) {
  213. return func(writer io.Writer) error {
  214. _, err := writer.Write(entry.Content[offset : offset+size])
  215. if err != nil {
  216. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorWriteEntry).Inc()
  217. glog.Errorf("failed to write entry content: %v", err)
  218. }
  219. return err
  220. }, nil
  221. }
  222. chunks := entry.GetChunks()
  223. if entry.IsInRemoteOnly() {
  224. dir, name := entry.FullPath.DirAndName()
  225. if resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
  226. Directory: dir,
  227. Name: name,
  228. }); err != nil {
  229. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadCache).Inc()
  230. glog.Errorf("CacheRemoteObjectToLocalCluster %s: %v", entry.FullPath, err)
  231. return nil, fmt.Errorf("cache %s: %v", entry.FullPath, err)
  232. } else {
  233. chunks = resp.Entry.GetChunks()
  234. }
  235. }
  236. streamFn, err := filer.PrepareStreamContentWithThrottler(fs.filer.MasterClient, chunks, offset, size, fs.option.DownloadMaxBytesPs)
  237. if err != nil {
  238. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  239. glog.Errorf("failed to prepare stream content %s: %v", r.URL, err)
  240. return nil, err
  241. }
  242. return func(writer io.Writer) error {
  243. err := streamFn(writer)
  244. if err != nil {
  245. stats.FilerHandlerCounter.WithLabelValues(stats.ErrorReadStream).Inc()
  246. glog.Errorf("failed to stream content %s: %v", r.URL, err)
  247. }
  248. return err
  249. }, nil
  250. })
  251. }