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.

315 lines
8.7 KiB

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