api.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  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. "context"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "encoding/json"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "runtime"
  24. "runtime/pprof"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "unicode"
  30. "github.com/calmh/incontainer"
  31. "github.com/julienschmidt/httprouter"
  32. "github.com/prometheus/client_golang/prometheus/promhttp"
  33. "github.com/rcrowley/go-metrics"
  34. "github.com/thejerf/suture/v4"
  35. "github.com/vitrun/qart/qr"
  36. "golang.org/x/text/runes"
  37. "golang.org/x/text/transform"
  38. "golang.org/x/text/unicode/norm"
  39. "github.com/syncthing/syncthing/lib/build"
  40. "github.com/syncthing/syncthing/lib/config"
  41. "github.com/syncthing/syncthing/lib/connections"
  42. "github.com/syncthing/syncthing/lib/db"
  43. "github.com/syncthing/syncthing/lib/discover"
  44. "github.com/syncthing/syncthing/lib/events"
  45. "github.com/syncthing/syncthing/lib/fs"
  46. "github.com/syncthing/syncthing/lib/ignore"
  47. "github.com/syncthing/syncthing/lib/locations"
  48. "github.com/syncthing/syncthing/lib/logger"
  49. "github.com/syncthing/syncthing/lib/model"
  50. "github.com/syncthing/syncthing/lib/protocol"
  51. "github.com/syncthing/syncthing/lib/rand"
  52. "github.com/syncthing/syncthing/lib/svcutil"
  53. "github.com/syncthing/syncthing/lib/sync"
  54. "github.com/syncthing/syncthing/lib/tlsutil"
  55. "github.com/syncthing/syncthing/lib/upgrade"
  56. "github.com/syncthing/syncthing/lib/ur"
  57. )
  58. const (
  59. // Default mask excludes these very noisy event types to avoid filling the pipe.
  60. // FIXME: ItemStarted and ItemFinished should be excluded for the same reason.
  61. DefaultEventMask = events.AllEvents &^ events.LocalChangeDetected &^ events.RemoteChangeDetected
  62. DiskEventMask = events.LocalChangeDetected | events.RemoteChangeDetected
  63. EventSubBufferSize = 1000
  64. defaultEventTimeout = time.Minute
  65. httpsCertLifetimeDays = 820
  66. )
  67. type service struct {
  68. suture.Service
  69. id protocol.DeviceID
  70. cfg config.Wrapper
  71. statics *staticsServer
  72. model model.Model
  73. eventSubs map[events.EventType]events.BufferedSubscription
  74. eventSubsMut sync.Mutex
  75. evLogger events.Logger
  76. discoverer discover.Manager
  77. connectionsService connections.Service
  78. fss model.FolderSummaryService
  79. urService *ur.Service
  80. noUpgrade bool
  81. tlsDefaultCommonName string
  82. configChanged chan struct{} // signals intentional listener close due to config change
  83. started chan string // signals startup complete by sending the listener address, for testing only
  84. startedOnce chan struct{} // the service has started successfully at least once
  85. startupErr error
  86. listenerAddr net.Addr
  87. exitChan chan *svcutil.FatalErr
  88. guiErrors logger.Recorder
  89. systemLog logger.Recorder
  90. }
  91. var _ config.Verifier = &service{}
  92. type Service interface {
  93. suture.Service
  94. config.Committer
  95. WaitForStart() error
  96. }
  97. func New(id protocol.DeviceID, cfg config.Wrapper, assetDir, tlsDefaultCommonName string, m model.Model, defaultSub, diskSub events.BufferedSubscription, evLogger events.Logger, discoverer discover.Manager, connectionsService connections.Service, urService *ur.Service, fss model.FolderSummaryService, errors, systemLog logger.Recorder, noUpgrade bool) Service {
  98. return &service{
  99. id: id,
  100. cfg: cfg,
  101. statics: newStaticsServer(cfg.GUI().Theme, assetDir),
  102. model: m,
  103. eventSubs: map[events.EventType]events.BufferedSubscription{
  104. DefaultEventMask: defaultSub,
  105. DiskEventMask: diskSub,
  106. },
  107. eventSubsMut: sync.NewMutex(),
  108. evLogger: evLogger,
  109. discoverer: discoverer,
  110. connectionsService: connectionsService,
  111. fss: fss,
  112. urService: urService,
  113. guiErrors: errors,
  114. systemLog: systemLog,
  115. noUpgrade: noUpgrade,
  116. tlsDefaultCommonName: tlsDefaultCommonName,
  117. configChanged: make(chan struct{}),
  118. startedOnce: make(chan struct{}),
  119. exitChan: make(chan *svcutil.FatalErr, 1),
  120. }
  121. }
  122. func (s *service) WaitForStart() error {
  123. <-s.startedOnce
  124. return s.startupErr
  125. }
  126. func (s *service) getListener(guiCfg config.GUIConfiguration) (net.Listener, error) {
  127. httpsCertFile := locations.Get(locations.HTTPSCertFile)
  128. httpsKeyFile := locations.Get(locations.HTTPSKeyFile)
  129. cert, err := tls.LoadX509KeyPair(httpsCertFile, httpsKeyFile)
  130. // If the certificate has expired or will expire in the next month, fail
  131. // it and generate a new one.
  132. if err == nil {
  133. err = shouldRegenerateCertificate(cert)
  134. }
  135. if err != nil {
  136. l.Infoln("Loading HTTPS certificate:", err)
  137. l.Infoln("Creating new HTTPS certificate")
  138. // When generating the HTTPS certificate, use the system host name per
  139. // default. If that isn't available, use the "syncthing" default.
  140. var name string
  141. name, err = os.Hostname()
  142. if err != nil {
  143. name = s.tlsDefaultCommonName
  144. }
  145. name, err = sanitizedHostname(name)
  146. if err != nil {
  147. name = s.tlsDefaultCommonName
  148. }
  149. cert, err = tlsutil.NewCertificate(httpsCertFile, httpsKeyFile, name, httpsCertLifetimeDays)
  150. }
  151. if err != nil {
  152. return nil, err
  153. }
  154. tlsCfg := tlsutil.SecureDefaultWithTLS12()
  155. tlsCfg.Certificates = []tls.Certificate{cert}
  156. if guiCfg.Network() == "unix" {
  157. // When listening on a UNIX socket we should unlink before bind,
  158. // lest we get a "bind: address already in use". We don't
  159. // particularly care if this succeeds or not.
  160. os.Remove(guiCfg.Address())
  161. }
  162. rawListener, err := net.Listen(guiCfg.Network(), guiCfg.Address())
  163. if err != nil {
  164. return nil, err
  165. }
  166. if guiCfg.Network() == "unix" && guiCfg.UnixSocketPermissions() != 0 {
  167. // We should error if this fails under the assumption that these permissions are
  168. // required for operation.
  169. err = os.Chmod(guiCfg.Address(), guiCfg.UnixSocketPermissions())
  170. if err != nil {
  171. return nil, err
  172. }
  173. }
  174. listener := &tlsutil.DowngradingListener{
  175. Listener: rawListener,
  176. TLSConfig: tlsCfg,
  177. }
  178. return listener, nil
  179. }
  180. func sendJSON(w http.ResponseWriter, jsonObject interface{}) {
  181. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  182. // Marshalling might fail, in which case we should return a 500 with the
  183. // actual error.
  184. bs, err := json.MarshalIndent(jsonObject, "", " ")
  185. if err != nil {
  186. // This Marshal() can't fail though.
  187. bs, _ = json.Marshal(map[string]string{"error": err.Error()})
  188. http.Error(w, string(bs), http.StatusInternalServerError)
  189. return
  190. }
  191. fmt.Fprintf(w, "%s\n", bs)
  192. }
  193. func (s *service) Serve(ctx context.Context) error {
  194. listener, err := s.getListener(s.cfg.GUI())
  195. if err != nil {
  196. select {
  197. case <-s.startedOnce:
  198. // We let this be a loud user-visible warning as it may be the only
  199. // indication they get that the GUI won't be available.
  200. l.Warnln("Starting API/GUI:", err)
  201. default:
  202. // This is during initialization. A failure here should be fatal
  203. // as there will be no way for the user to communicate with us
  204. // otherwise anyway.
  205. s.startupErr = err
  206. close(s.startedOnce)
  207. }
  208. return err
  209. }
  210. if listener == nil {
  211. // Not much we can do here other than exit quickly. The supervisor
  212. // will log an error at some point.
  213. return nil
  214. }
  215. s.listenerAddr = listener.Addr()
  216. defer listener.Close()
  217. s.cfg.Subscribe(s)
  218. defer s.cfg.Unsubscribe(s)
  219. restMux := httprouter.New()
  220. // The GET handlers
  221. restMux.HandlerFunc(http.MethodGet, "/rest/cluster/pending/devices", s.getPendingDevices) // -
  222. restMux.HandlerFunc(http.MethodGet, "/rest/cluster/pending/folders", s.getPendingFolders) // [device]
  223. restMux.HandlerFunc(http.MethodGet, "/rest/db/completion", s.getDBCompletion) // [device] [folder]
  224. restMux.HandlerFunc(http.MethodGet, "/rest/db/file", s.getDBFile) // folder file
  225. restMux.HandlerFunc(http.MethodGet, "/rest/db/ignores", s.getDBIgnores) // folder
  226. restMux.HandlerFunc(http.MethodGet, "/rest/db/need", s.getDBNeed) // folder [perpage] [page]
  227. restMux.HandlerFunc(http.MethodGet, "/rest/db/remoteneed", s.getDBRemoteNeed) // device folder [perpage] [page]
  228. restMux.HandlerFunc(http.MethodGet, "/rest/db/localchanged", s.getDBLocalChanged) // folder [perpage] [page]
  229. restMux.HandlerFunc(http.MethodGet, "/rest/db/status", s.getDBStatus) // folder
  230. restMux.HandlerFunc(http.MethodGet, "/rest/db/browse", s.getDBBrowse) // folder [prefix] [dirsonly] [levels]
  231. restMux.HandlerFunc(http.MethodGet, "/rest/folder/versions", s.getFolderVersions) // folder
  232. restMux.HandlerFunc(http.MethodGet, "/rest/folder/errors", s.getFolderErrors) // folder [perpage] [page]
  233. restMux.HandlerFunc(http.MethodGet, "/rest/folder/pullerrors", s.getFolderErrors) // folder (deprecated)
  234. restMux.HandlerFunc(http.MethodGet, "/rest/events", s.getIndexEvents) // [since] [limit] [timeout] [events]
  235. restMux.HandlerFunc(http.MethodGet, "/rest/events/disk", s.getDiskEvents) // [since] [limit] [timeout]
  236. restMux.HandlerFunc(http.MethodGet, "/rest/noauth/health", s.getHealth) // -
  237. restMux.HandlerFunc(http.MethodGet, "/rest/stats/device", s.getDeviceStats) // -
  238. restMux.HandlerFunc(http.MethodGet, "/rest/stats/folder", s.getFolderStats) // -
  239. restMux.HandlerFunc(http.MethodGet, "/rest/svc/deviceid", s.getDeviceID) // id
  240. restMux.HandlerFunc(http.MethodGet, "/rest/svc/lang", s.getLang) // -
  241. restMux.HandlerFunc(http.MethodGet, "/rest/svc/report", s.getReport) // -
  242. restMux.HandlerFunc(http.MethodGet, "/rest/svc/random/string", s.getRandomString) // [length]
  243. restMux.HandlerFunc(http.MethodGet, "/rest/system/browse", s.getSystemBrowse) // current
  244. restMux.HandlerFunc(http.MethodGet, "/rest/system/connections", s.getSystemConnections) // -
  245. restMux.HandlerFunc(http.MethodGet, "/rest/system/discovery", s.getSystemDiscovery) // -
  246. restMux.HandlerFunc(http.MethodGet, "/rest/system/error", s.getSystemError) // -
  247. restMux.HandlerFunc(http.MethodGet, "/rest/system/paths", s.getSystemPaths) // -
  248. restMux.HandlerFunc(http.MethodGet, "/rest/system/ping", s.restPing) // -
  249. restMux.HandlerFunc(http.MethodGet, "/rest/system/status", s.getSystemStatus) // -
  250. restMux.HandlerFunc(http.MethodGet, "/rest/system/upgrade", s.getSystemUpgrade) // -
  251. restMux.HandlerFunc(http.MethodGet, "/rest/system/version", s.getSystemVersion) // -
  252. restMux.HandlerFunc(http.MethodGet, "/rest/system/debug", s.getSystemDebug) // -
  253. restMux.HandlerFunc(http.MethodGet, "/rest/system/log", s.getSystemLog) // [since]
  254. restMux.HandlerFunc(http.MethodGet, "/rest/system/log.txt", s.getSystemLogTxt) // [since]
  255. // The POST handlers
  256. restMux.HandlerFunc(http.MethodPost, "/rest/db/prio", s.postDBPrio) // folder file
  257. restMux.HandlerFunc(http.MethodPost, "/rest/db/ignores", s.postDBIgnores) // folder
  258. restMux.HandlerFunc(http.MethodPost, "/rest/db/override", s.postDBOverride) // folder
  259. restMux.HandlerFunc(http.MethodPost, "/rest/db/revert", s.postDBRevert) // folder
  260. restMux.HandlerFunc(http.MethodPost, "/rest/db/scan", s.postDBScan) // folder [sub...] [delay]
  261. restMux.HandlerFunc(http.MethodPost, "/rest/folder/versions", s.postFolderVersionsRestore) // folder <body>
  262. restMux.HandlerFunc(http.MethodPost, "/rest/system/error", s.postSystemError) // <body>
  263. restMux.HandlerFunc(http.MethodPost, "/rest/system/error/clear", s.postSystemErrorClear) // -
  264. restMux.HandlerFunc(http.MethodPost, "/rest/system/ping", s.restPing) // -
  265. restMux.HandlerFunc(http.MethodPost, "/rest/system/reset", s.postSystemReset) // [folder]
  266. restMux.HandlerFunc(http.MethodPost, "/rest/system/restart", s.postSystemRestart) // -
  267. restMux.HandlerFunc(http.MethodPost, "/rest/system/shutdown", s.postSystemShutdown) // -
  268. restMux.HandlerFunc(http.MethodPost, "/rest/system/upgrade", s.postSystemUpgrade) // -
  269. restMux.HandlerFunc(http.MethodPost, "/rest/system/pause", s.makeDevicePauseHandler(true)) // [device]
  270. restMux.HandlerFunc(http.MethodPost, "/rest/system/resume", s.makeDevicePauseHandler(false)) // [device]
  271. restMux.HandlerFunc(http.MethodPost, "/rest/system/debug", s.postSystemDebug) // [enable] [disable]
  272. // The DELETE handlers
  273. restMux.HandlerFunc(http.MethodDelete, "/rest/cluster/pending/devices", s.deletePendingDevices) // device
  274. restMux.HandlerFunc(http.MethodDelete, "/rest/cluster/pending/folders", s.deletePendingFolders) // folder [device]
  275. // Config endpoints
  276. configBuilder := &configMuxBuilder{
  277. Router: restMux,
  278. id: s.id,
  279. cfg: s.cfg,
  280. }
  281. configBuilder.registerConfig("/rest/config")
  282. configBuilder.registerConfigInsync("/rest/config/insync") // deprecated
  283. configBuilder.registerConfigRequiresRestart("/rest/config/restart-required")
  284. configBuilder.registerFolders("/rest/config/folders")
  285. configBuilder.registerDevices("/rest/config/devices")
  286. configBuilder.registerFolder("/rest/config/folders/:id")
  287. configBuilder.registerDevice("/rest/config/devices/:id")
  288. configBuilder.registerDefaultFolder("/rest/config/defaults/folder")
  289. configBuilder.registerDefaultDevice("/rest/config/defaults/device")
  290. configBuilder.registerDefaultIgnores("/rest/config/defaults/ignores")
  291. configBuilder.registerOptions("/rest/config/options")
  292. configBuilder.registerLDAP("/rest/config/ldap")
  293. configBuilder.registerGUI("/rest/config/gui")
  294. // Deprecated config endpoints
  295. configBuilder.registerConfigDeprecated("/rest/system/config") // POST instead of PUT
  296. configBuilder.registerConfigInsync("/rest/system/config/insync")
  297. // Debug endpoints, not for general use
  298. debugMux := http.NewServeMux()
  299. debugMux.HandleFunc("/rest/debug/peerCompletion", s.getPeerCompletion)
  300. debugMux.HandleFunc("/rest/debug/httpmetrics", s.getSystemHTTPMetrics)
  301. debugMux.HandleFunc("/rest/debug/cpuprof", s.getCPUProf) // duration
  302. debugMux.HandleFunc("/rest/debug/heapprof", s.getHeapProf)
  303. debugMux.HandleFunc("/rest/debug/support", s.getSupportBundle)
  304. debugMux.HandleFunc("/rest/debug/file", s.getDebugFile)
  305. restMux.Handler(http.MethodGet, "/rest/debug/*method", s.whenDebugging(debugMux))
  306. // A handler that disables caching
  307. noCacheRestMux := noCacheMiddleware(metricsMiddleware(restMux))
  308. // The main routing handler
  309. mux := http.NewServeMux()
  310. mux.Handle("/rest/", noCacheRestMux)
  311. mux.HandleFunc("/qr/", s.getQR)
  312. // Serve compiled in assets unless an asset directory was set (for development)
  313. mux.Handle("/", s.statics)
  314. // Handle the special meta.js path
  315. mux.Handle("/meta.js", noCacheMiddleware(http.HandlerFunc(s.getJSMetadata)))
  316. // Handle Prometheus metrics
  317. promHttpHandler := promhttp.Handler()
  318. mux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
  319. // fetching metrics counts as an event, for the purpose of whether
  320. // we should prepare folder summaries etc.
  321. s.fss.OnEventRequest()
  322. promHttpHandler.ServeHTTP(w, req)
  323. })
  324. guiCfg := s.cfg.GUI()
  325. // Wrap everything in CSRF protection. The /rest prefix should be
  326. // protected, other requests will grant cookies.
  327. var handler http.Handler = newCsrfManager(s.id.Short().String(), "/rest", guiCfg, mux, locations.Get(locations.CsrfTokens))
  328. // Add our version and ID as a header to responses
  329. handler = withDetailsMiddleware(s.id, handler)
  330. // Wrap everything in basic auth, if user/password is set.
  331. if guiCfg.IsAuthEnabled() {
  332. sessionCookieName := "sessionid-" + s.id.Short().String()
  333. handler = basicAuthAndSessionMiddleware(sessionCookieName, s.id.Short().String(), guiCfg, s.cfg.LDAP(), handler, s.evLogger)
  334. handlePasswordAuth := passwordAuthHandler(sessionCookieName, guiCfg, s.cfg.LDAP(), s.evLogger)
  335. restMux.Handler(http.MethodPost, "/rest/noauth/auth/password", handlePasswordAuth)
  336. // Logout is a no-op without a valid session cookie, so /noauth/ is fine here
  337. restMux.Handler(http.MethodPost, "/rest/noauth/auth/logout", handleLogout(sessionCookieName))
  338. }
  339. // Redirect to HTTPS if we are supposed to
  340. if guiCfg.UseTLS() {
  341. handler = redirectToHTTPSMiddleware(handler)
  342. }
  343. // Add the CORS handling
  344. handler = corsMiddleware(handler, guiCfg.InsecureAllowFrameLoading)
  345. if addressIsLocalhost(guiCfg.Address()) && !guiCfg.InsecureSkipHostCheck {
  346. // Verify source host
  347. handler = localhostMiddleware(handler)
  348. }
  349. handler = debugMiddleware(handler)
  350. srv := http.Server{
  351. Handler: handler,
  352. // ReadTimeout must be longer than SyncthingController $scope.refresh
  353. // interval to avoid HTTP keepalive/GUI refresh race.
  354. ReadTimeout: 15 * time.Second,
  355. // Prevent the HTTP server from logging stuff on its own. The things we
  356. // care about we log ourselves from the handlers.
  357. ErrorLog: log.New(io.Discard, "", 0),
  358. }
  359. l.Infoln("GUI and API listening on", listener.Addr())
  360. l.Infoln("Access the GUI via the following URL:", guiCfg.URL())
  361. if s.started != nil {
  362. // only set when run by the tests
  363. select {
  364. case <-ctx.Done(): // Shouldn't return directly due to cleanup below
  365. case s.started <- listener.Addr().String():
  366. }
  367. }
  368. // Indicate successful initial startup, to ourselves and to interested
  369. // listeners (i.e. the thing that starts the browser).
  370. select {
  371. case <-s.startedOnce:
  372. default:
  373. close(s.startedOnce)
  374. }
  375. // Serve in the background
  376. serveError := make(chan error, 1)
  377. go func() {
  378. select {
  379. case serveError <- srv.Serve(listener):
  380. case <-ctx.Done():
  381. }
  382. }()
  383. // Wait for stop, restart or error signals
  384. err = nil
  385. select {
  386. case <-ctx.Done():
  387. // Shutting down permanently
  388. l.Debugln("shutting down (stop)")
  389. case <-s.configChanged:
  390. // Soft restart due to configuration change
  391. l.Debugln("restarting (config changed)")
  392. case err = <-s.exitChan:
  393. case err = <-serveError:
  394. // Restart due to listen/serve failure
  395. l.Warnln("GUI/API:", err, "(restarting)")
  396. }
  397. // Give it a moment to shut down gracefully, e.g. if we are restarting
  398. // due to a config change through the API, let that finish successfully.
  399. timeout, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  400. defer cancel()
  401. if err := srv.Shutdown(timeout); err == timeout.Err() {
  402. srv.Close()
  403. }
  404. return err
  405. }
  406. // Complete implements suture.IsCompletable, which signifies to the supervisor
  407. // whether to stop restarting the service.
  408. func (s *service) Complete() bool {
  409. select {
  410. case <-s.startedOnce:
  411. return s.startupErr != nil
  412. default:
  413. }
  414. return false
  415. }
  416. func (s *service) String() string {
  417. return fmt.Sprintf("api.service@%p", s)
  418. }
  419. func (*service) VerifyConfiguration(_, to config.Configuration) error {
  420. if to.GUI.Network() != "tcp" {
  421. return nil
  422. }
  423. _, err := net.ResolveTCPAddr("tcp", to.GUI.Address())
  424. return err
  425. }
  426. func (s *service) CommitConfiguration(from, to config.Configuration) bool {
  427. // No action required when this changes, so mask the fact that it changed at all.
  428. from.GUI.Debugging = to.GUI.Debugging
  429. if to.GUI == from.GUI {
  430. // No GUI changes, we're done here.
  431. return true
  432. }
  433. if to.GUI.Theme != from.GUI.Theme {
  434. s.statics.setTheme(to.GUI.Theme)
  435. }
  436. // Tell the serve loop to restart
  437. s.configChanged <- struct{}{}
  438. return true
  439. }
  440. func (s *service) fatal(err *svcutil.FatalErr) {
  441. // s.exitChan is 1-buffered and whoever is first gets handled.
  442. select {
  443. case s.exitChan <- err:
  444. default:
  445. }
  446. }
  447. func debugMiddleware(h http.Handler) http.Handler {
  448. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  449. t0 := time.Now()
  450. h.ServeHTTP(w, r)
  451. if shouldDebugHTTP() {
  452. ms := 1000 * time.Since(t0).Seconds()
  453. // The variable `w` is most likely a *http.response, which we can't do
  454. // much with since it's a non exported type. We can however peek into
  455. // it with reflection to get at the status code and number of bytes
  456. // written.
  457. var status, written int64
  458. if rw := reflect.Indirect(reflect.ValueOf(w)); rw.IsValid() && rw.Kind() == reflect.Struct {
  459. if rf := rw.FieldByName("status"); rf.IsValid() && rf.Kind() == reflect.Int {
  460. status = rf.Int()
  461. }
  462. if rf := rw.FieldByName("written"); rf.IsValid() && rf.Kind() == reflect.Int64 {
  463. written = rf.Int()
  464. }
  465. }
  466. l.Debugf("http: %s %q: status %d, %d bytes in %.02f ms", r.Method, r.URL.String(), status, written, ms)
  467. }
  468. })
  469. }
  470. func corsMiddleware(next http.Handler, allowFrameLoading bool) http.Handler {
  471. // Handle CORS headers and CORS OPTIONS request.
  472. // CORS OPTIONS request are typically sent by browser during AJAX preflight
  473. // when the browser initiate a POST request.
  474. //
  475. // As the OPTIONS request is unauthorized, this handler must be the first
  476. // of the chain (hence added at the end).
  477. //
  478. // See https://www.w3.org/TR/cors/ for details.
  479. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  480. // Process OPTIONS requests
  481. if r.Method == "OPTIONS" {
  482. // Add a generous access-control-allow-origin header for CORS requests
  483. w.Header().Add("Access-Control-Allow-Origin", "*")
  484. // Only GET/POST/OPTIONS Methods are supported
  485. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
  486. // Only these headers can be set
  487. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
  488. // The request is meant to be cached 10 minutes
  489. w.Header().Set("Access-Control-Max-Age", "600")
  490. // Indicate that no content will be returned
  491. w.WriteHeader(204)
  492. return
  493. }
  494. // Other security related headers that should be present.
  495. // https://www.owasp.org/index.php/Security_Headers
  496. if !allowFrameLoading {
  497. // We don't want to be rendered in an <iframe>,
  498. // <frame> or <object>. (Unless we do it ourselves.
  499. // This is also an escape hatch for people who serve
  500. // Syncthing GUI as part of their own website
  501. // through a proxy, so they don't need to set the
  502. // allowFrameLoading bool.)
  503. w.Header().Set("X-Frame-Options", "SAMEORIGIN")
  504. }
  505. // If the browser senses an XSS attack it's allowed to take
  506. // action. (How this would not always be the default I
  507. // don't fully understand.)
  508. w.Header().Set("X-XSS-Protection", "1; mode=block")
  509. // Our content type headers are correct. Don't guess.
  510. w.Header().Set("X-Content-Type-Options", "nosniff")
  511. // For everything else, pass to the next handler
  512. next.ServeHTTP(w, r)
  513. })
  514. }
  515. func metricsMiddleware(h http.Handler) http.Handler {
  516. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  517. t := metrics.GetOrRegisterTimer(r.URL.Path, nil)
  518. t0 := time.Now()
  519. h.ServeHTTP(w, r)
  520. t.UpdateSince(t0)
  521. })
  522. }
  523. func redirectToHTTPSMiddleware(h http.Handler) http.Handler {
  524. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  525. if r.TLS == nil {
  526. // Redirect HTTP requests to HTTPS
  527. r.URL.Host = r.Host
  528. r.URL.Scheme = "https"
  529. http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
  530. } else {
  531. h.ServeHTTP(w, r)
  532. }
  533. })
  534. }
  535. func noCacheMiddleware(h http.Handler) http.Handler {
  536. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  537. w.Header().Set("Cache-Control", "max-age=0, no-cache, no-store")
  538. w.Header().Set("Expires", time.Now().UTC().Format(http.TimeFormat))
  539. w.Header().Set("Pragma", "no-cache")
  540. h.ServeHTTP(w, r)
  541. })
  542. }
  543. func withDetailsMiddleware(id protocol.DeviceID, h http.Handler) http.Handler {
  544. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  545. w.Header().Set("X-Syncthing-Version", build.Version)
  546. w.Header().Set("X-Syncthing-ID", id.String())
  547. h.ServeHTTP(w, r)
  548. })
  549. }
  550. func localhostMiddleware(h http.Handler) http.Handler {
  551. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  552. if addressIsLocalhost(r.Host) {
  553. h.ServeHTTP(w, r)
  554. return
  555. }
  556. http.Error(w, "Host check error", http.StatusForbidden)
  557. })
  558. }
  559. func (s *service) whenDebugging(h http.Handler) http.Handler {
  560. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  561. if s.cfg.GUI().Debugging {
  562. h.ServeHTTP(w, r)
  563. return
  564. }
  565. http.Error(w, "Debugging disabled", http.StatusForbidden)
  566. })
  567. }
  568. func (s *service) getPendingDevices(w http.ResponseWriter, _ *http.Request) {
  569. devices, err := s.model.PendingDevices()
  570. if err != nil {
  571. http.Error(w, err.Error(), http.StatusInternalServerError)
  572. return
  573. }
  574. sendJSON(w, devices)
  575. }
  576. func (s *service) deletePendingDevices(w http.ResponseWriter, r *http.Request) {
  577. qs := r.URL.Query()
  578. device := qs.Get("device")
  579. deviceID, err := protocol.DeviceIDFromString(device)
  580. if err != nil {
  581. http.Error(w, err.Error(), http.StatusBadRequest)
  582. return
  583. }
  584. if err := s.model.DismissPendingDevice(deviceID); err != nil {
  585. http.Error(w, err.Error(), http.StatusInternalServerError)
  586. }
  587. }
  588. func (s *service) getPendingFolders(w http.ResponseWriter, r *http.Request) {
  589. qs := r.URL.Query()
  590. device := qs.Get("device")
  591. deviceID, err := protocol.DeviceIDFromString(device)
  592. if err != nil {
  593. http.Error(w, err.Error(), http.StatusBadRequest)
  594. return
  595. }
  596. folders, err := s.model.PendingFolders(deviceID)
  597. if err != nil {
  598. http.Error(w, err.Error(), http.StatusInternalServerError)
  599. return
  600. }
  601. sendJSON(w, folders)
  602. }
  603. func (s *service) deletePendingFolders(w http.ResponseWriter, r *http.Request) {
  604. qs := r.URL.Query()
  605. device := qs.Get("device")
  606. deviceID, err := protocol.DeviceIDFromString(device)
  607. if err != nil {
  608. http.Error(w, err.Error(), http.StatusBadRequest)
  609. return
  610. }
  611. folderID := qs.Get("folder")
  612. if err := s.model.DismissPendingFolder(deviceID, folderID); err != nil {
  613. http.Error(w, err.Error(), http.StatusInternalServerError)
  614. }
  615. }
  616. func (*service) restPing(w http.ResponseWriter, _ *http.Request) {
  617. sendJSON(w, map[string]string{"ping": "pong"})
  618. }
  619. func (*service) getSystemPaths(w http.ResponseWriter, _ *http.Request) {
  620. sendJSON(w, locations.ListExpandedPaths())
  621. }
  622. func (s *service) getJSMetadata(w http.ResponseWriter, _ *http.Request) {
  623. meta, _ := json.Marshal(map[string]interface{}{
  624. "deviceID": s.id.String(),
  625. "deviceIDShort": s.id.Short().String(),
  626. "authenticated": true,
  627. })
  628. w.Header().Set("Content-Type", "application/javascript")
  629. fmt.Fprintf(w, "var metadata = %s;\n", meta)
  630. }
  631. func (*service) getSystemVersion(w http.ResponseWriter, _ *http.Request) {
  632. sendJSON(w, map[string]interface{}{
  633. "version": build.Version,
  634. "codename": build.Codename,
  635. "longVersion": build.LongVersion,
  636. "extra": build.Extra,
  637. "os": runtime.GOOS,
  638. "arch": runtime.GOARCH,
  639. "isBeta": build.IsBeta,
  640. "isCandidate": build.IsCandidate,
  641. "isRelease": build.IsRelease,
  642. "date": build.Date,
  643. "tags": build.TagsList(),
  644. "stamp": build.Stamp,
  645. "user": build.User,
  646. "container": incontainer.Detect(),
  647. })
  648. }
  649. func (*service) getSystemDebug(w http.ResponseWriter, _ *http.Request) {
  650. names := l.Facilities()
  651. enabled := l.FacilityDebugging()
  652. sort.Strings(enabled)
  653. sendJSON(w, map[string]interface{}{
  654. "facilities": names,
  655. "enabled": enabled,
  656. })
  657. }
  658. func (*service) postSystemDebug(w http.ResponseWriter, r *http.Request) {
  659. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  660. q := r.URL.Query()
  661. for _, f := range strings.Split(q.Get("enable"), ",") {
  662. if f == "" || l.ShouldDebug(f) {
  663. continue
  664. }
  665. l.SetDebug(f, true)
  666. l.Infof("Enabled debug data for %q", f)
  667. }
  668. for _, f := range strings.Split(q.Get("disable"), ",") {
  669. if f == "" || !l.ShouldDebug(f) {
  670. continue
  671. }
  672. l.SetDebug(f, false)
  673. l.Infof("Disabled debug data for %q", f)
  674. }
  675. }
  676. func (s *service) getDBBrowse(w http.ResponseWriter, r *http.Request) {
  677. qs := r.URL.Query()
  678. folder := qs.Get("folder")
  679. prefix := qs.Get("prefix")
  680. dirsOnly := qs.Get("dirsonly") != ""
  681. levels, err := strconv.Atoi(qs.Get("levels"))
  682. if err != nil {
  683. levels = -1
  684. }
  685. result, err := s.model.GlobalDirectoryTree(folder, prefix, levels, dirsOnly)
  686. if err != nil {
  687. http.Error(w, err.Error(), http.StatusInternalServerError)
  688. return
  689. }
  690. sendJSON(w, result)
  691. }
  692. func (s *service) getDBCompletion(w http.ResponseWriter, r *http.Request) {
  693. qs := r.URL.Query()
  694. folder := qs.Get("folder") // empty means all folders
  695. deviceStr := qs.Get("device") // empty means local device ID
  696. // We will check completion status for either the local device, or a
  697. // specific given device ID.
  698. device := protocol.LocalDeviceID
  699. if deviceStr != "" {
  700. var err error
  701. device, err = protocol.DeviceIDFromString(deviceStr)
  702. if err != nil {
  703. http.Error(w, err.Error(), http.StatusBadRequest)
  704. return
  705. }
  706. }
  707. if comp, err := s.model.Completion(device, folder); err != nil {
  708. status := http.StatusInternalServerError
  709. if isFolderNotFound(err) {
  710. status = http.StatusNotFound
  711. }
  712. http.Error(w, err.Error(), status)
  713. } else {
  714. sendJSON(w, comp.Map())
  715. }
  716. }
  717. func (s *service) getDBStatus(w http.ResponseWriter, r *http.Request) {
  718. qs := r.URL.Query()
  719. folder := qs.Get("folder")
  720. if sum, err := s.fss.Summary(folder); err != nil {
  721. http.Error(w, err.Error(), http.StatusNotFound)
  722. } else {
  723. sendJSON(w, sum)
  724. }
  725. }
  726. func (s *service) postDBOverride(_ http.ResponseWriter, r *http.Request) {
  727. qs := r.URL.Query()
  728. folder := qs.Get("folder")
  729. go s.model.Override(folder)
  730. }
  731. func (s *service) postDBRevert(_ http.ResponseWriter, r *http.Request) {
  732. qs := r.URL.Query()
  733. folder := qs.Get("folder")
  734. go s.model.Revert(folder)
  735. }
  736. func getPagingParams(qs url.Values) (int, int) {
  737. page, err := strconv.Atoi(qs.Get("page"))
  738. if err != nil || page < 1 {
  739. page = 1
  740. }
  741. perpage, err := strconv.Atoi(qs.Get("perpage"))
  742. if err != nil || perpage < 1 {
  743. perpage = 1 << 16
  744. }
  745. return page, perpage
  746. }
  747. func (s *service) getDBNeed(w http.ResponseWriter, r *http.Request) {
  748. qs := r.URL.Query()
  749. folder := qs.Get("folder")
  750. page, perpage := getPagingParams(qs)
  751. progress, queued, rest, err := s.model.NeedFolderFiles(folder, page, perpage)
  752. if err != nil {
  753. http.Error(w, err.Error(), http.StatusNotFound)
  754. return
  755. }
  756. // Convert the struct to a more loose structure, and inject the size.
  757. sendJSON(w, map[string]interface{}{
  758. "progress": toJsonFileInfoSlice(progress),
  759. "queued": toJsonFileInfoSlice(queued),
  760. "rest": toJsonFileInfoSlice(rest),
  761. "page": page,
  762. "perpage": perpage,
  763. })
  764. }
  765. func (s *service) getDBRemoteNeed(w http.ResponseWriter, r *http.Request) {
  766. qs := r.URL.Query()
  767. folder := qs.Get("folder")
  768. device := qs.Get("device")
  769. deviceID, err := protocol.DeviceIDFromString(device)
  770. if err != nil {
  771. http.Error(w, err.Error(), http.StatusInternalServerError)
  772. return
  773. }
  774. page, perpage := getPagingParams(qs)
  775. files, err := s.model.RemoteNeedFolderFiles(folder, deviceID, page, perpage)
  776. if err != nil {
  777. http.Error(w, err.Error(), http.StatusNotFound)
  778. return
  779. }
  780. sendJSON(w, map[string]interface{}{
  781. "files": toJsonFileInfoSlice(files),
  782. "page": page,
  783. "perpage": perpage,
  784. })
  785. }
  786. func (s *service) getDBLocalChanged(w http.ResponseWriter, r *http.Request) {
  787. qs := r.URL.Query()
  788. folder := qs.Get("folder")
  789. page, perpage := getPagingParams(qs)
  790. files, err := s.model.LocalChangedFolderFiles(folder, page, perpage)
  791. if err != nil {
  792. http.Error(w, err.Error(), http.StatusNotFound)
  793. return
  794. }
  795. sendJSON(w, map[string]interface{}{
  796. "files": toJsonFileInfoSlice(files),
  797. "page": page,
  798. "perpage": perpage,
  799. })
  800. }
  801. func (s *service) getSystemConnections(w http.ResponseWriter, _ *http.Request) {
  802. sendJSON(w, s.model.ConnectionStats())
  803. }
  804. func (s *service) getDeviceStats(w http.ResponseWriter, _ *http.Request) {
  805. stats, err := s.model.DeviceStatistics()
  806. if err != nil {
  807. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  808. return
  809. }
  810. sendJSON(w, stats)
  811. }
  812. func (s *service) getFolderStats(w http.ResponseWriter, _ *http.Request) {
  813. stats, err := s.model.FolderStatistics()
  814. if err != nil {
  815. http.Error(w, "Internal Server Error", http.StatusInternalServerError)
  816. return
  817. }
  818. sendJSON(w, stats)
  819. }
  820. func (s *service) getDBFile(w http.ResponseWriter, r *http.Request) {
  821. qs := r.URL.Query()
  822. folder := qs.Get("folder")
  823. file := qs.Get("file")
  824. errStatus := http.StatusInternalServerError
  825. gf, gfOk, err := s.model.CurrentGlobalFile(folder, file)
  826. if err != nil {
  827. if isFolderNotFound(err) {
  828. errStatus = http.StatusNotFound
  829. }
  830. http.Error(w, err.Error(), errStatus)
  831. return
  832. }
  833. lf, lfOk, err := s.model.CurrentFolderFile(folder, file)
  834. if err != nil {
  835. if isFolderNotFound(err) {
  836. errStatus = http.StatusNotFound
  837. }
  838. http.Error(w, err.Error(), errStatus)
  839. return
  840. }
  841. if !(gfOk || lfOk) {
  842. // This file for sure does not exist.
  843. http.Error(w, "No such object in the index", http.StatusNotFound)
  844. return
  845. }
  846. av, err := s.model.Availability(folder, gf, protocol.BlockInfo{})
  847. if err != nil {
  848. http.Error(w, err.Error(), http.StatusInternalServerError)
  849. }
  850. mtimeMapping, mtimeErr := s.model.GetMtimeMapping(folder, file)
  851. sendJSON(w, map[string]interface{}{
  852. "global": jsonFileInfo(gf),
  853. "local": jsonFileInfo(lf),
  854. "availability": av,
  855. "mtime": map[string]interface{}{
  856. "err": mtimeErr,
  857. "value": mtimeMapping,
  858. },
  859. })
  860. }
  861. func (s *service) getDebugFile(w http.ResponseWriter, r *http.Request) {
  862. qs := r.URL.Query()
  863. folder := qs.Get("folder")
  864. file := qs.Get("file")
  865. snap, err := s.model.DBSnapshot(folder)
  866. if err != nil {
  867. http.Error(w, err.Error(), http.StatusNotFound)
  868. return
  869. }
  870. mtimeMapping, mtimeErr := s.model.GetMtimeMapping(folder, file)
  871. lf, _ := snap.Get(protocol.LocalDeviceID, file)
  872. gf, _ := snap.GetGlobal(file)
  873. av := snap.Availability(file)
  874. vl := snap.DebugGlobalVersions(file)
  875. sendJSON(w, map[string]interface{}{
  876. "global": jsonFileInfo(gf),
  877. "local": jsonFileInfo(lf),
  878. "availability": av,
  879. "globalVersions": vl.String(),
  880. "mtime": map[string]interface{}{
  881. "err": mtimeErr,
  882. "value": mtimeMapping,
  883. },
  884. })
  885. }
  886. func (s *service) postSystemRestart(w http.ResponseWriter, _ *http.Request) {
  887. s.flushResponse(`{"ok": "restarting"}`, w)
  888. s.fatal(&svcutil.FatalErr{
  889. Err: errors.New("restart initiated by rest API"),
  890. Status: svcutil.ExitRestart,
  891. })
  892. }
  893. func (s *service) postSystemReset(w http.ResponseWriter, r *http.Request) {
  894. qs := r.URL.Query()
  895. folder := qs.Get("folder")
  896. if len(folder) > 0 {
  897. if _, ok := s.cfg.Folders()[folder]; !ok {
  898. http.Error(w, "Invalid folder ID", http.StatusInternalServerError)
  899. return
  900. }
  901. }
  902. if folder == "" {
  903. // Reset all folders.
  904. for folder := range s.cfg.Folders() {
  905. if err := s.model.ResetFolder(folder); err != nil {
  906. http.Error(w, err.Error(), http.StatusInternalServerError)
  907. return
  908. }
  909. }
  910. s.flushResponse(`{"ok": "resetting database"}`, w)
  911. } else {
  912. // Reset a specific folder, assuming it's supposed to exist.
  913. if err := s.model.ResetFolder(folder); err != nil {
  914. http.Error(w, err.Error(), http.StatusInternalServerError)
  915. return
  916. }
  917. s.flushResponse(`{"ok": "resetting folder `+folder+`"}`, w)
  918. }
  919. s.fatal(&svcutil.FatalErr{
  920. Err: errors.New("restart after db reset initiated by rest API"),
  921. Status: svcutil.ExitRestart,
  922. })
  923. }
  924. func (s *service) postSystemShutdown(w http.ResponseWriter, _ *http.Request) {
  925. s.flushResponse(`{"ok": "shutting down"}`, w)
  926. s.fatal(&svcutil.FatalErr{
  927. Err: errors.New("shutdown initiated by rest API"),
  928. Status: svcutil.ExitSuccess,
  929. })
  930. }
  931. func (*service) flushResponse(resp string, w http.ResponseWriter) {
  932. w.Write([]byte(resp + "\n"))
  933. f := w.(http.Flusher)
  934. f.Flush()
  935. }
  936. func (s *service) getSystemStatus(w http.ResponseWriter, _ *http.Request) {
  937. var m runtime.MemStats
  938. runtime.ReadMemStats(&m)
  939. tilde, _ := fs.ExpandTilde("~")
  940. res := make(map[string]interface{})
  941. res["myID"] = s.id.String()
  942. res["goroutines"] = runtime.NumGoroutine()
  943. res["alloc"] = m.Alloc
  944. res["sys"] = m.Sys - m.HeapReleased
  945. res["tilde"] = tilde
  946. if s.cfg.Options().LocalAnnEnabled || s.cfg.Options().GlobalAnnEnabled {
  947. res["discoveryEnabled"] = true
  948. discoStatus := s.discoverer.ChildErrors()
  949. res["discoveryStatus"] = discoveryStatusMap(discoStatus)
  950. res["discoveryMethods"] = len(discoStatus) // DEPRECATED: Redundant, only for backwards compatibility, should be removed.
  951. discoErrors := make(map[string]*string, len(discoStatus))
  952. for s, e := range discoStatus {
  953. if e != nil {
  954. discoErrors[s] = errorString(e)
  955. }
  956. }
  957. res["discoveryErrors"] = discoErrors // DEPRECATED: Redundant, only for backwards compatibility, should be removed.
  958. }
  959. res["connectionServiceStatus"] = s.connectionsService.ListenerStatus()
  960. res["lastDialStatus"] = s.connectionsService.ConnectionStatus()
  961. res["cpuPercent"] = 0 // deprecated from API
  962. res["pathSeparator"] = string(filepath.Separator)
  963. res["urVersionMax"] = ur.Version
  964. res["uptime"] = s.urService.UptimeS()
  965. res["startTime"] = ur.StartTime
  966. res["guiAddressOverridden"] = s.cfg.GUI().IsOverridden()
  967. res["guiAddressUsed"] = s.listenerAddr.String()
  968. sendJSON(w, res)
  969. }
  970. func (s *service) getSystemError(w http.ResponseWriter, _ *http.Request) {
  971. sendJSON(w, map[string][]logger.Line{
  972. "errors": s.guiErrors.Since(time.Time{}),
  973. })
  974. }
  975. func (*service) postSystemError(_ http.ResponseWriter, r *http.Request) {
  976. bs, _ := io.ReadAll(r.Body)
  977. r.Body.Close()
  978. l.Warnln(string(bs))
  979. }
  980. func (s *service) postSystemErrorClear(_ http.ResponseWriter, _ *http.Request) {
  981. s.guiErrors.Clear()
  982. }
  983. func (s *service) getSystemLog(w http.ResponseWriter, r *http.Request) {
  984. q := r.URL.Query()
  985. since, err := time.Parse(time.RFC3339, q.Get("since"))
  986. if err != nil {
  987. l.Debugln(err)
  988. }
  989. sendJSON(w, map[string][]logger.Line{
  990. "messages": s.systemLog.Since(since),
  991. })
  992. }
  993. func (s *service) getSystemLogTxt(w http.ResponseWriter, r *http.Request) {
  994. q := r.URL.Query()
  995. since, err := time.Parse(time.RFC3339, q.Get("since"))
  996. if err != nil {
  997. l.Debugln(err)
  998. }
  999. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  1000. for _, line := range s.systemLog.Since(since) {
  1001. fmt.Fprintf(w, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  1002. }
  1003. }
  1004. type fileEntry struct {
  1005. name string
  1006. data []byte
  1007. }
  1008. func (s *service) getSupportBundle(w http.ResponseWriter, r *http.Request) {
  1009. var files []fileEntry
  1010. // Redacted configuration as a JSON
  1011. if jsonConfig, err := json.MarshalIndent(getRedactedConfig(s), "", " "); err != nil {
  1012. l.Warnln("Support bundle: failed to create config.json:", err)
  1013. } else {
  1014. files = append(files, fileEntry{name: "config.json.txt", data: jsonConfig})
  1015. }
  1016. // Log as a text
  1017. var buflog bytes.Buffer
  1018. for _, line := range s.systemLog.Since(time.Time{}) {
  1019. fmt.Fprintf(&buflog, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  1020. }
  1021. files = append(files, fileEntry{name: "log-inmemory.txt", data: buflog.Bytes()})
  1022. // Errors as a JSON
  1023. if errs := s.guiErrors.Since(time.Time{}); len(errs) > 0 {
  1024. if jsonError, err := json.MarshalIndent(errs, "", " "); err != nil {
  1025. l.Warnln("Support bundle: failed to create errors.json:", err)
  1026. } else {
  1027. files = append(files, fileEntry{name: "errors.json.txt", data: jsonError})
  1028. }
  1029. }
  1030. // Panic files
  1031. if panicFiles, err := filepath.Glob(filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), "panic*")); err == nil {
  1032. for _, f := range panicFiles {
  1033. if panicFile, err := os.ReadFile(f); err != nil {
  1034. l.Warnf("Support bundle: failed to load %s: %s", filepath.Base(f), err)
  1035. } else {
  1036. files = append(files, fileEntry{name: filepath.Base(f), data: panicFile})
  1037. }
  1038. }
  1039. }
  1040. // Archived log (default on Windows)
  1041. if logFile, err := os.ReadFile(locations.Get(locations.LogFile)); err == nil {
  1042. files = append(files, fileEntry{name: "log-ondisk.txt", data: logFile})
  1043. }
  1044. // Version and platform information as a JSON
  1045. if versionPlatform, err := json.MarshalIndent(map[string]string{
  1046. "now": time.Now().Format(time.RFC3339),
  1047. "version": build.Version,
  1048. "codename": build.Codename,
  1049. "longVersion": build.LongVersion,
  1050. "os": runtime.GOOS,
  1051. "arch": runtime.GOARCH,
  1052. }, "", " "); err == nil {
  1053. files = append(files, fileEntry{name: "version-platform.json.txt", data: versionPlatform})
  1054. } else {
  1055. l.Warnln("Failed to create versionPlatform.json: ", err)
  1056. }
  1057. // Report Data as a JSON
  1058. if r, err := s.urService.ReportDataPreview(r.Context(), ur.Version); err != nil {
  1059. l.Warnln("Support bundle: failed to create usage-reporting.json.txt:", err)
  1060. } else {
  1061. if usageReportingData, err := json.MarshalIndent(r, "", " "); err != nil {
  1062. l.Warnln("Support bundle: failed to serialize usage-reporting.json.txt", err)
  1063. } else {
  1064. files = append(files, fileEntry{name: "usage-reporting.json.txt", data: usageReportingData})
  1065. }
  1066. }
  1067. // Metrics data as text
  1068. buf := bytes.NewBuffer(nil)
  1069. wr := bufferedResponseWriter{Writer: buf}
  1070. promhttp.Handler().ServeHTTP(wr, &http.Request{Method: http.MethodGet})
  1071. files = append(files, fileEntry{name: "metrics.txt", data: buf.Bytes()})
  1072. // Connection data as JSON
  1073. connStats := s.model.ConnectionStats()
  1074. if connStatsJSON, err := json.MarshalIndent(connStats, "", " "); err != nil {
  1075. l.Warnln("Support bundle: failed to serialize connection-stats.json.txt", err)
  1076. } else {
  1077. files = append(files, fileEntry{name: "connection-stats.json.txt", data: connStatsJSON})
  1078. }
  1079. // Heap and CPU Proofs as a pprof extension
  1080. var heapBuffer, cpuBuffer bytes.Buffer
  1081. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1082. runtime.GC()
  1083. if err := pprof.WriteHeapProfile(&heapBuffer); err == nil {
  1084. files = append(files, fileEntry{name: filename, data: heapBuffer.Bytes()})
  1085. }
  1086. const duration = 4 * time.Second
  1087. filename = fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1088. if err := pprof.StartCPUProfile(&cpuBuffer); err == nil {
  1089. time.Sleep(duration)
  1090. pprof.StopCPUProfile()
  1091. files = append(files, fileEntry{name: filename, data: cpuBuffer.Bytes()})
  1092. }
  1093. // Add buffer files to buffer zip
  1094. var zipFilesBuffer bytes.Buffer
  1095. if err := writeZip(&zipFilesBuffer, files); err != nil {
  1096. l.Warnln("Support bundle: failed to create support bundle zip:", err)
  1097. http.Error(w, err.Error(), http.StatusInternalServerError)
  1098. return
  1099. }
  1100. // Set zip file name and path
  1101. zipFileName := fmt.Sprintf("support-bundle-%s-%s.zip", s.id.Short().String(), time.Now().Format("2006-01-02T150405"))
  1102. zipFilePath := filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), zipFileName)
  1103. // Write buffer zip to local zip file (back up)
  1104. if err := os.WriteFile(zipFilePath, zipFilesBuffer.Bytes(), 0o600); err != nil {
  1105. l.Warnln("Support bundle: support bundle zip could not be created:", err)
  1106. }
  1107. // Serve the buffer zip to client for download
  1108. w.Header().Set("Content-Type", "application/zip")
  1109. w.Header().Set("Content-Disposition", "attachment; filename="+zipFileName)
  1110. io.Copy(w, &zipFilesBuffer)
  1111. }
  1112. func (*service) getSystemHTTPMetrics(w http.ResponseWriter, _ *http.Request) {
  1113. stats := make(map[string]interface{})
  1114. metrics.Each(func(name string, intf interface{}) {
  1115. if m, ok := intf.(*metrics.StandardTimer); ok {
  1116. pct := m.Percentiles([]float64{0.50, 0.95, 0.99})
  1117. for i := range pct {
  1118. pct[i] /= 1e6 // ns to ms
  1119. }
  1120. stats[name] = map[string]interface{}{
  1121. "count": m.Count(),
  1122. "sumMs": m.Sum() / 1e6, // ns to ms
  1123. "ratesPerS": []float64{m.Rate1(), m.Rate5(), m.Rate15()},
  1124. "percentilesMs": pct,
  1125. }
  1126. }
  1127. })
  1128. bs, _ := json.MarshalIndent(stats, "", " ")
  1129. w.Write(bs)
  1130. }
  1131. func (s *service) getSystemDiscovery(w http.ResponseWriter, _ *http.Request) {
  1132. devices := make(map[string]discover.CacheEntry)
  1133. if s.discoverer != nil {
  1134. // Device ids can't be marshalled as keys so we need to manually
  1135. // rebuild this map using strings. Discoverer may be nil if discovery
  1136. // has not started yet.
  1137. for device, entry := range s.discoverer.Cache() {
  1138. devices[device.String()] = entry
  1139. }
  1140. }
  1141. sendJSON(w, devices)
  1142. }
  1143. func (s *service) getReport(w http.ResponseWriter, r *http.Request) {
  1144. version := ur.Version
  1145. if val, _ := strconv.Atoi(r.URL.Query().Get("version")); val > 0 {
  1146. version = val
  1147. }
  1148. if r, err := s.urService.ReportDataPreview(context.TODO(), version); err != nil {
  1149. http.Error(w, err.Error(), http.StatusInternalServerError)
  1150. return
  1151. } else {
  1152. sendJSON(w, r)
  1153. }
  1154. }
  1155. func (*service) getRandomString(w http.ResponseWriter, r *http.Request) {
  1156. length := 32
  1157. if val, _ := strconv.Atoi(r.URL.Query().Get("length")); val > 0 {
  1158. length = val
  1159. }
  1160. str := rand.String(length)
  1161. sendJSON(w, map[string]string{"random": str})
  1162. }
  1163. func (s *service) getDBIgnores(w http.ResponseWriter, r *http.Request) {
  1164. qs := r.URL.Query()
  1165. folder := qs.Get("folder")
  1166. lines, patterns, err := s.model.LoadIgnores(folder)
  1167. if err != nil && !ignore.IsParseError(err) {
  1168. http.Error(w, err.Error(), http.StatusInternalServerError)
  1169. return
  1170. }
  1171. sendJSON(w, map[string]interface{}{
  1172. "ignore": lines,
  1173. "expanded": patterns,
  1174. "error": errorString(err),
  1175. })
  1176. }
  1177. func (s *service) postDBIgnores(w http.ResponseWriter, r *http.Request) {
  1178. qs := r.URL.Query()
  1179. bs, err := io.ReadAll(r.Body)
  1180. r.Body.Close()
  1181. if err != nil {
  1182. http.Error(w, err.Error(), http.StatusInternalServerError)
  1183. return
  1184. }
  1185. var data map[string][]string
  1186. err = json.Unmarshal(bs, &data)
  1187. if err != nil {
  1188. http.Error(w, err.Error(), http.StatusInternalServerError)
  1189. return
  1190. }
  1191. err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
  1192. if err != nil {
  1193. http.Error(w, err.Error(), http.StatusInternalServerError)
  1194. return
  1195. }
  1196. s.getDBIgnores(w, r)
  1197. }
  1198. func (s *service) getIndexEvents(w http.ResponseWriter, r *http.Request) {
  1199. mask := s.getEventMask(r.URL.Query().Get("events"))
  1200. sub := s.getEventSub(mask)
  1201. s.getEvents(w, r, sub)
  1202. }
  1203. func (s *service) getDiskEvents(w http.ResponseWriter, r *http.Request) {
  1204. sub := s.getEventSub(DiskEventMask)
  1205. s.getEvents(w, r, sub)
  1206. }
  1207. func (s *service) getEvents(w http.ResponseWriter, r *http.Request, eventSub events.BufferedSubscription) {
  1208. if eventSub.Mask()&(events.FolderSummary|events.FolderCompletion) != 0 {
  1209. s.fss.OnEventRequest()
  1210. }
  1211. qs := r.URL.Query()
  1212. sinceStr := qs.Get("since")
  1213. limitStr := qs.Get("limit")
  1214. timeoutStr := qs.Get("timeout")
  1215. since, _ := strconv.Atoi(sinceStr)
  1216. limit, _ := strconv.Atoi(limitStr)
  1217. timeout := defaultEventTimeout
  1218. if timeoutSec, timeoutErr := strconv.Atoi(timeoutStr); timeoutErr == nil && timeoutSec >= 0 { // 0 is a valid timeout
  1219. timeout = time.Duration(timeoutSec) * time.Second
  1220. }
  1221. // Flush before blocking, to indicate that we've received the request and
  1222. // that it should not be retried. Must set Content-Type header before
  1223. // flushing.
  1224. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  1225. f := w.(http.Flusher)
  1226. f.Flush()
  1227. // If there are no events available return an empty slice, as this gets serialized as `[]`
  1228. evs := eventSub.Since(since, []events.Event{}, timeout)
  1229. if 0 < limit && limit < len(evs) {
  1230. evs = evs[len(evs)-limit:]
  1231. }
  1232. sendJSON(w, evs)
  1233. }
  1234. func (*service) getEventMask(evs string) events.EventType {
  1235. eventMask := DefaultEventMask
  1236. if evs != "" {
  1237. eventList := strings.Split(evs, ",")
  1238. eventMask = 0
  1239. for _, ev := range eventList {
  1240. eventMask |= events.UnmarshalEventType(strings.TrimSpace(ev))
  1241. }
  1242. }
  1243. return eventMask
  1244. }
  1245. func (s *service) getEventSub(mask events.EventType) events.BufferedSubscription {
  1246. s.eventSubsMut.Lock()
  1247. bufsub, ok := s.eventSubs[mask]
  1248. if !ok {
  1249. evsub := s.evLogger.Subscribe(mask)
  1250. bufsub = events.NewBufferedSubscription(evsub, EventSubBufferSize)
  1251. s.eventSubs[mask] = bufsub
  1252. }
  1253. s.eventSubsMut.Unlock()
  1254. return bufsub
  1255. }
  1256. func (s *service) getSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
  1257. if s.noUpgrade {
  1258. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
  1259. return
  1260. }
  1261. opts := s.cfg.Options()
  1262. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1263. if err != nil {
  1264. httpError(w, err)
  1265. return
  1266. }
  1267. res := make(map[string]interface{})
  1268. res["running"] = build.Version
  1269. res["latest"] = rel.Tag
  1270. res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer
  1271. res["majorNewer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.MajorNewer
  1272. sendJSON(w, res)
  1273. }
  1274. func (*service) getDeviceID(w http.ResponseWriter, r *http.Request) {
  1275. qs := r.URL.Query()
  1276. idStr := qs.Get("id")
  1277. id, err := protocol.DeviceIDFromString(idStr)
  1278. if err == nil {
  1279. sendJSON(w, map[string]string{
  1280. "id": id.String(),
  1281. })
  1282. } else {
  1283. sendJSON(w, map[string]string{
  1284. "error": err.Error(),
  1285. })
  1286. }
  1287. }
  1288. func (*service) getLang(w http.ResponseWriter, r *http.Request) {
  1289. lang := r.Header.Get("Accept-Language")
  1290. var langs []string
  1291. for _, l := range strings.Split(lang, ",") {
  1292. parts := strings.SplitN(l, ";", 2)
  1293. langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0])))
  1294. }
  1295. sendJSON(w, langs)
  1296. }
  1297. func (s *service) postSystemUpgrade(w http.ResponseWriter, _ *http.Request) {
  1298. opts := s.cfg.Options()
  1299. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1300. if err != nil {
  1301. httpError(w, err)
  1302. return
  1303. }
  1304. if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
  1305. err = upgrade.To(rel)
  1306. if err != nil {
  1307. l.Warnln("upgrading:", err)
  1308. http.Error(w, err.Error(), http.StatusInternalServerError)
  1309. return
  1310. }
  1311. s.flushResponse(`{"ok": "restarting"}`, w)
  1312. s.fatal(&svcutil.FatalErr{
  1313. Err: errors.New("exit after upgrade initiated by rest API"),
  1314. Status: svcutil.ExitUpgrade,
  1315. })
  1316. }
  1317. }
  1318. func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
  1319. return func(w http.ResponseWriter, r *http.Request) {
  1320. qs := r.URL.Query()
  1321. deviceStr := qs.Get("device")
  1322. var msg string
  1323. var status int
  1324. _, err := s.cfg.Modify(func(cfg *config.Configuration) {
  1325. if deviceStr == "" {
  1326. for i := range cfg.Devices {
  1327. cfg.Devices[i].Paused = paused
  1328. }
  1329. return
  1330. }
  1331. device, err := protocol.DeviceIDFromString(deviceStr)
  1332. if err != nil {
  1333. msg = err.Error()
  1334. status = 500
  1335. return
  1336. }
  1337. _, i, ok := cfg.Device(device)
  1338. if !ok {
  1339. msg = "not found"
  1340. status = http.StatusNotFound
  1341. return
  1342. }
  1343. cfg.Devices[i].Paused = paused
  1344. })
  1345. if msg != "" {
  1346. http.Error(w, msg, status)
  1347. } else if err != nil {
  1348. http.Error(w, err.Error(), http.StatusInternalServerError)
  1349. }
  1350. }
  1351. }
  1352. func (s *service) postDBScan(w http.ResponseWriter, r *http.Request) {
  1353. qs := r.URL.Query()
  1354. folder := qs.Get("folder")
  1355. if folder != "" {
  1356. subs := qs["sub"]
  1357. err := s.model.ScanFolderSubdirs(folder, subs)
  1358. if err != nil {
  1359. http.Error(w, err.Error(), http.StatusInternalServerError)
  1360. return
  1361. }
  1362. nextStr := qs.Get("next")
  1363. next, err := strconv.Atoi(nextStr)
  1364. if err == nil {
  1365. s.model.DelayScan(folder, time.Duration(next)*time.Second)
  1366. }
  1367. } else {
  1368. errors := s.model.ScanFolders()
  1369. if len(errors) > 0 {
  1370. http.Error(w, "Error scanning folders", http.StatusInternalServerError)
  1371. sendJSON(w, errors)
  1372. return
  1373. }
  1374. }
  1375. }
  1376. func (s *service) postDBPrio(w http.ResponseWriter, r *http.Request) {
  1377. qs := r.URL.Query()
  1378. folder := qs.Get("folder")
  1379. file := qs.Get("file")
  1380. s.model.BringToFront(folder, file)
  1381. s.getDBNeed(w, r)
  1382. }
  1383. func (*service) getHealth(w http.ResponseWriter, _ *http.Request) {
  1384. sendJSON(w, map[string]string{"status": "OK"})
  1385. }
  1386. func (*service) getQR(w http.ResponseWriter, r *http.Request) {
  1387. qs := r.URL.Query()
  1388. text := qs.Get("text")
  1389. code, err := qr.Encode(text, qr.M)
  1390. if err != nil {
  1391. http.Error(w, "Invalid", http.StatusInternalServerError)
  1392. return
  1393. }
  1394. w.Header().Set("Content-Type", "image/png")
  1395. w.Write(code.PNG())
  1396. }
  1397. func (s *service) getPeerCompletion(w http.ResponseWriter, _ *http.Request) {
  1398. tot := map[string]float64{}
  1399. count := map[string]float64{}
  1400. for _, folder := range s.cfg.Folders() {
  1401. for _, device := range folder.DeviceIDs() {
  1402. deviceStr := device.String()
  1403. if s.model.ConnectedTo(device) {
  1404. comp, err := s.model.Completion(device, folder.ID)
  1405. if err != nil {
  1406. http.Error(w, err.Error(), http.StatusInternalServerError)
  1407. return
  1408. }
  1409. tot[deviceStr] += comp.CompletionPct
  1410. } else {
  1411. tot[deviceStr] = 0
  1412. }
  1413. count[deviceStr]++
  1414. }
  1415. }
  1416. comp := map[string]int{}
  1417. for device := range tot {
  1418. comp[device] = int(tot[device] / count[device])
  1419. }
  1420. sendJSON(w, comp)
  1421. }
  1422. func (s *service) getFolderVersions(w http.ResponseWriter, r *http.Request) {
  1423. qs := r.URL.Query()
  1424. versions, err := s.model.GetFolderVersions(qs.Get("folder"))
  1425. if err != nil {
  1426. http.Error(w, err.Error(), http.StatusInternalServerError)
  1427. return
  1428. }
  1429. sendJSON(w, versions)
  1430. }
  1431. func (s *service) postFolderVersionsRestore(w http.ResponseWriter, r *http.Request) {
  1432. qs := r.URL.Query()
  1433. bs, err := io.ReadAll(r.Body)
  1434. r.Body.Close()
  1435. if err != nil {
  1436. http.Error(w, err.Error(), http.StatusInternalServerError)
  1437. return
  1438. }
  1439. var versions map[string]time.Time
  1440. err = json.Unmarshal(bs, &versions)
  1441. if err != nil {
  1442. http.Error(w, err.Error(), http.StatusInternalServerError)
  1443. return
  1444. }
  1445. ferr, err := s.model.RestoreFolderVersions(qs.Get("folder"), versions)
  1446. if err != nil {
  1447. http.Error(w, err.Error(), http.StatusInternalServerError)
  1448. return
  1449. }
  1450. sendJSON(w, errorStringMap(ferr))
  1451. }
  1452. func (s *service) getFolderErrors(w http.ResponseWriter, r *http.Request) {
  1453. qs := r.URL.Query()
  1454. folder := qs.Get("folder")
  1455. page, perpage := getPagingParams(qs)
  1456. errors, err := s.model.FolderErrors(folder)
  1457. if err != nil {
  1458. http.Error(w, err.Error(), http.StatusNotFound)
  1459. return
  1460. }
  1461. start := (page - 1) * perpage
  1462. if start >= len(errors) {
  1463. errors = nil
  1464. } else {
  1465. errors = errors[start:]
  1466. if perpage < len(errors) {
  1467. errors = errors[:perpage]
  1468. }
  1469. }
  1470. sendJSON(w, map[string]interface{}{
  1471. "folder": folder,
  1472. "errors": errors,
  1473. "page": page,
  1474. "perpage": perpage,
  1475. })
  1476. }
  1477. func (*service) getSystemBrowse(w http.ResponseWriter, r *http.Request) {
  1478. qs := r.URL.Query()
  1479. current := qs.Get("current")
  1480. // Default value or in case of error unmarshalling ends up being basic fs.
  1481. var fsType fs.FilesystemType
  1482. fsType.UnmarshalText([]byte(qs.Get("filesystem")))
  1483. sendJSON(w, browse(fsType, current))
  1484. }
  1485. func browse(fsType fs.FilesystemType, current string) []string {
  1486. if current == "" {
  1487. return browseRoots(fsType)
  1488. }
  1489. parent, base := parentAndBase(current)
  1490. ffs := fs.NewFilesystem(fsType, parent)
  1491. files := browseFiles(ffs, base)
  1492. for i := range files {
  1493. files[i] = filepath.Join(parent, files[i])
  1494. }
  1495. return files
  1496. }
  1497. const (
  1498. matchExact int = iota
  1499. matchCaseIns
  1500. noMatch
  1501. )
  1502. func checkPrefixMatch(s, prefix string) int {
  1503. if strings.HasPrefix(s, prefix) {
  1504. return matchExact
  1505. }
  1506. if strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
  1507. return matchCaseIns
  1508. }
  1509. return noMatch
  1510. }
  1511. func browseRoots(fsType fs.FilesystemType) []string {
  1512. filesystem := fs.NewFilesystem(fsType, "")
  1513. if roots, err := filesystem.Roots(); err == nil {
  1514. return roots
  1515. }
  1516. return nil
  1517. }
  1518. // parentAndBase returns the parent directory and the remaining base of the
  1519. // path. The base may be empty if the path ends with a path separator.
  1520. func parentAndBase(current string) (string, string) {
  1521. search, _ := fs.ExpandTilde(current)
  1522. pathSeparator := string(fs.PathSeparator)
  1523. if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) {
  1524. search = search + pathSeparator
  1525. }
  1526. searchDir := filepath.Dir(search)
  1527. // The searchFile should be the last component of search, or empty if it
  1528. // ends with a path separator
  1529. var searchFile string
  1530. if !strings.HasSuffix(search, pathSeparator) {
  1531. searchFile = filepath.Base(search)
  1532. }
  1533. return searchDir, searchFile
  1534. }
  1535. func browseFiles(ffs fs.Filesystem, search string) []string {
  1536. subdirectories, _ := ffs.DirNames(".")
  1537. pathSeparator := string(fs.PathSeparator)
  1538. exactMatches := make([]string, 0, len(subdirectories))
  1539. caseInsMatches := make([]string, 0, len(subdirectories))
  1540. for _, subdirectory := range subdirectories {
  1541. info, err := ffs.Stat(subdirectory)
  1542. if err != nil || !info.IsDir() {
  1543. continue
  1544. }
  1545. switch checkPrefixMatch(subdirectory, search) {
  1546. case matchExact:
  1547. exactMatches = append(exactMatches, subdirectory+pathSeparator)
  1548. case matchCaseIns:
  1549. caseInsMatches = append(caseInsMatches, subdirectory+pathSeparator)
  1550. }
  1551. }
  1552. // sort to return matches in deterministic order (don't depend on file system order)
  1553. sort.Strings(exactMatches)
  1554. sort.Strings(caseInsMatches)
  1555. return append(exactMatches, caseInsMatches...)
  1556. }
  1557. func (*service) getCPUProf(w http.ResponseWriter, r *http.Request) {
  1558. duration, err := time.ParseDuration(r.FormValue("duration"))
  1559. if err != nil {
  1560. duration = 30 * time.Second
  1561. }
  1562. filename := fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1563. w.Header().Set("Content-Type", "application/octet-stream")
  1564. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1565. if err := pprof.StartCPUProfile(w); err == nil {
  1566. time.Sleep(duration)
  1567. pprof.StopCPUProfile()
  1568. }
  1569. }
  1570. func (*service) getHeapProf(w http.ResponseWriter, _ *http.Request) {
  1571. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1572. w.Header().Set("Content-Type", "application/octet-stream")
  1573. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1574. runtime.GC()
  1575. pprof.WriteHeapProfile(w)
  1576. }
  1577. func toJsonFileInfoSlice(fs []db.FileInfoTruncated) []jsonFileInfoTrunc {
  1578. res := make([]jsonFileInfoTrunc, len(fs))
  1579. for i, f := range fs {
  1580. res[i] = jsonFileInfoTrunc(f)
  1581. }
  1582. return res
  1583. }
  1584. // Type wrappers for nice JSON serialization
  1585. type jsonFileInfo protocol.FileInfo
  1586. func (f jsonFileInfo) MarshalJSON() ([]byte, error) {
  1587. m := fileIntfJSONMap(protocol.FileInfo(f))
  1588. m["numBlocks"] = len(f.Blocks)
  1589. return json.Marshal(m)
  1590. }
  1591. type jsonFileInfoTrunc db.FileInfoTruncated
  1592. func (f jsonFileInfoTrunc) MarshalJSON() ([]byte, error) {
  1593. m := fileIntfJSONMap(db.FileInfoTruncated(f))
  1594. m["numBlocks"] = nil // explicitly unknown
  1595. return json.Marshal(m)
  1596. }
  1597. func fileIntfJSONMap(f protocol.FileIntf) map[string]interface{} {
  1598. out := map[string]interface{}{
  1599. "name": f.FileName(),
  1600. "type": f.FileType().String(),
  1601. "size": f.FileSize(),
  1602. "deleted": f.IsDeleted(),
  1603. "invalid": f.IsInvalid(),
  1604. "ignored": f.IsIgnored(),
  1605. "mustRescan": f.MustRescan(),
  1606. "noPermissions": !f.HasPermissionBits(),
  1607. "modified": f.ModTime(),
  1608. "modifiedBy": f.FileModifiedBy().String(),
  1609. "sequence": f.SequenceNo(),
  1610. "version": jsonVersionVector(f.FileVersion()),
  1611. "localFlags": f.FileLocalFlags(),
  1612. "platform": f.PlatformData(),
  1613. "inodeChange": f.InodeChangeTime(),
  1614. "blocksHash": f.FileBlocksHash(),
  1615. }
  1616. if f.HasPermissionBits() {
  1617. out["permissions"] = fmt.Sprintf("%#o", f.FilePermissions())
  1618. }
  1619. return out
  1620. }
  1621. type jsonVersionVector protocol.Vector
  1622. func (v jsonVersionVector) MarshalJSON() ([]byte, error) {
  1623. res := make([]string, len(v.Counters))
  1624. for i, c := range v.Counters {
  1625. res[i] = fmt.Sprintf("%v:%d", c.ID, c.Value)
  1626. }
  1627. return json.Marshal(res)
  1628. }
  1629. func dirNames(dir string) []string {
  1630. fis, err := os.ReadDir(dir)
  1631. if err != nil {
  1632. return nil
  1633. }
  1634. var dirs []string
  1635. for _, fi := range fis {
  1636. if fi.IsDir() {
  1637. dirs = append(dirs, filepath.Base(fi.Name()))
  1638. }
  1639. }
  1640. sort.Strings(dirs)
  1641. return dirs
  1642. }
  1643. func addressIsLocalhost(addr string) bool {
  1644. host, _, err := net.SplitHostPort(addr)
  1645. if err != nil {
  1646. // There was no port, so we assume the address was just a hostname
  1647. host = addr
  1648. }
  1649. host = strings.ToLower(host)
  1650. switch {
  1651. case host == "localhost":
  1652. return true
  1653. case host == "localhost.":
  1654. return true
  1655. case strings.HasSuffix(host, ".localhost"):
  1656. return true
  1657. default:
  1658. ip := net.ParseIP(host)
  1659. if ip == nil {
  1660. // not an IP address
  1661. return false
  1662. }
  1663. return ip.IsLoopback()
  1664. }
  1665. }
  1666. // shouldRegenerateCertificate checks for certificate expiry or other known
  1667. // issues with our API/GUI certificate and returns either nil (leave the
  1668. // certificate alone) or an error describing the reason the certificate
  1669. // should be regenerated.
  1670. func shouldRegenerateCertificate(cert tls.Certificate) error {
  1671. leaf := cert.Leaf
  1672. if leaf == nil {
  1673. // Leaf can be nil or not, depending on how parsed the certificate
  1674. // was when we got it.
  1675. if len(cert.Certificate) < 1 {
  1676. // can't happen
  1677. return errors.New("no certificate in certificate")
  1678. }
  1679. var err error
  1680. leaf, err = x509.ParseCertificate(cert.Certificate[0])
  1681. if err != nil {
  1682. return err
  1683. }
  1684. }
  1685. if leaf.Subject.String() != leaf.Issuer.String() || len(leaf.IPAddresses) != 0 {
  1686. // The certificate is not self signed, or has IP attributes we don't
  1687. // add, so we leave it alone.
  1688. return nil
  1689. }
  1690. if len(leaf.DNSNames) > 1 {
  1691. // The certificate has more DNS SANs attributes than we ever add, so
  1692. // we leave it alone.
  1693. return nil
  1694. }
  1695. if len(leaf.DNSNames) == 1 && leaf.DNSNames[0] != leaf.Issuer.CommonName {
  1696. // The one SAN is different from the issuer, so it's not one of our
  1697. // newer self signed certificates.
  1698. return nil
  1699. }
  1700. if leaf.NotAfter.Before(time.Now()) {
  1701. return errors.New("certificate has expired")
  1702. }
  1703. if leaf.NotAfter.Before(time.Now().Add(30 * 24 * time.Hour)) {
  1704. return errors.New("certificate will soon expire")
  1705. }
  1706. // On macOS, check for certificates issued on or after July 1st, 2019,
  1707. // with a longer validity time than 825 days.
  1708. cutoff := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
  1709. if build.IsDarwin &&
  1710. leaf.NotBefore.After(cutoff) &&
  1711. leaf.NotAfter.Sub(leaf.NotBefore) > 825*24*time.Hour {
  1712. return errors.New("certificate incompatible with macOS 10.15 (Catalina)")
  1713. }
  1714. return nil
  1715. }
  1716. func errorStringMap(errs map[string]error) map[string]*string {
  1717. out := make(map[string]*string, len(errs))
  1718. for s, e := range errs {
  1719. out[s] = errorString(e)
  1720. }
  1721. return out
  1722. }
  1723. func errorString(err error) *string {
  1724. if err != nil {
  1725. msg := err.Error()
  1726. return &msg
  1727. }
  1728. return nil
  1729. }
  1730. type discoveryStatusEntry struct {
  1731. Error *string `json:"error"`
  1732. }
  1733. func discoveryStatusMap(errs map[string]error) map[string]discoveryStatusEntry {
  1734. out := make(map[string]discoveryStatusEntry, len(errs))
  1735. for s, e := range errs {
  1736. out[s] = discoveryStatusEntry{
  1737. Error: errorString(e),
  1738. }
  1739. }
  1740. return out
  1741. }
  1742. // sanitizedHostname returns the given name in a suitable form for use as
  1743. // the common name in a certificate, or an error.
  1744. func sanitizedHostname(name string) (string, error) {
  1745. // Remove diacritics and non-alphanumerics. This works by first
  1746. // transforming into normalization form D (things with diacriticals are
  1747. // split into the base character and the mark) and then removing
  1748. // undesired characters.
  1749. t := transform.Chain(
  1750. // Split runes with diacritics into base character and mark.
  1751. norm.NFD,
  1752. // Leave only [A-Za-z0-9-.].
  1753. runes.Remove(runes.Predicate(func(r rune) bool {
  1754. return r > unicode.MaxASCII ||
  1755. !unicode.IsLetter(r) && !unicode.IsNumber(r) &&
  1756. r != '.' && r != '-'
  1757. })))
  1758. name, _, err := transform.String(t, name)
  1759. if err != nil {
  1760. return "", err
  1761. }
  1762. // Name should not start or end with a dash or dot.
  1763. name = strings.Trim(name, "-.")
  1764. // Name should not be empty.
  1765. if name == "" {
  1766. return "", errors.New("no suitable name")
  1767. }
  1768. return strings.ToLower(name), nil
  1769. }
  1770. func isFolderNotFound(err error) bool {
  1771. for _, target := range []error{
  1772. model.ErrFolderMissing,
  1773. model.ErrFolderPaused,
  1774. model.ErrFolderNotRunning,
  1775. } {
  1776. if errors.Is(err, target) {
  1777. return true
  1778. }
  1779. }
  1780. return false
  1781. }
  1782. func httpError(w http.ResponseWriter, err error) {
  1783. if errors.Is(err, upgrade.ErrUpgradeUnsupported) {
  1784. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusNotImplemented)
  1785. } else {
  1786. http.Error(w, err.Error(), http.StatusInternalServerError)
  1787. }
  1788. }
  1789. type bufferedResponseWriter struct {
  1790. io.Writer
  1791. }
  1792. func (w bufferedResponseWriter) WriteHeader(int) {}
  1793. func (w bufferedResponseWriter) Header() http.Header {
  1794. return http.Header{}
  1795. }