authenticator.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package internet
  2. import (
  3. "errors"
  4. "github.com/v2ray/v2ray-core/common/alloc"
  5. "github.com/v2ray/v2ray-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(AuthenticatorConfig) Authenticator
  14. }
  15. type AuthenticatorConfig interface {
  16. }
  17. var (
  18. ErrDuplicatedAuthenticator = errors.New("Authenticator already registered.")
  19. ErrAuthenticatorNotFound = errors.New("Authenticator not found.")
  20. authenticatorCache = make(map[string]AuthenticatorFactory)
  21. configCache loader.ConfigLoader
  22. )
  23. func RegisterAuthenticator(name string, factory AuthenticatorFactory, configCreator loader.ConfigCreator) error {
  24. if _, found := authenticatorCache[name]; found {
  25. return ErrDuplicatedAuthenticator
  26. }
  27. authenticatorCache[name] = factory
  28. return configCache.RegisterCreator(name, configCreator)
  29. }
  30. func CreateAuthenticator(name string, config AuthenticatorConfig) (Authenticator, error) {
  31. factory, found := authenticatorCache[name]
  32. if !found {
  33. return nil, ErrAuthenticatorNotFound
  34. }
  35. return factory.Create(config), nil
  36. }
  37. func CreateAuthenticatorConfig(rawConfig []byte) (string, AuthenticatorConfig, error) {
  38. config, name, err := configCache.Load(rawConfig)
  39. if err != nil {
  40. return name, nil, err
  41. }
  42. return name, config, nil
  43. }
  44. type AuthenticatorChain struct {
  45. authenticators []Authenticator
  46. }
  47. func NewAuthenticatorChain(auths ...Authenticator) Authenticator {
  48. return &AuthenticatorChain{
  49. authenticators: auths,
  50. }
  51. }
  52. func (this *AuthenticatorChain) Overhead() int {
  53. total := 0
  54. for _, auth := range this.authenticators {
  55. total += auth.Overhead()
  56. }
  57. return total
  58. }
  59. func (this *AuthenticatorChain) Open(payload *alloc.Buffer) bool {
  60. for _, auth := range this.authenticators {
  61. if !auth.Open(payload) {
  62. return false
  63. }
  64. }
  65. return true
  66. }
  67. func (this *AuthenticatorChain) Seal(payload *alloc.Buffer) {
  68. for i := len(this.authenticators) - 1; i >= 0; i-- {
  69. auth := this.authenticators[i]
  70. auth.Seal(payload)
  71. }
  72. }