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.
 
 
 

611 lines
15 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014 DutchCoders [https://github.com/dutchcoders/]
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. package main
  21. import (
  22. // _ "transfer.sh/app/handlers"
  23. // _ "transfer.sh/app/utils"
  24. "archive/tar"
  25. "archive/zip"
  26. "bytes"
  27. "compress/gzip"
  28. "errors"
  29. "fmt"
  30. html_template "html/template"
  31. "io"
  32. "io/ioutil"
  33. "log"
  34. "math/rand"
  35. "mime"
  36. "net/http"
  37. "os"
  38. "path/filepath"
  39. "strconv"
  40. "strings"
  41. text_template "text/template"
  42. "time"
  43. clamd "github.com/dutchcoders/go-clamd"
  44. "github.com/gorilla/mux"
  45. "github.com/kennygrant/sanitize"
  46. "github.com/russross/blackfriday"
  47. )
  48. func healthHandler(w http.ResponseWriter, r *http.Request) {
  49. fmt.Fprintf(w, "Approaching Neutral Zone, all systems normal and functioning.")
  50. }
  51. /* The preview handler will show a preview of the content for browsers (accept type text/html), and referer is not transfer.sh */
  52. func previewHandler(w http.ResponseWriter, r *http.Request) {
  53. vars := mux.Vars(r)
  54. token := vars["token"]
  55. filename := vars["filename"]
  56. contentType, contentLength, err := storage.Head(token, filename)
  57. if err != nil {
  58. http.Error(w, http.StatusText(404), 404)
  59. return
  60. }
  61. var templatePath string
  62. var content html_template.HTML
  63. switch {
  64. case strings.HasPrefix(contentType, "image/"):
  65. templatePath = "download.image.html"
  66. case strings.HasPrefix(contentType, "video/"):
  67. templatePath = "download.video.html"
  68. case strings.HasPrefix(contentType, "audio/"):
  69. templatePath = "download.audio.html"
  70. case strings.HasPrefix(contentType, "text/"):
  71. templatePath = "download.markdown.html"
  72. var reader io.ReadCloser
  73. if reader, _, _, err = storage.Get(token, filename); err != nil {
  74. http.Error(w, err.Error(), http.StatusInternalServerError)
  75. return
  76. }
  77. var data []byte
  78. if data, err = ioutil.ReadAll(reader); err != nil {
  79. http.Error(w, err.Error(), http.StatusInternalServerError)
  80. return
  81. }
  82. if strings.HasPrefix(contentType, "text/x-markdown") || strings.HasPrefix(contentType, "text/markdown") {
  83. output := blackfriday.MarkdownCommon(data)
  84. content = html_template.HTML(output)
  85. } else if strings.HasPrefix(contentType, "text/plain") {
  86. content = html_template.HTML(fmt.Sprintf("<pre>%s</pre>", data))
  87. } else {
  88. templatePath = "download.sandbox.html"
  89. }
  90. default:
  91. templatePath = "download.html"
  92. }
  93. tmpl, err := html_template.New(templatePath).Funcs(html_template.FuncMap{"format": formatNumber}).ParseFiles("static/" + templatePath)
  94. if err != nil {
  95. http.Error(w, err.Error(), http.StatusInternalServerError)
  96. return
  97. }
  98. data := struct {
  99. ContentType string
  100. Content html_template.HTML
  101. Filename string
  102. Url string
  103. ContentLength uint64
  104. }{
  105. contentType,
  106. content,
  107. filename,
  108. r.URL.String(),
  109. contentLength,
  110. }
  111. if err := tmpl.ExecuteTemplate(w, templatePath, data); err != nil {
  112. http.Error(w, err.Error(), http.StatusInternalServerError)
  113. return
  114. }
  115. }
  116. // this handler will output html or text, depending on the
  117. // support of the client (Accept header).
  118. func viewHandler(w http.ResponseWriter, r *http.Request) {
  119. // vars := mux.Vars(r)
  120. if acceptsHtml(r.Header) {
  121. tmpl, err := html_template.ParseFiles("static/index.html")
  122. if err != nil {
  123. http.Error(w, err.Error(), http.StatusInternalServerError)
  124. return
  125. }
  126. if err := tmpl.Execute(w, nil); err != nil {
  127. http.Error(w, err.Error(), http.StatusInternalServerError)
  128. return
  129. }
  130. } else {
  131. tmpl, err := text_template.ParseFiles("static/index.txt")
  132. if err != nil {
  133. http.Error(w, err.Error(), http.StatusInternalServerError)
  134. return
  135. }
  136. if err := tmpl.Execute(w, nil); err != nil {
  137. http.Error(w, err.Error(), http.StatusInternalServerError)
  138. return
  139. }
  140. }
  141. }
  142. func notFoundHandler(w http.ResponseWriter, r *http.Request) {
  143. http.Error(w, http.StatusText(404), 404)
  144. }
  145. func postHandler(w http.ResponseWriter, r *http.Request) {
  146. if err := r.ParseMultipartForm(_24K); nil != err {
  147. log.Printf("%s", err.Error())
  148. http.Error(w, "Error occured copying to output stream", 500)
  149. return
  150. }
  151. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  152. w.Header().Set("Content-Type", "text/plain")
  153. for _, fheaders := range r.MultipartForm.File {
  154. for _, fheader := range fheaders {
  155. filename := sanitize.Path(filepath.Base(fheader.Filename))
  156. contentType := fheader.Header.Get("Content-Type")
  157. if contentType == "" {
  158. contentType = mime.TypeByExtension(filepath.Ext(fheader.Filename))
  159. }
  160. var f io.Reader
  161. var err error
  162. if f, err = fheader.Open(); err != nil {
  163. log.Printf("%s", err.Error())
  164. http.Error(w, err.Error(), 500)
  165. return
  166. }
  167. var b bytes.Buffer
  168. n, err := io.CopyN(&b, f, _24K+1)
  169. if err != nil && err != io.EOF {
  170. log.Printf("%s", err.Error())
  171. http.Error(w, err.Error(), 500)
  172. return
  173. }
  174. var reader io.Reader
  175. if n > _24K {
  176. file, err := ioutil.TempFile(config.Temp, "transfer-")
  177. if err != nil {
  178. log.Fatal(err)
  179. }
  180. defer file.Close()
  181. n, err = io.Copy(file, io.MultiReader(&b, f))
  182. if err != nil {
  183. os.Remove(file.Name())
  184. log.Printf("%s", err.Error())
  185. http.Error(w, err.Error(), 500)
  186. return
  187. }
  188. reader, err = os.Open(file.Name())
  189. } else {
  190. reader = bytes.NewReader(b.Bytes())
  191. }
  192. contentLength := n
  193. log.Printf("Uploading %s %s %d %s", token, filename, contentLength, contentType)
  194. if err = storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  195. log.Printf("%s", err.Error())
  196. http.Error(w, err.Error(), 500)
  197. return
  198. }
  199. fmt.Fprintf(w, "https://%s/%s/%s\n", ipAddrFromRemoteAddr(r.Host), token, filename)
  200. }
  201. }
  202. }
  203. func scanHandler(w http.ResponseWriter, r *http.Request) {
  204. vars := mux.Vars(r)
  205. filename := sanitize.Path(filepath.Base(vars["filename"]))
  206. contentLength := r.ContentLength
  207. contentType := r.Header.Get("Content-Type")
  208. log.Printf("Scanning %s %d %s", filename, contentLength, contentType)
  209. var reader io.Reader
  210. reader = r.Body
  211. c := clamd.NewClamd(config.CLAMAV_DAEMON_HOST)
  212. response, err := c.ScanStream(reader)
  213. if err != nil {
  214. log.Printf("%s", err.Error())
  215. http.Error(w, err.Error(), 500)
  216. return
  217. }
  218. var b string
  219. for s := range response {
  220. b += s
  221. if !strings.HasPrefix(s, "stream: ") {
  222. continue
  223. }
  224. w.Write([]byte(fmt.Sprintf("%v\n", s[8:])))
  225. }
  226. }
  227. func putHandler(w http.ResponseWriter, r *http.Request) {
  228. vars := mux.Vars(r)
  229. filename := sanitize.Path(filepath.Base(vars["filename"]))
  230. contentLength := r.ContentLength
  231. var reader io.Reader
  232. reader = r.Body
  233. if contentLength == -1 {
  234. // queue file to disk, because s3 needs content length
  235. var err error
  236. var f io.Reader
  237. f = reader
  238. var b bytes.Buffer
  239. n, err := io.CopyN(&b, f, _24K+1)
  240. if err != nil && err != io.EOF {
  241. log.Printf("%s", err.Error())
  242. http.Error(w, err.Error(), 500)
  243. return
  244. }
  245. if n > _24K {
  246. file, err := ioutil.TempFile(config.Temp, "transfer-")
  247. if err != nil {
  248. log.Printf("%s", err.Error())
  249. http.Error(w, err.Error(), 500)
  250. return
  251. }
  252. defer file.Close()
  253. n, err = io.Copy(file, io.MultiReader(&b, f))
  254. if err != nil {
  255. os.Remove(file.Name())
  256. log.Printf("%s", err.Error())
  257. http.Error(w, err.Error(), 500)
  258. return
  259. }
  260. reader, err = os.Open(file.Name())
  261. } else {
  262. reader = bytes.NewReader(b.Bytes())
  263. }
  264. contentLength = n
  265. }
  266. contentType := r.Header.Get("Content-Type")
  267. if contentType == "" {
  268. contentType = mime.TypeByExtension(filepath.Ext(vars["filename"]))
  269. }
  270. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  271. log.Printf("Uploading %s %d %s", token, filename, contentLength, contentType)
  272. var err error
  273. if err = storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  274. log.Printf("%s", err.Error())
  275. http.Error(w, errors.New("Could not save file").Error(), 500)
  276. return
  277. }
  278. // w.Statuscode = 200
  279. w.Header().Set("Content-Type", "text/plain")
  280. fmt.Fprintf(w, "https://%s/%s/%s\n", ipAddrFromRemoteAddr(r.Host), token, filename)
  281. }
  282. func zipHandler(w http.ResponseWriter, r *http.Request) {
  283. vars := mux.Vars(r)
  284. files := vars["files"]
  285. zipfilename := fmt.Sprintf("transfersh-%d.zip", uint16(time.Now().UnixNano()))
  286. w.Header().Set("Content-Type", "application/zip")
  287. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", zipfilename))
  288. w.Header().Set("Connection", "close")
  289. zw := zip.NewWriter(w)
  290. for _, key := range strings.Split(files, ",") {
  291. if strings.HasPrefix(key, "/") {
  292. key = key[1:]
  293. }
  294. key = strings.Replace(key, "\\", "/", -1)
  295. token := strings.Split(key, "/")[0]
  296. filename := sanitize.Path(strings.Split(key, "/")[1])
  297. reader, _, _, err := storage.Get(token, filename)
  298. if err != nil {
  299. if storage.IsNotExist(err) {
  300. http.Error(w, "File not found", 404)
  301. return
  302. } else {
  303. log.Printf("%s", err.Error())
  304. http.Error(w, "Could not retrieve file.", 500)
  305. return
  306. }
  307. }
  308. defer reader.Close()
  309. header := &zip.FileHeader{
  310. Name: strings.Split(key, "/")[1],
  311. Method: zip.Store,
  312. ModifiedTime: uint16(time.Now().UnixNano()),
  313. ModifiedDate: uint16(time.Now().UnixNano()),
  314. }
  315. fw, err := zw.CreateHeader(header)
  316. if err != nil {
  317. log.Printf("%s", err.Error())
  318. http.Error(w, "Internal server error.", 500)
  319. return
  320. }
  321. if _, err = io.Copy(fw, reader); err != nil {
  322. log.Printf("%s", err.Error())
  323. http.Error(w, "Internal server error.", 500)
  324. return
  325. }
  326. }
  327. if err := zw.Close(); err != nil {
  328. log.Printf("%s", err.Error())
  329. http.Error(w, "Internal server error.", 500)
  330. return
  331. }
  332. }
  333. func tarGzHandler(w http.ResponseWriter, r *http.Request) {
  334. vars := mux.Vars(r)
  335. files := vars["files"]
  336. tarfilename := fmt.Sprintf("transfersh-%d.tar.gz", uint16(time.Now().UnixNano()))
  337. w.Header().Set("Content-Type", "application/x-gzip")
  338. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  339. w.Header().Set("Connection", "close")
  340. os := gzip.NewWriter(w)
  341. defer os.Close()
  342. zw := tar.NewWriter(os)
  343. defer zw.Close()
  344. for _, key := range strings.Split(files, ",") {
  345. if strings.HasPrefix(key, "/") {
  346. key = key[1:]
  347. }
  348. key = strings.Replace(key, "\\", "/", -1)
  349. token := strings.Split(key, "/")[0]
  350. filename := sanitize.Path(strings.Split(key, "/")[1])
  351. reader, _, contentLength, err := storage.Get(token, filename)
  352. if err != nil {
  353. if storage.IsNotExist(err) {
  354. http.Error(w, "File not found", 404)
  355. return
  356. } else {
  357. log.Printf("%s", err.Error())
  358. http.Error(w, "Could not retrieve file.", 500)
  359. return
  360. }
  361. }
  362. defer reader.Close()
  363. header := &tar.Header{
  364. Name: strings.Split(key, "/")[1],
  365. Size: int64(contentLength),
  366. }
  367. err = zw.WriteHeader(header)
  368. if err != nil {
  369. log.Printf("%s", err.Error())
  370. http.Error(w, "Internal server error.", 500)
  371. return
  372. }
  373. if _, err = io.Copy(zw, reader); err != nil {
  374. log.Printf("%s", err.Error())
  375. http.Error(w, "Internal server error.", 500)
  376. return
  377. }
  378. }
  379. }
  380. func tarHandler(w http.ResponseWriter, r *http.Request) {
  381. vars := mux.Vars(r)
  382. files := vars["files"]
  383. tarfilename := fmt.Sprintf("transfersh-%d.tar", uint16(time.Now().UnixNano()))
  384. w.Header().Set("Content-Type", "application/x-tar")
  385. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  386. w.Header().Set("Connection", "close")
  387. zw := tar.NewWriter(w)
  388. defer zw.Close()
  389. for _, key := range strings.Split(files, ",") {
  390. token := strings.Split(key, "/")[0]
  391. filename := strings.Split(key, "/")[1]
  392. reader, _, contentLength, err := storage.Get(token, filename)
  393. if err != nil {
  394. if storage.IsNotExist(err) {
  395. http.Error(w, "File not found", 404)
  396. return
  397. } else {
  398. log.Printf("%s", err.Error())
  399. http.Error(w, "Could not retrieve file.", 500)
  400. return
  401. }
  402. }
  403. defer reader.Close()
  404. header := &tar.Header{
  405. Name: strings.Split(key, "/")[1],
  406. Size: int64(contentLength),
  407. }
  408. err = zw.WriteHeader(header)
  409. if err != nil {
  410. log.Printf("%s", err.Error())
  411. http.Error(w, "Internal server error.", 500)
  412. return
  413. }
  414. if _, err = io.Copy(zw, reader); err != nil {
  415. log.Printf("%s", err.Error())
  416. http.Error(w, "Internal server error.", 500)
  417. return
  418. }
  419. }
  420. }
  421. func getHandler(w http.ResponseWriter, r *http.Request) {
  422. vars := mux.Vars(r)
  423. token := vars["token"]
  424. filename := vars["filename"]
  425. reader, contentType, contentLength, err := storage.Get(token, filename)
  426. if err != nil {
  427. if storage.IsNotExist(err) {
  428. http.Error(w, "File not found", 404)
  429. return
  430. } else {
  431. log.Printf("%s", err.Error())
  432. http.Error(w, "Could not retrieve file.", 500)
  433. return
  434. }
  435. }
  436. defer reader.Close()
  437. w.Header().Set("Content-Type", contentType)
  438. w.Header().Set("Content-Length", strconv.FormatUint(contentLength, 10))
  439. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  440. w.Header().Set("Connection", "close")
  441. if _, err = io.Copy(w, reader); err != nil {
  442. log.Printf("%s", err.Error())
  443. http.Error(w, "Error occured copying to output stream", 500)
  444. return
  445. }
  446. }
  447. func RedirectHandler(h http.Handler) http.HandlerFunc {
  448. return func(w http.ResponseWriter, r *http.Request) {
  449. if r.URL.Path == "/health.html" {
  450. } else if ipAddrFromRemoteAddr(r.Host) == "127.0.0.1" {
  451. } else if strings.HasSuffix(ipAddrFromRemoteAddr(r.Host), ".elasticbeanstalk.com") {
  452. } else if ipAddrFromRemoteAddr(r.Host) == "jxm5d6emw5rknovg.onion" {
  453. } else if ipAddrFromRemoteAddr(r.Host) == "transfer.sh" {
  454. if r.Header.Get("X-Forwarded-Proto") != "https" && r.Method == "GET" {
  455. http.Redirect(w, r, "https://transfer.sh"+r.RequestURI, 301)
  456. return
  457. }
  458. } else if ipAddrFromRemoteAddr(r.Host) != "transfer.sh" {
  459. http.Redirect(w, r, "https://transfer.sh"+r.RequestURI, 301)
  460. return
  461. }
  462. h.ServeHTTP(w, r)
  463. }
  464. }
  465. // Create a log handler for every request it receives.
  466. func LoveHandler(h http.Handler) http.HandlerFunc {
  467. return func(w http.ResponseWriter, r *http.Request) {
  468. w.Header().Set("x-made-with", "<3 by DutchCoders")
  469. w.Header().Set("x-served-by", "Proudly served by DutchCoders")
  470. w.Header().Set("Server", "Transfer.sh HTTP Server 1.0")
  471. h.ServeHTTP(w, r)
  472. }
  473. }