main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package main
  2. import (
  3. "compress/gzip"
  4. "crypto/tls"
  5. "fmt"
  6. "log"
  7. "net"
  8. "net/http"
  9. _ "net/http/pprof"
  10. "os"
  11. "path"
  12. "runtime"
  13. "runtime/debug"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/calmh/ini"
  18. "github.com/calmh/syncthing/discover"
  19. flags "github.com/calmh/syncthing/github.com/jessevdk/go-flags"
  20. "github.com/calmh/syncthing/model"
  21. "github.com/calmh/syncthing/protocol"
  22. )
  23. type Options struct {
  24. ConfDir string `short:"c" long:"cfg" description:"Configuration directory" default:"~/.syncthing" value-name:"DIR"`
  25. Listen string `short:"l" long:"listen" description:"Listen address" default:":22000" value-name:"ADDR"`
  26. ReadOnly bool `short:"r" long:"ro" description:"Repository is read only"`
  27. Rehash bool `long:"rehash" description:"Ignore cache and rehash all files in repository"`
  28. NoDelete bool `long:"no-delete" description:"Never delete files"`
  29. NoSymlinks bool `long:"no-symlinks" description:"Don't follow first level symlinks in the repo"`
  30. NoStats bool `long:"no-stats" description:"Don't print model and connection statistics"`
  31. NoGUI bool `long:"no-gui" description:"Don't start GUI"`
  32. GUIAddr string `long:"gui-addr" description:"GUI listen address" default:"127.0.0.1:8080" value-name:"ADDR"`
  33. ShowVersion bool `short:"v" long:"version" description:"Show version"`
  34. Discovery DiscoveryOptions `group:"Discovery Options"`
  35. Advanced AdvancedOptions `group:"Advanced Options"`
  36. Debug DebugOptions `group:"Debugging Options"`
  37. }
  38. type DebugOptions struct {
  39. LogSource bool `long:"log-source"`
  40. TraceModel []string `long:"trace-model" value-name:"TRACE" description:"idx, net, file, need, pull"`
  41. TraceConnect bool `long:"trace-connect"`
  42. Profiler string `long:"profiler" value-name:"ADDR"`
  43. }
  44. type DiscoveryOptions struct {
  45. ExternalServer string `long:"ext-server" description:"External discovery server" value-name:"NAME" default:"syncthing.nym.se"`
  46. ExternalPort int `short:"e" long:"ext-port" description:"External listen port" value-name:"PORT" default:"22000"`
  47. NoExternalDiscovery bool `short:"n" long:"no-ext-announce" description:"Do not announce presence externally"`
  48. NoLocalDiscovery bool `short:"N" long:"no-local-announce" description:"Do not announce presence locally"`
  49. }
  50. type AdvancedOptions struct {
  51. RequestsInFlight int `long:"reqs-in-flight" description:"Parallell in flight requests per node" default:"8" value-name:"REQS"`
  52. LimitRate int `long:"send-rate" description:"Rate limit for outgoing data" default:"0" value-name:"KBPS"`
  53. ScanInterval time.Duration `long:"scan-intv" description:"Repository scan interval" default:"60s" value-name:"INTV"`
  54. ConnInterval time.Duration `long:"conn-intv" description:"Node reconnect interval" default:"60s" value-name:"INTV"`
  55. MaxChangeBW int `long:"max-change-bw" description:"Max change bandwidth per file" default:"1e6" value-name:"MB/s"`
  56. }
  57. var opts Options
  58. var Version string = "unknown-dev"
  59. const (
  60. confFileName = "syncthing.ini"
  61. )
  62. var (
  63. myID string
  64. config ini.Config
  65. nodeAddrs = make(map[string][]string)
  66. )
  67. func main() {
  68. log.SetOutput(os.Stderr)
  69. logger = log.New(os.Stderr, "", log.Flags())
  70. _, err := flags.Parse(&opts)
  71. if err != nil {
  72. if err, ok := err.(*flags.Error); ok {
  73. if err.Type == flags.ErrHelp {
  74. os.Exit(0)
  75. }
  76. }
  77. fatalln(err)
  78. }
  79. if opts.ShowVersion {
  80. fmt.Println(Version)
  81. os.Exit(0)
  82. }
  83. if len(os.Getenv("GOGC")) == 0 {
  84. debug.SetGCPercent(25)
  85. }
  86. if len(os.Getenv("GOMAXPROCS")) == 0 {
  87. runtime.GOMAXPROCS(runtime.NumCPU())
  88. }
  89. if len(opts.Debug.TraceModel) > 0 || opts.Debug.LogSource {
  90. log.SetFlags(log.Lshortfile | log.Ldate | log.Ltime | log.Lmicroseconds)
  91. logger.SetFlags(log.Lshortfile | log.Ldate | log.Ltime | log.Lmicroseconds)
  92. }
  93. opts.ConfDir = expandTilde(opts.ConfDir)
  94. infoln("Version", Version)
  95. // Ensure that our home directory exists and that we have a certificate and key.
  96. ensureDir(opts.ConfDir, 0700)
  97. cert, err := loadCert(opts.ConfDir)
  98. if err != nil {
  99. newCertificate(opts.ConfDir)
  100. cert, err = loadCert(opts.ConfDir)
  101. fatalErr(err)
  102. }
  103. myID = string(certId(cert.Certificate[0]))
  104. infoln("My ID:", myID)
  105. log.SetPrefix("[" + myID[0:5] + "] ")
  106. logger.SetPrefix("[" + myID[0:5] + "] ")
  107. // Load the configuration file, if it exists.
  108. // If it does not, create a template.
  109. cfgFile := path.Join(opts.ConfDir, confFileName)
  110. cf, err := os.Open(cfgFile)
  111. if err != nil {
  112. infoln("No config file; creating a template")
  113. config = ini.Config{}
  114. config.AddComment("repository", "Set the following to the directory you wish to synchronize")
  115. config.AddComment("repository", "dir = ~/Syncthing")
  116. config.Set("nodes", myID, "auto")
  117. config.AddComment("nodes", "Add peer nodes here")
  118. fd, err := os.Create(cfgFile)
  119. if err != nil {
  120. fatalln(err)
  121. }
  122. config.Write(fd)
  123. fd.Close()
  124. infof("Edit %s to suit and restart syncthing.", cfgFile)
  125. os.Exit(0)
  126. }
  127. config = ini.Parse(cf)
  128. cf.Close()
  129. var dir = expandTilde(config.Get("repository", "dir"))
  130. if len(dir) == 0 {
  131. fatalln("No repository directory. Set dir under [repository] in syncthing.ini.")
  132. }
  133. if opts.Debug.Profiler != "" {
  134. go func() {
  135. err := http.ListenAndServe(opts.Debug.Profiler, nil)
  136. if err != nil {
  137. warnln(err)
  138. }
  139. }()
  140. }
  141. // The TLS configuration is used for both the listening socket and outgoing
  142. // connections.
  143. cfg := &tls.Config{
  144. Certificates: []tls.Certificate{cert},
  145. NextProtos: []string{"bep/1.0"},
  146. ServerName: myID,
  147. ClientAuth: tls.RequestClientCert,
  148. SessionTicketsDisabled: true,
  149. InsecureSkipVerify: true,
  150. MinVersion: tls.VersionTLS12,
  151. }
  152. // Create a map of desired node connections based on the configuration file
  153. // directives.
  154. for nodeID, addrs := range config.OptionMap("nodes") {
  155. addrs := strings.Fields(addrs)
  156. nodeAddrs[nodeID] = addrs
  157. }
  158. ensureDir(dir, -1)
  159. m := model.NewModel(dir, opts.Advanced.MaxChangeBW)
  160. for _, t := range opts.Debug.TraceModel {
  161. m.Trace(t)
  162. }
  163. if opts.Advanced.LimitRate > 0 {
  164. m.LimitRate(opts.Advanced.LimitRate)
  165. }
  166. // GUI
  167. if !opts.NoGUI && opts.GUIAddr != "" {
  168. host, port, err := net.SplitHostPort(opts.GUIAddr)
  169. if err != nil {
  170. warnf("Cannot start GUI on %q: %v", opts.GUIAddr, err)
  171. } else {
  172. if len(host) > 0 {
  173. infof("Starting web GUI on http://%s", opts.GUIAddr)
  174. } else {
  175. infof("Starting web GUI on port %s", port)
  176. }
  177. startGUI(opts.GUIAddr, m)
  178. }
  179. }
  180. // Walk the repository and update the local model before establishing any
  181. // connections to other nodes.
  182. if !opts.Rehash {
  183. infoln("Loading index cache")
  184. loadIndex(m)
  185. }
  186. infoln("Populating repository index")
  187. updateLocalModel(m)
  188. // Routine to listen for incoming connections
  189. infoln("Listening for incoming connections")
  190. go listen(myID, opts.Listen, m, cfg)
  191. // Routine to connect out to configured nodes
  192. infoln("Attempting to connect to other nodes")
  193. go connect(myID, opts.Listen, nodeAddrs, m, cfg)
  194. // Routine to pull blocks from other nodes to synchronize the local
  195. // repository. Does not run when we are in read only (publish only) mode.
  196. if !opts.ReadOnly {
  197. if opts.NoDelete {
  198. infoln("Deletes from peer nodes will be ignored")
  199. } else {
  200. infoln("Deletes from peer nodes are allowed")
  201. }
  202. okln("Ready to synchronize (read-write)")
  203. m.StartRW(!opts.NoDelete, opts.Advanced.RequestsInFlight)
  204. } else {
  205. okln("Ready to synchronize (read only; no external updates accepted)")
  206. }
  207. // Periodically scan the repository and update the local model.
  208. // XXX: Should use some fsnotify mechanism.
  209. go func() {
  210. for {
  211. time.Sleep(opts.Advanced.ScanInterval)
  212. if m.LocalAge() > opts.Advanced.ScanInterval.Seconds()/2 {
  213. updateLocalModel(m)
  214. }
  215. }
  216. }()
  217. if !opts.NoStats {
  218. // Periodically print statistics
  219. go printStatsLoop(m)
  220. }
  221. select {}
  222. }
  223. func printStatsLoop(m *model.Model) {
  224. var lastUpdated int64
  225. var lastStats = make(map[string]model.ConnectionInfo)
  226. for {
  227. time.Sleep(60 * time.Second)
  228. for node, stats := range m.ConnectionStats() {
  229. secs := time.Since(lastStats[node].At).Seconds()
  230. inbps := 8 * int(float64(stats.InBytesTotal-lastStats[node].InBytesTotal)/secs)
  231. outbps := 8 * int(float64(stats.OutBytesTotal-lastStats[node].OutBytesTotal)/secs)
  232. if inbps+outbps > 0 {
  233. infof("%s: %sb/s in, %sb/s out", node[0:5], MetricPrefix(inbps), MetricPrefix(outbps))
  234. }
  235. lastStats[node] = stats
  236. }
  237. if lu := m.Generation(); lu > lastUpdated {
  238. lastUpdated = lu
  239. files, _, bytes := m.GlobalSize()
  240. infof("%6d files, %9sB in cluster", files, BinaryPrefix(bytes))
  241. files, _, bytes = m.LocalSize()
  242. infof("%6d files, %9sB in local repo", files, BinaryPrefix(bytes))
  243. needFiles, bytes := m.NeedFiles()
  244. infof("%6d files, %9sB to synchronize", len(needFiles), BinaryPrefix(bytes))
  245. }
  246. }
  247. }
  248. func listen(myID string, addr string, m *model.Model, cfg *tls.Config) {
  249. l, err := tls.Listen("tcp", addr, cfg)
  250. fatalErr(err)
  251. connOpts := map[string]string{
  252. "clientId": "syncthing",
  253. "clientVersion": Version,
  254. }
  255. listen:
  256. for {
  257. conn, err := l.Accept()
  258. if err != nil {
  259. warnln(err)
  260. continue
  261. }
  262. if opts.Debug.TraceConnect {
  263. debugln("NET: Connect from", conn.RemoteAddr())
  264. }
  265. tc := conn.(*tls.Conn)
  266. err = tc.Handshake()
  267. if err != nil {
  268. warnln(err)
  269. tc.Close()
  270. continue
  271. }
  272. remoteID := certId(tc.ConnectionState().PeerCertificates[0].Raw)
  273. if remoteID == myID {
  274. warnf("Connect from myself (%s) - should not happen", remoteID)
  275. conn.Close()
  276. continue
  277. }
  278. if m.ConnectedTo(remoteID) {
  279. warnf("Connect from connected node (%s)", remoteID)
  280. }
  281. for nodeID := range nodeAddrs {
  282. if nodeID == remoteID {
  283. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  284. m.AddConnection(conn, protoConn)
  285. continue listen
  286. }
  287. }
  288. conn.Close()
  289. }
  290. }
  291. func connect(myID string, addr string, nodeAddrs map[string][]string, m *model.Model, cfg *tls.Config) {
  292. _, portstr, err := net.SplitHostPort(addr)
  293. fatalErr(err)
  294. port, _ := strconv.Atoi(portstr)
  295. if opts.Discovery.NoLocalDiscovery {
  296. port = -1
  297. } else {
  298. infoln("Sending local discovery announcements")
  299. }
  300. if opts.Discovery.NoExternalDiscovery {
  301. opts.Discovery.ExternalPort = -1
  302. } else {
  303. infoln("Sending external discovery announcements")
  304. }
  305. disc, err := discover.NewDiscoverer(myID, port, opts.Discovery.ExternalPort, opts.Discovery.ExternalServer)
  306. if err != nil {
  307. warnf("No discovery possible (%v)", err)
  308. }
  309. connOpts := map[string]string{
  310. "clientId": "syncthing",
  311. "clientVersion": Version,
  312. }
  313. for {
  314. nextNode:
  315. for nodeID, addrs := range nodeAddrs {
  316. if nodeID == myID {
  317. continue
  318. }
  319. if m.ConnectedTo(nodeID) {
  320. continue
  321. }
  322. for _, addr := range addrs {
  323. if addr == "dynamic" {
  324. var ok bool
  325. if disc != nil {
  326. addr, ok = disc.Lookup(nodeID)
  327. }
  328. if !ok {
  329. continue
  330. }
  331. }
  332. if opts.Debug.TraceConnect {
  333. debugln("NET: Dial", nodeID, addr)
  334. }
  335. conn, err := tls.Dial("tcp", addr, cfg)
  336. if err != nil {
  337. if opts.Debug.TraceConnect {
  338. debugln("NET:", err)
  339. }
  340. continue
  341. }
  342. remoteID := certId(conn.ConnectionState().PeerCertificates[0].Raw)
  343. if remoteID != nodeID {
  344. warnln("Unexpected nodeID", remoteID, "!=", nodeID)
  345. conn.Close()
  346. continue
  347. }
  348. protoConn := protocol.NewConnection(remoteID, conn, conn, m, connOpts)
  349. m.AddConnection(conn, protoConn)
  350. continue nextNode
  351. }
  352. }
  353. time.Sleep(opts.Advanced.ConnInterval)
  354. }
  355. }
  356. func updateLocalModel(m *model.Model) {
  357. files, _ := m.Walk(!opts.NoSymlinks)
  358. m.ReplaceLocal(files)
  359. saveIndex(m)
  360. }
  361. func saveIndex(m *model.Model) {
  362. name := m.RepoID() + ".idx.gz"
  363. fullName := path.Join(opts.ConfDir, name)
  364. idxf, err := os.Create(fullName + ".tmp")
  365. if err != nil {
  366. return
  367. }
  368. gzw := gzip.NewWriter(idxf)
  369. protocol.WriteIndex(gzw, m.ProtocolIndex())
  370. gzw.Close()
  371. idxf.Close()
  372. os.Rename(fullName+".tmp", fullName)
  373. }
  374. func loadIndex(m *model.Model) {
  375. name := m.RepoID() + ".idx.gz"
  376. idxf, err := os.Open(path.Join(opts.ConfDir, name))
  377. if err != nil {
  378. return
  379. }
  380. defer idxf.Close()
  381. gzr, err := gzip.NewReader(idxf)
  382. if err != nil {
  383. return
  384. }
  385. defer gzr.Close()
  386. idx, err := protocol.ReadIndex(gzr)
  387. if err != nil {
  388. return
  389. }
  390. m.SeedLocal(idx)
  391. }
  392. func ensureDir(dir string, mode int) {
  393. fi, err := os.Stat(dir)
  394. if os.IsNotExist(err) {
  395. err := os.MkdirAll(dir, 0700)
  396. fatalErr(err)
  397. } else if mode >= 0 && err == nil && int(fi.Mode()&0777) != mode {
  398. err := os.Chmod(dir, os.FileMode(mode))
  399. fatalErr(err)
  400. }
  401. }
  402. func expandTilde(p string) string {
  403. if strings.HasPrefix(p, "~/") {
  404. return strings.Replace(p, "~", getHomeDir(), 1)
  405. }
  406. return p
  407. }
  408. func getHomeDir() string {
  409. home := os.Getenv("HOME")
  410. if home == "" {
  411. fatalln("No home directory?")
  412. }
  413. return home
  414. }