authenticator.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package internet
  2. import (
  3. "v2ray.com/core/common"
  4. "v2ray.com/core/common/alloc"
  5. "v2ray.com/core/common/loader"
  6. )
  7. type Authenticator interface {
  8. Seal(*alloc.Buffer)
  9. Open(*alloc.Buffer) bool
  10. Overhead() int
  11. }
  12. type AuthenticatorFactory interface {
  13. Create(interface{}) Authenticator
  14. }
  15. var (
  16. authenticatorCache = make(map[string]AuthenticatorFactory)
  17. configCache = loader.ConfigCreatorCache{}
  18. )
  19. func RegisterAuthenticator(name string, factory AuthenticatorFactory) error {
  20. if _, found := authenticatorCache[name]; found {
  21. return common.ErrDuplicatedName
  22. }
  23. authenticatorCache[name] = factory
  24. return nil
  25. }
  26. func CreateAuthenticator(name string, config interface{}) (Authenticator, error) {
  27. factory, found := authenticatorCache[name]
  28. if !found {
  29. return nil, common.ErrObjectNotFound
  30. }
  31. return factory.Create(config), nil
  32. }
  33. type AuthenticatorChain struct {
  34. authenticators []Authenticator
  35. }
  36. func NewAuthenticatorChain(auths ...Authenticator) Authenticator {
  37. return &AuthenticatorChain{
  38. authenticators: auths,
  39. }
  40. }
  41. func (this *AuthenticatorChain) Overhead() int {
  42. total := 0
  43. for _, auth := range this.authenticators {
  44. total += auth.Overhead()
  45. }
  46. return total
  47. }
  48. func (this *AuthenticatorChain) Open(payload *alloc.Buffer) bool {
  49. for _, auth := range this.authenticators {
  50. if !auth.Open(payload) {
  51. return false
  52. }
  53. }
  54. return true
  55. }
  56. func (this *AuthenticatorChain) Seal(payload *alloc.Buffer) {
  57. for i := len(this.authenticators) - 1; i >= 0; i-- {
  58. auth := this.authenticators[i]
  59. auth.Seal(payload)
  60. }
  61. }