pluginProtocol.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 common
  20. import (
  21. "io"
  22. "net"
  23. "sync/atomic"
  24. )
  25. var registeredPluginProtocolDialer atomic.Value
  26. // PluginProtocolNetDialer is a base network dialer that's used
  27. // by PluginProtocolDialer to make its IP network connections. This
  28. // is used, for example, to create TCPConns as the base TCP
  29. // connections used by the plugin protocol.
  30. type PluginProtocolNetDialer func(network, addr string) (net.Conn, error)
  31. // PluginProtocolDialer creates a connection to addr over a
  32. // plugin protocol. It uses netDialer to create its base network
  33. // connection(s) and sends its log messages to loggerOutput.
  34. // PluginProtocolDialer returns true if it attempts to create
  35. // a connection, or false if it decides not to attempt a connection.
  36. type PluginProtocolDialer func(
  37. loggerOutput io.Writer,
  38. netDialer PluginProtocolNetDialer,
  39. addr string) (
  40. bool, net.Conn, error)
  41. // RegisterPluginProtocol sets the current plugin protocol
  42. // dialer.
  43. func RegisterPluginProtocol(protcolDialer PluginProtocolDialer) {
  44. registeredPluginProtocolDialer.Store(protcolDialer)
  45. }
  46. // DialPluginProtocol uses the current plugin protocol dialer,
  47. // if set, to connect to addr over the plugin protocol.
  48. func DialPluginProtocol(
  49. loggerOutput io.Writer,
  50. netDialer PluginProtocolNetDialer,
  51. addr string) (
  52. bool, net.Conn, error) {
  53. dialer := registeredPluginProtocolDialer.Load()
  54. if dialer != nil {
  55. return dialer.(PluginProtocolDialer)(loggerOutput, netDialer, addr)
  56. }
  57. return false, nil, nil
  58. }