needle.go 4.5 KB

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