main.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "log"
  13. "net/http"
  14. "os"
  15. "sort"
  16. "strings"
  17. "time"
  18. "github.com/alecthomas/kong"
  19. _ "github.com/syncthing/syncthing/lib/automaxprocs"
  20. "github.com/syncthing/syncthing/lib/httpcache"
  21. "github.com/syncthing/syncthing/lib/upgrade"
  22. )
  23. type cli struct {
  24. Listen string `default:":8080" help:"Listen address"`
  25. URL string `short:"u" default:"https://api.github.com/repos/syncthing/syncthing/releases?per_page=25" help:"GitHub releases url"`
  26. Forward []string `short:"f" help:"Forwarded pages, format: /path->https://example/com/url"`
  27. CacheTime time.Duration `default:"15m" help:"Cache time"`
  28. }
  29. func main() {
  30. var params cli
  31. kong.Parse(&params)
  32. if err := server(&params); err != nil {
  33. fmt.Printf("Error: %v\n", err)
  34. os.Exit(1)
  35. }
  36. }
  37. func server(params *cli) error {
  38. http.Handle("/meta.json", httpcache.SinglePath(&githubReleases{url: params.URL}, params.CacheTime))
  39. for _, fwd := range params.Forward {
  40. path, url, ok := strings.Cut(fwd, "->")
  41. if !ok {
  42. return fmt.Errorf("invalid forward: %q", fwd)
  43. }
  44. http.Handle(path, httpcache.SinglePath(&proxy{url: url}, params.CacheTime))
  45. }
  46. return http.ListenAndServe(params.Listen, nil)
  47. }
  48. type githubReleases struct {
  49. url string
  50. }
  51. func (p *githubReleases) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
  52. log.Println("Fetching", p.url)
  53. rels := upgrade.FetchLatestReleases(p.url, "")
  54. if rels == nil {
  55. http.Error(w, "no releases", http.StatusInternalServerError)
  56. return
  57. }
  58. sort.Sort(upgrade.SortByRelease(rels))
  59. rels = filterForLatest(rels)
  60. // Move the URL used for browser downloads to the URL field, and remove
  61. // the browser URL field. This avoids going via the GitHub API for
  62. // downloads, since Syncthing uses the URL field.
  63. for _, rel := range rels {
  64. for j, asset := range rel.Assets {
  65. rel.Assets[j].URL = asset.BrowserURL
  66. rel.Assets[j].BrowserURL = ""
  67. }
  68. }
  69. buf := new(bytes.Buffer)
  70. _ = json.NewEncoder(buf).Encode(rels)
  71. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  72. w.Header().Set("Access-Control-Allow-Origin", "*")
  73. w.Header().Set("Access-Control-Allow-Methods", "GET")
  74. w.Write(buf.Bytes())
  75. }
  76. type proxy struct {
  77. url string
  78. }
  79. func (p *proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  80. log.Println("Fetching", p.url)
  81. req, err := http.NewRequestWithContext(req.Context(), http.MethodGet, p.url, nil)
  82. if err != nil {
  83. http.Error(w, err.Error(), http.StatusInternalServerError)
  84. return
  85. }
  86. resp, err := http.DefaultClient.Do(req)
  87. if err != nil {
  88. http.Error(w, err.Error(), http.StatusInternalServerError)
  89. return
  90. }
  91. defer resp.Body.Close()
  92. ct := resp.Header.Get("Content-Type")
  93. w.Header().Set("Content-Type", ct)
  94. if resp.StatusCode == http.StatusOK {
  95. w.Header().Set("Cache-Control", "public, max-age=900")
  96. w.Header().Set("Access-Control-Allow-Origin", "*")
  97. w.Header().Set("Access-Control-Allow-Methods", "GET")
  98. }
  99. w.WriteHeader(resp.StatusCode)
  100. if strings.HasPrefix(ct, "application/json") {
  101. // Special JSON handling; clean it up a bit.
  102. var v interface{}
  103. if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
  104. http.Error(w, err.Error(), http.StatusInternalServerError)
  105. return
  106. }
  107. _ = json.NewEncoder(w).Encode(v)
  108. } else {
  109. _, _ = io.Copy(w, resp.Body)
  110. }
  111. }
  112. // filterForLatest returns the latest stable and prerelease only. If the
  113. // stable version is newer (comes first in the list) there is no need to go
  114. // looking for a prerelease at all.
  115. func filterForLatest(rels []upgrade.Release) []upgrade.Release {
  116. var filtered []upgrade.Release
  117. var havePre bool
  118. for _, rel := range rels {
  119. if !rel.Prerelease {
  120. // We found a stable version, we're good now.
  121. filtered = append(filtered, rel)
  122. break
  123. }
  124. if rel.Prerelease && !havePre {
  125. // We remember the first prerelease we find.
  126. filtered = append(filtered, rel)
  127. havePre = true
  128. }
  129. }
  130. return filtered
  131. }