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.
 
 
 

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