main.go 12 KB

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