authenticator.go 1.9 KB

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