main.go 11 KB

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