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.

357 lines
9.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. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/andreimarcu/linx-server/backends"
  17. "github.com/andreimarcu/linx-server/expiry"
  18. "github.com/dchest/uniuri"
  19. "github.com/zenazn/goji/web"
  20. "gopkg.in/h2non/filetype.v1"
  21. )
  22. var fileBlacklist = map[string]bool{
  23. "favicon.ico": true,
  24. "index.htm": true,
  25. "index.html": true,
  26. "index.php": true,
  27. "robots.txt": true,
  28. "crossdomain.xml": true,
  29. }
  30. // Describes metadata directly from the user request
  31. type UploadRequest struct {
  32. src io.Reader
  33. filename string
  34. expiry time.Duration // Seconds until expiry, 0 = never
  35. randomBarename bool
  36. deletionKey string // Empty string if not defined
  37. }
  38. // Metadata associated with a file as it would actually be stored
  39. type Upload struct {
  40. Filename string // Final filename on disk
  41. Metadata backends.Metadata
  42. }
  43. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  44. if !strictReferrerCheck(r, getSiteURL(r), []string{"Linx-Delete-Key", "Linx-Expiry", "Linx-Randomize", "X-Requested-With"}) {
  45. badRequestHandler(c, w, r)
  46. return
  47. }
  48. upReq := UploadRequest{}
  49. uploadHeaderProcess(r, &upReq)
  50. contentType := r.Header.Get("Content-Type")
  51. if strings.HasPrefix(contentType, "multipart/form-data") {
  52. file, headers, err := r.FormFile("file")
  53. if err != nil {
  54. oopsHandler(c, w, r, RespHTML, "Could not upload file.")
  55. return
  56. }
  57. defer file.Close()
  58. r.ParseForm()
  59. if r.Form.Get("randomize") == "true" {
  60. upReq.randomBarename = true
  61. }
  62. upReq.expiry = parseExpiry(r.Form.Get("expires"))
  63. upReq.src = file
  64. upReq.filename = headers.Filename
  65. } else {
  66. if r.FormValue("content") == "" {
  67. oopsHandler(c, w, r, RespHTML, "Empty file")
  68. return
  69. }
  70. extension := r.FormValue("extension")
  71. if extension == "" {
  72. extension = "txt"
  73. }
  74. upReq.src = strings.NewReader(r.FormValue("content"))
  75. upReq.expiry = parseExpiry(r.FormValue("expires"))
  76. upReq.filename = r.FormValue("filename") + "." + extension
  77. }
  78. upload, err := processUpload(upReq)
  79. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  80. if err != nil {
  81. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  82. return
  83. }
  84. js := generateJSONresponse(upload, r)
  85. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  86. w.Write(js)
  87. } else {
  88. if err != nil {
  89. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  90. return
  91. }
  92. http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
  93. }
  94. }
  95. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  96. upReq := UploadRequest{}
  97. uploadHeaderProcess(r, &upReq)
  98. defer r.Body.Close()
  99. upReq.filename = c.URLParams["name"]
  100. upReq.src = r.Body
  101. upload, err := processUpload(upReq)
  102. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  103. if err != nil {
  104. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  105. return
  106. }
  107. js := generateJSONresponse(upload, r)
  108. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  109. w.Write(js)
  110. } else {
  111. if err != nil {
  112. oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
  113. return
  114. }
  115. fmt.Fprintf(w, "%s\n", getSiteURL(r)+upload.Filename)
  116. }
  117. }
  118. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  119. if Config.remoteAuthFile != "" {
  120. result, err := checkAuth(remoteAuthKeys, r.FormValue("key"))
  121. if err != nil || !result {
  122. unauthorizedHandler(c, w, r)
  123. return
  124. }
  125. }
  126. if r.FormValue("url") == "" {
  127. http.Redirect(w, r, Config.sitePath, 303)
  128. return
  129. }
  130. upReq := UploadRequest{}
  131. grabUrl, _ := url.Parse(r.FormValue("url"))
  132. resp, err := http.Get(grabUrl.String())
  133. if err != nil {
  134. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  135. return
  136. }
  137. upReq.filename = filepath.Base(grabUrl.Path)
  138. upReq.src = resp.Body
  139. upReq.deletionKey = r.FormValue("deletekey")
  140. upReq.randomBarename = r.FormValue("randomize") == "yes"
  141. upReq.expiry = parseExpiry(r.FormValue("expiry"))
  142. upload, err := processUpload(upReq)
  143. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  144. if err != nil {
  145. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  146. return
  147. }
  148. js := generateJSONresponse(upload, r)
  149. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  150. w.Write(js)
  151. } else {
  152. if err != nil {
  153. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  154. return
  155. }
  156. http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
  157. }
  158. }
  159. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  160. if r.Header.Get("Linx-Randomize") == "yes" {
  161. upReq.randomBarename = true
  162. }
  163. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  164. // Get seconds until expiry. Non-integer responses never expire.
  165. expStr := r.Header.Get("Linx-Expiry")
  166. upReq.expiry = parseExpiry(expStr)
  167. }
  168. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  169. // Determine the appropriate filename, then write to disk
  170. barename, extension := barePlusExt(upReq.filename)
  171. if upReq.randomBarename || len(barename) == 0 {
  172. barename = generateBarename()
  173. }
  174. var header []byte
  175. if len(extension) == 0 {
  176. // Pull the first 512 bytes off for use in MIME detection
  177. header = make([]byte, 512)
  178. n, _ := upReq.src.Read(header)
  179. if n == 0 {
  180. return upload, errors.New("Empty file")
  181. }
  182. header = header[:n]
  183. // Determine the type of file from header
  184. kind, err := filetype.Match(header)
  185. if err != nil || kind.Extension == "unknown" {
  186. extension = "file"
  187. } else {
  188. extension = kind.Extension
  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 fileExpiry time.Time
  218. if upReq.expiry == 0 {
  219. fileExpiry = expiry.NeverExpire
  220. } else {
  221. fileExpiry = 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, fileExpiry, 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. fileExpiry, 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 && (fileExpiry > Config.maxExpiry || fileExpiry == 0) {
  294. fileExpiry = Config.maxExpiry
  295. }
  296. return time.Duration(fileExpiry) * time.Second
  297. }
  298. }
  299. }