Contains the Concourse pipeline definition for building a line-server container
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.

267 lines
6.7 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "path"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "bitbucket.org/taruti/mimemagic"
  15. "github.com/zenazn/goji/web"
  16. )
  17. // Describes metadata directly from the user request
  18. type UploadRequest struct {
  19. src io.Reader
  20. filename string
  21. expiry int64 // Seconds until expiry, 0 = never
  22. randomBarename bool
  23. deletionKey string // Empty string if not defined
  24. }
  25. // Metadata associated with a file as it would actually be stored
  26. type Upload struct {
  27. Filename string // Final filename on disk
  28. Size int64
  29. Expiry int64 // Unix timestamp of expiry, 0=never
  30. DeleteKey string // Deletion key, one generated if not provided
  31. }
  32. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  33. upReq := UploadRequest{}
  34. uploadHeaderProcess(r, &upReq)
  35. contentType := r.Header.Get("Content-Type")
  36. if contentType == "application/octet-stream" {
  37. if r.URL.Query().Get("randomize") == "true" {
  38. upReq.randomBarename = true
  39. }
  40. upReq.expiry = parseExpiry(r.URL.Query().Get("expires"))
  41. defer r.Body.Close()
  42. upReq.src = r.Body
  43. upReq.filename = r.URL.Query().Get("qqfile")
  44. } else if strings.HasPrefix(contentType, "multipart/form-data") {
  45. file, headers, err := r.FormFile("file")
  46. if err != nil {
  47. oopsHandler(c, w, r)
  48. return
  49. }
  50. defer file.Close()
  51. r.ParseForm()
  52. if r.Form.Get("randomize") == "true" {
  53. upReq.randomBarename = true
  54. }
  55. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  56. upReq.src = file
  57. upReq.filename = headers.Filename
  58. } else {
  59. if r.FormValue("content") == "" {
  60. oopsHandler(c, w, r)
  61. return
  62. }
  63. extension := r.FormValue("extension")
  64. if extension == "" {
  65. extension = "txt"
  66. }
  67. upReq.src = strings.NewReader(r.FormValue("content"))
  68. upReq.expiry = parseExpiry(r.FormValue("expires"))
  69. upReq.filename = r.FormValue("filename") + "." + extension
  70. }
  71. upload, err := processUpload(upReq)
  72. if err != nil {
  73. oopsHandler(c, w, r)
  74. return
  75. }
  76. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  77. js := generateJSONresponse(upload)
  78. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  79. w.Write(js)
  80. } else {
  81. http.Redirect(w, r, "/"+upload.Filename, 301)
  82. }
  83. }
  84. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  85. upReq := UploadRequest{}
  86. uploadHeaderProcess(r, &upReq)
  87. defer r.Body.Close()
  88. upReq.filename = c.URLParams["name"]
  89. upReq.src = r.Body
  90. upload, err := processUpload(upReq)
  91. if err != nil {
  92. oopsHandler(c, w, r)
  93. return
  94. }
  95. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  96. js := generateJSONresponse(upload)
  97. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  98. w.Write(js)
  99. } else {
  100. fmt.Fprintf(w, Config.siteURL+upload.Filename)
  101. }
  102. }
  103. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  104. // For legacy reasons
  105. if r.Header.Get("X-Randomized-Filename") == "yes" {
  106. upReq.randomBarename = true
  107. } else if r.Header.Get("X-Randomized-Barename") == "yes" {
  108. upReq.randomBarename = true
  109. }
  110. upReq.deletionKey = r.Header.Get("X-Delete-Key")
  111. // Get seconds until expiry. Non-integer responses never expire.
  112. expStr := r.Header.Get("X-File-Expiry")
  113. upReq.expiry = parseExpiry(expStr)
  114. }
  115. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  116. // Determine the appropriate filename, then write to disk
  117. barename, extension := barePlusExt(upReq.filename)
  118. // Pull the first 512 bytes off for use in MIME detection if needed
  119. // If the file uploaded fit in 512 or less bytes, then the Read will have returned EOF
  120. // In this situation we don't want to create a MultiReader as this will cause no EOF to be emitted
  121. // by the resulting io.Reader. Instead we just create a new reader from the bytes we already read,
  122. // and only create a multiReader if we have yet to get EOF from the first read.
  123. var fileSrc io.Reader
  124. header := make([]byte, 512)
  125. n, err := upReq.src.Read(header)
  126. if n == 0 {
  127. return
  128. } else if err == io.EOF {
  129. fileSrc = bytes.NewReader(header[:n])
  130. } else {
  131. fileSrc = io.MultiReader(bytes.NewReader(header), upReq.src)
  132. }
  133. if upReq.randomBarename || len(barename) == 0 {
  134. barename = generateBarename()
  135. }
  136. if len(extension) == 0 {
  137. // Determine the type of file from header
  138. mimetype := mimemagic.Match("", header)
  139. // If the mime type is in our map, use that
  140. // otherwise just use "ext"
  141. if val, exists := mimeToExtension[mimetype]; exists {
  142. extension = val
  143. } else {
  144. extension = "ext"
  145. }
  146. }
  147. upload.Filename = strings.Join([]string{barename, extension}, ".")
  148. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  149. fileexists := err == nil
  150. for fileexists {
  151. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  152. if err != nil {
  153. barename = barename + "1"
  154. } else {
  155. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  156. }
  157. upload.Filename = strings.Join([]string{barename, extension}, ".")
  158. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  159. fileexists = err == nil
  160. }
  161. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  162. if err != nil {
  163. return
  164. }
  165. defer dst.Close()
  166. // Get the rest of the metadata needed for storage
  167. upload.Expiry = getFutureTimestamp(upReq.expiry)
  168. // If no delete key specified, pick a random one.
  169. if upReq.deletionKey == "" {
  170. upload.DeleteKey = randomString(30)
  171. } else {
  172. upload.DeleteKey = upReq.deletionKey
  173. }
  174. metadataWrite(upload.Filename, &upload)
  175. bytes, err := io.Copy(dst, fileSrc)
  176. if err != nil {
  177. return
  178. } else if bytes == 0 {
  179. os.Remove(path.Join(Config.filesDir, upload.Filename))
  180. os.Remove(path.Join(Config.metaDir, upload.Filename))
  181. return upload, errors.New("Empty file")
  182. }
  183. upload.Size = bytes
  184. return
  185. }
  186. func generateBarename() string {
  187. return randomString(8)
  188. }
  189. func generateJSONresponse(upload Upload) []byte {
  190. js, _ := json.Marshal(map[string]string{
  191. "url": Config.siteURL + upload.Filename,
  192. "filename": upload.Filename,
  193. "delete_key": upload.DeleteKey,
  194. "expiry": strconv.FormatInt(int64(upload.Expiry), 10),
  195. "size": strconv.FormatInt(upload.Size, 10),
  196. })
  197. return js
  198. }
  199. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  200. func barePlusExt(filename string) (barename, extension string) {
  201. filename = strings.TrimSpace(filename)
  202. filename = strings.ToLower(filename)
  203. extension = path.Ext(filename)
  204. barename = filename[:len(filename)-len(extension)]
  205. extension = barePlusRe.ReplaceAllString(extension, "")
  206. barename = barePlusRe.ReplaceAllString(barename, "")
  207. return
  208. }
  209. func parseExpiry(expStr string) int64 {
  210. if expStr == "" {
  211. return 0
  212. } else {
  213. expiry, err := strconv.ParseInt(expStr, 10, 64)
  214. if err != nil {
  215. return 0
  216. } else {
  217. return int64(expiry)
  218. }
  219. }
  220. }