broadcast.go 3.8 KB

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