net.go 9.9 KB

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