api.go 52 KB

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