broadcast.go 3.6 KB

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