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
|
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner (pzz@apevzner.com)
* See LICENSE for license terms and conditions
*
* DNS-SD publisher: system-independent stuff
*/
package main
import (
"fmt"
"strings"
"sync"
"time"
)
// DNSSdTxtItem represents a single TXT record item
type DNSSdTxtItem struct {
Key, Value string // TXT entry: Key=Value
URL bool // It's an URL, hostname must be adjusted
}
// DNSSdTxtRecord represents a TXT record
type DNSSdTxtRecord []DNSSdTxtItem
// Add adds regular (non-URL) item to DNSSdTxtRecord
func (txt *DNSSdTxtRecord) Add(key, value string) {
*txt = append(*txt, DNSSdTxtItem{key, value, false})
}
// AddURL adds URL item to DNSSdTxtRecord
func (txt *DNSSdTxtRecord) AddURL(key, value string) {
*txt = append(*txt, DNSSdTxtItem{key, value, true})
}
// AddPDL adds PDL list (list of supported Page Description Languages, i.e.,
// document formats) to the DNSSdTxtRecord.
//
// Sometimes the PDL list that comes from device, is too large to fit
// TXT record (key=value pair must not exceed 255 bytes). At this case
// we take only as much as possible leading entries of the device-supplied
// list in hope that firmware is smart enough to place most common PDLs
// to the beginning of the list, while more exotic entries goes to the end
func (txt *DNSSdTxtRecord) AddPDL(key, value string) {
// How many space we have for value? Is it enough?
max := 255 - len(key) - 1
if max >= len(value) {
txt.Add(key, value)
return
}
// Safety check
if max <= 0 {
return
}
// Truncate the value to fit available space
value = value[:max+1]
i := strings.LastIndexByte(value, ',')
if i < 0 {
return
}
value = value[:i]
txt.Add(key, value)
}
// IfNotEmpty adds item to DNSSdTxtRecord if its value is not empty
//
// It returns true if item was actually added, false otherwise
func (txt *DNSSdTxtRecord) IfNotEmpty(key, value string) bool {
if value != "" {
txt.Add(key, value)
return true
}
return false
}
// URLIfNotEmpty works as IfNotEmpty, but for URLs
func (txt *DNSSdTxtRecord) URLIfNotEmpty(key, value string) bool {
if value != "" {
txt.AddURL(key, value)
return true
}
return false
}
// export DNSSdTxtRecord into Avahi format
func (txt DNSSdTxtRecord) export() [][]byte {
var exported [][]byte
// Note, for a some strange reason, Avahi published
// TXT record in reverse order, so compensate it here
for i := len(txt) - 1; i >= 0; i-- {
item := txt[i]
exported = append(exported, []byte(item.Key+"="+item.Value))
}
return exported
}
// DNSSdSvcInfo represents a DNS-SD service information
type DNSSdSvcInfo struct {
Instance string // If not "", override common instance name
Type string // Service type, i.e. "_ipp._tcp"
SubTypes []string // Service subtypes, if any
Port int // TCP port
Txt DNSSdTxtRecord // TXT record
Loopback bool // Advertise only on loopback interface
}
// DNSSdServices represents a collection of DNS-SD services
type DNSSdServices []DNSSdSvcInfo
// Add DNSSdSvcInfo to DNSSdServices
func (services *DNSSdServices) Add(srv DNSSdSvcInfo) {
*services = append(*services, srv)
}
// DNSSdPublisher represents a DNS-SD service publisher
// One publisher may publish multiple services unser the
// same Service Instance Name
type DNSSdPublisher struct {
Log *Logger // Device's logger
DevState *DevState // Device persistent state
Services DNSSdServices // Registered services
fin chan struct{} // Closed to terminate publisher goroutine
finDone sync.WaitGroup // To wait for goroutine termination
sysdep *dnssdSysdep // System-dependent stuff
}
// DNSSdStatus represents DNS-SD publisher status
type DNSSdStatus int
const (
DNSSdNoStatus DNSSdStatus = iota // Invalid status
DNSSdCollision // Service instance name collision
DNSSdFailure // Publisher failed
DNSSdSuccess // Services successfully published
)
// String returns human-readable representation of DNSSdStatus
func (status DNSSdStatus) String() string {
switch status {
case DNSSdNoStatus:
return "DNSSdNoStatus"
case DNSSdCollision:
return "DNSSdCollision"
case DNSSdFailure:
return "DNSSdFailure"
case DNSSdSuccess:
return "DNSSdSuccess"
}
return fmt.Sprintf("Unknown DNSSdStatus %d", status)
}
// NewDNSSdPublisher creates new DNSSdPublisher
//
// Service instance name comes from the DevState, and if
// name changes as result of name collision resolution,
// DevState will be updated
func NewDNSSdPublisher(log *Logger,
devstate *DevState, services DNSSdServices) *DNSSdPublisher {
return &DNSSdPublisher{
Log: log,
DevState: devstate,
Services: services,
fin: make(chan struct{}),
}
}
// Publish all services
func (publisher *DNSSdPublisher) Publish() error {
instance := publisher.instance(0)
publisher.sysdep = newDnssdSysdep(publisher.Log, instance,
publisher.Services)
publisher.Log.Info('+', "DNS-SD: %s: publishing requested", instance)
publisher.finDone.Add(1)
go publisher.goroutine()
return nil
}
// Unpublish everything
func (publisher *DNSSdPublisher) Unpublish() {
close(publisher.fin)
publisher.finDone.Wait()
publisher.sysdep.Halt()
publisher.Log.Info('-', "DNS-SD: %s: removed", publisher.instance(0))
}
// Build service instance name with optional collision-resolution suffix
func (publisher *DNSSdPublisher) instance(suffix int) string {
name := publisher.DevState.DNSSdName
strSuffix := ""
switch {
// This happens when we try to resolve name conflict
case suffix != 0:
strSuffix = fmt.Sprintf(" (USB %d)", suffix)
// This happens when we've just initialized or reset DNSSdOverride,
// so append "(USB)" suffix
case publisher.DevState.DNSSdName == publisher.DevState.DNSSdOverride:
strSuffix = " (USB)"
// Otherwise, DNSSdOverride contains saved conflict-resolved device name
default:
name = publisher.DevState.DNSSdOverride
}
const MAX_DNSSD_NAME = 63
if len(name)+len(strSuffix) > MAX_DNSSD_NAME {
name = name[:MAX_DNSSD_NAME-len(strSuffix)]
}
return name + strSuffix
}
// Event handling goroutine
func (publisher *DNSSdPublisher) goroutine() {
// Catch panics to log
defer func() {
v := recover()
if v != nil {
Log.Panic(v)
}
}()
defer publisher.finDone.Done()
timer := time.NewTimer(time.Hour)
timer.Stop() // Not ticking now
defer timer.Stop() // And cleanup at return
var err error
var suffix int
instance := publisher.instance(0)
for {
fail := false
select {
case <-publisher.fin:
return
case status := <-publisher.sysdep.Chan():
switch status {
case DNSSdSuccess:
publisher.Log.Info(' ', "DNS-SD: %s: published", instance)
if instance != publisher.DevState.DNSSdOverride {
publisher.DevState.DNSSdOverride = instance
publisher.DevState.Save()
}
case DNSSdCollision:
publisher.Log.Error(' ', "DNS-SD: %s: name collision",
instance)
suffix++
fallthrough
case DNSSdFailure:
publisher.Log.Error(' ', "DNS-SD: %s: publishing failed",
instance)
fail = true
publisher.sysdep.Halt()
default:
publisher.Log.Error(' ', "DNS-SD: %s: unknown event %s",
instance, status)
}
case <-timer.C:
instance = publisher.instance(suffix)
publisher.sysdep = newDnssdSysdep(publisher.Log,
instance, publisher.Services)
if err != nil {
publisher.Log.Error('!', "DNS-SD: %s: %s", instance, err)
fail = true
}
}
if fail {
timer.Reset(DNSSdRetryInterval)
}
}
}
|