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.

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