net.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "net"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. )
  27. // Conns is a synchronized list of Conns that is used to coordinate
  28. // interrupting a set of goroutines establishing connections, or
  29. // close a set of open connections, etc.
  30. // Once the list is closed, no more items may be added to the
  31. // list (unless it is reset).
  32. type Conns struct {
  33. mutex sync.Mutex
  34. isClosed bool
  35. conns map[net.Conn]bool
  36. }
  37. func (conns *Conns) Reset() {
  38. conns.mutex.Lock()
  39. defer conns.mutex.Unlock()
  40. conns.isClosed = false
  41. conns.conns = make(map[net.Conn]bool)
  42. }
  43. func (conns *Conns) Add(conn net.Conn) bool {
  44. conns.mutex.Lock()
  45. defer conns.mutex.Unlock()
  46. if conns.isClosed {
  47. return false
  48. }
  49. if conns.conns == nil {
  50. conns.conns = make(map[net.Conn]bool)
  51. }
  52. conns.conns[conn] = true
  53. return true
  54. }
  55. func (conns *Conns) Remove(conn net.Conn) {
  56. conns.mutex.Lock()
  57. defer conns.mutex.Unlock()
  58. delete(conns.conns, conn)
  59. }
  60. func (conns *Conns) CloseAll() {
  61. conns.mutex.Lock()
  62. defer conns.mutex.Unlock()
  63. conns.isClosed = true
  64. for conn, _ := range conns.conns {
  65. conn.Close()
  66. }
  67. conns.conns = make(map[net.Conn]bool)
  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. // LRUConns is a concurrency-safe list of net.Conns ordered
  82. // by recent activity. Its purpose is to facilitate closing
  83. // the oldest connection in a set of connections.
  84. //
  85. // New connections added are referenced by a LRUConnsEntry,
  86. // which is used to Touch() active connections, which
  87. // promotes them to the front of the order and to Remove()
  88. // connections that are no longer LRU candidates.
  89. //
  90. // CloseOldest() will remove the oldest connection from the
  91. // list and call net.Conn.Close() on the connection.
  92. //
  93. // After an entry has been removed, LRUConnsEntry Touch()
  94. // and Remove() will have no effect.
  95. type LRUConns struct {
  96. mutex sync.Mutex
  97. list *list.List
  98. }
  99. // NewLRUConns initializes a new LRUConns.
  100. func NewLRUConns() *LRUConns {
  101. return &LRUConns{list: list.New()}
  102. }
  103. // Add inserts a net.Conn as the freshest connection
  104. // in a LRUConns and returns an LRUConnsEntry to be
  105. // used to freshen the connection or remove the connection
  106. // from the LRU list.
  107. func (conns *LRUConns) Add(conn net.Conn) *LRUConnsEntry {
  108. conns.mutex.Lock()
  109. defer conns.mutex.Unlock()
  110. return &LRUConnsEntry{
  111. lruConns: conns,
  112. element: conns.list.PushFront(conn),
  113. }
  114. }
  115. // CloseOldest closes the oldest connection in a
  116. // LRUConns. It calls net.Conn.Close() on the
  117. // connection.
  118. func (conns *LRUConns) CloseOldest() {
  119. conns.mutex.Lock()
  120. oldest := conns.list.Back()
  121. if oldest != nil {
  122. conns.list.Remove(oldest)
  123. }
  124. // Release mutex before closing conn
  125. conns.mutex.Unlock()
  126. if oldest != nil {
  127. oldest.Value.(net.Conn).Close()
  128. }
  129. }
  130. // LRUConnsEntry is an entry in a LRUConns list.
  131. type LRUConnsEntry struct {
  132. lruConns *LRUConns
  133. element *list.Element
  134. }
  135. // Remove deletes the connection referenced by the
  136. // LRUConnsEntry from the associated LRUConns.
  137. // Has no effect if the entry was not initialized
  138. // or previously removed.
  139. func (entry *LRUConnsEntry) Remove() {
  140. if entry.lruConns == nil || entry.element == nil {
  141. return
  142. }
  143. entry.lruConns.mutex.Lock()
  144. defer entry.lruConns.mutex.Unlock()
  145. entry.lruConns.list.Remove(entry.element)
  146. }
  147. // Touch promotes the connection referenced by the
  148. // LRUConnsEntry to the front of the associated LRUConns.
  149. // Has no effect if the entry was not initialized
  150. // or previously removed.
  151. func (entry *LRUConnsEntry) Touch() {
  152. if entry.lruConns == nil || entry.element == nil {
  153. return
  154. }
  155. entry.lruConns.mutex.Lock()
  156. defer entry.lruConns.mutex.Unlock()
  157. entry.lruConns.list.MoveToFront(entry.element)
  158. }
  159. // ActivityMonitoredConn wraps a net.Conn, adding logic to deal with
  160. // events triggered by I/O activity.
  161. //
  162. // When an inactivity timeout is specified, the network I/O will
  163. // timeout after the specified period of read inactivity. Optionally,
  164. // for the purpose of inactivity only, ActivityMonitoredConn will also
  165. // consider the connection active when data is written to it.
  166. //
  167. // When a LRUConnsEntry is specified, then the LRU entry is promoted on
  168. // either a successful read or write.
  169. //
  170. type ActivityMonitoredConn struct {
  171. // Note: 64-bit ints used with atomic operations are at placed
  172. // at the start of struct to ensure 64-bit alignment.
  173. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  174. startTime int64
  175. lastReadActivityTime int64
  176. net.Conn
  177. inactivityTimeout time.Duration
  178. activeOnWrite bool
  179. lruEntry *LRUConnsEntry
  180. }
  181. func NewActivityMonitoredConn(
  182. conn net.Conn,
  183. inactivityTimeout time.Duration,
  184. activeOnWrite bool,
  185. lruEntry *LRUConnsEntry) (*ActivityMonitoredConn, error) {
  186. if inactivityTimeout > 0 {
  187. err := conn.SetDeadline(time.Now().Add(inactivityTimeout))
  188. if err != nil {
  189. return nil, ContextError(err)
  190. }
  191. }
  192. now := time.Now().UnixNano()
  193. return &ActivityMonitoredConn{
  194. Conn: conn,
  195. inactivityTimeout: inactivityTimeout,
  196. activeOnWrite: activeOnWrite,
  197. startTime: now,
  198. lastReadActivityTime: now,
  199. lruEntry: lruEntry,
  200. }, nil
  201. }
  202. // GetStartTime gets the time when the ActivityMonitoredConn was
  203. // initialized.
  204. func (conn *ActivityMonitoredConn) GetStartTime() time.Time {
  205. return time.Unix(0, conn.startTime)
  206. }
  207. // GetActiveDuration returns the time elapsed between the initialization
  208. // of the ActivityMonitoredConn and the last Read. Only reads are used
  209. // for this calculation since writes may succeed locally due to buffering.
  210. func (conn *ActivityMonitoredConn) GetActiveDuration() time.Duration {
  211. return time.Duration(atomic.LoadInt64(&conn.lastReadActivityTime) - conn.startTime)
  212. }
  213. // GetLastActivityTime returns the time of the last Read.
  214. func (conn *ActivityMonitoredConn) GetLastActivityTime() time.Time {
  215. return time.Unix(0, atomic.LoadInt64(&conn.lastReadActivityTime))
  216. }
  217. func (conn *ActivityMonitoredConn) Read(buffer []byte) (int, error) {
  218. n, err := conn.Conn.Read(buffer)
  219. if err == nil {
  220. if conn.inactivityTimeout > 0 {
  221. err = conn.Conn.SetDeadline(time.Now().Add(conn.inactivityTimeout))
  222. if err != nil {
  223. return n, ContextError(err)
  224. }
  225. }
  226. if conn.lruEntry != nil {
  227. conn.lruEntry.Touch()
  228. }
  229. atomic.StoreInt64(&conn.lastReadActivityTime, time.Now().UnixNano())
  230. }
  231. // Note: no context error to preserve error type
  232. return n, err
  233. }
  234. func (conn *ActivityMonitoredConn) Write(buffer []byte) (int, error) {
  235. n, err := conn.Conn.Write(buffer)
  236. if err == nil && conn.activeOnWrite {
  237. if conn.inactivityTimeout > 0 {
  238. err = conn.Conn.SetDeadline(time.Now().Add(conn.inactivityTimeout))
  239. if err != nil {
  240. return n, ContextError(err)
  241. }
  242. }
  243. if conn.lruEntry != nil {
  244. conn.lruEntry.Touch()
  245. }
  246. }
  247. // Note: no context error to preserve error type
  248. return n, err
  249. }