TCPConn_unix.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. }
  68. // Get the remote IP and port, resolving a domain name if necessary
  69. // TODO: domain name resolution isn't interruptible
  70. host, strPort, err := net.SplitHostPort(dialAddr)
  71. if err != nil {
  72. return nil, ContextError(err)
  73. }
  74. port, err := strconv.Atoi(strPort)
  75. if err != nil {
  76. return nil, ContextError(err)
  77. }
  78. ipAddrs, err := LookupIP(host, config)
  79. if err != nil {
  80. return nil, ContextError(err)
  81. }
  82. if len(ipAddrs) < 1 {
  83. return nil, ContextError(errors.New("no IP address"))
  84. }
  85. // Select an IP at random from the list, so we're not always
  86. // trying the same IP (when > 1) which may be blocked.
  87. // TODO: retry all IPs until one connects? For now, this retry
  88. // will happen on subsequent TCPDial calls, when a different IP
  89. // is selected.
  90. index, err := MakeSecureRandomInt(len(ipAddrs))
  91. if err != nil {
  92. return nil, ContextError(err)
  93. }
  94. // TODO: IPv6 support
  95. var ip [4]byte
  96. copy(ip[:], ipAddrs[index].To4())
  97. // Enable interruption
  98. conn = &TCPConn{
  99. interruptible: interruptibleTCPSocket{socketFd: socketFd},
  100. readTimeout: config.ReadTimeout,
  101. writeTimeout: config.WriteTimeout}
  102. if !config.PendingConns.Add(conn) {
  103. return nil, ContextError(errors.New("pending connections already closed"))
  104. }
  105. // Connect the socket
  106. // TODO: adjust the timeout to account for time spent resolving hostname
  107. sockAddr := syscall.SockaddrInet4{Addr: ip, Port: port}
  108. if config.ConnectTimeout != 0 {
  109. errChannel := make(chan error, 2)
  110. time.AfterFunc(config.ConnectTimeout, func() {
  111. errChannel <- errors.New("connect timeout")
  112. })
  113. go func() {
  114. errChannel <- syscall.Connect(socketFd, &sockAddr)
  115. }()
  116. err = <-errChannel
  117. } else {
  118. err = syscall.Connect(socketFd, &sockAddr)
  119. }
  120. // Mutex required for writing to conn, since conn remains in
  121. // pendingConns, through which conn.Close() may be called from
  122. // another goroutine.
  123. conn.mutex.Lock()
  124. // From this point, ensure conn.interruptible.socketFd is reset
  125. // since the fd value may be reused for a different file or socket
  126. // before Close() -- and interruptibleTCPClose() -- is called for
  127. // this conn.
  128. conn.interruptible.socketFd = _INVALID_FD // (requires mutex)
  129. // This is the syscall.Connect result
  130. if err != nil {
  131. conn.mutex.Unlock()
  132. return nil, ContextError(err)
  133. }
  134. // Convert the socket fd to a net.Conn
  135. file := os.NewFile(uintptr(socketFd), "")
  136. fileConn, err := net.FileConn(file)
  137. file.Close()
  138. // No more deferred fd clean up on err
  139. socketFd = _INVALID_FD
  140. if err != nil {
  141. conn.mutex.Unlock()
  142. return nil, ContextError(err)
  143. }
  144. conn.Conn = fileConn // (requires mutex)
  145. conn.mutex.Unlock()
  146. // Going through upstream HTTP proxy
  147. if config.UpstreamHttpProxyAddress != "" {
  148. // This call can be interrupted by closing the pending conn
  149. err := HttpProxyConnect(conn, addr)
  150. if err != nil {
  151. return nil, ContextError(err)
  152. }
  153. }
  154. return conn, nil
  155. }
  156. func interruptibleTCPClose(interruptible interruptibleTCPSocket) error {
  157. if interruptible.socketFd == _INVALID_FD {
  158. return nil
  159. }
  160. return syscall.Close(interruptible.socketFd)
  161. }