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.

263 lines
7.2 KiB

9 years ago
9 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
9 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime"
  9. "net/http"
  10. "net/url"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/images"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/stats"
  19. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  20. "github.com/chrislusf/seaweedfs/weed/util"
  21. )
  22. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  23. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  24. stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
  25. start := time.Now()
  26. defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }()
  27. n := new(needle.Needle)
  28. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  29. if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
  30. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  31. return
  32. }
  33. volumeId, err := needle.NewVolumeId(vid)
  34. if err != nil {
  35. glog.V(2).Infof("parsing vid %s: %v", r.URL.Path, err)
  36. w.WriteHeader(http.StatusBadRequest)
  37. return
  38. }
  39. err = n.ParsePath(fid)
  40. if err != nil {
  41. glog.V(2).Infof("parsing fid %s: %v", r.URL.Path, err)
  42. w.WriteHeader(http.StatusBadRequest)
  43. return
  44. }
  45. // glog.V(4).Infoln("volume", volumeId, "reading", n)
  46. hasVolume := vs.store.HasVolume(volumeId)
  47. _, hasEcVolume := vs.store.FindEcVolume(volumeId)
  48. if !hasVolume && !hasEcVolume {
  49. if !vs.ReadRedirect {
  50. glog.V(2).Infoln("volume is not local:", err, r.URL.Path)
  51. w.WriteHeader(http.StatusNotFound)
  52. return
  53. }
  54. lookupResult, err := operation.Lookup(vs.GetMaster(), volumeId.String())
  55. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  56. if err == nil && len(lookupResult.Locations) > 0 {
  57. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  58. u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
  59. arg := url.Values{}
  60. if c := r.FormValue("collection"); c != "" {
  61. arg.Set("collection", c)
  62. }
  63. u.RawQuery = arg.Encode()
  64. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  65. } else {
  66. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  67. w.WriteHeader(http.StatusNotFound)
  68. }
  69. return
  70. }
  71. cookie := n.Cookie
  72. var count int
  73. if hasVolume {
  74. count, err = vs.store.ReadVolumeNeedle(volumeId, n)
  75. } else if hasEcVolume {
  76. count, err = vs.store.ReadEcShardNeedle(volumeId, n)
  77. }
  78. // glog.V(4).Infoln("read bytes", count, "error", err)
  79. if err != nil || count < 0 {
  80. glog.V(0).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  81. w.WriteHeader(http.StatusNotFound)
  82. return
  83. }
  84. if n.Cookie != cookie {
  85. glog.V(0).Infof("request %s with cookie:%x expected:%x from %s agent %s", r.URL.Path, cookie, n.Cookie, r.RemoteAddr, r.UserAgent())
  86. w.WriteHeader(http.StatusNotFound)
  87. return
  88. }
  89. if n.LastModified != 0 {
  90. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  91. if r.Header.Get("If-Modified-Since") != "" {
  92. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  93. if t.Unix() >= int64(n.LastModified) {
  94. w.WriteHeader(http.StatusNotModified)
  95. return
  96. }
  97. }
  98. }
  99. }
  100. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  101. w.WriteHeader(http.StatusNotModified)
  102. return
  103. }
  104. setEtag(w, n.Etag())
  105. if n.HasPairs() {
  106. pairMap := make(map[string]string)
  107. err = json.Unmarshal(n.Pairs, &pairMap)
  108. if err != nil {
  109. glog.V(0).Infoln("Unmarshal pairs error:", err)
  110. }
  111. for k, v := range pairMap {
  112. w.Header().Set(k, v)
  113. }
  114. }
  115. if vs.tryHandleChunkedFile(n, filename, ext, w, r) {
  116. return
  117. }
  118. if n.NameSize > 0 && filename == "" {
  119. filename = string(n.Name)
  120. if ext == "" {
  121. ext = filepath.Ext(filename)
  122. }
  123. }
  124. mtype := ""
  125. if n.MimeSize > 0 {
  126. mt := string(n.Mime)
  127. if !strings.HasPrefix(mt, "application/octet-stream") {
  128. mtype = mt
  129. }
  130. }
  131. if ext != ".gz" {
  132. if n.IsGzipped() {
  133. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  134. if _, _, _, shouldResize := shouldResizeImages(ext, r); shouldResize {
  135. if n.Data, err = util.UnGzipData(n.Data); err != nil {
  136. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  137. }
  138. } else {
  139. w.Header().Set("Content-Encoding", "gzip")
  140. }
  141. } else {
  142. if n.Data, err = util.UnGzipData(n.Data); err != nil {
  143. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  144. }
  145. }
  146. }
  147. }
  148. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  149. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  150. glog.V(2).Infoln("response write error:", e)
  151. }
  152. }
  153. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, ext string, w http.ResponseWriter, r *http.Request) (processed bool) {
  154. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  155. return false
  156. }
  157. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  158. if e != nil {
  159. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  160. return false
  161. }
  162. if fileName == "" && chunkManifest.Name != "" {
  163. fileName = chunkManifest.Name
  164. }
  165. if ext == "" {
  166. ext = filepath.Ext(fileName)
  167. }
  168. mType := ""
  169. if chunkManifest.Mime != "" {
  170. mt := chunkManifest.Mime
  171. if !strings.HasPrefix(mt, "application/octet-stream") {
  172. mType = mt
  173. }
  174. }
  175. w.Header().Set("X-File-Store", "chunked")
  176. chunkedFileReader := operation.NewChunkedFileReader(chunkManifest.Chunks, vs.GetMaster())
  177. defer chunkedFileReader.Close()
  178. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  179. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  180. glog.V(2).Infoln("response write error:", e)
  181. }
  182. return true
  183. }
  184. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  185. rs := originalDataReaderSeeker
  186. width, height, mode, shouldResize := shouldResizeImages(ext, r)
  187. if shouldResize {
  188. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, mode)
  189. }
  190. return rs
  191. }
  192. func shouldResizeImages(ext string, r *http.Request) (width, height int, mode string, shouldResize bool) {
  193. if len(ext) > 0 {
  194. ext = strings.ToLower(ext)
  195. }
  196. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  197. if r.FormValue("width") != "" {
  198. width, _ = strconv.Atoi(r.FormValue("width"))
  199. }
  200. if r.FormValue("height") != "" {
  201. height, _ = strconv.Atoi(r.FormValue("height"))
  202. }
  203. }
  204. mode = r.FormValue("mode")
  205. shouldResize = width > 0 || height > 0
  206. return
  207. }
  208. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  209. totalSize, e := rs.Seek(0, 2)
  210. if mimeType == "" {
  211. if ext := filepath.Ext(filename); ext != "" {
  212. mimeType = mime.TypeByExtension(ext)
  213. }
  214. }
  215. if mimeType != "" {
  216. w.Header().Set("Content-Type", mimeType)
  217. }
  218. w.Header().Set("Accept-Ranges", "bytes")
  219. if r.Method == "HEAD" {
  220. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  221. return nil
  222. }
  223. adjustHeadersAfterHEAD(w, r, filename)
  224. processRangeRequest(r, w, totalSize, mimeType, func(writer io.Writer, offset int64, size int64) error {
  225. if _, e = rs.Seek(offset, 0); e != nil {
  226. return e
  227. }
  228. _, e = io.CopyN(writer, rs, size)
  229. return e
  230. })
  231. return nil
  232. }