api.go 49 KB

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