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.
 
 
 

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