visitor.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2019 fatedier, [email protected]
  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 visitor
  15. import (
  16. "fmt"
  17. "io"
  18. "net"
  19. "sync"
  20. frpNet "github.com/fatedier/frp/pkg/util/net"
  21. "github.com/fatedier/frp/pkg/util/util"
  22. frpIo "github.com/fatedier/golib/io"
  23. )
  24. // Manager for visitor listeners.
  25. type Manager struct {
  26. visitorListeners map[string]*frpNet.CustomListener
  27. skMap map[string]string
  28. mu sync.RWMutex
  29. }
  30. func NewManager() *Manager {
  31. return &Manager{
  32. visitorListeners: make(map[string]*frpNet.CustomListener),
  33. skMap: make(map[string]string),
  34. }
  35. }
  36. func (vm *Manager) Listen(name string, sk string) (l *frpNet.CustomListener, err error) {
  37. vm.mu.Lock()
  38. defer vm.mu.Unlock()
  39. if _, ok := vm.visitorListeners[name]; ok {
  40. err = fmt.Errorf("custom listener for [%s] is repeated", name)
  41. return
  42. }
  43. l = frpNet.NewCustomListener()
  44. vm.visitorListeners[name] = l
  45. vm.skMap[name] = sk
  46. return
  47. }
  48. func (vm *Manager) NewConn(name string, conn net.Conn, timestamp int64, signKey string,
  49. useEncryption bool, useCompression bool) (err error) {
  50. vm.mu.RLock()
  51. defer vm.mu.RUnlock()
  52. if l, ok := vm.visitorListeners[name]; ok {
  53. var sk string
  54. if sk = vm.skMap[name]; util.GetAuthKey(sk, timestamp) != signKey {
  55. err = fmt.Errorf("visitor connection of [%s] auth failed", name)
  56. return
  57. }
  58. var rwc io.ReadWriteCloser = conn
  59. if useEncryption {
  60. if rwc, err = frpIo.WithEncryption(rwc, []byte(sk)); err != nil {
  61. err = fmt.Errorf("create encryption connection failed: %v", err)
  62. return
  63. }
  64. }
  65. if useCompression {
  66. rwc = frpIo.WithCompression(rwc)
  67. }
  68. err = l.PutConn(frpNet.WrapReadWriteCloserToConn(rwc, conn))
  69. } else {
  70. err = fmt.Errorf("custom listener for [%s] doesn't exist", name)
  71. return
  72. }
  73. return
  74. }
  75. func (vm *Manager) CloseListener(name string) {
  76. vm.mu.Lock()
  77. defer vm.mu.Unlock()
  78. delete(vm.visitorListeners, name)
  79. delete(vm.skMap, name)
  80. }