TCPConn_bind.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. "errors"
  23. "fmt"
  24. "net"
  25. "os"
  26. "strconv"
  27. "syscall"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. )
  31. // tcpDial is the platform-specific part of interruptibleTCPDial
  32. //
  33. // To implement socket device binding, the lower-level syscall APIs are used.
  34. // The sequence of syscalls in this implementation are taken from:
  35. // https://code.google.com/p/go/issues/detail?id=6966
  36. func tcpDial(addr string, config *DialConfig, dialResult chan error) (net.Conn, error) {
  37. // Like interruption, this timeout doesn't stop this connection goroutine,
  38. // it just unblocks the calling interruptibleTCPDial.
  39. if config.ConnectTimeout != 0 {
  40. time.AfterFunc(config.ConnectTimeout, func() {
  41. select {
  42. case dialResult <- errors.New("connect timeout"):
  43. default:
  44. }
  45. })
  46. }
  47. // Get the remote IP and port, resolving a domain name if necessary
  48. host, strPort, err := net.SplitHostPort(addr)
  49. if err != nil {
  50. return nil, common.ContextError(err)
  51. }
  52. port, err := strconv.Atoi(strPort)
  53. if err != nil {
  54. return nil, common.ContextError(err)
  55. }
  56. ipAddrs, err := LookupIP(host, config)
  57. if err != nil {
  58. return nil, common.ContextError(err)
  59. }
  60. if len(ipAddrs) < 1 {
  61. return nil, common.ContextError(errors.New("no IP address"))
  62. }
  63. // Select an IP at random from the list, so we're not always
  64. // trying the same IP (when > 1) which may be blocked.
  65. // TODO: retry all IPs until one connects? For now, this retry
  66. // will happen on subsequent TCPDial calls, when a different IP
  67. // is selected.
  68. index, err := common.MakeSecureRandomInt(len(ipAddrs))
  69. if err != nil {
  70. return nil, common.ContextError(err)
  71. }
  72. var ipv4 [4]byte
  73. var ipv6 [16]byte
  74. var domain int
  75. ipAddr := ipAddrs[index]
  76. // Get address type (IPv4 or IPv6)
  77. if ipAddr != nil && ipAddr.To4() != nil {
  78. copy(ipv4[:], ipAddr.To4())
  79. domain = syscall.AF_INET
  80. } else if ipAddr != nil && ipAddr.To16() != nil {
  81. copy(ipv6[:], ipAddr.To16())
  82. domain = syscall.AF_INET6
  83. } else {
  84. return nil, common.ContextError(fmt.Errorf("Got invalid IP address: %s", ipAddr.String()))
  85. }
  86. // Create a socket and bind to device, when configured to do so
  87. socketFd, err := syscall.Socket(domain, syscall.SOCK_STREAM, 0)
  88. if err != nil {
  89. return nil, common.ContextError(err)
  90. }
  91. if config.DeviceBinder != nil {
  92. // WARNING: this potentially violates the direction to not call into
  93. // external components after the Controller may have been stopped.
  94. // TODO: rework DeviceBinder as an internal 'service' which can trap
  95. // external calls when they should not be made?
  96. err = config.DeviceBinder.BindToDevice(socketFd)
  97. if err != nil {
  98. syscall.Close(socketFd)
  99. return nil, common.ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  100. }
  101. }
  102. // Connect socket to the server's IP address
  103. if domain == syscall.AF_INET {
  104. sockAddr := syscall.SockaddrInet4{Addr: ipv4, Port: port}
  105. err = syscall.Connect(socketFd, &sockAddr)
  106. } else if domain == syscall.AF_INET6 {
  107. sockAddr := syscall.SockaddrInet6{Addr: ipv6, Port: port}
  108. err = syscall.Connect(socketFd, &sockAddr)
  109. }
  110. if err != nil {
  111. syscall.Close(socketFd)
  112. return nil, common.ContextError(err)
  113. }
  114. // Convert the socket fd to a net.Conn
  115. file := os.NewFile(uintptr(socketFd), "")
  116. netConn, err := net.FileConn(file) // net.FileConn() dups socketFd
  117. file.Close() // file.Close() closes socketFd
  118. if err != nil {
  119. return nil, common.ContextError(err)
  120. }
  121. return netConn, nil
  122. }