broadcast.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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(err)
  44. return err
  45. }
  46. var dsts []net.IP
  47. for _, intf := range intfs {
  48. if intf.Flags&net.FlagBroadcast == 0 {
  49. continue
  50. }
  51. addrs, err := intf.Addrs()
  52. if err != nil {
  53. l.Debugln(err)
  54. return err
  55. }
  56. for _, addr := range addrs {
  57. if iaddr, ok := addr.(*net.IPNet); ok && len(iaddr.IP) >= 4 && iaddr.IP.IsGlobalUnicast() && iaddr.IP.To4() != nil {
  58. baddr := bcast(iaddr)
  59. dsts = append(dsts, baddr.IP)
  60. }
  61. }
  62. }
  63. if len(dsts) == 0 {
  64. // Fall back to the general IPv4 broadcast address
  65. dsts = append(dsts, net.IP{0xff, 0xff, 0xff, 0xff})
  66. }
  67. l.Debugln("addresses:", dsts)
  68. success := 0
  69. for _, ip := range dsts {
  70. dst := &net.UDPAddr{IP: ip, Port: port}
  71. conn.SetWriteDeadline(time.Now().Add(time.Second))
  72. _, err = conn.WriteTo(bs, dst)
  73. conn.SetWriteDeadline(time.Time{})
  74. if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
  75. // Write timeouts should not happen. We treat it as a fatal
  76. // error on the socket.
  77. l.Debugln(err)
  78. return err
  79. }
  80. if err != nil {
  81. // Some other error that we don't expect. Debug and continue.
  82. l.Debugln(err)
  83. continue
  84. }
  85. l.Debugf("sent %d bytes to %s", len(bs), dst)
  86. success++
  87. }
  88. if success == 0 {
  89. l.Debugln("couldn't send any braodcasts")
  90. return err
  91. }
  92. }
  93. }
  94. func readBroadcasts(ctx context.Context, outbox chan<- recv, port int) error {
  95. conn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: port})
  96. if err != nil {
  97. l.Debugln(err)
  98. return err
  99. }
  100. doneCtx, cancel := context.WithCancel(ctx)
  101. defer cancel()
  102. go func() {
  103. <-doneCtx.Done()
  104. conn.Close()
  105. }()
  106. bs := make([]byte, 65536)
  107. for {
  108. n, addr, err := conn.ReadFrom(bs)
  109. if err != nil {
  110. l.Debugln(err)
  111. return err
  112. }
  113. l.Debugf("recv %d bytes from %s", n, addr)
  114. c := make([]byte, n)
  115. copy(c, bs)
  116. select {
  117. case outbox <- recv{c, addr}:
  118. case <-doneCtx.Done():
  119. return doneCtx.Err()
  120. default:
  121. l.Debugln("dropping message")
  122. }
  123. }
  124. }
  125. func bcast(ip *net.IPNet) *net.IPNet {
  126. var bc = &net.IPNet{}
  127. bc.IP = make([]byte, len(ip.IP))
  128. copy(bc.IP, ip.IP)
  129. bc.Mask = ip.Mask
  130. offset := len(bc.IP) - len(bc.Mask)
  131. for i := range bc.IP {
  132. if i-offset >= 0 {
  133. bc.IP[i] = ip.IP[i] | ^ip.Mask[i-offset]
  134. }
  135. }
  136. return bc
  137. }