syncthing/lib/discover/discover.go

546 lines
13 KiB
Go
Raw Normal View History

2014-11-16 13:13:20 -07:00
// Copyright (C) 2014 The Syncthing Authors.
2014-09-29 12:43:32 -07:00
//
2015-03-07 13:36:35 -07:00
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
2014-06-01 13:50:14 -07:00
2013-12-15 03:43:31 -07:00
package discover
import (
"bytes"
2014-02-20 09:40:15 -07:00
"encoding/hex"
"errors"
"fmt"
2014-05-11 15:55:43 -07:00
"io"
2013-12-15 03:43:31 -07:00
"net"
"net/url"
"sort"
2013-12-15 03:43:31 -07:00
"time"
2013-12-24 09:10:49 -07:00
"github.com/syncthing/protocol"
2015-08-06 02:29:25 -07:00
"github.com/syncthing/syncthing/lib/beacon"
"github.com/syncthing/syncthing/lib/events"
"github.com/syncthing/syncthing/lib/osutil"
2015-08-06 02:29:25 -07:00
"github.com/syncthing/syncthing/lib/sync"
2013-12-15 03:43:31 -07:00
)
type Discoverer struct {
2015-09-02 09:56:44 -07:00
myID protocol.DeviceID
listenAddrs []string
relayStatusProvider relayStatusProvider
localBcastIntv time.Duration
localBcastStart time.Time
cacheLifetime time.Duration
negCacheCutoff time.Duration
beacons []beacon.Interface
2015-09-12 12:59:15 -07:00
extAddr externalAddr
2015-09-02 09:56:44 -07:00
localBcastTick <-chan time.Time
forcedBcastTick chan time.Time
registryLock sync.RWMutex
addressRegistry map[protocol.DeviceID][]CacheEntry
relayRegistry map[protocol.DeviceID][]CacheEntry
lastLookup map[protocol.DeviceID]time.Time
clients []Client
mut sync.RWMutex
2013-12-22 14:29:23 -07:00
}
2015-09-02 09:56:44 -07:00
type relayStatusProvider interface {
ClientStatus() map[string]bool
}
2015-09-12 12:59:15 -07:00
type externalAddr interface {
ExternalAddresses() []string
}
type CacheEntry struct {
Address string
Seen time.Time
}
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
)
2015-09-02 09:56:44 -07:00
func NewDiscoverer(id protocol.DeviceID, addresses []string, relayStatusProvider relayStatusProvider) *Discoverer {
return &Discoverer{
2015-09-02 09:56:44 -07:00
myID: id,
listenAddrs: addresses,
relayStatusProvider: relayStatusProvider,
localBcastIntv: 30 * time.Second,
cacheLifetime: 5 * time.Minute,
negCacheCutoff: 3 * time.Minute,
addressRegistry: make(map[protocol.DeviceID][]CacheEntry),
relayRegistry: make(map[protocol.DeviceID][]CacheEntry),
lastLookup: make(map[protocol.DeviceID]time.Time),
registryLock: sync.NewRWMutex(),
mut: sync.NewRWMutex(),
}
}
2013-12-15 03:43:31 -07:00
func (d *Discoverer) StartLocal(localPort int, localMCAddr string) {
if localPort > 0 {
d.startLocalIPv4Broadcasts(localPort)
}
if len(localMCAddr) > 0 {
d.startLocalIPv6Multicasts(localMCAddr)
}
if len(d.beacons) == 0 {
l.Warnln("Local discovery unavailable")
return
}
d.localBcastTick = time.Tick(d.localBcastIntv)
d.forcedBcastTick = make(chan time.Time)
d.localBcastStart = time.Now()
go d.sendLocalAnnouncements()
}
func (d *Discoverer) startLocalIPv4Broadcasts(localPort int) {
bb := beacon.NewBroadcast(localPort)
d.beacons = append(d.beacons, bb)
go d.recvAnnouncements(bb)
bb.ServeBackground()
}
func (d *Discoverer) startLocalIPv6Multicasts(localMCAddr string) {
mb, err := beacon.NewMulticast(localMCAddr)
if err != nil {
if debug {
l.Debugln("beacon.NewMulticast:", err)
}
l.Infoln("Local discovery over IPv6 unavailable")
return
}
d.beacons = append(d.beacons, mb)
go d.recvAnnouncements(mb)
}
2015-09-12 12:59:15 -07:00
func (d *Discoverer) StartGlobal(servers []string, extAddr externalAddr) {
d.mut.Lock()
defer d.mut.Unlock()
if len(d.clients) > 0 {
d.stopGlobal()
}
2015-09-12 12:59:15 -07:00
d.extAddr = extAddr
2015-04-22 15:54:31 -07:00
wg := sync.NewWaitGroup()
clients := make(chan Client, len(servers))
for _, address := range servers {
wg.Add(1)
go func(addr string) {
defer wg.Done()
client, err := New(addr, d)
if err != nil {
l.Infoln("Error creating discovery client", addr, err)
return
}
clients <- client
}(address)
}
wg.Wait()
close(clients)
for client := range clients {
d.clients = append(d.clients, client)
}
}
func (d *Discoverer) StopGlobal() {
d.mut.Lock()
defer d.mut.Unlock()
d.stopGlobal()
}
func (d *Discoverer) stopGlobal() {
for _, client := range d.clients {
client.Stop()
}
d.clients = []Client{}
}
func (d *Discoverer) ExtAnnounceOK() map[string]bool {
d.mut.RLock()
defer d.mut.RUnlock()
ret := make(map[string]bool)
for _, client := range d.clients {
ret[client.Address()] = client.StatusOK()
}
return ret
}
// Lookup returns a list of addresses the device is available at, as well as
// a list of relays the device is supposed to be available on sorted by the
// sum of latencies between this device, and the device in question.
func (d *Discoverer) Lookup(device protocol.DeviceID) ([]string, []string) {
d.registryLock.RLock()
cachedAddresses := d.filterCached(d.addressRegistry[device])
cachedRelays := d.filterCached(d.relayRegistry[device])
lastLookup := d.lastLookup[device]
d.registryLock.RUnlock()
2014-05-01 23:53:19 -07:00
d.mut.RLock()
defer d.mut.RUnlock()
relays := make([]string, len(cachedRelays))
for i := range cachedRelays {
relays[i] = cachedRelays[i].Address
}
if len(cachedAddresses) > 0 {
// There are cached address entries.
addrs := make([]string, len(cachedAddresses))
for i := range cachedAddresses {
addrs[i] = cachedAddresses[i].Address
}
return addrs, relays
}
if time.Since(lastLookup) < d.negCacheCutoff {
// We have recently tried to lookup this address and failed. Lets
// chill for a while.
return nil, relays
}
if len(d.clients) != 0 && time.Since(d.localBcastStart) > d.localBcastIntv {
// Only perform external lookups if we have at least one external
// server client and one local announcement interval has passed. This is
// to avoid finding local peers on their remote address at startup.
results := make(chan Announce, len(d.clients))
2015-04-22 15:54:31 -07:00
wg := sync.NewWaitGroup()
for _, client := range d.clients {
wg.Add(1)
go func(c Client) {
defer wg.Done()
ann, err := c.Lookup(device)
if err == nil {
results <- ann
}
}(client)
}
wg.Wait()
close(results)
cachedAddresses := []CacheEntry{}
availableRelays := []Relay{}
seenAddresses := make(map[string]struct{})
seenRelays := make(map[string]struct{})
now := time.Now()
var addrs []string
for result := range results {
for _, addr := range result.This.Addresses {
_, ok := seenAddresses[addr]
if !ok {
cachedAddresses = append(cachedAddresses, CacheEntry{
Address: addr,
Seen: now,
})
seenAddresses[addr] = struct{}{}
addrs = append(addrs, addr)
}
}
for _, relay := range result.This.Relays {
_, ok := seenRelays[relay.Address]
if !ok {
availableRelays = append(availableRelays, relay)
seenRelays[relay.Address] = struct{}{}
}
}
}
2015-09-02 09:56:44 -07:00
relays = RelayAddressesSortedByLatency(availableRelays)
cachedRelays := make([]CacheEntry, len(relays))
for i := range relays {
cachedRelays[i] = CacheEntry{
Address: relays[i],
Seen: now,
}
}
d.registryLock.Lock()
d.addressRegistry[device] = cachedAddresses
d.relayRegistry[device] = cachedRelays
d.lastLookup[device] = time.Now()
d.registryLock.Unlock()
return addrs, relays
2014-05-01 23:53:19 -07:00
}
return nil, relays
2014-05-01 23:53:19 -07:00
}
func (d *Discoverer) Hint(device string, addrs []string) {
resAddrs := resolveAddrs(addrs)
var id protocol.DeviceID
id.UnmarshalText([]byte(device))
d.registerDevice(nil, Device{
Addresses: resAddrs,
ID: id[:],
})
}
func (d *Discoverer) All() map[protocol.DeviceID][]CacheEntry {
d.registryLock.RLock()
devices := make(map[protocol.DeviceID][]CacheEntry, len(d.addressRegistry))
for device, addrs := range d.addressRegistry {
addrsCopy := make([]CacheEntry, len(addrs))
copy(addrsCopy, addrs)
devices[device] = addrsCopy
}
d.registryLock.RUnlock()
return devices
}
func (d *Discoverer) Announcement() Announce {
return d.announcementPkt(true)
}
func (d *Discoverer) announcementPkt(allowExternal bool) Announce {
var addrs []string
2015-09-12 12:59:15 -07:00
if allowExternal && d.extAddr != nil {
addrs = d.extAddr.ExternalAddresses()
} else {
addrs = resolveAddrs(d.listenAddrs)
}
var relayAddrs []string
2015-09-02 09:56:44 -07:00
if d.relayStatusProvider != nil {
status := d.relayStatusProvider.ClientStatus()
for uri, ok := range status {
if ok {
relayAddrs = append(relayAddrs, uri)
}
}
}
return Announce{
Magic: AnnouncementMagic,
This: Device{d.myID[:], addrs, measureLatency(relayAddrs)},
}
}
func (d *Discoverer) sendLocalAnnouncements() {
var pkt = d.announcementPkt(false)
2014-10-20 23:40:05 -07:00
msg := pkt.MustMarshalXDR()
2014-03-28 03:04:48 -07:00
for {
for _, b := range d.beacons {
b.Send(msg)
}
select {
case <-d.localBcastTick:
case <-d.forcedBcastTick:
}
}
2013-12-22 14:29:23 -07:00
}
2013-12-15 03:43:31 -07:00
func (d *Discoverer) recvAnnouncements(b beacon.Interface) {
2014-03-28 03:04:48 -07:00
for {
buf, addr := b.Recv()
2013-12-22 14:29:23 -07:00
var pkt Announce
2014-03-28 03:04:48 -07:00
err := pkt.UnmarshalXDR(buf)
2014-05-11 15:55:43 -07:00
if err != nil && err != io.EOF {
if debug {
l.Debugf("discover: Failed to unmarshal local announcement from %s:\n%s", addr, hex.Dump(buf))
}
2013-12-15 03:43:31 -07:00
continue
}
if debug {
l.Debugf("discover: Received local announcement from %s for %s", addr, protocol.DeviceIDFromBytes(pkt.This.ID))
}
var newDevice bool
if bytes.Compare(pkt.This.ID, d.myID[:]) != 0 {
newDevice = d.registerDevice(addr, pkt.This)
2014-05-11 15:55:43 -07:00
}
if newDevice {
2014-05-11 15:55:43 -07:00
select {
case d.forcedBcastTick <- time.Now():
}
2013-12-15 03:43:31 -07:00
}
}
}
func (d *Discoverer) registerDevice(addr net.Addr, device Device) bool {
var id protocol.DeviceID
copy(id[:], device.ID)
d.registryLock.Lock()
defer d.registryLock.Unlock()
current := d.filterCached(d.addressRegistry[id])
orig := current
for _, deviceAddr := range device.Addresses {
uri, err := url.Parse(deviceAddr)
if err != nil {
if debug {
l.Debugf("discover: Failed to parse address %s: %s", deviceAddr, err)
}
continue
2014-05-11 15:55:43 -07:00
}
host, port, err := net.SplitHostPort(uri.Host)
if err != nil {
if debug {
l.Debugf("discover: Failed to split address host %s: %s", deviceAddr, err)
}
continue
}
if host == "" {
uri.Host = net.JoinHostPort(addr.(*net.UDPAddr).IP.String(), port)
deviceAddr = uri.String()
}
for i := range current {
if current[i].Address == deviceAddr {
current[i].Seen = time.Now()
goto done
}
2014-05-11 15:55:43 -07:00
}
current = append(current, CacheEntry{
Address: deviceAddr,
Seen: time.Now(),
})
done:
2014-05-11 15:55:43 -07:00
}
2014-05-11 15:55:43 -07:00
if debug {
l.Debugf("discover: Caching %s addresses: %v", id, current)
2014-05-11 15:55:43 -07:00
}
d.addressRegistry[id] = current
2014-07-17 04:38:36 -07:00
if len(current) > len(orig) {
addrs := make([]string, len(current))
for i := range current {
addrs[i] = current[i].Address
}
events.Default.Log(events.DeviceDiscovered, map[string]interface{}{
2014-09-28 04:05:25 -07:00
"device": id.String(),
"addrs": addrs,
2014-07-17 04:38:36 -07:00
})
}
return len(current) > len(orig)
2014-05-11 15:55:43 -07:00
}
func (d *Discoverer) filterCached(c []CacheEntry) []CacheEntry {
for i := 0; i < len(c); {
if ago := time.Since(c[i].Seen); ago > d.cacheLifetime {
if debug {
l.Debugf("discover: Removing cached entry %s - seen %v ago", c[i].Address, ago)
}
c[i] = c[len(c)-1]
c = c[:len(c)-1]
} else {
i++
}
}
return c
}
func addrToAddr(addr *net.TCPAddr) string {
2014-05-11 15:55:43 -07:00
if len(addr.IP) == 0 || addr.IP.IsUnspecified() {
return fmt.Sprintf(":%d", addr.Port)
2014-05-11 15:55:43 -07:00
} else if bs := addr.IP.To4(); bs != nil {
return fmt.Sprintf("%s:%d", bs.String(), addr.Port)
2014-05-11 15:55:43 -07:00
} else if bs := addr.IP.To16(); bs != nil {
return fmt.Sprintf("[%s]:%d", bs.String(), addr.Port)
2014-05-11 15:55:43 -07:00
}
return ""
2014-05-11 15:55:43 -07:00
}
func resolveAddrs(addrs []string) []string {
var raddrs []string
2014-05-11 15:55:43 -07:00
for _, addrStr := range addrs {
uri, err := url.Parse(addrStr)
if err != nil {
continue
}
addrRes, err := net.ResolveTCPAddr("tcp", uri.Host)
2014-05-11 15:55:43 -07:00
if err != nil {
continue
}
addr := addrToAddr(addrRes)
if len(addr) > 0 {
uri.Host = addr
raddrs = append(raddrs, uri.String())
2014-05-11 15:55:43 -07:00
}
}
return raddrs
}
func measureLatency(relayAdresses []string) []Relay {
relays := make([]Relay, 0, len(relayAdresses))
for i, addr := range relayAdresses {
relay := Relay{
Address: addr,
Latency: int32(time.Hour / time.Millisecond),
}
relays = append(relays, relay)
2015-09-02 09:56:44 -07:00
if latency, err := osutil.GetLatencyForURL(addr); err == nil {
if debug {
l.Debugf("Relay %s latency %s", addr, latency)
}
relays[i].Latency = int32(latency / time.Millisecond)
} else {
l.Debugf("Failed to get relay %s latency %s", addr, err)
}
}
return relays
}
2015-09-02 09:56:44 -07:00
// RelayAddressesSortedByLatency adds local latency to the relay, and sorts them
// by sum latency, and returns the addresses.
2015-09-02 09:56:44 -07:00
func RelayAddressesSortedByLatency(input []Relay) []string {
relays := make([]Relay, len(input))
copy(relays, input)
for i, relay := range relays {
2015-09-02 09:56:44 -07:00
if latency, err := osutil.GetLatencyForURL(relay.Address); err == nil {
relays[i].Latency += int32(latency / time.Millisecond)
} else {
relays[i].Latency += int32(time.Hour / time.Millisecond)
}
}
sort.Sort(relayList(relays))
addresses := make([]string, 0, len(relays))
for _, relay := range relays {
addresses = append(addresses, relay.Address)
}
return addresses
}
type relayList []Relay
func (l relayList) Len() int {
return len(l)
}
func (l relayList) Less(a, b int) bool {
return l[a].Latency < l[b].Latency
}
func (l relayList) Swap(a, b int) {
l[a], l[b] = l[b], l[a]
}