main.go 12 KB

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