socksProxy.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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(
  42. config *Config,
  43. tunneler Tunneler,
  44. listenIP string) (proxy *SocksProxy, err error) {
  45. listener, err := socks.ListenSocks(
  46. "tcp", fmt.Sprintf("%s:%d", listenIP, config.LocalSocksProxyPort))
  47. if err != nil {
  48. if IsAddressInUseError(err) {
  49. NoticeSocksProxyPortInUse(config.LocalSocksProxyPort)
  50. }
  51. return nil, ContextError(err)
  52. }
  53. proxy = &SocksProxy{
  54. tunneler: tunneler,
  55. listener: listener,
  56. serveWaitGroup: new(sync.WaitGroup),
  57. openConns: new(Conns),
  58. stopListeningBroadcast: make(chan struct{}),
  59. }
  60. proxy.serveWaitGroup.Add(1)
  61. go proxy.serve()
  62. NoticeListeningSocksProxyPort(proxy.listener.Addr().(*net.TCPAddr).Port)
  63. return proxy, nil
  64. }
  65. // Close terminates the listener and waits for the accept loop
  66. // goroutine to complete.
  67. func (proxy *SocksProxy) Close() {
  68. close(proxy.stopListeningBroadcast)
  69. proxy.listener.Close()
  70. proxy.serveWaitGroup.Wait()
  71. proxy.openConns.CloseAll()
  72. }
  73. func (proxy *SocksProxy) socksConnectionHandler(localConn *socks.SocksConn) (err error) {
  74. defer localConn.Close()
  75. defer proxy.openConns.Remove(localConn)
  76. proxy.openConns.Add(localConn)
  77. // Using downstreamConn so localConn.Close() will be called when remoteConn.Close() is called.
  78. // This ensures that the downstream client (e.g., web browser) doesn't keep waiting on the
  79. // open connection for data which will never arrive.
  80. remoteConn, err := proxy.tunneler.Dial(localConn.Req.Target, false, localConn)
  81. if err != nil {
  82. return ContextError(err)
  83. }
  84. defer remoteConn.Close()
  85. err = localConn.Grant(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})
  86. if err != nil {
  87. return ContextError(err)
  88. }
  89. LocalProxyRelay(_SOCKS_PROXY_TYPE, localConn, remoteConn)
  90. return nil
  91. }
  92. func (proxy *SocksProxy) serve() {
  93. defer proxy.listener.Close()
  94. defer proxy.serveWaitGroup.Done()
  95. loop:
  96. for {
  97. // Note: will be interrupted by listener.Close() call made by proxy.Close()
  98. socksConnection, err := proxy.listener.AcceptSocks()
  99. // Can't check for the exact error that Close() will cause in Accept(),
  100. // (see: https://code.google.com/p/go/issues/detail?id=4373). So using an
  101. // explicit stop signal to stop gracefully.
  102. select {
  103. case <-proxy.stopListeningBroadcast:
  104. break loop
  105. default:
  106. }
  107. if err != nil {
  108. NoticeAlert("SOCKS proxy accept error: %s", err)
  109. if e, ok := err.(net.Error); ok && e.Temporary() {
  110. // Temporary error, keep running
  111. continue
  112. }
  113. // Fatal error, stop the proxy
  114. proxy.tunneler.SignalComponentFailure()
  115. break loop
  116. }
  117. go func() {
  118. err := proxy.socksConnectionHandler(socksConnection)
  119. if err != nil {
  120. NoticeLocalProxyError(_SOCKS_PROXY_TYPE, ContextError(err))
  121. }
  122. }()
  123. }
  124. NoticeInfo("SOCKS proxy stopped")
  125. }