UDPConn.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. /*
  2. * Copyright (c) 2018, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "context"
  22. "math/rand"
  23. "net"
  24. "strconv"
  25. "syscall"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  27. )
  28. // NewUDPConn resolves addr and configures a new *net.UDPConn. The UDP socket
  29. // is created using options in DialConfig, including DeviceBinder. The
  30. // returned UDPAddr uses DialConfig options IPv6Synthesizer and
  31. // ResolvedIPCallback.
  32. //
  33. // The UDP conn is not dialed; it is intended for use with WriteTo using the
  34. // returned UDPAddr, not Write.
  35. //
  36. // The returned conn is not a common.Closer; the caller is expected to wrap
  37. // this conn with another higher-level conn that provides that interface.
  38. func NewUDPConn(
  39. ctx context.Context, addr string, config *DialConfig) (net.PacketConn, *net.UDPAddr, error) {
  40. host, strPort, err := net.SplitHostPort(addr)
  41. if err != nil {
  42. return nil, nil, errors.Trace(err)
  43. }
  44. port, err := strconv.Atoi(strPort)
  45. if err != nil {
  46. return nil, nil, errors.Trace(err)
  47. }
  48. if port <= 0 || port >= 65536 {
  49. return nil, nil, errors.Tracef("invalid destination port: %d", port)
  50. }
  51. if config.ResolveIP == nil {
  52. // Fail even if we don't need a resolver for this dial: this is a code
  53. // misconfiguration.
  54. return nil, nil, errors.TraceNew("missing resolver")
  55. }
  56. ipAddrs, err := config.ResolveIP(ctx, host)
  57. if err != nil {
  58. return nil, nil, errors.Trace(err)
  59. }
  60. if len(ipAddrs) < 1 {
  61. return nil, nil, errors.TraceNew("no IP address")
  62. }
  63. ipAddr := ipAddrs[rand.Intn(len(ipAddrs))]
  64. if config.IPv6Synthesizer != nil {
  65. if ipAddr.To4() != nil {
  66. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(ipAddr.String())
  67. if synthesizedIPAddress != "" {
  68. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  69. if synthesizedAddr != nil {
  70. ipAddr = synthesizedAddr
  71. }
  72. }
  73. }
  74. }
  75. listen := &net.ListenConfig{
  76. Control: func(_, _ string, c syscall.RawConn) error {
  77. var controlErr error
  78. err := c.Control(func(fd uintptr) {
  79. socketFD := int(fd)
  80. setAdditionalSocketOptions(socketFD)
  81. if config.BPFProgramInstructions != nil {
  82. err := setSocketBPF(config.BPFProgramInstructions, socketFD)
  83. if err != nil {
  84. controlErr = errors.Tracef("setSocketBPF failed: %s", err)
  85. return
  86. }
  87. }
  88. if config.DeviceBinder != nil {
  89. _, err := config.DeviceBinder.BindToDevice(socketFD)
  90. if err != nil {
  91. controlErr = errors.Tracef("BindToDevice failed: %s", err)
  92. return
  93. }
  94. }
  95. })
  96. if controlErr != nil {
  97. return errors.Trace(controlErr)
  98. }
  99. return errors.Trace(err)
  100. },
  101. }
  102. network := "udp4"
  103. if ipAddr.To4() == nil {
  104. network = "udp6"
  105. }
  106. // It's necessary to create an "unconnected" UDP socket, for use with
  107. // WriteTo, as required by quic-go. As documented in net.ListenUDP: with
  108. // an unspecified IP address, the resulting conn "listens on all
  109. // available IP addresses of the local system except multicast IP
  110. // addresses".
  111. //
  112. // Limitation: these UDP sockets are not necessarily closed when a device
  113. // changes active network (e.g., WiFi to mobile). It's possible that a
  114. // QUIC connection does not immediately close on a network change, and
  115. // instead outbound packets are sent from a different active interface.
  116. // As quic-go does not yet support connection migration, these packets
  117. // will be dropped by the server. This situation is mitigated by use of
  118. // DeviceBinder; by network change event detection, which initiates new
  119. // tunnel connections; and by timeouts/keep-alives.
  120. conn, err := listen.ListenPacket(ctx, network, "")
  121. if err != nil {
  122. return nil, nil, errors.Trace(err)
  123. }
  124. udpConn, ok := conn.(*net.UDPConn)
  125. if !ok {
  126. return nil, nil, errors.Tracef("unexpected conn type: %T", conn)
  127. }
  128. if config.ResolvedIPCallback != nil {
  129. config.ResolvedIPCallback(ipAddr.String())
  130. }
  131. return udpConn, &net.UDPAddr{IP: ipAddr, Port: port}, nil
  132. }