main.go 11 KB

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