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.

251 lines
6.0 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. if upReq.randomBarename || len(barename) == 0 {
  112. barename = generateBarename()
  113. }
  114. var header []byte
  115. if len(extension) == 0 {
  116. // Pull the first 512 bytes off for use in MIME detection
  117. header = make([]byte, 512)
  118. n, err := upReq.src.Read(header)
  119. if n == 0 {
  120. return upload, err
  121. }
  122. header = header[:n]
  123. // Determine the type of file from header
  124. mimetype := mimemagic.Match("", header)
  125. // If the mime type is in our map, use that
  126. // otherwise just use "ext"
  127. if val, exists := mimeToExtension[mimetype]; exists {
  128. extension = val
  129. } else {
  130. extension = "ext"
  131. }
  132. }
  133. upload.Filename = strings.Join([]string{barename, extension}, ".")
  134. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  135. fileexists := err == nil
  136. for fileexists {
  137. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  138. if err != nil {
  139. barename = barename + "1"
  140. } else {
  141. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  142. }
  143. upload.Filename = strings.Join([]string{barename, extension}, ".")
  144. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  145. fileexists = err == nil
  146. }
  147. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  148. if err != nil {
  149. return
  150. }
  151. defer dst.Close()
  152. // Get the rest of the metadata needed for storage
  153. upload.Expiry = getFutureTimestamp(upReq.expiry)
  154. // If no delete key specified, pick a random one.
  155. if upReq.deletionKey == "" {
  156. upload.DeleteKey = randomString(30)
  157. } else {
  158. upload.DeleteKey = upReq.deletionKey
  159. }
  160. metadataWrite(upload.Filename, &upload)
  161. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  162. if err != nil {
  163. return
  164. } else if bytes == 0 {
  165. os.Remove(path.Join(Config.filesDir, upload.Filename))
  166. os.Remove(path.Join(Config.metaDir, upload.Filename))
  167. return upload, errors.New("Empty file")
  168. }
  169. upload.Size = bytes
  170. return
  171. }
  172. func generateBarename() string {
  173. return randomString(8)
  174. }
  175. func generateJSONresponse(upload Upload) []byte {
  176. js, _ := json.Marshal(map[string]string{
  177. "url": Config.siteURL + upload.Filename,
  178. "filename": upload.Filename,
  179. "delete_key": upload.DeleteKey,
  180. "expiry": strconv.FormatInt(int64(upload.Expiry), 10),
  181. "size": strconv.FormatInt(upload.Size, 10),
  182. })
  183. return js
  184. }
  185. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  186. func barePlusExt(filename string) (barename, extension string) {
  187. filename = strings.TrimSpace(filename)
  188. filename = strings.ToLower(filename)
  189. extension = path.Ext(filename)
  190. barename = filename[:len(filename)-len(extension)]
  191. extension = barePlusRe.ReplaceAllString(extension, "")
  192. barename = barePlusRe.ReplaceAllString(barename, "")
  193. return
  194. }
  195. func parseExpiry(expStr string) int64 {
  196. if expStr == "" {
  197. return 0
  198. } else {
  199. expiry, err := strconv.ParseInt(expStr, 10, 64)
  200. if err != nil {
  201. return 0
  202. } else {
  203. return int64(expiry)
  204. }
  205. }
  206. }