TCPConn_unix.go 4.9 KB

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