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.

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