net.go 12 KB

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