main.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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/prometheus/client_golang/prometheus/promhttp"
  20. _ "github.com/syncthing/syncthing/lib/automaxprocs"
  21. "github.com/syncthing/syncthing/lib/httpcache"
  22. "github.com/syncthing/syncthing/lib/upgrade"
  23. )
  24. type cli struct {
  25. Listen string `default:":8080" help:"Listen address"`
  26. MetricsListen string `default:":8081" help:"Listen address for metrics"`
  27. URL string `short:"u" default:"https://api.github.com/repos/syncthing/syncthing/releases?per_page=25" help:"GitHub releases url"`
  28. Forward []string `short:"f" help:"Forwarded pages, format: /path->https://example/com/url"`
  29. CacheTime time.Duration `default:"15m" help:"Cache time"`
  30. }
  31. func main() {
  32. var params cli
  33. kong.Parse(&params)
  34. if err := server(&params); err != nil {
  35. fmt.Printf("Error: %v\n", err)
  36. os.Exit(1)
  37. }
  38. }
  39. func server(params *cli) error {
  40. if params.MetricsListen != "" {
  41. mux := http.NewServeMux()
  42. mux.Handle("/metrics", promhttp.Handler())
  43. go func() {
  44. log.Println("Listening for metrics on", params.MetricsListen)
  45. if err := http.ListenAndServe(params.MetricsListen, mux); err != nil {
  46. log.Fatalf("Failed to start metrics server: %v", err)
  47. }
  48. }()
  49. }
  50. mux := http.NewServeMux()
  51. mux.Handle("/meta.json", httpcache.SinglePath(&githubReleases{url: params.URL}, params.CacheTime))
  52. for _, fwd := range params.Forward {
  53. path, url, ok := strings.Cut(fwd, "->")
  54. if !ok {
  55. return fmt.Errorf("invalid forward: %q", fwd)
  56. }
  57. log.Println("Forwarding", path, "to", url)
  58. mux.Handle(path, httpcache.SinglePath(&proxy{url: url}, params.CacheTime))
  59. }
  60. srv := &http.Server{
  61. Addr: params.Listen,
  62. Handler: mux,
  63. ReadTimeout: 5 * time.Second,
  64. WriteTimeout: 10 * time.Second,
  65. }
  66. srv.SetKeepAlivesEnabled(false)
  67. return srv.ListenAndServe()
  68. }
  69. type githubReleases struct {
  70. url string
  71. }
  72. func (p *githubReleases) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
  73. log.Println("Fetching", p.url)
  74. rels := upgrade.FetchLatestReleases(p.url, "")
  75. if rels == nil {
  76. http.Error(w, "no releases", http.StatusInternalServerError)
  77. return
  78. }
  79. sort.Sort(upgrade.SortByRelease(rels))
  80. rels = filterForLatest(rels)
  81. // Move the URL used for browser downloads to the URL field, and remove
  82. // the browser URL field. This avoids going via the GitHub API for
  83. // downloads, since Syncthing uses the URL field.
  84. for _, rel := range rels {
  85. for j, asset := range rel.Assets {
  86. rel.Assets[j].URL = asset.BrowserURL
  87. rel.Assets[j].BrowserURL = ""
  88. }
  89. }
  90. buf := new(bytes.Buffer)
  91. _ = json.NewEncoder(buf).Encode(rels)
  92. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  93. w.Header().Set("Access-Control-Allow-Origin", "*")
  94. w.Header().Set("Access-Control-Allow-Methods", "GET")
  95. w.Write(buf.Bytes())
  96. }
  97. type proxy struct {
  98. url string
  99. }
  100. func (p *proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  101. log.Println("Fetching", p.url)
  102. req, err := http.NewRequestWithContext(req.Context(), http.MethodGet, p.url, nil)
  103. if err != nil {
  104. http.Error(w, err.Error(), http.StatusInternalServerError)
  105. return
  106. }
  107. resp, err := http.DefaultClient.Do(req)
  108. if err != nil {
  109. http.Error(w, err.Error(), http.StatusInternalServerError)
  110. return
  111. }
  112. defer resp.Body.Close()
  113. ct := resp.Header.Get("Content-Type")
  114. w.Header().Set("Content-Type", ct)
  115. if resp.StatusCode == http.StatusOK {
  116. w.Header().Set("Cache-Control", "public, max-age=900")
  117. w.Header().Set("Access-Control-Allow-Origin", "*")
  118. w.Header().Set("Access-Control-Allow-Methods", "GET")
  119. }
  120. w.WriteHeader(resp.StatusCode)
  121. if strings.HasPrefix(ct, "application/json") {
  122. // Special JSON handling; clean it up a bit.
  123. var v interface{}
  124. if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
  125. http.Error(w, err.Error(), http.StatusInternalServerError)
  126. return
  127. }
  128. _ = json.NewEncoder(w).Encode(v)
  129. } else {
  130. _, _ = io.Copy(w, resp.Body)
  131. }
  132. }
  133. // filterForLatest returns the latest stable and prerelease only. If the
  134. // stable version is newer (comes first in the list) there is no need to go
  135. // looking for a prerelease at all.
  136. func filterForLatest(rels []upgrade.Release) []upgrade.Release {
  137. var filtered []upgrade.Release
  138. var havePre bool
  139. for _, rel := range rels {
  140. if !rel.Prerelease {
  141. // We found a stable version, we're good now.
  142. filtered = append(filtered, rel)
  143. break
  144. }
  145. if rel.Prerelease && !havePre {
  146. // We remember the first prerelease we find.
  147. filtered = append(filtered, rel)
  148. havePre = true
  149. }
  150. }
  151. return filtered
  152. }