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.

284 lines
8.6 KiB

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