From b469a462704b7c602f1221088ff8d750d72ee418 Mon Sep 17 00:00:00 2001 From: Farshid Tavakolizadeh Date: Sun, 7 Mar 2021 15:21:19 +0100 Subject: [PATCH] fixed dns-sd instance name escaping --- discovery.go | 13 ++++++++++--- discovery_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 discovery_test.go diff --git a/discovery.go b/discovery.go index 5297f0a..29ade98 100644 --- a/discovery.go +++ b/discovery.go @@ -15,11 +15,18 @@ import ( "github.com/linksmart/thing-directory/catalog" ) +// escape special characters as recommended by https://tools.ietf.org/html/rfc6763#section-4.3 +func escapeDNSSDServiceInstance(instance string) (escaped string) { + // replace \ by \\ + escaped = strings.ReplaceAll(instance, "\\", "\\\\") + // replace . by \. + escaped = strings.ReplaceAll(escaped, ".", "\\.") + return escaped +} + // register as a DNS-SD Service func registerDNSSDService(conf *Config) (func(), error) { - // escape special characters (https://tools.ietf.org/html/rfc6763#section-4.3) - instance := strings.ReplaceAll(conf.DNSSD.Publish.Instance, ".", "\\.") - instance = strings.ReplaceAll(conf.DNSSD.Publish.Instance, "\\", "\\\\") + instance := escapeDNSSDServiceInstance(conf.DNSSD.Publish.Instance) log.Printf("DNS-SD: registering as \"%s.%s.%s\", subtype: %s", instance, catalog.DNSSDServiceType, conf.DNSSD.Publish.Domain, catalog.DNSSDServiceSubtype) diff --git a/discovery_test.go b/discovery_test.go new file mode 100644 index 0000000..7c3d271 --- /dev/null +++ b/discovery_test.go @@ -0,0 +1,31 @@ +package main + +import "testing" + +func TestEscapeDNSSDServiceInstance(t *testing.T) { + t.Run("no escaping", func(t *testing.T) { + instance := "thing-directory" + escaped := escapeDNSSDServiceInstance(instance) + if escaped != instance { + t.Fatalf("Unexpected escaping of %s to %s", instance, escaped) + } + }) + + t.Run("escape dot", func(t *testing.T) { + instance := "thing.directory" // from thing.directory + expected := "thing\\.directory" // to thing\.directory + escaped := escapeDNSSDServiceInstance(instance) + if escaped != expected { + t.Fatalf("Escaped value for %s is %s. Expected %s", instance, escaped, expected) + } + }) + + t.Run("escape backslash", func(t *testing.T) { + instance := "thing\\directory" // from thing\directory + expected := "thing\\\\directory" // to thing\\directory + escaped := escapeDNSSDServiceInstance(instance) + if escaped != expected { + t.Fatalf("Escaped value for %s is %s. Expected %s", instance, escaped, expected) + } + }) +}