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.

205 lines
5.6 KiB

6 years ago
12 years ago
12 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
7 years ago
12 years ago
  1. package needle
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/chrislusf/seaweedfs/weed/images"
  12. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. )
  15. const (
  16. NeedleChecksumSize = 4
  17. PairNamePrefix = "Seaweed-"
  18. )
  19. /*
  20. * A Needle means a uploaded and stored file.
  21. * Needle file size is limited to 4GB for now.
  22. */
  23. type Needle struct {
  24. Cookie Cookie `comment:"random number to mitigate brute force lookups"`
  25. Id NeedleId `comment:"needle id"`
  26. Size uint32 `comment:"sum of DataSize,Data,NameSize,Name,MimeSize,Mime"`
  27. DataSize uint32 `comment:"Data size"` //version2
  28. Data []byte `comment:"The actual file data"`
  29. Flags byte `comment:"boolean flags"` //version2
  30. NameSize uint8 //version2
  31. Name []byte `comment:"maximum 256 characters"` //version2
  32. MimeSize uint8 //version2
  33. Mime []byte `comment:"maximum 256 characters"` //version2
  34. PairsSize uint16 //version2
  35. Pairs []byte `comment:"additional name value pairs, json format, maximum 64kB"`
  36. LastModified uint64 //only store LastModifiedBytesLength bytes, which is 5 bytes to disk
  37. Ttl *TTL
  38. Checksum CRC `comment:"CRC32 to check integrity"`
  39. AppendAtNs uint64 `comment:"append timestamp in nano seconds"` //version3
  40. Padding []byte `comment:"Aligned to 8 bytes"`
  41. }
  42. func (n *Needle) String() (str string) {
  43. str = fmt.Sprintf("%s Size:%d, DataSize:%d, Name:%s, Mime:%s", formatNeedleIdCookie(n.Id, n.Cookie), n.Size, n.DataSize, n.Name, n.Mime)
  44. return
  45. }
  46. func ParseUpload(r *http.Request, sizeLimit int64) (
  47. fileName string, data []byte, mimeType string, pairMap map[string]string, isGzipped bool, originalDataSize int,
  48. modifiedTime uint64, ttl *TTL, isChunkedFile bool, e error) {
  49. pairMap = make(map[string]string)
  50. for k, v := range r.Header {
  51. if len(v) > 0 && strings.HasPrefix(k, PairNamePrefix) {
  52. pairMap[k] = v[0]
  53. }
  54. }
  55. if r.Method == "POST" {
  56. fileName, data, mimeType, isGzipped, originalDataSize, isChunkedFile, e = parseMultipart(r, sizeLimit)
  57. } else {
  58. isGzipped = r.Header.Get("Content-Encoding") == "gzip"
  59. mimeType = r.Header.Get("Content-Type")
  60. fileName = ""
  61. data, e = ioutil.ReadAll(io.LimitReader(r.Body, sizeLimit+1))
  62. originalDataSize = len(data)
  63. if e == io.EOF || int64(originalDataSize) == sizeLimit+1 {
  64. io.Copy(ioutil.Discard, r.Body)
  65. }
  66. r.Body.Close()
  67. if isGzipped {
  68. if unzipped, e := util.UnGzipData(data); e == nil {
  69. originalDataSize = len(unzipped)
  70. }
  71. } else if shouldGzip, _ := util.IsGzippableFileType("", mimeType); shouldGzip {
  72. if compressedData, err := util.GzipData(data); err == nil {
  73. data = compressedData
  74. isGzipped = true
  75. }
  76. }
  77. }
  78. if e != nil {
  79. return
  80. }
  81. modifiedTime, _ = strconv.ParseUint(r.FormValue("ts"), 10, 64)
  82. ttl, _ = ReadTTL(r.FormValue("ttl"))
  83. return
  84. }
  85. func CreateNeedleFromRequest(r *http.Request, fixJpgOrientation bool, sizeLimit int64) (n *Needle, originalSize int, e error) {
  86. var pairMap map[string]string
  87. fname, mimeType, isGzipped, isChunkedFile := "", "", false, false
  88. n = new(Needle)
  89. fname, n.Data, mimeType, pairMap, isGzipped, originalSize, n.LastModified, n.Ttl, isChunkedFile, e = ParseUpload(r, sizeLimit)
  90. if e != nil {
  91. return
  92. }
  93. if len(fname) < 256 {
  94. n.Name = []byte(fname)
  95. n.SetHasName()
  96. }
  97. if len(mimeType) < 256 {
  98. n.Mime = []byte(mimeType)
  99. n.SetHasMime()
  100. }
  101. if len(pairMap) != 0 {
  102. trimmedPairMap := make(map[string]string)
  103. for k, v := range pairMap {
  104. trimmedPairMap[k[len(PairNamePrefix):]] = v
  105. }
  106. pairs, _ := json.Marshal(trimmedPairMap)
  107. if len(pairs) < 65536 {
  108. n.Pairs = pairs
  109. n.PairsSize = uint16(len(pairs))
  110. n.SetHasPairs()
  111. }
  112. }
  113. if isGzipped {
  114. n.SetGzipped()
  115. }
  116. if n.LastModified == 0 {
  117. n.LastModified = uint64(time.Now().Unix())
  118. }
  119. n.SetHasLastModifiedDate()
  120. if n.Ttl != EMPTY_TTL {
  121. n.SetHasTtl()
  122. }
  123. if isChunkedFile {
  124. n.SetIsChunkManifest()
  125. }
  126. if fixJpgOrientation {
  127. loweredName := strings.ToLower(fname)
  128. if mimeType == "image/jpeg" || strings.HasSuffix(loweredName, ".jpg") || strings.HasSuffix(loweredName, ".jpeg") {
  129. n.Data = images.FixJpgOrientation(n.Data)
  130. }
  131. }
  132. n.Checksum = NewCRC(n.Data)
  133. commaSep := strings.LastIndex(r.URL.Path, ",")
  134. dotSep := strings.LastIndex(r.URL.Path, ".")
  135. fid := r.URL.Path[commaSep+1:]
  136. if dotSep > 0 {
  137. fid = r.URL.Path[commaSep+1 : dotSep]
  138. }
  139. e = n.ParsePath(fid)
  140. return
  141. }
  142. func (n *Needle) ParsePath(fid string) (err error) {
  143. length := len(fid)
  144. if length <= CookieSize*2 {
  145. return fmt.Errorf("Invalid fid: %s", fid)
  146. }
  147. delta := ""
  148. deltaIndex := strings.LastIndex(fid, "_")
  149. if deltaIndex > 0 {
  150. fid, delta = fid[0:deltaIndex], fid[deltaIndex+1:]
  151. }
  152. n.Id, n.Cookie, err = ParseNeedleIdCookie(fid)
  153. if err != nil {
  154. return err
  155. }
  156. if delta != "" {
  157. if d, e := strconv.ParseUint(delta, 10, 64); e == nil {
  158. n.Id += Uint64ToNeedleId(d)
  159. } else {
  160. return e
  161. }
  162. }
  163. return err
  164. }
  165. func ParseNeedleIdCookie(key_hash_string string) (NeedleId, Cookie, error) {
  166. if len(key_hash_string) <= CookieSize*2 {
  167. return NeedleIdEmpty, 0, fmt.Errorf("KeyHash is too short.")
  168. }
  169. if len(key_hash_string) > (NeedleIdSize+CookieSize)*2 {
  170. return NeedleIdEmpty, 0, fmt.Errorf("KeyHash is too long.")
  171. }
  172. split := len(key_hash_string) - CookieSize*2
  173. needleId, err := ParseNeedleId(key_hash_string[:split])
  174. if err != nil {
  175. return NeedleIdEmpty, 0, fmt.Errorf("Parse needleId error: %v", err)
  176. }
  177. cookie, err := ParseCookie(key_hash_string[split:])
  178. if err != nil {
  179. return NeedleIdEmpty, 0, fmt.Errorf("Parse cookie error: %v", err)
  180. }
  181. return needleId, cookie, nil
  182. }
  183. func (n *Needle) LastModifiedString() string {
  184. return time.Unix(int64(n.LastModified), 0).Format("2006-01-02T15:04:05")
  185. }