main.go 10 KB

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