main.go 10 KB

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