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.
 
 
 

921 lines
23 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. "encoding/json"
  29. "errors"
  30. "fmt"
  31. "html"
  32. html_template "html/template"
  33. "io"
  34. "io/ioutil"
  35. "log"
  36. "math/rand"
  37. "mime"
  38. "net/http"
  39. "net/url"
  40. "os"
  41. "path"
  42. "path/filepath"
  43. "strconv"
  44. "strings"
  45. "sync"
  46. text_template "text/template"
  47. "time"
  48. "net"
  49. web "github.com/dutchcoders/transfer.sh-web"
  50. "github.com/gorilla/mux"
  51. "github.com/russross/blackfriday"
  52. "encoding/base64"
  53. qrcode "github.com/skip2/go-qrcode"
  54. )
  55. var (
  56. htmlTemplates = initHTMLTemplates()
  57. textTemplates = initTextTemplates()
  58. )
  59. func stripPrefix(path string) string {
  60. return strings.Replace(path, web.Prefix+"/", "", -1)
  61. }
  62. func initTextTemplates() *text_template.Template {
  63. templateMap := text_template.FuncMap{"format": formatNumber}
  64. // Templates with functions available to them
  65. var templates = text_template.New("").Funcs(templateMap)
  66. return templates
  67. }
  68. func initHTMLTemplates() *html_template.Template {
  69. templateMap := html_template.FuncMap{"format": formatNumber}
  70. // Templates with functions available to them
  71. var templates = html_template.New("").Funcs(templateMap)
  72. return templates
  73. }
  74. func healthHandler(w http.ResponseWriter, r *http.Request) {
  75. fmt.Fprintf(w, "Approaching Neutral Zone, all systems normal and functioning.")
  76. }
  77. /* The preview handler will show a preview of the content for browsers (accept type text/html), and referer is not transfer.sh */
  78. func (s *Server) previewHandler(w http.ResponseWriter, r *http.Request) {
  79. vars := mux.Vars(r)
  80. token := vars["token"]
  81. filename := vars["filename"]
  82. contentType, contentLength, err := s.storage.Head(token, filename)
  83. if err != nil {
  84. http.Error(w, http.StatusText(404), 404)
  85. return
  86. }
  87. var templatePath string
  88. var content html_template.HTML
  89. switch {
  90. case strings.HasPrefix(contentType, "image/"):
  91. templatePath = "download.image.html"
  92. case strings.HasPrefix(contentType, "video/"):
  93. templatePath = "download.video.html"
  94. case strings.HasPrefix(contentType, "audio/"):
  95. templatePath = "download.audio.html"
  96. case strings.HasPrefix(contentType, "text/"):
  97. templatePath = "download.markdown.html"
  98. var reader io.ReadCloser
  99. if reader, _, _, err = s.storage.Get(token, filename); err != nil {
  100. http.Error(w, err.Error(), http.StatusInternalServerError)
  101. return
  102. }
  103. var data []byte
  104. if data, err = ioutil.ReadAll(reader); err != nil {
  105. http.Error(w, err.Error(), http.StatusInternalServerError)
  106. return
  107. }
  108. if strings.HasPrefix(contentType, "text/x-markdown") || strings.HasPrefix(contentType, "text/markdown") {
  109. escapedData := html.EscapeString(string(data))
  110. output := blackfriday.MarkdownCommon([]byte(escapedData))
  111. content = html_template.HTML(output)
  112. } else if strings.HasPrefix(contentType, "text/plain") {
  113. content = html_template.HTML(fmt.Sprintf("<pre>%s</pre>", html.EscapeString(string(data))))
  114. } else {
  115. templatePath = "download.sandbox.html"
  116. }
  117. default:
  118. templatePath = "download.html"
  119. }
  120. if err != nil {
  121. http.Error(w, err.Error(), http.StatusInternalServerError)
  122. return
  123. }
  124. var png []byte
  125. png, err = qrcode.Encode(resolveUrl(r, getURL(r).ResolveReference(r.URL), true), qrcode.High, 150)
  126. if err != nil {
  127. http.Error(w, err.Error(), http.StatusInternalServerError)
  128. return
  129. }
  130. qrCode := base64.StdEncoding.EncodeToString(png)
  131. data := struct {
  132. ContentType string
  133. Content html_template.HTML
  134. Filename string
  135. Url string
  136. ContentLength uint64
  137. GAKey string
  138. UserVoiceKey string
  139. QRCode string
  140. }{
  141. contentType,
  142. content,
  143. filename,
  144. r.URL.String(),
  145. contentLength,
  146. s.gaKey,
  147. s.userVoiceKey,
  148. qrCode,
  149. }
  150. if err := htmlTemplates.ExecuteTemplate(w, templatePath, data); err != nil {
  151. http.Error(w, err.Error(), http.StatusInternalServerError)
  152. return
  153. }
  154. }
  155. // this handler will output html or text, depending on the
  156. // support of the client (Accept header).
  157. func (s *Server) viewHandler(w http.ResponseWriter, r *http.Request) {
  158. // vars := mux.Vars(r)
  159. if acceptsHTML(r.Header) {
  160. if err := htmlTemplates.ExecuteTemplate(w, "index.html", nil); err != nil {
  161. http.Error(w, err.Error(), http.StatusInternalServerError)
  162. return
  163. }
  164. } else {
  165. if err := textTemplates.ExecuteTemplate(w, "index.txt", nil); err != nil {
  166. http.Error(w, err.Error(), http.StatusInternalServerError)
  167. return
  168. }
  169. }
  170. }
  171. func (s *Server) notFoundHandler(w http.ResponseWriter, r *http.Request) {
  172. http.Error(w, http.StatusText(404), 404)
  173. }
  174. func sanitize(fileName string) string {
  175. return path.Clean(path.Base(fileName))
  176. }
  177. func (s *Server) postHandler(w http.ResponseWriter, r *http.Request) {
  178. if err := r.ParseMultipartForm(_24K); nil != err {
  179. log.Printf("%s", err.Error())
  180. http.Error(w, "Error occurred copying to output stream", 500)
  181. return
  182. }
  183. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  184. w.Header().Set("Content-Type", "text/plain")
  185. for _, fheaders := range r.MultipartForm.File {
  186. for _, fheader := range fheaders {
  187. filename := sanitize(fheader.Filename)
  188. contentType := fheader.Header.Get("Content-Type")
  189. if contentType == "" {
  190. contentType = mime.TypeByExtension(filepath.Ext(fheader.Filename))
  191. }
  192. var f io.Reader
  193. var err error
  194. if f, err = fheader.Open(); err != nil {
  195. log.Printf("%s", err.Error())
  196. http.Error(w, err.Error(), 500)
  197. return
  198. }
  199. var b bytes.Buffer
  200. n, err := io.CopyN(&b, f, _24K+1)
  201. if err != nil && err != io.EOF {
  202. log.Printf("%s", err.Error())
  203. http.Error(w, err.Error(), 500)
  204. return
  205. }
  206. var reader io.Reader
  207. if n > _24K {
  208. file, err := ioutil.TempFile(s.tempPath, "transfer-")
  209. if err != nil {
  210. log.Fatal(err)
  211. }
  212. defer file.Close()
  213. n, err = io.Copy(file, io.MultiReader(&b, f))
  214. if err != nil {
  215. os.Remove(file.Name())
  216. log.Printf("%s", err.Error())
  217. http.Error(w, err.Error(), 500)
  218. return
  219. }
  220. reader, err = os.Open(file.Name())
  221. } else {
  222. reader = bytes.NewReader(b.Bytes())
  223. }
  224. contentLength := n
  225. metadata := MetadataForRequest(contentType, r)
  226. buffer := &bytes.Buffer{}
  227. if err := json.NewEncoder(buffer).Encode(metadata); err != nil {
  228. log.Printf("%s", err.Error())
  229. http.Error(w, errors.New("Could not encode metadata").Error(), 500)
  230. return
  231. } else if err := s.storage.Put(token, fmt.Sprintf("%s.metadata", filename), buffer, "text/json", uint64(buffer.Len())); err != nil {
  232. log.Printf("%s", err.Error())
  233. http.Error(w, errors.New("Could not save metadata").Error(), 500)
  234. return
  235. }
  236. log.Printf("Uploading %s %s %d %s", token, filename, contentLength, contentType)
  237. if err = s.storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  238. log.Printf("Backend storage error: %s", err.Error())
  239. http.Error(w, err.Error(), 500)
  240. return
  241. }
  242. relativeURL, _ := url.Parse(path.Join(token, filename))
  243. fmt.Fprint(w, getURL(r).ResolveReference(relativeURL).String())
  244. }
  245. }
  246. }
  247. type Metadata struct {
  248. // ContentType is the original uploading content type
  249. ContentType string
  250. // Secret as knowledge to delete file
  251. // Secret string
  252. // Downloads is the actual number of downloads
  253. Downloads int
  254. // MaxDownloads contains the maximum numbers of downloads
  255. MaxDownloads int
  256. // MaxDate contains the max age of the file
  257. MaxDate time.Time
  258. // DeletionToken contains the token to match against for deletion
  259. DeletionToken string
  260. }
  261. func MetadataForRequest(contentType string, r *http.Request) Metadata {
  262. metadata := Metadata{
  263. ContentType: contentType,
  264. MaxDate: time.Now().Add(time.Hour * 24 * 365 * 10),
  265. Downloads: 0,
  266. MaxDownloads: 99999999,
  267. DeletionToken: Encode(10000000+int64(rand.Intn(1000000000))) + Encode(10000000+int64(rand.Intn(1000000000))),
  268. }
  269. if v := r.Header.Get("Max-Downloads"); v == "" {
  270. } else if v, err := strconv.Atoi(v); err != nil {
  271. } else {
  272. metadata.MaxDownloads = v
  273. }
  274. if v := r.Header.Get("Max-Days"); v == "" {
  275. } else if v, err := strconv.Atoi(v); err != nil {
  276. } else {
  277. metadata.MaxDate = time.Now().Add(time.Hour * 24 * time.Duration(v))
  278. }
  279. return metadata
  280. }
  281. func (s *Server) putHandler(w http.ResponseWriter, r *http.Request) {
  282. vars := mux.Vars(r)
  283. filename := sanitize(vars["filename"])
  284. contentLength := r.ContentLength
  285. var reader io.Reader
  286. reader = r.Body
  287. if contentLength == -1 {
  288. // queue file to disk, because s3 needs content length
  289. var err error
  290. var f io.Reader
  291. f = reader
  292. var b bytes.Buffer
  293. n, err := io.CopyN(&b, f, _24K+1)
  294. if err != nil && err != io.EOF {
  295. log.Printf("Error putting new file: %s", err.Error())
  296. http.Error(w, err.Error(), 500)
  297. return
  298. }
  299. if n > _24K {
  300. file, err := ioutil.TempFile(s.tempPath, "transfer-")
  301. if err != nil {
  302. log.Printf("%s", err.Error())
  303. http.Error(w, err.Error(), 500)
  304. return
  305. }
  306. defer file.Close()
  307. n, err = io.Copy(file, io.MultiReader(&b, f))
  308. if err != nil {
  309. os.Remove(file.Name())
  310. log.Printf("%s", err.Error())
  311. http.Error(w, err.Error(), 500)
  312. return
  313. }
  314. reader, err = os.Open(file.Name())
  315. } else {
  316. reader = bytes.NewReader(b.Bytes())
  317. }
  318. contentLength = n
  319. }
  320. if contentLength == 0 {
  321. log.Print("Empty content-length")
  322. http.Error(w, errors.New("Could not uplpoad empty file").Error(), 400)
  323. return
  324. }
  325. contentType := r.Header.Get("Content-Type")
  326. if contentType == "" {
  327. contentType = mime.TypeByExtension(filepath.Ext(vars["filename"]))
  328. }
  329. token := Encode(10000000 + int64(rand.Intn(1000000000)))
  330. metadata := MetadataForRequest(contentType, r)
  331. buffer := &bytes.Buffer{}
  332. if err := json.NewEncoder(buffer).Encode(metadata); err != nil {
  333. log.Printf("%s", err.Error())
  334. http.Error(w, errors.New("Could not encode metadata").Error(), 500)
  335. return
  336. } else if err := s.storage.Put(token, fmt.Sprintf("%s.metadata", filename), buffer, "text/json", uint64(buffer.Len())); err != nil {
  337. log.Printf("%s", err.Error())
  338. http.Error(w, errors.New("Could not save metadata").Error(), 500)
  339. return
  340. }
  341. log.Printf("Uploading %s %s %d %s", token, filename, contentLength, contentType)
  342. var err error
  343. if err = s.storage.Put(token, filename, reader, contentType, uint64(contentLength)); err != nil {
  344. log.Printf("Error putting new file: %s", err.Error())
  345. http.Error(w, errors.New("Could not save file").Error(), 500)
  346. return
  347. }
  348. // w.Statuscode = 200
  349. w.Header().Set("Content-Type", "text/plain")
  350. relativeURL, _ := url.Parse(path.Join(token, filename))
  351. deleteUrl, _ := url.Parse(path.Join(token, filename, metadata.DeletionToken))
  352. w.Header().Set("X-Url-Delete", resolveUrl(r, deleteUrl, true))
  353. fmt.Fprint(w, resolveUrl(r, relativeURL, false))
  354. }
  355. func resolveUrl(r *http.Request, u *url.URL, absolutePath bool) string {
  356. if u.RawQuery != "" {
  357. u.Path = fmt.Sprintf("%s?%s", u.Path, url.QueryEscape(u.RawQuery))
  358. u.RawQuery = ""
  359. }
  360. if u.Fragment != "" {
  361. u.Path = fmt.Sprintf("%s#%s", u.Path, u.Fragment)
  362. u.Fragment = ""
  363. }
  364. if absolutePath {
  365. r.URL.Path = ""
  366. }
  367. return getURL(r).ResolveReference(u).String()
  368. }
  369. func getURL(r *http.Request) *url.URL {
  370. u := *r.URL
  371. if r.TLS != nil {
  372. u.Scheme = "https"
  373. } else if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  374. u.Scheme = proto
  375. } else {
  376. u.Scheme = "http"
  377. }
  378. if u.Host != "" {
  379. } else if host, port, err := net.SplitHostPort(r.Host); err != nil {
  380. u.Host = r.Host
  381. } else {
  382. if port == "80" && u.Scheme == "http" {
  383. u.Host = host
  384. } else if port == "443" && u.Scheme == "https" {
  385. u.Host = host
  386. } else {
  387. u.Host = net.JoinHostPort(host, port)
  388. }
  389. }
  390. return &u
  391. }
  392. func (s *Server) Lock(token, filename string) error {
  393. key := path.Join(token, filename)
  394. if _, ok := s.locks[key]; !ok {
  395. s.locks[key] = &sync.Mutex{}
  396. }
  397. s.locks[key].Lock()
  398. return nil
  399. }
  400. func (s *Server) Unlock(token, filename string) error {
  401. key := path.Join(token, filename)
  402. s.locks[key].Unlock()
  403. return nil
  404. }
  405. func (s *Server) CheckMetadata(token, filename string) error {
  406. s.Lock(token, filename)
  407. defer s.Unlock(token, filename)
  408. var metadata Metadata
  409. r, _, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename))
  410. if s.storage.IsNotExist(err) {
  411. return nil
  412. } else if err != nil {
  413. return err
  414. }
  415. defer r.Close()
  416. if err := json.NewDecoder(r).Decode(&metadata); err != nil {
  417. return err
  418. } else if metadata.Downloads >= metadata.MaxDownloads {
  419. return errors.New("MaxDownloads expired.")
  420. } else if time.Now().After(metadata.MaxDate) {
  421. return errors.New("MaxDate expired.")
  422. } else {
  423. // todo(nl5887): mutex?
  424. // update number of downloads
  425. metadata.Downloads++
  426. buffer := &bytes.Buffer{}
  427. if err := json.NewEncoder(buffer).Encode(metadata); err != nil {
  428. return errors.New("Could not encode metadata")
  429. } else if err := s.storage.Put(token, fmt.Sprintf("%s.metadata", filename), buffer, "text/json", uint64(buffer.Len())); err != nil {
  430. return errors.New("Could not save metadata")
  431. }
  432. }
  433. return nil
  434. }
  435. func (s *Server) CheckDeletionToken(deletionToken, token, filename string) error {
  436. s.Lock(token, filename)
  437. defer s.Unlock(token, filename)
  438. var metadata Metadata
  439. r, _, _, err := s.storage.Get(token, fmt.Sprintf("%s.metadata", filename))
  440. if s.storage.IsNotExist(err) {
  441. return nil
  442. } else if err != nil {
  443. return err
  444. }
  445. defer r.Close()
  446. if err := json.NewDecoder(r).Decode(&metadata); err != nil {
  447. return err
  448. } else if metadata.DeletionToken != deletionToken {
  449. return errors.New("Deletion token doesn't match.")
  450. }
  451. return nil
  452. }
  453. func (s *Server) deleteHandler(w http.ResponseWriter, r *http.Request) {
  454. vars := mux.Vars(r)
  455. token := vars["token"]
  456. filename := vars["filename"]
  457. deletionToken := vars["deletionToken"]
  458. if err := s.CheckDeletionToken(deletionToken, token, filename); err != nil {
  459. log.Printf("Error metadata: %s", err.Error())
  460. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  461. return
  462. }
  463. err := s.storage.Delete(token, filename)
  464. if s.storage.IsNotExist(err) {
  465. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  466. return
  467. } else if err != nil {
  468. log.Printf("%s", err.Error())
  469. http.Error(w, "Could not delete file.", 500)
  470. return
  471. }
  472. }
  473. func (s *Server) zipHandler(w http.ResponseWriter, r *http.Request) {
  474. vars := mux.Vars(r)
  475. files := vars["files"]
  476. zipfilename := fmt.Sprintf("transfersh-%d.zip", uint16(time.Now().UnixNano()))
  477. w.Header().Set("Content-Type", "application/zip")
  478. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", zipfilename))
  479. w.Header().Set("Connection", "close")
  480. zw := zip.NewWriter(w)
  481. for _, key := range strings.Split(files, ",") {
  482. if strings.HasPrefix(key, "/") {
  483. key = key[1:]
  484. }
  485. key = strings.Replace(key, "\\", "/", -1)
  486. token := strings.Split(key, "/")[0]
  487. filename := sanitize(strings.Split(key, "/")[1])
  488. if err := s.CheckMetadata(token, filename); err != nil {
  489. log.Printf("Error metadata: %s", err.Error())
  490. continue
  491. }
  492. reader, _, _, err := s.storage.Get(token, filename)
  493. if err != nil {
  494. if s.storage.IsNotExist(err) {
  495. http.Error(w, "File not found", 404)
  496. return
  497. } else {
  498. log.Printf("%s", err.Error())
  499. http.Error(w, "Could not retrieve file.", 500)
  500. return
  501. }
  502. }
  503. defer reader.Close()
  504. header := &zip.FileHeader{
  505. Name: strings.Split(key, "/")[1],
  506. Method: zip.Store,
  507. ModifiedTime: uint16(time.Now().UnixNano()),
  508. ModifiedDate: uint16(time.Now().UnixNano()),
  509. }
  510. fw, err := zw.CreateHeader(header)
  511. if err != nil {
  512. log.Printf("%s", err.Error())
  513. http.Error(w, "Internal server error.", 500)
  514. return
  515. }
  516. if _, err = io.Copy(fw, reader); err != nil {
  517. log.Printf("%s", err.Error())
  518. http.Error(w, "Internal server error.", 500)
  519. return
  520. }
  521. }
  522. if err := zw.Close(); err != nil {
  523. log.Printf("%s", err.Error())
  524. http.Error(w, "Internal server error.", 500)
  525. return
  526. }
  527. }
  528. func (s *Server) tarGzHandler(w http.ResponseWriter, r *http.Request) {
  529. vars := mux.Vars(r)
  530. files := vars["files"]
  531. tarfilename := fmt.Sprintf("transfersh-%d.tar.gz", uint16(time.Now().UnixNano()))
  532. w.Header().Set("Content-Type", "application/x-gzip")
  533. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  534. w.Header().Set("Connection", "close")
  535. os := gzip.NewWriter(w)
  536. defer os.Close()
  537. zw := tar.NewWriter(os)
  538. defer zw.Close()
  539. for _, key := range strings.Split(files, ",") {
  540. if strings.HasPrefix(key, "/") {
  541. key = key[1:]
  542. }
  543. key = strings.Replace(key, "\\", "/", -1)
  544. token := strings.Split(key, "/")[0]
  545. filename := sanitize(strings.Split(key, "/")[1])
  546. if err := s.CheckMetadata(token, filename); err != nil {
  547. log.Printf("Error metadata: %s", err.Error())
  548. continue
  549. }
  550. reader, _, contentLength, err := s.storage.Get(token, filename)
  551. if err != nil {
  552. if s.storage.IsNotExist(err) {
  553. http.Error(w, "File not found", 404)
  554. return
  555. } else {
  556. log.Printf("%s", err.Error())
  557. http.Error(w, "Could not retrieve file.", 500)
  558. return
  559. }
  560. }
  561. defer reader.Close()
  562. header := &tar.Header{
  563. Name: strings.Split(key, "/")[1],
  564. Size: int64(contentLength),
  565. }
  566. err = zw.WriteHeader(header)
  567. if err != nil {
  568. log.Printf("%s", err.Error())
  569. http.Error(w, "Internal server error.", 500)
  570. return
  571. }
  572. if _, err = io.Copy(zw, reader); err != nil {
  573. log.Printf("%s", err.Error())
  574. http.Error(w, "Internal server error.", 500)
  575. return
  576. }
  577. }
  578. }
  579. func (s *Server) tarHandler(w http.ResponseWriter, r *http.Request) {
  580. vars := mux.Vars(r)
  581. files := vars["files"]
  582. tarfilename := fmt.Sprintf("transfersh-%d.tar", uint16(time.Now().UnixNano()))
  583. w.Header().Set("Content-Type", "application/x-tar")
  584. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
  585. w.Header().Set("Connection", "close")
  586. zw := tar.NewWriter(w)
  587. defer zw.Close()
  588. for _, key := range strings.Split(files, ",") {
  589. token := strings.Split(key, "/")[0]
  590. filename := strings.Split(key, "/")[1]
  591. if err := s.CheckMetadata(token, filename); err != nil {
  592. log.Printf("Error metadata: %s", err.Error())
  593. continue
  594. }
  595. reader, _, contentLength, err := s.storage.Get(token, filename)
  596. if err != nil {
  597. if s.storage.IsNotExist(err) {
  598. http.Error(w, "File not found", 404)
  599. return
  600. } else {
  601. log.Printf("%s", err.Error())
  602. http.Error(w, "Could not retrieve file.", 500)
  603. return
  604. }
  605. }
  606. defer reader.Close()
  607. header := &tar.Header{
  608. Name: strings.Split(key, "/")[1],
  609. Size: int64(contentLength),
  610. }
  611. err = zw.WriteHeader(header)
  612. if err != nil {
  613. log.Printf("%s", err.Error())
  614. http.Error(w, "Internal server error.", 500)
  615. return
  616. }
  617. if _, err = io.Copy(zw, reader); err != nil {
  618. log.Printf("%s", err.Error())
  619. http.Error(w, "Internal server error.", 500)
  620. return
  621. }
  622. }
  623. }
  624. func (s *Server) headHandler(w http.ResponseWriter, r *http.Request) {
  625. vars := mux.Vars(r)
  626. token := vars["token"]
  627. filename := vars["filename"]
  628. if err := s.CheckMetadata(token, filename); err != nil {
  629. log.Printf("Error metadata: %s", err.Error())
  630. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  631. return
  632. }
  633. contentType, contentLength, err := s.storage.Head(token, filename)
  634. if s.storage.IsNotExist(err) {
  635. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  636. return
  637. } else if err != nil {
  638. log.Printf("%s", err.Error())
  639. http.Error(w, "Could not retrieve file.", 500)
  640. return
  641. }
  642. w.Header().Set("Content-Type", contentType)
  643. w.Header().Set("Content-Length", strconv.FormatUint(contentLength, 10))
  644. w.Header().Set("Connection", "close")
  645. }
  646. func (s *Server) getHandler(w http.ResponseWriter, r *http.Request) {
  647. vars := mux.Vars(r)
  648. action := vars["action"]
  649. token := vars["token"]
  650. filename := vars["filename"]
  651. if err := s.CheckMetadata(token, filename); err != nil {
  652. log.Printf("Error metadata: %s", err.Error())
  653. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  654. return
  655. }
  656. reader, contentType, contentLength, err := s.storage.Get(token, filename)
  657. if s.storage.IsNotExist(err) {
  658. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  659. return
  660. } else if err != nil {
  661. log.Printf("%s", err.Error())
  662. http.Error(w, "Could not retrieve file.", 500)
  663. return
  664. }
  665. defer reader.Close()
  666. var disposition string
  667. if action == "inline" {
  668. disposition = "inline"
  669. } else {
  670. disposition = "attachment"
  671. }
  672. w.Header().Set("Content-Type", contentType)
  673. w.Header().Set("Content-Length", strconv.FormatUint(contentLength, 10))
  674. w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disposition, filename))
  675. w.Header().Set("Connection", "keep-alive")
  676. if _, err = io.Copy(w, reader); err != nil {
  677. log.Printf("%s", err.Error())
  678. http.Error(w, "Error occurred copying to output stream", 500)
  679. return
  680. }
  681. }
  682. func (s *Server) RedirectHandler(h http.Handler) http.HandlerFunc {
  683. return func(w http.ResponseWriter, r *http.Request) {
  684. if !s.forceHTTPs {
  685. // we don't want to enforce https
  686. } else if r.URL.Path == "/health.html" {
  687. // health check url won't redirect
  688. } else if strings.HasSuffix(ipAddrFromRemoteAddr(r.Host), ".onion") {
  689. // .onion addresses cannot get a valid certificate, so don't redirect
  690. } else if r.Header.Get("X-Forwarded-Proto") == "https" {
  691. } else if r.URL.Scheme == "https" {
  692. } else {
  693. u := getURL(r)
  694. u.Scheme = "https"
  695. http.Redirect(w, r, u.String(), http.StatusPermanentRedirect)
  696. return
  697. }
  698. h.ServeHTTP(w, r)
  699. }
  700. }
  701. // Create a log handler for every request it receives.
  702. func LoveHandler(h http.Handler) http.HandlerFunc {
  703. return func(w http.ResponseWriter, r *http.Request) {
  704. w.Header().Set("x-made-with", "<3 by DutchCoders")
  705. w.Header().Set("x-served-by", "Proudly served by DutchCoders")
  706. w.Header().Set("Server", "Transfer.sh HTTP Server 1.0")
  707. h.ServeHTTP(w, r)
  708. }
  709. }
  710. func (s *Server) BasicAuthHandler(h http.Handler) http.HandlerFunc {
  711. return func(w http.ResponseWriter, r *http.Request) {
  712. if s.AuthUser == "" || s.AuthPass == "" {
  713. h.ServeHTTP(w, r)
  714. return
  715. }
  716. w.Header().Set("WWW-Authenticate", "Basic realm=\"Restricted\"")
  717. username, password, authOK := r.BasicAuth()
  718. if authOK == false {
  719. http.Error(w, "Not authorized", 401)
  720. return
  721. }
  722. if username != s.AuthUser || password != s.AuthPass {
  723. http.Error(w, "Not authorized", 401)
  724. return
  725. }
  726. h.ServeHTTP(w, r)
  727. }
  728. }