net.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. "sync/atomic"
  28. "time"
  29. "github.com/Psiphon-Labs/goarista/monotime"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  31. "github.com/miekg/dns"
  32. "github.com/wader/filtertransport"
  33. )
  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. // TerminateHTTPConnection sends a 404 response to a client and also closes
  56. // the persistent connection.
  57. func TerminateHTTPConnection(
  58. responseWriter http.ResponseWriter, request *http.Request) {
  59. http.NotFound(responseWriter, request)
  60. hijack, ok := responseWriter.(http.Hijacker)
  61. if !ok {
  62. return
  63. }
  64. conn, buffer, err := hijack.Hijack()
  65. if err != nil {
  66. return
  67. }
  68. buffer.Flush()
  69. conn.Close()
  70. }
  71. // IPAddressFromAddr is a helper which extracts an IP address
  72. // from a net.Addr or returns "" if there is no IP address.
  73. func IPAddressFromAddr(addr net.Addr) string {
  74. ipAddress := ""
  75. if addr != nil {
  76. host, _, err := net.SplitHostPort(addr.String())
  77. if err == nil {
  78. ipAddress = host
  79. }
  80. }
  81. return ipAddress
  82. }
  83. // PortFromAddr is a helper which extracts a port number from a net.Addr or
  84. // returns 0 if there is no port number.
  85. func PortFromAddr(addr net.Addr) int {
  86. port := 0
  87. if addr != nil {
  88. _, portStr, err := net.SplitHostPort(addr.String())
  89. if err == nil {
  90. port, _ = strconv.Atoi(portStr)
  91. }
  92. }
  93. return port
  94. }
  95. // Conns is a synchronized list of Conns that is used to coordinate
  96. // interrupting a set of goroutines establishing connections, or
  97. // close a set of open connections, etc.
  98. // Once the list is closed, no more items may be added to the
  99. // list (unless it is reset).
  100. type Conns struct {
  101. mutex sync.Mutex
  102. isClosed bool
  103. conns map[net.Conn]bool
  104. }
  105. // NewConns initializes a new Conns.
  106. func NewConns() *Conns {
  107. return &Conns{}
  108. }
  109. func (conns *Conns) Reset() {
  110. conns.mutex.Lock()
  111. defer conns.mutex.Unlock()
  112. conns.isClosed = false
  113. conns.conns = make(map[net.Conn]bool)
  114. }
  115. func (conns *Conns) Add(conn net.Conn) bool {
  116. conns.mutex.Lock()
  117. defer conns.mutex.Unlock()
  118. if conns.isClosed {
  119. return false
  120. }
  121. if conns.conns == nil {
  122. conns.conns = make(map[net.Conn]bool)
  123. }
  124. conns.conns[conn] = true
  125. return true
  126. }
  127. func (conns *Conns) Remove(conn net.Conn) {
  128. conns.mutex.Lock()
  129. defer conns.mutex.Unlock()
  130. delete(conns.conns, conn)
  131. }
  132. func (conns *Conns) CloseAll() {
  133. conns.mutex.Lock()
  134. defer conns.mutex.Unlock()
  135. conns.isClosed = true
  136. for conn := range conns.conns {
  137. conn.Close()
  138. }
  139. conns.conns = make(map[net.Conn]bool)
  140. }
  141. // LRUConns is a concurrency-safe list of net.Conns ordered
  142. // by recent activity. Its purpose is to facilitate closing
  143. // the oldest connection in a set of connections.
  144. //
  145. // New connections added are referenced by a LRUConnsEntry,
  146. // which is used to Touch() active connections, which
  147. // promotes them to the front of the order and to Remove()
  148. // connections that are no longer LRU candidates.
  149. //
  150. // CloseOldest() will remove the oldest connection from the
  151. // list and call net.Conn.Close() on the connection.
  152. //
  153. // After an entry has been removed, LRUConnsEntry Touch()
  154. // and Remove() will have no effect.
  155. type LRUConns struct {
  156. mutex sync.Mutex
  157. list *list.List
  158. }
  159. // NewLRUConns initializes a new LRUConns.
  160. func NewLRUConns() *LRUConns {
  161. return &LRUConns{list: list.New()}
  162. }
  163. // Add inserts a net.Conn as the freshest connection
  164. // in a LRUConns and returns an LRUConnsEntry to be
  165. // used to freshen the connection or remove the connection
  166. // from the LRU list.
  167. func (conns *LRUConns) Add(conn net.Conn) *LRUConnsEntry {
  168. conns.mutex.Lock()
  169. defer conns.mutex.Unlock()
  170. return &LRUConnsEntry{
  171. lruConns: conns,
  172. element: conns.list.PushFront(conn),
  173. }
  174. }
  175. // CloseOldest closes the oldest connection in a
  176. // LRUConns. It calls net.Conn.Close() on the
  177. // connection.
  178. func (conns *LRUConns) CloseOldest() {
  179. conns.mutex.Lock()
  180. oldest := conns.list.Back()
  181. if oldest != nil {
  182. conns.list.Remove(oldest)
  183. }
  184. // Release mutex before closing conn
  185. conns.mutex.Unlock()
  186. if oldest != nil {
  187. oldest.Value.(net.Conn).Close()
  188. }
  189. }
  190. // LRUConnsEntry is an entry in a LRUConns list.
  191. type LRUConnsEntry struct {
  192. lruConns *LRUConns
  193. element *list.Element
  194. }
  195. // Remove deletes the connection referenced by the
  196. // LRUConnsEntry from the associated LRUConns.
  197. // Has no effect if the entry was not initialized
  198. // or previously removed.
  199. func (entry *LRUConnsEntry) Remove() {
  200. if entry.lruConns == nil || entry.element == nil {
  201. return
  202. }
  203. entry.lruConns.mutex.Lock()
  204. defer entry.lruConns.mutex.Unlock()
  205. entry.lruConns.list.Remove(entry.element)
  206. }
  207. // Touch promotes the connection referenced by the
  208. // LRUConnsEntry to the front of the associated LRUConns.
  209. // Has no effect if the entry was not initialized
  210. // or previously removed.
  211. func (entry *LRUConnsEntry) Touch() {
  212. if entry.lruConns == nil || entry.element == nil {
  213. return
  214. }
  215. entry.lruConns.mutex.Lock()
  216. defer entry.lruConns.mutex.Unlock()
  217. entry.lruConns.list.MoveToFront(entry.element)
  218. }
  219. // ActivityMonitoredConn wraps a net.Conn, adding logic to deal with
  220. // events triggered by I/O activity.
  221. //
  222. // When an inactivity timeout is specified, the network I/O will
  223. // timeout after the specified period of read inactivity. Optionally,
  224. // for the purpose of inactivity only, ActivityMonitoredConn will also
  225. // consider the connection active when data is written to it.
  226. //
  227. // When a LRUConnsEntry is specified, then the LRU entry is promoted on
  228. // either a successful read or write.
  229. //
  230. // When an ActivityUpdater is set, then its UpdateActivity method is
  231. // called on each read and write with the number of bytes transferred.
  232. // The durationNanoseconds, which is the time since the last read, is
  233. // reported only on reads.
  234. //
  235. type ActivityMonitoredConn struct {
  236. // Note: 64-bit ints used with atomic operations are placed
  237. // at the start of struct to ensure 64-bit alignment.
  238. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  239. monotonicStartTime int64
  240. lastReadActivityTime int64
  241. realStartTime time.Time
  242. net.Conn
  243. inactivityTimeout time.Duration
  244. activeOnWrite bool
  245. activityUpdater ActivityUpdater
  246. lruEntry *LRUConnsEntry
  247. }
  248. // ActivityUpdater defines an interface for receiving updates for
  249. // ActivityMonitoredConn activity. Values passed to UpdateProgress are
  250. // bytes transferred and conn duration since the previous UpdateProgress.
  251. type ActivityUpdater interface {
  252. UpdateProgress(bytesRead, bytesWritten int64, durationNanoseconds int64)
  253. }
  254. // NewActivityMonitoredConn creates a new ActivityMonitoredConn.
  255. func NewActivityMonitoredConn(
  256. conn net.Conn,
  257. inactivityTimeout time.Duration,
  258. activeOnWrite bool,
  259. activityUpdater ActivityUpdater,
  260. lruEntry *LRUConnsEntry) (*ActivityMonitoredConn, error) {
  261. if inactivityTimeout > 0 {
  262. err := conn.SetDeadline(time.Now().Add(inactivityTimeout))
  263. if err != nil {
  264. return nil, errors.Trace(err)
  265. }
  266. }
  267. now := int64(monotime.Now())
  268. return &ActivityMonitoredConn{
  269. Conn: conn,
  270. inactivityTimeout: inactivityTimeout,
  271. activeOnWrite: activeOnWrite,
  272. realStartTime: time.Now(),
  273. monotonicStartTime: now,
  274. lastReadActivityTime: now,
  275. activityUpdater: activityUpdater,
  276. lruEntry: lruEntry,
  277. }, nil
  278. }
  279. // GetStartTime gets the time when the ActivityMonitoredConn was
  280. // initialized. Reported time is UTC.
  281. func (conn *ActivityMonitoredConn) GetStartTime() time.Time {
  282. return conn.realStartTime.UTC()
  283. }
  284. // GetActiveDuration returns the time elapsed between the initialization
  285. // of the ActivityMonitoredConn and the last Read. Only reads are used
  286. // for this calculation since writes may succeed locally due to buffering.
  287. func (conn *ActivityMonitoredConn) GetActiveDuration() time.Duration {
  288. return time.Duration(atomic.LoadInt64(&conn.lastReadActivityTime) - conn.monotonicStartTime)
  289. }
  290. // GetLastActivityMonotime returns the arbitrary monotonic time of the last Read.
  291. func (conn *ActivityMonitoredConn) GetLastActivityMonotime() monotime.Time {
  292. return monotime.Time(atomic.LoadInt64(&conn.lastReadActivityTime))
  293. }
  294. func (conn *ActivityMonitoredConn) Read(buffer []byte) (int, error) {
  295. n, err := conn.Conn.Read(buffer)
  296. if err == nil {
  297. if conn.inactivityTimeout > 0 {
  298. err = conn.Conn.SetDeadline(time.Now().Add(conn.inactivityTimeout))
  299. if err != nil {
  300. return n, errors.Trace(err)
  301. }
  302. }
  303. readActivityTime := int64(monotime.Now())
  304. if conn.activityUpdater != nil {
  305. conn.activityUpdater.UpdateProgress(
  306. int64(n), 0, readActivityTime-atomic.LoadInt64(&conn.lastReadActivityTime))
  307. }
  308. if conn.lruEntry != nil {
  309. conn.lruEntry.Touch()
  310. }
  311. atomic.StoreInt64(&conn.lastReadActivityTime, readActivityTime)
  312. }
  313. // Note: no context error to preserve error type
  314. return n, err
  315. }
  316. func (conn *ActivityMonitoredConn) Write(buffer []byte) (int, error) {
  317. n, err := conn.Conn.Write(buffer)
  318. if err == nil && conn.activeOnWrite {
  319. if conn.inactivityTimeout > 0 {
  320. err = conn.Conn.SetDeadline(time.Now().Add(conn.inactivityTimeout))
  321. if err != nil {
  322. return n, errors.Trace(err)
  323. }
  324. }
  325. if conn.activityUpdater != nil {
  326. conn.activityUpdater.UpdateProgress(0, int64(n), 0)
  327. }
  328. if conn.lruEntry != nil {
  329. conn.lruEntry.Touch()
  330. }
  331. }
  332. // Note: no context error to preserve error type
  333. return n, err
  334. }
  335. // IsClosed implements the Closer iterface. The return value
  336. // indicates whether the underlying conn has been closed.
  337. func (conn *ActivityMonitoredConn) IsClosed() bool {
  338. closer, ok := conn.Conn.(Closer)
  339. if !ok {
  340. return false
  341. }
  342. return closer.IsClosed()
  343. }
  344. // IsBogon checks if the specified IP is a bogon (loopback, private addresses,
  345. // link-local addresses, etc.)
  346. func IsBogon(IP net.IP) bool {
  347. return filtertransport.FindIPNet(
  348. filtertransport.DefaultFilteredNetworks, IP)
  349. }
  350. // ParseDNSQuestion parses a DNS message. When the message is a query,
  351. // the first question, a fully-qualified domain name, is returned.
  352. //
  353. // For other valid DNS messages, "" is returned. An error is returned only
  354. // for invalid DNS messages.
  355. //
  356. // Limitations:
  357. // - Only the first Question field is extracted.
  358. // - ParseDNSQuestion only functions for plaintext DNS and cannot
  359. // extract domains from DNS-over-TLS/HTTPS, etc.
  360. func ParseDNSQuestion(request []byte) (string, error) {
  361. m := new(dns.Msg)
  362. err := m.Unpack(request)
  363. if err != nil {
  364. return "", errors.Trace(err)
  365. }
  366. if len(m.Question) > 0 {
  367. return m.Question[0].Name, nil
  368. }
  369. return "", nil
  370. }