plugin.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. "context"
  17. "fmt"
  18. "io"
  19. "net"
  20. "sync"
  21. "github.com/fatedier/golib/errors"
  22. pp "github.com/pires/go-proxyproto"
  23. v1 "github.com/fatedier/frp/pkg/config/v1"
  24. )
  25. // Creators is used for create plugins to handle connections.
  26. var creators = make(map[string]CreatorFn)
  27. // params has prefix "plugin_"
  28. type CreatorFn func(options v1.ClientPluginOptions) (Plugin, error)
  29. func Register(name string, fn CreatorFn) {
  30. if _, exist := creators[name]; exist {
  31. panic(fmt.Sprintf("plugin [%s] is already registered", name))
  32. }
  33. creators[name] = fn
  34. }
  35. func Create(name string, options v1.ClientPluginOptions) (p Plugin, err error) {
  36. if fn, ok := creators[name]; ok {
  37. p, err = fn(options)
  38. } else {
  39. err = fmt.Errorf("plugin [%s] is not registered", name)
  40. }
  41. return
  42. }
  43. type ExtraInfo struct {
  44. ProxyProtocolHeader *pp.Header
  45. SrcAddr net.Addr
  46. DstAddr net.Addr
  47. }
  48. type Plugin interface {
  49. Name() string
  50. Handle(ctx context.Context, conn io.ReadWriteCloser, realConn net.Conn, extra *ExtraInfo)
  51. Close() error
  52. }
  53. type Listener struct {
  54. conns chan net.Conn
  55. closed bool
  56. mu sync.Mutex
  57. }
  58. func NewProxyListener() *Listener {
  59. return &Listener{
  60. conns: make(chan net.Conn, 64),
  61. }
  62. }
  63. func (l *Listener) Accept() (net.Conn, error) {
  64. conn, ok := <-l.conns
  65. if !ok {
  66. return nil, fmt.Errorf("listener closed")
  67. }
  68. return conn, nil
  69. }
  70. func (l *Listener) PutConn(conn net.Conn) error {
  71. err := errors.PanicToError(func() {
  72. l.conns <- conn
  73. })
  74. return err
  75. }
  76. func (l *Listener) Close() error {
  77. l.mu.Lock()
  78. defer l.mu.Unlock()
  79. if !l.closed {
  80. close(l.conns)
  81. l.closed = true
  82. }
  83. return nil
  84. }
  85. func (l *Listener) Addr() net.Addr {
  86. return (*net.TCPAddr)(nil)
  87. }