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.

229 lines
5.6 KiB

12 years ago
12 years ago
12 years ago
12 years ago
9 years ago
9 years ago
12 years ago
  1. package storage
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "mime"
  6. "net/http"
  7. "path"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/chrislusf/seaweedfs/go/glog"
  12. "github.com/chrislusf/seaweedfs/go/images"
  13. "github.com/chrislusf/seaweedfs/go/operation"
  14. )
  15. const (
  16. NeedleHeaderSize = 16 //should never change this
  17. NeedlePaddingSize = 8
  18. NeedleChecksumSize = 4
  19. MaxPossibleVolumeSize = 4 * 1024 * 1024 * 1024 * 8
  20. )
  21. /*
  22. * A Needle means a uploaded and stored file.
  23. * Needle file size is limited to 4GB for now.
  24. */
  25. type Needle struct {
  26. Cookie uint32 `comment:"random number to mitigate brute force lookups"`
  27. Id uint64 `comment:"needle id"`
  28. Size uint32 `comment:"sum of DataSize,Data,NameSize,Name,MimeSize,Mime"`
  29. DataSize uint32 `comment:"Data size"` //version2
  30. Data []byte `comment:"The actual file data"`
  31. Flags byte `comment:"boolean flags"` //version2
  32. NameSize uint8 //version2
  33. Name []byte `comment:"maximum 256 characters"` //version2
  34. MimeSize uint8 //version2
  35. Mime []byte `comment:"maximum 256 characters"` //version2
  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. Padding []byte `comment:"Aligned to 8 bytes"`
  40. }
  41. func (n *Needle) String() (str string) {
  42. str = fmt.Sprintf("Cookie:%d, Id:%d, Size:%d, DataSize:%d, Name: %s, Mime: %s", n.Cookie, n.Id, n.Size, n.DataSize, n.Name, n.Mime)
  43. return
  44. }
  45. func ParseUpload(r *http.Request) (
  46. fileName string, data []byte, mimeType string, isGzipped bool,
  47. modifiedTime uint64, ttl *TTL, isChunkedFile bool, e error) {
  48. form, fe := r.MultipartReader()
  49. if fe != nil {
  50. glog.V(0).Infoln("MultipartReader [ERROR]", fe)
  51. e = fe
  52. return
  53. }
  54. //first multi-part item
  55. part, fe := form.NextPart()
  56. if fe != nil {
  57. glog.V(0).Infoln("Reading Multi part [ERROR]", fe)
  58. e = fe
  59. return
  60. }
  61. fileName = part.FileName()
  62. if fileName != "" {
  63. fileName = path.Base(fileName)
  64. }
  65. data, e = ioutil.ReadAll(part)
  66. if e != nil {
  67. glog.V(0).Infoln("Reading Content [ERROR]", e)
  68. return
  69. }
  70. //if the filename is empty string, do a search on the other multi-part items
  71. for fileName == "" {
  72. part2, fe := form.NextPart()
  73. if fe != nil {
  74. break // no more or on error, just safely break
  75. }
  76. fName := part2.FileName()
  77. //found the first <file type> multi-part has filename
  78. if fName != "" {
  79. data2, fe2 := ioutil.ReadAll(part2)
  80. if fe2 != nil {
  81. glog.V(0).Infoln("Reading Content [ERROR]", fe2)
  82. e = fe2
  83. return
  84. }
  85. //update
  86. data = data2
  87. fileName = path.Base(fName)
  88. break
  89. }
  90. }
  91. dotIndex := strings.LastIndex(fileName, ".")
  92. ext, mtype := "", ""
  93. if dotIndex > 0 {
  94. ext = strings.ToLower(fileName[dotIndex:])
  95. mtype = mime.TypeByExtension(ext)
  96. }
  97. contentType := part.Header.Get("Content-Type")
  98. if contentType != "" && mtype != contentType {
  99. mimeType = contentType //only return mime type if not deductable
  100. mtype = contentType
  101. }
  102. if part.Header.Get("Content-Encoding") == "gzip" {
  103. isGzipped = true
  104. } else if operation.IsGzippable(ext, mtype) {
  105. if data, e = operation.GzipData(data); e != nil {
  106. return
  107. }
  108. isGzipped = true
  109. }
  110. if ext == ".gz" {
  111. isGzipped = true
  112. }
  113. if strings.HasSuffix(fileName, ".gz") &&
  114. !strings.HasSuffix(fileName, ".tar.gz") {
  115. fileName = fileName[:len(fileName)-3]
  116. }
  117. modifiedTime, _ = strconv.ParseUint(r.FormValue("ts"), 10, 64)
  118. ttl, _ = ReadTTL(r.FormValue("ttl"))
  119. isChunkedFile, _ = strconv.ParseBool(r.FormValue("cm"))
  120. return
  121. }
  122. func NewNeedle(r *http.Request, fixJpgOrientation bool) (n *Needle, e error) {
  123. fname, mimeType, isGzipped, isChunkedFile := "", "", false, false
  124. n = new(Needle)
  125. fname, n.Data, mimeType, isGzipped, n.LastModified, n.Ttl, isChunkedFile, e = ParseUpload(r)
  126. if e != nil {
  127. return
  128. }
  129. if len(fname) < 256 {
  130. n.Name = []byte(fname)
  131. n.SetHasName()
  132. }
  133. if len(mimeType) < 256 {
  134. n.Mime = []byte(mimeType)
  135. n.SetHasMime()
  136. }
  137. if isGzipped {
  138. n.SetGzipped()
  139. }
  140. if n.LastModified == 0 {
  141. n.LastModified = uint64(time.Now().Unix())
  142. }
  143. n.SetHasLastModifiedDate()
  144. if n.Ttl != EMPTY_TTL {
  145. n.SetHasTtl()
  146. }
  147. if isChunkedFile {
  148. n.SetIsChunkManifest()
  149. }
  150. if fixJpgOrientation {
  151. loweredName := strings.ToLower(fname)
  152. if mimeType == "image/jpeg" || strings.HasSuffix(loweredName, ".jpg") || strings.HasSuffix(loweredName, ".jpeg") {
  153. n.Data = images.FixJpgOrientation(n.Data)
  154. }
  155. }
  156. n.Checksum = NewCRC(n.Data)
  157. commaSep := strings.LastIndex(r.URL.Path, ",")
  158. dotSep := strings.LastIndex(r.URL.Path, ".")
  159. fid := r.URL.Path[commaSep+1:]
  160. if dotSep > 0 {
  161. fid = r.URL.Path[commaSep+1 : dotSep]
  162. }
  163. e = n.ParsePath(fid)
  164. return
  165. }
  166. func (n *Needle) ParsePath(fid string) (err error) {
  167. length := len(fid)
  168. if length <= 8 {
  169. return fmt.Errorf("Invalid fid: %s", fid)
  170. }
  171. delta := ""
  172. deltaIndex := strings.LastIndex(fid, "_")
  173. if deltaIndex > 0 {
  174. fid, delta = fid[0:deltaIndex], fid[deltaIndex+1:]
  175. }
  176. n.Id, n.Cookie, err = ParseKeyHash(fid)
  177. if err != nil {
  178. return err
  179. }
  180. if delta != "" {
  181. if d, e := strconv.ParseUint(delta, 10, 64); e == nil {
  182. n.Id += d
  183. } else {
  184. return e
  185. }
  186. }
  187. return err
  188. }
  189. func ParseKeyHash(key_hash_string string) (uint64, uint32, error) {
  190. if len(key_hash_string) <= 8 {
  191. return 0, 0, fmt.Errorf("KeyHash is too short.")
  192. }
  193. if len(key_hash_string) > 24 {
  194. return 0, 0, fmt.Errorf("KeyHash is too long.")
  195. }
  196. split := len(key_hash_string) - 8
  197. key, err := strconv.ParseUint(key_hash_string[:split], 16, 64)
  198. if err != nil {
  199. return 0, 0, fmt.Errorf("Parse key error: %v", err)
  200. }
  201. hash, err := strconv.ParseUint(key_hash_string[split:], 16, 32)
  202. if err != nil {
  203. return 0, 0, fmt.Errorf("Parse hash error: %v", err)
  204. }
  205. return key, uint32(hash), nil
  206. }