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.
 
 
 

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