mdns.go 3.42 KB
Newer Older
1
2
3
package discovery

import (
Jeromy's avatar
Jeromy committed
4
	"errors"
5
6
7
8
9
10
11
	"io"
	"io/ioutil"
	golog "log"
	"net"
	"sync"
	"time"

Jeromy's avatar
Jeromy committed
12
13
	"github.com/cryptix/mdns"
	"github.com/ipfs/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
14
	pstore "github.com/ipfs/go-libp2p-peerstore"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	"github.com/ipfs/go-libp2p/p2p/host"
Jeromy's avatar
Jeromy committed
16
17
18
	logging "github.com/ipfs/go-log"
	ma "github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-multiaddr-net"
19
20
)

Jeromy's avatar
Jeromy committed
21
var log = logging.Logger("mdns")
22

23
const ServiceTag = "_ipfs-discovery._udp"
24
25
26
27
28
29
30
31

type Service interface {
	io.Closer
	RegisterNotifee(Notifee)
	UnregisterNotifee(Notifee)
}

type Notifee interface {
Jeromy's avatar
Jeromy committed
32
	HandlePeerFound(pstore.PeerInfo)
33
34
35
36
37
38
39
40
41
}

type mdnsService struct {
	server  *mdns.Server
	service *mdns.MDNSService
	host    host.Host

	lk       sync.Mutex
	notifees []Notifee
Jeromy's avatar
Jeromy committed
42
	interval time.Duration
43
44
}

Jeromy's avatar
Jeromy committed
45
46
func getDialableListenAddrs(ph host.Host) ([]*net.TCPAddr, error) {
	var out []*net.TCPAddr
Jeromy's avatar
Jeromy committed
47
48
49
50
51
52
53
	for _, addr := range ph.Addrs() {
		na, err := manet.ToNetAddr(addr)
		if err != nil {
			continue
		}
		tcp, ok := na.(*net.TCPAddr)
		if ok {
Jeromy's avatar
Jeromy committed
54
			out = append(out, tcp)
Jeromy's avatar
Jeromy committed
55
56
		}
	}
Jeromy's avatar
Jeromy committed
57
58
59
60
	if len(out) == 0 {
		return nil, errors.New("failed to find good external addr from peerhost")
	}
	return out, nil
Jeromy's avatar
Jeromy committed
61
62
63
}

func NewMdnsService(peerhost host.Host, interval time.Duration) (Service, error) {
64
65
66
67

	// TODO: dont let mdns use logging...
	golog.SetOutput(ioutil.Discard)

Jeromy's avatar
Jeromy committed
68
	var ipaddrs []net.IP
69
	port := 4001
Jeromy's avatar
Jeromy committed
70

Jeromy's avatar
Jeromy committed
71
	addrs, err := getDialableListenAddrs(peerhost)
Jeromy's avatar
Jeromy committed
72
73
74
	if err != nil {
		log.Warning(err)
	} else {
Jeromy's avatar
Jeromy committed
75
76
77
78
		port = addrs[0].Port
		for _, a := range addrs {
			ipaddrs = append(ipaddrs, a.IP)
		}
79
	}
Jeromy's avatar
Jeromy committed
80

81
82
83
	myid := peerhost.ID().Pretty()

	info := []string{myid}
Jeromy's avatar
Jeromy committed
84
	service, err := mdns.NewMDNSService(myid, ServiceTag, "", "", port, ipaddrs, info)
85
86
87
88
89
90
91
92
93
94
95
	if err != nil {
		return nil, err
	}

	// Create the mDNS server, defer shutdown
	server, err := mdns.NewServer(&mdns.Config{Zone: service})
	if err != nil {
		return nil, err
	}

	s := &mdnsService{
Jeromy's avatar
Jeromy committed
96
97
98
99
		server:   server,
		service:  service,
		host:     peerhost,
		interval: interval,
100
101
102
103
104
105
106
107
108
109
110
111
	}

	go s.pollForEntries()

	return s, nil
}

func (m *mdnsService) Close() error {
	return m.server.Shutdown()
}

func (m *mdnsService) pollForEntries() {
Jeromy's avatar
Jeromy committed
112
	ticker := time.NewTicker(m.interval)
John Steidley's avatar
John Steidley committed
113
114
115
116
117
	for range ticker.C {
		entriesCh := make(chan *mdns.ServiceEntry, 16)
		go func() {
			for entry := range entriesCh {
				m.handleEntry(entry)
118
			}
John Steidley's avatar
John Steidley committed
119
120
121
122
123
124
125
126
127
128
129
		}()

		qp := mdns.QueryParam{}
		qp.Domain = "local"
		qp.Entries = entriesCh
		qp.Service = ServiceTag
		qp.Timeout = time.Second * 5

		err := mdns.Query(&qp)
		if err != nil {
			log.Error("mdns lookup error: ", err)
130
		}
John Steidley's avatar
John Steidley committed
131
		close(entriesCh)
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
	}
}

func (m *mdnsService) handleEntry(e *mdns.ServiceEntry) {
	mpeer, err := peer.IDB58Decode(e.Info)
	if err != nil {
		log.Warning("Error parsing peer ID from mdns entry: ", err)
		return
	}

	if mpeer == m.host.ID() {
		return
	}

	maddr, err := manet.FromNetAddr(&net.TCPAddr{
		IP:   e.AddrV4,
		Port: e.Port,
	})
	if err != nil {
		log.Warning("Error parsing multiaddr from mdns entry: ", err)
		return
	}

Jeromy's avatar
Jeromy committed
155
	pi := pstore.PeerInfo{
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
		ID:    mpeer,
		Addrs: []ma.Multiaddr{maddr},
	}

	m.lk.Lock()
	for _, n := range m.notifees {
		n.HandlePeerFound(pi)
	}
	m.lk.Unlock()
}

func (m *mdnsService) RegisterNotifee(n Notifee) {
	m.lk.Lock()
	m.notifees = append(m.notifees, n)
	m.lk.Unlock()
}

func (m *mdnsService) UnregisterNotifee(n Notifee) {
	m.lk.Lock()
	found := -1
	for i, notif := range m.notifees {
		if notif == n {
			found = i
			break
		}
	}
	if found != -1 {
		m.notifees = append(m.notifees[:found], m.notifees[found+1:]...)
	}
	m.lk.Unlock()
}