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.

279 lines
7.8 KiB

9 years ago
  1. package weed_server
  2. import (
  3. "io"
  4. "mime"
  5. "mime/multipart"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "path"
  11. "bytes"
  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. raw, _ := strconv.ParseBool(r.FormValue("raw"))
  127. if raw {
  128. return false
  129. }
  130. processed = true
  131. chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
  132. if e != nil {
  133. glog.V(0).Infof("Load chunked manifest (%s) error: %s", r.URL.Path, e.Error())
  134. return false
  135. }
  136. if fileName == "" && chunkManifest.Name != "" {
  137. fileName = chunkManifest.Name
  138. }
  139. mType := ""
  140. if chunkManifest.Mime != "" {
  141. mt := chunkManifest.Mime
  142. if !strings.HasPrefix(mt, "application/octet-stream") {
  143. mType = mt
  144. }
  145. }
  146. w.Header().Set("X-File-Store", "chunked")
  147. chunkedFileReader := &operation.ChunkedFileReader{
  148. Manifest: chunkManifest,
  149. Master: vs.GetMasterNode(),
  150. }
  151. defer chunkedFileReader.Close()
  152. if e := writeResponseContent(fileName, mType, chunkedFileReader, w, r); e != nil {
  153. glog.V(2).Infoln("response write error:", e)
  154. }
  155. return
  156. }
  157. func writeResponseContent(filename, mimeType string, rs io.ReadSeeker, w http.ResponseWriter, r *http.Request) error {
  158. totalSize, e := rs.Seek(0, 2)
  159. if mimeType == "" {
  160. if ext := path.Ext(filename); ext != "" {
  161. mimeType = mime.TypeByExtension(ext)
  162. }
  163. }
  164. if mimeType != "" {
  165. w.Header().Set("Content-Type", mimeType)
  166. }
  167. if filename != "" {
  168. w.Header().Set("Content-Disposition", `filename="`+fileNameEscaper.Replace(filename)+`"`)
  169. }
  170. w.Header().Set("Accept-Ranges", "bytes")
  171. if r.Method == "HEAD" {
  172. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  173. return nil
  174. }
  175. rangeReq := r.Header.Get("Range")
  176. if rangeReq == "" {
  177. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  178. if _, e = rs.Seek(0, 0); e != nil {
  179. return e
  180. }
  181. _, e = io.Copy(w, rs)
  182. return e
  183. }
  184. //the rest is dealing with partial content request
  185. //mostly copy from src/pkg/net/http/fs.go
  186. ranges, err := parseRange(rangeReq, totalSize)
  187. if err != nil {
  188. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  189. return nil
  190. }
  191. if sumRangesSize(ranges) > totalSize {
  192. // The total number of bytes in all the ranges
  193. // is larger than the size of the file by
  194. // itself, so this is probably an attack, or a
  195. // dumb client. Ignore the range request.
  196. return nil
  197. }
  198. if len(ranges) == 0 {
  199. return nil
  200. }
  201. if len(ranges) == 1 {
  202. // RFC 2616, Section 14.16:
  203. // "When an HTTP message includes the content of a single
  204. // range (for example, a response to a request for a
  205. // single range, or to a request for a set of ranges
  206. // that overlap without any holes), this content is
  207. // transmitted with a Content-Range header, and a
  208. // Content-Length header showing the number of bytes
  209. // actually transferred.
  210. // ...
  211. // A response to a request for a single range MUST NOT
  212. // be sent using the multipart/byteranges media type."
  213. ra := ranges[0]
  214. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  215. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  216. w.WriteHeader(http.StatusPartialContent)
  217. if _, e = rs.Seek(ra.start, 0); e != nil {
  218. return e
  219. }
  220. _, e = io.CopyN(w, rs, ra.length)
  221. return e
  222. }
  223. // process multiple ranges
  224. for _, ra := range ranges {
  225. if ra.start > totalSize {
  226. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  227. return nil
  228. }
  229. }
  230. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  231. pr, pw := io.Pipe()
  232. mw := multipart.NewWriter(pw)
  233. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  234. sendContent := pr
  235. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  236. go func() {
  237. for _, ra := range ranges {
  238. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  239. if e != nil {
  240. pw.CloseWithError(e)
  241. return
  242. }
  243. if _, e = rs.Seek(ra.start, 0); e != nil {
  244. pw.CloseWithError(e)
  245. return
  246. }
  247. if _, e = io.CopyN(part, rs, ra.length); e != nil {
  248. pw.CloseWithError(e)
  249. return
  250. }
  251. }
  252. mw.Close()
  253. pw.Close()
  254. }()
  255. if w.Header().Get("Content-Encoding") == "" {
  256. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  257. }
  258. w.WriteHeader(http.StatusPartialContent)
  259. _, e = io.CopyN(w, sendContent, sendSize)
  260. return e
  261. }