api.go 52 KB

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