main.go 10 KB

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