main.go 10 KB

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