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.
 
 
 

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