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.

283 lines
7.9 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "io"
  5. "mime"
  6. "mime/multipart"
  7. "net/http"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "net/url"
  13. "github.com/chrislusf/seaweedfs/go/glog"
  14. "github.com/chrislusf/seaweedfs/go/images"
  15. "github.com/chrislusf/seaweedfs/go/operation"
  16. "github.com/chrislusf/seaweedfs/go/storage"
  17. "github.com/chrislusf/seaweedfs/go/util"
  18. )
  19. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  20. func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
  21. n := new(storage.Needle)
  22. vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
  23. volumeId, err := storage.NewVolumeId(vid)
  24. if err != nil {
  25. glog.V(2).Infoln("parsing error:", err, r.URL.Path)
  26. w.WriteHeader(http.StatusBadRequest)
  27. return
  28. }
  29. err = n.ParsePath(fid)
  30. if err != nil {
  31. glog.V(2).Infoln("parsing fid error:", err, r.URL.Path)
  32. w.WriteHeader(http.StatusBadRequest)
  33. return
  34. }
  35. glog.V(4).Infoln("volume", volumeId, "reading", n)
  36. if !vs.store.HasVolume(volumeId) {
  37. if !vs.ReadRedirect {
  38. glog.V(2).Infoln("volume is not local:", err, r.URL.Path)
  39. w.WriteHeader(http.StatusNotFound)
  40. return
  41. }
  42. lookupResult, err := operation.Lookup(vs.GetMasterNode(), volumeId.String())
  43. glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
  44. if err == nil && len(lookupResult.Locations) > 0 {
  45. u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
  46. u.Path = r.URL.Path
  47. arg := url.Values{}
  48. if c := r.FormValue("collection"); c != "" {
  49. arg.Set("collection", c)
  50. }
  51. u.RawQuery = arg.Encode()
  52. http.Redirect(w, r, u.String(), http.StatusMovedPermanently)
  53. } else {
  54. glog.V(2).Infoln("lookup error:", err, r.URL.Path)
  55. w.WriteHeader(http.StatusNotFound)
  56. }
  57. return
  58. }
  59. cookie := n.Cookie
  60. count, e := vs.store.ReadVolumeNeedle(volumeId, n)
  61. glog.V(4).Infoln("read bytes", count, "error", e)
  62. defer n.ReleaseMemory()
  63. if e != nil || count <= 0 {
  64. glog.V(0).Infoln("read error:", e, r.URL.Path)
  65. w.WriteHeader(http.StatusNotFound)
  66. return
  67. }
  68. if n.Cookie != cookie {
  69. glog.V(0).Infoln("request", r.URL.Path, "with unmaching cookie seen:", cookie, "expected:", n.Cookie, "from", r.RemoteAddr, "agent", r.UserAgent())
  70. w.WriteHeader(http.StatusNotFound)
  71. return
  72. }
  73. if n.LastModified != 0 {
  74. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  75. if r.Header.Get("If-Modified-Since") != "" {
  76. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  77. if t.Unix() >= int64(n.LastModified) {
  78. w.WriteHeader(http.StatusNotModified)
  79. return
  80. }
  81. }
  82. }
  83. }
  84. etag := n.Etag()
  85. if inm := r.Header.Get("If-None-Match"); inm == etag {
  86. w.WriteHeader(http.StatusNotModified)
  87. return
  88. }
  89. w.Header().Set("Etag", etag)
  90. if vs.tryHandleChunkedFile(n, filename, w, r) {
  91. return
  92. }
  93. if n.NameSize > 0 && filename == "" {
  94. filename = string(n.Name)
  95. if ext == "" {
  96. ext = path.Ext(filename)
  97. }
  98. }
  99. mtype := ""
  100. if n.MimeSize > 0 {
  101. mt := string(n.Mime)
  102. if !strings.HasPrefix(mt, "application/octet-stream") {
  103. mtype = mt
  104. }
  105. }
  106. if ext != ".gz" {
  107. if n.IsGzipped() {
  108. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  109. w.Header().Set("Content-Encoding", "gzip")
  110. } else {
  111. if n.Data, err = operation.UnGzipData(n.Data); err != nil {
  112. glog.V(0).Infoln("ungzip error:", err, r.URL.Path)
  113. }
  114. }
  115. }
  116. }
  117. if ext == ".png" || ext == ".jpg" || ext == ".gif" {
  118. width, height := 0, 0
  119. if r.FormValue("width") != "" {
  120. width, _ = strconv.Atoi(r.FormValue("width"))
  121. }
  122. if r.FormValue("height") != "" {
  123. height, _ = strconv.Atoi(r.FormValue("height"))
  124. }
  125. n.Data, _, _ = images.Resized(ext, n.Data, width, height)
  126. }
  127. if e := writeResponseContent(filename, mtype, bytes.NewReader(n.Data), w, r); e != nil {
  128. glog.V(2).Infoln("response write error:", e)
  129. }
  130. }
  131. func (vs *VolumeServer) tryHandleChunkedFile(n *storage.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
  132. if !n.IsChunkedManifest() {
  133. return false
  134. }
  135. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  136. if e != nil {
  137. glog.V(0).Infof("load chunked manifest (%s) error: %v", r.URL.Path, e)
  138. return false
  139. }
  140. if fileName == "" && chunkManifest.Name != "" {
  141. fileName = chunkManifest.Name
  142. }
  143. mType := ""
  144. if chunkManifest.Mime != "" {
  145. mt := chunkManifest.Mime
  146. if !strings.HasPrefix(mt, "application/octet-stream") {
  147. mType = mt
  148. }
  149. }
  150. w.Header().Set("X-File-Store", "chunked")
  151. chunkedFileReader := &operation.ChunkedFileReader{
  152. Manifest: chunkManifest,
  153. Master: vs.GetMasterNode(),
  154. }
  155. defer chunkedFileReader.Close()
  156. if e := writeResponseContent(fileName, mType, chunkedFileReader, w, r); e != nil {
  157. glog.V(2).Infoln("response write error:", e)
  158. }
  159. return true
  160. }
  161. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  162. totalSize, e := rs.Seek(0, 2)
  163. if mimeType == "" {
  164. if ext := path.Ext(filename); ext != "" {
  165. mimeType = mime.TypeByExtension(ext)
  166. }
  167. }
  168. if mimeType != "" {
  169. w.Header().Set("Content-Type", mimeType)
  170. }
  171. if filename != "" {
  172. w.Header().Set("Content-Disposition", `filename="`+fileNameEscaper.Replace(filename)+`"`)
  173. }
  174. w.Header().Set("Accept-Ranges", "bytes")
  175. if r.Method == "HEAD" {
  176. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  177. return nil
  178. }
  179. rangeReq := r.Header.Get("Range")
  180. if rangeReq == "" {
  181. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  182. if _, e = rs.Seek(0, 0); e != nil {
  183. return e
  184. }
  185. _, e = io.Copy(w, rs)
  186. return e
  187. }
  188. //the rest is dealing with partial content request
  189. //mostly copy from src/pkg/net/http/fs.go
  190. ranges, err := parseRange(rangeReq, totalSize)
  191. if err != nil {
  192. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  193. return nil
  194. }
  195. if sumRangesSize(ranges) > totalSize {
  196. // The total number of bytes in all the ranges
  197. // is larger than the size of the file by
  198. // itself, so this is probably an attack, or a
  199. // dumb client. Ignore the range request.
  200. return nil
  201. }
  202. if len(ranges) == 0 {
  203. return nil
  204. }
  205. if len(ranges) == 1 {
  206. // RFC 2616, Section 14.16:
  207. // "When an HTTP message includes the content of a single
  208. // range (for example, a response to a request for a
  209. // single range, or to a request for a set of ranges
  210. // that overlap without any holes), this content is
  211. // transmitted with a Content-Range header, and a
  212. // Content-Length header showing the number of bytes
  213. // actually transferred.
  214. // ...
  215. // A response to a request for a single range MUST NOT
  216. // be sent using the multipart/byteranges media type."
  217. ra := ranges[0]
  218. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  219. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  220. w.WriteHeader(http.StatusPartialContent)
  221. if _, e = rs.Seek(ra.start, 0); e != nil {
  222. return e
  223. }
  224. _, e = io.CopyN(w, rs, ra.length)
  225. return e
  226. }
  227. // process multiple ranges
  228. for _, ra := range ranges {
  229. if ra.start > totalSize {
  230. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  231. return nil
  232. }
  233. }
  234. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  235. pr, pw := io.Pipe()
  236. mw := multipart.NewWriter(pw)
  237. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  238. sendContent := pr
  239. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  240. go func() {
  241. for _, ra := range ranges {
  242. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  243. if e != nil {
  244. pw.CloseWithError(e)
  245. return
  246. }
  247. if _, e = rs.Seek(ra.start, 0); e != nil {
  248. pw.CloseWithError(e)
  249. return
  250. }
  251. if _, e = io.CopyN(part, rs, ra.length); e != nil {
  252. pw.CloseWithError(e)
  253. return
  254. }
  255. }
  256. mw.Close()
  257. pw.Close()
  258. }()
  259. if w.Header().Get("Content-Encoding") == "" {
  260. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  261. }
  262. w.WriteHeader(http.StatusPartialContent)
  263. _, e = io.CopyN(w, sendContent, sendSize)
  264. return e
  265. }