net.go 10 KB

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