github.com/humaniq/go-ethereum@v1.6.8-0.20171225131628-061223a13848/p2p/discover/udp.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package discover 18 19 import ( 20 "bytes" 21 "container/list" 22 "crypto/ecdsa" 23 "errors" 24 "fmt" 25 "net" 26 "time" 27 28 "github.com/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/log" 30 "github.com/ethereum/go-ethereum/p2p/nat" 31 "github.com/ethereum/go-ethereum/p2p/netutil" 32 "github.com/ethereum/go-ethereum/rlp" 33 ) 34 35 const Version = 4 36 37 // Errors 38 var ( 39 errPacketTooSmall = errors.New("too small") 40 errBadHash = errors.New("bad hash") 41 errExpired = errors.New("expired") 42 errUnsolicitedReply = errors.New("unsolicited reply") 43 errUnknownNode = errors.New("unknown node") 44 errTimeout = errors.New("RPC timeout") 45 errClockWarp = errors.New("reply deadline too far in the future") 46 errClosed = errors.New("socket closed") 47 ) 48 49 // Timeouts 50 const ( 51 respTimeout = 500 * time.Millisecond 52 sendTimeout = 500 * time.Millisecond 53 expiration = 20 * time.Second 54 55 ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP 56 ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning 57 driftThreshold = 10 * time.Second // Allowed clock drift before warning user 58 ) 59 60 // RPC packet types 61 const ( 62 pingPacket = iota + 1 // zero is 'reserved' 63 pongPacket 64 findnodePacket 65 neighborsPacket 66 ) 67 68 // RPC request structures 69 type ( 70 ping struct { 71 Version uint 72 From, To rpcEndpoint 73 Expiration uint64 74 // Ignore additional fields (for forward compatibility). 75 Rest []rlp.RawValue `rlp:"tail"` 76 } 77 78 // pong is the reply to ping. 79 pong struct { 80 // This field should mirror the UDP envelope address 81 // of the ping packet, which provides a way to discover the 82 // the external address (after NAT). 83 To rpcEndpoint 84 85 ReplyTok []byte // This contains the hash of the ping packet. 86 Expiration uint64 // Absolute timestamp at which the packet becomes invalid. 87 // Ignore additional fields (for forward compatibility). 88 Rest []rlp.RawValue `rlp:"tail"` 89 } 90 91 // findnode is a query for nodes close to the given target. 92 findnode struct { 93 Target NodeID // doesn't need to be an actual public key 94 Expiration uint64 95 // Ignore additional fields (for forward compatibility). 96 Rest []rlp.RawValue `rlp:"tail"` 97 } 98 99 // reply to findnode 100 neighbors struct { 101 Nodes []rpcNode 102 Expiration uint64 103 // Ignore additional fields (for forward compatibility). 104 Rest []rlp.RawValue `rlp:"tail"` 105 } 106 107 rpcNode struct { 108 IP net.IP // len 4 for IPv4 or 16 for IPv6 109 UDP uint16 // for discovery protocol 110 TCP uint16 // for RLPx protocol 111 ID NodeID 112 } 113 114 rpcEndpoint struct { 115 IP net.IP // len 4 for IPv4 or 16 for IPv6 116 UDP uint16 // for discovery protocol 117 TCP uint16 // for RLPx protocol 118 } 119 ) 120 121 func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint { 122 ip := addr.IP.To4() 123 if ip == nil { 124 ip = addr.IP.To16() 125 } 126 return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort} 127 } 128 129 func (t *udp) nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) { 130 if rn.UDP <= 1024 { 131 return nil, errors.New("low port") 132 } 133 if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil { 134 return nil, err 135 } 136 if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) { 137 return nil, errors.New("not contained in netrestrict whitelist") 138 } 139 n := NewNode(rn.ID, rn.IP, rn.UDP, rn.TCP) 140 err := n.validateComplete() 141 return n, err 142 } 143 144 func nodeToRPC(n *Node) rpcNode { 145 return rpcNode{ID: n.ID, IP: n.IP, UDP: n.UDP, TCP: n.TCP} 146 } 147 148 type packet interface { 149 handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error 150 name() string 151 } 152 153 type conn interface { 154 ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) 155 WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error) 156 Close() error 157 LocalAddr() net.Addr 158 } 159 160 // udp implements the RPC protocol. 161 type udp struct { 162 conn conn 163 netrestrict *netutil.Netlist 164 priv *ecdsa.PrivateKey 165 ourEndpoint rpcEndpoint 166 167 addpending chan *pending 168 gotreply chan reply 169 170 closing chan struct{} 171 nat nat.Interface 172 173 *Table 174 } 175 176 // pending represents a pending reply. 177 // 178 // some implementations of the protocol wish to send more than one 179 // reply packet to findnode. in general, any neighbors packet cannot 180 // be matched up with a specific findnode packet. 181 // 182 // our implementation handles this by storing a callback function for 183 // each pending reply. incoming packets from a node are dispatched 184 // to all the callback functions for that node. 185 type pending struct { 186 // these fields must match in the reply. 187 from NodeID 188 ptype byte 189 190 // time when the request must complete 191 deadline time.Time 192 193 // callback is called when a matching reply arrives. if it returns 194 // true, the callback is removed from the pending reply queue. 195 // if it returns false, the reply is considered incomplete and 196 // the callback will be invoked again for the next matching reply. 197 callback func(resp interface{}) (done bool) 198 199 // errc receives nil when the callback indicates completion or an 200 // error if no further reply is received within the timeout. 201 errc chan<- error 202 } 203 204 type reply struct { 205 from NodeID 206 ptype byte 207 data interface{} 208 // loop indicates whether there was 209 // a matching request by sending on this channel. 210 matched chan<- bool 211 } 212 213 // ListenUDP returns a new table that listens for UDP packets on laddr. 214 func ListenUDP(priv *ecdsa.PrivateKey, laddr string, natm nat.Interface, nodeDBPath string, netrestrict *netutil.Netlist) (*Table, error) { 215 addr, err := net.ResolveUDPAddr("udp", laddr) 216 if err != nil { 217 return nil, err 218 } 219 conn, err := net.ListenUDP("udp", addr) 220 if err != nil { 221 return nil, err 222 } 223 tab, _, err := newUDP(priv, conn, natm, nodeDBPath, netrestrict) 224 if err != nil { 225 return nil, err 226 } 227 log.Info("UDP listener up", "self", tab.self) 228 return tab, nil 229 } 230 231 func newUDP(priv *ecdsa.PrivateKey, c conn, natm nat.Interface, nodeDBPath string, netrestrict *netutil.Netlist) (*Table, *udp, error) { 232 udp := &udp{ 233 conn: c, 234 priv: priv, 235 netrestrict: netrestrict, 236 closing: make(chan struct{}), 237 gotreply: make(chan reply), 238 addpending: make(chan *pending), 239 } 240 realaddr := c.LocalAddr().(*net.UDPAddr) 241 if natm != nil { 242 if !realaddr.IP.IsLoopback() { 243 go nat.Map(natm, udp.closing, "udp", realaddr.Port, realaddr.Port, "ethereum discovery") 244 } 245 // TODO: react to external IP changes over time. 246 if ext, err := natm.ExternalIP(); err == nil { 247 realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port} 248 } 249 } 250 // TODO: separate TCP port 251 udp.ourEndpoint = makeEndpoint(realaddr, uint16(realaddr.Port)) 252 tab, err := newTable(udp, PubkeyID(&priv.PublicKey), realaddr, nodeDBPath) 253 if err != nil { 254 return nil, nil, err 255 } 256 udp.Table = tab 257 258 go udp.loop() 259 go udp.readLoop() 260 return udp.Table, udp, nil 261 } 262 263 func (t *udp) close() { 264 close(t.closing) 265 t.conn.Close() 266 // TODO: wait for the loops to end. 267 } 268 269 // ping sends a ping message to the given node and waits for a reply. 270 func (t *udp) ping(toid NodeID, toaddr *net.UDPAddr) error { 271 // TODO: maybe check for ReplyTo field in callback to measure RTT 272 errc := t.pending(toid, pongPacket, func(interface{}) bool { return true }) 273 t.send(toaddr, pingPacket, &ping{ 274 Version: Version, 275 From: t.ourEndpoint, 276 To: makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB 277 Expiration: uint64(time.Now().Add(expiration).Unix()), 278 }) 279 return <-errc 280 } 281 282 func (t *udp) waitping(from NodeID) error { 283 return <-t.pending(from, pingPacket, func(interface{}) bool { return true }) 284 } 285 286 // findnode sends a findnode request to the given node and waits until 287 // the node has sent up to k neighbors. 288 func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) { 289 nodes := make([]*Node, 0, bucketSize) 290 nreceived := 0 291 errc := t.pending(toid, neighborsPacket, func(r interface{}) bool { 292 reply := r.(*neighbors) 293 for _, rn := range reply.Nodes { 294 nreceived++ 295 n, err := t.nodeFromRPC(toaddr, rn) 296 if err != nil { 297 log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err) 298 continue 299 } 300 nodes = append(nodes, n) 301 } 302 return nreceived >= bucketSize 303 }) 304 t.send(toaddr, findnodePacket, &findnode{ 305 Target: target, 306 Expiration: uint64(time.Now().Add(expiration).Unix()), 307 }) 308 err := <-errc 309 return nodes, err 310 } 311 312 // pending adds a reply callback to the pending reply queue. 313 // see the documentation of type pending for a detailed explanation. 314 func (t *udp) pending(id NodeID, ptype byte, callback func(interface{}) bool) <-chan error { 315 ch := make(chan error, 1) 316 p := &pending{from: id, ptype: ptype, callback: callback, errc: ch} 317 select { 318 case t.addpending <- p: 319 // loop will handle it 320 case <-t.closing: 321 ch <- errClosed 322 } 323 return ch 324 } 325 326 func (t *udp) handleReply(from NodeID, ptype byte, req packet) bool { 327 matched := make(chan bool, 1) 328 select { 329 case t.gotreply <- reply{from, ptype, req, matched}: 330 // loop will handle it 331 return <-matched 332 case <-t.closing: 333 return false 334 } 335 } 336 337 // loop runs in its own goroutine. it keeps track of 338 // the refresh timer and the pending reply queue. 339 func (t *udp) loop() { 340 var ( 341 plist = list.New() 342 timeout = time.NewTimer(0) 343 nextTimeout *pending // head of plist when timeout was last reset 344 contTimeouts = 0 // number of continuous timeouts to do NTP checks 345 ntpWarnTime = time.Unix(0, 0) 346 ) 347 <-timeout.C // ignore first timeout 348 defer timeout.Stop() 349 350 resetTimeout := func() { 351 if plist.Front() == nil || nextTimeout == plist.Front().Value { 352 return 353 } 354 // Start the timer so it fires when the next pending reply has expired. 355 now := time.Now() 356 for el := plist.Front(); el != nil; el = el.Next() { 357 nextTimeout = el.Value.(*pending) 358 if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout { 359 timeout.Reset(dist) 360 return 361 } 362 // Remove pending replies whose deadline is too far in the 363 // future. These can occur if the system clock jumped 364 // backwards after the deadline was assigned. 365 nextTimeout.errc <- errClockWarp 366 plist.Remove(el) 367 } 368 nextTimeout = nil 369 timeout.Stop() 370 } 371 372 for { 373 resetTimeout() 374 375 select { 376 case <-t.closing: 377 for el := plist.Front(); el != nil; el = el.Next() { 378 el.Value.(*pending).errc <- errClosed 379 } 380 return 381 382 case p := <-t.addpending: 383 p.deadline = time.Now().Add(respTimeout) 384 plist.PushBack(p) 385 386 case r := <-t.gotreply: 387 var matched bool 388 for el := plist.Front(); el != nil; el = el.Next() { 389 p := el.Value.(*pending) 390 if p.from == r.from && p.ptype == r.ptype { 391 matched = true 392 // Remove the matcher if its callback indicates 393 // that all replies have been received. This is 394 // required for packet types that expect multiple 395 // reply packets. 396 if p.callback(r.data) { 397 p.errc <- nil 398 plist.Remove(el) 399 } 400 // Reset the continuous timeout counter (time drift detection) 401 contTimeouts = 0 402 } 403 } 404 r.matched <- matched 405 406 case now := <-timeout.C: 407 nextTimeout = nil 408 409 // Notify and remove callbacks whose deadline is in the past. 410 for el := plist.Front(); el != nil; el = el.Next() { 411 p := el.Value.(*pending) 412 if now.After(p.deadline) || now.Equal(p.deadline) { 413 p.errc <- errTimeout 414 plist.Remove(el) 415 contTimeouts++ 416 } 417 } 418 // If we've accumulated too many timeouts, do an NTP time sync check 419 if contTimeouts > ntpFailureThreshold { 420 if time.Since(ntpWarnTime) >= ntpWarningCooldown { 421 ntpWarnTime = time.Now() 422 go checkClockDrift() 423 } 424 contTimeouts = 0 425 } 426 } 427 } 428 } 429 430 const ( 431 macSize = 256 / 8 432 sigSize = 520 / 8 433 headSize = macSize + sigSize // space of packet frame data 434 ) 435 436 var ( 437 headSpace = make([]byte, headSize) 438 439 // Neighbors replies are sent across multiple packets to 440 // stay below the 1280 byte limit. We compute the maximum number 441 // of entries by stuffing a packet until it grows too large. 442 maxNeighbors int 443 ) 444 445 func init() { 446 p := neighbors{Expiration: ^uint64(0)} 447 maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)} 448 for n := 0; ; n++ { 449 p.Nodes = append(p.Nodes, maxSizeNode) 450 size, _, err := rlp.EncodeToReader(p) 451 if err != nil { 452 // If this ever happens, it will be caught by the unit tests. 453 panic("cannot encode: " + err.Error()) 454 } 455 if headSize+size+1 >= 1280 { 456 maxNeighbors = n 457 break 458 } 459 } 460 } 461 462 func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req packet) error { 463 packet, err := encodePacket(t.priv, ptype, req) 464 if err != nil { 465 return err 466 } 467 _, err = t.conn.WriteToUDP(packet, toaddr) 468 log.Trace(">> "+req.name(), "addr", toaddr, "err", err) 469 return err 470 } 471 472 func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte, error) { 473 b := new(bytes.Buffer) 474 b.Write(headSpace) 475 b.WriteByte(ptype) 476 if err := rlp.Encode(b, req); err != nil { 477 log.Error("Can't encode discv4 packet", "err", err) 478 return nil, err 479 } 480 packet := b.Bytes() 481 sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv) 482 if err != nil { 483 log.Error("Can't sign discv4 packet", "err", err) 484 return nil, err 485 } 486 copy(packet[macSize:], sig) 487 // add the hash to the front. Note: this doesn't protect the 488 // packet in any way. Our public key will be part of this hash in 489 // The future. 490 copy(packet, crypto.Keccak256(packet[macSize:])) 491 return packet, nil 492 } 493 494 // readLoop runs in its own goroutine. it handles incoming UDP packets. 495 func (t *udp) readLoop() { 496 defer t.conn.Close() 497 // Discovery packets are defined to be no larger than 1280 bytes. 498 // Packets larger than this size will be cut at the end and treated 499 // as invalid because their hash won't match. 500 buf := make([]byte, 1280) 501 for { 502 nbytes, from, err := t.conn.ReadFromUDP(buf) 503 if netutil.IsTemporaryError(err) { 504 // Ignore temporary read errors. 505 log.Debug("Temporary UDP read error", "err", err) 506 continue 507 } else if err != nil { 508 // Shut down the loop for permament errors. 509 log.Debug("UDP read error", "err", err) 510 return 511 } 512 t.handlePacket(from, buf[:nbytes]) 513 } 514 } 515 516 func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error { 517 packet, fromID, hash, err := decodePacket(buf) 518 if err != nil { 519 log.Debug("Bad discv4 packet", "addr", from, "err", err) 520 return err 521 } 522 err = packet.handle(t, from, fromID, hash) 523 log.Trace("<< "+packet.name(), "addr", from, "err", err) 524 return err 525 } 526 527 func decodePacket(buf []byte) (packet, NodeID, []byte, error) { 528 if len(buf) < headSize+1 { 529 return nil, NodeID{}, nil, errPacketTooSmall 530 } 531 hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:] 532 shouldhash := crypto.Keccak256(buf[macSize:]) 533 if !bytes.Equal(hash, shouldhash) { 534 return nil, NodeID{}, nil, errBadHash 535 } 536 fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig) 537 if err != nil { 538 return nil, NodeID{}, hash, err 539 } 540 var req packet 541 switch ptype := sigdata[0]; ptype { 542 case pingPacket: 543 req = new(ping) 544 case pongPacket: 545 req = new(pong) 546 case findnodePacket: 547 req = new(findnode) 548 case neighborsPacket: 549 req = new(neighbors) 550 default: 551 return nil, fromID, hash, fmt.Errorf("unknown type: %d", ptype) 552 } 553 s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0) 554 err = s.Decode(req) 555 return req, fromID, hash, err 556 } 557 558 func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 559 if expired(req.Expiration) { 560 return errExpired 561 } 562 t.send(from, pongPacket, &pong{ 563 To: makeEndpoint(from, req.From.TCP), 564 ReplyTok: mac, 565 Expiration: uint64(time.Now().Add(expiration).Unix()), 566 }) 567 if !t.handleReply(fromID, pingPacket, req) { 568 // Note: we're ignoring the provided IP address right now 569 go t.bond(true, fromID, from, req.From.TCP) 570 } 571 return nil 572 } 573 574 func (req *ping) name() string { return "PING/v4" } 575 576 func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 577 if expired(req.Expiration) { 578 return errExpired 579 } 580 if !t.handleReply(fromID, pongPacket, req) { 581 return errUnsolicitedReply 582 } 583 return nil 584 } 585 586 func (req *pong) name() string { return "PONG/v4" } 587 588 func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 589 if expired(req.Expiration) { 590 return errExpired 591 } 592 if t.db.node(fromID) == nil { 593 // No bond exists, we don't process the packet. This prevents 594 // an attack vector where the discovery protocol could be used 595 // to amplify traffic in a DDOS attack. A malicious actor 596 // would send a findnode request with the IP address and UDP 597 // port of the target as the source address. The recipient of 598 // the findnode packet would then send a neighbors packet 599 // (which is a much bigger packet than findnode) to the victim. 600 return errUnknownNode 601 } 602 target := crypto.Keccak256Hash(req.Target[:]) 603 t.mutex.Lock() 604 closest := t.closest(target, bucketSize).entries 605 t.mutex.Unlock() 606 607 p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())} 608 // Send neighbors in chunks with at most maxNeighbors per packet 609 // to stay below the 1280 byte limit. 610 for i, n := range closest { 611 if netutil.CheckRelayIP(from.IP, n.IP) != nil { 612 continue 613 } 614 p.Nodes = append(p.Nodes, nodeToRPC(n)) 615 if len(p.Nodes) == maxNeighbors || i == len(closest)-1 { 616 t.send(from, neighborsPacket, &p) 617 p.Nodes = p.Nodes[:0] 618 } 619 } 620 return nil 621 } 622 623 func (req *findnode) name() string { return "FINDNODE/v4" } 624 625 func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error { 626 if expired(req.Expiration) { 627 return errExpired 628 } 629 if !t.handleReply(fromID, neighborsPacket, req) { 630 return errUnsolicitedReply 631 } 632 return nil 633 } 634 635 func (req *neighbors) name() string { return "NEIGHBORS/v4" } 636 637 func expired(ts uint64) bool { 638 return time.Unix(int64(ts), 0).Before(time.Now()) 639 }