socksProxy.go 4.6 KB

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