api.go 55 KB

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