1
0

plugin.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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/frp/utils/errors"
  21. frpNet "github.com/fatedier/frp/utils/net"
  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(params map[string]string) (Plugin, error)
  27. func Register(name string, fn CreatorFn) {
  28. creators[name] = fn
  29. }
  30. func Create(name string, params map[string]string) (p Plugin, err error) {
  31. if fn, ok := creators[name]; ok {
  32. p, err = fn(params)
  33. } else {
  34. err = fmt.Errorf("plugin [%s] is not registered", name)
  35. }
  36. return
  37. }
  38. type Plugin interface {
  39. Name() string
  40. Handle(conn io.ReadWriteCloser, realConn frpNet.Conn)
  41. Close() error
  42. }
  43. type Listener struct {
  44. conns chan net.Conn
  45. closed bool
  46. mu sync.Mutex
  47. }
  48. func NewProxyListener() *Listener {
  49. return &Listener{
  50. conns: make(chan net.Conn, 64),
  51. }
  52. }
  53. func (l *Listener) Accept() (net.Conn, error) {
  54. conn, ok := <-l.conns
  55. if !ok {
  56. return nil, fmt.Errorf("listener closed")
  57. }
  58. return conn, nil
  59. }
  60. func (l *Listener) PutConn(conn net.Conn) error {
  61. err := errors.PanicToError(func() {
  62. l.conns <- conn
  63. })
  64. return err
  65. }
  66. func (l *Listener) Close() error {
  67. l.mu.Lock()
  68. defer l.mu.Unlock()
  69. if !l.closed {
  70. close(l.conns)
  71. l.closed = true
  72. }
  73. return nil
  74. }
  75. func (l *Listener) Addr() net.Addr {
  76. return (*net.TCPAddr)(nil)
  77. }