api.go 50 KB

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