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.

280 lines
7.6 KiB

9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
6 years ago
9 years ago
6 years ago
6 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "mime"
  8. "mime/multipart"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "github.com/chrislusf/seaweedfs/weed/filer2"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/stats"
  17. "github.com/chrislusf/seaweedfs/weed/util"
  18. )
  19. func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  20. path := r.URL.Path
  21. isForDirectory := strings.HasSuffix(path, "/")
  22. if isForDirectory && len(path) > 1 {
  23. path = path[:len(path)-1]
  24. }
  25. entry, err := fs.filer.FindEntry(context.Background(), filer2.FullPath(path))
  26. if err != nil {
  27. if path == "/" {
  28. fs.listDirectoryHandler(w, r)
  29. return
  30. }
  31. if err == filer2.ErrNotFound {
  32. glog.V(1).Infof("Not found %s: %v", path, err)
  33. stats.FilerRequestCounter.WithLabelValues("read.notfound").Inc()
  34. w.WriteHeader(http.StatusNotFound)
  35. } else {
  36. glog.V(0).Infof("Internal %s: %v", path, err)
  37. stats.FilerRequestCounter.WithLabelValues("read.internalerror").Inc()
  38. w.WriteHeader(http.StatusInternalServerError)
  39. }
  40. return
  41. }
  42. if entry.IsDirectory() {
  43. if fs.option.DisableDirListing {
  44. w.WriteHeader(http.StatusMethodNotAllowed)
  45. return
  46. }
  47. fs.listDirectoryHandler(w, r)
  48. return
  49. }
  50. if isForDirectory {
  51. w.WriteHeader(http.StatusNotFound)
  52. return
  53. }
  54. if len(entry.Chunks) == 0 {
  55. glog.V(1).Infof("no file chunks for %s, attr=%+v", path, entry.Attr)
  56. stats.FilerRequestCounter.WithLabelValues("read.nocontent").Inc()
  57. w.WriteHeader(http.StatusNoContent)
  58. return
  59. }
  60. w.Header().Set("Accept-Ranges", "bytes")
  61. if r.Method == "HEAD" {
  62. w.Header().Set("Content-Length", strconv.FormatInt(int64(filer2.TotalSize(entry.Chunks)), 10))
  63. w.Header().Set("Last-Modified", entry.Attr.Mtime.Format(http.TimeFormat))
  64. if entry.Attr.Mime != "" {
  65. w.Header().Set("Content-Type", entry.Attr.Mime)
  66. }
  67. setEtag(w, filer2.ETag(entry.Chunks))
  68. return
  69. }
  70. if len(entry.Chunks) == 1 {
  71. fs.handleSingleChunk(w, r, entry)
  72. return
  73. }
  74. fs.handleMultipleChunks(w, r, entry)
  75. }
  76. func (fs *FilerServer) handleSingleChunk(w http.ResponseWriter, r *http.Request, entry *filer2.Entry) {
  77. fileId := entry.Chunks[0].GetFileIdString()
  78. urlString, err := fs.filer.MasterClient.LookupFileId(fileId)
  79. if err != nil {
  80. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", fileId, err)
  81. w.WriteHeader(http.StatusNotFound)
  82. return
  83. }
  84. if fs.option.RedirectOnRead && entry.Chunks[0].CipherKey == nil {
  85. stats.FilerRequestCounter.WithLabelValues("redirect").Inc()
  86. http.Redirect(w, r, urlString, http.StatusFound)
  87. return
  88. }
  89. u, _ := url.Parse(urlString)
  90. q := u.Query()
  91. for key, values := range r.URL.Query() {
  92. for _, value := range values {
  93. q.Add(key, value)
  94. }
  95. }
  96. u.RawQuery = q.Encode()
  97. request := &http.Request{
  98. Method: r.Method,
  99. URL: u,
  100. Proto: r.Proto,
  101. ProtoMajor: r.ProtoMajor,
  102. ProtoMinor: r.ProtoMinor,
  103. Header: r.Header,
  104. Body: r.Body,
  105. Host: r.Host,
  106. ContentLength: r.ContentLength,
  107. }
  108. glog.V(3).Infoln("retrieving from", u)
  109. resp, do_err := util.Do(request)
  110. if do_err != nil {
  111. glog.V(0).Infoln("failing to connect to volume server", do_err.Error())
  112. writeJsonError(w, r, http.StatusInternalServerError, do_err)
  113. return
  114. }
  115. defer func() {
  116. io.Copy(ioutil.Discard, resp.Body)
  117. resp.Body.Close()
  118. }()
  119. for k, v := range resp.Header {
  120. w.Header()[k] = v
  121. }
  122. if entry.Attr.Mime != "" {
  123. w.Header().Set("Content-Type", entry.Attr.Mime)
  124. }
  125. if entry.Chunks[0].CipherKey == nil {
  126. w.WriteHeader(resp.StatusCode)
  127. io.Copy(w, resp.Body)
  128. } else {
  129. fs.writeEncryptedChunk(w, resp, entry)
  130. }
  131. }
  132. func (fs *FilerServer) writeEncryptedChunk(w http.ResponseWriter, resp *http.Response, entry *filer2.Entry) {
  133. chunk := entry.Chunks[0]
  134. encryptedData, err := ioutil.ReadAll(resp.Body)
  135. if err != nil {
  136. glog.V(1).Infof("read encrypted %s failed, err: %v", chunk.FileId, err)
  137. w.WriteHeader(http.StatusNotFound)
  138. return
  139. }
  140. decryptedData, err := util.Decrypt(encryptedData, util.CipherKey(chunk.CipherKey))
  141. if err != nil {
  142. glog.V(1).Infof("decrypt %s failed, err: %v", chunk.FileId, err)
  143. w.WriteHeader(http.StatusNotFound)
  144. return
  145. }
  146. w.Header().Set("Content-Length", fmt.Sprintf("%d", chunk.Size))
  147. w.WriteHeader(resp.StatusCode)
  148. w.Write(decryptedData)
  149. }
  150. func (fs *FilerServer) handleMultipleChunks(w http.ResponseWriter, r *http.Request, entry *filer2.Entry) {
  151. mimeType := entry.Attr.Mime
  152. if mimeType == "" {
  153. if ext := path.Ext(entry.Name()); ext != "" {
  154. mimeType = mime.TypeByExtension(ext)
  155. }
  156. }
  157. if mimeType != "" {
  158. w.Header().Set("Content-Type", mimeType)
  159. }
  160. setEtag(w, filer2.ETag(entry.Chunks))
  161. totalSize := int64(filer2.TotalSize(entry.Chunks))
  162. rangeReq := r.Header.Get("Range")
  163. if rangeReq == "" {
  164. w.Header().Set("Content-Length", strconv.FormatInt(totalSize, 10))
  165. if err := fs.writeContent(w, entry, 0, int(totalSize)); err != nil {
  166. http.Error(w, err.Error(), http.StatusInternalServerError)
  167. return
  168. }
  169. return
  170. }
  171. //the rest is dealing with partial content request
  172. //mostly copy from src/pkg/net/http/fs.go
  173. ranges, err := parseRange(rangeReq, totalSize)
  174. if err != nil {
  175. http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
  176. return
  177. }
  178. if sumRangesSize(ranges) > totalSize {
  179. // The total number of bytes in all the ranges
  180. // is larger than the size of the file by
  181. // itself, so this is probably an attack, or a
  182. // dumb client. Ignore the range request.
  183. return
  184. }
  185. if len(ranges) == 0 {
  186. return
  187. }
  188. if len(ranges) == 1 {
  189. // RFC 2616, Section 14.16:
  190. // "When an HTTP message includes the content of a single
  191. // range (for example, a response to a request for a
  192. // single range, or to a request for a set of ranges
  193. // that overlap without any holes), this content is
  194. // transmitted with a Content-Range header, and a
  195. // Content-Length header showing the number of bytes
  196. // actually transferred.
  197. // ...
  198. // A response to a request for a single range MUST NOT
  199. // be sent using the multipart/byteranges media type."
  200. ra := ranges[0]
  201. w.Header().Set("Content-Length", strconv.FormatInt(ra.length, 10))
  202. w.Header().Set("Content-Range", ra.contentRange(totalSize))
  203. w.WriteHeader(http.StatusPartialContent)
  204. err = fs.writeContent(w, entry, ra.start, int(ra.length))
  205. if err != nil {
  206. http.Error(w, err.Error(), http.StatusInternalServerError)
  207. return
  208. }
  209. return
  210. }
  211. // process multiple ranges
  212. for _, ra := range ranges {
  213. if ra.start > totalSize {
  214. http.Error(w, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
  215. return
  216. }
  217. }
  218. sendSize := rangesMIMESize(ranges, mimeType, totalSize)
  219. pr, pw := io.Pipe()
  220. mw := multipart.NewWriter(pw)
  221. w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
  222. sendContent := pr
  223. defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
  224. go func() {
  225. for _, ra := range ranges {
  226. part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
  227. if e != nil {
  228. pw.CloseWithError(e)
  229. return
  230. }
  231. if e = fs.writeContent(part, entry, ra.start, int(ra.length)); e != nil {
  232. pw.CloseWithError(e)
  233. return
  234. }
  235. }
  236. mw.Close()
  237. pw.Close()
  238. }()
  239. if w.Header().Get("Content-Encoding") == "" {
  240. w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
  241. }
  242. w.WriteHeader(http.StatusPartialContent)
  243. if _, err := io.CopyN(w, sendContent, sendSize); err != nil {
  244. http.Error(w, "Internal Error", http.StatusInternalServerError)
  245. return
  246. }
  247. }
  248. func (fs *FilerServer) writeContent(w io.Writer, entry *filer2.Entry, offset int64, size int) error {
  249. return filer2.StreamContent(fs.filer.MasterClient, w, entry.Chunks, offset, size)
  250. }