plugin.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package plugin
  15. import (
  16. "fmt"
  17. "io"
  18. "net"
  19. "sync"
  20. "github.com/fatedier/golib/errors"
  21. pp "github.com/pires/go-proxyproto"
  22. v1 "github.com/fatedier/frp/pkg/config/v1"
  23. )
  24. // Creators is used for create plugins to handle connections.
  25. var creators = make(map[string]CreatorFn)
  26. // params has prefix "plugin_"
  27. type CreatorFn func(options v1.ClientPluginOptions) (Plugin, error)
  28. func Register(name string, fn CreatorFn) {
  29. if _, exist := creators[name]; exist {
  30. panic(fmt.Sprintf("plugin [%s] is already registered", name))
  31. }
  32. creators[name] = fn
  33. }
  34. func Create(name string, options v1.ClientPluginOptions) (p Plugin, err error) {
  35. if fn, ok := creators[name]; ok {
  36. p, err = fn(options)
  37. } else {
  38. err = fmt.Errorf("plugin [%s] is not registered", name)
  39. }
  40. return
  41. }
  42. type ExtraInfo struct {
  43. ProxyProtocolHeader *pp.Header
  44. }
  45. type Plugin interface {
  46. Name() string
  47. Handle(conn io.ReadWriteCloser, realConn net.Conn, extra *ExtraInfo)
  48. Close() error
  49. }
  50. type Listener struct {
  51. conns chan net.Conn
  52. closed bool
  53. mu sync.Mutex
  54. }
  55. func NewProxyListener() *Listener {
  56. return &Listener{
  57. conns: make(chan net.Conn, 64),
  58. }
  59. }
  60. func (l *Listener) Accept() (net.Conn, error) {
  61. conn, ok := <-l.conns
  62. if !ok {
  63. return nil, fmt.Errorf("listener closed")
  64. }
  65. return conn, nil
  66. }
  67. func (l *Listener) PutConn(conn net.Conn) error {
  68. err := errors.PanicToError(func() {
  69. l.conns <- conn
  70. })
  71. return err
  72. }
  73. func (l *Listener) Close() error {
  74. l.mu.Lock()
  75. defer l.mu.Unlock()
  76. if !l.closed {
  77. close(l.conns)
  78. l.closed = true
  79. }
  80. return nil
  81. }
  82. func (l *Listener) Addr() net.Addr {
  83. return (*net.TCPAddr)(nil)
  84. }