net.go 10 KB

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