main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. if opts.Debug.Profiler != "" {
  108. go func() {
  109. err := http.ListenAndServe(opts.Debug.Profiler, nil)
  110. if err != nil {
  111. warnln(err)
  112. }
  113. }()
  114. }
  115. // The TLS configuration is used for both the listening socket and outgoing
  116. // connections.
  117. cfg := &tls.Config{
  118. Certificates: []tls.Certificate{cert},
  119. NextProtos: []string{"bep/1.0"},
  120. ServerName: myID,
  121. ClientAuth: tls.RequestClientCert,
  122. SessionTicketsDisabled: true,
  123. InsecureSkipVerify: true,
  124. MinVersion: tls.VersionTLS12,
  125. }
  126. // Load the configuration file, if it exists.
  127. cf, err := os.Open(path.Join(opts.ConfDir, confFileName))
  128. if err != nil {
  129. fatalln("No config file")
  130. config = ini.Config{}
  131. }
  132. config = ini.Parse(cf)
  133. cf.Close()
  134. var dir = expandTilde(config.Get("repository", "dir"))
  135. // Create a map of desired node connections based on the configuration file
  136. // directives.
  137. for nodeID, addrs := range config.OptionMap("nodes") {
  138. addrs := strings.Fields(addrs)
  139. nodeAddrs[nodeID] = addrs
  140. }
  141. ensureDir(dir, -1)
  142. m := model.NewModel(dir, opts.Advanced.MaxChangeBW)
  143. for _, t := range opts.Debug.TraceModel {
  144. m.Trace(t)
  145. }
  146. if opts.Advanced.LimitRate > 0 {
  147. m.LimitRate(opts.Advanced.LimitRate)
  148. }
  149. // GUI
  150. if !opts.NoGUI && opts.GUIAddr != "" {
  151. host, port, err := net.SplitHostPort(opts.GUIAddr)
  152. if err != nil {
  153. warnf("Cannot start GUI on %q: %v", opts.GUIAddr, err)
  154. } else {
  155. if len(host) > 0 {
  156. infof("Starting web GUI on http://%s", opts.GUIAddr)
  157. } else {
  158. infof("Starting web GUI on port %s", port)
  159. }
  160. startGUI(opts.GUIAddr, m)
  161. }
  162. }
  163. // Walk the repository and update the local model before establishing any
  164. // connections to other nodes.
  165. if !opts.Rehash {
  166. infoln("Loading index cache")
  167. loadIndex(m)
  168. }
  169. infoln("Populating repository index")
  170. updateLocalModel(m)
  171. // Routine to listen for incoming connections
  172. infoln("Listening for incoming connections")
  173. go listen(myID, opts.Listen, m, cfg)
  174. // Routine to connect out to configured nodes
  175. infoln("Attempting to connect to other nodes")
  176. go connect(myID, opts.Listen, nodeAddrs, m, cfg)
  177. // Routine to pull blocks from other nodes to synchronize the local
  178. // repository. Does not run when we are in read only (publish only) mode.
  179. if !opts.ReadOnly {
  180. if opts.NoDelete {
  181. infoln("Deletes from peer nodes will be ignored")
  182. } else {
  183. infoln("Deletes from peer nodes are allowed")
  184. }
  185. okln("Ready to synchronize (read-write)")
  186. m.StartRW(!opts.NoDelete, opts.Advanced.RequestsInFlight)
  187. } else {
  188. okln("Ready to synchronize (read only; no external updates accepted)")
  189. }
  190. // Periodically scan the repository and update the local model.
  191. // XXX: Should use some fsnotify mechanism.
  192. go func() {
  193. for {
  194. time.Sleep(opts.Advanced.ScanInterval)
  195. if m.LocalAge() > opts.Advanced.ScanInterval.Seconds()/2 {
  196. updateLocalModel(m)
  197. }
  198. }
  199. }()
  200. if !opts.NoStats {
  201. // Periodically print statistics
  202. go printStatsLoop(m)
  203. }
  204. select {}
  205. }
  206. func printStatsLoop(m *model.Model) {
  207. var lastUpdated int64
  208. var lastStats = make(map[string]model.ConnectionInfo)
  209. for {
  210. time.Sleep(60 * time.Second)
  211. for node, stats := range m.ConnectionStats() {
  212. secs := time.Since(lastStats[node].At).Seconds()
  213. inbps := 8 * int(float64(stats.InBytesTotal-lastStats[node].InBytesTotal)/secs)
  214. outbps := 8 * int(float64(stats.OutBytesTotal-lastStats[node].OutBytesTotal)/secs)
  215. if inbps+outbps > 0 {
  216. infof("%s: %sb/s in, %sb/s out", node[0:5], MetricPrefix(inbps), MetricPrefix(outbps))
  217. }
  218. lastStats[node] = stats
  219. }
  220. if lu := m.Generation(); lu > lastUpdated {
  221. lastUpdated = lu
  222. files, _, bytes := m.GlobalSize()
  223. infof("%6d files, %9sB in cluster", files, BinaryPrefix(bytes))
  224. files, _, bytes = m.LocalSize()
  225. infof("%6d files, %9sB in local repo", files, BinaryPrefix(bytes))
  226. needFiles, bytes := m.NeedFiles()
  227. infof("%6d files, %9sB to synchronize", len(needFiles), BinaryPrefix(bytes))
  228. }
  229. }
  230. }
  231. func listen(myID string, addr string, m *model.Model, cfg *tls.Config) {
  232. l, err := tls.Listen("tcp", addr, cfg)
  233. fatalErr(err)
  234. listen:
  235. for {
  236. conn, err := l.Accept()
  237. if err != nil {
  238. warnln(err)
  239. continue
  240. }
  241. if opts.Debug.TraceConnect {
  242. debugln("NET: Connect from", conn.RemoteAddr())
  243. }
  244. tc := conn.(*tls.Conn)
  245. err = tc.Handshake()
  246. if err != nil {
  247. warnln(err)
  248. tc.Close()
  249. continue
  250. }
  251. remoteID := certId(tc.ConnectionState().PeerCertificates[0].Raw)
  252. if remoteID == myID {
  253. warnf("Connect from myself (%s) - should not happen", remoteID)
  254. conn.Close()
  255. continue
  256. }
  257. if m.ConnectedTo(remoteID) {
  258. warnf("Connect from connected node (%s)", remoteID)
  259. }
  260. for nodeID := range nodeAddrs {
  261. if nodeID == remoteID {
  262. protoConn := protocol.NewConnection(remoteID, conn, conn, m)
  263. m.AddConnection(conn, protoConn)
  264. continue listen
  265. }
  266. }
  267. conn.Close()
  268. }
  269. }
  270. func connect(myID string, addr string, nodeAddrs map[string][]string, m *model.Model, cfg *tls.Config) {
  271. _, portstr, err := net.SplitHostPort(addr)
  272. fatalErr(err)
  273. port, _ := strconv.Atoi(portstr)
  274. if opts.Discovery.NoLocalDiscovery {
  275. port = -1
  276. } else {
  277. infoln("Sending local discovery announcements")
  278. }
  279. if opts.Discovery.NoExternalDiscovery {
  280. opts.Discovery.ExternalPort = -1
  281. } else {
  282. infoln("Sending external discovery announcements")
  283. }
  284. disc, err := discover.NewDiscoverer(myID, port, opts.Discovery.ExternalPort, opts.Discovery.ExternalServer)
  285. if err != nil {
  286. warnf("No discovery possible (%v)", err)
  287. }
  288. for {
  289. nextNode:
  290. for nodeID, addrs := range nodeAddrs {
  291. if nodeID == myID {
  292. continue
  293. }
  294. if m.ConnectedTo(nodeID) {
  295. continue
  296. }
  297. for _, addr := range addrs {
  298. if addr == "dynamic" {
  299. var ok bool
  300. if disc != nil {
  301. addr, ok = disc.Lookup(nodeID)
  302. }
  303. if !ok {
  304. continue
  305. }
  306. }
  307. if opts.Debug.TraceConnect {
  308. debugln("NET: Dial", nodeID, addr)
  309. }
  310. conn, err := tls.Dial("tcp", addr, cfg)
  311. if err != nil {
  312. if opts.Debug.TraceConnect {
  313. debugln("NET:", err)
  314. }
  315. continue
  316. }
  317. remoteID := certId(conn.ConnectionState().PeerCertificates[0].Raw)
  318. if remoteID != nodeID {
  319. warnln("Unexpected nodeID", remoteID, "!=", nodeID)
  320. conn.Close()
  321. continue
  322. }
  323. protoConn := protocol.NewConnection(remoteID, conn, conn, m)
  324. m.AddConnection(conn, protoConn)
  325. continue nextNode
  326. }
  327. }
  328. time.Sleep(opts.Advanced.ConnInterval)
  329. }
  330. }
  331. func updateLocalModel(m *model.Model) {
  332. files, _ := m.Walk(!opts.NoSymlinks)
  333. m.ReplaceLocal(files)
  334. saveIndex(m)
  335. }
  336. func saveIndex(m *model.Model) {
  337. name := m.RepoID() + ".idx.gz"
  338. fullName := path.Join(opts.ConfDir, name)
  339. idxf, err := os.Create(fullName + ".tmp")
  340. if err != nil {
  341. return
  342. }
  343. gzw := gzip.NewWriter(idxf)
  344. protocol.WriteIndex(gzw, m.ProtocolIndex())
  345. gzw.Close()
  346. idxf.Close()
  347. os.Rename(fullName+".tmp", fullName)
  348. }
  349. func loadIndex(m *model.Model) {
  350. name := m.RepoID() + ".idx.gz"
  351. idxf, err := os.Open(path.Join(opts.ConfDir, name))
  352. if err != nil {
  353. return
  354. }
  355. defer idxf.Close()
  356. gzr, err := gzip.NewReader(idxf)
  357. if err != nil {
  358. return
  359. }
  360. defer gzr.Close()
  361. idx, err := protocol.ReadIndex(gzr)
  362. if err != nil {
  363. return
  364. }
  365. m.SeedLocal(idx)
  366. }
  367. func ensureDir(dir string, mode int) {
  368. fi, err := os.Stat(dir)
  369. if os.IsNotExist(err) {
  370. err := os.MkdirAll(dir, 0700)
  371. fatalErr(err)
  372. } else if mode >= 0 && err == nil && int(fi.Mode()&0777) != mode {
  373. err := os.Chmod(dir, os.FileMode(mode))
  374. fatalErr(err)
  375. }
  376. }
  377. func expandTilde(p string) string {
  378. if strings.HasPrefix(p, "~/") {
  379. return strings.Replace(p, "~", getHomeDir(), 1)
  380. }
  381. return p
  382. }
  383. func getHomeDir() string {
  384. home := os.Getenv("HOME")
  385. if home == "" {
  386. fatalln("No home directory?")
  387. }
  388. return home
  389. }