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.
 
 
 

623 lines
15 KiB

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