plugin.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. )
  23. // Creators is used for create plugins to handle connections.
  24. var creators = make(map[string]CreatorFn)
  25. // params has prefix "plugin_"
  26. type CreatorFn func(options v1.ClientPluginOptions) (Plugin, error)
  27. func Register(name string, fn CreatorFn) {
  28. creators[name] = fn
  29. }
  30. func Create(name string, options v1.ClientPluginOptions) (p Plugin, err error) {
  31. if fn, ok := creators[name]; ok {
  32. p, err = fn(options)
  33. } else {
  34. err = fmt.Errorf("plugin [%s] is not registered", name)
  35. }
  36. return
  37. }
  38. type Plugin interface {
  39. Name() string
  40. // extraBufToLocal will send to local connection first, then join conn with local connection
  41. Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte)
  42. Close() error
  43. }
  44. type Listener struct {
  45. conns chan net.Conn
  46. closed bool
  47. mu sync.Mutex
  48. }
  49. func NewProxyListener() *Listener {
  50. return &Listener{
  51. conns: make(chan net.Conn, 64),
  52. }
  53. }
  54. func (l *Listener) Accept() (net.Conn, error) {
  55. conn, ok := <-l.conns
  56. if !ok {
  57. return nil, fmt.Errorf("listener closed")
  58. }
  59. return conn, nil
  60. }
  61. func (l *Listener) PutConn(conn net.Conn) error {
  62. err := errors.PanicToError(func() {
  63. l.conns <- conn
  64. })
  65. return err
  66. }
  67. func (l *Listener) Close() error {
  68. l.mu.Lock()
  69. defer l.mu.Unlock()
  70. if !l.closed {
  71. close(l.conns)
  72. l.closed = true
  73. }
  74. return nil
  75. }
  76. func (l *Listener) Addr() net.Addr {
  77. return (*net.TCPAddr)(nil)
  78. }