-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostnameresolver.go
249 lines (219 loc) · 6.62 KB
/
hostnameresolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// CGo binding for Avahi
//
// Copyright (C) 2024 and up by Alexander Pevzner ([email protected])
// See LICENSE for license terms and conditions
//
// Hostname resolver
//
//go:build linux || freebsd
package avahi
import (
"context"
"net/netip"
"runtime/cgo"
"sync/atomic"
"unsafe"
)
// #include <stdlib.h>
// #include <avahi-client/lookup.h>
//
// void hostnameResolverCallback (
// AvahiHostNameResolver *r,
// AvahiIfIndex interface,
// AvahiProtocol proto,
// AvahiResolverEvent event,
// char *host_name,
// AvahiAddress *a,
// AvahiLookupResultFlags flags,
// void *userdata);
import "C"
// HostNameResolver resolves hostname by IP address.
type HostNameResolver struct {
clnt *Client // Owning Client
handle cgo.Handle // Handle to self
avahiResolver *C.AvahiHostNameResolver // Underlying object
queue eventqueue[*HostNameResolverEvent] // Event queue
closed atomic.Bool // Resolver is closed
}
// HostNameResolverEvent represents events, generated by the
// [HostNameResolver].
type HostNameResolverEvent struct {
Event ResolverEvent // Event code
IfIdx IfIndex // Network interface index
Proto Protocol // Network protocol
Err ErrCode // In a case of ResolverFailure
Flags LookupResultFlags // Lookup flags
Hostname string // Hostname (mirrored)
Addr netip.Addr // IP address (resolved)
}
// NewHostNameResolver creates a new [HostNameResolver].
//
// HostNameResolver resolves IP addresses by provided hostname.
// Roughly speaking, it does the work similar to gethostbyname
// using MDNS. Resolved information is reported via channel
// returned by the [HostNameResolver.Chan].
//
// This is important to understand the proper usage of the "proto"
// and "addrproto" parameters and difference between them. Please
// read the "IP4 vs IP6" section of the package Overview for technical
// details.
//
// Function parameters:
// - clnt is the pointer to [Client]
// - ifidx is the network interface index. Use [IfIndexUnspec]
// to specify all interfaces.
// - proto is the IP4/IP6 protocol, used as transport for queries. If
// set to [ProtocolUnspec], both protocols will be used.
// - hostname is the name of the host to lookup for
// - flags provide some lookup options. See [LookupFlags] for details.
//
// HostNameResolver must be closed after use with the [HostNameResolver.Close]
// function call.
func NewHostNameResolver(
clnt *Client,
ifidx IfIndex,
proto Protocol,
hostname string,
addrproto Protocol,
flags LookupFlags) (*HostNameResolver, error) {
// Initialize HostNameResolver structure
resolver := &HostNameResolver{clnt: clnt}
resolver.handle = cgo.NewHandle(resolver)
resolver.queue.init()
// Handle ClientLoopbackWorkarounds.
//
// Only if all of the following is true:
// 1. ClientLoopbackWorkarounds enabled
// 2. ifidx is loopback
// 3. hostname is localhost
// 4. LookupUseMulticast query
// 5. proto is valid
//
// If all matches, we resolve "locahost" by ourselves.
if clnt.hasFlags(ClientLoopbackWorkarounds) {
use := flags & (LookupUseWideArea | LookupUseMulticast)
if use == LookupUseMulticast && isLocalhost(hostname) {
loopback, err := Loopback()
if err != nil {
return nil, err
}
if ifidx == loopback {
// Avahi can't resolve "localhost".
// So just do its work for it.
flags := LookupResultCached |
LookupResultMulticast |
LookupResultLocal
var addr netip.Addr
switch proto {
case ProtocolIP4:
addr = loopbackIP4
// Avahi treats ProtocolUnspec as IP6
case ProtocolIP6, ProtocolUnspec:
addr = loopbackIP6
default:
return nil, ErrInvalidProtocol
}
evnt := &HostNameResolverEvent{
Event: ResolverFound,
IfIdx: ifidx,
Proto: proto,
Flags: flags,
Hostname: hostname,
Addr: addr,
}
resolver.queue.Push(evnt)
resolver.clnt.addCloser(resolver)
return resolver, nil
}
}
}
// Convert strings from Go to C
chostname := C.CString(hostname)
defer C.free(unsafe.Pointer(chostname))
// Create AvahiHostNameResolver
avahiClient := clnt.begin()
defer clnt.end()
resolver.avahiResolver = C.avahi_host_name_resolver_new(
avahiClient,
C.AvahiIfIndex(ifidx),
C.AvahiProtocol(proto),
chostname,
C.AvahiProtocol(addrproto),
C.AvahiLookupFlags(flags),
C.AvahiHostNameResolverCallback(C.hostnameResolverCallback),
unsafe.Pointer(&resolver.handle),
)
if resolver.avahiResolver == nil {
resolver.queue.Close()
resolver.handle.Delete()
return nil, clnt.errno()
}
// Register self to be closed if Client is closed
resolver.clnt.addCloser(resolver)
return resolver, nil
}
// Chan returns channel where [HostNameResolverEvent]s are sent.
func (resolver *HostNameResolver) Chan() <-chan *HostNameResolverEvent {
return resolver.queue.Chan()
}
// Get waits for the next [HostNameResolverEvent].
//
// It returns:
// - event, nil - if event available
// - nil, error - if context is canceled
// - nil, nil - if HostNameResolver was closed
func (resolver *HostNameResolver) Get(ctx context.Context) (
*HostNameResolverEvent, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case evnt := <-resolver.Chan():
return evnt, nil
}
}
// Close closes the [HostNameResolver] and releases allocated resources.
// It closes the event channel, effectively unblocking pending readers.
//
// Note, double close is safe
func (resolver *HostNameResolver) Close() {
if !resolver.closed.Swap(true) {
resolver.clnt.begin()
resolver.clnt.delCloser(resolver)
if resolver.avahiResolver != nil {
C.avahi_host_name_resolver_free(resolver.avahiResolver)
resolver.avahiResolver = nil
}
resolver.clnt.end()
resolver.queue.Close()
resolver.handle.Delete()
}
}
// hostnameResolverCallback called by AvahiHostNameResolver to
// report discovered services
//
//export hostnameResolverCallback
func hostnameResolverCallback(
r *C.AvahiHostNameResolver,
ifidx C.AvahiIfIndex,
proto C.AvahiProtocol,
event C.AvahiResolverEvent,
hostname *C.char,
caddr *C.AvahiAddress,
flags C.AvahiLookupResultFlags,
p unsafe.Pointer) {
resolver := (*cgo.Handle)(p).Value().(*HostNameResolver)
// Generate an event
ip := decodeAvahiAddress(IfIndex(ifidx), caddr)
evnt := &HostNameResolverEvent{
Event: ResolverEvent(event),
IfIdx: IfIndex(ifidx),
Proto: Protocol(proto),
Flags: LookupResultFlags(flags),
Hostname: C.GoString(hostname),
Addr: ip,
}
if evnt.Event == ResolverFailure {
evnt.Err = resolver.clnt.errno()
}
resolver.queue.Push(evnt)
}