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.

354 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 = http.MaxBytesReader(w, file, Config.maxSize)
  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. content := r.FormValue("content")
  75. if int64(len(content)) > Config.maxSize {
  76. oopsHandler(c, w, r, RespJSON, "Content length exceeds max size")
  77. return
  78. }
  79. upReq.src = strings.NewReader(content)
  80. upReq.expiry = parseExpiry(r.FormValue("expires"))
  81. upReq.filename = r.FormValue("filename") + "." + extension
  82. }
  83. upload, err := processUpload(upReq)
  84. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  85. if err != nil {
  86. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  87. return
  88. }
  89. js := generateJSONresponse(upload, r)
  90. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  91. w.Write(js)
  92. } else {
  93. if err != nil {
  94. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  95. return
  96. }
  97. http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
  98. }
  99. }
  100. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  101. upReq := UploadRequest{}
  102. uploadHeaderProcess(r, &upReq)
  103. defer r.Body.Close()
  104. upReq.filename = c.URLParams["name"]
  105. upReq.src = http.MaxBytesReader(w, r.Body, Config.maxSize)
  106. upload, err := processUpload(upReq)
  107. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  108. if err != nil {
  109. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  110. return
  111. }
  112. js := generateJSONresponse(upload, r)
  113. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  114. w.Write(js)
  115. } else {
  116. if err != nil {
  117. oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
  118. return
  119. }
  120. fmt.Fprintf(w, "%s\n", getSiteURL(r)+upload.Filename)
  121. }
  122. }
  123. func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
  124. if Config.remoteAuthFile != "" {
  125. result, err := checkAuth(remoteAuthKeys, r.FormValue("key"))
  126. if err != nil || !result {
  127. unauthorizedHandler(c, w, r)
  128. return
  129. }
  130. }
  131. if r.FormValue("url") == "" {
  132. http.Redirect(w, r, Config.sitePath, 303)
  133. return
  134. }
  135. upReq := UploadRequest{}
  136. grabUrl, _ := url.Parse(r.FormValue("url"))
  137. resp, err := http.Get(grabUrl.String())
  138. if err != nil {
  139. oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
  140. return
  141. }
  142. upReq.filename = filepath.Base(grabUrl.Path)
  143. upReq.src = http.MaxBytesReader(w, resp.Body, Config.maxSize)
  144. upReq.deletionKey = r.FormValue("deletekey")
  145. upReq.randomBarename = r.FormValue("randomize") == "yes"
  146. upReq.expiry = parseExpiry(r.FormValue("expiry"))
  147. upload, err := processUpload(upReq)
  148. if strings.EqualFold("application/json", r.Header.Get("Accept")) {
  149. if err != nil {
  150. oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
  151. return
  152. }
  153. js := generateJSONresponse(upload, r)
  154. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  155. w.Write(js)
  156. } else {
  157. if err != nil {
  158. oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
  159. return
  160. }
  161. http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
  162. }
  163. }
  164. func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
  165. if r.Header.Get("Linx-Randomize") == "yes" {
  166. upReq.randomBarename = true
  167. }
  168. upReq.deletionKey = r.Header.Get("Linx-Delete-Key")
  169. // Get seconds until expiry. Non-integer responses never expire.
  170. expStr := r.Header.Get("Linx-Expiry")
  171. upReq.expiry = parseExpiry(expStr)
  172. }
  173. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  174. // Determine the appropriate filename, then write to disk
  175. barename, extension := barePlusExt(upReq.filename)
  176. if upReq.randomBarename || len(barename) == 0 {
  177. barename = generateBarename()
  178. }
  179. var header []byte
  180. if len(extension) == 0 {
  181. // Pull the first 512 bytes off for use in MIME detection
  182. header = make([]byte, 512)
  183. n, _ := upReq.src.Read(header)
  184. if n == 0 {
  185. return upload, errors.New("Empty file")
  186. }
  187. header = header[:n]
  188. // Determine the type of file from header
  189. kind, err := filetype.Match(header)
  190. if err != nil || kind.Extension == "unknown" {
  191. extension = "file"
  192. } else {
  193. extension = kind.Extension
  194. }
  195. }
  196. upload.Filename = strings.Join([]string{barename, extension}, ".")
  197. upload.Filename = strings.Replace(upload.Filename, " ", "", -1)
  198. fileexists, _ := storageBackend.Exists(upload.Filename)
  199. // Check if the delete key matches, in which case overwrite
  200. if fileexists {
  201. metad, merr := storageBackend.Head(upload.Filename)
  202. if merr == nil {
  203. if upReq.deletionKey == metad.DeleteKey {
  204. fileexists = false
  205. }
  206. }
  207. }
  208. for fileexists {
  209. counter, err := strconv.Atoi(string(barename[len(barename)-1]))
  210. if err != nil {
  211. barename = barename + "1"
  212. } else {
  213. barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
  214. }
  215. upload.Filename = strings.Join([]string{barename, extension}, ".")
  216. fileexists, err = storageBackend.Exists(upload.Filename)
  217. }
  218. if fileBlacklist[strings.ToLower(upload.Filename)] {
  219. return upload, errors.New("Prohibited filename")
  220. }
  221. // Get the rest of the metadata needed for storage
  222. var fileExpiry time.Time
  223. if upReq.expiry == 0 {
  224. fileExpiry = expiry.NeverExpire
  225. } else {
  226. fileExpiry = time.Now().Add(upReq.expiry)
  227. }
  228. if upReq.deletionKey == "" {
  229. upReq.deletionKey = uniuri.NewLen(30)
  230. }
  231. upload.Metadata, err = storageBackend.Put(upload.Filename, io.MultiReader(bytes.NewReader(header), upReq.src), fileExpiry, upReq.deletionKey)
  232. if err != nil {
  233. return upload, err
  234. }
  235. return
  236. }
  237. func generateBarename() string {
  238. return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
  239. }
  240. func generateJSONresponse(upload Upload, r *http.Request) []byte {
  241. js, _ := json.Marshal(map[string]string{
  242. "url": getSiteURL(r) + upload.Filename,
  243. "filename": upload.Filename,
  244. "delete_key": upload.Metadata.DeleteKey,
  245. "expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
  246. "size": strconv.FormatInt(upload.Metadata.Size, 10),
  247. "mimetype": upload.Metadata.Mimetype,
  248. "sha256sum": upload.Metadata.Sha256sum,
  249. })
  250. return js
  251. }
  252. var bareRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
  253. var extRe = regexp.MustCompile(`[^A-Za-z0-9\-\.]`)
  254. var compressedExts = map[string]bool{
  255. ".bz2": true,
  256. ".gz": true,
  257. ".xz": true,
  258. }
  259. var archiveExts = map[string]bool{
  260. ".tar": true,
  261. }
  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. if compressedExts[extension] {
  268. ext2 := path.Ext(barename)
  269. if archiveExts[ext2] {
  270. barename = barename[:len(barename)-len(ext2)]
  271. extension = ext2 + extension
  272. }
  273. }
  274. extension = extRe.ReplaceAllString(extension, "")
  275. barename = bareRe.ReplaceAllString(barename, "")
  276. extension = strings.Trim(extension, "-.")
  277. barename = strings.Trim(barename, "-")
  278. return
  279. }
  280. func parseExpiry(expStr string) time.Duration {
  281. if expStr == "" {
  282. return time.Duration(Config.maxExpiry) * time.Second
  283. } else {
  284. fileExpiry, err := strconv.ParseUint(expStr, 10, 64)
  285. if err != nil {
  286. return time.Duration(Config.maxExpiry) * time.Second
  287. } else {
  288. if Config.maxExpiry > 0 && (fileExpiry > Config.maxExpiry || fileExpiry == 0) {
  289. fileExpiry = Config.maxExpiry
  290. }
  291. return time.Duration(fileExpiry) * time.Second
  292. }
  293. }
  294. }