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.

217 lines
6.3 KiB

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