net.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  30. "github.com/miekg/dns"
  31. "github.com/wader/filtertransport"
  32. )
  33. // Dialer is a custom network dialer.
  34. type Dialer func(context.Context, string, string) (net.Conn, error)
  35. // NetDialer mimicks the net.Dialer interface.
  36. type NetDialer interface {
  37. Dial(network, address string) (net.Conn, error)
  38. DialContext(ctx context.Context, network, address string) (net.Conn, error)
  39. }
  40. // Closer defines the interface to a type, typically a net.Conn, that can be
  41. // closed.
  42. type Closer interface {
  43. IsClosed() bool
  44. }
  45. // CloseWriter defines the interface to a type, typically a net.TCPConn, that
  46. // implements CloseWrite.
  47. type CloseWriter interface {
  48. CloseWrite() error
  49. }
  50. // IrregularIndicator defines the interface for a type, typically a net.Conn,
  51. // that detects and reports irregular conditions during initial network
  52. // connection establishment.
  53. type IrregularIndicator interface {
  54. IrregularTunnelError() error
  55. }
  56. // UnderlyingTCPAddrSource defines the interface for a type, typically a
  57. // net.Conn, such as a server meek Conn, which has an underlying TCP conn(s),
  58. // providing access to the LocalAddr and RemoteAddr properties of the
  59. // underlying TCP conn.
  60. type UnderlyingTCPAddrSource interface {
  61. // GetUnderlyingTCPAddrs returns the LocalAddr and RemoteAddr properties of
  62. // the underlying TCP conn.
  63. GetUnderlyingTCPAddrs() (*net.TCPAddr, *net.TCPAddr, bool)
  64. }
  65. // FragmentorAccessor defines the interface for accessing properties
  66. // of a fragmentor Conn.
  67. type FragmentorAccessor interface {
  68. SetReplay(*prng.PRNG)
  69. GetReplay() (*prng.Seed, bool)
  70. StopFragmenting()
  71. }
  72. // HTTPRoundTripper is an adapter that allows using a function as a
  73. // http.RoundTripper.
  74. type HTTPRoundTripper struct {
  75. roundTrip func(*http.Request) (*http.Response, error)
  76. }
  77. // NewHTTPRoundTripper creates a new HTTPRoundTripper, using the specified
  78. // roundTrip function for HTTP round trips.
  79. func NewHTTPRoundTripper(
  80. roundTrip func(*http.Request) (*http.Response, error)) *HTTPRoundTripper {
  81. return &HTTPRoundTripper{roundTrip: roundTrip}
  82. }
  83. // RoundTrip implements http.RoundTripper RoundTrip.
  84. func (h HTTPRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
  85. return h.roundTrip(request)
  86. }
  87. // TerminateHTTPConnection sends a 404 response to a client and also closes
  88. // the persistent connection.
  89. func TerminateHTTPConnection(
  90. responseWriter http.ResponseWriter, request *http.Request) {
  91. responseWriter.Header().Set("Content-Length", "0")
  92. http.NotFound(responseWriter, request)
  93. hijack, ok := responseWriter.(http.Hijacker)
  94. if !ok {
  95. return
  96. }
  97. conn, buffer, err := hijack.Hijack()
  98. if err != nil {
  99. return
  100. }
  101. buffer.Flush()
  102. conn.Close()
  103. }
  104. // IPAddressFromAddr is a helper which extracts an IP address
  105. // from a net.Addr or returns "" if there is no IP address.
  106. func IPAddressFromAddr(addr net.Addr) string {
  107. ipAddress := ""
  108. if addr != nil {
  109. host, _, err := net.SplitHostPort(addr.String())
  110. if err == nil {
  111. ipAddress = host
  112. }
  113. }
  114. return ipAddress
  115. }
  116. // PortFromAddr is a helper which extracts a port number from a net.Addr or
  117. // returns 0 if there is no port number.
  118. func PortFromAddr(addr net.Addr) int {
  119. port := 0
  120. if addr != nil {
  121. _, portStr, err := net.SplitHostPort(addr.String())
  122. if err == nil {
  123. port, _ = strconv.Atoi(portStr)
  124. }
  125. }
  126. return port
  127. }
  128. // Conns is a synchronized list of Conns that is used to coordinate
  129. // interrupting a set of goroutines establishing connections, or
  130. // close a set of open connections, etc.
  131. // Once the list is closed, no more items may be added to the
  132. // list (unless it is reset).
  133. type Conns struct {
  134. mutex sync.Mutex
  135. isClosed bool
  136. conns map[net.Conn]bool
  137. }
  138. // NewConns initializes a new Conns.
  139. func NewConns() *Conns {
  140. return &Conns{}
  141. }
  142. func (conns *Conns) Reset() {
  143. conns.mutex.Lock()
  144. defer conns.mutex.Unlock()
  145. conns.isClosed = false
  146. conns.conns = make(map[net.Conn]bool)
  147. }
  148. func (conns *Conns) Add(conn net.Conn) bool {
  149. conns.mutex.Lock()
  150. defer conns.mutex.Unlock()
  151. if conns.isClosed {
  152. return false
  153. }
  154. if conns.conns == nil {
  155. conns.conns = make(map[net.Conn]bool)
  156. }
  157. conns.conns[conn] = true
  158. return true
  159. }
  160. func (conns *Conns) Remove(conn net.Conn) {
  161. conns.mutex.Lock()
  162. defer conns.mutex.Unlock()
  163. delete(conns.conns, conn)
  164. }
  165. func (conns *Conns) CloseAll() {
  166. conns.mutex.Lock()
  167. defer conns.mutex.Unlock()
  168. conns.isClosed = true
  169. for conn := range conns.conns {
  170. conn.Close()
  171. }
  172. conns.conns = make(map[net.Conn]bool)
  173. }
  174. // LRUConns is a concurrency-safe list of net.Conns ordered
  175. // by recent activity. Its purpose is to facilitate closing
  176. // the oldest connection in a set of connections.
  177. //
  178. // New connections added are referenced by a LRUConnsEntry,
  179. // which is used to Touch() active connections, which
  180. // promotes them to the front of the order and to Remove()
  181. // connections that are no longer LRU candidates.
  182. //
  183. // CloseOldest() will remove the oldest connection from the
  184. // list and call net.Conn.Close() on the connection.
  185. //
  186. // After an entry has been removed, LRUConnsEntry Touch()
  187. // and Remove() will have no effect.
  188. type LRUConns struct {
  189. mutex sync.Mutex
  190. list *list.List
  191. }
  192. // NewLRUConns initializes a new LRUConns.
  193. func NewLRUConns() *LRUConns {
  194. return &LRUConns{list: list.New()}
  195. }
  196. // Add inserts a net.Conn as the freshest connection
  197. // in a LRUConns and returns an LRUConnsEntry to be
  198. // used to freshen the connection or remove the connection
  199. // from the LRU list.
  200. func (conns *LRUConns) Add(conn net.Conn) *LRUConnsEntry {
  201. conns.mutex.Lock()
  202. defer conns.mutex.Unlock()
  203. return &LRUConnsEntry{
  204. lruConns: conns,
  205. element: conns.list.PushFront(conn),
  206. }
  207. }
  208. // CloseOldest closes the oldest connection in a
  209. // LRUConns. It calls net.Conn.Close() on the
  210. // connection.
  211. func (conns *LRUConns) CloseOldest() {
  212. conns.mutex.Lock()
  213. oldest := conns.list.Back()
  214. if oldest != nil {
  215. conns.list.Remove(oldest)
  216. }
  217. // Release mutex before closing conn
  218. conns.mutex.Unlock()
  219. if oldest != nil {
  220. oldest.Value.(net.Conn).Close()
  221. }
  222. }
  223. // LRUConnsEntry is an entry in a LRUConns list.
  224. type LRUConnsEntry struct {
  225. lruConns *LRUConns
  226. element *list.Element
  227. }
  228. // Remove deletes the connection referenced by the
  229. // LRUConnsEntry from the associated LRUConns.
  230. // Has no effect if the entry was not initialized
  231. // or previously removed.
  232. func (entry *LRUConnsEntry) Remove() {
  233. if entry.lruConns == nil || entry.element == nil {
  234. return
  235. }
  236. entry.lruConns.mutex.Lock()
  237. defer entry.lruConns.mutex.Unlock()
  238. entry.lruConns.list.Remove(entry.element)
  239. }
  240. // Touch promotes the connection referenced by the
  241. // LRUConnsEntry to the front of the associated LRUConns.
  242. // Has no effect if the entry was not initialized
  243. // or previously removed.
  244. func (entry *LRUConnsEntry) Touch() {
  245. if entry.lruConns == nil || entry.element == nil {
  246. return
  247. }
  248. entry.lruConns.mutex.Lock()
  249. defer entry.lruConns.mutex.Unlock()
  250. entry.lruConns.list.MoveToFront(entry.element)
  251. }
  252. // IsBogon checks if the specified IP is a bogon (loopback, private addresses,
  253. // link-local addresses, etc.)
  254. func IsBogon(IP net.IP) bool {
  255. return filtertransport.FindIPNet(
  256. filtertransport.DefaultFilteredNetworks, IP)
  257. }
  258. // ParseDNSQuestion parses a DNS message. When the message is a query,
  259. // the first question, a fully-qualified domain name, is returned.
  260. //
  261. // For other valid DNS messages, "" is returned. An error is returned only
  262. // for invalid DNS messages.
  263. //
  264. // Limitations:
  265. // - Only the first Question field is extracted.
  266. // - ParseDNSQuestion only functions for plaintext DNS and cannot
  267. // extract domains from DNS-over-TLS/HTTPS, etc.
  268. func ParseDNSQuestion(request []byte) (string, error) {
  269. m := new(dns.Msg)
  270. err := m.Unpack(request)
  271. if err != nil {
  272. return "", errors.Trace(err)
  273. }
  274. if len(m.Question) > 0 {
  275. return m.Question[0].Name, nil
  276. }
  277. return "", nil
  278. }
  279. // WriteTimeoutUDPConn sets write deadlines before each UDP packet write.
  280. //
  281. // Generally, a UDP packet write doesn't block. However, Go's
  282. // internal/poll.FD.WriteMsg continues to loop when syscall.SendmsgN fails
  283. // with EAGAIN, which indicates that an OS socket buffer is currently full;
  284. // in certain OS states this may cause WriteMsgUDP/etc. to block
  285. // indefinitely. In this scenario, we want to instead behave as if the packet
  286. // were dropped, so we set a write deadline which will eventually interrupt
  287. // any EAGAIN loop.
  288. type WriteTimeoutUDPConn struct {
  289. *net.UDPConn
  290. }
  291. func (conn *WriteTimeoutUDPConn) Write(b []byte) (int, error) {
  292. err := conn.SetWriteDeadline(time.Now().Add(UDP_PACKET_WRITE_TIMEOUT))
  293. if err != nil {
  294. return 0, errors.Trace(err)
  295. }
  296. // Do not wrap any I/O err returned by udpConn
  297. return conn.UDPConn.Write(b)
  298. }
  299. func (conn *WriteTimeoutUDPConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (int, int, error) {
  300. err := conn.SetWriteDeadline(time.Now().Add(UDP_PACKET_WRITE_TIMEOUT))
  301. if err != nil {
  302. return 0, 0, errors.Trace(err)
  303. }
  304. // Do not wrap any I/O err returned by udpConn
  305. return conn.UDPConn.WriteMsgUDP(b, oob, addr)
  306. }
  307. func (conn *WriteTimeoutUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
  308. err := conn.SetWriteDeadline(time.Now().Add(UDP_PACKET_WRITE_TIMEOUT))
  309. if err != nil {
  310. return 0, errors.Trace(err)
  311. }
  312. // Do not wrap any I/O err returned by udpConn
  313. return conn.UDPConn.WriteTo(b, addr)
  314. }
  315. func (conn *WriteTimeoutUDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) {
  316. err := conn.SetWriteDeadline(time.Now().Add(UDP_PACKET_WRITE_TIMEOUT))
  317. if err != nil {
  318. return 0, errors.Trace(err)
  319. }
  320. // Do not wrap any I/O err returned by udpConn
  321. return conn.UDPConn.WriteToUDP(b, addr)
  322. }
  323. // WriteTimeoutPacketConn is the equivilent of WriteTimeoutUDPConn for
  324. // non-*net.UDPConns.
  325. type WriteTimeoutPacketConn struct {
  326. net.PacketConn
  327. }
  328. const UDP_PACKET_WRITE_TIMEOUT = 1 * time.Second
  329. func (conn *WriteTimeoutPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
  330. err := conn.SetWriteDeadline(time.Now().Add(UDP_PACKET_WRITE_TIMEOUT))
  331. if err != nil {
  332. return 0, errors.Trace(err)
  333. }
  334. // Do not wrap any I/O err returned by udpConn
  335. return conn.PacketConn.WriteTo(b, addr)
  336. }