protocol.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. package protocol
  2. import (
  3. "bufio"
  4. "compress/flate"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "log"
  9. "sync"
  10. "time"
  11. "github.com/calmh/syncthing/buffers"
  12. "github.com/calmh/syncthing/xdr"
  13. )
  14. const BlockSize = 128 * 1024
  15. const (
  16. messageTypeIndex = 1
  17. messageTypeRequest = 2
  18. messageTypeResponse = 3
  19. messageTypePing = 4
  20. messageTypePong = 5
  21. messageTypeIndexUpdate = 6
  22. messageTypeOptions = 7
  23. )
  24. const (
  25. FlagDeleted uint32 = 1 << 12
  26. FlagInvalid = 1 << 13
  27. FlagDirectory = 1 << 14
  28. )
  29. var (
  30. ErrClusterHash = fmt.Errorf("configuration error: mismatched cluster hash")
  31. ErrClosed = errors.New("connection closed")
  32. )
  33. type Model interface {
  34. // An index was received from the peer node
  35. Index(nodeID string, repo string, files []FileInfo)
  36. // An index update was received from the peer node
  37. IndexUpdate(nodeID string, repo string, files []FileInfo)
  38. // A request was made by the peer node
  39. Request(nodeID string, repo string, name string, offset int64, size int) ([]byte, error)
  40. // The peer node closed the connection
  41. Close(nodeID string, err error)
  42. }
  43. type Connection interface {
  44. ID() string
  45. Index(repo string, files []FileInfo)
  46. Request(repo string, name string, offset int64, size int) ([]byte, error)
  47. Statistics() Statistics
  48. Option(key string) string
  49. }
  50. type rawConnection struct {
  51. sync.RWMutex
  52. id string
  53. receiver Model
  54. reader io.ReadCloser
  55. xr *xdr.Reader
  56. writer io.WriteCloser
  57. wb *bufio.Writer
  58. xw *xdr.Writer
  59. closed chan struct{}
  60. awaiting map[int]chan asyncResult
  61. nextID int
  62. indexSent map[string]map[string][2]int64
  63. peerOptions map[string]string
  64. myOptions map[string]string
  65. optionsLock sync.Mutex
  66. hasSentIndex bool
  67. hasRecvdIndex bool
  68. }
  69. type asyncResult struct {
  70. val []byte
  71. err error
  72. }
  73. const (
  74. pingTimeout = 2 * time.Minute
  75. pingIdleTime = 5 * time.Minute
  76. )
  77. func NewConnection(nodeID string, reader io.Reader, writer io.Writer, receiver Model, options map[string]string) Connection {
  78. flrd := flate.NewReader(reader)
  79. flwr, err := flate.NewWriter(writer, flate.BestSpeed)
  80. if err != nil {
  81. panic(err)
  82. }
  83. wb := bufio.NewWriter(flwr)
  84. c := rawConnection{
  85. id: nodeID,
  86. receiver: nativeModel{receiver},
  87. reader: flrd,
  88. xr: xdr.NewReader(flrd),
  89. writer: flwr,
  90. wb: wb,
  91. xw: xdr.NewWriter(wb),
  92. closed: make(chan struct{}),
  93. awaiting: make(map[int]chan asyncResult),
  94. indexSent: make(map[string]map[string][2]int64),
  95. }
  96. go c.readerLoop()
  97. go c.pingerLoop()
  98. if options != nil {
  99. c.myOptions = options
  100. go func() {
  101. c.Lock()
  102. header{0, c.nextID, messageTypeOptions}.encodeXDR(c.xw)
  103. var om OptionsMessage
  104. for k, v := range options {
  105. om.Options = append(om.Options, Option{k, v})
  106. }
  107. om.encodeXDR(c.xw)
  108. err := c.xw.Error()
  109. if err == nil {
  110. err = c.flush()
  111. }
  112. if err != nil {
  113. log.Println("Warning: Write error during initial handshake:", err)
  114. }
  115. c.nextID++
  116. c.Unlock()
  117. }()
  118. }
  119. return wireFormatConnection{&c}
  120. }
  121. func (c *rawConnection) ID() string {
  122. return c.id
  123. }
  124. // Index writes the list of file information to the connected peer node
  125. func (c *rawConnection) Index(repo string, idx []FileInfo) {
  126. c.Lock()
  127. if c.isClosed() {
  128. c.Unlock()
  129. return
  130. }
  131. var msgType int
  132. if c.indexSent[repo] == nil {
  133. // This is the first time we send an index.
  134. msgType = messageTypeIndex
  135. c.indexSent[repo] = make(map[string][2]int64)
  136. for _, f := range idx {
  137. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  138. }
  139. } else {
  140. // We have sent one full index. Only send updates now.
  141. msgType = messageTypeIndexUpdate
  142. var diff []FileInfo
  143. for _, f := range idx {
  144. if vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {
  145. diff = append(diff, f)
  146. c.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}
  147. }
  148. }
  149. idx = diff
  150. }
  151. header{0, c.nextID, msgType}.encodeXDR(c.xw)
  152. _, err := IndexMessage{repo, idx}.encodeXDR(c.xw)
  153. if err == nil {
  154. err = c.flush()
  155. }
  156. c.nextID = (c.nextID + 1) & 0xfff
  157. c.hasSentIndex = true
  158. c.Unlock()
  159. if err != nil {
  160. c.close(err)
  161. return
  162. }
  163. }
  164. // Request returns the bytes for the specified block after fetching them from the connected peer.
  165. func (c *rawConnection) Request(repo string, name string, offset int64, size int) ([]byte, error) {
  166. c.Lock()
  167. if c.isClosed() {
  168. c.Unlock()
  169. return nil, ErrClosed
  170. }
  171. rc := make(chan asyncResult)
  172. if _, ok := c.awaiting[c.nextID]; ok {
  173. panic("id taken")
  174. }
  175. c.awaiting[c.nextID] = rc
  176. header{0, c.nextID, messageTypeRequest}.encodeXDR(c.xw)
  177. _, err := RequestMessage{repo, name, uint64(offset), uint32(size)}.encodeXDR(c.xw)
  178. if err == nil {
  179. err = c.flush()
  180. }
  181. if err != nil {
  182. c.Unlock()
  183. c.close(err)
  184. return nil, err
  185. }
  186. c.nextID = (c.nextID + 1) & 0xfff
  187. c.Unlock()
  188. res, ok := <-rc
  189. if !ok {
  190. return nil, ErrClosed
  191. }
  192. return res.val, res.err
  193. }
  194. func (c *rawConnection) ping() bool {
  195. c.Lock()
  196. if c.isClosed() {
  197. c.Unlock()
  198. return false
  199. }
  200. rc := make(chan asyncResult, 1)
  201. c.awaiting[c.nextID] = rc
  202. header{0, c.nextID, messageTypePing}.encodeXDR(c.xw)
  203. err := c.flush()
  204. if err != nil {
  205. c.Unlock()
  206. c.close(err)
  207. return false
  208. } else if c.xw.Error() != nil {
  209. c.Unlock()
  210. c.close(c.xw.Error())
  211. return false
  212. }
  213. c.nextID = (c.nextID + 1) & 0xfff
  214. c.Unlock()
  215. res, ok := <-rc
  216. return ok && res.err == nil
  217. }
  218. type flusher interface {
  219. Flush() error
  220. }
  221. func (c *rawConnection) flush() error {
  222. c.wb.Flush()
  223. if f, ok := c.writer.(flusher); ok {
  224. return f.Flush()
  225. }
  226. return nil
  227. }
  228. func (c *rawConnection) close(err error) {
  229. c.Lock()
  230. select {
  231. case <-c.closed:
  232. c.Unlock()
  233. return
  234. default:
  235. }
  236. close(c.closed)
  237. for _, ch := range c.awaiting {
  238. close(ch)
  239. }
  240. c.awaiting = nil
  241. c.writer.Close()
  242. c.reader.Close()
  243. c.Unlock()
  244. c.receiver.Close(c.id, err)
  245. }
  246. func (c *rawConnection) isClosed() bool {
  247. select {
  248. case <-c.closed:
  249. return true
  250. default:
  251. return false
  252. }
  253. }
  254. func (c *rawConnection) readerLoop() {
  255. loop:
  256. for !c.isClosed() {
  257. var hdr header
  258. hdr.decodeXDR(c.xr)
  259. if c.xr.Error() != nil {
  260. c.close(c.xr.Error())
  261. break loop
  262. }
  263. if hdr.version != 0 {
  264. c.close(fmt.Errorf("protocol error: %s: unknown message version %#x", c.id, hdr.version))
  265. break loop
  266. }
  267. switch hdr.msgType {
  268. case messageTypeIndex:
  269. var im IndexMessage
  270. im.decodeXDR(c.xr)
  271. if c.xr.Error() != nil {
  272. c.close(c.xr.Error())
  273. break loop
  274. } else {
  275. // We run this (and the corresponding one for update, below)
  276. // in a separate goroutine to avoid blocking the read loop.
  277. // There is otherwise a potential deadlock where both sides
  278. // has the model locked because it's sending a large index
  279. // update and can't receive the large index update from the
  280. // other side.
  281. go c.receiver.Index(c.id, im.Repository, im.Files)
  282. }
  283. c.Lock()
  284. c.hasRecvdIndex = true
  285. c.Unlock()
  286. case messageTypeIndexUpdate:
  287. var im IndexMessage
  288. im.decodeXDR(c.xr)
  289. if c.xr.Error() != nil {
  290. c.close(c.xr.Error())
  291. break loop
  292. } else {
  293. go c.receiver.IndexUpdate(c.id, im.Repository, im.Files)
  294. }
  295. case messageTypeRequest:
  296. var req RequestMessage
  297. req.decodeXDR(c.xr)
  298. if c.xr.Error() != nil {
  299. c.close(c.xr.Error())
  300. break loop
  301. }
  302. go c.processRequest(hdr.msgID, req)
  303. case messageTypeResponse:
  304. data := c.xr.ReadBytesMax(256 * 1024) // Sufficiently larger than max expected block size
  305. if c.xr.Error() != nil {
  306. c.close(c.xr.Error())
  307. break loop
  308. }
  309. go func(hdr header, err error) {
  310. c.Lock()
  311. rc, ok := c.awaiting[hdr.msgID]
  312. delete(c.awaiting, hdr.msgID)
  313. c.Unlock()
  314. if ok {
  315. rc <- asyncResult{data, err}
  316. close(rc)
  317. }
  318. }(hdr, c.xr.Error())
  319. case messageTypePing:
  320. c.Lock()
  321. header{0, hdr.msgID, messageTypePong}.encodeXDR(c.xw)
  322. err := c.flush()
  323. c.Unlock()
  324. if err != nil {
  325. c.close(err)
  326. break loop
  327. } else if c.xw.Error() != nil {
  328. c.close(c.xw.Error())
  329. break loop
  330. }
  331. case messageTypePong:
  332. c.RLock()
  333. rc, ok := c.awaiting[hdr.msgID]
  334. c.RUnlock()
  335. if ok {
  336. rc <- asyncResult{}
  337. close(rc)
  338. c.Lock()
  339. delete(c.awaiting, hdr.msgID)
  340. c.Unlock()
  341. }
  342. case messageTypeOptions:
  343. var om OptionsMessage
  344. om.decodeXDR(c.xr)
  345. if c.xr.Error() != nil {
  346. c.close(c.xr.Error())
  347. break loop
  348. }
  349. c.optionsLock.Lock()
  350. c.peerOptions = make(map[string]string, len(om.Options))
  351. for _, opt := range om.Options {
  352. c.peerOptions[opt.Key] = opt.Value
  353. }
  354. c.optionsLock.Unlock()
  355. if mh, rh := c.myOptions["clusterHash"], c.peerOptions["clusterHash"]; len(mh) > 0 && len(rh) > 0 && mh != rh {
  356. c.close(ErrClusterHash)
  357. break loop
  358. }
  359. default:
  360. c.close(fmt.Errorf("protocol error: %s: unknown message type %#x", c.id, hdr.msgType))
  361. break loop
  362. }
  363. }
  364. }
  365. func (c *rawConnection) processRequest(msgID int, req RequestMessage) {
  366. data, _ := c.receiver.Request(c.id, req.Repository, req.Name, int64(req.Offset), int(req.Size))
  367. c.Lock()
  368. header{0, msgID, messageTypeResponse}.encodeXDR(c.xw)
  369. _, err := c.xw.WriteBytes(data)
  370. if err == nil {
  371. err = c.flush()
  372. }
  373. c.Unlock()
  374. buffers.Put(data)
  375. if err != nil {
  376. c.close(err)
  377. }
  378. }
  379. func (c *rawConnection) pingerLoop() {
  380. var rc = make(chan bool, 1)
  381. ticker := time.Tick(pingIdleTime / 2)
  382. for {
  383. select {
  384. case <-ticker:
  385. c.RLock()
  386. ready := c.hasRecvdIndex && c.hasSentIndex
  387. c.RUnlock()
  388. if ready {
  389. go func() {
  390. rc <- c.ping()
  391. }()
  392. select {
  393. case ok := <-rc:
  394. if !ok {
  395. c.close(fmt.Errorf("ping failure"))
  396. }
  397. case <-time.After(pingTimeout):
  398. c.close(fmt.Errorf("ping timeout"))
  399. }
  400. }
  401. case <-c.closed:
  402. return
  403. }
  404. }
  405. }
  406. type Statistics struct {
  407. At time.Time
  408. InBytesTotal int
  409. OutBytesTotal int
  410. }
  411. func (c *rawConnection) Statistics() Statistics {
  412. return Statistics{
  413. At: time.Now(),
  414. InBytesTotal: int(c.xr.Tot()),
  415. OutBytesTotal: int(c.xw.Tot()),
  416. }
  417. }
  418. func (c *rawConnection) Option(key string) string {
  419. c.optionsLock.Lock()
  420. defer c.optionsLock.Unlock()
  421. return c.peerOptions[key]
  422. }