LookupIP.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. "context"
  23. std_errors "errors"
  24. "net"
  25. "os"
  26. "syscall"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. )
  29. // LookupIP resolves a hostname. When BindToDevice is not required, it
  30. // simply uses net.LookupIP.
  31. // When BindToDevice is required, LookupIP explicitly creates a UDP
  32. // socket, binds it to the device, and makes an explicit DNS request
  33. // to the specified DNS resolver.
  34. func LookupIP(ctx context.Context, host string, config *DialConfig) ([]net.IP, error) {
  35. ip := net.ParseIP(host)
  36. if ip != nil {
  37. return []net.IP{ip}, nil
  38. }
  39. if config.DeviceBinder != nil {
  40. dnsServer := config.DnsServerGetter.GetPrimaryDnsServer()
  41. ips, err := bindLookupIP(ctx, host, dnsServer, config)
  42. if err == nil {
  43. if len(ips) == 0 {
  44. err = std_errors.New("empty address list")
  45. } else {
  46. return ips, err
  47. }
  48. }
  49. dnsServer = config.DnsServerGetter.GetSecondaryDnsServer()
  50. if dnsServer == "" {
  51. return ips, err
  52. }
  53. if GetEmitNetworkParameters() {
  54. NoticeAlert("retry resolve host %s: %s", host, err)
  55. }
  56. return bindLookupIP(ctx, host, dnsServer, config)
  57. }
  58. addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
  59. // Remove domain names from "net" error messages.
  60. if err != nil && !GetEmitNetworkParameters() {
  61. err = RedactNetError(err)
  62. }
  63. if err != nil {
  64. return nil, errors.Trace(err)
  65. }
  66. ips := make([]net.IP, len(addrs))
  67. for i, addr := range addrs {
  68. ips[i] = addr.IP
  69. }
  70. return ips, nil
  71. }
  72. // bindLookupIP implements the BindToDevice LookupIP case.
  73. // To implement socket device binding, the lower-level syscall APIs are used.
  74. func bindLookupIP(
  75. ctx context.Context, host, dnsServer string, config *DialConfig) ([]net.IP, error) {
  76. // config.DnsServerGetter.GetDnsServers() must return IP addresses
  77. ipAddr := net.ParseIP(dnsServer)
  78. if ipAddr == nil {
  79. return nil, errors.TraceNew("invalid IP address")
  80. }
  81. // When configured, attempt to synthesize an IPv6 address from
  82. // an IPv4 address for compatibility on DNS64/NAT64 networks.
  83. // If synthesize fails, try the original address.
  84. if config.IPv6Synthesizer != nil && ipAddr.To4() != nil {
  85. synthesizedIPAddress := config.IPv6Synthesizer.IPv6Synthesize(dnsServer)
  86. if synthesizedIPAddress != "" {
  87. synthesizedAddr := net.ParseIP(synthesizedIPAddress)
  88. if synthesizedAddr != nil {
  89. ipAddr = synthesizedAddr
  90. }
  91. }
  92. }
  93. var ipv4 [4]byte
  94. var ipv6 [16]byte
  95. var domain int
  96. // Get address type (IPv4 or IPv6)
  97. if ipAddr.To4() != nil {
  98. copy(ipv4[:], ipAddr.To4())
  99. domain = syscall.AF_INET
  100. } else if ipAddr.To16() != nil {
  101. copy(ipv6[:], ipAddr.To16())
  102. domain = syscall.AF_INET6
  103. } else {
  104. return nil, errors.TraceNew("invalid IP address for DNS server")
  105. }
  106. socketFd, err := syscall.Socket(domain, syscall.SOCK_DGRAM, 0)
  107. if err != nil {
  108. return nil, errors.Trace(err)
  109. }
  110. _, err = config.DeviceBinder.BindToDevice(socketFd)
  111. if err != nil {
  112. syscall.Close(socketFd)
  113. return nil, errors.Tracef("BindToDevice failed with %s", err)
  114. }
  115. // Connect socket to the server's IP address
  116. // Note: no timeout or interrupt for this connect, as it's a datagram socket
  117. if domain == syscall.AF_INET {
  118. sockAddr := syscall.SockaddrInet4{Addr: ipv4, Port: DNS_PORT}
  119. err = syscall.Connect(socketFd, &sockAddr)
  120. } else if domain == syscall.AF_INET6 {
  121. sockAddr := syscall.SockaddrInet6{Addr: ipv6, Port: DNS_PORT}
  122. err = syscall.Connect(socketFd, &sockAddr)
  123. }
  124. if err != nil {
  125. syscall.Close(socketFd)
  126. return nil, errors.Trace(err)
  127. }
  128. // Convert the syscall socket to a net.Conn, for use in the dns package
  129. // This code block is from:
  130. // https://github.com/golang/go/issues/6966
  131. file := os.NewFile(uintptr(socketFd), "")
  132. netConn, err := net.FileConn(file) // net.FileConn() dups socketFd
  133. file.Close() // file.Close() closes socketFd
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. type resolveIPResult struct {
  138. ips []net.IP
  139. err error
  140. }
  141. resultChannel := make(chan resolveIPResult)
  142. go func() {
  143. ips, _, err := ResolveIP(host, netConn)
  144. netConn.Close()
  145. resultChannel <- resolveIPResult{ips: ips, err: err}
  146. }()
  147. var result resolveIPResult
  148. select {
  149. case result = <-resultChannel:
  150. case <-ctx.Done():
  151. result.err = ctx.Err()
  152. // Interrupt the goroutine
  153. netConn.Close()
  154. <-resultChannel
  155. }
  156. if result.err != nil {
  157. return nil, errors.Trace(err)
  158. }
  159. return result.ips, nil
  160. }