main.go 10 KB

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