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.

340 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
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/stats"
  20. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  21. "github.com/chrislusf/seaweedfs/weed/util"
  22. )
  23. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  24. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  25. stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
  26. start := time.Now()
  27. defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }()
  28. n := new(needle.Needle)
  29. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  30. if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
  31. writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
  32. return
  33. }
  34. volumeId, err := needle.NewVolumeId(vid)
  35. if err != nil {
  36. glog.V(2).Infoln("parsing error:", err, r.URL.Path)
  37. w.WriteHeader(http.StatusBadRequest)
  38. return
  39. }
  40. err = n.ParsePath(fid)
  41. if err != nil {
  42. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  43. w.WriteHeader(http.StatusBadRequest)
  44. return
  45. }
  46. glog.V(4).Infoln("volume", volumeId, "reading", n)
  47. hasVolume := vs.store.HasVolume(volumeId)
  48. _, hasEcVolume := vs.store.FindEcVolume(volumeId)
  49. if !hasVolume && !hasEcVolume {
  50. if !vs.ReadRedirect {
  51. glog.V(2).Infoln("volume is not local:", err, r.URL.Path)
  52. w.WriteHeader(http.StatusNotFound)
  53. return
  54. }
  55. lookupResult, err := operation.Lookup(vs.GetMaster(), volumeId.String())
  56. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  57. if err == nil && len(lookupResult.Locations) > 0 {
  58. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  59. u.Path = r.URL.Path
  60. arg := url.Values{}
  61. if c := r.FormValue("collection"); c != "" {
  62. arg.Set("collection", c)
  63. }
  64. u.RawQuery = arg.Encode()
  65. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  66. } else {
  67. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  68. w.WriteHeader(http.StatusNotFound)
  69. }
  70. return
  71. }
  72. cookie := n.Cookie
  73. var count int
  74. if hasVolume {
  75. count, err = vs.store.ReadVolumeNeedle(volumeId, n)
  76. } else if hasEcVolume {
  77. count, err = vs.store.ReadEcShardNeedle(context.Background(), volumeId, n)
  78. }
  79. glog.V(4).Infoln("read bytes", count, "error", err)
  80. if err != nil || count < 0 {
  81. glog.V(0).Infof("read %s isNormalVolume %v error: %v", r.URL.Path, hasVolume, err)
  82. w.WriteHeader(http.StatusNotFound)
  83. return
  84. }
  85. if n.Cookie != cookie {
  86. 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())
  87. w.WriteHeader(http.StatusNotFound)
  88. return
  89. }
  90. if n.LastModified != 0 {
  91. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  92. if r.Header.Get("If-Modified-Since") != "" {
  93. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  94. if t.Unix() >= int64(n.LastModified) {
  95. w.WriteHeader(http.StatusNotModified)
  96. return
  97. }
  98. }
  99. }
  100. }
  101. if inm := r.Header.Get("If-None-Match"); inm == "\""+n.Etag()+"\"" {
  102. w.WriteHeader(http.StatusNotModified)
  103. return
  104. }
  105. if r.Header.Get("ETag-MD5") == "True" {
  106. setEtag(w, n.MD5())
  107. } else {
  108. setEtag(w, n.Etag())
  109. }
  110. if n.HasPairs() {
  111. pairMap := make(map[string]string)
  112. err = json.Unmarshal(n.Pairs, &pairMap)
  113. if err != nil {
  114. glog.V(0).Infoln("Unmarshal pairs error:", err)
  115. }
  116. for k, v := range pairMap {
  117. w.Header().Set(k, v)
  118. }
  119. }
  120. if vs.tryHandleChunkedFile(n, filename, w, r) {
  121. return
  122. }
  123. if n.NameSize > 0 && filename == "" {
  124. filename = string(n.Name)
  125. if ext == "" {
  126. ext = path.Ext(filename)
  127. }
  128. }
  129. mtype := ""
  130. if n.MimeSize > 0 {
  131. mt := string(n.Mime)
  132. if !strings.HasPrefix(mt, "application/octet-stream") {
  133. mtype = mt
  134. }
  135. }
  136. if ext != ".gz" {
  137. if n.IsGzipped() {
  138. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  139. w.Header().Set("Content-Encoding", "gzip")
  140. } else {
  141. if n.Data, err = util.UnGzipData(n.Data); err != nil {
  142. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  143. }
  144. }
  145. }
  146. }
  147. rs := conditionallyResizeImages(bytes.NewReader(n.Data), ext, r)
  148. if e := writeResponseContent(filename, mtype, rs, w, r); e != nil {
  149. glog.V(2).Infoln("response write error:", e)
  150. }
  151. }
  152. func (vs *VolumeServer) tryHandleChunkedFile(n *needle.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
  153. if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
  154. return false
  155. }
  156. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  157. if e != nil {
  158. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  159. return false
  160. }
  161. if fileName == "" && chunkManifest.Name != "" {
  162. fileName = chunkManifest.Name
  163. }
  164. ext := path.Ext(fileName)
  165. mType := ""
  166. if chunkManifest.Mime != "" {
  167. mt := chunkManifest.Mime
  168. if !strings.HasPrefix(mt, "application/octet-stream") {
  169. mType = mt
  170. }
  171. }
  172. w.Header().Set("X-File-Store", "chunked")
  173. chunkedFileReader := &operation.ChunkedFileReader{
  174. Manifest: chunkManifest,
  175. Master: vs.GetMaster(),
  176. }
  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. if len(ext) > 0 {
  187. ext = strings.ToLower(ext)
  188. }
  189. if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
  190. width, height := 0, 0
  191. if r.FormValue("width") != "" {
  192. width, _ = strconv.Atoi(r.FormValue("width"))
  193. }
  194. if r.FormValue("height") != "" {
  195. height, _ = strconv.Atoi(r.FormValue("height"))
  196. }
  197. rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, r.FormValue("mode"))
  198. }
  199. return rs
  200. }
  201. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  202. totalSize, e := rs.Seek(0, 2)
  203. if mimeType == "" {
  204. if ext := path.Ext(filename); ext != "" {
  205. mimeType = mime.TypeByExtension(ext)
  206. }
  207. }
  208. if mimeType != "" {
  209. w.Header().Set("Content-Type", mimeType)
  210. }
  211. if filename != "" {
  212. contentDisposition := "inline"
  213. if r.FormValue("dl") != "" {
  214. if dl, _ := strconv.ParseBool(r.FormValue("dl")); dl {
  215. contentDisposition = "attachment"
  216. }
  217. }
  218. w.Header().Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
  219. }
  220. w.Header().Set("Accept-Ranges", "bytes")
  221. if r.Method == "HEAD" {
  222. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  223. return nil
  224. }
  225. rangeReq := r.Header.Get("Range")
  226. if rangeReq == "" {
  227. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  228. if _, e = rs.Seek(0, 0); e != nil {
  229. return e
  230. }
  231. _, e = io.Copy(w, rs)
  232. return e
  233. }
  234. //the rest is dealing with partial content request
  235. //mostly copy from src/pkg/net/http/fs.go
  236. ranges, err := parseRange(rangeReq, totalSize)
  237. if err != nil {
  238. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  239. return nil
  240. }
  241. if sumRangesSize(ranges) > totalSize {
  242. // The total number of bytes in all the ranges
  243. // is larger than the size of the file by
  244. // itself, so this is probably an attack, or a
  245. // dumb client. Ignore the range request.
  246. return nil
  247. }
  248. if len(ranges) == 0 {
  249. return nil
  250. }
  251. if len(ranges) == 1 {
  252. // RFC 2616, Section 14.16:
  253. // "When an HTTP message includes the content of a single
  254. // range (for example, a response to a request for a
  255. // single range, or to a request for a set of ranges
  256. // that overlap without any holes), this content is
  257. // transmitted with a Content-Range header, and a
  258. // Content-Length header showing the number of bytes
  259. // actually transferred.
  260. // ...
  261. // A response to a request for a single range MUST NOT
  262. // be sent using the multipart/byteranges media type."
  263. ra := ranges[0]
  264. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  265. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  266. w.WriteHeader(http.StatusPartialContent)
  267. if _, e = rs.Seek(ra.start, 0); e != nil {
  268. return e
  269. }
  270. _, e = io.CopyN(w, rs, ra.length)
  271. return e
  272. }
  273. // process multiple ranges
  274. for _, ra := range ranges {
  275. if ra.start > totalSize {
  276. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  277. return nil
  278. }
  279. }
  280. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  281. pr, pw := io.Pipe()
  282. mw := multipart.NewWriter(pw)
  283. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  284. sendContent := pr
  285. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  286. go func() {
  287. for _, ra := range ranges {
  288. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  289. if e != nil {
  290. pw.CloseWithError(e)
  291. return
  292. }
  293. if _, e = rs.Seek(ra.start, 0); e != nil {
  294. pw.CloseWithError(e)
  295. return
  296. }
  297. if _, e = io.CopyN(part, rs, ra.length); e != nil {
  298. pw.CloseWithError(e)
  299. return
  300. }
  301. }
  302. mw.Close()
  303. pw.Close()
  304. }()
  305. if w.Header().Get("Content-Encoding") == "" {
  306. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  307. }
  308. w.WriteHeader(http.StatusPartialContent)
  309. _, e = io.CopyN(w, sendContent, sendSize)
  310. return e
  311. }