api.go 54 KB

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