broadcast.go 3.8 KB

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