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.

329 lines
8.0 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
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. Metadata Metadata
  40. }
  41. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  42. if !strictReferrerCheck(r, Config.siteURL, []string{"Linx-Delete-Key", "Linx-Expiry", "Linx-Randomize"}) {
  43. badRequestHandler(c, w, r)
  44. return
  45. }
  46. upReq := UploadRequest{}
  47. uploadHeaderProcess(r, &upReq)
  48. contentType := r.Header.Get("Content-Type")
  49. if strings.HasPrefix(contentType, "multipart/form-data") {
  50. file, headers, err := r.FormFile("file")
  51. if err != nil {
  52. oopsHandler(c, w, r, RespHTML, "Could not upload file.")
  53. return
  54. }
  55. defer file.Close()
  56. r.ParseForm()
  57. if r.Form.Get("randomize") == "true" {
  58. upReq.randomBarename = true
  59. }
  60. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  61. upReq.src = file
  62. upReq.filename = headers.Filename
  63. } else {
  64. if r.FormValue("content") == "" {
  65. oopsHandler(c, w, r, RespHTML, "Empty file")
  66. return
  67. }
  68. extension := r.FormValue("extension")
  69. if extension == "" {
  70. extension = "txt"
  71. }
  72. upReq.src = strings.NewReader(r.FormValue("content"))
  73. upReq.expiry = parseExpiry(r.FormValue("expires"))
  74. upReq.filename = r.FormValue("filename") + "." + extension
  75. }
  76. upload, err := processUpload(upReq)
  77. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  78. if err != nil {
  79. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  80. return
  81. }
  82. js := generateJSONresponse(upload)
  83. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  84. w.Write(js)
  85. } else {
  86. if err != nil {
  87. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  88. return
  89. }
  90. http.Redirect(w, r, "/"+upload.Filename, 301)
  91. }
  92. }
  93. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  94. upReq := UploadRequest{}
  95. uploadHeaderProcess(r, &upReq)
  96. defer r.Body.Close()
  97. upReq.filename = c.URLParams["name"]
  98. upReq.src = r.Body
  99. upload, err := processUpload(upReq)
  100. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  101. if err != nil {
  102. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  103. return
  104. }
  105. js := generateJSONresponse(upload)
  106. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  107. w.Write(js)
  108. } else {
  109. if err != nil {
  110. oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
  111. return
  112. }
  113. fmt.Fprintf(w, Config.siteURL+upload.Filename)
  114. }
  115. }
  116. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  117. if r.FormValue("url") == "" {
  118. http.Redirect(w, r, "/", 301)
  119. return
  120. }
  121. upReq := UploadRequest{}
  122. grabUrl, _ := url.Parse(r.FormValue("url"))
  123. resp, err := http.Get(grabUrl.String())
  124. if err != nil {
  125. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  126. return
  127. }
  128. upReq.filename = filepath.Base(grabUrl.Path)
  129. upReq.src = resp.Body
  130. upReq.deletionKey = r.FormValue("deletekey")
  131. upReq.expiry = parseExpiry(r.FormValue("expiry"))
  132. upload, err := processUpload(upReq)
  133. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  134. if err != nil {
  135. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  136. return
  137. }
  138. js := generateJSONresponse(upload)
  139. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  140. w.Write(js)
  141. } else {
  142. if err != nil {
  143. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  144. return
  145. }
  146. http.Redirect(w, r, "/"+upload.Filename, 301)
  147. }
  148. }
  149. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  150. if r.Header.Get("Linx-Randomize") == "yes" {
  151. upReq.randomBarename = true
  152. }
  153. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  154. // Get seconds until expiry. Non-integer responses never expire.
  155. expStr := r.Header.Get("Linx-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, _ := upReq.src.Read(header)
  169. if n == 0 {
  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. var expiry time.Time
  207. if upReq.expiry == 0 {
  208. expiry = neverExpire
  209. } else {
  210. expiry = time.Now().Add(upReq.expiry)
  211. }
  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. return upload, errors.New("Empty file")
  216. } else if err != nil {
  217. os.Remove(path.Join(Config.filesDir, upload.Filename))
  218. return
  219. }
  220. upload.Metadata, err = generateMetadata(upload.Filename, expiry, upReq.deletionKey)
  221. 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. err = metadataWrite(upload.Filename, &upload.Metadata)
  227. if err != nil {
  228. os.Remove(path.Join(Config.filesDir, upload.Filename))
  229. os.Remove(path.Join(Config.metaDir, upload.Filename))
  230. return
  231. }
  232. return
  233. }
  234. func generateBarename() string {
  235. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  236. }
  237. func generateJSONresponse(upload Upload) []byte {
  238. js, _ := json.Marshal(map[string]string{
  239. "url": Config.siteURL + upload.Filename,
  240. "filename": upload.Filename,
  241. "delete_key": upload.Metadata.DeleteKey,
  242. "expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
  243. "size": strconv.FormatInt(upload.Metadata.Size, 10),
  244. "mimetype": upload.Metadata.Mimetype,
  245. "sha256sum": upload.Metadata.Sha256sum,
  246. })
  247. return js
  248. }
  249. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  250. func barePlusExt(filename string) (barename, extension string) {
  251. filename = strings.TrimSpace(filename)
  252. filename = strings.ToLower(filename)
  253. extension = path.Ext(filename)
  254. barename = filename[:len(filename)-len(extension)]
  255. extension = barePlusRe.ReplaceAllString(extension, "")
  256. barename = barePlusRe.ReplaceAllString(barename, "")
  257. return
  258. }
  259. func parseExpiry(expStr string) time.Duration {
  260. if expStr == "" {
  261. return 0
  262. } else {
  263. expiry, err := strconv.ParseInt(expStr, 10, 64)
  264. if err != nil {
  265. return 0
  266. } else {
  267. return time.Duration(expiry) * time.Second
  268. }
  269. }
  270. }