-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
256 lines (216 loc) · 6.89 KB
/
client.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
250
251
252
253
254
255
256
// CGo binding for Avahi
//
// Copyright (C) 2024 and up by Alexander Pevzner ([email protected])
// See LICENSE for license terms and conditions
//
// Avahi Client
//
//go:build linux || freebsd
package avahi
import (
"context"
"fmt"
"runtime/cgo"
"sync/atomic"
"unsafe"
)
// #include <avahi-client/client.h>
// #include <avahi-common/thread-watch.h>
//
// void clientCallback (AvahiClient*, AvahiClientState, void*);
import "C"
// Client represents a client connection to the Avahi daemon.
//
// Client may change its state dynamically. [ClientState] changes
// reported as a series of [ClientEvent] via the channel returned
// by the [Client.Chan] call.
//
// When Client is not in use anymore, it must be closed using the
// Client.Close call to free associated resources. Closing the client
// closes its event notifications channel, effectively unblocking
// pending readers.
type Client struct {
flags ClientFlags // Client creation flags
handle cgo.Handle // Handle to self
avahiClient *C.AvahiClient // Underlying AvahiClient
threadedPoll *C.AvahiThreadedPoll // Avahi event loop
queue eventqueue[*ClientEvent] // Event queue
children closers // Children objects
closed atomic.Bool // Client is closed
}
// ClientFlags modify certain aspects of the Client behavior.
type ClientFlags int
// ClientFlags bits:
const (
// Loopback handling in Avahi is broken. In particular:
// - AvahiServiceResolver and AvahiAddressResolver
// return real host name and domain for loopback addresses
// - AvahiHostNameResolver doesn't resolve neither
// "localhost" nor "localhost.localdomain".
//
// Among other things, it breaks IPP over USB support. This
// protocol uses Avahi for local service discovery and has
// a strong requirement to use "localhost" as a hostname
// when working with local services.
//
// If Client is created with this flag, the following
// workarounds are enabled:
// - Host name and domain returned by ServiceResolver and
// AddressResolver for the loopback addresses (127.0.0.1
// and ::1) are forced to be localhost.localdomain
// - HostNameResolver resolves "localhost" and
// "localhost.localdomain" as 127.0.0.1.
ClientLoopbackWorkarounds ClientFlags = 1 << iota
)
// ClientEvent represents events, generated by the [Client].
type ClientEvent struct {
State ClientState // New client state
Err ErrCode // Only for ClientStateFailure
}
// NewClient creates a new [Client].
func NewClient(flags ClientFlags) (*Client, error) {
// Create Avahi event loop. We use individual event loop for
// each client to simplify things.
threadedPoll := C.avahi_threaded_poll_new()
if threadedPoll == nil {
return nil, ErrNoMemory
}
// Create Avahi client
clnt := &Client{flags: flags, threadedPoll: threadedPoll}
clnt.handle = cgo.NewHandle(clnt)
clnt.queue.init()
clnt.children.init()
var rc C.int
clnt.avahiClient = C.avahi_client_new(
C.avahi_threaded_poll_get(threadedPoll),
C.AVAHI_CLIENT_NO_FAIL,
C.AvahiClientCallback(C.clientCallback),
unsafe.Pointer(&clnt.handle),
&rc)
if clnt.avahiClient == nil {
C.avahi_threaded_poll_free(threadedPoll)
clnt.queue.Close()
clnt.handle.Delete()
return nil, fmt.Errorf("avahi: error %d", rc)
}
// And now we finally ready to let AvahiClient run.
C.avahi_threaded_poll_start(threadedPoll)
return clnt, nil
}
// Close closes a [Client].
//
// Note, double close is safe.
func (clnt *Client) Close() {
if !clnt.closed.Swap(true) {
C.avahi_threaded_poll_stop(clnt.threadedPoll)
clnt.children.close()
C.avahi_client_free(clnt.avahiClient)
clnt.avahiClient = nil
C.avahi_threaded_poll_free(clnt.threadedPoll)
clnt.threadedPoll = nil
clnt.queue.Close()
clnt.handle.Delete()
}
}
// addCloser adds a child object that will be closed when client is closed
func (clnt *Client) addCloser(obj closer) {
clnt.children.add(obj)
}
// delCloser deletes a child object
func (clnt *Client) delCloser(obj closer) {
clnt.children.del(obj)
}
// Chan returns a channel where [ClientState] change events
// are delivered.
//
// Client.Close closes the sending side of this channel, effectively
// unblocking pending receivers.
func (clnt *Client) Chan() <-chan *ClientEvent {
return clnt.queue.Chan()
}
// Get waits for the next [ClientEvent].
//
// It returns:
// - event, nil - on success
// - nil, error - if context is canceled
// - nil, nil - if Client was closed
func (clnt *Client) Get(ctx context.Context) (*ClientEvent, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case state := <-clnt.Chan():
return state, nil
}
}
// GetVersionString returns avahi-daemon version string
func (clnt *Client) GetVersionString() string {
clnt.begin()
defer clnt.end()
s := C.avahi_client_get_version_string(clnt.avahiClient)
return C.GoString(s)
}
// GetHostName returns host name (e.g., "name")
func (clnt *Client) GetHostName() string {
clnt.begin()
defer clnt.end()
s := C.avahi_client_get_host_name(clnt.avahiClient)
return C.GoString(s)
}
// GetDomainName returns domain name (e.g., "local")
func (clnt *Client) GetDomainName() string {
clnt.begin()
defer clnt.end()
s := C.avahi_client_get_domain_name(clnt.avahiClient)
return C.GoString(s)
}
// GetHostFQDN returns FQDN host name (e.g., "name.local")
func (clnt *Client) GetHostFQDN() string {
clnt.begin()
defer clnt.end()
s := C.avahi_client_get_host_name_fqdn(clnt.avahiClient)
return C.GoString(s)
}
// begin locks the Client event loop and returns *C.AvahiClient.
//
// All operations that affects underlying AvahiClient must begin
// with this call.
//
// Caller MUST call Client.end after end of operation.
func (clnt *Client) begin() *C.AvahiClient {
C.avahi_threaded_poll_lock(clnt.threadedPoll)
return clnt.avahiClient
}
// end must be called after completion of any operation, started
// with Client.begin.
func (clnt *Client) end() {
C.avahi_threaded_poll_unlock(clnt.threadedPoll)
}
// hasFlags checks if some of the specified flags were used during
// the Client creation.
func (clnt *Client) hasFlags(flags ClientFlags) bool {
return clnt.flags&flags != 0
}
// errno returns an error code of latest failed operation.
func (clnt *Client) errno() ErrCode {
return ErrCode(C.avahi_client_errno(clnt.avahiClient))
}
// clientCallback called by AvahiClient to report client state change
//
//export clientCallback
func clientCallback(avahiClient *C.AvahiClient,
s C.AvahiClientState, p unsafe.Pointer) {
clntHandle := *(*cgo.Handle)(p)
clnt := clntHandle.Value().(*Client)
state := ClientState(s)
evnt := &ClientEvent{State: state}
if state == ClientStateFailure {
// The very first callback may come too early, even
// before C.avahi_client_new returns, so Client.avahiClient
// may be not yet initialized at that time...
evnt.Err = ErrFailure
if clnt.avahiClient != nil {
evnt.Err = clnt.errno()
}
}
clnt.queue.Push(evnt)
}