LookupIP.go 5.1 KB

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