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.

194 lines
5.3 KiB

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