main.go 12 KB

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