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.
 
 
 

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