api.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  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. "crypto/tls"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path/filepath"
  20. "reflect"
  21. "regexp"
  22. "runtime"
  23. "runtime/pprof"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "time"
  28. metrics "github.com/rcrowley/go-metrics"
  29. "github.com/thejerf/suture"
  30. "github.com/vitrun/qart/qr"
  31. "golang.org/x/crypto/bcrypt"
  32. "github.com/syncthing/syncthing/lib/build"
  33. "github.com/syncthing/syncthing/lib/config"
  34. "github.com/syncthing/syncthing/lib/connections"
  35. "github.com/syncthing/syncthing/lib/db"
  36. "github.com/syncthing/syncthing/lib/discover"
  37. "github.com/syncthing/syncthing/lib/events"
  38. "github.com/syncthing/syncthing/lib/fs"
  39. "github.com/syncthing/syncthing/lib/locations"
  40. "github.com/syncthing/syncthing/lib/logger"
  41. "github.com/syncthing/syncthing/lib/model"
  42. "github.com/syncthing/syncthing/lib/protocol"
  43. "github.com/syncthing/syncthing/lib/rand"
  44. "github.com/syncthing/syncthing/lib/sync"
  45. "github.com/syncthing/syncthing/lib/tlsutil"
  46. "github.com/syncthing/syncthing/lib/upgrade"
  47. "github.com/syncthing/syncthing/lib/ur"
  48. "github.com/syncthing/syncthing/lib/util"
  49. )
  50. // matches a bcrypt hash and not too much else
  51. var bcryptExpr = regexp.MustCompile(`^\$2[aby]\$\d+\$.{50,}`)
  52. const (
  53. DefaultEventMask = events.AllEvents &^ events.LocalChangeDetected &^ events.RemoteChangeDetected
  54. DiskEventMask = events.LocalChangeDetected | events.RemoteChangeDetected
  55. EventSubBufferSize = 1000
  56. defaultEventTimeout = time.Minute
  57. )
  58. type service struct {
  59. suture.Service
  60. id protocol.DeviceID
  61. cfg config.Wrapper
  62. statics *staticsServer
  63. model model.Model
  64. eventSubs map[events.EventType]events.BufferedSubscription
  65. eventSubsMut sync.Mutex
  66. evLogger events.Logger
  67. discoverer discover.CachingMux
  68. connectionsService connections.Service
  69. fss model.FolderSummaryService
  70. urService *ur.Service
  71. systemConfigMut sync.Mutex // serializes posts to /rest/system/config
  72. cpu Rater
  73. contr Controller
  74. noUpgrade bool
  75. tlsDefaultCommonName string
  76. configChanged chan struct{} // signals intentional listener close due to config change
  77. started chan string // signals startup complete by sending the listener address, for testing only
  78. startedOnce chan struct{} // the service has started successfully at least once
  79. startupErr error
  80. listenerAddr net.Addr
  81. guiErrors logger.Recorder
  82. systemLog logger.Recorder
  83. }
  84. type Rater interface {
  85. Rate() float64
  86. }
  87. type Controller interface {
  88. ExitUpgrading()
  89. Restart()
  90. Shutdown()
  91. }
  92. type Service interface {
  93. suture.Service
  94. config.Committer
  95. WaitForStart() error
  96. }
  97. func New(id protocol.DeviceID, cfg config.Wrapper, assetDir, tlsDefaultCommonName string, m model.Model, defaultSub, diskSub events.BufferedSubscription, evLogger events.Logger, discoverer discover.CachingMux, connectionsService connections.Service, urService *ur.Service, fss model.FolderSummaryService, errors, systemLog logger.Recorder, cpu Rater, contr Controller, noUpgrade bool) Service {
  98. s := &service{
  99. id: id,
  100. cfg: cfg,
  101. statics: newStaticsServer(cfg.GUI().Theme, assetDir),
  102. model: m,
  103. eventSubs: map[events.EventType]events.BufferedSubscription{
  104. DefaultEventMask: defaultSub,
  105. DiskEventMask: diskSub,
  106. },
  107. eventSubsMut: sync.NewMutex(),
  108. evLogger: evLogger,
  109. discoverer: discoverer,
  110. connectionsService: connectionsService,
  111. fss: fss,
  112. urService: urService,
  113. systemConfigMut: sync.NewMutex(),
  114. guiErrors: errors,
  115. systemLog: systemLog,
  116. cpu: cpu,
  117. contr: contr,
  118. noUpgrade: noUpgrade,
  119. tlsDefaultCommonName: tlsDefaultCommonName,
  120. configChanged: make(chan struct{}),
  121. startedOnce: make(chan struct{}),
  122. }
  123. s.Service = util.AsService(s.serve)
  124. return s
  125. }
  126. func (s *service) WaitForStart() error {
  127. <-s.startedOnce
  128. return s.startupErr
  129. }
  130. func (s *service) getListener(guiCfg config.GUIConfiguration) (net.Listener, error) {
  131. httpsCertFile := locations.Get(locations.HTTPSCertFile)
  132. httpsKeyFile := locations.Get(locations.HTTPSKeyFile)
  133. cert, err := tls.LoadX509KeyPair(httpsCertFile, httpsKeyFile)
  134. if err != nil {
  135. l.Infoln("Loading HTTPS certificate:", err)
  136. l.Infoln("Creating new HTTPS certificate")
  137. // When generating the HTTPS certificate, use the system host name per
  138. // default. If that isn't available, use the "syncthing" default.
  139. var name string
  140. name, err = os.Hostname()
  141. if err != nil {
  142. name = s.tlsDefaultCommonName
  143. }
  144. cert, err = tlsutil.NewCertificate(httpsCertFile, httpsKeyFile, name)
  145. }
  146. if err != nil {
  147. return nil, err
  148. }
  149. tlsCfg := tlsutil.SecureDefault()
  150. tlsCfg.Certificates = []tls.Certificate{cert}
  151. if guiCfg.Network() == "unix" {
  152. // When listening on a UNIX socket we should unlink before bind,
  153. // lest we get a "bind: address already in use". We don't
  154. // particularly care if this succeeds or not.
  155. os.Remove(guiCfg.Address())
  156. }
  157. rawListener, err := net.Listen(guiCfg.Network(), guiCfg.Address())
  158. if err != nil {
  159. return nil, err
  160. }
  161. listener := &tlsutil.DowngradingListener{
  162. Listener: rawListener,
  163. TLSConfig: tlsCfg,
  164. }
  165. return listener, nil
  166. }
  167. func sendJSON(w http.ResponseWriter, jsonObject interface{}) {
  168. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  169. // Marshalling might fail, in which case we should return a 500 with the
  170. // actual error.
  171. bs, err := json.MarshalIndent(jsonObject, "", " ")
  172. if err != nil {
  173. // This Marshal() can't fail though.
  174. bs, _ = json.Marshal(map[string]string{"error": err.Error()})
  175. http.Error(w, string(bs), http.StatusInternalServerError)
  176. return
  177. }
  178. fmt.Fprintf(w, "%s\n", bs)
  179. }
  180. func (s *service) serve(stop chan struct{}) {
  181. listener, err := s.getListener(s.cfg.GUI())
  182. if err != nil {
  183. select {
  184. case <-s.startedOnce:
  185. // We let this be a loud user-visible warning as it may be the only
  186. // indication they get that the GUI won't be available.
  187. l.Warnln("Starting API/GUI:", err)
  188. default:
  189. // This is during initialization. A failure here should be fatal
  190. // as there will be no way for the user to communicate with us
  191. // otherwise anyway.
  192. s.startupErr = err
  193. close(s.startedOnce)
  194. }
  195. return
  196. }
  197. if listener == nil {
  198. // Not much we can do here other than exit quickly. The supervisor
  199. // will log an error at some point.
  200. return
  201. }
  202. s.listenerAddr = listener.Addr()
  203. defer listener.Close()
  204. s.cfg.Subscribe(s)
  205. defer s.cfg.Unsubscribe(s)
  206. // The GET handlers
  207. getRestMux := http.NewServeMux()
  208. getRestMux.HandleFunc("/rest/db/completion", s.getDBCompletion) // device folder
  209. getRestMux.HandleFunc("/rest/db/file", s.getDBFile) // folder file
  210. getRestMux.HandleFunc("/rest/db/ignores", s.getDBIgnores) // folder
  211. getRestMux.HandleFunc("/rest/db/need", s.getDBNeed) // folder [perpage] [page]
  212. getRestMux.HandleFunc("/rest/db/remoteneed", s.getDBRemoteNeed) // device folder [perpage] [page]
  213. getRestMux.HandleFunc("/rest/db/localchanged", s.getDBLocalChanged) // folder
  214. getRestMux.HandleFunc("/rest/db/status", s.getDBStatus) // folder
  215. getRestMux.HandleFunc("/rest/db/browse", s.getDBBrowse) // folder [prefix] [dirsonly] [levels]
  216. getRestMux.HandleFunc("/rest/folder/versions", s.getFolderVersions) // folder
  217. getRestMux.HandleFunc("/rest/folder/errors", s.getFolderErrors) // folder
  218. getRestMux.HandleFunc("/rest/folder/pullerrors", s.getFolderErrors) // folder (deprecated)
  219. getRestMux.HandleFunc("/rest/events", s.getIndexEvents) // [since] [limit] [timeout] [events]
  220. getRestMux.HandleFunc("/rest/events/disk", s.getDiskEvents) // [since] [limit] [timeout]
  221. getRestMux.HandleFunc("/rest/stats/device", s.getDeviceStats) // -
  222. getRestMux.HandleFunc("/rest/stats/folder", s.getFolderStats) // -
  223. getRestMux.HandleFunc("/rest/svc/deviceid", s.getDeviceID) // id
  224. getRestMux.HandleFunc("/rest/svc/lang", s.getLang) // -
  225. getRestMux.HandleFunc("/rest/svc/report", s.getReport) // -
  226. getRestMux.HandleFunc("/rest/svc/random/string", s.getRandomString) // [length]
  227. getRestMux.HandleFunc("/rest/system/browse", s.getSystemBrowse) // current
  228. getRestMux.HandleFunc("/rest/system/config", s.getSystemConfig) // -
  229. getRestMux.HandleFunc("/rest/system/config/insync", s.getSystemConfigInsync) // -
  230. getRestMux.HandleFunc("/rest/system/connections", s.getSystemConnections) // -
  231. getRestMux.HandleFunc("/rest/system/discovery", s.getSystemDiscovery) // -
  232. getRestMux.HandleFunc("/rest/system/error", s.getSystemError) // -
  233. getRestMux.HandleFunc("/rest/system/ping", s.restPing) // -
  234. getRestMux.HandleFunc("/rest/system/status", s.getSystemStatus) // -
  235. getRestMux.HandleFunc("/rest/system/upgrade", s.getSystemUpgrade) // -
  236. getRestMux.HandleFunc("/rest/system/version", s.getSystemVersion) // -
  237. getRestMux.HandleFunc("/rest/system/debug", s.getSystemDebug) // -
  238. getRestMux.HandleFunc("/rest/system/log", s.getSystemLog) // [since]
  239. getRestMux.HandleFunc("/rest/system/log.txt", s.getSystemLogTxt) // [since]
  240. // The POST handlers
  241. postRestMux := http.NewServeMux()
  242. postRestMux.HandleFunc("/rest/db/prio", s.postDBPrio) // folder file [perpage] [page]
  243. postRestMux.HandleFunc("/rest/db/ignores", s.postDBIgnores) // folder
  244. postRestMux.HandleFunc("/rest/db/override", s.postDBOverride) // folder
  245. postRestMux.HandleFunc("/rest/db/revert", s.postDBRevert) // folder
  246. postRestMux.HandleFunc("/rest/db/scan", s.postDBScan) // folder [sub...] [delay]
  247. postRestMux.HandleFunc("/rest/folder/versions", s.postFolderVersionsRestore) // folder <body>
  248. postRestMux.HandleFunc("/rest/system/config", s.postSystemConfig) // <body>
  249. postRestMux.HandleFunc("/rest/system/error", s.postSystemError) // <body>
  250. postRestMux.HandleFunc("/rest/system/error/clear", s.postSystemErrorClear) // -
  251. postRestMux.HandleFunc("/rest/system/ping", s.restPing) // -
  252. postRestMux.HandleFunc("/rest/system/reset", s.postSystemReset) // [folder]
  253. postRestMux.HandleFunc("/rest/system/restart", s.postSystemRestart) // -
  254. postRestMux.HandleFunc("/rest/system/shutdown", s.postSystemShutdown) // -
  255. postRestMux.HandleFunc("/rest/system/upgrade", s.postSystemUpgrade) // -
  256. postRestMux.HandleFunc("/rest/system/pause", s.makeDevicePauseHandler(true)) // [device]
  257. postRestMux.HandleFunc("/rest/system/resume", s.makeDevicePauseHandler(false)) // [device]
  258. postRestMux.HandleFunc("/rest/system/debug", s.postSystemDebug) // [enable] [disable]
  259. // Debug endpoints, not for general use
  260. debugMux := http.NewServeMux()
  261. debugMux.HandleFunc("/rest/debug/peerCompletion", s.getPeerCompletion)
  262. debugMux.HandleFunc("/rest/debug/httpmetrics", s.getSystemHTTPMetrics)
  263. debugMux.HandleFunc("/rest/debug/cpuprof", s.getCPUProf) // duration
  264. debugMux.HandleFunc("/rest/debug/heapprof", s.getHeapProf)
  265. debugMux.HandleFunc("/rest/debug/support", s.getSupportBundle)
  266. getRestMux.Handle("/rest/debug/", s.whenDebugging(debugMux))
  267. // A handler that splits requests between the two above and disables
  268. // caching
  269. restMux := noCacheMiddleware(metricsMiddleware(getPostHandler(getRestMux, postRestMux)))
  270. // The main routing handler
  271. mux := http.NewServeMux()
  272. mux.Handle("/rest/", restMux)
  273. mux.HandleFunc("/qr/", s.getQR)
  274. // Serve compiled in assets unless an asset directory was set (for development)
  275. mux.Handle("/", s.statics)
  276. // Handle the special meta.js path
  277. mux.HandleFunc("/meta.js", s.getJSMetadata)
  278. guiCfg := s.cfg.GUI()
  279. // Wrap everything in CSRF protection. The /rest prefix should be
  280. // protected, other requests will grant cookies.
  281. var handler http.Handler = newCsrfManager(s.id.String()[:5], "/rest", guiCfg, mux, locations.Get(locations.CsrfTokens))
  282. // Add our version and ID as a header to responses
  283. handler = withDetailsMiddleware(s.id, handler)
  284. // Wrap everything in basic auth, if user/password is set.
  285. if guiCfg.IsAuthEnabled() {
  286. handler = basicAuthAndSessionMiddleware("sessionid-"+s.id.String()[:5], guiCfg, s.cfg.LDAP(), handler, s.evLogger)
  287. }
  288. // Redirect to HTTPS if we are supposed to
  289. if guiCfg.UseTLS() {
  290. handler = redirectToHTTPSMiddleware(handler)
  291. }
  292. // Add the CORS handling
  293. handler = corsMiddleware(handler, guiCfg.InsecureAllowFrameLoading)
  294. if addressIsLocalhost(guiCfg.Address()) && !guiCfg.InsecureSkipHostCheck {
  295. // Verify source host
  296. handler = localhostMiddleware(handler)
  297. }
  298. handler = debugMiddleware(handler)
  299. srv := http.Server{
  300. Handler: handler,
  301. // ReadTimeout must be longer than SyncthingController $scope.refresh
  302. // interval to avoid HTTP keepalive/GUI refresh race.
  303. ReadTimeout: 15 * time.Second,
  304. // Prevent the HTTP server from logging stuff on its own. The things we
  305. // care about we log ourselves from the handlers.
  306. ErrorLog: log.New(ioutil.Discard, "", 0),
  307. }
  308. l.Infoln("GUI and API listening on", listener.Addr())
  309. l.Infoln("Access the GUI via the following URL:", guiCfg.URL())
  310. if s.started != nil {
  311. // only set when run by the tests
  312. s.started <- listener.Addr().String()
  313. }
  314. // Indicate successful initial startup, to ourselves and to interested
  315. // listeners (i.e. the thing that starts the browser).
  316. select {
  317. case <-s.startedOnce:
  318. default:
  319. close(s.startedOnce)
  320. }
  321. // Serve in the background
  322. serveError := make(chan error, 1)
  323. go func() {
  324. serveError <- srv.Serve(listener)
  325. }()
  326. // Wait for stop, restart or error signals
  327. select {
  328. case <-stop:
  329. // Shutting down permanently
  330. l.Debugln("shutting down (stop)")
  331. case <-s.configChanged:
  332. // Soft restart due to configuration change
  333. l.Debugln("restarting (config changed)")
  334. case <-serveError:
  335. // Restart due to listen/serve failure
  336. l.Warnln("GUI/API:", err, "(restarting)")
  337. }
  338. srv.Close()
  339. }
  340. // Complete implements suture.IsCompletable, which signifies to the supervisor
  341. // whether to stop restarting the service.
  342. func (s *service) Complete() bool {
  343. select {
  344. case <-s.startedOnce:
  345. return s.startupErr != nil
  346. default:
  347. }
  348. return false
  349. }
  350. func (s *service) String() string {
  351. return fmt.Sprintf("api.service@%p", s)
  352. }
  353. func (s *service) VerifyConfiguration(from, to config.Configuration) error {
  354. if to.GUI.Network() != "tcp" {
  355. return nil
  356. }
  357. _, err := net.ResolveTCPAddr("tcp", to.GUI.Address())
  358. return err
  359. }
  360. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  361. // No action required when this changes, so mask the fact that it changed at all.
  362. from.GUI.Debugging = to.GUI.Debugging
  363. if to.GUI == from.GUI {
  364. return true
  365. }
  366. if to.GUI.Theme != from.GUI.Theme {
  367. s.statics.setTheme(to.GUI.Theme)
  368. }
  369. // Tell the serve loop to restart
  370. s.configChanged <- struct{}{}
  371. return true
  372. }
  373. func getPostHandler(get, post http.Handler) http.Handler {
  374. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  375. switch r.Method {
  376. case "GET":
  377. get.ServeHTTP(w, r)
  378. case "POST":
  379. post.ServeHTTP(w, r)
  380. default:
  381. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  382. }
  383. })
  384. }
  385. func debugMiddleware(h http.Handler) http.Handler {
  386. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  387. t0 := time.Now()
  388. h.ServeHTTP(w, r)
  389. if shouldDebugHTTP() {
  390. ms := 1000 * time.Since(t0).Seconds()
  391. // The variable `w` is most likely a *http.response, which we can't do
  392. // much with since it's a non exported type. We can however peek into
  393. // it with reflection to get at the status code and number of bytes
  394. // written.
  395. var status, written int64
  396. if rw := reflect.Indirect(reflect.ValueOf(w)); rw.IsValid() && rw.Kind() == reflect.Struct {
  397. if rf := rw.FieldByName("status"); rf.IsValid() && rf.Kind() == reflect.Int {
  398. status = rf.Int()
  399. }
  400. if rf := rw.FieldByName("written"); rf.IsValid() && rf.Kind() == reflect.Int64 {
  401. written = rf.Int()
  402. }
  403. }
  404. l.Debugf("http: %s %q: status %d, %d bytes in %.02f ms", r.Method, r.URL.String(), status, written, ms)
  405. }
  406. })
  407. }
  408. func corsMiddleware(next http.Handler, allowFrameLoading bool) http.Handler {
  409. // Handle CORS headers and CORS OPTIONS request.
  410. // CORS OPTIONS request are typically sent by browser during AJAX preflight
  411. // when the browser initiate a POST request.
  412. //
  413. // As the OPTIONS request is unauthorized, this handler must be the first
  414. // of the chain (hence added at the end).
  415. //
  416. // See https://www.w3.org/TR/cors/ for details.
  417. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  418. // Process OPTIONS requests
  419. if r.Method == "OPTIONS" {
  420. // Add a generous access-control-allow-origin header for CORS requests
  421. w.Header().Add("Access-Control-Allow-Origin", "*")
  422. // Only GET/POST Methods are supported
  423. w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
  424. // Only these headers can be set
  425. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
  426. // The request is meant to be cached 10 minutes
  427. w.Header().Set("Access-Control-Max-Age", "600")
  428. // Indicate that no content will be returned
  429. w.WriteHeader(204)
  430. return
  431. }
  432. // Other security related headers that should be present.
  433. // https://www.owasp.org/index.php/Security_Headers
  434. if !allowFrameLoading {
  435. // We don't want to be rendered in an <iframe>,
  436. // <frame> or <object>. (Unless we do it ourselves.
  437. // This is also an escape hatch for people who serve
  438. // Syncthing GUI as part of their own website
  439. // through a proxy, so they don't need to set the
  440. // allowFrameLoading bool.)
  441. w.Header().Set("X-Frame-Options", "SAMEORIGIN")
  442. }
  443. // If the browser senses an XSS attack it's allowed to take
  444. // action. (How this would not always be the default I
  445. // don't fully understand.)
  446. w.Header().Set("X-XSS-Protection", "1; mode=block")
  447. // Our content type headers are correct. Don't guess.
  448. w.Header().Set("X-Content-Type-Options", "nosniff")
  449. // For everything else, pass to the next handler
  450. next.ServeHTTP(w, r)
  451. })
  452. }
  453. func metricsMiddleware(h http.Handler) http.Handler {
  454. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  455. t := metrics.GetOrRegisterTimer(r.URL.Path, nil)
  456. t0 := time.Now()
  457. h.ServeHTTP(w, r)
  458. t.UpdateSince(t0)
  459. })
  460. }
  461. func redirectToHTTPSMiddleware(h http.Handler) http.Handler {
  462. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  463. if r.TLS == nil {
  464. // Redirect HTTP requests to HTTPS
  465. r.URL.Host = r.Host
  466. r.URL.Scheme = "https"
  467. http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
  468. } else {
  469. h.ServeHTTP(w, r)
  470. }
  471. })
  472. }
  473. func noCacheMiddleware(h http.Handler) http.Handler {
  474. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  475. w.Header().Set("Cache-Control", "max-age=0, no-cache, no-store")
  476. w.Header().Set("Expires", time.Now().UTC().Format(http.TimeFormat))
  477. w.Header().Set("Pragma", "no-cache")
  478. h.ServeHTTP(w, r)
  479. })
  480. }
  481. func withDetailsMiddleware(id protocol.DeviceID, h http.Handler) http.Handler {
  482. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  483. w.Header().Set("X-Syncthing-Version", build.Version)
  484. w.Header().Set("X-Syncthing-ID", id.String())
  485. h.ServeHTTP(w, r)
  486. })
  487. }
  488. func localhostMiddleware(h http.Handler) http.Handler {
  489. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  490. if addressIsLocalhost(r.Host) {
  491. h.ServeHTTP(w, r)
  492. return
  493. }
  494. http.Error(w, "Host check error", http.StatusForbidden)
  495. })
  496. }
  497. func (s *service) whenDebugging(h http.Handler) http.Handler {
  498. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  499. if s.cfg.GUI().Debugging {
  500. h.ServeHTTP(w, r)
  501. return
  502. }
  503. http.Error(w, "Debugging disabled", http.StatusForbidden)
  504. })
  505. }
  506. func (s *service) restPing(w http.ResponseWriter, r *http.Request) {
  507. sendJSON(w, map[string]string{"ping": "pong"})
  508. }
  509. func (s *service) getJSMetadata(w http.ResponseWriter, r *http.Request) {
  510. meta, _ := json.Marshal(map[string]string{
  511. "deviceID": s.id.String(),
  512. })
  513. w.Header().Set("Content-Type", "application/javascript")
  514. fmt.Fprintf(w, "var metadata = %s;\n", meta)
  515. }
  516. func (s *service) getSystemVersion(w http.ResponseWriter, r *http.Request) {
  517. sendJSON(w, map[string]interface{}{
  518. "version": build.Version,
  519. "codename": build.Codename,
  520. "longVersion": build.LongVersion,
  521. "os": runtime.GOOS,
  522. "arch": runtime.GOARCH,
  523. "isBeta": build.IsBeta,
  524. "isCandidate": build.IsCandidate,
  525. "isRelease": build.IsRelease,
  526. })
  527. }
  528. func (s *service) getSystemDebug(w http.ResponseWriter, r *http.Request) {
  529. names := l.Facilities()
  530. enabled := l.FacilityDebugging()
  531. sort.Strings(enabled)
  532. sendJSON(w, map[string]interface{}{
  533. "facilities": names,
  534. "enabled": enabled,
  535. })
  536. }
  537. func (s *service) postSystemDebug(w http.ResponseWriter, r *http.Request) {
  538. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  539. q := r.URL.Query()
  540. for _, f := range strings.Split(q.Get("enable"), ",") {
  541. if f == "" || l.ShouldDebug(f) {
  542. continue
  543. }
  544. l.SetDebug(f, true)
  545. l.Infof("Enabled debug data for %q", f)
  546. }
  547. for _, f := range strings.Split(q.Get("disable"), ",") {
  548. if f == "" || !l.ShouldDebug(f) {
  549. continue
  550. }
  551. l.SetDebug(f, false)
  552. l.Infof("Disabled debug data for %q", f)
  553. }
  554. }
  555. func (s *service) getDBBrowse(w http.ResponseWriter, r *http.Request) {
  556. qs := r.URL.Query()
  557. folder := qs.Get("folder")
  558. prefix := qs.Get("prefix")
  559. dirsonly := qs.Get("dirsonly") != ""
  560. levels, err := strconv.Atoi(qs.Get("levels"))
  561. if err != nil {
  562. levels = -1
  563. }
  564. sendJSON(w, s.model.GlobalDirectoryTree(folder, prefix, levels, dirsonly))
  565. }
  566. func (s *service) getDBCompletion(w http.ResponseWriter, r *http.Request) {
  567. var qs = r.URL.Query()
  568. var folder = qs.Get("folder")
  569. var deviceStr = qs.Get("device")
  570. device, err := protocol.DeviceIDFromString(deviceStr)
  571. if err != nil {
  572. http.Error(w, err.Error(), 500)
  573. return
  574. }
  575. sendJSON(w, s.model.Completion(device, folder).Map())
  576. }
  577. func (s *service) getDBStatus(w http.ResponseWriter, r *http.Request) {
  578. qs := r.URL.Query()
  579. folder := qs.Get("folder")
  580. if sum, err := s.fss.Summary(folder); err != nil {
  581. http.Error(w, err.Error(), http.StatusNotFound)
  582. } else {
  583. sendJSON(w, sum)
  584. }
  585. }
  586. func (s *service) postDBOverride(w http.ResponseWriter, r *http.Request) {
  587. var qs = r.URL.Query()
  588. var folder = qs.Get("folder")
  589. go s.model.Override(folder)
  590. }
  591. func (s *service) postDBRevert(w http.ResponseWriter, r *http.Request) {
  592. var qs = r.URL.Query()
  593. var folder = qs.Get("folder")
  594. go s.model.Revert(folder)
  595. }
  596. func getPagingParams(qs url.Values) (int, int) {
  597. page, err := strconv.Atoi(qs.Get("page"))
  598. if err != nil || page < 1 {
  599. page = 1
  600. }
  601. perpage, err := strconv.Atoi(qs.Get("perpage"))
  602. if err != nil || perpage < 1 {
  603. perpage = 1 << 16
  604. }
  605. return page, perpage
  606. }
  607. func (s *service) getDBNeed(w http.ResponseWriter, r *http.Request) {
  608. qs := r.URL.Query()
  609. folder := qs.Get("folder")
  610. page, perpage := getPagingParams(qs)
  611. progress, queued, rest := s.model.NeedFolderFiles(folder, page, perpage)
  612. // Convert the struct to a more loose structure, and inject the size.
  613. sendJSON(w, map[string]interface{}{
  614. "progress": toJsonFileInfoSlice(progress),
  615. "queued": toJsonFileInfoSlice(queued),
  616. "rest": toJsonFileInfoSlice(rest),
  617. "page": page,
  618. "perpage": perpage,
  619. })
  620. }
  621. func (s *service) getDBRemoteNeed(w http.ResponseWriter, r *http.Request) {
  622. qs := r.URL.Query()
  623. folder := qs.Get("folder")
  624. device := qs.Get("device")
  625. deviceID, err := protocol.DeviceIDFromString(device)
  626. if err != nil {
  627. http.Error(w, err.Error(), 500)
  628. return
  629. }
  630. page, perpage := getPagingParams(qs)
  631. if files, err := s.model.RemoteNeedFolderFiles(deviceID, folder, page, perpage); err != nil {
  632. http.Error(w, err.Error(), http.StatusNotFound)
  633. } else {
  634. sendJSON(w, map[string]interface{}{
  635. "files": toJsonFileInfoSlice(files),
  636. "page": page,
  637. "perpage": perpage,
  638. })
  639. }
  640. }
  641. func (s *service) getDBLocalChanged(w http.ResponseWriter, r *http.Request) {
  642. qs := r.URL.Query()
  643. folder := qs.Get("folder")
  644. page, perpage := getPagingParams(qs)
  645. files := s.model.LocalChangedFiles(folder, page, perpage)
  646. sendJSON(w, map[string]interface{}{
  647. "files": toJsonFileInfoSlice(files),
  648. "page": page,
  649. "perpage": perpage,
  650. })
  651. }
  652. func (s *service) getSystemConnections(w http.ResponseWriter, r *http.Request) {
  653. sendJSON(w, s.model.ConnectionStats())
  654. }
  655. func (s *service) getDeviceStats(w http.ResponseWriter, r *http.Request) {
  656. sendJSON(w, s.model.DeviceStatistics())
  657. }
  658. func (s *service) getFolderStats(w http.ResponseWriter, r *http.Request) {
  659. sendJSON(w, s.model.FolderStatistics())
  660. }
  661. func (s *service) getDBFile(w http.ResponseWriter, r *http.Request) {
  662. qs := r.URL.Query()
  663. folder := qs.Get("folder")
  664. file := qs.Get("file")
  665. gf, gfOk := s.model.CurrentGlobalFile(folder, file)
  666. lf, lfOk := s.model.CurrentFolderFile(folder, file)
  667. if !(gfOk || lfOk) {
  668. // This file for sure does not exist.
  669. http.Error(w, "No such object in the index", http.StatusNotFound)
  670. return
  671. }
  672. av := s.model.Availability(folder, gf, protocol.BlockInfo{})
  673. sendJSON(w, map[string]interface{}{
  674. "global": jsonFileInfo(gf),
  675. "local": jsonFileInfo(lf),
  676. "availability": av,
  677. })
  678. }
  679. func (s *service) getSystemConfig(w http.ResponseWriter, r *http.Request) {
  680. sendJSON(w, s.cfg.RawCopy())
  681. }
  682. func (s *service) postSystemConfig(w http.ResponseWriter, r *http.Request) {
  683. s.systemConfigMut.Lock()
  684. defer s.systemConfigMut.Unlock()
  685. to, err := config.ReadJSON(r.Body, s.id)
  686. r.Body.Close()
  687. if err != nil {
  688. l.Warnln("Decoding posted config:", err)
  689. http.Error(w, err.Error(), http.StatusBadRequest)
  690. return
  691. }
  692. if to.GUI.Password != s.cfg.GUI().Password {
  693. if to.GUI.Password != "" && !bcryptExpr.MatchString(to.GUI.Password) {
  694. hash, err := bcrypt.GenerateFromPassword([]byte(to.GUI.Password), 0)
  695. if err != nil {
  696. l.Warnln("bcrypting password:", err)
  697. http.Error(w, err.Error(), http.StatusInternalServerError)
  698. return
  699. }
  700. to.GUI.Password = string(hash)
  701. }
  702. }
  703. // Activate and save. Wait for the configuration to become active before
  704. // completing the request.
  705. if wg, err := s.cfg.Replace(to); err != nil {
  706. l.Warnln("Replacing config:", err)
  707. http.Error(w, err.Error(), http.StatusInternalServerError)
  708. return
  709. } else {
  710. wg.Wait()
  711. }
  712. if err := s.cfg.Save(); err != nil {
  713. l.Warnln("Saving config:", err)
  714. http.Error(w, err.Error(), http.StatusInternalServerError)
  715. return
  716. }
  717. }
  718. func (s *service) getSystemConfigInsync(w http.ResponseWriter, r *http.Request) {
  719. sendJSON(w, map[string]bool{"configInSync": !s.cfg.RequiresRestart()})
  720. }
  721. func (s *service) postSystemRestart(w http.ResponseWriter, r *http.Request) {
  722. s.flushResponse(`{"ok": "restarting"}`, w)
  723. go s.contr.Restart()
  724. }
  725. func (s *service) postSystemReset(w http.ResponseWriter, r *http.Request) {
  726. var qs = r.URL.Query()
  727. folder := qs.Get("folder")
  728. if len(folder) > 0 {
  729. if _, ok := s.cfg.Folders()[folder]; !ok {
  730. http.Error(w, "Invalid folder ID", 500)
  731. return
  732. }
  733. }
  734. if len(folder) == 0 {
  735. // Reset all folders.
  736. for folder := range s.cfg.Folders() {
  737. s.model.ResetFolder(folder)
  738. }
  739. s.flushResponse(`{"ok": "resetting database"}`, w)
  740. } else {
  741. // Reset a specific folder, assuming it's supposed to exist.
  742. s.model.ResetFolder(folder)
  743. s.flushResponse(`{"ok": "resetting folder `+folder+`"}`, w)
  744. }
  745. go s.contr.Restart()
  746. }
  747. func (s *service) postSystemShutdown(w http.ResponseWriter, r *http.Request) {
  748. s.flushResponse(`{"ok": "shutting down"}`, w)
  749. go s.contr.Shutdown()
  750. }
  751. func (s *service) flushResponse(resp string, w http.ResponseWriter) {
  752. w.Write([]byte(resp + "\n"))
  753. f := w.(http.Flusher)
  754. f.Flush()
  755. }
  756. func (s *service) getSystemStatus(w http.ResponseWriter, r *http.Request) {
  757. var m runtime.MemStats
  758. runtime.ReadMemStats(&m)
  759. tilde, _ := fs.ExpandTilde("~")
  760. res := make(map[string]interface{})
  761. res["myID"] = s.id.String()
  762. res["goroutines"] = runtime.NumGoroutine()
  763. res["alloc"] = m.Alloc
  764. res["sys"] = m.Sys - m.HeapReleased
  765. res["tilde"] = tilde
  766. if s.cfg.Options().LocalAnnEnabled || s.cfg.Options().GlobalAnnEnabled {
  767. res["discoveryEnabled"] = true
  768. discoErrors := make(map[string]string)
  769. discoMethods := 0
  770. for disco, err := range s.discoverer.ChildErrors() {
  771. discoMethods++
  772. if err != nil {
  773. discoErrors[disco] = err.Error()
  774. }
  775. }
  776. res["discoveryMethods"] = discoMethods
  777. res["discoveryErrors"] = discoErrors
  778. }
  779. res["connectionServiceStatus"] = s.connectionsService.ListenerStatus()
  780. res["lastDialStatus"] = s.connectionsService.ConnectionStatus()
  781. // cpuUsage.Rate() is in milliseconds per second, so dividing by ten
  782. // gives us percent
  783. res["cpuPercent"] = s.cpu.Rate() / 10 / float64(runtime.NumCPU())
  784. res["pathSeparator"] = string(filepath.Separator)
  785. res["urVersionMax"] = ur.Version
  786. res["uptime"] = s.urService.UptimeS()
  787. res["startTime"] = ur.StartTime
  788. res["guiAddressOverridden"] = s.cfg.GUI().IsOverridden()
  789. res["guiAddressUsed"] = s.listenerAddr.String()
  790. sendJSON(w, res)
  791. }
  792. func (s *service) getSystemError(w http.ResponseWriter, r *http.Request) {
  793. sendJSON(w, map[string][]logger.Line{
  794. "errors": s.guiErrors.Since(time.Time{}),
  795. })
  796. }
  797. func (s *service) postSystemError(w http.ResponseWriter, r *http.Request) {
  798. bs, _ := ioutil.ReadAll(r.Body)
  799. r.Body.Close()
  800. l.Warnln(string(bs))
  801. }
  802. func (s *service) postSystemErrorClear(w http.ResponseWriter, r *http.Request) {
  803. s.guiErrors.Clear()
  804. }
  805. func (s *service) getSystemLog(w http.ResponseWriter, r *http.Request) {
  806. q := r.URL.Query()
  807. since, err := time.Parse(time.RFC3339, q.Get("since"))
  808. if err != nil {
  809. l.Debugln(err)
  810. }
  811. sendJSON(w, map[string][]logger.Line{
  812. "messages": s.systemLog.Since(since),
  813. })
  814. }
  815. func (s *service) getSystemLogTxt(w http.ResponseWriter, r *http.Request) {
  816. q := r.URL.Query()
  817. since, err := time.Parse(time.RFC3339, q.Get("since"))
  818. if err != nil {
  819. l.Debugln(err)
  820. }
  821. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  822. for _, line := range s.systemLog.Since(since) {
  823. fmt.Fprintf(w, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  824. }
  825. }
  826. type fileEntry struct {
  827. name string
  828. data []byte
  829. }
  830. func (s *service) getSupportBundle(w http.ResponseWriter, r *http.Request) {
  831. var files []fileEntry
  832. // Redacted configuration as a JSON
  833. if jsonConfig, err := json.MarshalIndent(getRedactedConfig(s), "", " "); err != nil {
  834. l.Warnln("Support bundle: failed to create config.json:", err)
  835. } else {
  836. files = append(files, fileEntry{name: "config.json.txt", data: jsonConfig})
  837. }
  838. // Log as a text
  839. var buflog bytes.Buffer
  840. for _, line := range s.systemLog.Since(time.Time{}) {
  841. fmt.Fprintf(&buflog, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  842. }
  843. files = append(files, fileEntry{name: "log-inmemory.txt", data: buflog.Bytes()})
  844. // Errors as a JSON
  845. if errs := s.guiErrors.Since(time.Time{}); len(errs) > 0 {
  846. if jsonError, err := json.MarshalIndent(errs, "", " "); err != nil {
  847. l.Warnln("Support bundle: failed to create errors.json:", err)
  848. } else {
  849. files = append(files, fileEntry{name: "errors.json.txt", data: jsonError})
  850. }
  851. }
  852. // Panic files
  853. if panicFiles, err := filepath.Glob(filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), "panic*")); err == nil {
  854. for _, f := range panicFiles {
  855. if panicFile, err := ioutil.ReadFile(f); err != nil {
  856. l.Warnf("Support bundle: failed to load %s: %s", filepath.Base(f), err)
  857. } else {
  858. files = append(files, fileEntry{name: filepath.Base(f), data: panicFile})
  859. }
  860. }
  861. }
  862. // Archived log (default on Windows)
  863. if logFile, err := ioutil.ReadFile(locations.Get(locations.LogFile)); err == nil {
  864. files = append(files, fileEntry{name: "log-ondisk.txt", data: logFile})
  865. }
  866. // Version and platform information as a JSON
  867. if versionPlatform, err := json.MarshalIndent(map[string]string{
  868. "now": time.Now().Format(time.RFC3339),
  869. "version": build.Version,
  870. "codename": build.Codename,
  871. "longVersion": build.LongVersion,
  872. "os": runtime.GOOS,
  873. "arch": runtime.GOARCH,
  874. }, "", " "); err == nil {
  875. files = append(files, fileEntry{name: "version-platform.json.txt", data: versionPlatform})
  876. } else {
  877. l.Warnln("Failed to create versionPlatform.json: ", err)
  878. }
  879. // Report Data as a JSON
  880. if usageReportingData, err := json.MarshalIndent(s.urService.ReportData(), "", " "); err != nil {
  881. l.Warnln("Support bundle: failed to create versionPlatform.json:", err)
  882. } else {
  883. files = append(files, fileEntry{name: "usage-reporting.json.txt", data: usageReportingData})
  884. }
  885. // Heap and CPU Proofs as a pprof extension
  886. var heapBuffer, cpuBuffer bytes.Buffer
  887. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  888. runtime.GC()
  889. if err := pprof.WriteHeapProfile(&heapBuffer); err == nil {
  890. files = append(files, fileEntry{name: filename, data: heapBuffer.Bytes()})
  891. }
  892. const duration = 4 * time.Second
  893. filename = fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  894. if err := pprof.StartCPUProfile(&cpuBuffer); err == nil {
  895. time.Sleep(duration)
  896. pprof.StopCPUProfile()
  897. files = append(files, fileEntry{name: filename, data: cpuBuffer.Bytes()})
  898. }
  899. // Add buffer files to buffer zip
  900. var zipFilesBuffer bytes.Buffer
  901. if err := writeZip(&zipFilesBuffer, files); err != nil {
  902. l.Warnln("Support bundle: failed to create support bundle zip:", err)
  903. http.Error(w, err.Error(), http.StatusInternalServerError)
  904. return
  905. }
  906. // Set zip file name and path
  907. zipFileName := fmt.Sprintf("support-bundle-%s-%s.zip", s.id.Short().String(), time.Now().Format("2006-01-02T150405"))
  908. zipFilePath := filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), zipFileName)
  909. // Write buffer zip to local zip file (back up)
  910. if err := ioutil.WriteFile(zipFilePath, zipFilesBuffer.Bytes(), 0600); err != nil {
  911. l.Warnln("Support bundle: support bundle zip could not be created:", err)
  912. }
  913. // Serve the buffer zip to client for download
  914. w.Header().Set("Content-Type", "application/zip")
  915. w.Header().Set("Content-Disposition", "attachment; filename="+zipFileName)
  916. io.Copy(w, &zipFilesBuffer)
  917. }
  918. func (s *service) getSystemHTTPMetrics(w http.ResponseWriter, r *http.Request) {
  919. stats := make(map[string]interface{})
  920. metrics.Each(func(name string, intf interface{}) {
  921. if m, ok := intf.(*metrics.StandardTimer); ok {
  922. pct := m.Percentiles([]float64{0.50, 0.95, 0.99})
  923. for i := range pct {
  924. pct[i] /= 1e6 // ns to ms
  925. }
  926. stats[name] = map[string]interface{}{
  927. "count": m.Count(),
  928. "sumMs": m.Sum() / 1e6, // ns to ms
  929. "ratesPerS": []float64{m.Rate1(), m.Rate5(), m.Rate15()},
  930. "percentilesMs": pct,
  931. }
  932. }
  933. })
  934. bs, _ := json.MarshalIndent(stats, "", " ")
  935. w.Write(bs)
  936. }
  937. func (s *service) getSystemDiscovery(w http.ResponseWriter, r *http.Request) {
  938. devices := make(map[string]discover.CacheEntry)
  939. if s.discoverer != nil {
  940. // Device ids can't be marshalled as keys so we need to manually
  941. // rebuild this map using strings. Discoverer may be nil if discovery
  942. // has not started yet.
  943. for device, entry := range s.discoverer.Cache() {
  944. devices[device.String()] = entry
  945. }
  946. }
  947. sendJSON(w, devices)
  948. }
  949. func (s *service) getReport(w http.ResponseWriter, r *http.Request) {
  950. version := ur.Version
  951. if val, _ := strconv.Atoi(r.URL.Query().Get("version")); val > 0 {
  952. version = val
  953. }
  954. sendJSON(w, s.urService.ReportDataPreview(version))
  955. }
  956. func (s *service) getRandomString(w http.ResponseWriter, r *http.Request) {
  957. length := 32
  958. if val, _ := strconv.Atoi(r.URL.Query().Get("length")); val > 0 {
  959. length = val
  960. }
  961. str := rand.String(length)
  962. sendJSON(w, map[string]string{"random": str})
  963. }
  964. func (s *service) getDBIgnores(w http.ResponseWriter, r *http.Request) {
  965. qs := r.URL.Query()
  966. folder := qs.Get("folder")
  967. ignores, patterns, err := s.model.GetIgnores(folder)
  968. if err != nil {
  969. http.Error(w, err.Error(), 500)
  970. return
  971. }
  972. sendJSON(w, map[string][]string{
  973. "ignore": ignores,
  974. "expanded": patterns,
  975. })
  976. }
  977. func (s *service) postDBIgnores(w http.ResponseWriter, r *http.Request) {
  978. qs := r.URL.Query()
  979. bs, err := ioutil.ReadAll(r.Body)
  980. r.Body.Close()
  981. if err != nil {
  982. http.Error(w, err.Error(), 500)
  983. return
  984. }
  985. var data map[string][]string
  986. err = json.Unmarshal(bs, &data)
  987. if err != nil {
  988. http.Error(w, err.Error(), 500)
  989. return
  990. }
  991. err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
  992. if err != nil {
  993. http.Error(w, err.Error(), 500)
  994. return
  995. }
  996. s.getDBIgnores(w, r)
  997. }
  998. func (s *service) getIndexEvents(w http.ResponseWriter, r *http.Request) {
  999. s.fss.OnEventRequest()
  1000. mask := s.getEventMask(r.URL.Query().Get("events"))
  1001. sub := s.getEventSub(mask)
  1002. s.getEvents(w, r, sub)
  1003. }
  1004. func (s *service) getDiskEvents(w http.ResponseWriter, r *http.Request) {
  1005. sub := s.getEventSub(DiskEventMask)
  1006. s.getEvents(w, r, sub)
  1007. }
  1008. func (s *service) getEvents(w http.ResponseWriter, r *http.Request, eventSub events.BufferedSubscription) {
  1009. qs := r.URL.Query()
  1010. sinceStr := qs.Get("since")
  1011. limitStr := qs.Get("limit")
  1012. timeoutStr := qs.Get("timeout")
  1013. since, _ := strconv.Atoi(sinceStr)
  1014. limit, _ := strconv.Atoi(limitStr)
  1015. timeout := defaultEventTimeout
  1016. if timeoutSec, timeoutErr := strconv.Atoi(timeoutStr); timeoutErr == nil && timeoutSec >= 0 { // 0 is a valid timeout
  1017. timeout = time.Duration(timeoutSec) * time.Second
  1018. }
  1019. // Flush before blocking, to indicate that we've received the request and
  1020. // that it should not be retried. Must set Content-Type header before
  1021. // flushing.
  1022. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  1023. f := w.(http.Flusher)
  1024. f.Flush()
  1025. // If there are no events available return an empty slice, as this gets serialized as `[]`
  1026. evs := eventSub.Since(since, []events.Event{}, timeout)
  1027. if 0 < limit && limit < len(evs) {
  1028. evs = evs[len(evs)-limit:]
  1029. }
  1030. sendJSON(w, evs)
  1031. }
  1032. func (s *service) getEventMask(evs string) events.EventType {
  1033. eventMask := DefaultEventMask
  1034. if evs != "" {
  1035. eventList := strings.Split(evs, ",")
  1036. eventMask = 0
  1037. for _, ev := range eventList {
  1038. eventMask |= events.UnmarshalEventType(strings.TrimSpace(ev))
  1039. }
  1040. }
  1041. return eventMask
  1042. }
  1043. func (s *service) getEventSub(mask events.EventType) events.BufferedSubscription {
  1044. s.eventSubsMut.Lock()
  1045. bufsub, ok := s.eventSubs[mask]
  1046. if !ok {
  1047. evsub := s.evLogger.Subscribe(mask)
  1048. bufsub = events.NewBufferedSubscription(evsub, EventSubBufferSize)
  1049. s.eventSubs[mask] = bufsub
  1050. }
  1051. s.eventSubsMut.Unlock()
  1052. return bufsub
  1053. }
  1054. func (s *service) getSystemUpgrade(w http.ResponseWriter, r *http.Request) {
  1055. if s.noUpgrade {
  1056. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), 500)
  1057. return
  1058. }
  1059. opts := s.cfg.Options()
  1060. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1061. if err != nil {
  1062. http.Error(w, err.Error(), 500)
  1063. return
  1064. }
  1065. res := make(map[string]interface{})
  1066. res["running"] = build.Version
  1067. res["latest"] = rel.Tag
  1068. res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer
  1069. res["majorNewer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.MajorNewer
  1070. sendJSON(w, res)
  1071. }
  1072. func (s *service) getDeviceID(w http.ResponseWriter, r *http.Request) {
  1073. qs := r.URL.Query()
  1074. idStr := qs.Get("id")
  1075. id, err := protocol.DeviceIDFromString(idStr)
  1076. if err == nil {
  1077. sendJSON(w, map[string]string{
  1078. "id": id.String(),
  1079. })
  1080. } else {
  1081. sendJSON(w, map[string]string{
  1082. "error": err.Error(),
  1083. })
  1084. }
  1085. }
  1086. func (s *service) getLang(w http.ResponseWriter, r *http.Request) {
  1087. lang := r.Header.Get("Accept-Language")
  1088. var langs []string
  1089. for _, l := range strings.Split(lang, ",") {
  1090. parts := strings.SplitN(l, ";", 2)
  1091. langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0])))
  1092. }
  1093. sendJSON(w, langs)
  1094. }
  1095. func (s *service) postSystemUpgrade(w http.ResponseWriter, r *http.Request) {
  1096. opts := s.cfg.Options()
  1097. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1098. if err != nil {
  1099. l.Warnln("getting latest release:", err)
  1100. http.Error(w, err.Error(), 500)
  1101. return
  1102. }
  1103. if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
  1104. err = upgrade.To(rel)
  1105. if err != nil {
  1106. l.Warnln("upgrading:", err)
  1107. http.Error(w, err.Error(), 500)
  1108. return
  1109. }
  1110. s.flushResponse(`{"ok": "restarting"}`, w)
  1111. s.contr.ExitUpgrading()
  1112. }
  1113. }
  1114. func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
  1115. return func(w http.ResponseWriter, r *http.Request) {
  1116. var qs = r.URL.Query()
  1117. var deviceStr = qs.Get("device")
  1118. var cfgs []config.DeviceConfiguration
  1119. if deviceStr == "" {
  1120. for _, cfg := range s.cfg.Devices() {
  1121. cfg.Paused = paused
  1122. cfgs = append(cfgs, cfg)
  1123. }
  1124. } else {
  1125. device, err := protocol.DeviceIDFromString(deviceStr)
  1126. if err != nil {
  1127. http.Error(w, err.Error(), 500)
  1128. return
  1129. }
  1130. cfg, ok := s.cfg.Devices()[device]
  1131. if !ok {
  1132. http.Error(w, "not found", http.StatusNotFound)
  1133. return
  1134. }
  1135. cfg.Paused = paused
  1136. cfgs = append(cfgs, cfg)
  1137. }
  1138. if _, err := s.cfg.SetDevices(cfgs); err != nil {
  1139. http.Error(w, err.Error(), 500)
  1140. }
  1141. }
  1142. }
  1143. func (s *service) postDBScan(w http.ResponseWriter, r *http.Request) {
  1144. qs := r.URL.Query()
  1145. folder := qs.Get("folder")
  1146. if folder != "" {
  1147. subs := qs["sub"]
  1148. err := s.model.ScanFolderSubdirs(folder, subs)
  1149. if err != nil {
  1150. http.Error(w, err.Error(), 500)
  1151. return
  1152. }
  1153. nextStr := qs.Get("next")
  1154. next, err := strconv.Atoi(nextStr)
  1155. if err == nil {
  1156. s.model.DelayScan(folder, time.Duration(next)*time.Second)
  1157. }
  1158. } else {
  1159. errors := s.model.ScanFolders()
  1160. if len(errors) > 0 {
  1161. http.Error(w, "Error scanning folders", 500)
  1162. sendJSON(w, errors)
  1163. return
  1164. }
  1165. }
  1166. }
  1167. func (s *service) postDBPrio(w http.ResponseWriter, r *http.Request) {
  1168. qs := r.URL.Query()
  1169. folder := qs.Get("folder")
  1170. file := qs.Get("file")
  1171. s.model.BringToFront(folder, file)
  1172. s.getDBNeed(w, r)
  1173. }
  1174. func (s *service) getQR(w http.ResponseWriter, r *http.Request) {
  1175. var qs = r.URL.Query()
  1176. var text = qs.Get("text")
  1177. code, err := qr.Encode(text, qr.M)
  1178. if err != nil {
  1179. http.Error(w, "Invalid", 500)
  1180. return
  1181. }
  1182. w.Header().Set("Content-Type", "image/png")
  1183. w.Write(code.PNG())
  1184. }
  1185. func (s *service) getPeerCompletion(w http.ResponseWriter, r *http.Request) {
  1186. tot := map[string]float64{}
  1187. count := map[string]float64{}
  1188. for _, folder := range s.cfg.Folders() {
  1189. for _, device := range folder.DeviceIDs() {
  1190. deviceStr := device.String()
  1191. if _, ok := s.model.Connection(device); ok {
  1192. tot[deviceStr] += s.model.Completion(device, folder.ID).CompletionPct
  1193. } else {
  1194. tot[deviceStr] = 0
  1195. }
  1196. count[deviceStr]++
  1197. }
  1198. }
  1199. comp := map[string]int{}
  1200. for device := range tot {
  1201. comp[device] = int(tot[device] / count[device])
  1202. }
  1203. sendJSON(w, comp)
  1204. }
  1205. func (s *service) getFolderVersions(w http.ResponseWriter, r *http.Request) {
  1206. qs := r.URL.Query()
  1207. versions, err := s.model.GetFolderVersions(qs.Get("folder"))
  1208. if err != nil {
  1209. http.Error(w, err.Error(), 500)
  1210. return
  1211. }
  1212. sendJSON(w, versions)
  1213. }
  1214. func (s *service) postFolderVersionsRestore(w http.ResponseWriter, r *http.Request) {
  1215. qs := r.URL.Query()
  1216. bs, err := ioutil.ReadAll(r.Body)
  1217. r.Body.Close()
  1218. if err != nil {
  1219. http.Error(w, err.Error(), 500)
  1220. return
  1221. }
  1222. var versions map[string]time.Time
  1223. err = json.Unmarshal(bs, &versions)
  1224. if err != nil {
  1225. http.Error(w, err.Error(), 500)
  1226. return
  1227. }
  1228. ferr, err := s.model.RestoreFolderVersions(qs.Get("folder"), versions)
  1229. if err != nil {
  1230. http.Error(w, err.Error(), 500)
  1231. return
  1232. }
  1233. sendJSON(w, ferr)
  1234. }
  1235. func (s *service) getFolderErrors(w http.ResponseWriter, r *http.Request) {
  1236. qs := r.URL.Query()
  1237. folder := qs.Get("folder")
  1238. page, perpage := getPagingParams(qs)
  1239. errors, err := s.model.FolderErrors(folder)
  1240. if err != nil {
  1241. http.Error(w, err.Error(), http.StatusNotFound)
  1242. return
  1243. }
  1244. start := (page - 1) * perpage
  1245. if start >= len(errors) {
  1246. errors = nil
  1247. } else {
  1248. errors = errors[start:]
  1249. if perpage < len(errors) {
  1250. errors = errors[:perpage]
  1251. }
  1252. }
  1253. sendJSON(w, map[string]interface{}{
  1254. "folder": folder,
  1255. "errors": errors,
  1256. "page": page,
  1257. "perpage": perpage,
  1258. })
  1259. }
  1260. func (s *service) getSystemBrowse(w http.ResponseWriter, r *http.Request) {
  1261. qs := r.URL.Query()
  1262. current := qs.Get("current")
  1263. // Default value or in case of error unmarshalling ends up being basic fs.
  1264. var fsType fs.FilesystemType
  1265. fsType.UnmarshalText([]byte(qs.Get("filesystem")))
  1266. sendJSON(w, browseFiles(current, fsType))
  1267. }
  1268. const (
  1269. matchExact int = iota
  1270. matchCaseIns
  1271. noMatch
  1272. )
  1273. func checkPrefixMatch(s, prefix string) int {
  1274. if strings.HasPrefix(s, prefix) {
  1275. return matchExact
  1276. }
  1277. if strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
  1278. return matchCaseIns
  1279. }
  1280. return noMatch
  1281. }
  1282. func browseFiles(current string, fsType fs.FilesystemType) []string {
  1283. if current == "" {
  1284. filesystem := fs.NewFilesystem(fsType, "")
  1285. if roots, err := filesystem.Roots(); err == nil {
  1286. return roots
  1287. }
  1288. return nil
  1289. }
  1290. search, _ := fs.ExpandTilde(current)
  1291. pathSeparator := string(fs.PathSeparator)
  1292. if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) {
  1293. search = search + pathSeparator
  1294. }
  1295. searchDir := filepath.Dir(search)
  1296. // The searchFile should be the last component of search, or empty if it
  1297. // ends with a path separator
  1298. var searchFile string
  1299. if !strings.HasSuffix(search, pathSeparator) {
  1300. searchFile = filepath.Base(search)
  1301. }
  1302. fs := fs.NewFilesystem(fsType, searchDir)
  1303. subdirectories, _ := fs.DirNames(".")
  1304. exactMatches := make([]string, 0, len(subdirectories))
  1305. caseInsMatches := make([]string, 0, len(subdirectories))
  1306. for _, subdirectory := range subdirectories {
  1307. info, err := fs.Stat(subdirectory)
  1308. if err != nil || !info.IsDir() {
  1309. continue
  1310. }
  1311. switch checkPrefixMatch(subdirectory, searchFile) {
  1312. case matchExact:
  1313. exactMatches = append(exactMatches, filepath.Join(searchDir, subdirectory)+pathSeparator)
  1314. case matchCaseIns:
  1315. caseInsMatches = append(caseInsMatches, filepath.Join(searchDir, subdirectory)+pathSeparator)
  1316. }
  1317. }
  1318. // sort to return matches in deterministic order (don't depend on file system order)
  1319. sort.Strings(exactMatches)
  1320. sort.Strings(caseInsMatches)
  1321. return append(exactMatches, caseInsMatches...)
  1322. }
  1323. func (s *service) getCPUProf(w http.ResponseWriter, r *http.Request) {
  1324. duration, err := time.ParseDuration(r.FormValue("duration"))
  1325. if err != nil {
  1326. duration = 30 * time.Second
  1327. }
  1328. filename := fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1329. w.Header().Set("Content-Type", "application/octet-stream")
  1330. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1331. if err := pprof.StartCPUProfile(w); err == nil {
  1332. time.Sleep(duration)
  1333. pprof.StopCPUProfile()
  1334. }
  1335. }
  1336. func (s *service) getHeapProf(w http.ResponseWriter, r *http.Request) {
  1337. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1338. w.Header().Set("Content-Type", "application/octet-stream")
  1339. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1340. runtime.GC()
  1341. pprof.WriteHeapProfile(w)
  1342. }
  1343. func toJsonFileInfoSlice(fs []db.FileInfoTruncated) []jsonFileInfoTrunc {
  1344. res := make([]jsonFileInfoTrunc, len(fs))
  1345. for i, f := range fs {
  1346. res[i] = jsonFileInfoTrunc(f)
  1347. }
  1348. return res
  1349. }
  1350. // Type wrappers for nice JSON serialization
  1351. type jsonFileInfo protocol.FileInfo
  1352. func (f jsonFileInfo) MarshalJSON() ([]byte, error) {
  1353. m := fileIntfJSONMap(protocol.FileInfo(f))
  1354. m["numBlocks"] = len(f.Blocks)
  1355. return json.Marshal(m)
  1356. }
  1357. type jsonFileInfoTrunc db.FileInfoTruncated
  1358. func (f jsonFileInfoTrunc) MarshalJSON() ([]byte, error) {
  1359. m := fileIntfJSONMap(db.FileInfoTruncated(f))
  1360. m["numBlocks"] = nil // explicitly unknown
  1361. return json.Marshal(m)
  1362. }
  1363. func fileIntfJSONMap(f db.FileIntf) map[string]interface{} {
  1364. out := map[string]interface{}{
  1365. "name": f.FileName(),
  1366. "type": f.FileType().String(),
  1367. "size": f.FileSize(),
  1368. "deleted": f.IsDeleted(),
  1369. "invalid": f.IsInvalid(),
  1370. "ignored": f.IsIgnored(),
  1371. "mustRescan": f.MustRescan(),
  1372. "noPermissions": !f.HasPermissionBits(),
  1373. "modified": f.ModTime(),
  1374. "modifiedBy": f.FileModifiedBy().String(),
  1375. "sequence": f.SequenceNo(),
  1376. "version": jsonVersionVector(f.FileVersion()),
  1377. "localFlags": f.FileLocalFlags(),
  1378. }
  1379. if f.HasPermissionBits() {
  1380. out["permissions"] = fmt.Sprintf("%#o", f.FilePermissions())
  1381. }
  1382. return out
  1383. }
  1384. type jsonVersionVector protocol.Vector
  1385. func (v jsonVersionVector) MarshalJSON() ([]byte, error) {
  1386. res := make([]string, len(v.Counters))
  1387. for i, c := range v.Counters {
  1388. res[i] = fmt.Sprintf("%v:%d", c.ID, c.Value)
  1389. }
  1390. return json.Marshal(res)
  1391. }
  1392. func dirNames(dir string) []string {
  1393. fd, err := os.Open(dir)
  1394. if err != nil {
  1395. return nil
  1396. }
  1397. defer fd.Close()
  1398. fis, err := fd.Readdir(-1)
  1399. if err != nil {
  1400. return nil
  1401. }
  1402. var dirs []string
  1403. for _, fi := range fis {
  1404. if fi.IsDir() {
  1405. dirs = append(dirs, filepath.Base(fi.Name()))
  1406. }
  1407. }
  1408. sort.Strings(dirs)
  1409. return dirs
  1410. }
  1411. func addressIsLocalhost(addr string) bool {
  1412. host, _, err := net.SplitHostPort(addr)
  1413. if err != nil {
  1414. // There was no port, so we assume the address was just a hostname
  1415. host = addr
  1416. }
  1417. switch strings.ToLower(host) {
  1418. case "localhost", "localhost.":
  1419. return true
  1420. default:
  1421. ip := net.ParseIP(host)
  1422. if ip == nil {
  1423. // not an IP address
  1424. return false
  1425. }
  1426. return ip.IsLoopback()
  1427. }
  1428. }