1
0

api.go 49 KB

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