main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. )
  23. var cfg Configuration
  24. var Version = "unknown-dev"
  25. var (
  26. myID string
  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. pgm, err := exec.LookPath(os.Args[0])
  242. if err != nil {
  243. warnln(err)
  244. return
  245. }
  246. proc, err := os.StartProcess(pgm, args, &os.ProcAttr{
  247. Env: os.Environ(),
  248. Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
  249. })
  250. if err != nil {
  251. fatalln(err)
  252. }
  253. proc.Release()
  254. os.Exit(0)
  255. }
  256. var saveConfigCh = make(chan struct{})
  257. func saveConfigLoop(cfgFile string) {
  258. for _ = range saveConfigCh {
  259. fd, err := os.Create(cfgFile + ".tmp")
  260. if err != nil {
  261. warnln(err)
  262. continue
  263. }
  264. err = writeConfigXML(fd, cfg)
  265. if err != nil {
  266. warnln(err)
  267. fd.Close()
  268. continue
  269. }
  270. err = fd.Close()
  271. if err != nil {
  272. warnln(err)
  273. continue
  274. }
  275. err = os.Rename(cfgFile+".tmp", cfgFile)
  276. if err != nil {
  277. warnln(err)
  278. }
  279. }
  280. }
  281. func saveConfig() {
  282. saveConfigCh <- struct{}{}
  283. }
  284. func printStatsLoop(m *Model) {
  285. var lastUpdated int64
  286. var lastStats = make(map[string]ConnectionInfo)
  287. for {
  288. time.Sleep(60 * time.Second)
  289. for node, stats := range m.ConnectionStats() {
  290. secs := time.Since(lastStats[node].At).Seconds()
  291. inbps := 8 * int(float64(stats.InBytesTotal-lastStats[node].InBytesTotal)/secs)
  292. outbps := 8 * int(float64(stats.OutBytesTotal-lastStats[node].OutBytesTotal)/secs)
  293. if inbps+outbps > 0 {
  294. infof("%s: %sb/s in, %sb/s out", node[0:5], MetricPrefix(int64(inbps)), MetricPrefix(int64(outbps)))
  295. }
  296. lastStats[node] = stats
  297. }
  298. if lu := m.Generation(); lu > lastUpdated {
  299. lastUpdated = lu
  300. files, _, bytes := m.GlobalSize()
  301. infof("%6d files, %9sB in cluster", files, BinaryPrefix(bytes))
  302. files, _, bytes = m.LocalSize()
  303. infof("%6d files, %9sB in local repo", files, BinaryPrefix(bytes))
  304. needFiles, bytes := m.NeedFiles()
  305. infof("%6d files, %9sB to synchronize", len(needFiles), BinaryPrefix(bytes))
  306. }
  307. }
  308. }
  309. func listen(myID string, addr string, m *Model, tlsCfg *tls.Config, connOpts map[string]string) {
  310. if strings.Contains(trace, "connect") {
  311. debugln("NET: Listening on", addr)
  312. }
  313. l, err := tls.Listen("tcp", addr, tlsCfg)
  314. fatalErr(err)
  315. listen:
  316. for {
  317. conn, err := l.Accept()
  318. if err != nil {
  319. warnln(err)
  320. continue
  321. }
  322. if strings.Contains(trace, "connect") {
  323. debugln("NET: Connect from", conn.RemoteAddr())
  324. }
  325. tc := conn.(*tls.Conn)
  326. err = tc.Handshake()
  327. if err != nil {
  328. warnln(err)
  329. tc.Close()
  330. continue
  331. }
  332. remoteID := certID(tc.ConnectionState().PeerCertificates[0].Raw)
  333. if remoteID == myID {
  334. warnf("Connect from myself (%s) - should not happen", remoteID)
  335. conn.Close()
  336. continue
  337. }
  338. if m.ConnectedTo(remoteID) {
  339. warnf("Connect from connected node (%s)", remoteID)
  340. }
  341. for _, nodeCfg := range cfg.Repositories[0].Nodes {
  342. if nodeCfg.NodeID == remoteID {
  343. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  344. m.AddConnection(conn, protoConn)
  345. continue listen
  346. }
  347. }
  348. conn.Close()
  349. }
  350. }
  351. func discovery(addr string) *discover.Discoverer {
  352. _, portstr, err := net.SplitHostPort(addr)
  353. fatalErr(err)
  354. port, _ := strconv.Atoi(portstr)
  355. if !cfg.Options.LocalAnnEnabled {
  356. port = -1
  357. } else if verbose {
  358. infoln("Sending local discovery announcements")
  359. }
  360. if !cfg.Options.GlobalAnnEnabled {
  361. cfg.Options.GlobalAnnServer = ""
  362. } else if verbose {
  363. infoln("Sending external discovery announcements")
  364. }
  365. disc, err := discover.NewDiscoverer(myID, port, cfg.Options.GlobalAnnServer)
  366. if err != nil {
  367. warnf("No discovery possible (%v)", err)
  368. }
  369. return disc
  370. }
  371. func connect(myID string, disc *discover.Discoverer, m *Model, tlsCfg *tls.Config, connOpts map[string]string) {
  372. for {
  373. nextNode:
  374. for _, nodeCfg := range cfg.Repositories[0].Nodes {
  375. if nodeCfg.NodeID == myID {
  376. continue
  377. }
  378. if m.ConnectedTo(nodeCfg.NodeID) {
  379. continue
  380. }
  381. for _, addr := range nodeCfg.Addresses {
  382. if addr == "dynamic" {
  383. if disc != nil {
  384. t := disc.Lookup(nodeCfg.NodeID)
  385. if len(t) == 0 {
  386. continue
  387. }
  388. addr = t[0] //XXX: Handle all of them
  389. }
  390. }
  391. if strings.Contains(trace, "connect") {
  392. debugln("NET: Dial", nodeCfg.NodeID, addr)
  393. }
  394. conn, err := tls.Dial("tcp", addr, tlsCfg)
  395. if err != nil {
  396. if strings.Contains(trace, "connect") {
  397. debugln("NET:", err)
  398. }
  399. continue
  400. }
  401. remoteID := certID(conn.ConnectionState().PeerCertificates[0].Raw)
  402. if remoteID != nodeCfg.NodeID {
  403. warnln("Unexpected nodeID", remoteID, "!=", nodeCfg.NodeID)
  404. conn.Close()
  405. continue
  406. }
  407. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  408. m.AddConnection(conn, protoConn)
  409. continue nextNode
  410. }
  411. }
  412. time.Sleep(time.Duration(cfg.Options.ReconnectIntervalS) * time.Second)
  413. }
  414. }
  415. func updateLocalModel(m *Model) {
  416. files, _ := m.Walk(cfg.Options.FollowSymlinks)
  417. m.ReplaceLocal(files)
  418. saveIndex(m)
  419. }
  420. func saveIndex(m *Model) {
  421. name := m.RepoID() + ".idx.gz"
  422. fullName := path.Join(confDir, name)
  423. idxf, err := os.Create(fullName + ".tmp")
  424. if err != nil {
  425. return
  426. }
  427. gzw := gzip.NewWriter(idxf)
  428. protocol.IndexMessage{
  429. Repository: "local",
  430. Files: m.ProtocolIndex(),
  431. }.EncodeXDR(gzw)
  432. gzw.Close()
  433. idxf.Close()
  434. os.Rename(fullName+".tmp", fullName)
  435. }
  436. func loadIndex(m *Model) {
  437. name := m.RepoID() + ".idx.gz"
  438. idxf, err := os.Open(path.Join(confDir, name))
  439. if err != nil {
  440. return
  441. }
  442. defer idxf.Close()
  443. gzr, err := gzip.NewReader(idxf)
  444. if err != nil {
  445. return
  446. }
  447. defer gzr.Close()
  448. var im protocol.IndexMessage
  449. err = im.DecodeXDR(gzr)
  450. if err != nil || im.Repository != "local" {
  451. return
  452. }
  453. m.SeedLocal(im.Files)
  454. }
  455. func ensureDir(dir string, mode int) {
  456. fi, err := os.Stat(dir)
  457. if os.IsNotExist(err) {
  458. err := os.MkdirAll(dir, 0700)
  459. fatalErr(err)
  460. } else if mode >= 0 && err == nil && int(fi.Mode()&0777) != mode {
  461. err := os.Chmod(dir, os.FileMode(mode))
  462. fatalErr(err)
  463. }
  464. }
  465. func expandTilde(p string) string {
  466. if strings.HasPrefix(p, "~/") {
  467. return strings.Replace(p, "~", getHomeDir(), 1)
  468. }
  469. return p
  470. }
  471. func getHomeDir() string {
  472. home := os.Getenv("HOME")
  473. if home == "" {
  474. fatalln("No home directory?")
  475. }
  476. return home
  477. }