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