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.

319 lines
7.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
  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. upload, err := processUpload(upReq)
  128. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  129. if err != nil {
  130. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  131. return
  132. }
  133. js := generateJSONresponse(upload)
  134. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  135. w.Write(js)
  136. } else {
  137. if err != nil {
  138. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  139. return
  140. }
  141. http.Redirect(w, r, "/"+upload.Filename, 301)
  142. }
  143. }
  144. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  145. // For legacy reasons
  146. if r.Header.Get("X-Randomized-Filename") == "yes" {
  147. upReq.randomBarename = true
  148. } else if r.Header.Get("X-Randomized-Barename") == "yes" {
  149. upReq.randomBarename = true
  150. }
  151. upReq.deletionKey = r.Header.Get("X-Delete-Key")
  152. // Get seconds until expiry. Non-integer responses never expire.
  153. expStr := r.Header.Get("X-File-Expiry")
  154. upReq.expiry = parseExpiry(expStr)
  155. }
  156. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  157. // Determine the appropriate filename, then write to disk
  158. barename, extension := barePlusExt(upReq.filename)
  159. if upReq.randomBarename || len(barename) == 0 {
  160. barename = generateBarename()
  161. }
  162. var header []byte
  163. if len(extension) == 0 {
  164. // Pull the first 512 bytes off for use in MIME detection
  165. header = make([]byte, 512)
  166. n, err := upReq.src.Read(header)
  167. if n == 0 || err != nil {
  168. return upload, errors.New("Empty file")
  169. }
  170. header = header[:n]
  171. // Determine the type of file from header
  172. mimetype := mimemagic.Match("", header)
  173. // If the mime type is in our map, use that
  174. // otherwise just use "ext"
  175. if val, exists := mimeToExtension[mimetype]; exists {
  176. extension = val
  177. } else {
  178. extension = "ext"
  179. }
  180. }
  181. upload.Filename = strings.Join([]string{barename, extension}, ".")
  182. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  183. fileexists := err == nil
  184. for fileexists {
  185. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  186. if err != nil {
  187. barename = barename + "1"
  188. } else {
  189. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  190. }
  191. upload.Filename = strings.Join([]string{barename, extension}, ".")
  192. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  193. fileexists = err == nil
  194. }
  195. if fileBlacklist[strings.ToLower(upload.Filename)] {
  196. return upload, errors.New("Prohibited filename")
  197. }
  198. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  199. if err != nil {
  200. return
  201. }
  202. defer dst.Close()
  203. // Get the rest of the metadata needed for storage
  204. upload.Expiry = getFutureTimestamp(upReq.expiry)
  205. // If no delete key specified, pick a random one.
  206. if upReq.deletionKey == "" {
  207. upload.DeleteKey = uniuri.NewLen(30)
  208. } else {
  209. upload.DeleteKey = upReq.deletionKey
  210. }
  211. metadataWrite(upload.Filename, &upload)
  212. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  213. if bytes == 0 {
  214. os.Remove(path.Join(Config.filesDir, upload.Filename))
  215. os.Remove(path.Join(Config.metaDir, upload.Filename))
  216. return upload, errors.New("Empty file")
  217. } else if err != nil {
  218. os.Remove(path.Join(Config.filesDir, upload.Filename))
  219. os.Remove(path.Join(Config.metaDir, upload.Filename))
  220. return
  221. }
  222. upload.Size = bytes
  223. return
  224. }
  225. func generateBarename() string {
  226. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  227. }
  228. func generateJSONresponse(upload Upload) []byte {
  229. js, _ := json.Marshal(map[string]string{
  230. "url": Config.siteURL + upload.Filename,
  231. "filename": upload.Filename,
  232. "delete_key": upload.DeleteKey,
  233. "expiry": strconv.FormatInt(int64(upload.Expiry), 10),
  234. "size": strconv.FormatInt(upload.Size, 10),
  235. })
  236. return js
  237. }
  238. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  239. func barePlusExt(filename string) (barename, extension string) {
  240. filename = strings.TrimSpace(filename)
  241. filename = strings.ToLower(filename)
  242. extension = path.Ext(filename)
  243. barename = filename[:len(filename)-len(extension)]
  244. extension = barePlusRe.ReplaceAllString(extension, "")
  245. barename = barePlusRe.ReplaceAllString(barename, "")
  246. return
  247. }
  248. func parseExpiry(expStr string) int64 {
  249. if expStr == "" {
  250. return 0
  251. } else {
  252. expiry, err := strconv.ParseInt(expStr, 10, 64)
  253. if err != nil {
  254. return 0
  255. } else {
  256. return int64(expiry)
  257. }
  258. }
  259. }