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.

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