syncthing.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 syncthing
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "os"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/thejerf/suture/v4"
  21. "github.com/syncthing/syncthing/lib/api"
  22. "github.com/syncthing/syncthing/lib/build"
  23. "github.com/syncthing/syncthing/lib/config"
  24. "github.com/syncthing/syncthing/lib/connections"
  25. "github.com/syncthing/syncthing/lib/db"
  26. "github.com/syncthing/syncthing/lib/db/backend"
  27. "github.com/syncthing/syncthing/lib/discover"
  28. "github.com/syncthing/syncthing/lib/events"
  29. "github.com/syncthing/syncthing/lib/locations"
  30. "github.com/syncthing/syncthing/lib/logger"
  31. "github.com/syncthing/syncthing/lib/model"
  32. "github.com/syncthing/syncthing/lib/osutil"
  33. "github.com/syncthing/syncthing/lib/protocol"
  34. "github.com/syncthing/syncthing/lib/rand"
  35. "github.com/syncthing/syncthing/lib/sha256"
  36. "github.com/syncthing/syncthing/lib/tlsutil"
  37. "github.com/syncthing/syncthing/lib/upgrade"
  38. "github.com/syncthing/syncthing/lib/ur"
  39. "github.com/syncthing/syncthing/lib/util"
  40. )
  41. const (
  42. bepProtocolName = "bep/1.0"
  43. tlsDefaultCommonName = "syncthing"
  44. maxSystemErrors = 5
  45. initialSystemLog = 10
  46. maxSystemLog = 250
  47. deviceCertLifetimeDays = 20 * 365
  48. )
  49. type Options struct {
  50. AssetDir string
  51. AuditWriter io.Writer
  52. DeadlockTimeoutS int
  53. NoUpgrade bool
  54. ProfilerURL string
  55. ResetDeltaIdxs bool
  56. Verbose bool
  57. // null duration means use default value
  58. DBRecheckInterval time.Duration
  59. DBIndirectGCInterval time.Duration
  60. }
  61. type App struct {
  62. myID protocol.DeviceID
  63. mainService *suture.Supervisor
  64. cfg config.Wrapper
  65. ll *db.Lowlevel
  66. evLogger events.Logger
  67. cert tls.Certificate
  68. opts Options
  69. exitStatus util.ExitStatus
  70. err error
  71. stopOnce sync.Once
  72. mainServiceCancel context.CancelFunc
  73. stopped chan struct{}
  74. }
  75. func New(cfg config.Wrapper, dbBackend backend.Backend, evLogger events.Logger, cert tls.Certificate, opts Options) (*App, error) {
  76. ll, err := db.NewLowlevel(dbBackend, evLogger, db.WithRecheckInterval(opts.DBRecheckInterval), db.WithIndirectGCInterval(opts.DBIndirectGCInterval))
  77. if err != nil {
  78. return nil, err
  79. }
  80. a := &App{
  81. cfg: cfg,
  82. ll: ll,
  83. evLogger: evLogger,
  84. opts: opts,
  85. cert: cert,
  86. stopped: make(chan struct{}),
  87. }
  88. close(a.stopped) // Hasn't been started, so shouldn't block on Wait.
  89. return a, nil
  90. }
  91. // Start executes the app and returns once all the startup operations are done,
  92. // e.g. the API is ready for use.
  93. // Must be called once only.
  94. func (a *App) Start() error {
  95. // Create a main service manager. We'll add things to this as we go along.
  96. // We want any logging it does to go through our log system.
  97. spec := util.SpecWithDebugLogger(l)
  98. a.mainService = suture.New("main", spec)
  99. // Start the supervisor and wait for it to stop to handle cleanup.
  100. a.stopped = make(chan struct{})
  101. ctx, cancel := context.WithCancel(context.Background())
  102. a.mainServiceCancel = cancel
  103. go a.run(ctx)
  104. if err := a.startup(); err != nil {
  105. a.stopWithErr(util.ExitError, err)
  106. return err
  107. }
  108. return nil
  109. }
  110. func (a *App) startup() error {
  111. a.mainService.Add(ur.NewFailureHandler(a.cfg, a.evLogger))
  112. a.mainService.Add(a.ll)
  113. if a.opts.AuditWriter != nil {
  114. a.mainService.Add(newAuditService(a.opts.AuditWriter, a.evLogger))
  115. }
  116. if a.opts.Verbose {
  117. a.mainService.Add(newVerboseService(a.evLogger))
  118. }
  119. errors := logger.NewRecorder(l, logger.LevelWarn, maxSystemErrors, 0)
  120. systemLog := logger.NewRecorder(l, logger.LevelDebug, maxSystemLog, initialSystemLog)
  121. // Event subscription for the API; must start early to catch the early
  122. // events. The LocalChangeDetected event might overwhelm the event
  123. // receiver in some situations so we will not subscribe to it here.
  124. defaultSub := events.NewBufferedSubscription(a.evLogger.Subscribe(api.DefaultEventMask), api.EventSubBufferSize)
  125. diskSub := events.NewBufferedSubscription(a.evLogger.Subscribe(api.DiskEventMask), api.EventSubBufferSize)
  126. // Attempt to increase the limit on number of open files to the maximum
  127. // allowed, in case we have many peers. We don't really care enough to
  128. // report the error if there is one.
  129. osutil.MaximizeOpenFileLimit()
  130. // Figure out our device ID, set it as the log prefix and log it.
  131. a.myID = protocol.NewDeviceID(a.cert.Certificate[0])
  132. l.SetPrefix(fmt.Sprintf("[%s] ", a.myID.String()[:5]))
  133. l.Infoln("My ID:", a.myID)
  134. // Select SHA256 implementation and report. Affected by the
  135. // STHASHING environment variable.
  136. sha256.SelectAlgo()
  137. sha256.Report()
  138. // Emit the Starting event, now that we know who we are.
  139. a.evLogger.Log(events.Starting, map[string]string{
  140. "home": locations.GetBaseDir(locations.ConfigBaseDir),
  141. "myID": a.myID.String(),
  142. })
  143. if err := checkShortIDs(a.cfg); err != nil {
  144. l.Warnln("Short device IDs are in conflict. Unlucky!\n Regenerate the device ID of one of the following:\n ", err)
  145. return err
  146. }
  147. if len(a.opts.ProfilerURL) > 0 {
  148. go func() {
  149. l.Debugln("Starting profiler on", a.opts.ProfilerURL)
  150. runtime.SetBlockProfileRate(1)
  151. err := http.ListenAndServe(a.opts.ProfilerURL, nil)
  152. if err != nil {
  153. l.Warnln(err)
  154. return
  155. }
  156. }()
  157. }
  158. perf := ur.CpuBench(context.Background(), 3, 150*time.Millisecond, true)
  159. l.Infof("Hashing performance is %.02f MB/s", perf)
  160. if err := db.UpdateSchema(a.ll); err != nil {
  161. l.Warnln("Database schema:", err)
  162. return err
  163. }
  164. if a.opts.ResetDeltaIdxs {
  165. l.Infoln("Reinitializing delta index IDs")
  166. db.DropDeltaIndexIDs(a.ll)
  167. }
  168. protectedFiles := []string{
  169. locations.Get(locations.Database),
  170. locations.Get(locations.ConfigFile),
  171. locations.Get(locations.CertFile),
  172. locations.Get(locations.KeyFile),
  173. }
  174. // Remove database entries for folders that no longer exist in the config
  175. folders := a.cfg.Folders()
  176. for _, folder := range a.ll.ListFolders() {
  177. if _, ok := folders[folder]; !ok {
  178. l.Infof("Cleaning data for dropped folder %q", folder)
  179. db.DropFolder(a.ll, folder)
  180. }
  181. }
  182. // Grab the previously running version string from the database.
  183. miscDB := db.NewMiscDataNamespace(a.ll)
  184. prevVersion, _, err := miscDB.String("prevVersion")
  185. if err != nil {
  186. l.Warnln("Database:", err)
  187. return err
  188. }
  189. // Strip away prerelease/beta stuff and just compare the release
  190. // numbers. 0.14.44 to 0.14.45-banana is an upgrade, 0.14.45-banana to
  191. // 0.14.45-pineapple is not.
  192. prevParts := strings.Split(prevVersion, "-")
  193. curParts := strings.Split(build.Version, "-")
  194. if rel := upgrade.CompareVersions(prevParts[0], curParts[0]); rel != upgrade.Equal {
  195. if prevVersion != "" {
  196. l.Infoln("Detected upgrade from", prevVersion, "to", build.Version)
  197. }
  198. if a.cfg.Options().SendFullIndexOnUpgrade {
  199. // Drop delta indexes in case we've changed random stuff we
  200. // shouldn't have. We will resend our index on next connect.
  201. db.DropDeltaIndexIDs(a.ll)
  202. }
  203. }
  204. if build.Version != prevVersion {
  205. // Remember the new version.
  206. miscDB.PutString("prevVersion", build.Version)
  207. }
  208. m := model.NewModel(a.cfg, a.myID, "syncthing", build.Version, a.ll, protectedFiles, a.evLogger)
  209. if a.opts.DeadlockTimeoutS > 0 {
  210. m.StartDeadlockDetector(time.Duration(a.opts.DeadlockTimeoutS) * time.Second)
  211. } else if !build.IsRelease || build.IsBeta {
  212. m.StartDeadlockDetector(20 * time.Minute)
  213. }
  214. a.mainService.Add(m)
  215. // The TLS configuration is used for both the listening socket and outgoing
  216. // connections.
  217. tlsCfg := tlsutil.SecureDefault()
  218. tlsCfg.Certificates = []tls.Certificate{a.cert}
  219. tlsCfg.NextProtos = []string{bepProtocolName}
  220. tlsCfg.ClientAuth = tls.RequestClientCert
  221. tlsCfg.SessionTicketsDisabled = true
  222. tlsCfg.InsecureSkipVerify = true
  223. // Start discovery and connection management
  224. // Chicken and egg, discovery manager depends on connection service to tell it what addresses it's listening on
  225. // Connection service depends on discovery manager to get addresses to connect to.
  226. // Create a wrapper that is then wired after they are both setup.
  227. addrLister := &lateAddressLister{}
  228. discoveryManager := discover.NewManager(a.myID, a.cfg, a.cert, a.evLogger, addrLister)
  229. connectionsService := connections.NewService(a.cfg, a.myID, m, tlsCfg, discoveryManager, bepProtocolName, tlsDefaultCommonName, a.evLogger)
  230. addrLister.AddressLister = connectionsService
  231. a.mainService.Add(discoveryManager)
  232. a.mainService.Add(connectionsService)
  233. // Candidate builds always run with usage reporting.
  234. if opts := a.cfg.Options(); build.IsCandidate {
  235. l.Infoln("Anonymous usage reporting is always enabled for candidate releases.")
  236. if opts.URAccepted != ur.Version {
  237. opts.URAccepted = ur.Version
  238. a.cfg.SetOptions(opts)
  239. a.cfg.Save()
  240. // Unique ID will be set and config saved below if necessary.
  241. }
  242. }
  243. // If we are going to do usage reporting, ensure we have a valid unique ID.
  244. if opts := a.cfg.Options(); opts.URAccepted > 0 && opts.URUniqueID == "" {
  245. opts.URUniqueID = rand.String(8)
  246. a.cfg.SetOptions(opts)
  247. a.cfg.Save()
  248. }
  249. usageReportingSvc := ur.New(a.cfg, m, connectionsService, a.opts.NoUpgrade)
  250. a.mainService.Add(usageReportingSvc)
  251. // GUI
  252. if err := a.setupGUI(m, defaultSub, diskSub, discoveryManager, connectionsService, usageReportingSvc, errors, systemLog); err != nil {
  253. l.Warnln("Failed starting API:", err)
  254. return err
  255. }
  256. myDev, _ := a.cfg.Device(a.myID)
  257. l.Infof(`My name is "%v"`, myDev.Name)
  258. for _, device := range a.cfg.Devices() {
  259. if device.DeviceID != a.myID {
  260. l.Infof(`Device %s is "%v" at %v`, device.DeviceID, device.Name, device.Addresses)
  261. }
  262. }
  263. if isSuperUser() {
  264. l.Warnln("Syncthing should not run as a privileged or system user. Please consider using a normal user account.")
  265. }
  266. a.evLogger.Log(events.StartupComplete, map[string]string{
  267. "myID": a.myID.String(),
  268. })
  269. if a.cfg.Options().SetLowPriority {
  270. if err := osutil.SetLowPriority(); err != nil {
  271. l.Warnln("Failed to lower process priority:", err)
  272. }
  273. }
  274. return nil
  275. }
  276. func (a *App) run(ctx context.Context) {
  277. err := a.mainService.Serve(ctx)
  278. a.handleMainServiceError(err)
  279. done := make(chan struct{})
  280. go func() {
  281. a.ll.Close()
  282. close(done)
  283. }()
  284. select {
  285. case <-done:
  286. case <-time.After(10 * time.Second):
  287. l.Warnln("Database failed to stop within 10s")
  288. }
  289. l.Infoln("Exiting")
  290. close(a.stopped)
  291. }
  292. func (a *App) handleMainServiceError(err error) {
  293. if err == nil || errors.Is(err, context.Canceled) {
  294. return
  295. }
  296. var fatalErr *util.FatalErr
  297. if errors.As(err, &fatalErr) {
  298. a.exitStatus = fatalErr.Status
  299. a.err = fatalErr.Err
  300. return
  301. }
  302. a.err = err
  303. a.exitStatus = util.ExitError
  304. }
  305. // Wait blocks until the app stops running. Also returns if the app hasn't been
  306. // started yet.
  307. func (a *App) Wait() util.ExitStatus {
  308. <-a.stopped
  309. return a.exitStatus
  310. }
  311. // Error returns an error if one occurred while running the app. It does not wait
  312. // for the app to stop before returning.
  313. func (a *App) Error() error {
  314. select {
  315. case <-a.stopped:
  316. return a.err
  317. default:
  318. }
  319. return nil
  320. }
  321. // Stop stops the app and sets its exit status to given reason, unless the app
  322. // was already stopped before. In any case it returns the effective exit status.
  323. func (a *App) Stop(stopReason util.ExitStatus) util.ExitStatus {
  324. return a.stopWithErr(stopReason, nil)
  325. }
  326. func (a *App) stopWithErr(stopReason util.ExitStatus, err error) util.ExitStatus {
  327. a.stopOnce.Do(func() {
  328. a.exitStatus = stopReason
  329. a.err = err
  330. if shouldDebug() {
  331. l.Debugln("Services before stop:")
  332. printServiceTree(os.Stdout, a.mainService, 0)
  333. }
  334. a.mainServiceCancel()
  335. })
  336. <-a.stopped
  337. return a.exitStatus
  338. }
  339. func (a *App) setupGUI(m model.Model, defaultSub, diskSub events.BufferedSubscription, discoverer discover.Manager, connectionsService connections.Service, urService *ur.Service, errors, systemLog logger.Recorder) error {
  340. guiCfg := a.cfg.GUI()
  341. if !guiCfg.Enabled {
  342. return nil
  343. }
  344. if guiCfg.InsecureAdminAccess {
  345. l.Warnln("Insecure admin access is enabled.")
  346. }
  347. summaryService := model.NewFolderSummaryService(a.cfg, m, a.myID, a.evLogger)
  348. a.mainService.Add(summaryService)
  349. apiSvc := api.New(a.myID, a.cfg, a.opts.AssetDir, tlsDefaultCommonName, m, defaultSub, diskSub, a.evLogger, discoverer, connectionsService, urService, summaryService, errors, systemLog, a.opts.NoUpgrade)
  350. a.mainService.Add(apiSvc)
  351. if err := apiSvc.WaitForStart(); err != nil {
  352. return err
  353. }
  354. return nil
  355. }
  356. // checkShortIDs verifies that the configuration won't result in duplicate
  357. // short ID:s; that is, that the devices in the cluster all have unique
  358. // initial 64 bits.
  359. func checkShortIDs(cfg config.Wrapper) error {
  360. exists := make(map[protocol.ShortID]protocol.DeviceID)
  361. for deviceID := range cfg.Devices() {
  362. shortID := deviceID.Short()
  363. if otherID, ok := exists[shortID]; ok {
  364. return fmt.Errorf("%v in conflict with %v", deviceID, otherID)
  365. }
  366. exists[shortID] = deviceID
  367. }
  368. return nil
  369. }
  370. type supervisor interface{ Services() []suture.Service }
  371. func printServiceTree(w io.Writer, sup supervisor, level int) {
  372. printService(w, sup, level)
  373. svcs := sup.Services()
  374. sort.Slice(svcs, func(a, b int) bool {
  375. return fmt.Sprint(svcs[a]) < fmt.Sprint(svcs[b])
  376. })
  377. for _, svc := range svcs {
  378. if sub, ok := svc.(supervisor); ok {
  379. printServiceTree(w, sub, level+1)
  380. } else {
  381. printService(w, svc, level+1)
  382. }
  383. }
  384. }
  385. func printService(w io.Writer, svc interface{}, level int) {
  386. type errorer interface{ Error() error }
  387. t := "-"
  388. if _, ok := svc.(supervisor); ok {
  389. t = "+"
  390. }
  391. fmt.Fprintln(w, strings.Repeat(" ", level), t, svc)
  392. if es, ok := svc.(errorer); ok {
  393. if err := es.Error(); err != nil {
  394. fmt.Fprintln(w, strings.Repeat(" ", level), " ->", err)
  395. }
  396. }
  397. }
  398. type lateAddressLister struct {
  399. discover.AddressLister
  400. }