api.go 63 KB

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