-
Notifications
You must be signed in to change notification settings - Fork 44
/
protocolserver.go
83 lines (78 loc) · 2.1 KB
/
protocolserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package desync
import (
"context"
"fmt"
"io"
"github.com/pkg/errors"
)
// ProtocolServer serves up chunks from a local store using the casync protocol
type ProtocolServer struct {
p *Protocol
store Store
}
// NewProtocolServer returns an initialized server that can serve chunks from
// a chunk store via the casync protocol
func NewProtocolServer(r io.Reader, w io.Writer, s Store) *ProtocolServer {
return &ProtocolServer{
p: NewProtocol(r, w),
store: s,
}
}
// Serve starts the protocol server. Blocks unless an error is encountered
func (s *ProtocolServer) Serve(ctx context.Context) error {
flags, err := s.p.Initialize(CaProtocolReadableStore)
if err != nil {
return errors.Wrap(err, "failed to perform protocol handshake")
}
if flags&CaProtocolPullChunks == 0 {
return fmt.Errorf("client is not requesting chunks, provided flags %x", flags)
}
for {
// See if we're meant to stop
select {
case <-ctx.Done():
return nil
default:
}
m, err := s.p.ReadMessage()
if err != nil {
return errors.Wrap(err, "failed to read protocol message from client")
}
switch m.Type {
case CaProtocolRequest:
if len(m.Body) < 40 {
return errors.New("protocol request too small")
}
id, err := ChunkIDFromSlice(m.Body[8:40])
if err != nil {
return errors.Wrap(err, "unable to decode requested chunk id")
}
chunk, err := s.store.GetChunk(id)
if err != nil {
if _, ok := err.(ChunkMissing); ok {
if err = s.p.SendMissing(id); err != nil {
return errors.Wrap(err, "failed to send to client")
}
}
return errors.Wrap(err, "unable to read chunk from store")
}
b, err := chunk.Data()
if err != nil {
return err
}
b, err = Compressor{}.toStorage(b)
if err != nil {
return err
}
if err := s.p.SendProtocolChunk(chunk.ID(), CaProtocolChunkCompressed, b); err != nil {
return errors.Wrap(err, "failed to send chunk data")
}
case CaProtocolAbort:
return errors.New("client aborted connection")
case CaProtocolGoodbye:
return nil
default:
return fmt.Errorf("unexpected command (%x) from client", m.Type)
}
}
}