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.

189 lines
5.1 KiB

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