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.

358 lines
8.9 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
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "bitbucket.org/taruti/mimemagic"
  17. "github.com/dchest/uniuri"
  18. "github.com/zenazn/goji/web"
  19. )
  20. var fileBlacklist = map[string]bool{
  21. "favicon.ico": true,
  22. "index.htm": true,
  23. "index.html": true,
  24. "index.php": true,
  25. "robots.txt": true,
  26. "crossdomain.xml": 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, getSiteURL(r), []string{"Linx-Delete-Key", "Linx-Expiry", "Linx-Randomize", "X-Requested-With"}) {
  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, r)
  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, Config.sitePath+upload.Filename, 303)
  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, r)
  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, "%s\n", getSiteURL(r)+upload.Filename)
  114. }
  115. }
  116. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  117. if Config.remoteAuthFile != "" {
  118. result, err := checkAuth(remoteAuthKeys, r.FormValue("key"))
  119. if err != nil || !result {
  120. unauthorizedHandler(c, w, r)
  121. return
  122. }
  123. }
  124. if r.FormValue("url") == "" {
  125. http.Redirect(w, r, Config.sitePath, 303)
  126. return
  127. }
  128. upReq := UploadRequest{}
  129. grabUrl, _ := url.Parse(r.FormValue("url"))
  130. resp, err := http.Get(grabUrl.String())
  131. if err != nil {
  132. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  133. return
  134. }
  135. upReq.filename = filepath.Base(grabUrl.Path)
  136. upReq.src = resp.Body
  137. upReq.deletionKey = r.FormValue("deletekey")
  138. upReq.randomBarename = r.FormValue("randomize") == "yes"
  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, r)
  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, Config.sitePath+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. upload.Filename = strings.Replace(upload.Filename, " ", "", -1)
  193. fileexists, _ := fileBackend.Exists(upload.Filename)
  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. fileexists, err = fileBackend.Exists(upload.Filename)
  212. }
  213. if fileBlacklist[strings.ToLower(upload.Filename)] {
  214. return upload, errors.New("Prohibited filename")
  215. }
  216. // Get the rest of the metadata needed for storage
  217. var expiry time.Time
  218. if upReq.expiry == 0 {
  219. expiry = neverExpire
  220. } else {
  221. expiry = time.Now().Add(upReq.expiry)
  222. }
  223. bytes, err := fileBackend.Put(upload.Filename, io.MultiReader(bytes.NewReader(header), upReq.src))
  224. if err != nil {
  225. return upload, err
  226. } else if bytes > Config.maxSize {
  227. fileBackend.Delete(upload.Filename)
  228. return upload, errors.New("File too large")
  229. }
  230. upload.Metadata, err = generateMetadata(upload.Filename, expiry, upReq.deletionKey)
  231. if err != nil {
  232. fileBackend.Delete(upload.Filename)
  233. return
  234. }
  235. err = metadataWrite(upload.Filename, &upload.Metadata)
  236. if err != nil {
  237. fileBackend.Delete(upload.Filename)
  238. return
  239. }
  240. return
  241. }
  242. func generateBarename() string {
  243. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  244. }
  245. func generateJSONresponse(upload Upload, r *http.Request) []byte {
  246. js, _ := json.Marshal(map[string]string{
  247. "url": getSiteURL(r) + upload.Filename,
  248. "filename": upload.Filename,
  249. "delete_key": upload.Metadata.DeleteKey,
  250. "expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
  251. "size": strconv.FormatInt(upload.Metadata.Size, 10),
  252. "mimetype": upload.Metadata.Mimetype,
  253. "sha256sum": upload.Metadata.Sha256sum,
  254. })
  255. return js
  256. }
  257. var bareRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  258. var extRe = regexp.MustCompile(`[^A-Za-z0-9\-\.]`)
  259. var compressedExts = map[string]bool{
  260. ".bz2": true,
  261. ".gz": true,
  262. ".xz": true,
  263. }
  264. var archiveExts = map[string]bool{
  265. ".tar": true,
  266. }
  267. func barePlusExt(filename string) (barename, extension string) {
  268. filename = strings.TrimSpace(filename)
  269. filename = strings.ToLower(filename)
  270. extension = path.Ext(filename)
  271. barename = filename[:len(filename)-len(extension)]
  272. if compressedExts[extension] {
  273. ext2 := path.Ext(barename)
  274. if archiveExts[ext2] {
  275. barename = barename[:len(barename)-len(ext2)]
  276. extension = ext2 + extension
  277. }
  278. }
  279. extension = extRe.ReplaceAllString(extension, "")
  280. barename = bareRe.ReplaceAllString(barename, "")
  281. extension = strings.Trim(extension, "-.")
  282. barename = strings.Trim(barename, "-")
  283. return
  284. }
  285. func parseExpiry(expStr string) time.Duration {
  286. if expStr == "" {
  287. return time.Duration(Config.maxExpiry) * time.Second
  288. } else {
  289. expiry, err := strconv.ParseUint(expStr, 10, 64)
  290. if err != nil {
  291. return time.Duration(Config.maxExpiry) * time.Second
  292. } else {
  293. if Config.maxExpiry > 0 && (expiry > Config.maxExpiry || expiry == 0) {
  294. expiry = Config.maxExpiry
  295. }
  296. return time.Duration(expiry) * time.Second
  297. }
  298. }
  299. }