api_statics.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright (C) 2014 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 api
  7. import (
  8. "bytes"
  9. "compress/gzip"
  10. "fmt"
  11. "io/ioutil"
  12. "mime"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. "github.com/syncthing/syncthing/lib/auto"
  19. "github.com/syncthing/syncthing/lib/config"
  20. "github.com/syncthing/syncthing/lib/sync"
  21. )
  22. type staticsServer struct {
  23. assetDir string
  24. assets map[string][]byte
  25. availableThemes []string
  26. mut sync.RWMutex
  27. theme string
  28. }
  29. func newStaticsServer(theme, assetDir string) *staticsServer {
  30. s := &staticsServer{
  31. assetDir: assetDir,
  32. assets: auto.Assets(),
  33. mut: sync.NewRWMutex(),
  34. theme: theme,
  35. }
  36. seen := make(map[string]struct{})
  37. // Load themes from compiled in assets.
  38. for file := range auto.Assets() {
  39. theme := strings.Split(file, "/")[0]
  40. if _, ok := seen[theme]; !ok {
  41. seen[theme] = struct{}{}
  42. s.availableThemes = append(s.availableThemes, theme)
  43. }
  44. }
  45. if assetDir != "" {
  46. // Load any extra themes from the asset override dir.
  47. for _, dir := range dirNames(assetDir) {
  48. if _, ok := seen[dir]; !ok {
  49. seen[dir] = struct{}{}
  50. s.availableThemes = append(s.availableThemes, dir)
  51. }
  52. }
  53. }
  54. return s
  55. }
  56. func (s *staticsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  57. switch r.URL.Path {
  58. case "/themes.json":
  59. s.serveThemes(w, r)
  60. default:
  61. s.serveAsset(w, r)
  62. }
  63. }
  64. func (s *staticsServer) serveAsset(w http.ResponseWriter, r *http.Request) {
  65. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  66. file := r.URL.Path
  67. if file[0] == '/' {
  68. file = file[1:]
  69. }
  70. if len(file) == 0 {
  71. file = "index.html"
  72. }
  73. s.mut.RLock()
  74. theme := s.theme
  75. s.mut.RUnlock()
  76. // Check for an override for the current theme.
  77. if s.assetDir != "" {
  78. p := filepath.Join(s.assetDir, theme, filepath.FromSlash(file))
  79. if _, err := os.Stat(p); err == nil {
  80. mtype := s.mimeTypeForFile(file)
  81. if len(mtype) != 0 {
  82. w.Header().Set("Content-Type", mtype)
  83. }
  84. http.ServeFile(w, r, p)
  85. return
  86. }
  87. }
  88. // Check for a compiled in asset for the current theme.
  89. bs, ok := s.assets[theme+"/"+file]
  90. if !ok {
  91. // Check for an overridden default asset.
  92. if s.assetDir != "" {
  93. p := filepath.Join(s.assetDir, config.DefaultTheme, filepath.FromSlash(file))
  94. if _, err := os.Stat(p); err == nil {
  95. mtype := s.mimeTypeForFile(file)
  96. if len(mtype) != 0 {
  97. w.Header().Set("Content-Type", mtype)
  98. }
  99. http.ServeFile(w, r, p)
  100. return
  101. }
  102. }
  103. // Check for a compiled in default asset.
  104. bs, ok = s.assets[config.DefaultTheme+"/"+file]
  105. if !ok {
  106. http.NotFound(w, r)
  107. return
  108. }
  109. }
  110. etag := fmt.Sprintf("%d", auto.Generated)
  111. modified := time.Unix(auto.Generated, 0).UTC()
  112. w.Header().Set("Last-Modified", modified.Format(http.TimeFormat))
  113. w.Header().Set("Etag", etag)
  114. if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil {
  115. if modified.Equal(t) || modified.Before(t) {
  116. w.WriteHeader(http.StatusNotModified)
  117. return
  118. }
  119. }
  120. if match := r.Header.Get("If-None-Match"); match != "" {
  121. if strings.Contains(match, etag) {
  122. w.WriteHeader(http.StatusNotModified)
  123. return
  124. }
  125. }
  126. mtype := s.mimeTypeForFile(file)
  127. if len(mtype) != 0 {
  128. w.Header().Set("Content-Type", mtype)
  129. }
  130. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  131. w.Header().Set("Content-Encoding", "gzip")
  132. } else {
  133. // ungzip if browser not send gzip accepted header
  134. var gr *gzip.Reader
  135. gr, _ = gzip.NewReader(bytes.NewReader(bs))
  136. bs, _ = ioutil.ReadAll(gr)
  137. gr.Close()
  138. }
  139. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  140. w.Write(bs)
  141. }
  142. func (s *staticsServer) serveThemes(w http.ResponseWriter, r *http.Request) {
  143. sendJSON(w, map[string][]string{
  144. "themes": s.availableThemes,
  145. })
  146. }
  147. func (s *staticsServer) mimeTypeForFile(file string) string {
  148. // We use a built in table of the common types since the system
  149. // TypeByExtension might be unreliable. But if we don't know, we delegate
  150. // to the system. All our files are UTF-8.
  151. ext := filepath.Ext(file)
  152. switch ext {
  153. case ".htm", ".html":
  154. return "text/html; charset=utf-8"
  155. case ".css":
  156. return "text/css; charset=utf-8"
  157. case ".js":
  158. return "application/javascript; charset=utf-8"
  159. case ".json":
  160. return "application/json; charset=utf-8"
  161. case ".png":
  162. return "image/png"
  163. case ".ttf":
  164. return "application/x-font-ttf"
  165. case ".woff":
  166. return "application/x-font-woff"
  167. case ".svg":
  168. return "image/svg+xml; charset=utf-8"
  169. default:
  170. return mime.TypeByExtension(ext)
  171. }
  172. }
  173. func (s *staticsServer) setTheme(theme string) {
  174. s.mut.Lock()
  175. s.theme = theme
  176. s.mut.Unlock()
  177. }
  178. func (s *staticsServer) String() string {
  179. return fmt.Sprintf("staticsServer@%p", s)
  180. }