net.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bufio"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net"
  26. "net/http"
  27. "sync"
  28. "time"
  29. "github.com/Psiphon-Inc/dns"
  30. )
  31. const DNS_PORT = 53
  32. // DialConfig contains parameters to determine the behavior
  33. // of a Psiphon dialer (TCPDial, MeekDial, etc.)
  34. type DialConfig struct {
  35. // UpstreamHttpProxyAddress specifies an HTTP proxy to connect through
  36. // (the proxy must support HTTP CONNECT). The address may be a hostname
  37. // or IP address and must include a port number.
  38. UpstreamHttpProxyAddress string
  39. ConnectTimeout time.Duration
  40. ReadTimeout time.Duration
  41. WriteTimeout time.Duration
  42. // PendingConns is used to interrupt dials in progress.
  43. // The dial may be interrupted using PendingConns.CloseAll(): on platforms
  44. // that support this, the new conn is added to pendingConns before the network
  45. // connect begins and removed from pendingConns once the connect succeeds or fails.
  46. PendingConns *Conns
  47. // BindToDevice parameters are used to exclude connections and
  48. // associated DNS requests from VPN routing.
  49. // When DeviceBinder is set, any underlying socket is
  50. // submitted to the device binding servicebefore connecting.
  51. // The service should bind the socket to a device so that it doesn't route
  52. // through a VPN interface. This service is also used to bind UDP sockets used
  53. // for DNS requests, in which case DnsServerGetter is used to get the
  54. // current active untunneled network DNS server.
  55. DeviceBinder DeviceBinder
  56. DnsServerGetter DnsServerGetter
  57. }
  58. // DeviceBinder defines the interface to the external BindToDevice provider
  59. type DeviceBinder interface {
  60. BindToDevice(fileDescriptor int) error
  61. }
  62. // NetworkConnectivityChecker defines the interface to the external
  63. // HasNetworkConnectivity provider
  64. type NetworkConnectivityChecker interface {
  65. // TODO: change to bool return value once gobind supports that type
  66. HasNetworkConnectivity() int
  67. }
  68. // DnsServerGetter defines the interface to the external GetDnsServer provider
  69. type DnsServerGetter interface {
  70. GetDnsServer() string
  71. }
  72. // Dialer is a custom dialer compatible with http.Transport.Dial.
  73. type Dialer func(string, string) (net.Conn, error)
  74. // Conn is a net.Conn which supports sending a signal to a channel when
  75. // it is closed. In Psiphon, this interface is implemented by tunnel
  76. // connection types (DirectConn and MeekConn) and the close signal is
  77. // used as one trigger for tearing down the tunnel.
  78. type Conn interface {
  79. net.Conn
  80. // SetClosedSignal sets the channel which will be signaled
  81. // when the connection is closed. This function returns false
  82. // if the connection is already closed (and would never send
  83. // the signal). SetClosedSignal and Close may be called by
  84. // concurrent goroutines.
  85. SetClosedSignal(closedSignal chan struct{}) bool
  86. }
  87. // Conns is a synchronized list of Conns that is used to coordinate
  88. // interrupting a set of goroutines establishing connections, or
  89. // close a set of open connections, etc.
  90. // Once the list is closed, no more items may be added to the
  91. // list (unless it is reset).
  92. type Conns struct {
  93. mutex sync.Mutex
  94. isClosed bool
  95. conns map[net.Conn]bool
  96. }
  97. func (conns *Conns) Reset() {
  98. conns.mutex.Lock()
  99. defer conns.mutex.Unlock()
  100. conns.isClosed = false
  101. conns.conns = make(map[net.Conn]bool)
  102. }
  103. func (conns *Conns) Add(conn net.Conn) bool {
  104. conns.mutex.Lock()
  105. defer conns.mutex.Unlock()
  106. if conns.isClosed {
  107. return false
  108. }
  109. if conns.conns == nil {
  110. conns.conns = make(map[net.Conn]bool)
  111. }
  112. conns.conns[conn] = true
  113. return true
  114. }
  115. func (conns *Conns) Remove(conn net.Conn) {
  116. conns.mutex.Lock()
  117. defer conns.mutex.Unlock()
  118. delete(conns.conns, conn)
  119. }
  120. func (conns *Conns) CloseAll() {
  121. conns.mutex.Lock()
  122. defer conns.mutex.Unlock()
  123. conns.isClosed = true
  124. for conn, _ := range conns.conns {
  125. conn.Close()
  126. }
  127. conns.conns = make(map[net.Conn]bool)
  128. }
  129. // Relay sends to remoteConn bytes received from localConn,
  130. // and sends to localConn bytes received from remoteConn.
  131. func Relay(localConn, remoteConn net.Conn) {
  132. copyWaitGroup := new(sync.WaitGroup)
  133. copyWaitGroup.Add(1)
  134. go func() {
  135. defer copyWaitGroup.Done()
  136. _, err := io.Copy(localConn, remoteConn)
  137. if err != nil {
  138. NoticeAlert("Relay failed: %s", ContextError(err))
  139. }
  140. }()
  141. _, err := io.Copy(remoteConn, localConn)
  142. if err != nil {
  143. NoticeAlert("Relay failed: %s", ContextError(err))
  144. }
  145. copyWaitGroup.Wait()
  146. }
  147. // HttpProxyConnect establishes a HTTP CONNECT tunnel to addr through
  148. // an established network connection to an HTTP proxy. It is assumed that
  149. // no payload bytes have been sent through the connection to the proxy.
  150. func HttpProxyConnect(rawConn net.Conn, addr string) (err error) {
  151. hostname, _, err := net.SplitHostPort(addr)
  152. if err != nil {
  153. return ContextError(err)
  154. }
  155. // TODO: use the proxy request/response code from net/http/transport.go?
  156. connectRequest := fmt.Sprintf(
  157. "CONNECT %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\n\r\n",
  158. addr, hostname)
  159. _, err = rawConn.Write([]byte(connectRequest))
  160. if err != nil {
  161. return ContextError(err)
  162. }
  163. // Adapted from dialConn in net/http/transport.go:
  164. // Read response.
  165. // Okay to use and discard buffered reader here, because
  166. // TLS server will not speak until spoken to.
  167. response, err := http.ReadResponse(bufio.NewReader(rawConn), nil)
  168. if err != nil {
  169. return ContextError(err)
  170. }
  171. if response.StatusCode != 200 {
  172. return ContextError(errors.New(response.Status))
  173. }
  174. return nil
  175. }
  176. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  177. // periodically check for network connectivity. It returns true if
  178. // no NetworkConnectivityChecker is provided (waiting is disabled)
  179. // or if NetworkConnectivityChecker.HasNetworkConnectivity() indicates
  180. // connectivity. It polls the checker once a second. If a stop is
  181. // broadcast, false is returned.
  182. func WaitForNetworkConnectivity(
  183. connectivityChecker NetworkConnectivityChecker, stopBroadcast <-chan struct{}) bool {
  184. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  185. return true
  186. }
  187. NoticeInfo("waiting for network connectivity")
  188. ticker := time.NewTicker(1 * time.Second)
  189. for {
  190. if 1 == connectivityChecker.HasNetworkConnectivity() {
  191. return true
  192. }
  193. select {
  194. case <-ticker.C:
  195. // Check again
  196. case <-stopBroadcast:
  197. return false
  198. }
  199. }
  200. }
  201. // ResolveIP uses a custom dns stack to make a DNS query over the
  202. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  203. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  204. // when we need to ensure that a DNS connection is tunneled.
  205. // Caller must set timeouts or interruptibility as required for conn.
  206. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  207. // Send the DNS query
  208. dnsConn := &dns.Conn{Conn: conn}
  209. defer dnsConn.Close()
  210. query := new(dns.Msg)
  211. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  212. query.RecursionDesired = true
  213. dnsConn.WriteMsg(query)
  214. // Process the response
  215. response, err := dnsConn.ReadMsg()
  216. if err != nil {
  217. return nil, nil, ContextError(err)
  218. }
  219. addrs = make([]net.IP, 0)
  220. ttls = make([]time.Duration, 0)
  221. for _, answer := range response.Answer {
  222. if a, ok := answer.(*dns.A); ok {
  223. addrs = append(addrs, a.A)
  224. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  225. ttls = append(ttls, ttl)
  226. }
  227. }
  228. return addrs, ttls, nil
  229. }