main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. package main
  2. import (
  3. "compress/gzip"
  4. "crypto/tls"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "net"
  9. "net/http"
  10. _ "net/http/pprof"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "runtime"
  15. "runtime/debug"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/calmh/ini"
  20. "github.com/calmh/syncthing/discover"
  21. "github.com/calmh/syncthing/protocol"
  22. "github.com/calmh/syncthing/scanner"
  23. )
  24. const BlockSize = 128 * 1024
  25. var cfg Configuration
  26. var Version = "unknown-dev"
  27. var (
  28. myID string
  29. )
  30. var (
  31. showVersion bool
  32. confDir string
  33. verbose bool
  34. )
  35. const (
  36. usage = "syncthing [options]"
  37. extraUsage = `The following enviroment variables are interpreted by syncthing:
  38. STNORESTART Do not attempt to restart when requested to, instead just exit.
  39. Set this variable when running under a service manager such as
  40. runit, launchd, etc.
  41. STPROFILER Set to a listen address such as "127.0.0.1:9090" to start the
  42. profiler with HTTP access.
  43. STTRACE A comma separated string of facilities to trace. The valid
  44. facility strings:
  45. - "scanner" (the file change scanner)
  46. - "discover" (the node discovery package)
  47. - "net" (connecting and disconnecting, network messages)
  48. - "idx" (index sending and receiving)
  49. - "need" (file need calculations)
  50. - "pull" (file pull activity)`
  51. )
  52. func main() {
  53. flag.StringVar(&confDir, "home", getDefaultConfDir(), "Set configuration directory")
  54. flag.BoolVar(&showVersion, "version", false, "Show version")
  55. flag.BoolVar(&verbose, "v", false, "Be more verbose")
  56. flag.Usage = usageFor(flag.CommandLine, usage, extraUsage)
  57. flag.Parse()
  58. if len(os.Getenv("STRESTART")) > 0 {
  59. // Give the parent process time to exit and release sockets etc.
  60. time.Sleep(1 * time.Second)
  61. }
  62. if showVersion {
  63. fmt.Println(Version)
  64. os.Exit(0)
  65. }
  66. if len(os.Getenv("GOGC")) == 0 {
  67. debug.SetGCPercent(25)
  68. }
  69. if len(os.Getenv("GOMAXPROCS")) == 0 {
  70. runtime.GOMAXPROCS(runtime.NumCPU())
  71. }
  72. confDir = expandTilde(confDir)
  73. // Ensure that our home directory exists and that we have a certificate and key.
  74. ensureDir(confDir, 0700)
  75. cert, err := loadCert(confDir)
  76. if err != nil {
  77. newCertificate(confDir)
  78. cert, err = loadCert(confDir)
  79. fatalErr(err)
  80. }
  81. myID = string(certID(cert.Certificate[0]))
  82. log.SetPrefix("[" + myID[0:5] + "] ")
  83. logger.SetPrefix("[" + myID[0:5] + "] ")
  84. infoln("Version", Version)
  85. infoln("My ID:", myID)
  86. // Prepare to be able to save configuration
  87. cfgFile := path.Join(confDir, "config.xml")
  88. go saveConfigLoop(cfgFile)
  89. // Load the configuration file, if it exists.
  90. // If it does not, create a template.
  91. cf, err := os.Open(cfgFile)
  92. if err == nil {
  93. // Read config.xml
  94. cfg, err = readConfigXML(cf)
  95. if err != nil {
  96. fatalln(err)
  97. }
  98. cf.Close()
  99. } else {
  100. // No config.xml, let's try the old syncthing.ini
  101. iniFile := path.Join(confDir, "syncthing.ini")
  102. cf, err := os.Open(iniFile)
  103. if err == nil {
  104. infoln("Migrating syncthing.ini to config.xml")
  105. iniCfg := ini.Parse(cf)
  106. cf.Close()
  107. os.Rename(iniFile, path.Join(confDir, "migrated_syncthing.ini"))
  108. cfg, _ = readConfigXML(nil)
  109. cfg.Repositories = []RepositoryConfiguration{
  110. {Directory: iniCfg.Get("repository", "dir")},
  111. }
  112. readConfigINI(iniCfg.OptionMap("settings"), &cfg.Options)
  113. for name, addrs := range iniCfg.OptionMap("nodes") {
  114. n := NodeConfiguration{
  115. NodeID: name,
  116. Addresses: strings.Fields(addrs),
  117. }
  118. cfg.Repositories[0].Nodes = append(cfg.Repositories[0].Nodes, n)
  119. }
  120. saveConfig()
  121. }
  122. }
  123. if len(cfg.Repositories) == 0 {
  124. infoln("No config file; starting with empty defaults")
  125. cfg, err = readConfigXML(nil)
  126. cfg.Repositories = []RepositoryConfiguration{
  127. {
  128. Directory: path.Join(getHomeDir(), "Sync"),
  129. Nodes: []NodeConfiguration{
  130. {NodeID: myID, Addresses: []string{"dynamic"}},
  131. },
  132. },
  133. }
  134. saveConfig()
  135. infof("Edit %s to taste or use the GUI\n", cfgFile)
  136. }
  137. // Make sure the local node is in the node list.
  138. cfg.Repositories[0].Nodes = cleanNodeList(cfg.Repositories[0].Nodes, myID)
  139. var dir = expandTilde(cfg.Repositories[0].Directory)
  140. if profiler := os.Getenv("STPROFILER"); len(profiler) > 0 {
  141. go func() {
  142. dlog.Println("Starting profiler on", profiler)
  143. err := http.ListenAndServe(profiler, nil)
  144. if err != nil {
  145. dlog.Fatal(err)
  146. }
  147. }()
  148. }
  149. // The TLS configuration is used for both the listening socket and outgoing
  150. // connections.
  151. tlsCfg := &tls.Config{
  152. Certificates: []tls.Certificate{cert},
  153. NextProtos: []string{"bep/1.0"},
  154. ServerName: myID,
  155. ClientAuth: tls.RequestClientCert,
  156. SessionTicketsDisabled: true,
  157. InsecureSkipVerify: true,
  158. MinVersion: tls.VersionTLS12,
  159. }
  160. ensureDir(dir, -1)
  161. m := NewModel(dir, cfg.Options.MaxChangeKbps*1000)
  162. if cfg.Options.MaxSendKbps > 0 {
  163. m.LimitRate(cfg.Options.MaxSendKbps)
  164. }
  165. // GUI
  166. if cfg.Options.GUIEnabled && cfg.Options.GUIAddress != "" {
  167. addr, err := net.ResolveTCPAddr("tcp", cfg.Options.GUIAddress)
  168. if err != nil {
  169. warnf("Cannot start GUI on %q: %v", cfg.Options.GUIAddress, err)
  170. } else {
  171. var hostOpen, hostShow string
  172. switch {
  173. case addr.IP == nil:
  174. hostOpen = "localhost"
  175. hostShow = "0.0.0.0"
  176. case addr.IP.IsUnspecified():
  177. hostOpen = "localhost"
  178. hostShow = addr.IP.String()
  179. default:
  180. hostOpen = addr.IP.String()
  181. hostShow = hostOpen
  182. }
  183. infof("Starting web GUI on http://%s:%d/", hostShow, addr.Port)
  184. startGUI(cfg.Options.GUIAddress, m)
  185. if cfg.Options.StartBrowser && len(os.Getenv("STRESTART")) == 0 {
  186. openURL(fmt.Sprintf("http://%s:%d", hostOpen, addr.Port))
  187. }
  188. }
  189. }
  190. // Walk the repository and update the local model before establishing any
  191. // connections to other nodes.
  192. if verbose {
  193. infoln("Populating repository index")
  194. }
  195. loadIndex(m)
  196. sup := &suppressor{threshold: int64(cfg.Options.MaxChangeKbps)}
  197. w := &scanner.Walker{
  198. Dir: m.dir,
  199. IgnoreFile: ".stignore",
  200. FollowSymlinks: cfg.Options.FollowSymlinks,
  201. BlockSize: BlockSize,
  202. Suppressor: sup,
  203. TempNamer: defTempNamer,
  204. }
  205. updateLocalModel(m, w)
  206. connOpts := map[string]string{
  207. "clientId": "syncthing",
  208. "clientVersion": Version,
  209. "clusterHash": clusterHash(cfg.Repositories[0].Nodes),
  210. }
  211. // Routine to listen for incoming connections
  212. if verbose {
  213. infoln("Listening for incoming connections")
  214. }
  215. for _, addr := range cfg.Options.ListenAddress {
  216. go listen(myID, addr, m, tlsCfg, connOpts)
  217. }
  218. // Routine to connect out to configured nodes
  219. if verbose {
  220. infoln("Attempting to connect to other nodes")
  221. }
  222. disc := discovery(cfg.Options.ListenAddress[0])
  223. go connect(myID, disc, m, tlsCfg, connOpts)
  224. // Routine to pull blocks from other nodes to synchronize the local
  225. // repository. Does not run when we are in read only (publish only) mode.
  226. if !cfg.Options.ReadOnly {
  227. if verbose {
  228. if cfg.Options.AllowDelete {
  229. infoln("Deletes from peer nodes are allowed")
  230. } else {
  231. infoln("Deletes from peer nodes will be ignored")
  232. }
  233. okln("Ready to synchronize (read-write)")
  234. }
  235. m.StartRW(cfg.Options.AllowDelete, cfg.Options.ParallelRequests)
  236. } else if verbose {
  237. okln("Ready to synchronize (read only; no external updates accepted)")
  238. }
  239. // Periodically scan the repository and update the local
  240. // XXX: Should use some fsnotify mechanism.
  241. go func() {
  242. td := time.Duration(cfg.Options.RescanIntervalS) * time.Second
  243. for {
  244. time.Sleep(td)
  245. if m.LocalAge() > (td / 2).Seconds() {
  246. updateLocalModel(m, w)
  247. }
  248. }
  249. }()
  250. if verbose {
  251. // Periodically print statistics
  252. go printStatsLoop(m)
  253. }
  254. select {}
  255. }
  256. func restart() {
  257. infoln("Restarting")
  258. if os.Getenv("SMF_FMRI") != "" || os.Getenv("STNORESTART") != "" {
  259. // Solaris SMF
  260. infoln("Service manager detected; exit instead of restart")
  261. os.Exit(0)
  262. }
  263. env := os.Environ()
  264. if len(os.Getenv("STRESTART")) == 0 {
  265. env = append(env, "STRESTART=1")
  266. }
  267. pgm, err := exec.LookPath(os.Args[0])
  268. if err != nil {
  269. warnln(err)
  270. return
  271. }
  272. proc, err := os.StartProcess(pgm, os.Args, &os.ProcAttr{
  273. Env: env,
  274. Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
  275. })
  276. if err != nil {
  277. fatalln(err)
  278. }
  279. proc.Release()
  280. os.Exit(0)
  281. }
  282. var saveConfigCh = make(chan struct{})
  283. func saveConfigLoop(cfgFile string) {
  284. for _ = range saveConfigCh {
  285. fd, err := os.Create(cfgFile + ".tmp")
  286. if err != nil {
  287. warnln(err)
  288. continue
  289. }
  290. err = writeConfigXML(fd, cfg)
  291. if err != nil {
  292. warnln(err)
  293. fd.Close()
  294. continue
  295. }
  296. err = fd.Close()
  297. if err != nil {
  298. warnln(err)
  299. continue
  300. }
  301. if runtime.GOOS == "windows" {
  302. err := os.Remove(cfgFile)
  303. if err != nil && !os.IsNotExist(err) {
  304. warnln(err)
  305. }
  306. }
  307. err = os.Rename(cfgFile+".tmp", cfgFile)
  308. if err != nil {
  309. warnln(err)
  310. }
  311. }
  312. }
  313. func saveConfig() {
  314. saveConfigCh <- struct{}{}
  315. }
  316. func printStatsLoop(m *Model) {
  317. var lastUpdated int64
  318. var lastStats = make(map[string]ConnectionInfo)
  319. for {
  320. time.Sleep(60 * time.Second)
  321. for node, stats := range m.ConnectionStats() {
  322. secs := time.Since(lastStats[node].At).Seconds()
  323. inbps := 8 * int(float64(stats.InBytesTotal-lastStats[node].InBytesTotal)/secs)
  324. outbps := 8 * int(float64(stats.OutBytesTotal-lastStats[node].OutBytesTotal)/secs)
  325. if inbps+outbps > 0 {
  326. infof("%s: %sb/s in, %sb/s out", node[0:5], MetricPrefix(int64(inbps)), MetricPrefix(int64(outbps)))
  327. }
  328. lastStats[node] = stats
  329. }
  330. if lu := m.Generation(); lu > lastUpdated {
  331. lastUpdated = lu
  332. files, _, bytes := m.GlobalSize()
  333. infof("%6d files, %9sB in cluster", files, BinaryPrefix(bytes))
  334. files, _, bytes = m.LocalSize()
  335. infof("%6d files, %9sB in local repo", files, BinaryPrefix(bytes))
  336. needFiles, bytes := m.NeedFiles()
  337. infof("%6d files, %9sB to synchronize", len(needFiles), BinaryPrefix(bytes))
  338. }
  339. }
  340. }
  341. func listen(myID string, addr string, m *Model, tlsCfg *tls.Config, connOpts map[string]string) {
  342. if debugNet {
  343. dlog.Println("listening on", addr)
  344. }
  345. l, err := tls.Listen("tcp", addr, tlsCfg)
  346. fatalErr(err)
  347. listen:
  348. for {
  349. conn, err := l.Accept()
  350. if err != nil {
  351. warnln(err)
  352. continue
  353. }
  354. if debugNet {
  355. dlog.Println("connect from", conn.RemoteAddr())
  356. }
  357. tc := conn.(*tls.Conn)
  358. err = tc.Handshake()
  359. if err != nil {
  360. warnln(err)
  361. tc.Close()
  362. continue
  363. }
  364. remoteID := certID(tc.ConnectionState().PeerCertificates[0].Raw)
  365. if remoteID == myID {
  366. warnf("Connect from myself (%s) - should not happen", remoteID)
  367. conn.Close()
  368. continue
  369. }
  370. if m.ConnectedTo(remoteID) {
  371. warnf("Connect from connected node (%s)", remoteID)
  372. }
  373. for _, nodeCfg := range cfg.Repositories[0].Nodes {
  374. if nodeCfg.NodeID == remoteID {
  375. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  376. m.AddConnection(conn, protoConn)
  377. continue listen
  378. }
  379. }
  380. conn.Close()
  381. }
  382. }
  383. func discovery(addr string) *discover.Discoverer {
  384. _, portstr, err := net.SplitHostPort(addr)
  385. fatalErr(err)
  386. port, _ := strconv.Atoi(portstr)
  387. if !cfg.Options.LocalAnnEnabled {
  388. port = -1
  389. } else if verbose {
  390. infoln("Sending local discovery announcements")
  391. }
  392. if !cfg.Options.GlobalAnnEnabled {
  393. cfg.Options.GlobalAnnServer = ""
  394. } else if verbose {
  395. infoln("Sending external discovery announcements")
  396. }
  397. disc, err := discover.NewDiscoverer(myID, port, cfg.Options.GlobalAnnServer)
  398. if err != nil {
  399. warnf("No discovery possible (%v)", err)
  400. }
  401. return disc
  402. }
  403. func connect(myID string, disc *discover.Discoverer, m *Model, tlsCfg *tls.Config, connOpts map[string]string) {
  404. for {
  405. nextNode:
  406. for _, nodeCfg := range cfg.Repositories[0].Nodes {
  407. if nodeCfg.NodeID == myID {
  408. continue
  409. }
  410. if m.ConnectedTo(nodeCfg.NodeID) {
  411. continue
  412. }
  413. for _, addr := range nodeCfg.Addresses {
  414. if addr == "dynamic" {
  415. if disc != nil {
  416. t := disc.Lookup(nodeCfg.NodeID)
  417. if len(t) == 0 {
  418. continue
  419. }
  420. addr = t[0] //XXX: Handle all of them
  421. }
  422. }
  423. if debugNet {
  424. dlog.Println("dial", nodeCfg.NodeID, addr)
  425. }
  426. conn, err := tls.Dial("tcp", addr, tlsCfg)
  427. if err != nil {
  428. if debugNet {
  429. dlog.Println(err)
  430. }
  431. continue
  432. }
  433. remoteID := certID(conn.ConnectionState().PeerCertificates[0].Raw)
  434. if remoteID != nodeCfg.NodeID {
  435. warnln("Unexpected nodeID", remoteID, "!=", nodeCfg.NodeID)
  436. conn.Close()
  437. continue
  438. }
  439. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  440. m.AddConnection(conn, protoConn)
  441. continue nextNode
  442. }
  443. }
  444. time.Sleep(time.Duration(cfg.Options.ReconnectIntervalS) * time.Second)
  445. }
  446. }
  447. func updateLocalModel(m *Model, w *scanner.Walker) {
  448. files, _ := w.Walk()
  449. m.ReplaceLocal(files)
  450. saveIndex(m)
  451. }
  452. func saveIndex(m *Model) {
  453. name := m.RepoID() + ".idx.gz"
  454. fullName := path.Join(confDir, name)
  455. idxf, err := os.Create(fullName + ".tmp")
  456. if err != nil {
  457. return
  458. }
  459. gzw := gzip.NewWriter(idxf)
  460. protocol.IndexMessage{
  461. Repository: "local",
  462. Files: m.ProtocolIndex(),
  463. }.EncodeXDR(gzw)
  464. gzw.Close()
  465. idxf.Close()
  466. os.Rename(fullName+".tmp", fullName)
  467. }
  468. func loadIndex(m *Model) {
  469. name := m.RepoID() + ".idx.gz"
  470. idxf, err := os.Open(path.Join(confDir, name))
  471. if err != nil {
  472. return
  473. }
  474. defer idxf.Close()
  475. gzr, err := gzip.NewReader(idxf)
  476. if err != nil {
  477. return
  478. }
  479. defer gzr.Close()
  480. var im protocol.IndexMessage
  481. err = im.DecodeXDR(gzr)
  482. if err != nil || im.Repository != "local" {
  483. return
  484. }
  485. m.SeedLocal(im.Files)
  486. }
  487. func ensureDir(dir string, mode int) {
  488. fi, err := os.Stat(dir)
  489. if os.IsNotExist(err) {
  490. err := os.MkdirAll(dir, 0700)
  491. fatalErr(err)
  492. } else if mode >= 0 && err == nil && int(fi.Mode()&0777) != mode {
  493. err := os.Chmod(dir, os.FileMode(mode))
  494. fatalErr(err)
  495. }
  496. }
  497. func expandTilde(p string) string {
  498. if runtime.GOOS == "windows" {
  499. return p
  500. }
  501. if strings.HasPrefix(p, "~/") {
  502. return strings.Replace(p, "~", getUnixHomeDir(), 1)
  503. }
  504. return p
  505. }
  506. func getUnixHomeDir() string {
  507. home := os.Getenv("HOME")
  508. if home == "" {
  509. fatalln("No home directory?")
  510. }
  511. return home
  512. }
  513. func getHomeDir() string {
  514. if runtime.GOOS == "windows" {
  515. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  516. if home == "" {
  517. home = os.Getenv("USERPROFILE")
  518. }
  519. return home
  520. }
  521. return getUnixHomeDir()
  522. }
  523. func getDefaultConfDir() string {
  524. if runtime.GOOS == "windows" {
  525. return path.Join(os.Getenv("AppData"), "syncthing")
  526. }
  527. return expandTilde("~/.syncthing")
  528. }