protocol.go 8.7 KB

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