broadcast.go 4.0 KB

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