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.

324 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
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. upReq.deletionKey = r.FormValue("deletekey")
  129. upReq.expiry = parseExpiry(r.FormValue("expiry"))
  130. upload, err := processUpload(upReq)
  131. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  132. if err != nil {
  133. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  134. return
  135. }
  136. js := generateJSONresponse(upload)
  137. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  138. w.Write(js)
  139. } else {
  140. if err != nil {
  141. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  142. return
  143. }
  144. http.Redirect(w, r, "/"+upload.Filename, 301)
  145. }
  146. }
  147. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  148. if r.Header.Get("Linx-Randomize") == "yes" {
  149. upReq.randomBarename = true
  150. }
  151. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  152. // Get seconds until expiry. Non-integer responses never expire.
  153. expStr := r.Header.Get("Linx-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, _ := upReq.src.Read(header)
  167. if n == 0 {
  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. if upReq.expiry == 0 {
  205. upload.Expiry = neverExpire
  206. } else {
  207. upload.Expiry = time.Now().Add(upReq.expiry)
  208. }
  209. // If no delete key specified, pick a random one.
  210. if upReq.deletionKey == "" {
  211. upload.DeleteKey = uniuri.NewLen(30)
  212. } else {
  213. upload.DeleteKey = upReq.deletionKey
  214. }
  215. metadataWrite(upload.Filename, &upload)
  216. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  217. if bytes == 0 {
  218. os.Remove(path.Join(Config.filesDir, upload.Filename))
  219. os.Remove(path.Join(Config.metaDir, upload.Filename))
  220. return upload, errors.New("Empty file")
  221. } else if err != nil {
  222. os.Remove(path.Join(Config.filesDir, upload.Filename))
  223. os.Remove(path.Join(Config.metaDir, upload.Filename))
  224. return
  225. }
  226. upload.Size = bytes
  227. return
  228. }
  229. func generateBarename() string {
  230. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  231. }
  232. func generateJSONresponse(upload Upload) []byte {
  233. js, _ := json.Marshal(map[string]string{
  234. "url": Config.siteURL + upload.Filename,
  235. "filename": upload.Filename,
  236. "delete_key": upload.DeleteKey,
  237. "expiry": strconv.FormatInt(upload.Expiry.Unix(), 10),
  238. "size": strconv.FormatInt(upload.Size, 10),
  239. })
  240. return js
  241. }
  242. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  243. func barePlusExt(filename string) (barename, extension string) {
  244. filename = strings.TrimSpace(filename)
  245. filename = strings.ToLower(filename)
  246. extension = path.Ext(filename)
  247. barename = filename[:len(filename)-len(extension)]
  248. extension = barePlusRe.ReplaceAllString(extension, "")
  249. barename = barePlusRe.ReplaceAllString(barename, "")
  250. return
  251. }
  252. func parseExpiry(expStr string) time.Duration {
  253. if expStr == "" {
  254. return 0
  255. } else {
  256. expiry, err := strconv.ParseInt(expStr, 10, 64)
  257. if err != nil {
  258. return 0
  259. } else {
  260. return time.Duration(expiry) * time.Second
  261. }
  262. }
  263. }