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.

342 lines
8.4 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. // Check if the delete key matches, in which case overwrite
  187. if fileexists {
  188. metad, merr := metadataRead(upload.Filename)
  189. if merr == nil {
  190. if upReq.deletionKey == metad.DeleteKey {
  191. fileexists = false
  192. }
  193. }
  194. }
  195. for fileexists {
  196. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  197. if err != nil {
  198. barename = barename + "1"
  199. } else {
  200. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  201. }
  202. upload.Filename = strings.Join([]string{barename, extension}, ".")
  203. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  204. fileexists = err == nil
  205. }
  206. if fileBlacklist[strings.ToLower(upload.Filename)] {
  207. return upload, errors.New("Prohibited filename")
  208. }
  209. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  210. if err != nil {
  211. return
  212. }
  213. defer dst.Close()
  214. // Get the rest of the metadata needed for storage
  215. var expiry time.Time
  216. if upReq.expiry == 0 {
  217. expiry = neverExpire
  218. } else {
  219. expiry = time.Now().Add(upReq.expiry)
  220. }
  221. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  222. if bytes == 0 {
  223. os.Remove(path.Join(Config.filesDir, upload.Filename))
  224. return upload, errors.New("Empty file")
  225. } else if err != nil {
  226. os.Remove(path.Join(Config.filesDir, upload.Filename))
  227. return
  228. } else if bytes > Config.maxSize {
  229. os.Remove(path.Join(Config.filesDir, upload.Filename))
  230. return upload, errors.New("File too large")
  231. }
  232. upload.Metadata, err = generateMetadata(upload.Filename, expiry, upReq.deletionKey)
  233. if err != nil {
  234. os.Remove(path.Join(Config.filesDir, upload.Filename))
  235. os.Remove(path.Join(Config.metaDir, upload.Filename))
  236. return
  237. }
  238. err = metadataWrite(upload.Filename, &upload.Metadata)
  239. if err != nil {
  240. os.Remove(path.Join(Config.filesDir, upload.Filename))
  241. os.Remove(path.Join(Config.metaDir, upload.Filename))
  242. return
  243. }
  244. return
  245. }
  246. func generateBarename() string {
  247. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  248. }
  249. func generateJSONresponse(upload Upload) []byte {
  250. js, _ := json.Marshal(map[string]string{
  251. "url": Config.siteURL + upload.Filename,
  252. "filename": upload.Filename,
  253. "delete_key": upload.Metadata.DeleteKey,
  254. "expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
  255. "size": strconv.FormatInt(upload.Metadata.Size, 10),
  256. "mimetype": upload.Metadata.Mimetype,
  257. "sha256sum": upload.Metadata.Sha256sum,
  258. })
  259. return js
  260. }
  261. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  262. func barePlusExt(filename string) (barename, extension string) {
  263. filename = strings.TrimSpace(filename)
  264. filename = strings.ToLower(filename)
  265. extension = path.Ext(filename)
  266. barename = filename[:len(filename)-len(extension)]
  267. extension = barePlusRe.ReplaceAllString(extension, "")
  268. barename = barePlusRe.ReplaceAllString(barename, "")
  269. return
  270. }
  271. func parseExpiry(expStr string) time.Duration {
  272. if expStr == "" {
  273. return 0
  274. } else {
  275. expiry, err := strconv.ParseInt(expStr, 10, 64)
  276. if err != nil {
  277. return 0
  278. } else {
  279. return time.Duration(expiry) * time.Second
  280. }
  281. }
  282. }