1
0

api.go 63 KB

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