peer.go 7.3 KB
Newer Older
Z
zelig 已提交
1 2 3
package p2p

import (
F
Felix Lange 已提交
4
	"errors"
Z
zelig 已提交
5
	"fmt"
6
	"io"
Z
zelig 已提交
7
	"net"
8 9 10 11 12
	"sort"
	"sync"
	"time"

	"github.com/ethereum/go-ethereum/logger"
13
	"github.com/ethereum/go-ethereum/logger/glog"
F
Felix Lange 已提交
14 15
	"github.com/ethereum/go-ethereum/p2p/discover"
	"github.com/ethereum/go-ethereum/rlp"
Z
zelig 已提交
16 17
)

F
Felix Lange 已提交
18
const (
19
	baseProtocolVersion    = 4
F
Felix Lange 已提交
20 21
	baseProtocolLength     = uint64(16)
	baseProtocolMaxMsgSize = 10 * 1024 * 1024
F
Felix Lange 已提交
22

23
	pingInterval = 15 * time.Second
F
Felix Lange 已提交
24
)
25

F
Felix Lange 已提交
26 27 28 29 30 31 32 33 34
const (
	// devp2p message codes
	handshakeMsg = 0x00
	discMsg      = 0x01
	pingMsg      = 0x02
	pongMsg      = 0x03
	getPeersMsg  = 0x04
	peersMsg     = 0x05
)
35

F
Felix Lange 已提交
36
// Peer represents a connected remote node.
Z
zelig 已提交
37
type Peer struct {
F
Felix Lange 已提交
38
	conn    net.Conn
F
Felix Lange 已提交
39 40
	rw      *conn
	running map[string]*protoRW
41

F
Felix Lange 已提交
42
	wg       sync.WaitGroup
43 44 45 46 47 48
	protoErr chan error
	closed   chan struct{}
	disc     chan DiscReason
}

// NewPeer returns a peer for testing purposes.
F
Felix Lange 已提交
49
func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer {
F
Felix Lange 已提交
50
	pipe, _ := net.Pipe()
F
Felix Lange 已提交
51 52 53
	msgpipe, _ := MsgPipe()
	conn := &conn{msgpipe, &protoHandshake{ID: id, Name: name, Caps: caps}}
	peer := newPeer(pipe, conn, nil)
F
Felix Lange 已提交
54
	close(peer.closed) // ensures Disconnect doesn't block
Z
zelig 已提交
55 56 57
	return peer
}

F
Felix Lange 已提交
58 59
// ID returns the node's public key.
func (p *Peer) ID() discover.NodeID {
F
Felix Lange 已提交
60
	return p.rw.ID
61 62
}

F
Felix Lange 已提交
63 64
// Name returns the node name that the remote node advertised.
func (p *Peer) Name() string {
F
Felix Lange 已提交
65
	return p.rw.Name
66 67
}

68 69
// Caps returns the capabilities (supported subprotocols) of the remote peer.
func (p *Peer) Caps() []Cap {
F
Felix Lange 已提交
70 71
	// TODO: maybe return copy
	return p.rw.Caps
72 73 74 75
}

// RemoteAddr returns the remote address of the network connection.
func (p *Peer) RemoteAddr() net.Addr {
F
Felix Lange 已提交
76
	return p.conn.RemoteAddr()
77 78 79 80
}

// LocalAddr returns the local address of the network connection.
func (p *Peer) LocalAddr() net.Addr {
F
Felix Lange 已提交
81
	return p.conn.LocalAddr()
82 83 84 85 86 87 88 89 90 91 92 93 94
}

// Disconnect terminates the peer connection with the given reason.
// It returns immediately and does not wait until the connection is closed.
func (p *Peer) Disconnect(reason DiscReason) {
	select {
	case p.disc <- reason:
	case <-p.closed:
	}
}

// String implements fmt.Stringer.
func (p *Peer) String() string {
F
Felix Lange 已提交
95
	return fmt.Sprintf("Peer %.8x %v", p.rw.ID[:], p.RemoteAddr())
F
Felix Lange 已提交
96 97
}

F
Felix Lange 已提交
98
func newPeer(fd net.Conn, conn *conn, protocols []Protocol) *Peer {
F
Felix Lange 已提交
99
	protomap := matchProtocols(protocols, conn.Caps, conn)
F
Felix Lange 已提交
100
	p := &Peer{
F
Felix Lange 已提交
101
		conn:     fd,
F
Felix Lange 已提交
102
		rw:       conn,
F
Felix Lange 已提交
103
		running:  protomap,
F
Felix Lange 已提交
104
		disc:     make(chan DiscReason),
F
Felix Lange 已提交
105
		protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop
F
Felix Lange 已提交
106
		closed:   make(chan struct{}),
Z
zelig 已提交
107
	}
F
Felix Lange 已提交
108
	return p
F
Felix Lange 已提交
109
}
110

F
Felix Lange 已提交
111
func (p *Peer) run() DiscReason {
F
Felix Lange 已提交
112 113 114 115
	readErr := make(chan error, 1)
	p.wg.Add(2)
	go p.readLoop(readErr)
	go p.pingLoop()
F
Felix Lange 已提交
116

F
Felix Lange 已提交
117
	p.startProtocols()
F
Felix Lange 已提交
118

F
Felix Lange 已提交
119
	// Wait for an error or disconnect.
F
Felix Lange 已提交
120
	var reason DiscReason
F
Felix Lange 已提交
121 122 123 124
	select {
	case err := <-readErr:
		if r, ok := err.(DiscReason); ok {
			reason = r
125 126 127
		} else {
			// Note: We rely on protocols to abort if there is a write
			// error. It might be more robust to handle them here as well.
128
			glog.V(logger.Detail).Infof("%v: Read error: %v\n", p, err)
129
			reason = DiscNetworkError
F
Felix Lange 已提交
130
		}
F
Felix Lange 已提交
131 132 133
	case err := <-p.protoErr:
		reason = discReasonForError(err)
	case reason = <-p.disc:
134 135
		p.politeDisconnect(reason)
		reason = DiscRequested
136
	}
F
Felix Lange 已提交
137

F
Felix Lange 已提交
138 139
	close(p.closed)
	p.wg.Wait()
140
	glog.V(logger.Debug).Infof("%v: Disconnected: %v\n", p, reason)
F
Felix Lange 已提交
141 142
	return reason
}
143

F
Felix Lange 已提交
144
func (p *Peer) politeDisconnect(reason DiscReason) {
145
	if reason != DiscNetworkError {
146
		SendItems(p.rw, discMsg, uint(reason))
147
	}
F
Felix Lange 已提交
148
	p.conn.Close()
149 150
}

F
Felix Lange 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
func (p *Peer) pingLoop() {
	ping := time.NewTicker(pingInterval)
	defer p.wg.Done()
	defer ping.Stop()
	for {
		select {
		case <-ping.C:
			if err := SendItems(p.rw, pingMsg); err != nil {
				p.protoErr <- err
				return
			}
		case <-p.closed:
			return
		}
	}
}

func (p *Peer) readLoop(errc chan<- error) {
	defer p.wg.Done()
F
Felix Lange 已提交
170 171 172
	for {
		msg, err := p.rw.ReadMsg()
		if err != nil {
F
Felix Lange 已提交
173 174
			errc <- err
			return
F
Felix Lange 已提交
175
		}
176
		msg.ReceivedAt = time.Now()
F
Felix Lange 已提交
177
		if err = p.handle(msg); err != nil {
F
Felix Lange 已提交
178 179
			errc <- err
			return
F
Felix Lange 已提交
180 181
		}
	}
182 183
}

F
Felix Lange 已提交
184 185 186 187
func (p *Peer) handle(msg Msg) error {
	switch {
	case msg.Code == pingMsg:
		msg.Discard()
188
		go SendItems(p.rw, pongMsg)
F
Felix Lange 已提交
189
	case msg.Code == discMsg:
190
		var reason [1]DiscReason
F
Felix Lange 已提交
191 192
		// This is the last message. We don't need to discard or
		// check errors because, the connection will be closed after it.
F
Felix Lange 已提交
193
		rlp.Decode(msg.Payload, &reason)
194
		glog.V(logger.Debug).Infof("%v: Disconnect Requested: %v\n", p, reason[0])
195
		return reason[0]
F
Felix Lange 已提交
196 197 198 199 200 201
	case msg.Code < baseProtocolLength:
		// ignore other base protocol messages
		return msg.Discard()
	default:
		// it's a subprotocol message
		proto, err := p.getProto(msg.Code)
202
		if err != nil {
F
Felix Lange 已提交
203
			return fmt.Errorf("msg code out of range: %v", msg.Code)
204
		}
F
Felix Lange 已提交
205 206 207 208 209 210
		select {
		case proto.in <- msg:
			return nil
		case <-p.closed:
			return io.EOF
		}
211
	}
F
Felix Lange 已提交
212
	return nil
213 214
}

215 216 217 218 219 220 221 222 223 224 225 226
func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
	n := 0
	for _, cap := range caps {
		for _, proto := range protocols {
			if proto.Name == cap.Name && proto.Version == cap.Version {
				n++
			}
		}
	}
	return n
}

F
Felix Lange 已提交
227 228
// matchProtocols creates structures for matching named subprotocols.
func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
229 230
	sort.Sort(capsByName(caps))
	offset := baseProtocolLength
F
Felix Lange 已提交
231
	result := make(map[string]*protoRW)
232 233
outer:
	for _, cap := range caps {
F
Felix Lange 已提交
234 235 236
		for _, proto := range protocols {
			if proto.Name == cap.Name && proto.Version == cap.Version && result[cap.Name] == nil {
				result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
237 238 239 240 241
				offset += proto.Length
				continue outer
			}
		}
	}
F
Felix Lange 已提交
242
	return result
243 244
}

F
Felix Lange 已提交
245
func (p *Peer) startProtocols() {
F
Felix Lange 已提交
246
	p.wg.Add(len(p.running))
F
Felix Lange 已提交
247 248
	for _, proto := range p.running {
		proto := proto
F
Felix Lange 已提交
249
		proto.closed = p.closed
250
		glog.V(logger.Detail).Infof("%v: Starting protocol %s/%d\n", p, proto.Name, proto.Version)
F
Felix Lange 已提交
251 252 253
		go func() {
			err := proto.Run(p, proto)
			if err == nil {
254
				glog.V(logger.Detail).Infof("%v: Protocol %s/%d returned\n", p, proto.Name, proto.Version)
F
Felix Lange 已提交
255
				err = errors.New("protocol returned")
256 257
			} else if err != io.EOF {
				glog.V(logger.Detail).Infof("%v: Protocol %s/%d error: \n", p, proto.Name, proto.Version, err)
F
Felix Lange 已提交
258
			}
F
Felix Lange 已提交
259 260
			p.protoErr <- err
			p.wg.Done()
F
Felix Lange 已提交
261
		}()
262 263 264 265 266
	}
}

// getProto finds the protocol responsible for handling
// the given message code.
F
Felix Lange 已提交
267
func (p *Peer) getProto(code uint64) (*protoRW, error) {
268
	for _, proto := range p.running {
F
Felix Lange 已提交
269
		if code >= proto.offset && code < proto.offset+proto.Length {
270 271 272 273 274 275 276
			return proto, nil
		}
	}
	return nil, newPeerError(errInvalidMsgCode, "%d", code)
}

// writeProtoMsg sends the given message on behalf of the given named protocol.
F
Felix Lange 已提交
277
// this exists because of Server.Broadcast.
278 279 280 281 282
func (p *Peer) writeProtoMsg(protoName string, msg Msg) error {
	proto, ok := p.running[protoName]
	if !ok {
		return fmt.Errorf("protocol %s not handled by peer", protoName)
	}
F
Felix Lange 已提交
283
	if msg.Code >= proto.Length {
284 285 286
		return newPeerError(errInvalidMsgCode, "code %x is out of range for protocol %q", msg.Code, protoName)
	}
	msg.Code += proto.offset
F
Felix Lange 已提交
287
	return p.rw.WriteMsg(msg)
288 289
}

F
Felix Lange 已提交
290 291 292
type protoRW struct {
	Protocol
	in     chan Msg
F
Felix Lange 已提交
293
	closed <-chan struct{}
F
Felix Lange 已提交
294 295
	offset uint64
	w      MsgWriter
296 297
}

F
Felix Lange 已提交
298 299
func (rw *protoRW) WriteMsg(msg Msg) error {
	if msg.Code >= rw.Length {
300 301 302
		return newPeerError(errInvalidMsgCode, "not handled")
	}
	msg.Code += rw.offset
F
Felix Lange 已提交
303
	return rw.w.WriteMsg(msg)
Z
zelig 已提交
304 305
}

F
Felix Lange 已提交
306
func (rw *protoRW) ReadMsg() (Msg, error) {
F
Felix Lange 已提交
307 308 309 310 311 312
	select {
	case msg := <-rw.in:
		msg.Code -= rw.offset
		return msg, nil
	case <-rw.closed:
		return Msg{}, io.EOF
313
	}
Z
zelig 已提交
314
}