TCPConn_bind.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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-Inc/goselect"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  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. func tcpDial(ctx context.Context, addr string, config *DialConfig) (net.Conn, error) {
  40. // Get the remote IP and port, resolving a domain name if necessary
  41. host, strPort, err := net.SplitHostPort(addr)
  42. if err != nil {
  43. return nil, common.ContextError(err)
  44. }
  45. port, err := strconv.Atoi(strPort)
  46. if err != nil {
  47. return nil, common.ContextError(err)
  48. }
  49. ipAddrs, err := LookupIP(ctx, host, config)
  50. if err != nil {
  51. return nil, common.ContextError(err)
  52. }
  53. if len(ipAddrs) < 1 {
  54. return nil, common.ContextError(errors.New("no IP address"))
  55. }
  56. // When configured, attempt to synthesize IPv6 addresses from
  57. // an IPv4 addresses for compatibility on DNS64/NAT64 networks.
  58. // If synthesize fails, try the original addresses.
  59. if config.IPv6Synthesizer != nil {
  60. for i, ipAddr := range ipAddrs {
  61. if ipAddr.To4() != nil {
  62. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(ipAddr.String())
  63. if synthesizedIPAddress != "" {
  64. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  65. if synthesizedAddr != nil {
  66. ipAddrs[i] = synthesizedAddr
  67. }
  68. }
  69. }
  70. }
  71. }
  72. // Iterate over a pseudorandom permutation of the destination
  73. // IPs and attempt connections.
  74. //
  75. // Only continue retrying as long as the dial context is not
  76. // done. Unlike net.Dial, we do not fractionalize the context
  77. // deadline, as the dial is generally intended to apply to a
  78. // single attempt. So these serial retries are most useful in
  79. // cases of immediate failure, such as "no route to host"
  80. // errors when a host resolves to both IPv4 and IPv6 but IPv6
  81. // addresses are unreachable.
  82. //
  83. // Retries at higher levels cover other cases: e.g.,
  84. // Controller.remoteServerListFetcher will retry its entire
  85. // operation and tcpDial will try a new permutation; or similarly,
  86. // Controller.establishCandidateGenerator will retry a candidate
  87. // tunnel server dials.
  88. permutedIndexes := rand.Perm(len(ipAddrs))
  89. lastErr := errors.New("unknown error")
  90. for _, index := range permutedIndexes {
  91. // Get address type (IPv4 or IPv6)
  92. var ipv4 [4]byte
  93. var ipv6 [16]byte
  94. var domain int
  95. var sockAddr syscall.Sockaddr
  96. ipAddr := ipAddrs[index]
  97. if ipAddr != nil && ipAddr.To4() != nil {
  98. copy(ipv4[:], ipAddr.To4())
  99. domain = syscall.AF_INET
  100. } else if ipAddr != nil && ipAddr.To16() != nil {
  101. copy(ipv6[:], ipAddr.To16())
  102. domain = syscall.AF_INET6
  103. } else {
  104. lastErr = common.ContextError(fmt.Errorf("invalid IP address: %s", ipAddr.String()))
  105. continue
  106. }
  107. if domain == syscall.AF_INET {
  108. sockAddr = &syscall.SockaddrInet4{Addr: ipv4, Port: port}
  109. } else if domain == syscall.AF_INET6 {
  110. sockAddr = &syscall.SockaddrInet6{Addr: ipv6, Port: port}
  111. }
  112. // Create a socket and bind to device, when configured to do so
  113. socketFD, err := syscall.Socket(domain, syscall.SOCK_STREAM, 0)
  114. if err != nil {
  115. lastErr = common.ContextError(err)
  116. continue
  117. }
  118. syscall.CloseOnExec(socketFD)
  119. tcpDialSetAdditionalSocketOptions(socketFD)
  120. if config.DeviceBinder != nil {
  121. err = config.DeviceBinder.BindToDevice(socketFD)
  122. if err != nil {
  123. syscall.Close(socketFD)
  124. lastErr = common.ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  125. continue
  126. }
  127. }
  128. // Connect socket to the server's IP address
  129. err = syscall.SetNonblock(socketFD, true)
  130. if err != nil {
  131. syscall.Close(socketFD)
  132. lastErr = common.ContextError(err)
  133. continue
  134. }
  135. err = syscall.Connect(socketFD, sockAddr)
  136. if err != nil {
  137. if errno, ok := err.(syscall.Errno); !ok || errno != syscall.EINPROGRESS {
  138. syscall.Close(socketFD)
  139. lastErr = common.ContextError(err)
  140. continue
  141. }
  142. }
  143. // Use a control pipe to interrupt if the dial context is done (timeout or
  144. // interrupted) before the TCP connection is established.
  145. var controlFDs [2]int
  146. err = syscall.Pipe(controlFDs[:])
  147. if err != nil {
  148. syscall.Close(socketFD)
  149. lastErr = common.ContextError(err)
  150. continue
  151. }
  152. for _, controlFD := range controlFDs {
  153. syscall.CloseOnExec(controlFD)
  154. err = syscall.SetNonblock(controlFD, true)
  155. if err != nil {
  156. break
  157. }
  158. }
  159. if err != nil {
  160. syscall.Close(socketFD)
  161. lastErr = common.ContextError(err)
  162. continue
  163. }
  164. resultChannel := make(chan error)
  165. go func() {
  166. readSet := goselect.FDSet{}
  167. readSet.Set(uintptr(controlFDs[0]))
  168. writeSet := goselect.FDSet{}
  169. writeSet.Set(uintptr(socketFD))
  170. max := socketFD
  171. if controlFDs[0] > max {
  172. max = controlFDs[0]
  173. }
  174. err := goselect.Select(max+1, &readSet, &writeSet, nil, -1)
  175. if err == nil && !writeSet.IsSet(uintptr(socketFD)) {
  176. err = errors.New("interrupted")
  177. }
  178. resultChannel <- err
  179. }()
  180. done := false
  181. select {
  182. case err = <-resultChannel:
  183. case <-ctx.Done():
  184. err = ctx.Err()
  185. // Interrupt the goroutine
  186. // TODO: if this Write fails, abandon the goroutine instead of hanging?
  187. var b [1]byte
  188. syscall.Write(controlFDs[1], b[:])
  189. <-resultChannel
  190. done = true
  191. }
  192. syscall.Close(controlFDs[0])
  193. syscall.Close(controlFDs[1])
  194. if err != nil {
  195. syscall.Close(socketFD)
  196. if done {
  197. // Skip retry as dial context has timed out of been canceled.
  198. return nil, common.ContextError(err)
  199. }
  200. lastErr = common.ContextError(err)
  201. continue
  202. }
  203. err = syscall.SetNonblock(socketFD, false)
  204. if err != nil {
  205. syscall.Close(socketFD)
  206. lastErr = common.ContextError(err)
  207. continue
  208. }
  209. // Convert the socket fd to a net.Conn
  210. // This code block is from:
  211. // https://github.com/golang/go/issues/6966
  212. file := os.NewFile(uintptr(socketFD), "")
  213. conn, err := net.FileConn(file) // net.FileConn() dups socketFD
  214. file.Close() // file.Close() closes socketFD
  215. if err != nil {
  216. lastErr = common.ContextError(err)
  217. continue
  218. }
  219. return &TCPConn{Conn: conn}, nil
  220. }
  221. return nil, lastErr
  222. }