volume_server_handlers_read.go 8.7 KB

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