main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. listen:
  252. for {
  253. conn, err := l.Accept()
  254. if err != nil {
  255. warnln(err)
  256. continue
  257. }
  258. if opts.Debug.TraceConnect {
  259. debugln("NET: Connect from", conn.RemoteAddr())
  260. }
  261. tc := conn.(*tls.Conn)
  262. err = tc.Handshake()
  263. if err != nil {
  264. warnln(err)
  265. tc.Close()
  266. continue
  267. }
  268. remoteID := certId(tc.ConnectionState().PeerCertificates[0].Raw)
  269. if remoteID == myID {
  270. warnf("Connect from myself (%s) - should not happen", remoteID)
  271. conn.Close()
  272. continue
  273. }
  274. if m.ConnectedTo(remoteID) {
  275. warnf("Connect from connected node (%s)", remoteID)
  276. }
  277. for nodeID := range nodeAddrs {
  278. if nodeID == remoteID {
  279. protoConn := protocol.NewConnection(remoteID, conn, conn, m)
  280. m.AddConnection(conn, protoConn)
  281. continue listen
  282. }
  283. }
  284. conn.Close()
  285. }
  286. }
  287. func connect(myID string, addr string, nodeAddrs map[string][]string, m *model.Model, cfg *tls.Config) {
  288. _, portstr, err := net.SplitHostPort(addr)
  289. fatalErr(err)
  290. port, _ := strconv.Atoi(portstr)
  291. if opts.Discovery.NoLocalDiscovery {
  292. port = -1
  293. } else {
  294. infoln("Sending local discovery announcements")
  295. }
  296. if opts.Discovery.NoExternalDiscovery {
  297. opts.Discovery.ExternalPort = -1
  298. } else {
  299. infoln("Sending external discovery announcements")
  300. }
  301. disc, err := discover.NewDiscoverer(myID, port, opts.Discovery.ExternalPort, opts.Discovery.ExternalServer)
  302. if err != nil {
  303. warnf("No discovery possible (%v)", err)
  304. }
  305. for {
  306. nextNode:
  307. for nodeID, addrs := range nodeAddrs {
  308. if nodeID == myID {
  309. continue
  310. }
  311. if m.ConnectedTo(nodeID) {
  312. continue
  313. }
  314. for _, addr := range addrs {
  315. if addr == "dynamic" {
  316. var ok bool
  317. if disc != nil {
  318. addr, ok = disc.Lookup(nodeID)
  319. }
  320. if !ok {
  321. continue
  322. }
  323. }
  324. if opts.Debug.TraceConnect {
  325. debugln("NET: Dial", nodeID, addr)
  326. }
  327. conn, err := tls.Dial("tcp", addr, cfg)
  328. if err != nil {
  329. if opts.Debug.TraceConnect {
  330. debugln("NET:", err)
  331. }
  332. continue
  333. }
  334. remoteID := certId(conn.ConnectionState().PeerCertificates[0].Raw)
  335. if remoteID != nodeID {
  336. warnln("Unexpected nodeID", remoteID, "!=", nodeID)
  337. conn.Close()
  338. continue
  339. }
  340. protoConn := protocol.NewConnection(remoteID, conn, conn, m)
  341. m.AddConnection(conn, protoConn)
  342. continue nextNode
  343. }
  344. }
  345. time.Sleep(opts.Advanced.ConnInterval)
  346. }
  347. }
  348. func updateLocalModel(m *model.Model) {
  349. files, _ := m.Walk(!opts.NoSymlinks)
  350. m.ReplaceLocal(files)
  351. saveIndex(m)
  352. }
  353. func saveIndex(m *model.Model) {
  354. name := m.RepoID() + ".idx.gz"
  355. fullName := path.Join(opts.ConfDir, name)
  356. idxf, err := os.Create(fullName + ".tmp")
  357. if err != nil {
  358. return
  359. }
  360. gzw := gzip.NewWriter(idxf)
  361. protocol.WriteIndex(gzw, m.ProtocolIndex())
  362. gzw.Close()
  363. idxf.Close()
  364. os.Rename(fullName+".tmp", fullName)
  365. }
  366. func loadIndex(m *model.Model) {
  367. name := m.RepoID() + ".idx.gz"
  368. idxf, err := os.Open(path.Join(opts.ConfDir, name))
  369. if err != nil {
  370. return
  371. }
  372. defer idxf.Close()
  373. gzr, err := gzip.NewReader(idxf)
  374. if err != nil {
  375. return
  376. }
  377. defer gzr.Close()
  378. idx, err := protocol.ReadIndex(gzr)
  379. if err != nil {
  380. return
  381. }
  382. m.SeedLocal(idx)
  383. }
  384. func ensureDir(dir string, mode int) {
  385. fi, err := os.Stat(dir)
  386. if os.IsNotExist(err) {
  387. err := os.MkdirAll(dir, 0700)
  388. fatalErr(err)
  389. } else if mode >= 0 && err == nil && int(fi.Mode()&0777) != mode {
  390. err := os.Chmod(dir, os.FileMode(mode))
  391. fatalErr(err)
  392. }
  393. }
  394. func expandTilde(p string) string {
  395. if strings.HasPrefix(p, "~/") {
  396. return strings.Replace(p, "~", getHomeDir(), 1)
  397. }
  398. return p
  399. }
  400. func getHomeDir() string {
  401. home := os.Getenv("HOME")
  402. if home == "" {
  403. fatalln("No home directory?")
  404. }
  405. return home
  406. }