main.go 12 KB

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