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.

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