LookupIP.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. // +build android linux darwin
  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. "syscall"
  27. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. )
  30. // LookupIP resolves a hostname. When BindToDevice is not required, it
  31. // simply uses net.LookupIP.
  32. // When BindToDevice is required, LookupIP explicitly creates a UDP
  33. // socket, binds it to the device, and makes an explicit DNS request
  34. // to the specified DNS resolver.
  35. func LookupIP(host string, config *DialConfig) (addrs []net.IP, err error) {
  36. // When the input host is an IP address, echo it back
  37. ipAddr := net.ParseIP(host)
  38. if ipAddr != nil {
  39. return []net.IP{ipAddr}, nil
  40. }
  41. if config.DeviceBinder != nil {
  42. addrs, err = bindLookupIP(host, config.DnsServerGetter.GetPrimaryDnsServer(), config)
  43. if err == nil {
  44. if len(addrs) == 0 {
  45. err = errors.New("empty address list")
  46. } else {
  47. return addrs, err
  48. }
  49. }
  50. NoticeAlert("retry resolve host %s: %s", host, err)
  51. dnsServer := config.DnsServerGetter.GetSecondaryDnsServer()
  52. if dnsServer == "" {
  53. return addrs, err
  54. }
  55. return bindLookupIP(host, dnsServer, config)
  56. }
  57. return net.LookupIP(host)
  58. }
  59. // bindLookupIP implements the BindToDevice LookupIP case.
  60. // To implement socket device binding, the lower-level syscall APIs are used.
  61. // The sequence of syscalls in this implementation are taken from:
  62. // https://code.google.com/p/go/issues/detail?id=6966
  63. func bindLookupIP(host, dnsServer string, config *DialConfig) (addrs []net.IP, err error) {
  64. // config.DnsServerGetter.GetDnsServers() must return IP addresses
  65. ipAddr := net.ParseIP(dnsServer)
  66. if ipAddr == nil {
  67. return nil, common.ContextError(errors.New("invalid IP address"))
  68. }
  69. // When configured, attempt to synthesize an IPv6 address from
  70. // an IPv4 address for compatibility on DNS64/NAT64 networks.
  71. // If synthesize fails, try the original address.
  72. if config.IPv6Synthesizer != nil && ipAddr.To4() != nil {
  73. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(dnsServer)
  74. if synthesizedIPAddress != "" {
  75. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  76. if synthesizedAddr != nil {
  77. ipAddr = synthesizedAddr
  78. }
  79. }
  80. }
  81. var ipv4 [4]byte
  82. var ipv6 [16]byte
  83. var domain int
  84. // Get address type (IPv4 or IPv6)
  85. if ipAddr.To4() != nil {
  86. copy(ipv4[:], ipAddr.To4())
  87. domain = syscall.AF_INET
  88. } else if ipAddr.To16() != nil {
  89. copy(ipv6[:], ipAddr.To16())
  90. domain = syscall.AF_INET6
  91. } else {
  92. return nil, common.ContextError(fmt.Errorf("invalid IP address for dns server: %s", ipAddr.String()))
  93. }
  94. socketFd, err := syscall.Socket(domain, syscall.SOCK_DGRAM, 0)
  95. if err != nil {
  96. return nil, common.ContextError(err)
  97. }
  98. err = config.DeviceBinder.BindToDevice(socketFd)
  99. if err != nil {
  100. syscall.Close(socketFd)
  101. return nil, common.ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  102. }
  103. // Connect socket to the server's IP address
  104. // Note: no timeout or interrupt for this connect, as it's a datagram socket
  105. if domain == syscall.AF_INET {
  106. sockAddr := syscall.SockaddrInet4{Addr: ipv4, Port: DNS_PORT}
  107. err = syscall.Connect(socketFd, &sockAddr)
  108. } else if domain == syscall.AF_INET6 {
  109. sockAddr := syscall.SockaddrInet6{Addr: ipv6, Port: DNS_PORT}
  110. err = syscall.Connect(socketFd, &sockAddr)
  111. }
  112. if err != nil {
  113. syscall.Close(socketFd)
  114. return nil, common.ContextError(err)
  115. }
  116. // Convert the syscall socket to a net.Conn, for use in the dns package
  117. file := os.NewFile(uintptr(socketFd), "")
  118. netConn, err := net.FileConn(file) // net.FileConn() dups socketFd
  119. file.Close() // file.Close() closes socketFd
  120. if err != nil {
  121. return nil, common.ContextError(err)
  122. }
  123. // Set DNS query timeouts, using the ConnectTimeout from the overall Dial
  124. if config.ConnectTimeout != 0 {
  125. netConn.SetReadDeadline(time.Now().Add(config.ConnectTimeout))
  126. netConn.SetWriteDeadline(time.Now().Add(config.ConnectTimeout))
  127. }
  128. addrs, _, err = ResolveIP(host, netConn)
  129. netConn.Close()
  130. if err != nil {
  131. return nil, common.ContextError(err)
  132. }
  133. return addrs, nil
  134. }