net.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. // TimeoutError implements the error interface
  73. type TimeoutError struct{}
  74. func (TimeoutError) Error() string { return "timed out" }
  75. func (TimeoutError) Timeout() bool { return true }
  76. func (TimeoutError) Temporary() bool { return true }
  77. // Dialer is a custom dialer compatible with http.Transport.Dial.
  78. type Dialer func(string, string) (net.Conn, error)
  79. // Conn is a net.Conn which supports sending a signal to a channel when
  80. // it is closed. In Psiphon, this interface is implemented by tunnel
  81. // connection types (DirectConn and MeekConn) and the close signal is
  82. // used as one trigger for tearing down the tunnel.
  83. type Conn interface {
  84. net.Conn
  85. // SetClosedSignal sets the channel which will be signaled
  86. // when the connection is closed. This function returns false
  87. // if the connection is already closed (and would never send
  88. // the signal). SetClosedSignal and Close may be called by
  89. // concurrent goroutines.
  90. SetClosedSignal(closedSignal chan struct{}) bool
  91. }
  92. // Conns is a synchronized list of Conns that is used to coordinate
  93. // interrupting a set of goroutines establishing connections, or
  94. // close a set of open connections, etc.
  95. // Once the list is closed, no more items may be added to the
  96. // list (unless it is reset).
  97. type Conns struct {
  98. mutex sync.Mutex
  99. isClosed bool
  100. conns map[net.Conn]bool
  101. }
  102. func (conns *Conns) Reset() {
  103. conns.mutex.Lock()
  104. defer conns.mutex.Unlock()
  105. conns.isClosed = false
  106. conns.conns = make(map[net.Conn]bool)
  107. }
  108. func (conns *Conns) Add(conn net.Conn) bool {
  109. conns.mutex.Lock()
  110. defer conns.mutex.Unlock()
  111. if conns.isClosed {
  112. return false
  113. }
  114. if conns.conns == nil {
  115. conns.conns = make(map[net.Conn]bool)
  116. }
  117. conns.conns[conn] = true
  118. return true
  119. }
  120. func (conns *Conns) Remove(conn net.Conn) {
  121. conns.mutex.Lock()
  122. defer conns.mutex.Unlock()
  123. delete(conns.conns, conn)
  124. }
  125. func (conns *Conns) CloseAll() {
  126. conns.mutex.Lock()
  127. defer conns.mutex.Unlock()
  128. conns.isClosed = true
  129. for conn, _ := range conns.conns {
  130. conn.Close()
  131. }
  132. conns.conns = make(map[net.Conn]bool)
  133. }
  134. // Relay sends to remoteConn bytes received from localConn,
  135. // and sends to localConn bytes received from remoteConn.
  136. func Relay(localConn, remoteConn net.Conn) {
  137. copyWaitGroup := new(sync.WaitGroup)
  138. copyWaitGroup.Add(1)
  139. go func() {
  140. defer copyWaitGroup.Done()
  141. _, err := io.Copy(localConn, remoteConn)
  142. if err != nil {
  143. NoticeAlert("Relay failed: %s", ContextError(err))
  144. }
  145. }()
  146. _, err := io.Copy(remoteConn, localConn)
  147. if err != nil {
  148. NoticeAlert("Relay failed: %s", ContextError(err))
  149. }
  150. copyWaitGroup.Wait()
  151. }
  152. // HttpProxyConnect establishes a HTTP CONNECT tunnel to addr through
  153. // an established network connection to an HTTP proxy. It is assumed that
  154. // no payload bytes have been sent through the connection to the proxy.
  155. func HttpProxyConnect(rawConn net.Conn, addr string) (err error) {
  156. hostname, _, err := net.SplitHostPort(addr)
  157. if err != nil {
  158. return ContextError(err)
  159. }
  160. // TODO: use the proxy request/response code from net/http/transport.go?
  161. connectRequest := fmt.Sprintf(
  162. "CONNECT %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\n\r\n",
  163. addr, hostname)
  164. _, err = rawConn.Write([]byte(connectRequest))
  165. if err != nil {
  166. return ContextError(err)
  167. }
  168. // Adapted from dialConn in net/http/transport.go:
  169. // Read response.
  170. // Okay to use and discard buffered reader here, because
  171. // TLS server will not speak until spoken to.
  172. response, err := http.ReadResponse(bufio.NewReader(rawConn), nil)
  173. if err != nil {
  174. return ContextError(err)
  175. }
  176. if response.StatusCode != 200 {
  177. return ContextError(errors.New(response.Status))
  178. }
  179. return nil
  180. }
  181. // WaitForNetworkConnectivity uses a NetworkConnectivityChecker to
  182. // periodically check for network connectivity. It returns true if
  183. // no NetworkConnectivityChecker is provided (waiting is disabled)
  184. // or if NetworkConnectivityChecker.HasNetworkConnectivity() indicates
  185. // connectivity. It polls the checker once a second. If a stop is
  186. // broadcast, false is returned.
  187. func WaitForNetworkConnectivity(
  188. connectivityChecker NetworkConnectivityChecker, stopBroadcast <-chan struct{}) bool {
  189. if connectivityChecker == nil || 1 == connectivityChecker.HasNetworkConnectivity() {
  190. return true
  191. }
  192. NoticeInfo("waiting for network connectivity")
  193. ticker := time.NewTicker(1 * time.Second)
  194. for {
  195. if 1 == connectivityChecker.HasNetworkConnectivity() {
  196. return true
  197. }
  198. select {
  199. case <-ticker.C:
  200. // Check again
  201. case <-stopBroadcast:
  202. return false
  203. }
  204. }
  205. }
  206. // ResolveIP uses a custom dns stack to make a DNS query over the
  207. // given TCP or UDP conn. This is used, e.g., when we need to ensure
  208. // that a DNS connection bypasses a VPN interface (BindToDevice) or
  209. // when we need to ensure that a DNS connection is tunneled.
  210. // Caller must set timeouts or interruptibility as required for conn.
  211. func ResolveIP(host string, conn net.Conn) (addrs []net.IP, ttls []time.Duration, err error) {
  212. // Send the DNS query
  213. dnsConn := &dns.Conn{Conn: conn}
  214. defer dnsConn.Close()
  215. query := new(dns.Msg)
  216. query.SetQuestion(dns.Fqdn(host), dns.TypeA)
  217. query.RecursionDesired = true
  218. dnsConn.WriteMsg(query)
  219. // Process the response
  220. response, err := dnsConn.ReadMsg()
  221. if err != nil {
  222. return nil, nil, ContextError(err)
  223. }
  224. addrs = make([]net.IP, 0)
  225. ttls = make([]time.Duration, 0)
  226. for _, answer := range response.Answer {
  227. if a, ok := answer.(*dns.A); ok {
  228. addrs = append(addrs, a.A)
  229. ttl := time.Duration(a.Hdr.Ttl) * time.Second
  230. ttls = append(ttls, ttl)
  231. }
  232. }
  233. return addrs, ttls, nil
  234. }