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

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

	"github.com/ethereum/go-ethereum/logger"
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    = 3
F
Felix Lange 已提交
20 21
	baseProtocolLength     = uint64(16)
	baseProtocolMaxMsgSize = 10 * 1024 * 1024
F
Felix Lange 已提交
22 23

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

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

F
Felix Lange 已提交
37
// Peer represents a connected remote node.
Z
zelig 已提交
38
type Peer struct {
39 40 41 42
	// Peers have all the log methods.
	// Use them to display messages related to the peer.
	*logger.Logger

F
Felix Lange 已提交
43 44
	rw      *conn
	running map[string]*protoRW
45 46 47 48 49 50 51 52

	protoWG  sync.WaitGroup
	protoErr chan error
	closed   chan struct{}
	disc     chan DiscReason
}

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

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

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

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

// RemoteAddr returns the remote address of the network connection.
func (p *Peer) RemoteAddr() net.Addr {
F
Felix Lange 已提交
79
	return p.rw.RemoteAddr()
80 81 82 83
}

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

// 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 已提交
98
	return fmt.Sprintf("Peer %.8x %v", p.rw.ID[:], p.RemoteAddr())
F
Felix Lange 已提交
99 100
}

F
Felix Lange 已提交
101 102 103 104 105 106 107 108 109
func newPeer(conn *conn, protocols []Protocol) *Peer {
	logtag := fmt.Sprintf("Peer %.8x %v", conn.ID[:], conn.RemoteAddr())
	p := &Peer{
		Logger:   logger.NewLogger(logtag),
		rw:       conn,
		running:  matchProtocols(protocols, conn.Caps, conn),
		disc:     make(chan DiscReason),
		protoErr: make(chan error),
		closed:   make(chan struct{}),
Z
zelig 已提交
110
	}
F
Felix Lange 已提交
111
	return p
F
Felix Lange 已提交
112
}
113

F
Felix Lange 已提交
114 115
func (p *Peer) run() DiscReason {
	var readErr = make(chan error, 1)
116 117
	defer p.closeProtocols()
	defer close(p.closed)
F
Felix Lange 已提交
118

F
Felix Lange 已提交
119
	p.startProtocols()
F
Felix Lange 已提交
120
	go func() { readErr <- p.readLoop() }()
121

F
Felix Lange 已提交
122 123 124
	ping := time.NewTicker(pingInterval)
	defer ping.Stop()

F
Felix Lange 已提交
125
	// Wait for an error or disconnect.
F
Felix Lange 已提交
126
	var reason DiscReason
F
Felix Lange 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
loop:
	for {
		select {
		case <-ping.C:
			go func() {
				if err := EncodeMsg(p.rw, pingMsg, nil); err != nil {
					p.protoErr <- err
					return
				}
			}()
		case err := <-readErr:
			// We rely on protocols to abort if there is a write error. It
			// might be more robust to handle them here as well.
			p.DebugDetailf("Read error: %v\n", err)
			p.rw.Close()
			return DiscNetworkError
		case err := <-p.protoErr:
			reason = discReasonForError(err)
			break loop
		case reason = <-p.disc:
			break loop
		}
149
	}
F
Felix Lange 已提交
150 151 152 153
	p.politeDisconnect(reason)

	// Wait for readLoop. It will end because conn is now closed.
	<-readErr
F
Felix Lange 已提交
154 155 156
	p.Debugf("Disconnected: %v\n", reason)
	return reason
}
157

F
Felix Lange 已提交
158
func (p *Peer) politeDisconnect(reason DiscReason) {
159 160
	done := make(chan struct{})
	go func() {
F
Felix Lange 已提交
161
		EncodeMsg(p.rw, discMsg, uint(reason))
F
Felix Lange 已提交
162 163
		// Wait for the other side to close the connection.
		// Discard any data that they send until then.
F
Felix Lange 已提交
164
		io.Copy(ioutil.Discard, p.rw)
165 166 167 168 169 170
		close(done)
	}()
	select {
	case <-done:
	case <-time.After(disconnectGracePeriod):
	}
F
Felix Lange 已提交
171
	p.rw.Close()
172 173
}

F
Felix Lange 已提交
174 175 176 177 178 179 180 181 182 183 184
func (p *Peer) readLoop() error {
	for {
		msg, err := p.rw.ReadMsg()
		if err != nil {
			return err
		}
		if err = p.handle(msg); err != nil {
			return err
		}
	}
	return nil
185 186
}

F
Felix Lange 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
func (p *Peer) handle(msg Msg) error {
	switch {
	case msg.Code == pingMsg:
		msg.Discard()
		go EncodeMsg(p.rw, pongMsg)
	case msg.Code == discMsg:
		var reason DiscReason
		// no need to discard or for error checking, we'll close the
		// connection after this.
		rlp.Decode(msg.Payload, &reason)
		p.Disconnect(DiscRequested)
		return discRequestedError(reason)
	case msg.Code < baseProtocolLength:
		// ignore other base protocol messages
		return msg.Discard()
	default:
		// it's a subprotocol message
		proto, err := p.getProto(msg.Code)
205
		if err != nil {
F
Felix Lange 已提交
206
			return fmt.Errorf("msg code out of range: %v", msg.Code)
207 208 209
		}
		proto.in <- msg
	}
F
Felix Lange 已提交
210
	return nil
211 212
}

F
Felix Lange 已提交
213 214
// matchProtocols creates structures for matching named subprotocols.
func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
215 216
	sort.Sort(capsByName(caps))
	offset := baseProtocolLength
F
Felix Lange 已提交
217
	result := make(map[string]*protoRW)
218 219
outer:
	for _, cap := range caps {
F
Felix Lange 已提交
220 221 222
		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}
223 224 225 226 227
				offset += proto.Length
				continue outer
			}
		}
	}
F
Felix Lange 已提交
228
	return result
229 230
}

F
Felix Lange 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
func (p *Peer) startProtocols() {
	for _, proto := range p.running {
		proto := proto
		p.DebugDetailf("Starting protocol %s/%d\n", proto.Name, proto.Version)
		p.protoWG.Add(1)
		go func() {
			err := proto.Run(p, proto)
			if err == nil {
				p.DebugDetailf("Protocol %s/%d returned\n", proto.Name, proto.Version)
				err = errors.New("protocol returned")
			} else {
				p.DebugDetailf("Protocol %s/%d error: %v\n", proto.Name, proto.Version, err)
			}
			select {
			case p.protoErr <- err:
			case <-p.closed:
			}
			p.protoWG.Done()
		}()
250 251 252 253 254
	}
}

// getProto finds the protocol responsible for handling
// the given message code.
F
Felix Lange 已提交
255
func (p *Peer) getProto(code uint64) (*protoRW, error) {
256
	for _, proto := range p.running {
F
Felix Lange 已提交
257
		if code >= proto.offset && code < proto.offset+proto.Length {
258 259 260 261 262 263 264 265 266 267 268 269 270 271
			return proto, nil
		}
	}
	return nil, newPeerError(errInvalidMsgCode, "%d", code)
}

func (p *Peer) closeProtocols() {
	for _, p := range p.running {
		close(p.in)
	}
	p.protoWG.Wait()
}

// writeProtoMsg sends the given message on behalf of the given named protocol.
F
Felix Lange 已提交
272
// this exists because of Server.Broadcast.
273 274 275 276 277
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 已提交
278
	if msg.Code >= proto.Length {
279 280 281
		return newPeerError(errInvalidMsgCode, "code %x is out of range for protocol %q", msg.Code, protoName)
	}
	msg.Code += proto.offset
F
Felix Lange 已提交
282
	return p.rw.WriteMsg(msg)
283 284
}

F
Felix Lange 已提交
285 286 287 288 289 290
type protoRW struct {
	Protocol

	in     chan Msg
	offset uint64
	w      MsgWriter
291 292
}

F
Felix Lange 已提交
293 294
func (rw *protoRW) WriteMsg(msg Msg) error {
	if msg.Code >= rw.Length {
295 296 297
		return newPeerError(errInvalidMsgCode, "not handled")
	}
	msg.Code += rw.offset
F
Felix Lange 已提交
298
	return rw.w.WriteMsg(msg)
Z
zelig 已提交
299 300
}

F
Felix Lange 已提交
301
func (rw *protoRW) ReadMsg() (Msg, error) {
302 303 304 305 306 307
	msg, ok := <-rw.in
	if !ok {
		return msg, io.EOF
	}
	msg.Code -= rw.offset
	return msg, nil
Z
zelig 已提交
308
}