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.
 
 
 

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