main.go 10 KB

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