net.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "net"
  22. "sync"
  23. )
  24. // Conns is a synchronized list of Conns that is used to coordinate
  25. // interrupting a set of goroutines establishing connections, or
  26. // close a set of open connections, etc.
  27. // Once the list is closed, no more items may be added to the
  28. // list (unless it is reset).
  29. type Conns struct {
  30. mutex sync.Mutex
  31. isClosed bool
  32. conns map[net.Conn]bool
  33. }
  34. func (conns *Conns) Reset() {
  35. conns.mutex.Lock()
  36. defer conns.mutex.Unlock()
  37. conns.isClosed = false
  38. conns.conns = make(map[net.Conn]bool)
  39. }
  40. func (conns *Conns) Add(conn net.Conn) bool {
  41. conns.mutex.Lock()
  42. defer conns.mutex.Unlock()
  43. if conns.isClosed {
  44. return false
  45. }
  46. if conns.conns == nil {
  47. conns.conns = make(map[net.Conn]bool)
  48. }
  49. conns.conns[conn] = true
  50. return true
  51. }
  52. func (conns *Conns) Remove(conn net.Conn) {
  53. conns.mutex.Lock()
  54. defer conns.mutex.Unlock()
  55. delete(conns.conns, conn)
  56. }
  57. func (conns *Conns) CloseAll() {
  58. conns.mutex.Lock()
  59. defer conns.mutex.Unlock()
  60. conns.isClosed = true
  61. for conn, _ := range conns.conns {
  62. conn.Close()
  63. }
  64. conns.conns = make(map[net.Conn]bool)
  65. }
  66. // IPAddressFromAddr is a helper which extracts an IP address
  67. // from a net.Addr or returns "" if there is no IP address.
  68. func IPAddressFromAddr(addr net.Addr) string {
  69. ipAddress := ""
  70. if addr != nil {
  71. host, _, err := net.SplitHostPort(addr.String())
  72. if err == nil {
  73. ipAddress = host
  74. }
  75. }
  76. return ipAddress
  77. }