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.

351 lines
8.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
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. "crossdomain.xml": true,
  28. }
  29. // Describes metadata directly from the user request
  30. type UploadRequest struct {
  31. src io.Reader
  32. filename string
  33. expiry time.Duration // Seconds until expiry, 0 = never
  34. randomBarename bool
  35. deletionKey string // Empty string if not defined
  36. }
  37. // Metadata associated with a file as it would actually be stored
  38. type Upload struct {
  39. Filename string // Final filename on disk
  40. Metadata Metadata
  41. }
  42. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  43. if !strictReferrerCheck(r, Config.siteURL, []string{"Linx-Delete-Key", "Linx-Expiry", "Linx-Randomize", "X-Requested-With"}) {
  44. badRequestHandler(c, w, r)
  45. return
  46. }
  47. upReq := UploadRequest{}
  48. uploadHeaderProcess(r, &upReq)
  49. contentType := r.Header.Get("Content-Type")
  50. if strings.HasPrefix(contentType, "multipart/form-data") {
  51. file, headers, err := r.FormFile("file")
  52. if err != nil {
  53. oopsHandler(c, w, r, RespHTML, "Could not upload file.")
  54. return
  55. }
  56. defer file.Close()
  57. r.ParseForm()
  58. if r.Form.Get("randomize") == "true" {
  59. upReq.randomBarename = true
  60. }
  61. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  62. upReq.src = file
  63. upReq.filename = headers.Filename
  64. } else {
  65. if r.FormValue("content") == "" {
  66. oopsHandler(c, w, r, RespHTML, "Empty file")
  67. return
  68. }
  69. extension := r.FormValue("extension")
  70. if extension == "" {
  71. extension = "txt"
  72. }
  73. upReq.src = strings.NewReader(r.FormValue("content"))
  74. upReq.expiry = parseExpiry(r.FormValue("expires"))
  75. upReq.filename = r.FormValue("filename") + "." + extension
  76. }
  77. upload, err := processUpload(upReq)
  78. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  79. if err != nil {
  80. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  81. return
  82. }
  83. js := generateJSONresponse(upload)
  84. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  85. w.Write(js)
  86. } else {
  87. if err != nil {
  88. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  89. return
  90. }
  91. http.Redirect(w, r, "/"+upload.Filename, 303)
  92. }
  93. }
  94. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  95. upReq := UploadRequest{}
  96. uploadHeaderProcess(r, &upReq)
  97. defer r.Body.Close()
  98. upReq.filename = c.URLParams["name"]
  99. upReq.src = r.Body
  100. upload, err := processUpload(upReq)
  101. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  102. if err != nil {
  103. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  104. return
  105. }
  106. js := generateJSONresponse(upload)
  107. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  108. w.Write(js)
  109. } else {
  110. if err != nil {
  111. oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
  112. return
  113. }
  114. fmt.Fprintf(w, Config.siteURL+upload.Filename)
  115. }
  116. }
  117. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  118. if Config.remoteAuthFile != "" {
  119. result, err := checkAuth(remoteAuthKeys, r.FormValue("key"))
  120. if err != nil || !result {
  121. unauthorizedHandler(c, w, r)
  122. return
  123. }
  124. }
  125. if r.FormValue("url") == "" {
  126. http.Redirect(w, r, "/", 303)
  127. return
  128. }
  129. upReq := UploadRequest{}
  130. grabUrl, _ := url.Parse(r.FormValue("url"))
  131. resp, err := http.Get(grabUrl.String())
  132. if err != nil {
  133. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  134. return
  135. }
  136. upReq.filename = filepath.Base(grabUrl.Path)
  137. upReq.src = resp.Body
  138. upReq.deletionKey = r.FormValue("deletekey")
  139. upReq.expiry = parseExpiry(r.FormValue("expiry"))
  140. upload, err := processUpload(upReq)
  141. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  142. if err != nil {
  143. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  144. return
  145. }
  146. js := generateJSONresponse(upload)
  147. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  148. w.Write(js)
  149. } else {
  150. if err != nil {
  151. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  152. return
  153. }
  154. http.Redirect(w, r, "/"+upload.Filename, 303)
  155. }
  156. }
  157. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  158. if r.Header.Get("Linx-Randomize") == "yes" {
  159. upReq.randomBarename = true
  160. }
  161. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  162. // Get seconds until expiry. Non-integer responses never expire.
  163. expStr := r.Header.Get("Linx-Expiry")
  164. upReq.expiry = parseExpiry(expStr)
  165. }
  166. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  167. // Determine the appropriate filename, then write to disk
  168. barename, extension := barePlusExt(upReq.filename)
  169. if upReq.randomBarename || len(barename) == 0 {
  170. barename = generateBarename()
  171. }
  172. var header []byte
  173. if len(extension) == 0 {
  174. // Pull the first 512 bytes off for use in MIME detection
  175. header = make([]byte, 512)
  176. n, _ := upReq.src.Read(header)
  177. if n == 0 {
  178. return upload, errors.New("Empty file")
  179. }
  180. header = header[:n]
  181. // Determine the type of file from header
  182. mimetype := mimemagic.Match("", header)
  183. // If the mime type is in our map, use that
  184. // otherwise just use "ext"
  185. if val, exists := mimeToExtension[mimetype]; exists {
  186. extension = val
  187. } else {
  188. extension = "ext"
  189. }
  190. }
  191. upload.Filename = strings.Join([]string{barename, extension}, ".")
  192. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  193. fileexists := err == nil
  194. // Check if the delete key matches, in which case overwrite
  195. if fileexists {
  196. metad, merr := metadataRead(upload.Filename)
  197. if merr == nil {
  198. if upReq.deletionKey == metad.DeleteKey {
  199. fileexists = false
  200. }
  201. }
  202. }
  203. for fileexists {
  204. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  205. if err != nil {
  206. barename = barename + "1"
  207. } else {
  208. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  209. }
  210. upload.Filename = strings.Join([]string{barename, extension}, ".")
  211. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  212. fileexists = err == nil
  213. }
  214. if fileBlacklist[strings.ToLower(upload.Filename)] {
  215. return upload, errors.New("Prohibited filename")
  216. }
  217. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  218. if err != nil {
  219. return
  220. }
  221. defer dst.Close()
  222. // Get the rest of the metadata needed for storage
  223. var expiry time.Time
  224. if upReq.expiry == 0 {
  225. expiry = neverExpire
  226. } else {
  227. expiry = time.Now().Add(upReq.expiry)
  228. }
  229. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  230. if bytes == 0 {
  231. os.Remove(path.Join(Config.filesDir, upload.Filename))
  232. return upload, errors.New("Empty file")
  233. } else if err != nil {
  234. os.Remove(path.Join(Config.filesDir, upload.Filename))
  235. return
  236. } else if bytes > Config.maxSize {
  237. os.Remove(path.Join(Config.filesDir, upload.Filename))
  238. return upload, errors.New("File too large")
  239. }
  240. upload.Metadata, err = generateMetadata(upload.Filename, expiry, upReq.deletionKey)
  241. if err != nil {
  242. os.Remove(path.Join(Config.filesDir, upload.Filename))
  243. os.Remove(path.Join(Config.metaDir, upload.Filename))
  244. return
  245. }
  246. err = metadataWrite(upload.Filename, &upload.Metadata)
  247. if err != nil {
  248. os.Remove(path.Join(Config.filesDir, upload.Filename))
  249. os.Remove(path.Join(Config.metaDir, upload.Filename))
  250. return
  251. }
  252. return
  253. }
  254. func generateBarename() string {
  255. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  256. }
  257. func generateJSONresponse(upload Upload) []byte {
  258. js, _ := json.Marshal(map[string]string{
  259. "url": Config.siteURL + upload.Filename,
  260. "filename": upload.Filename,
  261. "delete_key": upload.Metadata.DeleteKey,
  262. "expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
  263. "size": strconv.FormatInt(upload.Metadata.Size, 10),
  264. "mimetype": upload.Metadata.Mimetype,
  265. "sha256sum": upload.Metadata.Sha256sum,
  266. })
  267. return js
  268. }
  269. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  270. func barePlusExt(filename string) (barename, extension string) {
  271. filename = strings.TrimSpace(filename)
  272. filename = strings.ToLower(filename)
  273. extension = path.Ext(filename)
  274. barename = filename[:len(filename)-len(extension)]
  275. extension = barePlusRe.ReplaceAllString(extension, "")
  276. barename = barePlusRe.ReplaceAllString(barename, "")
  277. return
  278. }
  279. func parseExpiry(expStr string) time.Duration {
  280. if expStr == "" {
  281. return 0
  282. } else {
  283. expiry, err := strconv.ParseInt(expStr, 10, 64)
  284. if err != nil {
  285. return 0
  286. } else {
  287. return time.Duration(expiry) * time.Second
  288. }
  289. }
  290. }