1
0

plugin.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. SrcAddr net.Addr
  45. DstAddr net.Addr
  46. }
  47. type Plugin interface {
  48. Name() string
  49. Handle(conn io.ReadWriteCloser, realConn net.Conn, extra *ExtraInfo)
  50. Close() error
  51. }
  52. type Listener struct {
  53. conns chan net.Conn
  54. closed bool
  55. mu sync.Mutex
  56. }
  57. func NewProxyListener() *Listener {
  58. return &Listener{
  59. conns: make(chan net.Conn, 64),
  60. }
  61. }
  62. func (l *Listener) Accept() (net.Conn, error) {
  63. conn, ok := <-l.conns
  64. if !ok {
  65. return nil, fmt.Errorf("listener closed")
  66. }
  67. return conn, nil
  68. }
  69. func (l *Listener) PutConn(conn net.Conn) error {
  70. err := errors.PanicToError(func() {
  71. l.conns <- conn
  72. })
  73. return err
  74. }
  75. func (l *Listener) Close() error {
  76. l.mu.Lock()
  77. defer l.mu.Unlock()
  78. if !l.closed {
  79. close(l.conns)
  80. l.closed = true
  81. }
  82. return nil
  83. }
  84. func (l *Listener) Addr() net.Addr {
  85. return (*net.TCPAddr)(nil)
  86. }