socksProxy.go 4.5 KB

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