api.go 61 KB

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