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.

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