TCPConn_bind.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // +build !windows
  2. /*
  3. * Copyright (c) 2015, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package psiphon
  21. import (
  22. "context"
  23. "errors"
  24. "fmt"
  25. "math/rand"
  26. "net"
  27. "os"
  28. "strconv"
  29. "syscall"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/creack/goselect"
  32. )
  33. // tcpDial is the platform-specific part of DialTCP
  34. //
  35. // To implement socket device binding, the lower-level syscall APIs are used.
  36. // The sequence of syscalls in this implementation are taken from:
  37. // https://github.com/golang/go/issues/6966
  38. // (originally: https://code.google.com/p/go/issues/detail?id=6966)
  39. //
  40. // TODO: use https://golang.org/pkg/net/#Dialer.Control, introduced in Go 1.11?
  41. func tcpDial(ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  42. // Get the remote IP and port, resolving a domain name if necessary
  43. host, strPort, err := net.SplitHostPort(addr)
  44. if err != nil {
  45. return nil, common.ContextError(err)
  46. }
  47. port, err := strconv.Atoi(strPort)
  48. if err != nil {
  49. return nil, common.ContextError(err)
  50. }
  51. ipAddrs, err := LookupIP(ctx, host, config)
  52. if err != nil {
  53. return nil, common.ContextError(err)
  54. }
  55. if len(ipAddrs) < 1 {
  56. return nil, common.ContextError(errors.New("no IP address"))
  57. }
  58. // When configured, attempt to synthesize IPv6 addresses from
  59. // an IPv4 addresses for compatibility on DNS64/NAT64 networks.
  60. // If synthesize fails, try the original addresses.
  61. if config.IPv6Synthesizer != nil {
  62. for i, ipAddr := range ipAddrs {
  63. if ipAddr.To4() != nil {
  64. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(ipAddr.String())
  65. if synthesizedIPAddress != "" {
  66. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  67. if synthesizedAddr != nil {
  68. ipAddrs[i] = synthesizedAddr
  69. }
  70. }
  71. }
  72. }
  73. }
  74. // Iterate over a pseudorandom permutation of the destination
  75. // IPs and attempt connections.
  76. //
  77. // Only continue retrying as long as the dial context is not
  78. // done. Unlike net.Dial, we do not fractionalize the context
  79. // deadline, as the dial is generally intended to apply to a
  80. // single attempt. So these serial retries are most useful in
  81. // cases of immediate failure, such as "no route to host"
  82. // errors when a host resolves to both IPv4 and IPv6 but IPv6
  83. // addresses are unreachable.
  84. //
  85. // Retries at higher levels cover other cases: e.g.,
  86. // Controller.remoteServerListFetcher will retry its entire
  87. // operation and tcpDial will try a new permutation; or similarly,
  88. // Controller.establishCandidateGenerator will retry a candidate
  89. // tunnel server dials.
  90. permutedIndexes := rand.Perm(len(ipAddrs))
  91. lastErr := errors.New("unknown error")
  92. for _, index := range permutedIndexes {
  93. // Get address type (IPv4 or IPv6)
  94. var ipv4 [4]byte
  95. var ipv6 [16]byte
  96. var domain int
  97. var sockAddr syscall.Sockaddr
  98. ipAddr := ipAddrs[index]
  99. if ipAddr != nil && ipAddr.To4() != nil {
  100. copy(ipv4[:], ipAddr.To4())
  101. domain = syscall.AF_INET
  102. } else if ipAddr != nil && ipAddr.To16() != nil {
  103. copy(ipv6[:], ipAddr.To16())
  104. domain = syscall.AF_INET6
  105. } else {
  106. lastErr = common.ContextError(fmt.Errorf("invalid IP address: %s", ipAddr.String()))
  107. continue
  108. }
  109. if domain == syscall.AF_INET {
  110. sockAddr = &syscall.SockaddrInet4{Addr: ipv4, Port: port}
  111. } else if domain == syscall.AF_INET6 {
  112. sockAddr = &syscall.SockaddrInet6{Addr: ipv6, Port: port}
  113. }
  114. // Create a socket and bind to device, when configured to do so
  115. socketFD, err := syscall.Socket(domain, syscall.SOCK_STREAM, 0)
  116. if err != nil {
  117. lastErr = common.ContextError(err)
  118. continue
  119. }
  120. syscall.CloseOnExec(socketFD)
  121. setAdditionalSocketOptions(socketFD)
  122. if config.DeviceBinder != nil {
  123. _, err = config.DeviceBinder.BindToDevice(socketFD)
  124. if err != nil {
  125. syscall.Close(socketFD)
  126. lastErr = common.ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  127. continue
  128. }
  129. }
  130. // Connect socket to the server's IP address
  131. err = syscall.SetNonblock(socketFD, true)
  132. if err != nil {
  133. syscall.Close(socketFD)
  134. lastErr = common.ContextError(err)
  135. continue
  136. }
  137. err = syscall.Connect(socketFD, sockAddr)
  138. if err != nil {
  139. if errno, ok := err.(syscall.Errno); !ok || errno != syscall.EINPROGRESS {
  140. syscall.Close(socketFD)
  141. lastErr = common.ContextError(err)
  142. continue
  143. }
  144. }
  145. // Use a control pipe to interrupt if the dial context is done (timeout or
  146. // interrupted) before the TCP connection is established.
  147. var controlFDs [2]int
  148. err = syscall.Pipe(controlFDs[:])
  149. if err != nil {
  150. syscall.Close(socketFD)
  151. lastErr = common.ContextError(err)
  152. continue
  153. }
  154. for _, controlFD := range controlFDs {
  155. syscall.CloseOnExec(controlFD)
  156. err = syscall.SetNonblock(controlFD, true)
  157. if err != nil {
  158. break
  159. }
  160. }
  161. if err != nil {
  162. syscall.Close(socketFD)
  163. lastErr = common.ContextError(err)
  164. continue
  165. }
  166. resultChannel := make(chan error)
  167. go func() {
  168. readSet := goselect.FDSet{}
  169. readSet.Set(uintptr(controlFDs[0]))
  170. writeSet := goselect.FDSet{}
  171. writeSet.Set(uintptr(socketFD))
  172. max := socketFD
  173. if controlFDs[0] > max {
  174. max = controlFDs[0]
  175. }
  176. err := goselect.Select(max+1, &readSet, &writeSet, nil, -1)
  177. if err == nil && !writeSet.IsSet(uintptr(socketFD)) {
  178. err = errors.New("interrupted")
  179. }
  180. resultChannel <- err
  181. }()
  182. done := false
  183. select {
  184. case err = <-resultChannel:
  185. case <-ctx.Done():
  186. err = ctx.Err()
  187. // Interrupt the goroutine
  188. // TODO: if this Write fails, abandon the goroutine instead of hanging?
  189. var b [1]byte
  190. syscall.Write(controlFDs[1], b[:])
  191. <-resultChannel
  192. done = true
  193. }
  194. syscall.Close(controlFDs[0])
  195. syscall.Close(controlFDs[1])
  196. if err != nil {
  197. syscall.Close(socketFD)
  198. if done {
  199. // Skip retry as dial context has timed out of been canceled.
  200. return nil, common.ContextError(err)
  201. }
  202. lastErr = common.ContextError(err)
  203. continue
  204. }
  205. err = syscall.SetNonblock(socketFD, false)
  206. if err != nil {
  207. syscall.Close(socketFD)
  208. lastErr = common.ContextError(err)
  209. continue
  210. }
  211. // Convert the socket fd to a net.Conn
  212. // This code block is from:
  213. // https://github.com/golang/go/issues/6966
  214. file := os.NewFile(uintptr(socketFD), "")
  215. conn, err := net.FileConn(file) // net.FileConn() dups socketFD
  216. file.Close() // file.Close() closes socketFD
  217. if err != nil {
  218. lastErr = common.ContextError(err)
  219. continue
  220. }
  221. return &TCPConn{Conn: conn}, nil
  222. }
  223. return nil, lastErr
  224. }