socksProxy.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "fmt"
  22. "net"
  23. "sync"
  24. socks "github.com/Psiphon-Inc/goptlib"
  25. )
  26. // SocksProxy is a SOCKS server that accepts local host connections
  27. // and, for each connection, establishes a port forward through
  28. // the tunnel SSH client and relays traffic through the port
  29. // forward.
  30. type SocksProxy struct {
  31. tunneler Tunneler
  32. listener *socks.SocksListener
  33. serveWaitGroup *sync.WaitGroup
  34. openConns *Conns
  35. stopListeningBroadcast chan struct{}
  36. }
  37. var _SOCKS_PROXY_TYPE = "SOCKS"
  38. // NewSocksProxy initializes a new SOCKS server. It begins listening for
  39. // connections, starts a goroutine that runs an accept loop, and returns
  40. // leaving the accept loop running.
  41. func NewSocksProxy(config *Config, tunneler Tunneler) (proxy *SocksProxy, err error) {
  42. listener, err := socks.ListenSocks(
  43. "tcp", fmt.Sprintf("127.0.0.1:%d", config.LocalSocksProxyPort))
  44. if err != nil {
  45. if IsAddressInUseError(err) {
  46. NoticeSocksProxyPortInUse(config.LocalSocksProxyPort)
  47. }
  48. return nil, ContextError(err)
  49. }
  50. proxy = &SocksProxy{
  51. tunneler: tunneler,
  52. listener: listener,
  53. serveWaitGroup: new(sync.WaitGroup),
  54. openConns: new(Conns),
  55. stopListeningBroadcast: make(chan struct{}),
  56. }
  57. proxy.serveWaitGroup.Add(1)
  58. go proxy.serve()
  59. NoticeListeningSocksProxyPort(proxy.listener.Addr().(*net.TCPAddr).Port)
  60. return proxy, nil
  61. }
  62. // Close terminates the listener and waits for the accept loop
  63. // goroutine to complete.
  64. func (proxy *SocksProxy) Close() {
  65. close(proxy.stopListeningBroadcast)
  66. proxy.listener.Close()
  67. proxy.serveWaitGroup.Wait()
  68. proxy.openConns.CloseAll()
  69. }
  70. func (proxy *SocksProxy) socksConnectionHandler(localConn *socks.SocksConn) (err error) {
  71. defer localConn.Close()
  72. defer proxy.openConns.Remove(localConn)
  73. proxy.openConns.Add(localConn)
  74. // Using downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  75. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  76. // open connection for data which will never arrive.
  77. remoteConn, err := proxy.tunneler.Dial(localConn.Req.Target, false, localConn)
  78. if err != nil {
  79. return ContextError(err)
  80. }
  81. defer remoteConn.Close()
  82. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  83. if err != nil {
  84. return ContextError(err)
  85. }
  86. LocalProxyRelay(_SOCKS_PROXY_TYPE, localConn, remoteConn)
  87. return nil
  88. }
  89. func (proxy *SocksProxy) serve() {
  90. defer proxy.listener.Close()
  91. defer proxy.serveWaitGroup.Done()
  92. loop:
  93. for {
  94. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  95. socksConnection, err := proxy.listener.AcceptSocks()
  96. // Can't check for the exact error that Close() will cause in Accept(),
  97. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  98. // explicit stop signal to stop gracefully.
  99. select {
  100. case <-proxy.stopListeningBroadcast:
  101. break loop
  102. default:
  103. }
  104. if err != nil {
  105. NoticeAlert("SOCKS proxy accept error: %s", err)
  106. if e, ok := err.(net.Error); ok && e.Temporary() {
  107. // Temporary error, keep running
  108. continue
  109. }
  110. // Fatal error, stop the proxy
  111. proxy.tunneler.SignalComponentFailure()
  112. break loop
  113. }
  114. go func() {
  115. err := proxy.socksConnectionHandler(socksConnection)
  116. if err != nil {
  117. NoticeLocalProxyError(_SOCKS_PROXY_TYPE, ContextError(err))
  118. }
  119. }()
  120. }
  121. NoticeInfo("SOCKS proxy stopped")
  122. }