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.
 
 
 

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