net.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * Copyright (c) 2016, 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 common
  20. import (
  21. "container/list"
  22. "context"
  23. "net"
  24. "net/http"
  25. "strconv"
  26. "sync"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  29. "github.com/miekg/dns"
  30. "github.com/wader/filtertransport"
  31. )
  32. // Dialer is a custom network dialer.
  33. type Dialer func(context.Context, string, string) (net.Conn, error)
  34. // NetDialer mimicks the net.Dialer interface.
  35. type NetDialer interface {
  36. Dial(network, address string) (net.Conn, error)
  37. DialContext(ctx context.Context, network, address string) (net.Conn, error)
  38. }
  39. // Closer defines the interface to a type, typically a net.Conn, that can be
  40. // closed.
  41. type Closer interface {
  42. IsClosed() bool
  43. }
  44. // CloseWriter defines the interface to a type, typically a net.TCPConn, that
  45. // implements CloseWrite.
  46. type CloseWriter interface {
  47. CloseWrite() error
  48. }
  49. // IrregularIndicator defines the interface for a type, typically a net.Conn,
  50. // that detects and reports irregular conditions during initial network
  51. // connection establishment.
  52. type IrregularIndicator interface {
  53. IrregularTunnelError() error
  54. }
  55. // UnderlyingTCPAddrSource defines the interface for a type, typically a
  56. // net.Conn, such as a server meek Conn, which has an underlying TCP conn(s),
  57. // providing access to the LocalAddr and RemoteAddr properties of the
  58. // underlying TCP conn.
  59. type UnderlyingTCPAddrSource interface {
  60. // GetUnderlyingTCPAddrs returns the LocalAddr and RemoteAddr properties of
  61. // the underlying TCP conn.
  62. GetUnderlyingTCPAddrs() (*net.TCPAddr, *net.TCPAddr, bool)
  63. }
  64. // FragmentorReplayAccessor defines the interface for accessing replay properties
  65. // of a fragmentor Conn.
  66. type FragmentorReplayAccessor interface {
  67. SetReplay(*prng.PRNG)
  68. GetReplay() (*prng.Seed, bool)
  69. }
  70. // HTTPRoundTripper is an adapter that allows using a function as a
  71. // http.RoundTripper.
  72. type HTTPRoundTripper struct {
  73. roundTrip func(*http.Request) (*http.Response, error)
  74. }
  75. // NewHTTPRoundTripper creates a new HTTPRoundTripper, using the specified
  76. // roundTrip function for HTTP round trips.
  77. func NewHTTPRoundTripper(
  78. roundTrip func(*http.Request) (*http.Response, error)) *HTTPRoundTripper {
  79. return &HTTPRoundTripper{roundTrip: roundTrip}
  80. }
  81. // RoundTrip implements http.RoundTripper RoundTrip.
  82. func (h HTTPRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
  83. return h.roundTrip(request)
  84. }
  85. // TerminateHTTPConnection sends a 404 response to a client and also closes
  86. // the persistent connection.
  87. func TerminateHTTPConnection(
  88. responseWriter http.ResponseWriter, request *http.Request) {
  89. responseWriter.Header().Set("Content-Length", "0")
  90. http.NotFound(responseWriter, request)
  91. hijack, ok := responseWriter.(http.Hijacker)
  92. if !ok {
  93. return
  94. }
  95. conn, buffer, err := hijack.Hijack()
  96. if err != nil {
  97. return
  98. }
  99. buffer.Flush()
  100. conn.Close()
  101. }
  102. // IPAddressFromAddr is a helper which extracts an IP address
  103. // from a net.Addr or returns "" if there is no IP address.
  104. func IPAddressFromAddr(addr net.Addr) string {
  105. ipAddress := ""
  106. if addr != nil {
  107. host, _, err := net.SplitHostPort(addr.String())
  108. if err == nil {
  109. ipAddress = host
  110. }
  111. }
  112. return ipAddress
  113. }
  114. // PortFromAddr is a helper which extracts a port number from a net.Addr or
  115. // returns 0 if there is no port number.
  116. func PortFromAddr(addr net.Addr) int {
  117. port := 0
  118. if addr != nil {
  119. _, portStr, err := net.SplitHostPort(addr.String())
  120. if err == nil {
  121. port, _ = strconv.Atoi(portStr)
  122. }
  123. }
  124. return port
  125. }
  126. // Conns is a synchronized list of Conns that is used to coordinate
  127. // interrupting a set of goroutines establishing connections, or
  128. // close a set of open connections, etc.
  129. // Once the list is closed, no more items may be added to the
  130. // list (unless it is reset).
  131. type Conns struct {
  132. mutex sync.Mutex
  133. isClosed bool
  134. conns map[net.Conn]bool
  135. }
  136. // NewConns initializes a new Conns.
  137. func NewConns() *Conns {
  138. return &Conns{}
  139. }
  140. func (conns *Conns) Reset() {
  141. conns.mutex.Lock()
  142. defer conns.mutex.Unlock()
  143. conns.isClosed = false
  144. conns.conns = make(map[net.Conn]bool)
  145. }
  146. func (conns *Conns) Add(conn net.Conn) bool {
  147. conns.mutex.Lock()
  148. defer conns.mutex.Unlock()
  149. if conns.isClosed {
  150. return false
  151. }
  152. if conns.conns == nil {
  153. conns.conns = make(map[net.Conn]bool)
  154. }
  155. conns.conns[conn] = true
  156. return true
  157. }
  158. func (conns *Conns) Remove(conn net.Conn) {
  159. conns.mutex.Lock()
  160. defer conns.mutex.Unlock()
  161. delete(conns.conns, conn)
  162. }
  163. func (conns *Conns) CloseAll() {
  164. conns.mutex.Lock()
  165. defer conns.mutex.Unlock()
  166. conns.isClosed = true
  167. for conn := range conns.conns {
  168. conn.Close()
  169. }
  170. conns.conns = make(map[net.Conn]bool)
  171. }
  172. // LRUConns is a concurrency-safe list of net.Conns ordered
  173. // by recent activity. Its purpose is to facilitate closing
  174. // the oldest connection in a set of connections.
  175. //
  176. // New connections added are referenced by a LRUConnsEntry,
  177. // which is used to Touch() active connections, which
  178. // promotes them to the front of the order and to Remove()
  179. // connections that are no longer LRU candidates.
  180. //
  181. // CloseOldest() will remove the oldest connection from the
  182. // list and call net.Conn.Close() on the connection.
  183. //
  184. // After an entry has been removed, LRUConnsEntry Touch()
  185. // and Remove() will have no effect.
  186. type LRUConns struct {
  187. mutex sync.Mutex
  188. list *list.List
  189. }
  190. // NewLRUConns initializes a new LRUConns.
  191. func NewLRUConns() *LRUConns {
  192. return &LRUConns{list: list.New()}
  193. }
  194. // Add inserts a net.Conn as the freshest connection
  195. // in a LRUConns and returns an LRUConnsEntry to be
  196. // used to freshen the connection or remove the connection
  197. // from the LRU list.
  198. func (conns *LRUConns) Add(conn net.Conn) *LRUConnsEntry {
  199. conns.mutex.Lock()
  200. defer conns.mutex.Unlock()
  201. return &LRUConnsEntry{
  202. lruConns: conns,
  203. element: conns.list.PushFront(conn),
  204. }
  205. }
  206. // CloseOldest closes the oldest connection in a
  207. // LRUConns. It calls net.Conn.Close() on the
  208. // connection.
  209. func (conns *LRUConns) CloseOldest() {
  210. conns.mutex.Lock()
  211. oldest := conns.list.Back()
  212. if oldest != nil {
  213. conns.list.Remove(oldest)
  214. }
  215. // Release mutex before closing conn
  216. conns.mutex.Unlock()
  217. if oldest != nil {
  218. oldest.Value.(net.Conn).Close()
  219. }
  220. }
  221. // LRUConnsEntry is an entry in a LRUConns list.
  222. type LRUConnsEntry struct {
  223. lruConns *LRUConns
  224. element *list.Element
  225. }
  226. // Remove deletes the connection referenced by the
  227. // LRUConnsEntry from the associated LRUConns.
  228. // Has no effect if the entry was not initialized
  229. // or previously removed.
  230. func (entry *LRUConnsEntry) Remove() {
  231. if entry.lruConns == nil || entry.element == nil {
  232. return
  233. }
  234. entry.lruConns.mutex.Lock()
  235. defer entry.lruConns.mutex.Unlock()
  236. entry.lruConns.list.Remove(entry.element)
  237. }
  238. // Touch promotes the connection referenced by the
  239. // LRUConnsEntry to the front of the associated LRUConns.
  240. // Has no effect if the entry was not initialized
  241. // or previously removed.
  242. func (entry *LRUConnsEntry) Touch() {
  243. if entry.lruConns == nil || entry.element == nil {
  244. return
  245. }
  246. entry.lruConns.mutex.Lock()
  247. defer entry.lruConns.mutex.Unlock()
  248. entry.lruConns.list.MoveToFront(entry.element)
  249. }
  250. // IsBogon checks if the specified IP is a bogon (loopback, private addresses,
  251. // link-local addresses, etc.)
  252. func IsBogon(IP net.IP) bool {
  253. return filtertransport.FindIPNet(
  254. filtertransport.DefaultFilteredNetworks, IP)
  255. }
  256. // ParseDNSQuestion parses a DNS message. When the message is a query,
  257. // the first question, a fully-qualified domain name, is returned.
  258. //
  259. // For other valid DNS messages, "" is returned. An error is returned only
  260. // for invalid DNS messages.
  261. //
  262. // Limitations:
  263. // - Only the first Question field is extracted.
  264. // - ParseDNSQuestion only functions for plaintext DNS and cannot
  265. // extract domains from DNS-over-TLS/HTTPS, etc.
  266. func ParseDNSQuestion(request []byte) (string, error) {
  267. m := new(dns.Msg)
  268. err := m.Unpack(request)
  269. if err != nil {
  270. return "", errors.Trace(err)
  271. }
  272. if len(m.Question) > 0 {
  273. return m.Question[0].Name, nil
  274. }
  275. return "", nil
  276. }