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.

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