broadcast.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package beacon
  7. import (
  8. "context"
  9. "net"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/netutil"
  12. )
  13. func NewBroadcast(port int) Interface {
  14. c := newCast("broadcastBeacon")
  15. c.addReader(func(ctx context.Context) error {
  16. return readBroadcasts(ctx, c.outbox, port)
  17. })
  18. c.addWriter(func(ctx context.Context) error {
  19. return writeBroadcasts(ctx, c.inbox, port)
  20. })
  21. return c
  22. }
  23. func writeBroadcasts(ctx context.Context, inbox <-chan []byte, port int) error {
  24. conn, err := net.ListenUDP("udp4", nil)
  25. if err != nil {
  26. l.Debugln(err)
  27. return err
  28. }
  29. doneCtx, cancel := context.WithCancel(ctx)
  30. defer cancel()
  31. go func() {
  32. <-doneCtx.Done()
  33. conn.Close()
  34. }()
  35. for {
  36. var bs []byte
  37. select {
  38. case bs = <-inbox:
  39. case <-doneCtx.Done():
  40. return doneCtx.Err()
  41. }
  42. intfs, err := netutil.Interfaces()
  43. if err != nil {
  44. l.Debugln("Failed to list interfaces:", err)
  45. // net.Interfaces() is broken on Android. see https://github.com/golang/go/issues/40569
  46. // Use the general broadcast address 255.255.255.255 instead.
  47. }
  48. var dsts []net.IP
  49. for i := range intfs {
  50. intf := intfs[i]
  51. if intf.Flags&net.FlagRunning == 0 || intf.Flags&net.FlagBroadcast == 0 {
  52. continue
  53. }
  54. addrs, err := netutil.InterfaceAddrsByInterface(&intf)
  55. if err != nil {
  56. l.Debugln("Failed to list interface addresses:", err)
  57. // Interface discovery might work while retrieving the addresses doesn't. So log the error and carry on.
  58. continue
  59. }
  60. for _, addr := range addrs {
  61. if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
  62. baddr := bcast(iaddr)
  63. dsts = append(dsts, baddr.IP)
  64. }
  65. }
  66. }
  67. if len(dsts) == 0 {
  68. // Fall back to the general IPv4 broadcast address
  69. dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
  70. }
  71. l.Debugln("addresses:", dsts)
  72. success := 0
  73. for _, ip := range dsts {
  74. dst := &net.UDPAddr{IP: ip, Port: port}
  75. conn.SetWriteDeadline(time.Now().Add(time.Second))
  76. _, err = conn.WriteTo(bs, dst)
  77. conn.SetWriteDeadline(time.Time{})
  78. if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  79. // Write timeouts should not happen. We treat it as a fatal
  80. // error on the socket.
  81. l.Debugln(err)
  82. return err
  83. }
  84. if err != nil {
  85. // Some other error that we don't expect. Debug and continue.
  86. l.Debugln(err)
  87. continue
  88. }
  89. l.Debugf("sent %d bytes to %s", len(bs), dst)
  90. success++
  91. }
  92. if success == 0 {
  93. l.Debugln("couldn't send any broadcasts")
  94. return err
  95. }
  96. }
  97. }
  98. func readBroadcasts(ctx context.Context, outbox chan<- recv, port int) error {
  99. conn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: port})
  100. if err != nil {
  101. l.Debugln(err)
  102. return err
  103. }
  104. doneCtx, cancel := context.WithCancel(ctx)
  105. defer cancel()
  106. go func() {
  107. <-doneCtx.Done()
  108. conn.Close()
  109. }()
  110. bs := make([]byte, 65536)
  111. for {
  112. n, addr, err := conn.ReadFrom(bs)
  113. if err != nil {
  114. l.Debugln(err)
  115. return err
  116. }
  117. l.Debugf("recv %d bytes from %s", n, addr)
  118. c := make([]byte, n)
  119. copy(c, bs)
  120. select {
  121. case outbox <- recv{c, addr}:
  122. case <-doneCtx.Done():
  123. return doneCtx.Err()
  124. default:
  125. l.Debugln("dropping message")
  126. }
  127. }
  128. }
  129. func bcast(ip *net.IPNet) *net.IPNet {
  130. bc := &net.IPNet{}
  131. bc.IP = make([]byte, len(ip.IP))
  132. copy(bc.IP, ip.IP)
  133. bc.Mask = ip.Mask
  134. offset := len(bc.IP) - len(bc.Mask)
  135. for i := range bc.IP {
  136. if i-offset >= 0 {
  137. bc.IP[i] = ip.IP[i] | ^ip.Mask[i-offset]
  138. }
  139. }
  140. return bc
  141. }