TCPConn_unix.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // +build android darwin dragonfly freebsd linux nacl netbsd openbsd solaris
  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. "errors"
  23. "fmt"
  24. "net"
  25. "os"
  26. "strconv"
  27. "syscall"
  28. "time"
  29. )
  30. type interruptibleTCPSocket struct {
  31. socketFd int
  32. }
  33. const _INVALID_FD = -1
  34. // interruptibleTCPDial establishes a TCP network connection. A conn is added
  35. // to config.PendingConns before blocking on network IO, which enables interruption.
  36. // The caller is responsible for removing an established conn from PendingConns.
  37. //
  38. // To implement socket device binding and interruptible connecting, the lower-level
  39. // syscall APIs are used. The sequence of syscalls in this implementation are
  40. // taken from: https://code.google.com/p/go/issues/detail?id=6966
  41. func interruptibleTCPDial(addr string, config *DialConfig) (conn *TCPConn, err error) {
  42. // Create a socket and then, before connecting, add a TCPConn with
  43. // the unconnected socket to pendingConns. This allows pendingConns to
  44. // abort connections in progress.
  45. socketFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
  46. if err != nil {
  47. return nil, ContextError(err)
  48. }
  49. defer func() {
  50. // Cleanup on error
  51. // (socketFd is reset to _INVALID_FD once it should no longer be closed)
  52. if err != nil && socketFd != _INVALID_FD {
  53. syscall.Close(socketFd)
  54. }
  55. }()
  56. if config.DeviceBinder != nil {
  57. err = config.DeviceBinder.BindToDevice(socketFd)
  58. if err != nil {
  59. return nil, ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  60. }
  61. }
  62. // When using an upstream HTTP proxy, first connect to the proxy,
  63. // then use HTTP CONNECT to connect to the original destination.
  64. dialAddr := addr
  65. if config.UpstreamHttpProxyAddress != "" {
  66. dialAddr = config.UpstreamHttpProxyAddress
  67. // Report connection errors in a notice, as user may have input
  68. // invalid proxy address or credential
  69. defer func() {
  70. if err != nil {
  71. NoticeUpstreamProxyError(err)
  72. }
  73. }()
  74. }
  75. // Get the remote IP and port, resolving a domain name if necessary
  76. // TODO: domain name resolution isn't interruptible
  77. host, strPort, err := net.SplitHostPort(dialAddr)
  78. if err != nil {
  79. return nil, ContextError(err)
  80. }
  81. port, err := strconv.Atoi(strPort)
  82. if err != nil {
  83. return nil, ContextError(err)
  84. }
  85. ipAddrs, err := LookupIP(host, config)
  86. if err != nil {
  87. return nil, ContextError(err)
  88. }
  89. if len(ipAddrs) < 1 {
  90. return nil, ContextError(errors.New("no IP address"))
  91. }
  92. // Select an IP at random from the list, so we're not always
  93. // trying the same IP (when > 1) which may be blocked.
  94. // TODO: retry all IPs until one connects? For now, this retry
  95. // will happen on subsequent TCPDial calls, when a different IP
  96. // is selected.
  97. index, err := MakeSecureRandomInt(len(ipAddrs))
  98. if err != nil {
  99. return nil, ContextError(err)
  100. }
  101. // TODO: IPv6 support
  102. var ip [4]byte
  103. copy(ip[:], ipAddrs[index].To4())
  104. // Enable interruption
  105. conn = &TCPConn{
  106. interruptible: interruptibleTCPSocket{socketFd: socketFd},
  107. readTimeout: config.ReadTimeout,
  108. writeTimeout: config.WriteTimeout}
  109. if !config.PendingConns.Add(conn) {
  110. return nil, ContextError(errors.New("pending connections already closed"))
  111. }
  112. // Connect the socket
  113. // TODO: adjust the timeout to account for time spent resolving hostname
  114. sockAddr := syscall.SockaddrInet4{Addr: ip, Port: port}
  115. if config.ConnectTimeout != 0 {
  116. errChannel := make(chan error, 2)
  117. time.AfterFunc(config.ConnectTimeout, func() {
  118. errChannel <- errors.New("connect timeout")
  119. })
  120. go func() {
  121. errChannel <- syscall.Connect(socketFd, &sockAddr)
  122. }()
  123. err = <-errChannel
  124. } else {
  125. err = syscall.Connect(socketFd, &sockAddr)
  126. }
  127. // Mutex required for writing to conn, since conn remains in
  128. // pendingConns, through which conn.Close() may be called from
  129. // another goroutine.
  130. conn.mutex.Lock()
  131. // From this point, ensure conn.interruptible.socketFd is reset
  132. // since the fd value may be reused for a different file or socket
  133. // before Close() -- and interruptibleTCPClose() -- is called for
  134. // this conn.
  135. conn.interruptible.socketFd = _INVALID_FD // (requires mutex)
  136. // This is the syscall.Connect result
  137. if err != nil {
  138. conn.mutex.Unlock()
  139. return nil, ContextError(err)
  140. }
  141. // Convert the socket fd to a net.Conn
  142. file := os.NewFile(uintptr(socketFd), "")
  143. fileConn, err := net.FileConn(file)
  144. file.Close()
  145. // No more deferred fd clean up on err
  146. socketFd = _INVALID_FD
  147. if err != nil {
  148. conn.mutex.Unlock()
  149. return nil, ContextError(err)
  150. }
  151. conn.Conn = fileConn // (requires mutex)
  152. conn.mutex.Unlock()
  153. // Going through upstream HTTP proxy
  154. if config.UpstreamHttpProxyAddress != "" {
  155. // This call can be interrupted by closing the pending conn
  156. err = HttpProxyConnect(conn, addr)
  157. if err != nil {
  158. return nil, ContextError(err)
  159. }
  160. }
  161. return conn, nil
  162. }
  163. func interruptibleTCPClose(interruptible interruptibleTCPSocket) error {
  164. if interruptible.socketFd == _INVALID_FD {
  165. return nil
  166. }
  167. return syscall.Close(interruptible.socketFd)
  168. }