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.

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