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.

339 lines
9.4 KiB

9 years ago
9 years ago
9 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "io"
  7. "mime"
  8. "mime/multipart"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "encoding/json"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/images"
  18. "github.com/chrislusf/seaweedfs/weed/operation"
  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. volumeServerRequestCounter.WithLabelValues("get").Inc()
  25. start := time.Now()
  26. defer func() { 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).Infoln("parsing error:", err, r.URL.Path)
  36. w.WriteHeader(http.StatusBadRequest)
  37. return
  38. }
  39. err = n.ParsePath(fid)
  40. if err != nil {
  41. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  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 = r.URL.Path
  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(context.Background(), 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. if r.Header.Get("ETag-MD5") == "True" {
  105. setEtag(w, n.MD5())
  106. } else {
  107. setEtag(w, n.Etag())
  108. }
  109. if n.HasPairs() {
  110. pairMap := make(map[string]string)
  111. err = json.Unmarshal(n.Pairs, &pairMap)
  112. if err != nil {
  113. glog.V(0).Infoln("Unmarshal pairs error:", err)
  114. }
  115. for k, v := range pairMap {
  116. w.Header().Set(k, v)
  117. }
  118. }
  119. if vs.tryHandleChunkedFile(n, filename, w, r) {
  120. return
  121. }
  122. if n.NameSize > 0 && filename == "" {
  123. filename = string(n.Name)
  124. if ext == "" {
  125. ext = path.Ext(filename)
  126. }
  127. }
  128. mtype := ""
  129. if n.MimeSize > 0 {
  130. mt := string(n.Mime)
  131. if !strings.HasPrefix(mt, "application/octet-stream") {
  132. mtype = mt
  133. }
  134. }
  135. if ext != ".gz" {
  136. if n.IsGzipped() {
  137. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  138. w.Header().Set("Content-Encoding", "gzip")
  139. } else {
  140. if n.Data, err = util.UnGzipData(n.Data); err != nil {
  141. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  142. }
  143. }
  144. }
  145. }
  146. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  147. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  148. glog.V(2).Infoln("response write error:", e)
  149. }
  150. }
  151. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
  152. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  153. return false
  154. }
  155. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  156. if e != nil {
  157. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  158. return false
  159. }
  160. if fileName == "" && chunkManifest.Name != "" {
  161. fileName = chunkManifest.Name
  162. }
  163. ext := path.Ext(fileName)
  164. mType := ""
  165. if chunkManifest.Mime != "" {
  166. mt := chunkManifest.Mime
  167. if !strings.HasPrefix(mt, "application/octet-stream") {
  168. mType = mt
  169. }
  170. }
  171. w.Header().Set("X-File-Store", "chunked")
  172. chunkedFileReader := &operation.ChunkedFileReader{
  173. Manifest: chunkManifest,
  174. Master: vs.GetMaster(),
  175. }
  176. defer chunkedFileReader.Close()
  177. rs := conditionallyResizeImages(chunkedFileReader, ext, r)
  178. if e := writeResponseContent(fileName, mType, rs, w, r); e != nil {
  179. glog.V(2).Infoln("response write error:", e)
  180. }
  181. return true
  182. }
  183. func conditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, r *http.Request) io.ReadSeeker {
  184. rs := originalDataReaderSeeker
  185. if len(ext) > 0 {
  186. ext = strings.ToLower(ext)
  187. }
  188. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  189. width, height := 0, 0
  190. if r.FormValue("width") != "" {
  191. width, _ = strconv.Atoi(r.FormValue("width"))
  192. }
  193. if r.FormValue("height") != "" {
  194. height, _ = strconv.Atoi(r.FormValue("height"))
  195. }
  196. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, r.FormValue("mode"))
  197. }
  198. return rs
  199. }
  200. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  201. totalSize, e := rs.Seek(0, 2)
  202. if mimeType == "" {
  203. if ext := path.Ext(filename); ext != "" {
  204. mimeType = mime.TypeByExtension(ext)
  205. }
  206. }
  207. if mimeType != "" {
  208. w.Header().Set("Content-Type", mimeType)
  209. }
  210. if filename != "" {
  211. contentDisposition := "inline"
  212. if r.FormValue("dl") != "" {
  213. if dl, _ := strconv.ParseBool(r.FormValue("dl")); dl {
  214. contentDisposition = "attachment"
  215. }
  216. }
  217. w.Header().Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
  218. }
  219. w.Header().Set("Accept-Ranges", "bytes")
  220. if r.Method == "HEAD" {
  221. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  222. return nil
  223. }
  224. rangeReq := r.Header.Get("Range")
  225. if rangeReq == "" {
  226. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  227. if _, e = rs.Seek(0, 0); e != nil {
  228. return e
  229. }
  230. _, e = io.Copy(w, rs)
  231. return e
  232. }
  233. //the rest is dealing with partial content request
  234. //mostly copy from src/pkg/net/http/fs.go
  235. ranges, err := parseRange(rangeReq, totalSize)
  236. if err != nil {
  237. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  238. return nil
  239. }
  240. if sumRangesSize(ranges) > totalSize {
  241. // The total number of bytes in all the ranges
  242. // is larger than the size of the file by
  243. // itself, so this is probably an attack, or a
  244. // dumb client. Ignore the range request.
  245. return nil
  246. }
  247. if len(ranges) == 0 {
  248. return nil
  249. }
  250. if len(ranges) == 1 {
  251. // RFC 2616, Section 14.16:
  252. // "When an HTTP message includes the content of a single
  253. // range (for example, a response to a request for a
  254. // single range, or to a request for a set of ranges
  255. // that overlap without any holes), this content is
  256. // transmitted with a Content-Range header, and a
  257. // Content-Length header showing the number of bytes
  258. // actually transferred.
  259. // ...
  260. // A response to a request for a single range MUST NOT
  261. // be sent using the multipart/byteranges media type."
  262. ra := ranges[0]
  263. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  264. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  265. w.WriteHeader(http.StatusPartialContent)
  266. if _, e = rs.Seek(ra.start, 0); e != nil {
  267. return e
  268. }
  269. _, e = io.CopyN(w, rs, ra.length)
  270. return e
  271. }
  272. // process multiple ranges
  273. for _, ra := range ranges {
  274. if ra.start > totalSize {
  275. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  276. return nil
  277. }
  278. }
  279. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  280. pr, pw := io.Pipe()
  281. mw := multipart.NewWriter(pw)
  282. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  283. sendContent := pr
  284. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  285. go func() {
  286. for _, ra := range ranges {
  287. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  288. if e != nil {
  289. pw.CloseWithError(e)
  290. return
  291. }
  292. if _, e = rs.Seek(ra.start, 0); e != nil {
  293. pw.CloseWithError(e)
  294. return
  295. }
  296. if _, e = io.CopyN(part, rs, ra.length); e != nil {
  297. pw.CloseWithError(e)
  298. return
  299. }
  300. }
  301. mw.Close()
  302. pw.Close()
  303. }()
  304. if w.Header().Get("Content-Encoding") == "" {
  305. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  306. }
  307. w.WriteHeader(http.StatusPartialContent)
  308. _, e = io.CopyN(w, sendContent, sendSize)
  309. return e
  310. }