LookupIP.go 4.9 KB

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