conn.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package mdns
  2. import (
  3. "context"
  4. "errors"
  5. "math/big"
  6. "net"
  7. "runtime"
  8. "sync"
  9. "time"
  10. "github.com/pion/logging"
  11. "golang.org/x/net/dns/dnsmessage"
  12. "golang.org/x/net/ipv4"
  13. )
  14. // Conn represents a mDNS Server
  15. type Conn struct {
  16. mu sync.RWMutex
  17. log logging.LeveledLogger
  18. socket *ipv4.PacketConn
  19. dstAddr *net.UDPAddr
  20. queryInterval time.Duration
  21. localNames []string
  22. queries []query
  23. ifaces []net.Interface
  24. closed chan interface{}
  25. }
  26. type query struct {
  27. nameWithSuffix string
  28. queryResultChan chan queryResult
  29. }
  30. type queryResult struct {
  31. answer dnsmessage.ResourceHeader
  32. addr net.Addr
  33. }
  34. const (
  35. defaultQueryInterval = time.Second
  36. destinationAddress = "224.0.0.251:5353"
  37. maxMessageRecords = 3
  38. responseTTL = 120
  39. )
  40. var errNoPositiveMTUFound = errors.New("no positive MTU found")
  41. // Server establishes a mDNS connection over an existing conn
  42. func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) {
  43. if config == nil {
  44. return nil, errNilConfig
  45. }
  46. ifaces, err := net.Interfaces()
  47. if err != nil {
  48. return nil, err
  49. }
  50. inboundBufferSize := 0
  51. joinErrCount := 0
  52. ifacesToUse := make([]net.Interface, 0, len(ifaces))
  53. for i, ifc := range ifaces {
  54. if err = conn.JoinGroup(&ifaces[i], &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil {
  55. joinErrCount++
  56. continue
  57. }
  58. ifcCopy := ifc
  59. ifacesToUse = append(ifacesToUse, ifcCopy)
  60. if ifaces[i].MTU > inboundBufferSize {
  61. inboundBufferSize = ifaces[i].MTU
  62. }
  63. }
  64. if inboundBufferSize == 0 {
  65. return nil, errNoPositiveMTUFound
  66. }
  67. if joinErrCount >= len(ifaces) {
  68. return nil, errJoiningMulticastGroup
  69. }
  70. dstAddr, err := net.ResolveUDPAddr("udp", destinationAddress)
  71. if err != nil {
  72. return nil, err
  73. }
  74. loggerFactory := config.LoggerFactory
  75. if loggerFactory == nil {
  76. loggerFactory = logging.NewDefaultLoggerFactory()
  77. }
  78. localNames := []string{}
  79. for _, l := range config.LocalNames {
  80. localNames = append(localNames, l+".")
  81. }
  82. c := &Conn{
  83. queryInterval: defaultQueryInterval,
  84. queries: []query{},
  85. socket: conn,
  86. dstAddr: dstAddr,
  87. localNames: localNames,
  88. ifaces: ifacesToUse,
  89. log: loggerFactory.NewLogger("mdns"),
  90. closed: make(chan interface{}),
  91. }
  92. if config.QueryInterval != 0 {
  93. c.queryInterval = config.QueryInterval
  94. }
  95. // https://www.rfc-editor.org/rfc/rfc6762.html#section-17
  96. // Multicast DNS messages carried by UDP may be up to the IP MTU of the
  97. // physical interface, less the space required for the IP header (20
  98. // bytes for IPv4; 40 bytes for IPv6) and the UDP header (8 bytes).
  99. go c.start(inboundBufferSize - 20 - 8)
  100. return c, nil
  101. }
  102. // Close closes the mDNS Conn
  103. func (c *Conn) Close() error {
  104. select {
  105. case <-c.closed:
  106. return nil
  107. default:
  108. }
  109. if err := c.socket.Close(); err != nil {
  110. return err
  111. }
  112. <-c.closed
  113. return nil
  114. }
  115. // Query sends mDNS Queries for the following name until
  116. // either the Context is canceled/expires or we get a result
  117. func (c *Conn) Query(ctx context.Context, name string) (dnsmessage.ResourceHeader, net.Addr, error) {
  118. select {
  119. case <-c.closed:
  120. return dnsmessage.ResourceHeader{}, nil, errConnectionClosed
  121. default:
  122. }
  123. nameWithSuffix := name + "."
  124. queryChan := make(chan queryResult, 1)
  125. c.mu.Lock()
  126. c.queries = append(c.queries, query{nameWithSuffix, queryChan})
  127. ticker := time.NewTicker(c.queryInterval)
  128. c.mu.Unlock()
  129. defer ticker.Stop()
  130. c.sendQuestion(nameWithSuffix)
  131. for {
  132. select {
  133. case <-ticker.C:
  134. c.sendQuestion(nameWithSuffix)
  135. case <-c.closed:
  136. return dnsmessage.ResourceHeader{}, nil, errConnectionClosed
  137. case res := <-queryChan:
  138. return res.answer, res.addr, nil
  139. case <-ctx.Done():
  140. return dnsmessage.ResourceHeader{}, nil, errContextElapsed
  141. }
  142. }
  143. }
  144. func ipToBytes(ip net.IP) (out [4]byte) {
  145. rawIP := ip.To4()
  146. if rawIP == nil {
  147. return
  148. }
  149. ipInt := big.NewInt(0)
  150. ipInt.SetBytes(rawIP)
  151. copy(out[:], ipInt.Bytes())
  152. return
  153. }
  154. func interfaceForRemote(remote string) (net.IP, error) {
  155. conn, err := net.Dial("udp", remote)
  156. if err != nil {
  157. return nil, err
  158. }
  159. localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
  160. if !ok {
  161. return nil, errFailedCast
  162. }
  163. if err := conn.Close(); err != nil {
  164. return nil, err
  165. }
  166. return localAddr.IP, nil
  167. }
  168. func (c *Conn) sendQuestion(name string) {
  169. packedName, err := dnsmessage.NewName(name)
  170. if err != nil {
  171. c.log.Warnf("Failed to construct mDNS packet %v", err)
  172. return
  173. }
  174. msg := dnsmessage.Message{
  175. Header: dnsmessage.Header{},
  176. Questions: []dnsmessage.Question{
  177. {
  178. Type: dnsmessage.TypeA,
  179. Class: dnsmessage.ClassINET,
  180. Name: packedName,
  181. },
  182. },
  183. }
  184. rawQuery, err := msg.Pack()
  185. if err != nil {
  186. c.log.Warnf("Failed to construct mDNS packet %v", err)
  187. return
  188. }
  189. c.writeToSocket(rawQuery)
  190. }
  191. const isWindows = runtime.GOOS == "windows"
  192. func (c *Conn) writeToSocket(b []byte) {
  193. var wcm ipv4.ControlMessage
  194. for i := range c.ifaces {
  195. if isWindows {
  196. if err := c.socket.SetMulticastInterface(&c.ifaces[i]); err != nil {
  197. c.log.Warnf("Failed to set multicast interface for %d: %v", i, err)
  198. }
  199. } else {
  200. wcm.IfIndex = c.ifaces[i].Index
  201. }
  202. if _, err := c.socket.WriteTo(b, &wcm, c.dstAddr); err != nil {
  203. c.log.Warnf("Failed to send mDNS packet on interface %d: %v", i, err)
  204. }
  205. }
  206. }
  207. func (c *Conn) sendAnswer(name string, dst net.IP) {
  208. packedName, err := dnsmessage.NewName(name)
  209. if err != nil {
  210. c.log.Warnf("Failed to construct mDNS packet %v", err)
  211. return
  212. }
  213. msg := dnsmessage.Message{
  214. Header: dnsmessage.Header{
  215. Response: true,
  216. Authoritative: true,
  217. },
  218. Answers: []dnsmessage.Resource{
  219. {
  220. Header: dnsmessage.ResourceHeader{
  221. Type: dnsmessage.TypeA,
  222. Class: dnsmessage.ClassINET,
  223. Name: packedName,
  224. TTL: responseTTL,
  225. },
  226. Body: &dnsmessage.AResource{
  227. A: ipToBytes(dst),
  228. },
  229. },
  230. },
  231. }
  232. rawAnswer, err := msg.Pack()
  233. if err != nil {
  234. c.log.Warnf("Failed to construct mDNS packet %v", err)
  235. return
  236. }
  237. c.writeToSocket(rawAnswer)
  238. }
  239. func (c *Conn) start(inboundBufferSize int) { //nolint gocognit
  240. defer func() {
  241. c.mu.Lock()
  242. defer c.mu.Unlock()
  243. close(c.closed)
  244. }()
  245. b := make([]byte, inboundBufferSize)
  246. p := dnsmessage.Parser{}
  247. for {
  248. n, _, src, err := c.socket.ReadFrom(b)
  249. if err != nil {
  250. if errors.Is(err, net.ErrClosed) {
  251. return
  252. }
  253. c.log.Warnf("Failed to ReadFrom %q %v", src, err)
  254. continue
  255. }
  256. func() {
  257. c.mu.RLock()
  258. defer c.mu.RUnlock()
  259. if _, err := p.Start(b[:n]); err != nil {
  260. c.log.Warnf("Failed to parse mDNS packet %v", err)
  261. return
  262. }
  263. for i := 0; i <= maxMessageRecords; i++ {
  264. q, err := p.Question()
  265. if errors.Is(err, dnsmessage.ErrSectionDone) {
  266. break
  267. } else if err != nil {
  268. c.log.Warnf("Failed to parse mDNS packet %v", err)
  269. return
  270. }
  271. for _, localName := range c.localNames {
  272. if localName == q.Name.String() {
  273. localAddress, err := interfaceForRemote(src.String())
  274. if err != nil {
  275. c.log.Warnf("Failed to get local interface to communicate with %s: %v", src.String(), err)
  276. continue
  277. }
  278. c.sendAnswer(q.Name.String(), localAddress)
  279. }
  280. }
  281. }
  282. for i := 0; i <= maxMessageRecords; i++ {
  283. a, err := p.AnswerHeader()
  284. if errors.Is(err, dnsmessage.ErrSectionDone) {
  285. return
  286. }
  287. if err != nil {
  288. c.log.Warnf("Failed to parse mDNS packet %v", err)
  289. return
  290. }
  291. if a.Type != dnsmessage.TypeA && a.Type != dnsmessage.TypeAAAA {
  292. continue
  293. }
  294. for i := len(c.queries) - 1; i >= 0; i-- {
  295. if c.queries[i].nameWithSuffix == a.Name.String() {
  296. ip, err := ipFromAnswerHeader(a, p)
  297. if err != nil {
  298. c.log.Warnf("Failed to parse mDNS answer %v", err)
  299. return
  300. }
  301. c.queries[i].queryResultChan <- queryResult{a, &net.IPAddr{
  302. IP: ip,
  303. }}
  304. c.queries = append(c.queries[:i], c.queries[i+1:]...)
  305. }
  306. }
  307. }
  308. }()
  309. }
  310. }
  311. func ipFromAnswerHeader(a dnsmessage.ResourceHeader, p dnsmessage.Parser) (ip []byte, err error) {
  312. if a.Type == dnsmessage.TypeA {
  313. resource, err := p.AResource()
  314. if err != nil {
  315. return nil, err
  316. }
  317. ip = net.IP(resource.A[:])
  318. } else {
  319. resource, err := p.AAAAResource()
  320. if err != nil {
  321. return nil, err
  322. }
  323. ip = resource.AAAA[:]
  324. }
  325. return
  326. }