net.go 10 KB

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