pluginProtocol.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2017, 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. "io"
  22. "net"
  23. "sync/atomic"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. )
  26. var registeredPluginProtocolDialer atomic.Value
  27. // PluginProtocolDialer creates a connection to addr over a
  28. // plugin protocol. It uses dialConfig to create its base network
  29. // connection(s) and sends its log messages to loggerOutput.
  30. //
  31. // To ensure timely interruption and shutdown, each
  32. // PluginProtocolDialerimplementation must:
  33. //
  34. // - Places its outer net.Conn in pendingConns and leave it
  35. // there unless an error occurs
  36. // - Replace the dialConfig.pendingConns with its own
  37. // PendingConns and use that to ensure base network
  38. // connections are interrupted when Close() is invoked on
  39. // the returned net.Conn.
  40. //
  41. // PluginProtocolDialer returns true if it attempts to create
  42. // a connection, or false if it decides not to attempt a connection.
  43. type PluginProtocolDialer func(
  44. config *Config,
  45. loggerOutput io.Writer,
  46. pendingConns *common.Conns,
  47. addr string,
  48. dialConfig *DialConfig) (bool, net.Conn, error)
  49. // RegisterPluginProtocol sets the current plugin protocol
  50. // dialer.
  51. func RegisterPluginProtocol(protocolDialer PluginProtocolDialer) {
  52. registeredPluginProtocolDialer.Store(protocolDialer)
  53. }
  54. // DialPluginProtocol uses the current plugin protocol dialer,
  55. // if set, to connect to addr over the plugin protocol.
  56. func DialPluginProtocol(
  57. config *Config,
  58. loggerOutput io.Writer,
  59. pendingConns *common.Conns,
  60. addr string,
  61. dialConfig *DialConfig) (bool, net.Conn, error) {
  62. dialer := registeredPluginProtocolDialer.Load()
  63. if dialer != nil {
  64. return dialer.(PluginProtocolDialer)(
  65. config, loggerOutput, pendingConns, addr, dialConfig)
  66. }
  67. return false, nil, nil
  68. }