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
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. "time"
  17. "bitbucket.org/taruti/mimemagic"
  18. "github.com/dchest/uniuri"
  19. "github.com/zenazn/goji/web"
  20. )
  21. var fileBlacklist = map[string]bool{
  22. "favicon.ico": true,
  23. "index.htm": true,
  24. "index.html": true,
  25. "index.php": true,
  26. "robots.txt": true,
  27. }
  28. // Describes metadata directly from the user request
  29. type UploadRequest struct {
  30. src io.Reader
  31. filename string
  32. expiry time.Duration // Seconds until expiry, 0 = never
  33. randomBarename bool
  34. deletionKey string // Empty string if not defined
  35. }
  36. // Metadata associated with a file as it would actually be stored
  37. type Upload struct {
  38. Filename string // Final filename on disk
  39. Size int64
  40. Expiry time.Time // Unix timestamp of expiry, 0=never
  41. DeleteKey string // Deletion key, one generated if not provided
  42. }
  43. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  44. upReq := UploadRequest{}
  45. uploadHeaderProcess(r, &upReq)
  46. contentType := r.Header.Get("Content-Type")
  47. if strings.HasPrefix(contentType, "multipart/form-data") {
  48. file, headers, err := r.FormFile("file")
  49. if err != nil {
  50. oopsHandler(c, w, r, RespHTML, "Could not upload file.")
  51. return
  52. }
  53. defer file.Close()
  54. r.ParseForm()
  55. if r.Form.Get("randomize") == "true" {
  56. upReq.randomBarename = true
  57. }
  58. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  59. upReq.src = file
  60. upReq.filename = headers.Filename
  61. } else {
  62. if r.FormValue("content") == "" {
  63. oopsHandler(c, w, r, RespHTML, "Empty file")
  64. return
  65. }
  66. extension := r.FormValue("extension")
  67. if extension == "" {
  68. extension = "txt"
  69. }
  70. upReq.src = strings.NewReader(r.FormValue("content"))
  71. upReq.expiry = parseExpiry(r.FormValue("expires"))
  72. upReq.filename = r.FormValue("filename") + "." + extension
  73. }
  74. upload, err := processUpload(upReq)
  75. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  76. if err != nil {
  77. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  78. return
  79. }
  80. js := generateJSONresponse(upload)
  81. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  82. w.Write(js)
  83. } else {
  84. if err != nil {
  85. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  86. return
  87. }
  88. http.Redirect(w, r, "/"+upload.Filename, 301)
  89. }
  90. }
  91. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  92. upReq := UploadRequest{}
  93. uploadHeaderProcess(r, &upReq)
  94. defer r.Body.Close()
  95. upReq.filename = c.URLParams["name"]
  96. upReq.src = r.Body
  97. upload, err := processUpload(upReq)
  98. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  99. if err != nil {
  100. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  101. return
  102. }
  103. js := generateJSONresponse(upload)
  104. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  105. w.Write(js)
  106. } else {
  107. if err != nil {
  108. oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
  109. return
  110. }
  111. fmt.Fprintf(w, Config.siteURL+upload.Filename)
  112. }
  113. }
  114. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  115. if r.FormValue("url") == "" {
  116. http.Redirect(w, r, "/", 301)
  117. return
  118. }
  119. upReq := UploadRequest{}
  120. grabUrl, _ := url.Parse(r.FormValue("url"))
  121. resp, err := http.Get(grabUrl.String())
  122. if err != nil {
  123. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  124. return
  125. }
  126. upReq.filename = filepath.Base(grabUrl.Path)
  127. upReq.src = resp.Body
  128. upload, err := processUpload(upReq)
  129. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  130. if err != nil {
  131. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  132. return
  133. }
  134. js := generateJSONresponse(upload)
  135. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  136. w.Write(js)
  137. } else {
  138. if err != nil {
  139. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  140. return
  141. }
  142. http.Redirect(w, r, "/"+upload.Filename, 301)
  143. }
  144. }
  145. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  146. if r.Header.Get("Linx-Randomize") == "yes" {
  147. upReq.randomBarename = true
  148. }
  149. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  150. // Get seconds until expiry. Non-integer responses never expire.
  151. expStr := r.Header.Get("Linx-Expiry")
  152. upReq.expiry = parseExpiry(expStr)
  153. }
  154. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  155. // Determine the appropriate filename, then write to disk
  156. barename, extension := barePlusExt(upReq.filename)
  157. if upReq.randomBarename || len(barename) == 0 {
  158. barename = generateBarename()
  159. }
  160. var header []byte
  161. if len(extension) == 0 {
  162. // Pull the first 512 bytes off for use in MIME detection
  163. header = make([]byte, 512)
  164. n, err := upReq.src.Read(header)
  165. if n == 0 || err != nil {
  166. return upload, errors.New("Empty file")
  167. }
  168. header = header[:n]
  169. // Determine the type of file from header
  170. mimetype := mimemagic.Match("", header)
  171. // If the mime type is in our map, use that
  172. // otherwise just use "ext"
  173. if val, exists := mimeToExtension[mimetype]; exists {
  174. extension = val
  175. } else {
  176. extension = "ext"
  177. }
  178. }
  179. upload.Filename = strings.Join([]string{barename, extension}, ".")
  180. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  181. fileexists := err == nil
  182. for fileexists {
  183. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  184. if err != nil {
  185. barename = barename + "1"
  186. } else {
  187. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  188. }
  189. upload.Filename = strings.Join([]string{barename, extension}, ".")
  190. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  191. fileexists = err == nil
  192. }
  193. if fileBlacklist[strings.ToLower(upload.Filename)] {
  194. return upload, errors.New("Prohibited filename")
  195. }
  196. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  197. if err != nil {
  198. return
  199. }
  200. defer dst.Close()
  201. // Get the rest of the metadata needed for storage
  202. if upReq.expiry != 0 {
  203. upload.Expiry = time.Now().Add(upReq.expiry)
  204. }
  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(upload.Expiry.Unix(), 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) time.Duration {
  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 time.Duration(expiry) * time.Second
  257. }
  258. }
  259. }