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.

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