api.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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.Manager
  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.Manager, 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 = shouldRegenerateCertificate(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") // 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) getSystemConfig(w http.ResponseWriter, r *http.Request) {
  728. sendJSON(w, s.cfg.RawCopy())
  729. }
  730. func (s *service) postSystemConfig(w http.ResponseWriter, r *http.Request) {
  731. s.systemConfigMut.Lock()
  732. defer s.systemConfigMut.Unlock()
  733. to, err := config.ReadJSON(r.Body, s.id)
  734. r.Body.Close()
  735. if err != nil {
  736. l.Warnln("Decoding posted config:", err)
  737. http.Error(w, err.Error(), http.StatusBadRequest)
  738. return
  739. }
  740. if to.GUI.Password != s.cfg.GUI().Password {
  741. if to.GUI.Password != "" && !bcryptExpr.MatchString(to.GUI.Password) {
  742. hash, err := bcrypt.GenerateFromPassword([]byte(to.GUI.Password), 0)
  743. if err != nil {
  744. l.Warnln("bcrypting password:", err)
  745. http.Error(w, err.Error(), http.StatusInternalServerError)
  746. return
  747. }
  748. to.GUI.Password = string(hash)
  749. }
  750. }
  751. // Activate and save. Wait for the configuration to become active before
  752. // completing the request.
  753. if wg, err := s.cfg.Replace(to); err != nil {
  754. l.Warnln("Replacing config:", err)
  755. http.Error(w, err.Error(), http.StatusInternalServerError)
  756. return
  757. } else {
  758. wg.Wait()
  759. }
  760. if err := s.cfg.Save(); err != nil {
  761. l.Warnln("Saving config:", err)
  762. http.Error(w, err.Error(), http.StatusInternalServerError)
  763. return
  764. }
  765. }
  766. func (s *service) getSystemConfigInsync(w http.ResponseWriter, r *http.Request) {
  767. sendJSON(w, map[string]bool{"configInSync": !s.cfg.RequiresRestart()})
  768. }
  769. func (s *service) postSystemRestart(w http.ResponseWriter, r *http.Request) {
  770. s.flushResponse(`{"ok": "restarting"}`, w)
  771. go s.contr.Restart()
  772. }
  773. func (s *service) postSystemReset(w http.ResponseWriter, r *http.Request) {
  774. var qs = r.URL.Query()
  775. folder := qs.Get("folder")
  776. if len(folder) > 0 {
  777. if _, ok := s.cfg.Folders()[folder]; !ok {
  778. http.Error(w, "Invalid folder ID", 500)
  779. return
  780. }
  781. }
  782. if len(folder) == 0 {
  783. // Reset all folders.
  784. for folder := range s.cfg.Folders() {
  785. s.model.ResetFolder(folder)
  786. }
  787. s.flushResponse(`{"ok": "resetting database"}`, w)
  788. } else {
  789. // Reset a specific folder, assuming it's supposed to exist.
  790. s.model.ResetFolder(folder)
  791. s.flushResponse(`{"ok": "resetting folder `+folder+`"}`, w)
  792. }
  793. go s.contr.Restart()
  794. }
  795. func (s *service) postSystemShutdown(w http.ResponseWriter, r *http.Request) {
  796. s.flushResponse(`{"ok": "shutting down"}`, w)
  797. go s.contr.Shutdown()
  798. }
  799. func (s *service) flushResponse(resp string, w http.ResponseWriter) {
  800. w.Write([]byte(resp + "\n"))
  801. f := w.(http.Flusher)
  802. f.Flush()
  803. }
  804. func (s *service) getSystemStatus(w http.ResponseWriter, r *http.Request) {
  805. var m runtime.MemStats
  806. runtime.ReadMemStats(&m)
  807. tilde, _ := fs.ExpandTilde("~")
  808. res := make(map[string]interface{})
  809. res["myID"] = s.id.String()
  810. res["goroutines"] = runtime.NumGoroutine()
  811. res["alloc"] = m.Alloc
  812. res["sys"] = m.Sys - m.HeapReleased
  813. res["tilde"] = tilde
  814. if s.cfg.Options().LocalAnnEnabled || s.cfg.Options().GlobalAnnEnabled {
  815. res["discoveryEnabled"] = true
  816. discoErrors := make(map[string]string)
  817. discoMethods := 0
  818. for disco, err := range s.discoverer.ChildErrors() {
  819. discoMethods++
  820. if err != nil {
  821. discoErrors[disco] = err.Error()
  822. }
  823. }
  824. res["discoveryMethods"] = discoMethods
  825. res["discoveryErrors"] = discoErrors
  826. }
  827. res["connectionServiceStatus"] = s.connectionsService.ListenerStatus()
  828. res["lastDialStatus"] = s.connectionsService.ConnectionStatus()
  829. res["cpuPercent"] = 0 // deprecated from API
  830. res["pathSeparator"] = string(filepath.Separator)
  831. res["urVersionMax"] = ur.Version
  832. res["uptime"] = s.urService.UptimeS()
  833. res["startTime"] = ur.StartTime
  834. res["guiAddressOverridden"] = s.cfg.GUI().IsOverridden()
  835. res["guiAddressUsed"] = s.listenerAddr.String()
  836. sendJSON(w, res)
  837. }
  838. func (s *service) getSystemError(w http.ResponseWriter, r *http.Request) {
  839. sendJSON(w, map[string][]logger.Line{
  840. "errors": s.guiErrors.Since(time.Time{}),
  841. })
  842. }
  843. func (s *service) postSystemError(w http.ResponseWriter, r *http.Request) {
  844. bs, _ := ioutil.ReadAll(r.Body)
  845. r.Body.Close()
  846. l.Warnln(string(bs))
  847. }
  848. func (s *service) postSystemErrorClear(w http.ResponseWriter, r *http.Request) {
  849. s.guiErrors.Clear()
  850. }
  851. func (s *service) getSystemLog(w http.ResponseWriter, r *http.Request) {
  852. q := r.URL.Query()
  853. since, err := time.Parse(time.RFC3339, q.Get("since"))
  854. if err != nil {
  855. l.Debugln(err)
  856. }
  857. sendJSON(w, map[string][]logger.Line{
  858. "messages": s.systemLog.Since(since),
  859. })
  860. }
  861. func (s *service) getSystemLogTxt(w http.ResponseWriter, r *http.Request) {
  862. q := r.URL.Query()
  863. since, err := time.Parse(time.RFC3339, q.Get("since"))
  864. if err != nil {
  865. l.Debugln(err)
  866. }
  867. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  868. for _, line := range s.systemLog.Since(since) {
  869. fmt.Fprintf(w, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  870. }
  871. }
  872. type fileEntry struct {
  873. name string
  874. data []byte
  875. }
  876. func (s *service) getSupportBundle(w http.ResponseWriter, r *http.Request) {
  877. var files []fileEntry
  878. // Redacted configuration as a JSON
  879. if jsonConfig, err := json.MarshalIndent(getRedactedConfig(s), "", " "); err != nil {
  880. l.Warnln("Support bundle: failed to create config.json:", err)
  881. } else {
  882. files = append(files, fileEntry{name: "config.json.txt", data: jsonConfig})
  883. }
  884. // Log as a text
  885. var buflog bytes.Buffer
  886. for _, line := range s.systemLog.Since(time.Time{}) {
  887. fmt.Fprintf(&buflog, "%s: %s\n", line.When.Format(time.RFC3339), line.Message)
  888. }
  889. files = append(files, fileEntry{name: "log-inmemory.txt", data: buflog.Bytes()})
  890. // Errors as a JSON
  891. if errs := s.guiErrors.Since(time.Time{}); len(errs) > 0 {
  892. if jsonError, err := json.MarshalIndent(errs, "", " "); err != nil {
  893. l.Warnln("Support bundle: failed to create errors.json:", err)
  894. } else {
  895. files = append(files, fileEntry{name: "errors.json.txt", data: jsonError})
  896. }
  897. }
  898. // Panic files
  899. if panicFiles, err := filepath.Glob(filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), "panic*")); err == nil {
  900. for _, f := range panicFiles {
  901. if panicFile, err := ioutil.ReadFile(f); err != nil {
  902. l.Warnf("Support bundle: failed to load %s: %s", filepath.Base(f), err)
  903. } else {
  904. files = append(files, fileEntry{name: filepath.Base(f), data: panicFile})
  905. }
  906. }
  907. }
  908. // Archived log (default on Windows)
  909. if logFile, err := ioutil.ReadFile(locations.Get(locations.LogFile)); err == nil {
  910. files = append(files, fileEntry{name: "log-ondisk.txt", data: logFile})
  911. }
  912. // Version and platform information as a JSON
  913. if versionPlatform, err := json.MarshalIndent(map[string]string{
  914. "now": time.Now().Format(time.RFC3339),
  915. "version": build.Version,
  916. "codename": build.Codename,
  917. "longVersion": build.LongVersion,
  918. "os": runtime.GOOS,
  919. "arch": runtime.GOARCH,
  920. }, "", " "); err == nil {
  921. files = append(files, fileEntry{name: "version-platform.json.txt", data: versionPlatform})
  922. } else {
  923. l.Warnln("Failed to create versionPlatform.json: ", err)
  924. }
  925. // Report Data as a JSON
  926. if r, err := s.urService.ReportData(context.TODO()); err != nil {
  927. l.Warnln("Support bundle: failed to create usage-reporting.json.txt:", err)
  928. } else {
  929. if usageReportingData, err := json.MarshalIndent(r, "", " "); err != nil {
  930. l.Warnln("Support bundle: failed to serialize usage-reporting.json.txt", err)
  931. } else {
  932. files = append(files, fileEntry{name: "usage-reporting.json.txt", data: usageReportingData})
  933. }
  934. }
  935. // Heap and CPU Proofs as a pprof extension
  936. var heapBuffer, cpuBuffer bytes.Buffer
  937. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  938. runtime.GC()
  939. if err := pprof.WriteHeapProfile(&heapBuffer); err == nil {
  940. files = append(files, fileEntry{name: filename, data: heapBuffer.Bytes()})
  941. }
  942. const duration = 4 * time.Second
  943. filename = fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  944. if err := pprof.StartCPUProfile(&cpuBuffer); err == nil {
  945. time.Sleep(duration)
  946. pprof.StopCPUProfile()
  947. files = append(files, fileEntry{name: filename, data: cpuBuffer.Bytes()})
  948. }
  949. // Add buffer files to buffer zip
  950. var zipFilesBuffer bytes.Buffer
  951. if err := writeZip(&zipFilesBuffer, files); err != nil {
  952. l.Warnln("Support bundle: failed to create support bundle zip:", err)
  953. http.Error(w, err.Error(), http.StatusInternalServerError)
  954. return
  955. }
  956. // Set zip file name and path
  957. zipFileName := fmt.Sprintf("support-bundle-%s-%s.zip", s.id.Short().String(), time.Now().Format("2006-01-02T150405"))
  958. zipFilePath := filepath.Join(locations.GetBaseDir(locations.ConfigBaseDir), zipFileName)
  959. // Write buffer zip to local zip file (back up)
  960. if err := ioutil.WriteFile(zipFilePath, zipFilesBuffer.Bytes(), 0600); err != nil {
  961. l.Warnln("Support bundle: support bundle zip could not be created:", err)
  962. }
  963. // Serve the buffer zip to client for download
  964. w.Header().Set("Content-Type", "application/zip")
  965. w.Header().Set("Content-Disposition", "attachment; filename="+zipFileName)
  966. io.Copy(w, &zipFilesBuffer)
  967. }
  968. func (s *service) getSystemHTTPMetrics(w http.ResponseWriter, r *http.Request) {
  969. stats := make(map[string]interface{})
  970. metrics.Each(func(name string, intf interface{}) {
  971. if m, ok := intf.(*metrics.StandardTimer); ok {
  972. pct := m.Percentiles([]float64{0.50, 0.95, 0.99})
  973. for i := range pct {
  974. pct[i] /= 1e6 // ns to ms
  975. }
  976. stats[name] = map[string]interface{}{
  977. "count": m.Count(),
  978. "sumMs": m.Sum() / 1e6, // ns to ms
  979. "ratesPerS": []float64{m.Rate1(), m.Rate5(), m.Rate15()},
  980. "percentilesMs": pct,
  981. }
  982. }
  983. })
  984. bs, _ := json.MarshalIndent(stats, "", " ")
  985. w.Write(bs)
  986. }
  987. func (s *service) getSystemDiscovery(w http.ResponseWriter, r *http.Request) {
  988. devices := make(map[string]discover.CacheEntry)
  989. if s.discoverer != nil {
  990. // Device ids can't be marshalled as keys so we need to manually
  991. // rebuild this map using strings. Discoverer may be nil if discovery
  992. // has not started yet.
  993. for device, entry := range s.discoverer.Cache() {
  994. devices[device.String()] = entry
  995. }
  996. }
  997. sendJSON(w, devices)
  998. }
  999. func (s *service) getReport(w http.ResponseWriter, r *http.Request) {
  1000. version := ur.Version
  1001. if val, _ := strconv.Atoi(r.URL.Query().Get("version")); val > 0 {
  1002. version = val
  1003. }
  1004. if r, err := s.urService.ReportDataPreview(context.TODO(), version); err != nil {
  1005. http.Error(w, err.Error(), 500)
  1006. return
  1007. } else {
  1008. sendJSON(w, r)
  1009. }
  1010. }
  1011. func (s *service) getRandomString(w http.ResponseWriter, r *http.Request) {
  1012. length := 32
  1013. if val, _ := strconv.Atoi(r.URL.Query().Get("length")); val > 0 {
  1014. length = val
  1015. }
  1016. str := rand.String(length)
  1017. sendJSON(w, map[string]string{"random": str})
  1018. }
  1019. func (s *service) getDBIgnores(w http.ResponseWriter, r *http.Request) {
  1020. qs := r.URL.Query()
  1021. folder := qs.Get("folder")
  1022. lines, patterns, err := s.model.GetIgnores(folder)
  1023. if err != nil && !ignore.IsParseError(err) {
  1024. http.Error(w, err.Error(), 500)
  1025. return
  1026. }
  1027. sendJSON(w, map[string]interface{}{
  1028. "ignore": lines,
  1029. "expanded": patterns,
  1030. "error": errorString(err),
  1031. })
  1032. }
  1033. func (s *service) postDBIgnores(w http.ResponseWriter, r *http.Request) {
  1034. qs := r.URL.Query()
  1035. bs, err := ioutil.ReadAll(r.Body)
  1036. r.Body.Close()
  1037. if err != nil {
  1038. http.Error(w, err.Error(), 500)
  1039. return
  1040. }
  1041. var data map[string][]string
  1042. err = json.Unmarshal(bs, &data)
  1043. if err != nil {
  1044. http.Error(w, err.Error(), 500)
  1045. return
  1046. }
  1047. err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
  1048. if err != nil {
  1049. http.Error(w, err.Error(), 500)
  1050. return
  1051. }
  1052. s.getDBIgnores(w, r)
  1053. }
  1054. func (s *service) getIndexEvents(w http.ResponseWriter, r *http.Request) {
  1055. mask := s.getEventMask(r.URL.Query().Get("events"))
  1056. sub := s.getEventSub(mask)
  1057. s.getEvents(w, r, sub)
  1058. }
  1059. func (s *service) getDiskEvents(w http.ResponseWriter, r *http.Request) {
  1060. sub := s.getEventSub(DiskEventMask)
  1061. s.getEvents(w, r, sub)
  1062. }
  1063. func (s *service) getEvents(w http.ResponseWriter, r *http.Request, eventSub events.BufferedSubscription) {
  1064. if eventSub.Mask()&(events.FolderSummary|events.FolderCompletion) != 0 {
  1065. s.fss.OnEventRequest()
  1066. }
  1067. qs := r.URL.Query()
  1068. sinceStr := qs.Get("since")
  1069. limitStr := qs.Get("limit")
  1070. timeoutStr := qs.Get("timeout")
  1071. since, _ := strconv.Atoi(sinceStr)
  1072. limit, _ := strconv.Atoi(limitStr)
  1073. timeout := defaultEventTimeout
  1074. if timeoutSec, timeoutErr := strconv.Atoi(timeoutStr); timeoutErr == nil && timeoutSec >= 0 { // 0 is a valid timeout
  1075. timeout = time.Duration(timeoutSec) * time.Second
  1076. }
  1077. // Flush before blocking, to indicate that we've received the request and
  1078. // that it should not be retried. Must set Content-Type header before
  1079. // flushing.
  1080. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  1081. f := w.(http.Flusher)
  1082. f.Flush()
  1083. // If there are no events available return an empty slice, as this gets serialized as `[]`
  1084. evs := eventSub.Since(since, []events.Event{}, timeout)
  1085. if 0 < limit && limit < len(evs) {
  1086. evs = evs[len(evs)-limit:]
  1087. }
  1088. sendJSON(w, evs)
  1089. }
  1090. func (s *service) getEventMask(evs string) events.EventType {
  1091. eventMask := DefaultEventMask
  1092. if evs != "" {
  1093. eventList := strings.Split(evs, ",")
  1094. eventMask = 0
  1095. for _, ev := range eventList {
  1096. eventMask |= events.UnmarshalEventType(strings.TrimSpace(ev))
  1097. }
  1098. }
  1099. return eventMask
  1100. }
  1101. func (s *service) getEventSub(mask events.EventType) events.BufferedSubscription {
  1102. s.eventSubsMut.Lock()
  1103. bufsub, ok := s.eventSubs[mask]
  1104. if !ok {
  1105. evsub := s.evLogger.Subscribe(mask)
  1106. bufsub = events.NewBufferedSubscription(evsub, EventSubBufferSize)
  1107. s.eventSubs[mask] = bufsub
  1108. }
  1109. s.eventSubsMut.Unlock()
  1110. return bufsub
  1111. }
  1112. func (s *service) getSystemUpgrade(w http.ResponseWriter, r *http.Request) {
  1113. if s.noUpgrade {
  1114. http.Error(w, upgrade.ErrUpgradeUnsupported.Error(), http.StatusServiceUnavailable)
  1115. return
  1116. }
  1117. opts := s.cfg.Options()
  1118. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1119. if err != nil {
  1120. http.Error(w, err.Error(), 500)
  1121. return
  1122. }
  1123. res := make(map[string]interface{})
  1124. res["running"] = build.Version
  1125. res["latest"] = rel.Tag
  1126. res["newer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.Newer
  1127. res["majorNewer"] = upgrade.CompareVersions(rel.Tag, build.Version) == upgrade.MajorNewer
  1128. sendJSON(w, res)
  1129. }
  1130. func (s *service) getDeviceID(w http.ResponseWriter, r *http.Request) {
  1131. qs := r.URL.Query()
  1132. idStr := qs.Get("id")
  1133. id, err := protocol.DeviceIDFromString(idStr)
  1134. if err == nil {
  1135. sendJSON(w, map[string]string{
  1136. "id": id.String(),
  1137. })
  1138. } else {
  1139. sendJSON(w, map[string]string{
  1140. "error": err.Error(),
  1141. })
  1142. }
  1143. }
  1144. func (s *service) getLang(w http.ResponseWriter, r *http.Request) {
  1145. lang := r.Header.Get("Accept-Language")
  1146. var langs []string
  1147. for _, l := range strings.Split(lang, ",") {
  1148. parts := strings.SplitN(l, ";", 2)
  1149. langs = append(langs, strings.ToLower(strings.TrimSpace(parts[0])))
  1150. }
  1151. sendJSON(w, langs)
  1152. }
  1153. func (s *service) postSystemUpgrade(w http.ResponseWriter, r *http.Request) {
  1154. opts := s.cfg.Options()
  1155. rel, err := upgrade.LatestRelease(opts.ReleasesURL, build.Version, opts.UpgradeToPreReleases)
  1156. if err != nil {
  1157. l.Warnln("getting latest release:", err)
  1158. http.Error(w, err.Error(), 500)
  1159. return
  1160. }
  1161. if upgrade.CompareVersions(rel.Tag, build.Version) > upgrade.Equal {
  1162. err = upgrade.To(rel)
  1163. if err != nil {
  1164. l.Warnln("upgrading:", err)
  1165. http.Error(w, err.Error(), 500)
  1166. return
  1167. }
  1168. s.flushResponse(`{"ok": "restarting"}`, w)
  1169. s.contr.ExitUpgrading()
  1170. }
  1171. }
  1172. func (s *service) makeDevicePauseHandler(paused bool) http.HandlerFunc {
  1173. return func(w http.ResponseWriter, r *http.Request) {
  1174. var qs = r.URL.Query()
  1175. var deviceStr = qs.Get("device")
  1176. var cfgs []config.DeviceConfiguration
  1177. if deviceStr == "" {
  1178. for _, cfg := range s.cfg.Devices() {
  1179. cfg.Paused = paused
  1180. cfgs = append(cfgs, cfg)
  1181. }
  1182. } else {
  1183. device, err := protocol.DeviceIDFromString(deviceStr)
  1184. if err != nil {
  1185. http.Error(w, err.Error(), 500)
  1186. return
  1187. }
  1188. cfg, ok := s.cfg.Devices()[device]
  1189. if !ok {
  1190. http.Error(w, "not found", http.StatusNotFound)
  1191. return
  1192. }
  1193. cfg.Paused = paused
  1194. cfgs = append(cfgs, cfg)
  1195. }
  1196. if _, err := s.cfg.SetDevices(cfgs); err != nil {
  1197. http.Error(w, err.Error(), 500)
  1198. }
  1199. }
  1200. }
  1201. func (s *service) postDBScan(w http.ResponseWriter, r *http.Request) {
  1202. qs := r.URL.Query()
  1203. folder := qs.Get("folder")
  1204. if folder != "" {
  1205. subs := qs["sub"]
  1206. err := s.model.ScanFolderSubdirs(folder, subs)
  1207. if err != nil {
  1208. http.Error(w, err.Error(), 500)
  1209. return
  1210. }
  1211. nextStr := qs.Get("next")
  1212. next, err := strconv.Atoi(nextStr)
  1213. if err == nil {
  1214. s.model.DelayScan(folder, time.Duration(next)*time.Second)
  1215. }
  1216. } else {
  1217. errors := s.model.ScanFolders()
  1218. if len(errors) > 0 {
  1219. http.Error(w, "Error scanning folders", 500)
  1220. sendJSON(w, errors)
  1221. return
  1222. }
  1223. }
  1224. }
  1225. func (s *service) postDBPrio(w http.ResponseWriter, r *http.Request) {
  1226. qs := r.URL.Query()
  1227. folder := qs.Get("folder")
  1228. file := qs.Get("file")
  1229. s.model.BringToFront(folder, file)
  1230. s.getDBNeed(w, r)
  1231. }
  1232. func (s *service) getQR(w http.ResponseWriter, r *http.Request) {
  1233. var qs = r.URL.Query()
  1234. var text = qs.Get("text")
  1235. code, err := qr.Encode(text, qr.M)
  1236. if err != nil {
  1237. http.Error(w, "Invalid", 500)
  1238. return
  1239. }
  1240. w.Header().Set("Content-Type", "image/png")
  1241. w.Write(code.PNG())
  1242. }
  1243. func (s *service) getPeerCompletion(w http.ResponseWriter, r *http.Request) {
  1244. tot := map[string]float64{}
  1245. count := map[string]float64{}
  1246. for _, folder := range s.cfg.Folders() {
  1247. for _, device := range folder.DeviceIDs() {
  1248. deviceStr := device.String()
  1249. if _, ok := s.model.Connection(device); ok {
  1250. tot[deviceStr] += s.model.Completion(device, folder.ID).CompletionPct
  1251. } else {
  1252. tot[deviceStr] = 0
  1253. }
  1254. count[deviceStr]++
  1255. }
  1256. }
  1257. comp := map[string]int{}
  1258. for device := range tot {
  1259. comp[device] = int(tot[device] / count[device])
  1260. }
  1261. sendJSON(w, comp)
  1262. }
  1263. func (s *service) getFolderVersions(w http.ResponseWriter, r *http.Request) {
  1264. qs := r.URL.Query()
  1265. versions, err := s.model.GetFolderVersions(qs.Get("folder"))
  1266. if err != nil {
  1267. http.Error(w, err.Error(), 500)
  1268. return
  1269. }
  1270. sendJSON(w, versions)
  1271. }
  1272. func (s *service) postFolderVersionsRestore(w http.ResponseWriter, r *http.Request) {
  1273. qs := r.URL.Query()
  1274. bs, err := ioutil.ReadAll(r.Body)
  1275. r.Body.Close()
  1276. if err != nil {
  1277. http.Error(w, err.Error(), 500)
  1278. return
  1279. }
  1280. var versions map[string]time.Time
  1281. err = json.Unmarshal(bs, &versions)
  1282. if err != nil {
  1283. http.Error(w, err.Error(), 500)
  1284. return
  1285. }
  1286. ferr, err := s.model.RestoreFolderVersions(qs.Get("folder"), versions)
  1287. if err != nil {
  1288. http.Error(w, err.Error(), 500)
  1289. return
  1290. }
  1291. sendJSON(w, ferr)
  1292. }
  1293. func (s *service) getFolderErrors(w http.ResponseWriter, r *http.Request) {
  1294. qs := r.URL.Query()
  1295. folder := qs.Get("folder")
  1296. page, perpage := getPagingParams(qs)
  1297. errors, err := s.model.FolderErrors(folder)
  1298. if err != nil {
  1299. http.Error(w, err.Error(), http.StatusNotFound)
  1300. return
  1301. }
  1302. start := (page - 1) * perpage
  1303. if start >= len(errors) {
  1304. errors = nil
  1305. } else {
  1306. errors = errors[start:]
  1307. if perpage < len(errors) {
  1308. errors = errors[:perpage]
  1309. }
  1310. }
  1311. sendJSON(w, map[string]interface{}{
  1312. "folder": folder,
  1313. "errors": errors,
  1314. "page": page,
  1315. "perpage": perpage,
  1316. })
  1317. }
  1318. func (s *service) getSystemBrowse(w http.ResponseWriter, r *http.Request) {
  1319. qs := r.URL.Query()
  1320. current := qs.Get("current")
  1321. // Default value or in case of error unmarshalling ends up being basic fs.
  1322. var fsType fs.FilesystemType
  1323. fsType.UnmarshalText([]byte(qs.Get("filesystem")))
  1324. sendJSON(w, browseFiles(current, fsType))
  1325. }
  1326. const (
  1327. matchExact int = iota
  1328. matchCaseIns
  1329. noMatch
  1330. )
  1331. func checkPrefixMatch(s, prefix string) int {
  1332. if strings.HasPrefix(s, prefix) {
  1333. return matchExact
  1334. }
  1335. if strings.HasPrefix(strings.ToLower(s), strings.ToLower(prefix)) {
  1336. return matchCaseIns
  1337. }
  1338. return noMatch
  1339. }
  1340. func browseFiles(current string, fsType fs.FilesystemType) []string {
  1341. if current == "" {
  1342. filesystem := fs.NewFilesystem(fsType, "")
  1343. if roots, err := filesystem.Roots(); err == nil {
  1344. return roots
  1345. }
  1346. return nil
  1347. }
  1348. search, _ := fs.ExpandTilde(current)
  1349. pathSeparator := string(fs.PathSeparator)
  1350. if strings.HasSuffix(current, pathSeparator) && !strings.HasSuffix(search, pathSeparator) {
  1351. search = search + pathSeparator
  1352. }
  1353. searchDir := filepath.Dir(search)
  1354. // The searchFile should be the last component of search, or empty if it
  1355. // ends with a path separator
  1356. var searchFile string
  1357. if !strings.HasSuffix(search, pathSeparator) {
  1358. searchFile = filepath.Base(search)
  1359. }
  1360. fs := fs.NewFilesystem(fsType, searchDir)
  1361. subdirectories, _ := fs.DirNames(".")
  1362. exactMatches := make([]string, 0, len(subdirectories))
  1363. caseInsMatches := make([]string, 0, len(subdirectories))
  1364. for _, subdirectory := range subdirectories {
  1365. info, err := fs.Stat(subdirectory)
  1366. if err != nil || !info.IsDir() {
  1367. continue
  1368. }
  1369. switch checkPrefixMatch(subdirectory, searchFile) {
  1370. case matchExact:
  1371. exactMatches = append(exactMatches, filepath.Join(searchDir, subdirectory)+pathSeparator)
  1372. case matchCaseIns:
  1373. caseInsMatches = append(caseInsMatches, filepath.Join(searchDir, subdirectory)+pathSeparator)
  1374. }
  1375. }
  1376. // sort to return matches in deterministic order (don't depend on file system order)
  1377. sort.Strings(exactMatches)
  1378. sort.Strings(caseInsMatches)
  1379. return append(exactMatches, caseInsMatches...)
  1380. }
  1381. func (s *service) getCPUProf(w http.ResponseWriter, r *http.Request) {
  1382. duration, err := time.ParseDuration(r.FormValue("duration"))
  1383. if err != nil {
  1384. duration = 30 * time.Second
  1385. }
  1386. filename := fmt.Sprintf("syncthing-cpu-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1387. w.Header().Set("Content-Type", "application/octet-stream")
  1388. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1389. if err := pprof.StartCPUProfile(w); err == nil {
  1390. time.Sleep(duration)
  1391. pprof.StopCPUProfile()
  1392. }
  1393. }
  1394. func (s *service) getHeapProf(w http.ResponseWriter, r *http.Request) {
  1395. filename := fmt.Sprintf("syncthing-heap-%s-%s-%s-%s.pprof", runtime.GOOS, runtime.GOARCH, build.Version, time.Now().Format("150405")) // hhmmss
  1396. w.Header().Set("Content-Type", "application/octet-stream")
  1397. w.Header().Set("Content-Disposition", "attachment; filename="+filename)
  1398. runtime.GC()
  1399. pprof.WriteHeapProfile(w)
  1400. }
  1401. func toJsonFileInfoSlice(fs []db.FileInfoTruncated) []jsonFileInfoTrunc {
  1402. res := make([]jsonFileInfoTrunc, len(fs))
  1403. for i, f := range fs {
  1404. res[i] = jsonFileInfoTrunc(f)
  1405. }
  1406. return res
  1407. }
  1408. // Type wrappers for nice JSON serialization
  1409. type jsonFileInfo protocol.FileInfo
  1410. func (f jsonFileInfo) MarshalJSON() ([]byte, error) {
  1411. m := fileIntfJSONMap(protocol.FileInfo(f))
  1412. m["numBlocks"] = len(f.Blocks)
  1413. return json.Marshal(m)
  1414. }
  1415. type jsonFileInfoTrunc db.FileInfoTruncated
  1416. func (f jsonFileInfoTrunc) MarshalJSON() ([]byte, error) {
  1417. m := fileIntfJSONMap(db.FileInfoTruncated(f))
  1418. m["numBlocks"] = nil // explicitly unknown
  1419. return json.Marshal(m)
  1420. }
  1421. func fileIntfJSONMap(f protocol.FileIntf) map[string]interface{} {
  1422. out := map[string]interface{}{
  1423. "name": f.FileName(),
  1424. "type": f.FileType().String(),
  1425. "size": f.FileSize(),
  1426. "deleted": f.IsDeleted(),
  1427. "invalid": f.IsInvalid(),
  1428. "ignored": f.IsIgnored(),
  1429. "mustRescan": f.MustRescan(),
  1430. "noPermissions": !f.HasPermissionBits(),
  1431. "modified": f.ModTime(),
  1432. "modifiedBy": f.FileModifiedBy().String(),
  1433. "sequence": f.SequenceNo(),
  1434. "version": jsonVersionVector(f.FileVersion()),
  1435. "localFlags": f.FileLocalFlags(),
  1436. }
  1437. if f.HasPermissionBits() {
  1438. out["permissions"] = fmt.Sprintf("%#o", f.FilePermissions())
  1439. }
  1440. return out
  1441. }
  1442. type jsonVersionVector protocol.Vector
  1443. func (v jsonVersionVector) MarshalJSON() ([]byte, error) {
  1444. res := make([]string, len(v.Counters))
  1445. for i, c := range v.Counters {
  1446. res[i] = fmt.Sprintf("%v:%d", c.ID, c.Value)
  1447. }
  1448. return json.Marshal(res)
  1449. }
  1450. func dirNames(dir string) []string {
  1451. fd, err := os.Open(dir)
  1452. if err != nil {
  1453. return nil
  1454. }
  1455. defer fd.Close()
  1456. fis, err := fd.Readdir(-1)
  1457. if err != nil {
  1458. return nil
  1459. }
  1460. var dirs []string
  1461. for _, fi := range fis {
  1462. if fi.IsDir() {
  1463. dirs = append(dirs, filepath.Base(fi.Name()))
  1464. }
  1465. }
  1466. sort.Strings(dirs)
  1467. return dirs
  1468. }
  1469. func addressIsLocalhost(addr string) bool {
  1470. host, _, err := net.SplitHostPort(addr)
  1471. if err != nil {
  1472. // There was no port, so we assume the address was just a hostname
  1473. host = addr
  1474. }
  1475. switch strings.ToLower(host) {
  1476. case "localhost", "localhost.":
  1477. return true
  1478. default:
  1479. ip := net.ParseIP(host)
  1480. if ip == nil {
  1481. // not an IP address
  1482. return false
  1483. }
  1484. return ip.IsLoopback()
  1485. }
  1486. }
  1487. // shouldRegenerateCertificate checks for certificate expiry or other known
  1488. // issues with our API/GUI certificate and returns either nil (leave the
  1489. // certificate alone) or an error describing the reason the certificate
  1490. // should be regenerated.
  1491. func shouldRegenerateCertificate(cert tls.Certificate) error {
  1492. leaf := cert.Leaf
  1493. if leaf == nil {
  1494. // Leaf can be nil or not, depending on how parsed the certificate
  1495. // was when we got it.
  1496. if len(cert.Certificate) < 1 {
  1497. // can't happen
  1498. return errors.New("no certificate in certificate")
  1499. }
  1500. var err error
  1501. leaf, err = x509.ParseCertificate(cert.Certificate[0])
  1502. if err != nil {
  1503. return err
  1504. }
  1505. }
  1506. if leaf.Subject.String() != leaf.Issuer.String() || len(leaf.IPAddresses) != 0 {
  1507. // The certificate is not self signed, or has IP attributes we don't
  1508. // add, so we leave it alone.
  1509. return nil
  1510. }
  1511. if len(leaf.DNSNames) > 1 {
  1512. // The certificate has more DNS SANs attributes than we ever add, so
  1513. // we leave it alone.
  1514. return nil
  1515. }
  1516. if len(leaf.DNSNames) == 1 && leaf.DNSNames[0] != leaf.Issuer.CommonName {
  1517. // The one SAN is different from the issuer, so it's not one of our
  1518. // newer self signed certificates.
  1519. return nil
  1520. }
  1521. if leaf.NotAfter.Before(time.Now()) {
  1522. return errors.New("certificate has expired")
  1523. }
  1524. if leaf.NotAfter.Before(time.Now().Add(30 * 24 * time.Hour)) {
  1525. return errors.New("certificate will soon expire")
  1526. }
  1527. // On macOS, check for certificates issued on or after July 1st, 2019,
  1528. // with a longer validity time than 825 days.
  1529. cutoff := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
  1530. if runtime.GOOS == "darwin" &&
  1531. leaf.NotBefore.After(cutoff) &&
  1532. leaf.NotAfter.Sub(leaf.NotBefore) > 825*24*time.Hour {
  1533. return errors.New("certificate incompatible with macOS 10.15 (Catalina)")
  1534. }
  1535. return nil
  1536. }
  1537. func errorString(err error) *string {
  1538. if err != nil {
  1539. msg := err.Error()
  1540. return &msg
  1541. }
  1542. return nil
  1543. }