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.

286 lines
6.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
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. "bitbucket.org/taruti/mimemagic"
  17. "github.com/dchest/uniuri"
  18. "github.com/zenazn/goji/web"
  19. )
  20. // Describes metadata directly from the user request
  21. type UploadRequest struct {
  22. src io.Reader
  23. filename string
  24. expiry int64 // Seconds until expiry, 0 = never
  25. randomBarename bool
  26. deletionKey string // Empty string if not defined
  27. }
  28. // Metadata associated with a file as it would actually be stored
  29. type Upload struct {
  30. Filename string // Final filename on disk
  31. Size int64
  32. Expiry int64 // Unix timestamp of expiry, 0=never
  33. DeleteKey string // Deletion key, one generated if not provided
  34. }
  35. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  36. upReq := UploadRequest{}
  37. uploadHeaderProcess(r, &upReq)
  38. contentType := r.Header.Get("Content-Type")
  39. if strings.HasPrefix(contentType, "multipart/form-data") {
  40. file, headers, err := r.FormFile("file")
  41. if err != nil {
  42. oopsHandler(c, w, r)
  43. return
  44. }
  45. defer file.Close()
  46. r.ParseForm()
  47. if r.Form.Get("randomize") == "true" {
  48. upReq.randomBarename = true
  49. }
  50. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  51. upReq.src = file
  52. upReq.filename = headers.Filename
  53. } else {
  54. if r.FormValue("content") == "" {
  55. oopsHandler(c, w, r)
  56. return
  57. }
  58. extension := r.FormValue("extension")
  59. if extension == "" {
  60. extension = "txt"
  61. }
  62. upReq.src = strings.NewReader(r.FormValue("content"))
  63. upReq.expiry = parseExpiry(r.FormValue("expires"))
  64. upReq.filename = r.FormValue("filename") + "." + extension
  65. }
  66. upload, err := processUpload(upReq)
  67. if err != nil {
  68. oopsHandler(c, w, r)
  69. return
  70. }
  71. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  72. js := generateJSONresponse(upload)
  73. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  74. w.Write(js)
  75. } else {
  76. http.Redirect(w, r, "/"+upload.Filename, 301)
  77. }
  78. }
  79. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  80. upReq := UploadRequest{}
  81. uploadHeaderProcess(r, &upReq)
  82. defer r.Body.Close()
  83. upReq.filename = c.URLParams["name"]
  84. upReq.src = r.Body
  85. upload, err := processUpload(upReq)
  86. if err != nil {
  87. oopsHandler(c, w, r)
  88. return
  89. }
  90. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  91. js := generateJSONresponse(upload)
  92. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  93. w.Write(js)
  94. } else {
  95. fmt.Fprintf(w, Config.siteURL+upload.Filename)
  96. }
  97. }
  98. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  99. if r.FormValue("url") == "" {
  100. http.Redirect(w, r, "/", 301)
  101. return
  102. }
  103. upReq := UploadRequest{}
  104. grabUrl, _ := url.Parse(r.FormValue("url"))
  105. resp, err := http.Get(grabUrl.String())
  106. if err != nil {
  107. oopsHandler(c, w, r)
  108. return
  109. }
  110. upReq.filename = filepath.Base(grabUrl.Path)
  111. upReq.src = resp.Body
  112. upload, err := processUpload(upReq)
  113. if err != nil {
  114. oopsHandler(c, w, r)
  115. return
  116. }
  117. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  118. js := generateJSONresponse(upload)
  119. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  120. w.Write(js)
  121. } else {
  122. http.Redirect(w, r, "/"+upload.Filename, 301)
  123. }
  124. }
  125. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  126. // For legacy reasons
  127. if r.Header.Get("X-Randomized-Filename") == "yes" {
  128. upReq.randomBarename = true
  129. } else if r.Header.Get("X-Randomized-Barename") == "yes" {
  130. upReq.randomBarename = true
  131. }
  132. upReq.deletionKey = r.Header.Get("X-Delete-Key")
  133. // Get seconds until expiry. Non-integer responses never expire.
  134. expStr := r.Header.Get("X-File-Expiry")
  135. upReq.expiry = parseExpiry(expStr)
  136. }
  137. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  138. // Determine the appropriate filename, then write to disk
  139. barename, extension := barePlusExt(upReq.filename)
  140. if upReq.randomBarename || len(barename) == 0 {
  141. barename = generateBarename()
  142. }
  143. var header []byte
  144. if len(extension) == 0 {
  145. // Pull the first 512 bytes off for use in MIME detection
  146. header = make([]byte, 512)
  147. n, err := upReq.src.Read(header)
  148. if n == 0 {
  149. return upload, err
  150. }
  151. header = header[:n]
  152. // Determine the type of file from header
  153. mimetype := mimemagic.Match("", header)
  154. // If the mime type is in our map, use that
  155. // otherwise just use "ext"
  156. if val, exists := mimeToExtension[mimetype]; exists {
  157. extension = val
  158. } else {
  159. extension = "ext"
  160. }
  161. }
  162. upload.Filename = strings.Join([]string{barename, extension}, ".")
  163. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  164. fileexists := err == nil
  165. for fileexists {
  166. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  167. if err != nil {
  168. barename = barename + "1"
  169. } else {
  170. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  171. }
  172. upload.Filename = strings.Join([]string{barename, extension}, ".")
  173. _, err = os.Stat(path.Join(Config.filesDir, upload.Filename))
  174. fileexists = err == nil
  175. }
  176. dst, err := os.Create(path.Join(Config.filesDir, upload.Filename))
  177. if err != nil {
  178. return
  179. }
  180. defer dst.Close()
  181. // Get the rest of the metadata needed for storage
  182. upload.Expiry = getFutureTimestamp(upReq.expiry)
  183. // If no delete key specified, pick a random one.
  184. if upReq.deletionKey == "" {
  185. upload.DeleteKey = uniuri.NewLen(30)
  186. } else {
  187. upload.DeleteKey = upReq.deletionKey
  188. }
  189. metadataWrite(upload.Filename, &upload)
  190. bytes, err := io.Copy(dst, io.MultiReader(bytes.NewReader(header), upReq.src))
  191. if err != nil {
  192. return
  193. } else if bytes == 0 {
  194. os.Remove(path.Join(Config.filesDir, upload.Filename))
  195. os.Remove(path.Join(Config.metaDir, upload.Filename))
  196. return upload, errors.New("Empty file")
  197. }
  198. upload.Size = bytes
  199. return
  200. }
  201. func generateBarename() string {
  202. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  203. }
  204. func generateJSONresponse(upload Upload) []byte {
  205. js, _ := json.Marshal(map[string]string{
  206. "url": Config.siteURL + upload.Filename,
  207. "filename": upload.Filename,
  208. "delete_key": upload.DeleteKey,
  209. "expiry": strconv.FormatInt(int64(upload.Expiry), 10),
  210. "size": strconv.FormatInt(upload.Size, 10),
  211. })
  212. return js
  213. }
  214. var barePlusRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  215. func barePlusExt(filename string) (barename, extension string) {
  216. filename = strings.TrimSpace(filename)
  217. filename = strings.ToLower(filename)
  218. extension = path.Ext(filename)
  219. barename = filename[:len(filename)-len(extension)]
  220. extension = barePlusRe.ReplaceAllString(extension, "")
  221. barename = barePlusRe.ReplaceAllString(barename, "")
  222. return
  223. }
  224. func parseExpiry(expStr string) int64 {
  225. if expStr == "" {
  226. return 0
  227. } else {
  228. expiry, err := strconv.ParseInt(expStr, 10, 64)
  229. if err != nil {
  230. return 0
  231. } else {
  232. return int64(expiry)
  233. }
  234. }
  235. }