Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

611 righe
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.Printf("%s", err.Error())
  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.Printf("%s", err.Error())
  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.Printf("%s", err.Error())
  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.Printf("%s", err.Error())
  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.Printf("%s", err.Error())
  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. log.Printf("%s", err.Error())
  212. http.Error(w, err.Error(), 500)
  213. return
  214. }
  215. var b string
  216. for s := range response {
  217. b += s
  218. if !strings.HasPrefix(s, "stream: ") {
  219. continue
  220. }
  221. w.Write([]byte(fmt.Sprintf("%v\n", s[8:])))
  222. }
  223. }
  224. func putHandler(w http.ResponseWriter, r *http.Request) {
  225. vars := mux.Vars(r)
  226. filename := sanitize.Path(filepath.Base(vars["filename"]))
  227. contentLength := r.ContentLength
  228. var reader io.Reader
  229. reader = r.Body
  230. if contentLength == -1 {
  231. // queue file to disk, because s3 needs content length
  232. var err error
  233. var f io.Reader
  234. f = reader
  235. var b bytes.Buffer
  236. n, err := io.CopyN(&b, f, _24K+1)
  237. if err != nil && err != io.EOF {
  238. log.Printf("%s", err.Error())
  239. http.Error(w, err.Error(), 500)
  240. return
  241. }
  242. if n > _24K {
  243. file, err := ioutil.TempFile(config.Temp, "transfer-")
  244. if err != nil {
  245. log.Printf("%s", err.Error())
  246. http.Error(w, err.Error(), 500)
  247. return
  248. }
  249. defer file.Close()
  250. n, err = io.Copy(file, io.MultiReader(&b, f))
  251. if err != nil {
  252. os.Remove(file.Name())
  253. log.Printf("%s", err.Error())
  254. http.Error(w, err.Error(), 500)
  255. return
  256. }
  257. reader, err = os.Open(file.Name())
  258. } else {
  259. reader = bytes.NewReader(b.Bytes())
  260. }
  261. contentLength = n
  262. }
  263. contentType := r.Header.Get("Content-Type")
  264. if contentType == "" {
  265. contentType = mime.TypeByExtension(filepath.Ext(vars["filename"]))
  266. }
  267. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  268. log.Printf("Uploading %s %d %s", token, filename, contentLength, contentType)
  269. var err error
  270. if err = storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  271. log.Printf("%s", err.Error())
  272. http.Error(w, errors.New("Could not save file").Error(), 500)
  273. return
  274. }
  275. // w.Statuscode = 200
  276. w.Header().Set("Content-Type", "text/plain")
  277. fmt.Fprintf(w, "https://%s/%s/%s\n", ipAddrFromRemoteAddr(r.Host), token, filename)
  278. }
  279. func zipHandler(w http.ResponseWriter, r *http.Request) {
  280. vars := mux.Vars(r)
  281. files := vars["files"]
  282. zipfilename := fmt.Sprintf("transfersh-%d.zip", uint16(time.Now().UnixNano()))
  283. w.Header().Set("Content-Type", "application/zip")
  284. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", zipfilename))
  285. w.Header().Set("Connection", "close")
  286. zw := zip.NewWriter(w)
  287. for _, key := range strings.Split(files, ",") {
  288. if strings.HasPrefix(key, "/") {
  289. key = key[1:]
  290. }
  291. key = strings.Replace(key, "\\", "/", -1)
  292. token := strings.Split(key, "/")[0]
  293. filename := sanitize.Path(strings.Split(key, "/")[1])
  294. reader, _, _, err := storage.Get(token, filename)
  295. if err != nil {
  296. if err.Error() == "The specified key does not exist." {
  297. http.Error(w, "File not found", 404)
  298. return
  299. } else {
  300. log.Printf("%s", err.Error())
  301. http.Error(w, "Could not retrieve file.", 500)
  302. return
  303. }
  304. }
  305. defer reader.Close()
  306. header := &zip.FileHeader{
  307. Name: strings.Split(key, "/")[1],
  308. Method: zip.Store,
  309. ModifiedTime: uint16(time.Now().UnixNano()),
  310. ModifiedDate: uint16(time.Now().UnixNano()),
  311. }
  312. fw, err := zw.CreateHeader(header)
  313. if err != nil {
  314. log.Printf("%s", err.Error())
  315. http.Error(w, "Internal server error.", 500)
  316. return
  317. }
  318. if _, err = io.Copy(fw, reader); err != nil {
  319. log.Printf("%s", err.Error())
  320. http.Error(w, "Internal server error.", 500)
  321. return
  322. }
  323. }
  324. if err := zw.Close(); err != nil {
  325. log.Printf("%s", err.Error())
  326. http.Error(w, "Internal server error.", 500)
  327. return
  328. }
  329. }
  330. func tarGzHandler(w http.ResponseWriter, r *http.Request) {
  331. vars := mux.Vars(r)
  332. files := vars["files"]
  333. tarfilename := fmt.Sprintf("transfersh-%d.tar.gz", uint16(time.Now().UnixNano()))
  334. w.Header().Set("Content-Type", "application/x-gzip")
  335. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  336. w.Header().Set("Connection", "close")
  337. os := gzip.NewWriter(w)
  338. defer os.Close()
  339. zw := tar.NewWriter(os)
  340. defer zw.Close()
  341. for _, key := range strings.Split(files, ",") {
  342. if strings.HasPrefix(key, "/") {
  343. key = key[1:]
  344. }
  345. key = strings.Replace(key, "\\", "/", -1)
  346. token := strings.Split(key, "/")[0]
  347. filename := sanitize.Path(strings.Split(key, "/")[1])
  348. reader, _, contentLength, err := storage.Get(token, filename)
  349. if err != nil {
  350. if err.Error() == "The specified key does not exist." {
  351. http.Error(w, "File not found", 404)
  352. return
  353. } else {
  354. log.Printf("%s", err.Error())
  355. http.Error(w, "Could not retrieve file.", 500)
  356. return
  357. }
  358. }
  359. defer reader.Close()
  360. header := &tar.Header{
  361. Name: strings.Split(key, "/")[1],
  362. Size: int64(contentLength),
  363. }
  364. err = zw.WriteHeader(header)
  365. if err != nil {
  366. log.Printf("%s", err.Error())
  367. http.Error(w, "Internal server error.", 500)
  368. return
  369. }
  370. if _, err = io.Copy(zw, reader); err != nil {
  371. log.Printf("%s", err.Error())
  372. http.Error(w, "Internal server error.", 500)
  373. return
  374. }
  375. }
  376. }
  377. func tarHandler(w http.ResponseWriter, r *http.Request) {
  378. vars := mux.Vars(r)
  379. files := vars["files"]
  380. tarfilename := fmt.Sprintf("transfersh-%d.tar", uint16(time.Now().UnixNano()))
  381. w.Header().Set("Content-Type", "application/x-tar")
  382. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  383. w.Header().Set("Connection", "close")
  384. zw := tar.NewWriter(w)
  385. defer zw.Close()
  386. for _, key := range strings.Split(files, ",") {
  387. token := strings.Split(key, "/")[0]
  388. filename := strings.Split(key, "/")[1]
  389. reader, _, contentLength, err := storage.Get(token, filename)
  390. if err != nil {
  391. if err.Error() == "The specified key does not exist." {
  392. http.Error(w, "File not found", 404)
  393. return
  394. } else {
  395. log.Printf("%s", err.Error())
  396. http.Error(w, "Could not retrieve file.", 500)
  397. return
  398. }
  399. }
  400. defer reader.Close()
  401. header := &tar.Header{
  402. Name: strings.Split(key, "/")[1],
  403. Size: int64(contentLength),
  404. }
  405. err = zw.WriteHeader(header)
  406. if err != nil {
  407. log.Printf("%s", err.Error())
  408. http.Error(w, "Internal server error.", 500)
  409. return
  410. }
  411. if _, err = io.Copy(zw, reader); err != nil {
  412. log.Printf("%s", err.Error())
  413. http.Error(w, "Internal server error.", 500)
  414. return
  415. }
  416. }
  417. }
  418. func getHandler(w http.ResponseWriter, r *http.Request) {
  419. vars := mux.Vars(r)
  420. token := vars["token"]
  421. filename := vars["filename"]
  422. reader, contentType, contentLength, err := storage.Get(token, filename)
  423. if err != nil {
  424. if err.Error() == "The specified key does not exist." {
  425. http.Error(w, "File not found", 404)
  426. return
  427. } else {
  428. log.Printf("%s", err.Error())
  429. http.Error(w, "Could not retrieve file.", 500)
  430. return
  431. }
  432. }
  433. defer reader.Close()
  434. w.Header().Set("Content-Type", contentType)
  435. w.Header().Set("Content-Length", strconv.FormatUint(contentLength, 10))
  436. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  437. w.Header().Set("Connection", "close")
  438. if _, err = io.Copy(w, reader); err != nil {
  439. log.Printf("%s", err.Error())
  440. http.Error(w, "Error occured copying to output stream", 500)
  441. return
  442. }
  443. }
  444. func RedirectHandler(h http.Handler) http.HandlerFunc {
  445. return func(w http.ResponseWriter, r *http.Request) {
  446. if r.URL.Path == "/health.html" {
  447. } else if ipAddrFromRemoteAddr(r.Host) == "127.0.0.1" {
  448. } else if ipAddrFromRemoteAddr(r.Host) == "transfersh.elasticbeanstalk.com" {
  449. } else if ipAddrFromRemoteAddr(r.Host) == "jxm5d6emw5rknovg.onion" {
  450. if r.Header.Get("X-Forwarded-Proto") != "https" && r.Method == "GET" {
  451. http.Redirect(w, r, "https://jxm5d6emw5rknovg.onion"+r.RequestURI, 301)
  452. return
  453. }
  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. }