pluginProtocol.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // PluginProtocolDialer must add its connection to pendingConns
  37. // before the initial dial to allow for interruption.
  38. type PluginProtocolDialer func(
  39. loggerOutput io.Writer,
  40. pendingConns *Conns,
  41. netDialer PluginProtocolNetDialer,
  42. addr string) (
  43. bool, net.Conn, error)
  44. // RegisterPluginProtocol sets the current plugin protocol
  45. // dialer.
  46. func RegisterPluginProtocol(protcolDialer PluginProtocolDialer) {
  47. registeredPluginProtocolDialer.Store(protcolDialer)
  48. }
  49. // DialPluginProtocol uses the current plugin protocol dialer,
  50. // if set, to connect to addr over the plugin protocol.
  51. func DialPluginProtocol(
  52. loggerOutput io.Writer,
  53. pendingConns *Conns,
  54. netDialer PluginProtocolNetDialer,
  55. addr string) (
  56. bool, net.Conn, error) {
  57. dialer := registeredPluginProtocolDialer.Load()
  58. if dialer != nil {
  59. return dialer.(PluginProtocolDialer)(
  60. loggerOutput, pendingConns, netDialer, addr)
  61. }
  62. return false, nil, nil
  63. }