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.

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