forked from OpenPrinting/ipp-usb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dnssd_avahi.go
430 lines (359 loc) · 9.68 KB
/
dnssd_avahi.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// +build linux
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* DNS-SD publisher: Avahi-based system-dependent part
*/
package main
// #cgo pkg-config: avahi-client
//
// #include <stdlib.h>
// #include <avahi-client/publish.h>
// #include <avahi-common/error.h>
// #include <avahi-common/thread-watch.h>
// #include <avahi-common/watch.h>
//
// void avahiClientCallback(AvahiClient*, AvahiClientState, void*);
// void avahiEntryGroupCallback(AvahiEntryGroup*, AvahiEntryGroupState, void*);
import "C"
import (
"bytes"
"errors"
"fmt"
"net/url"
"sync"
"unsafe"
)
var (
avahiInitLock sync.Mutex
avahiThreadedPoll *C.AvahiThreadedPoll
avahiClientMap = make(map[*C.AvahiClient]*dnssdSysdep)
avahiEgroupMap = make(map[*C.AvahiEntryGroup]*dnssdSysdep)
)
// dnssdSysdep represents a system-dependent DNS-SD advertiser
type dnssdSysdep struct {
log *Logger // Device's logger
instance string // Service Instance Name
fqdn string // Host's fully-qualified domain name
client *C.AvahiClient // Avahi client
egroup *C.AvahiEntryGroup // Avahi entry group
statusChan chan DNSSdStatus // Status notifications channel
}
// dnssdSysdepErr implements error interface on a top of
// Avahi error codes
type dnssdSysdepErr C.int
// Error returns error string for the dnssdSysdepErr
func (err dnssdSysdepErr) Error() string {
return "Avahi error: " + C.GoString(C.avahi_strerror(C.int(err)))
}
// newDnssdSysdep creates new dnssdSysdep instance
func newDnssdSysdep(log *Logger, instance string,
services DNSSdServices) *dnssdSysdep {
log.Debug(' ', "DNS-SD: %s: trying", instance)
var err error
var poll *C.AvahiPoll
var rc C.int
var proto, iface int
sysdep := &dnssdSysdep{
log: log,
instance: instance,
statusChan: make(chan DNSSdStatus, 10),
}
// Obtain index of loopback interface
loopback, err := Loopback()
if err != nil {
goto ERROR // Very unlikely to happen
}
// Obtain AvahiPoll
poll, err = avahiGetPoll()
if err != nil {
goto ERROR
}
// Synchronize with Avahi thread
avahiThreadLock()
defer avahiThreadUnlock()
// Create Avahi client
sysdep.client = C.avahi_client_new(
poll,
C.AVAHI_CLIENT_NO_FAIL,
C.AvahiClientCallback(C.avahiClientCallback),
nil,
&rc,
)
if sysdep.client == nil {
goto AVAHI_ERROR
}
avahiClientMap[sysdep.client] = sysdep
sysdep.fqdn = C.GoString(C.avahi_client_get_host_name_fqdn(sysdep.client))
sysdep.log.Debug(' ', "DNS-SD: FQDN: %q", sysdep.fqdn)
// Create entry group
sysdep.egroup = C.avahi_entry_group_new(
sysdep.client,
C.AvahiEntryGroupCallback(C.avahiEntryGroupCallback),
nil,
)
if sysdep.egroup == nil {
rc = C.avahi_client_errno(sysdep.client)
goto AVAHI_ERROR
}
avahiEgroupMap[sysdep.egroup] = sysdep
// Compute iface and proto, adjust fqdn
iface = C.AVAHI_IF_UNSPEC
if Conf.LoopbackOnly {
iface = loopback
old := sysdep.fqdn
sysdep.fqdn = "localhost"
sysdep.log.Debug(' ', "DNS-SD: FQDN: %q->%q", old, sysdep.fqdn)
}
proto = C.AVAHI_PROTO_UNSPEC
if !Conf.IPV6Enable {
proto = C.AVAHI_PROTO_INET
}
// Populate entry group
for _, svc := range services {
// Prepare TXT record
var c_txt *C.AvahiStringList
c_txt, err = sysdep.avahiTxtRecord(svc.Port, svc.Txt)
if err != nil {
goto ERROR
}
// Prepare C strings for service instance and type
c_svc_type := C.CString(svc.Type)
var c_instance *C.char
if svc.Instance != "" {
c_instance = C.CString(svc.Instance)
} else {
c_instance = C.CString(instance)
}
// Handle loopback-only mode
iface_in_use := iface
if svc.Loopback {
iface_in_use = loopback
}
// Register service type
rc = C.avahi_entry_group_add_service_strlst(
sysdep.egroup,
C.AvahiIfIndex(iface_in_use),
C.AvahiProtocol(proto),
0,
c_instance,
c_svc_type,
nil, // Domain
nil, // Host
C.uint16_t(svc.Port),
c_txt,
)
// Register subtypes, if any
for _, subtype := range svc.SubTypes {
if rc != C.AVAHI_OK {
break
}
sysdep.log.Debug(' ', "DNS-SD: +subtype: %q", subtype)
c_subtype := C.CString(subtype)
rc = C.avahi_entry_group_add_service_subtype(
sysdep.egroup,
C.AvahiIfIndex(iface_in_use),
C.AvahiProtocol(proto),
0,
c_instance,
c_svc_type,
nil,
c_subtype,
)
C.free(unsafe.Pointer(c_subtype))
}
// Release C memory
C.free(unsafe.Pointer(c_instance))
C.free(unsafe.Pointer(c_svc_type))
C.avahi_string_list_free(c_txt)
// Check for Avahi error
if rc != C.AVAHI_OK {
goto AVAHI_ERROR
}
}
// Commit changes
rc = C.avahi_entry_group_commit(sysdep.egroup)
if rc != C.AVAHI_OK {
goto AVAHI_ERROR
}
// Create and return dnssdSysdep
return sysdep
// Error: cleanup and exit
AVAHI_ERROR:
err = dnssdSysdepErr(rc)
ERROR:
// Raise an error event
sysdep.log.Error(' ', "DNS-SD: %s: %s", sysdep.instance, err)
sysdep.haltLocked()
if err == dnssdSysdepErr(C.AVAHI_ERR_COLLISION) {
sysdep.notify(DNSSdCollision)
} else {
sysdep.notify(DNSSdFailure)
}
return sysdep
}
// Halt dnssdSysdep
//
// It cancel all activity related to the dnssdSysdep instance,
// but sysdep.Chan() remains valid, though no notifications
// will be pushed there anymore
func (sysdep *dnssdSysdep) Halt() {
avahiThreadLock()
sysdep.haltLocked()
avahiThreadUnlock()
}
// Get status change notification channel
func (sysdep *dnssdSysdep) Chan() <-chan DNSSdStatus {
return sysdep.statusChan
}
// Halt dnssdSysdep -- internal version
//
// Must be called under avahiThreadLock
// Can be used with semi-constructed dnssdSysdep
func (sysdep *dnssdSysdep) haltLocked() {
// Free all Avahi stuff
if sysdep.egroup != nil {
C.avahi_entry_group_free(sysdep.egroup)
delete(avahiEgroupMap, sysdep.egroup)
sysdep.egroup = nil
}
if sysdep.client != nil {
C.avahi_client_free(sysdep.client)
delete(avahiClientMap, sysdep.client)
sysdep.client = nil
}
// Drain status channel
for len(sysdep.statusChan) > 0 {
<-sysdep.statusChan
}
}
// Push status change notification
func (sysdep *dnssdSysdep) notify(status DNSSdStatus) {
sysdep.statusChan <- status
}
// avahiTxtRecord converts DNSSdTxtRecord to AvahiStringList
func (sysdep *dnssdSysdep) avahiTxtRecord(port int, txt DNSSdTxtRecord) (
*C.AvahiStringList, error) {
var buf bytes.Buffer
var list, prev *C.AvahiStringList
for _, t := range txt {
buf.Reset()
buf.WriteString(t.Key)
buf.WriteByte('=')
if !t.URL || sysdep.fqdn == "" {
buf.WriteString(t.Value)
} else {
value := t.Value
if parsed, err := url.Parse(value); err == nil && parsed.IsAbs() {
parsed.Host = sysdep.fqdn
if port != 0 {
parsed.Host += fmt.Sprintf(":%d", port)
}
value = parsed.String()
}
buf.WriteString(value)
}
b := buf.Bytes()
prev, list = list, C.avahi_string_list_add_arbitrary(
list,
(*C.uint8_t)(unsafe.Pointer(&b[0])),
C.size_t(len(b)),
)
if list == nil {
C.avahi_string_list_free(prev)
return nil, ErrNoMemory
}
}
return C.avahi_string_list_reverse(list), nil
}
// avahiClientCallback called by Avahi client to notify us about
// client state change
//
//export avahiClientCallback
func avahiClientCallback(client *C.AvahiClient,
state C.AvahiClientState, _ unsafe.Pointer) {
sysdep := avahiClientMap[client]
if sysdep == nil {
return
}
status := DNSSdNoStatus
event := ""
switch state {
case C.AVAHI_CLIENT_S_REGISTERING:
event = "AVAHI_CLIENT_S_REGISTERING"
case C.AVAHI_CLIENT_S_RUNNING:
event = "AVAHI_CLIENT_S_RUNNING"
case C.AVAHI_CLIENT_S_COLLISION:
// This is host name collision. We can't recover
// it here, so lets consider it as DNSSdFailure
event = "AVAHI_CLIENT_S_COLLISION"
status = DNSSdFailure
case C.AVAHI_CLIENT_FAILURE:
event = "AVAHI_CLIENT_FAILURE"
status = DNSSdFailure
case C.AVAHI_CLIENT_CONNECTING:
event = "AVAHI_CLIENT_CONNECTING"
default:
event = fmt.Sprintf("Unknown event %d", state)
}
sysdep.log.Debug(' ', "DNS-SD: %s: %s", sysdep.instance, event)
if status != DNSSdNoStatus {
sysdep.notify(status)
}
}
// avahiEntryGroupCallback called by Avahi client to notify us about
// entry group state change
//
//export avahiEntryGroupCallback
func avahiEntryGroupCallback(egroup *C.AvahiEntryGroup,
state C.AvahiEntryGroupState, _ unsafe.Pointer) {
sysdep := avahiEgroupMap[egroup]
if sysdep == nil {
return
}
status := DNSSdNoStatus
event := ""
switch state {
case C.AVAHI_ENTRY_GROUP_UNCOMMITED:
event = "AVAHI_ENTRY_GROUP_UNCOMMITED"
case C.AVAHI_ENTRY_GROUP_REGISTERING:
event = "AVAHI_ENTRY_GROUP_REGISTERING"
case C.AVAHI_ENTRY_GROUP_ESTABLISHED:
event = "AVAHI_ENTRY_GROUP_ESTABLISHED"
status = DNSSdSuccess
case C.AVAHI_ENTRY_GROUP_COLLISION:
event = "AVAHI_ENTRY_GROUP_COLLISION"
status = DNSSdCollision
case C.AVAHI_ENTRY_GROUP_FAILURE:
event = "AVAHI_ENTRY_GROUP_FAILURE"
status = DNSSdFailure
}
sysdep.log.Debug(' ', "DNS-SD: %s: %s", sysdep.instance, event)
if status != DNSSdNoStatus {
sysdep.notify(status)
}
}
// avahiGetPoll returns pointer to AvahiPoll
// Avahi helper thread is created on demand
func avahiGetPoll() (*C.AvahiPoll, error) {
avahiInitLock.Lock()
defer avahiInitLock.Unlock()
if avahiThreadedPoll == nil {
avahiThreadedPoll = C.avahi_threaded_poll_new()
if avahiThreadedPoll == nil {
return nil, errors.New("initialization failed, not enough memory")
}
C.avahi_threaded_poll_start(avahiThreadedPoll)
}
return C.avahi_threaded_poll_get(avahiThreadedPoll), nil
}
// Lock Avahi thread
func avahiThreadLock() {
C.avahi_threaded_poll_lock(avahiThreadedPoll)
}
// Unlock Avahi thread
func avahiThreadUnlock() {
C.avahi_threaded_poll_unlock(avahiThreadedPoll)
}