main.go 11 KB

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