• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2018 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package osp
6
7// TODO(jophba):
8// - Make our own abstraction that has
9//   .InstanceName, .HostName, .MetadataVersion, .FingerPrint
10//   rather than using mdns.ServiceEntry
11// - Advertise TXT (text below) with "fp" and "mv"
12
13import (
14	"context"
15
16	mdns "github.com/grandcat/zeroconf"
17)
18
19const (
20	MdnsServiceType = "_openscreen._udp"
21	MdnsDomain      = "local"
22)
23
24// Returns a channel of mDNS entries.  The critical parts are
25// entry.Target (service name) entry.HostName, entry.AddrIPv4, and
26// entry.AddrIPv6.
27func BrowseMdns(ctx context.Context) (<-chan *mdns.ServiceEntry, error) {
28	entries := make(chan *mdns.ServiceEntry)
29
30	resolver, err := mdns.NewResolver(nil)
31	if err != nil {
32		return entries, err
33	}
34
35	err = resolver.Browse(ctx, MdnsServiceType, MdnsDomain, entries)
36	return entries, err
37}
38
39// Returns a channel of mDNS entries. The critical parts are,
40// entry.HostName, entry.AddrIPv4, and entry.AddrIPv6.
41func LookupMdns(ctx context.Context, target string) (<-chan *mdns.ServiceEntry, error) {
42	entries := make(chan *mdns.ServiceEntry)
43
44	resolver, err := mdns.NewResolver(nil)
45	if err != nil {
46		return entries, err
47	}
48
49	err = resolver.Lookup(ctx, target, MdnsServiceType, MdnsDomain, entries)
50	return entries, err
51}
52
53func RunMdnsServer(ctx context.Context, instance string, port int) error {
54	var text []string
55	server, err := mdns.Register(instance, MdnsServiceType, MdnsDomain, port, text, nil /* ifaces */)
56	if err != nil {
57		return err
58	}
59	waitUntilDone(ctx)
60	server.Shutdown()
61	return nil
62}
63