server.go 12.6 KB
Newer Older
Z
zelig 已提交
1 2 3 4
package p2p

import (
	"bytes"
F
Felix Lange 已提交
5
	"crypto/ecdsa"
F
Felix Lange 已提交
6
	"crypto/rand"
7
	"errors"
Z
zelig 已提交
8 9 10 11 12
	"fmt"
	"net"
	"sync"
	"time"

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

const (
21 22
	defaultDialTimeout   = 10 * time.Second
	refreshPeersInterval = 30 * time.Second
F
Felix Lange 已提交
23

24 25 26 27 28
	// This is the maximum number of inbound connection
	// that are allowed to linger between 'accepted' and
	// 'added as peer'.
	maxAcceptConns = 50

F
Felix Lange 已提交
29 30 31 32 33 34 35 36
	// total timeout for encryption handshake and protocol
	// handshake in both directions.
	handshakeTimeout = 5 * time.Second
	// maximum time allowed for reading a complete message.
	// this is effectively the amount of time a connection can be idle.
	frameReadTimeout = 1 * time.Minute
	// maximum amount of time allowed for writing a complete message.
	frameWriteTimeout = 5 * time.Second
Z
zelig 已提交
37 38
)

39
var srvjslog = logger.NewJsonLogger()
Z
zelig 已提交
40

41 42 43 44 45
// Server manages all peer connections.
//
// The fields of Server are used as configuration parameters.
// You should set them before starting the Server. Fields may not be
// modified while the server is running.
Z
zelig 已提交
46
type Server struct {
F
Felix Lange 已提交
47 48
	// This field must be set to a valid secp256k1 private key.
	PrivateKey *ecdsa.PrivateKey
49 50 51 52 53

	// MaxPeers is the maximum number of peers that can be
	// connected. It must be greater than zero.
	MaxPeers int

F
Felix Lange 已提交
54
	// Name sets the node name of this server.
O
obscuren 已提交
55
	// Use common.MakeName to create a name that follows existing conventions.
F
Felix Lange 已提交
56 57 58 59
	Name string

	// Bootstrap nodes are used to establish connectivity
	// with the rest of the network.
60
	BootstrapNodes []*discover.Node
F
Felix Lange 已提交
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	// Protocols should contain the protocols supported
	// by the server. Matching protocols are launched for
	// each peer.
	Protocols []Protocol

	// If ListenAddr is set to a non-nil address, the server
	// will listen for incoming connections.
	//
	// If the port is zero, the operating system will pick a port. The
	// ListenAddr field will be updated with the actual address when
	// the server is started.
	ListenAddr string

	// If set to a non-nil value, the given NAT port mapper
	// is used to make the listening port available to the
	// Internet.
78
	NAT nat.Interface
79 80 81 82 83 84 85 86

	// If Dialer is set to a non-nil value, the given Dialer
	// is used to dial outbound peer connections.
	Dialer *net.Dialer

	// If NoDial is true, the server will not dial any peers.
	NoDial bool

F
Felix Lange 已提交
87
	// Hooks for testing. These are useful because we can inhibit
88
	// the whole protocol stack.
F
Felix Lange 已提交
89
	setupFunc
F
Felix Lange 已提交
90
	newPeerHook
Z
zelig 已提交
91

F
Felix Lange 已提交
92 93
	ourHandshake *protoHandshake

94 95 96
	lock    sync.RWMutex // protects running and peers
	running bool
	peers   map[discover.NodeID]*Peer
F
Felix Lange 已提交
97

98 99
	ntab     *discover.Table
	listener net.Listener
F
Felix Lange 已提交
100 101 102 103 104

	quit        chan struct{}
	loopWG      sync.WaitGroup // {dial,listen,nat}Loop
	peerWG      sync.WaitGroup // active peer goroutines
	peerConnect chan *discover.Node
Z
zelig 已提交
105 106
}

107
type setupFunc func(net.Conn, *ecdsa.PrivateKey, *protoHandshake, *discover.Node, bool) (*conn, error)
F
Felix Lange 已提交
108
type newPeerHook func(*Peer)
Z
zelig 已提交
109

110 111 112 113 114
// Peers returns all connected peers.
func (srv *Server) Peers() (peers []*Peer) {
	srv.lock.RLock()
	defer srv.lock.RUnlock()
	for _, peer := range srv.peers {
Z
zelig 已提交
115 116 117 118 119 120 121
		if peer != nil {
			peers = append(peers, peer)
		}
	}
	return
}

122 123 124
// PeerCount returns the number of connected peers.
func (srv *Server) PeerCount() int {
	srv.lock.RLock()
F
Felix Lange 已提交
125 126 127
	n := len(srv.peers)
	srv.lock.RUnlock()
	return n
Z
zelig 已提交
128 129
}

F
Felix Lange 已提交
130 131
// SuggestPeer creates a connection to the given Node if it
// is not already connected.
132 133
func (srv *Server) SuggestPeer(n *discover.Node) {
	srv.peerConnect <- n
Z
zelig 已提交
134 135
}

136 137
// Broadcast sends an RLP-encoded message to all connected peers.
// This method is deprecated and will be removed later.
138
func (srv *Server) Broadcast(protocol string, code uint64, data interface{}) error {
139 140 141 142 143 144
	return srv.BroadcastLimited(protocol, code, func(i float64) float64 { return i }, data)
}

// BroadcastsRange an RLP-encoded message to a random set of peers using the limit function to limit the amount
// of peers.
func (srv *Server) BroadcastLimited(protocol string, code uint64, limit func(float64) float64, data interface{}) error {
F
Felix Lange 已提交
145 146
	var payload []byte
	if data != nil {
147 148 149 150 151
		var err error
		payload, err = rlp.EncodeToBytes(data)
		if err != nil {
			return err
		}
F
Felix Lange 已提交
152
	}
153 154
	srv.lock.RLock()
	defer srv.lock.RUnlock()
155 156

	i, max := 0, int(limit(float64(len(srv.peers))))
157
	for _, peer := range srv.peers {
158 159 160 161
		if i >= max {
			break
		}

Z
zelig 已提交
162
		if peer != nil {
F
Felix Lange 已提交
163 164 165 166 167
			var msg = Msg{Code: code}
			if data != nil {
				msg.Payload = bytes.NewReader(payload)
				msg.Size = uint32(len(payload))
			}
168
			peer.writeProtoMsg(protocol, msg)
169
			i++
Z
zelig 已提交
170 171
		}
	}
172
	return nil
Z
zelig 已提交
173 174
}

175 176 177 178 179 180 181 182
// Start starts running the server.
// Servers can be re-used and started again after stopping.
func (srv *Server) Start() (err error) {
	srv.lock.Lock()
	defer srv.lock.Unlock()
	if srv.running {
		return errors.New("server already running")
	}
O
obscuren 已提交
183
	glog.V(logger.Info).Infoln("Starting Server")
184

185
	// static fields
F
Felix Lange 已提交
186 187
	if srv.PrivateKey == nil {
		return fmt.Errorf("Server.PrivateKey must be set to a non-nil key")
Z
zelig 已提交
188
	}
189 190 191 192
	if srv.MaxPeers <= 0 {
		return fmt.Errorf("Server.MaxPeers must be > 0")
	}
	srv.quit = make(chan struct{})
F
Felix Lange 已提交
193 194
	srv.peers = make(map[discover.NodeID]*Peer)
	srv.peerConnect = make(chan *discover.Node)
F
Felix Lange 已提交
195 196
	if srv.setupFunc == nil {
		srv.setupFunc = setupConn
197
	}
F
Felix Lange 已提交
198

199
	// node table
F
Felix Lange 已提交
200
	ntab, err := discover.ListenUDP(srv.PrivateKey, srv.ListenAddr, srv.NAT)
F
Felix Lange 已提交
201 202 203
	if err != nil {
		return err
	}
F
Felix Lange 已提交
204 205
	srv.ntab = ntab

206
	// handshake
207
	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: ntab.Self().ID}
F
Felix Lange 已提交
208 209 210 211
	for _, p := range srv.Protocols {
		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
	}

212 213 214 215 216 217
	// listen/dial
	if srv.ListenAddr != "" {
		if err := srv.startListening(); err != nil {
			return err
		}
	}
F
Felix Lange 已提交
218 219 220
	if srv.Dialer == nil {
		srv.Dialer = &net.Dialer{Timeout: defaultDialTimeout}
	}
221
	if !srv.NoDial {
F
Felix Lange 已提交
222
		srv.loopWG.Add(1)
223 224 225
		go srv.dialLoop()
	}
	if srv.NoDial && srv.ListenAddr == "" {
O
obscuren 已提交
226
		glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
227 228 229 230
	}

	srv.running = true
	return nil
Z
zelig 已提交
231 232
}

233 234 235 236 237
func (srv *Server) startListening() error {
	listener, err := net.Listen("tcp", srv.ListenAddr)
	if err != nil {
		return err
	}
238 239
	laddr := listener.Addr().(*net.TCPAddr)
	srv.ListenAddr = laddr.String()
240
	srv.listener = listener
F
Felix Lange 已提交
241
	srv.loopWG.Add(1)
242
	go srv.listenLoop()
243
	if !laddr.IP.IsLoopback() && srv.NAT != nil {
F
Felix Lange 已提交
244
		srv.loopWG.Add(1)
245 246 247 248
		go func() {
			nat.Map(srv.NAT, srv.quit, "tcp", laddr.Port, laddr.Port, "ethereum p2p")
			srv.loopWG.Done()
		}()
249 250 251 252 253 254 255 256 257 258 259
	}
	return nil
}

// Stop terminates the server and all active peer connections.
// It blocks until all active connections have been closed.
func (srv *Server) Stop() {
	srv.lock.Lock()
	if !srv.running {
		srv.lock.Unlock()
		return
Z
zelig 已提交
260
	}
261 262 263
	srv.running = false
	srv.lock.Unlock()

O
obscuren 已提交
264
	glog.V(logger.Info).Infoln("Stopping Server")
F
Felix Lange 已提交
265
	srv.ntab.Close()
266 267 268 269 270
	if srv.listener != nil {
		// this unblocks listener Accept
		srv.listener.Close()
	}
	close(srv.quit)
F
Felix Lange 已提交
271
	srv.loopWG.Wait()
272

F
Felix Lange 已提交
273 274 275
	// No new peers can be added at this point because dialLoop and
	// listenLoop are down. It is safe to call peerWG.Wait because
	// peerWG.Add is not called outside of those loops.
276
	srv.lock.Lock()
F
Felix Lange 已提交
277 278
	for _, peer := range srv.peers {
		peer.Disconnect(DiscQuitting)
279
	}
280
	srv.lock.Unlock()
F
Felix Lange 已提交
281
	srv.peerWG.Wait()
282
}
Z
zelig 已提交
283

284 285 286 287 288
// Self returns the local node's endpoint information.
func (srv *Server) Self() *discover.Node {
	return srv.ntab.Self()
}

289 290
// main loop for adding connections via listening
func (srv *Server) listenLoop() {
F
Felix Lange 已提交
291
	defer srv.loopWG.Done()
292 293 294 295 296 297 298 299 300

	// This channel acts as a semaphore limiting
	// active inbound connections that are lingering pre-handshake.
	// If all slots are taken, no further connections are accepted.
	slots := make(chan struct{}, maxAcceptConns)
	for i := 0; i < maxAcceptConns; i++ {
		slots <- struct{}{}
	}

O
obscuren 已提交
301
	glog.V(logger.Info).Infoln("Listening on", srv.listener.Addr())
Z
zelig 已提交
302
	for {
303
		<-slots
F
Felix Lange 已提交
304 305
		conn, err := srv.listener.Accept()
		if err != nil {
306
			return
Z
zelig 已提交
307
		}
O
obscuren 已提交
308
		glog.V(logger.Debug).Infof("Accepted conn %v\n", conn.RemoteAddr())
F
Felix Lange 已提交
309
		srv.peerWG.Add(1)
310 311 312 313
		go func() {
			srv.startPeer(conn, nil)
			slots <- struct{}{}
		}()
Z
zelig 已提交
314 315 316
	}
}

317
func (srv *Server) dialLoop() {
F
Felix Lange 已提交
318 319 320 321 322 323
	var (
		dialed      = make(chan *discover.Node)
		dialing     = make(map[discover.NodeID]bool)
		findresults = make(chan []*discover.Node)
		refresh     = time.NewTimer(0)
	)
F
Felix Lange 已提交
324 325 326
	defer srv.loopWG.Done()
	defer refresh.Stop()

F
Felix Lange 已提交
327 328 329 330 331 332
	// TODO: maybe limit number of active dials
	dial := func(dest *discover.Node) {
		// Don't dial nodes that would fail the checks in addPeer.
		// This is important because the connection handshake is a lot
		// of work and we'd rather avoid doing that work for peers
		// that can't be added.
333 334 335
		srv.lock.RLock()
		ok, _ := srv.checkPeer(dest.ID)
		srv.lock.RUnlock()
F
Felix Lange 已提交
336 337 338
		if !ok || dialing[dest.ID] {
			return
		}
339

F
Felix Lange 已提交
340 341 342 343 344 345 346
		dialing[dest.ID] = true
		srv.peerWG.Add(1)
		go func() {
			srv.dialNode(dest)
			dialed <- dest
		}()
	}
F
Felix Lange 已提交
347

F
Felix Lange 已提交
348
	srv.ntab.Bootstrap(srv.BootstrapNodes)
Z
zelig 已提交
349 350
	for {
		select {
F
Felix Lange 已提交
351
		case <-refresh.C:
352 353
			// Grab some nodes to connect to if we're not at capacity.
			srv.lock.RLock()
F
Felix Lange 已提交
354
			needpeers := len(srv.peers) < srv.MaxPeers
355
			srv.lock.RUnlock()
F
Felix Lange 已提交
356 357 358 359 360 361
			if needpeers {
				go func() {
					var target discover.NodeID
					rand.Read(target[:])
					findresults <- srv.ntab.Lookup(target)
				}()
F
Felix Lange 已提交
362 363 364 365
			} else {
				// Make sure we check again if the peer count falls
				// below MaxPeers.
				refresh.Reset(refreshPeersInterval)
Z
zelig 已提交
366
			}
F
Felix Lange 已提交
367 368 369 370 371 372 373
		case dest := <-srv.peerConnect:
			dial(dest)
		case dests := <-findresults:
			for _, dest := range dests {
				dial(dest)
			}
			refresh.Reset(refreshPeersInterval)
F
Felix Lange 已提交
374 375
		case dest := <-dialed:
			delete(dialing, dest.ID)
F
Felix Lange 已提交
376 377 378 379
			if len(dialing) == 0 {
				// Check again immediately after dialing all current candidates.
				refresh.Reset(0)
			}
F
Felix Lange 已提交
380 381
		case <-srv.quit:
			// TODO: maybe wait for active dials
Z
zelig 已提交
382 383 384 385 386
			return
		}
	}
}

F
Felix Lange 已提交
387
func (srv *Server) dialNode(dest *discover.Node) {
388
	addr := &net.TCPAddr{IP: dest.IP, Port: dest.TCPPort}
O
obscuren 已提交
389
	glog.V(logger.Debug).Infof("Dialing %v\n", dest)
390
	conn, err := srv.Dialer.Dial("tcp", addr.String())
Z
zelig 已提交
391
	if err != nil {
392 393 394 395
		// dialLoop adds to the wait group counter when launching
		// dialNode, so we need to count it down again. startPeer also
		// does that when an error occurs.
		srv.peerWG.Done()
O
obscuren 已提交
396
		glog.V(logger.Detail).Infof("dial error: %v", err)
F
Felix Lange 已提交
397
		return
Z
zelig 已提交
398
	}
F
Felix Lange 已提交
399
	srv.startPeer(conn, dest)
Z
zelig 已提交
400 401
}

F
Felix Lange 已提交
402
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
403
	// TODO: handle/store session token
404 405 406 407 408

	// Run setupFunc, which should create an authenticated connection
	// and run the capability exchange. Note that any early error
	// returns during that exchange need to call peerWG.Done because
	// the callers of startPeer added the peer to the wait group already.
F
Felix Lange 已提交
409
	fd.SetDeadline(time.Now().Add(handshakeTimeout))
410 411 412 413
	srv.lock.RLock()
	atcap := len(srv.peers) == srv.MaxPeers
	srv.lock.RUnlock()
	conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, atcap)
F
Felix Lange 已提交
414
	if err != nil {
F
Felix Lange 已提交
415
		fd.Close()
O
obscuren 已提交
416
		glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err)
417
		srv.peerWG.Done()
F
Felix Lange 已提交
418 419
		return
	}
F
Felix Lange 已提交
420 421 422 423
	conn.MsgReadWriter = &netWrapper{
		wrapped: conn.MsgReadWriter,
		conn:    fd, rtimeout: frameReadTimeout, wtimeout: frameWriteTimeout,
	}
F
Felix Lange 已提交
424
	p := newPeer(fd, conn, srv.Protocols)
F
Felix Lange 已提交
425
	if ok, reason := srv.addPeer(conn.ID, p); !ok {
O
obscuren 已提交
426
		glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
427
		p.politeDisconnect(reason)
428
		srv.peerWG.Done()
F
Felix Lange 已提交
429
		return
Z
zelig 已提交
430
	}
F
Felix Lange 已提交
431 432 433 434
	// The handshakes are done and it passed all checks.
	// Spawn the Peer loops.
	go srv.runPeer(p)
}
435

F
Felix Lange 已提交
436
func (srv *Server) runPeer(p *Peer) {
O
obscuren 已提交
437
	glog.V(logger.Debug).Infof("Added %v\n", p)
438
	srvjslog.LogJson(&logger.P2PConnected{
F
Felix Lange 已提交
439 440 441
		RemoteId:            p.ID().String(),
		RemoteAddress:       p.RemoteAddr().String(),
		RemoteVersionString: p.Name(),
442 443
		NumConnections:      srv.PeerCount(),
	})
F
Felix Lange 已提交
444 445 446
	if srv.newPeerHook != nil {
		srv.newPeerHook(p)
	}
447
	discreason := p.run()
F
Felix Lange 已提交
448
	srv.removePeer(p)
O
obscuren 已提交
449
	glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
450
	srvjslog.LogJson(&logger.P2PDisconnected{
F
Felix Lange 已提交
451
		RemoteId:       p.ID().String(),
452 453
		NumConnections: srv.PeerCount(),
	})
Z
zelig 已提交
454 455
}

F
Felix Lange 已提交
456
func (srv *Server) addPeer(id discover.NodeID, p *Peer) (bool, DiscReason) {
457 458
	srv.lock.Lock()
	defer srv.lock.Unlock()
F
Felix Lange 已提交
459 460 461 462 463 464 465 466
	if ok, reason := srv.checkPeer(id); !ok {
		return false, reason
	}
	srv.peers[id] = p
	return true, 0
}

func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) {
F
Felix Lange 已提交
467 468 469 470 471 472 473
	switch {
	case !srv.running:
		return false, DiscQuitting
	case len(srv.peers) >= srv.MaxPeers:
		return false, DiscTooManyPeers
	case srv.peers[id] != nil:
		return false, DiscAlreadyConnected
474
	case id == srv.Self().ID:
F
Felix Lange 已提交
475
		return false, DiscSelf
F
Felix Lange 已提交
476 477
	default:
		return true, 0
F
Felix Lange 已提交
478
	}
Z
zelig 已提交
479 480
}

F
Felix Lange 已提交
481 482
func (srv *Server) removePeer(p *Peer) {
	srv.lock.Lock()
F
Felix Lange 已提交
483
	delete(srv.peers, p.ID())
F
Felix Lange 已提交
484 485
	srv.lock.Unlock()
	srv.peerWG.Done()
F
Felix Lange 已提交
486
}