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.

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