syncthing/protocol/protocol.go

389 lines
7.7 KiB
Go
Raw Normal View History

2013-12-15 03:43:31 -07:00
package protocol
import (
"compress/flate"
"errors"
"io"
2013-12-21 00:15:19 -07:00
"log"
2013-12-15 03:43:31 -07:00
"sync"
"time"
2013-12-15 03:43:31 -07:00
"github.com/calmh/syncthing/buffers"
)
const (
2013-12-28 06:10:36 -07:00
messageTypeIndex = 1
messageTypeRequest = 2
messageTypeResponse = 3
messageTypePing = 4
messageTypePong = 5
messageTypeIndexUpdate = 6
2013-12-15 03:43:31 -07:00
)
type FileInfo struct {
Name string
Flags uint32
Modified int64
Blocks []BlockInfo
}
type BlockInfo struct {
Length uint32
Hash []byte
}
type Model interface {
// An index was received from the peer node
Index(nodeID string, files []FileInfo)
2013-12-28 06:10:36 -07:00
// An index update was received from the peer node
IndexUpdate(nodeID string, files []FileInfo)
2013-12-15 03:43:31 -07:00
// A request was made by the peer node
Request(nodeID, name string, offset uint64, size uint32, hash []byte) ([]byte, error)
// The peer node closed the connection
Close(nodeID string)
}
type Connection struct {
2013-12-24 09:45:16 -07:00
sync.RWMutex
2013-12-30 07:53:54 -07:00
ID string
receiver Model
reader io.Reader
mreader *marshalReader
writer io.Writer
mwriter *marshalWriter
closed bool
awaiting map[int]chan asyncResult
nextId int
peerLatency time.Duration
indexSent map[string]int64
2013-12-23 10:12:44 -07:00
lastStatistics Statistics
2013-12-30 07:53:54 -07:00
statisticsLock sync.Mutex
lastReceive time.Time
lastReceiveLock sync.RWMutex
2013-12-15 03:43:31 -07:00
}
2013-12-15 07:58:27 -07:00
var ErrClosed = errors.New("Connection closed")
type asyncResult struct {
val []byte
err error
}
const pingTimeout = 30 * time.Second
const pingIdleTime = 5 * time.Minute
2013-12-15 03:43:31 -07:00
func NewConnection(nodeID string, reader io.Reader, writer io.Writer, receiver Model) *Connection {
flrd := flate.NewReader(reader)
flwr, err := flate.NewWriter(writer, flate.BestSpeed)
if err != nil {
panic(err)
}
c := Connection{
2013-12-23 10:12:44 -07:00
receiver: receiver,
reader: flrd,
2013-12-29 18:33:57 -07:00
mreader: &marshalReader{r: flrd},
2013-12-23 10:12:44 -07:00
writer: flwr,
2013-12-29 18:33:57 -07:00
mwriter: &marshalWriter{w: flwr},
2013-12-23 10:12:44 -07:00
awaiting: make(map[int]chan asyncResult),
lastReceive: time.Now(),
ID: nodeID,
lastStatistics: Statistics{At: time.Now()},
2013-12-15 03:43:31 -07:00
}
go c.readerLoop()
go c.pingerLoop()
2013-12-15 03:43:31 -07:00
return &c
}
// Index writes the list of file information to the connected peer node
func (c *Connection) Index(idx []FileInfo) {
2013-12-24 09:45:16 -07:00
c.Lock()
2013-12-28 06:10:36 -07:00
var msgType int
2013-12-29 18:33:57 -07:00
if c.indexSent == nil {
2013-12-28 06:10:36 -07:00
// This is the first time we send an index.
msgType = messageTypeIndex
2013-12-29 18:33:57 -07:00
c.indexSent = make(map[string]int64)
2013-12-28 06:10:36 -07:00
for _, f := range idx {
2013-12-29 18:33:57 -07:00
c.indexSent[f.Name] = f.Modified
2013-12-28 06:10:36 -07:00
}
} else {
// We have sent one full index. Only send updates now.
msgType = messageTypeIndexUpdate
var diff []FileInfo
for _, f := range idx {
2013-12-29 18:33:57 -07:00
if modified, ok := c.indexSent[f.Name]; !ok || f.Modified != modified {
2013-12-28 06:10:36 -07:00
diff = append(diff, f)
2013-12-29 18:33:57 -07:00
c.indexSent[f.Name] = f.Modified
2013-12-28 06:10:36 -07:00
}
}
idx = diff
}
c.mwriter.writeHeader(header{0, c.nextId, msgType})
2013-12-15 03:43:31 -07:00
c.mwriter.writeIndex(idx)
2013-12-19 16:01:34 -07:00
err := c.flush()
c.nextId = (c.nextId + 1) & 0xfff
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
if err != nil || c.mwriter.err != nil {
c.close()
return
}
2013-12-15 03:43:31 -07:00
}
// Request returns the bytes for the specified block after fetching them from the connected peer.
func (c *Connection) Request(name string, offset uint64, size uint32, hash []byte) ([]byte, error) {
2013-12-30 13:27:20 -07:00
c.Lock()
if c.closed {
c.Unlock()
2013-12-28 08:30:02 -07:00
return nil, ErrClosed
}
2013-12-15 07:58:27 -07:00
rc := make(chan asyncResult)
2013-12-15 03:43:31 -07:00
c.awaiting[c.nextId] = rc
c.mwriter.writeHeader(header{0, c.nextId, messageTypeRequest})
c.mwriter.writeRequest(request{name, offset, size, hash})
2013-12-19 16:01:34 -07:00
if c.mwriter.err != nil {
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
c.close()
return nil, c.mwriter.err
}
err := c.flush()
if err != nil {
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
c.close()
return nil, err
}
2013-12-15 03:43:31 -07:00
c.nextId = (c.nextId + 1) & 0xfff
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-15 03:43:31 -07:00
2013-12-15 07:58:27 -07:00
res, ok := <-rc
if !ok {
return nil, ErrClosed
2013-12-15 03:43:31 -07:00
}
2013-12-15 07:58:27 -07:00
return res.val, res.err
2013-12-15 03:43:31 -07:00
}
2013-12-24 09:45:16 -07:00
func (c *Connection) Ping() (time.Duration, bool) {
2013-12-30 13:27:20 -07:00
c.Lock()
if c.closed {
c.Unlock()
2013-12-28 08:30:02 -07:00
return 0, false
}
2013-12-30 13:27:20 -07:00
rc := make(chan asyncResult, 1)
2013-12-15 03:43:31 -07:00
c.awaiting[c.nextId] = rc
2013-12-24 09:45:16 -07:00
t0 := time.Now()
2013-12-15 03:43:31 -07:00
c.mwriter.writeHeader(header{0, c.nextId, messageTypePing})
2013-12-19 16:01:34 -07:00
err := c.flush()
if err != nil || c.mwriter.err != nil {
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
c.close()
2013-12-24 09:45:16 -07:00
return 0, false
2013-12-19 16:01:34 -07:00
}
2013-12-15 03:43:31 -07:00
c.nextId = (c.nextId + 1) & 0xfff
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-15 03:43:31 -07:00
_, ok := <-rc
2013-12-24 09:45:16 -07:00
return time.Since(t0), ok
2013-12-15 03:43:31 -07:00
}
func (c *Connection) Stop() {
}
type flusher interface {
Flush() error
}
2013-12-19 16:01:34 -07:00
func (c *Connection) flush() error {
2013-12-15 03:43:31 -07:00
if f, ok := c.writer.(flusher); ok {
2013-12-19 16:01:34 -07:00
return f.Flush()
2013-12-15 03:43:31 -07:00
}
2013-12-19 16:01:34 -07:00
return nil
2013-12-15 03:43:31 -07:00
}
func (c *Connection) close() {
2013-12-24 09:45:16 -07:00
c.Lock()
2013-12-19 16:01:34 -07:00
if c.closed {
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
return
}
c.closed = true
2013-12-15 03:43:31 -07:00
for _, ch := range c.awaiting {
close(ch)
}
c.awaiting = nil
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-15 07:58:27 -07:00
2013-12-15 03:43:31 -07:00
c.receiver.Close(c.ID)
}
func (c *Connection) isClosed() bool {
2013-12-24 09:45:16 -07:00
c.RLock()
defer c.RUnlock()
2013-12-15 03:43:31 -07:00
return c.closed
}
func (c *Connection) readerLoop() {
for !c.isClosed() {
hdr := c.mreader.readHeader()
if c.mreader.err != nil {
c.close()
break
}
2013-12-21 00:06:54 -07:00
if hdr.version != 0 {
2013-12-21 00:15:19 -07:00
log.Printf("Protocol error: %s: unknown message version %#x", c.ID, hdr.version)
2013-12-21 00:06:54 -07:00
c.close()
break
}
2013-12-15 03:43:31 -07:00
c.lastReceiveLock.Lock()
c.lastReceive = time.Now()
c.lastReceiveLock.Unlock()
2013-12-15 03:43:31 -07:00
switch hdr.msgType {
case messageTypeIndex:
files := c.mreader.readIndex()
if c.mreader.err != nil {
c.close()
} else {
c.receiver.Index(c.ID, files)
}
2013-12-28 06:10:36 -07:00
case messageTypeIndexUpdate:
files := c.mreader.readIndex()
if c.mreader.err != nil {
c.close()
} else {
c.receiver.IndexUpdate(c.ID, files)
}
2013-12-15 03:43:31 -07:00
case messageTypeRequest:
c.processRequest(hdr.msgID)
case messageTypeResponse:
data := c.mreader.readResponse()
if c.mreader.err != nil {
c.close()
} else {
2013-12-30 13:27:20 -07:00
c.Lock()
2013-12-15 03:43:31 -07:00
rc, ok := c.awaiting[hdr.msgID]
2013-12-30 13:27:20 -07:00
delete(c.awaiting, hdr.msgID)
c.Unlock()
2013-12-15 03:43:31 -07:00
if ok {
2013-12-15 07:58:27 -07:00
rc <- asyncResult{data, c.mreader.err}
2013-12-15 03:43:31 -07:00
close(rc)
}
}
case messageTypePing:
2013-12-24 09:45:16 -07:00
c.Lock()
2013-12-15 03:43:31 -07:00
c.mwriter.writeUint32(encodeHeader(header{0, hdr.msgID, messageTypePong}))
2013-12-19 16:01:34 -07:00
err := c.flush()
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
if err != nil || c.mwriter.err != nil {
2013-12-18 10:29:15 -07:00
c.close()
}
2013-12-15 03:43:31 -07:00
case messageTypePong:
2013-12-24 09:45:16 -07:00
c.RLock()
2013-12-15 07:58:27 -07:00
rc, ok := c.awaiting[hdr.msgID]
2013-12-24 09:45:16 -07:00
c.RUnlock()
2013-12-15 07:58:27 -07:00
if ok {
rc <- asyncResult{}
2013-12-15 03:43:31 -07:00
close(rc)
2013-12-15 07:58:27 -07:00
2013-12-24 09:45:16 -07:00
c.Lock()
2013-12-15 03:43:31 -07:00
delete(c.awaiting, hdr.msgID)
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-15 03:43:31 -07:00
}
2013-12-21 00:15:19 -07:00
default:
log.Printf("Protocol error: %s: unknown message type %#x", c.ID, hdr.msgType)
c.close()
2013-12-15 03:43:31 -07:00
}
}
}
func (c *Connection) processRequest(msgID int) {
req := c.mreader.readRequest()
if c.mreader.err != nil {
c.close()
} else {
go func() {
data, _ := c.receiver.Request(c.ID, req.name, req.offset, req.size, req.hash)
2013-12-24 09:45:16 -07:00
c.Lock()
2013-12-15 03:43:31 -07:00
c.mwriter.writeUint32(encodeHeader(header{0, msgID, messageTypeResponse}))
c.mwriter.writeResponse(data)
2013-12-19 16:01:34 -07:00
err := c.flush()
2013-12-24 09:45:16 -07:00
c.Unlock()
2013-12-19 16:01:34 -07:00
buffers.Put(data)
if c.mwriter.err != nil || err != nil {
c.close()
}
2013-12-15 03:43:31 -07:00
}()
}
}
func (c *Connection) pingerLoop() {
2013-12-24 09:45:16 -07:00
var rc = make(chan time.Duration, 1)
for !c.isClosed() {
c.lastReceiveLock.RLock()
lr := c.lastReceive
c.lastReceiveLock.RUnlock()
if time.Since(lr) > pingIdleTime {
go func() {
2013-12-24 09:45:16 -07:00
t, ok := c.Ping()
if ok {
rc <- t
}
}()
select {
case lat := <-rc:
2013-12-24 09:45:16 -07:00
c.Lock()
c.peerLatency = (c.peerLatency + lat) / 2
2013-12-24 09:45:16 -07:00
c.Unlock()
case <-time.After(pingTimeout):
c.close()
}
}
time.Sleep(time.Second)
}
}
2013-12-23 10:12:44 -07:00
type Statistics struct {
At time.Time
InBytesTotal int
InBytesPerSec int
OutBytesTotal int
OutBytesPerSec int
Latency time.Duration
}
func (c *Connection) Statistics() Statistics {
2013-12-30 07:53:54 -07:00
c.statisticsLock.Lock()
defer c.statisticsLock.Unlock()
2013-12-23 10:12:44 -07:00
secs := time.Since(c.lastStatistics.At).Seconds()
2013-12-30 07:53:54 -07:00
rt := int(c.mreader.getTot())
wt := int(c.mwriter.getTot())
2013-12-23 10:12:44 -07:00
stats := Statistics{
At: time.Now(),
2013-12-30 07:53:54 -07:00
InBytesTotal: rt,
InBytesPerSec: int(float64(rt-c.lastStatistics.InBytesTotal) / secs),
OutBytesTotal: wt,
OutBytesPerSec: int(float64(wt-c.lastStatistics.OutBytesTotal) / secs),
2013-12-23 10:12:44 -07:00
Latency: c.peerLatency,
}
c.lastStatistics = stats
return stats
}