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.
 
 
 

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