syncthing/discover/discover.go

288 lines
6.3 KiB
Go
Raw Normal View History

2013-12-15 03:43:31 -07:00
package discover
import (
2014-02-20 09:40:15 -07:00
"encoding/hex"
"errors"
2013-12-15 03:43:31 -07:00
"fmt"
2013-12-18 10:29:15 -07:00
"log"
2013-12-15 03:43:31 -07:00
"net"
2014-02-20 09:40:15 -07:00
"strings"
2013-12-15 03:43:31 -07:00
"sync"
"time"
2013-12-24 09:10:49 -07:00
"github.com/calmh/syncthing/buffers"
2014-03-28 03:04:48 -07:00
"github.com/calmh/syncthing/mc"
2013-12-15 03:43:31 -07:00
)
2013-12-22 14:29:23 -07:00
const (
2014-02-20 09:40:15 -07:00
AnnouncementPort = 21025
2013-12-22 14:29:23 -07:00
)
2013-12-15 03:43:31 -07:00
type Discoverer struct {
2014-03-28 03:04:48 -07:00
MyID string
ListenAddresses []string
BroadcastIntv time.Duration
ExtBroadcastIntv time.Duration
beacon *mc.Beacon
registry map[string][]string
registryLock sync.RWMutex
extServer string
localBroadcastTick <-chan time.Time
forcedBroadcastTick chan time.Time
2013-12-22 14:29:23 -07:00
}
2014-02-20 09:40:15 -07:00
var (
2014-02-24 05:29:30 -07:00
ErrIncorrectMagic = errors.New("incorrect magic number")
2014-02-20 09:40:15 -07:00
)
2013-12-22 15:13:51 -07:00
// We tolerate a certain amount of errors because we might be running on
2013-12-18 10:29:15 -07:00
// laptops that sleep and wake, have intermittent network connectivity, etc.
// When we hit this many errors in succession, we stop.
const maxErrors = 30
func NewDiscoverer(id string, addresses []string) (*Discoverer, error) {
2013-12-15 03:43:31 -07:00
disc := &Discoverer{
2013-12-22 14:29:23 -07:00
MyID: id,
ListenAddresses: addresses,
2013-12-22 14:29:23 -07:00
BroadcastIntv: 30 * time.Second,
ExtBroadcastIntv: 1800 * time.Second,
2014-03-28 03:04:48 -07:00
beacon: mc.NewBeacon("239.21.0.25", 21025),
registry: make(map[string][]string),
}
2013-12-15 03:43:31 -07:00
// Receive announcements sent to the local multicast group.
go disc.recvAnnouncements()
return disc, nil
}
func (d *Discoverer) StartLocal() {
d.localBroadcastTick = time.Tick(d.BroadcastIntv)
d.forcedBroadcastTick = make(chan time.Time)
go d.sendLocalAnnouncements()
}
func (d *Discoverer) StartGlobal(server string) {
d.extServer = server
go d.sendExternalAnnouncements()
}
func (d *Discoverer) announcementPkt() []byte {
var addrs []Address
for _, astr := range d.ListenAddresses {
addr, err := net.ResolveTCPAddr("tcp", astr)
if err != nil {
log.Printf("discover/announcement: %v: not announcing %s", err, astr)
continue
} else if debug {
dlog.Printf("announcing %s: %#v", astr, addr)
}
if len(addr.IP) == 0 || addr.IP.IsUnspecified() {
addrs = append(addrs, Address{Port: uint16(addr.Port)})
} else if bs := addr.IP.To4(); bs != nil {
addrs = append(addrs, Address{IP: bs, Port: uint16(addr.Port)})
} else if bs := addr.IP.To16(); bs != nil {
addrs = append(addrs, Address{IP: bs, Port: uint16(addr.Port)})
}
}
var pkt = AnnounceV2{
Magic: AnnouncementMagicV2,
NodeID: d.MyID,
Addresses: addrs,
}
return pkt.MarshalXDR()
}
func (d *Discoverer) sendLocalAnnouncements() {
var buf = d.announcementPkt()
2014-03-28 03:04:48 -07:00
for {
d.beacon.Send(buf)
select {
case <-d.localBroadcastTick:
case <-d.forcedBroadcastTick:
}
}
2013-12-22 14:29:23 -07:00
}
2013-12-15 03:43:31 -07:00
func (d *Discoverer) sendExternalAnnouncements() {
remote, err := net.ResolveUDPAddr("udp", d.extServer)
2013-12-22 14:29:23 -07:00
if err != nil {
log.Printf("discover/external: %v; no external announcements", err)
return
}
conn, err := net.ListenUDP("udp", nil)
if err != nil {
log.Printf("discover/external: %v; no external announcements", err)
return
}
var buf = d.announcementPkt()
2013-12-18 10:29:15 -07:00
var errCounter = 0
2013-12-18 10:29:15 -07:00
for errCounter < maxErrors {
2014-03-09 00:58:03 -07:00
if debug {
2014-04-16 06:06:54 -07:00
dlog.Printf("send announcement -> %v\n%s", remote, hex.Dump(buf))
}
_, err = conn.WriteTo(buf, remote)
2013-12-15 03:43:31 -07:00
if err != nil {
2013-12-22 19:35:05 -07:00
log.Println("discover/write: warning:", err)
2013-12-18 10:29:15 -07:00
errCounter++
} else {
errCounter = 0
2013-12-15 03:43:31 -07:00
}
2014-04-16 06:06:54 -07:00
if debug {
time.Sleep(1 * time.Second)
res := d.externalLookup(d.MyID)
dlog.Println("external lookup check:", res)
}
time.Sleep(d.ExtBroadcastIntv)
2013-12-15 03:43:31 -07:00
}
2014-02-24 05:24:03 -07:00
log.Printf("discover/write: %v: stopping due to too many errors: %v", remote, err)
2013-12-15 03:43:31 -07:00
}
func (d *Discoverer) recvAnnouncements() {
2014-03-28 03:04:48 -07:00
for {
buf, addr := d.beacon.Recv()
2013-12-22 14:29:23 -07:00
2014-03-09 00:58:03 -07:00
if debug {
2014-03-28 03:04:48 -07:00
dlog.Printf("read announcement:\n%s", hex.Dump(buf))
2014-02-20 09:40:15 -07:00
}
var pkt AnnounceV2
2014-03-28 03:04:48 -07:00
err := pkt.UnmarshalXDR(buf)
2014-02-20 09:40:15 -07:00
if err != nil {
2013-12-15 03:43:31 -07:00
continue
}
2014-03-09 00:58:03 -07:00
if debug {
dlog.Printf("parsed announcement: %#v", pkt)
2014-02-20 09:40:15 -07:00
}
if pkt.NodeID != d.MyID {
var addrs []string
for _, a := range pkt.Addresses {
var nodeAddr string
if len(a.IP) > 0 {
nodeAddr = fmt.Sprintf("%s:%d", ipStr(a.IP), a.Port)
} else {
ua := addr.(*net.UDPAddr)
ua.Port = int(a.Port)
nodeAddr = ua.String()
2014-02-20 09:40:15 -07:00
}
addrs = append(addrs, nodeAddr)
}
2014-03-09 00:58:03 -07:00
if debug {
dlog.Printf("register: %#v", addrs)
2013-12-15 03:43:31 -07:00
}
2014-02-20 09:40:15 -07:00
d.registryLock.Lock()
_, seen := d.registry[pkt.NodeID]
if !seen {
select {
case d.forcedBroadcastTick <- time.Now():
}
}
2014-02-20 09:40:15 -07:00
d.registry[pkt.NodeID] = addrs
2013-12-15 03:43:31 -07:00
d.registryLock.Unlock()
}
}
}
2014-02-20 09:40:15 -07:00
func (d *Discoverer) externalLookup(node string) []string {
2014-01-26 06:28:41 -07:00
extIP, err := net.ResolveUDPAddr("udp", d.extServer)
2013-12-22 19:35:05 -07:00
if err != nil {
log.Printf("discover/external: %v; no external lookup", err)
2014-02-20 09:40:15 -07:00
return nil
2013-12-22 19:35:05 -07:00
}
conn, err := net.DialUDP("udp", nil, extIP)
2013-12-22 15:13:51 -07:00
if err != nil {
log.Printf("discover/external: %v; no external lookup", err)
2014-02-20 09:40:15 -07:00
return nil
2013-12-22 14:29:23 -07:00
}
2013-12-24 09:10:49 -07:00
defer conn.Close()
2013-12-22 14:29:23 -07:00
2013-12-24 09:10:49 -07:00
err = conn.SetDeadline(time.Now().Add(5 * time.Second))
2013-12-22 19:35:05 -07:00
if err != nil {
log.Printf("discover/external: %v; no external lookup", err)
2014-02-20 09:40:15 -07:00
return nil
2013-12-22 19:35:05 -07:00
}
2014-02-20 09:40:15 -07:00
buf := QueryV2{QueryMagicV2, node}.MarshalXDR()
_, err = conn.Write(buf)
2013-12-24 09:10:49 -07:00
if err != nil {
log.Printf("discover/external: %v; no external lookup", err)
2014-02-20 09:40:15 -07:00
return nil
2013-12-24 09:10:49 -07:00
}
2014-02-20 09:40:15 -07:00
buffers.Put(buf)
2013-12-22 14:29:23 -07:00
2014-02-20 09:40:15 -07:00
buf = buffers.Get(256)
2013-12-24 09:10:49 -07:00
defer buffers.Put(buf)
2013-12-22 14:29:23 -07:00
2013-12-24 09:10:49 -07:00
n, err := conn.Read(buf)
if err != nil {
2013-12-24 09:15:21 -07:00
if err, ok := err.(net.Error); ok && err.Timeout() {
// Expected if the server doesn't know about requested node ID
2014-02-20 09:40:15 -07:00
return nil
2013-12-24 09:15:21 -07:00
}
2013-12-24 09:10:49 -07:00
log.Printf("discover/external/read: %v; no external lookup", err)
2014-02-20 09:40:15 -07:00
return nil
2013-12-24 09:10:49 -07:00
}
2013-12-22 14:29:23 -07:00
2014-03-09 00:58:03 -07:00
if debug {
dlog.Printf("read external:\n%s", hex.Dump(buf[:n]))
2014-02-20 09:40:15 -07:00
}
var pkt AnnounceV2
err = pkt.UnmarshalXDR(buf[:n])
2013-12-24 09:10:49 -07:00
if err != nil {
2014-02-20 09:40:15 -07:00
log.Println("discover/external/decode:", err)
return nil
2013-12-24 09:10:49 -07:00
}
2013-12-22 14:29:23 -07:00
2014-03-09 00:58:03 -07:00
if debug {
dlog.Printf("parsed external: %#v", pkt)
2013-12-22 14:29:23 -07:00
}
2013-12-24 09:10:49 -07:00
2014-02-20 09:40:15 -07:00
var addrs []string
for _, a := range pkt.Addresses {
var nodeAddr string
if len(a.IP) > 0 {
nodeAddr = fmt.Sprintf("%s:%d", ipStr(a.IP), a.Port)
}
addrs = append(addrs, nodeAddr)
}
return addrs
2013-12-22 14:29:23 -07:00
}
2014-02-20 09:40:15 -07:00
func (d *Discoverer) Lookup(node string) []string {
2013-12-22 15:13:51 -07:00
d.registryLock.Lock()
addr, ok := d.registry[node]
d.registryLock.Unlock()
if ok {
2014-02-20 09:40:15 -07:00
return addr
2013-12-22 15:13:51 -07:00
} else if len(d.extServer) != 0 {
// We might want to cache this, but not permanently so it needs some intelligence
return d.externalLookup(node)
2013-12-22 14:29:23 -07:00
}
2014-02-20 09:40:15 -07:00
return nil
}
func ipStr(ip []byte) string {
var f = "%d"
var s = "."
if len(ip) > 4 {
f = "%x"
s = ":"
}
var ss = make([]string, len(ip))
for i := range ip {
ss[i] = fmt.Sprintf(f, ip[i])
}
return strings.Join(ss, s)
2013-12-22 14:29:23 -07:00
}