api.go 56 KB

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