authenticator.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package internet
  2. import (
  3. "v2ray.com/core/common"
  4. "v2ray.com/core/common/alloc"
  5. )
  6. type Authenticator interface {
  7. Seal(*alloc.Buffer)
  8. Open(*alloc.Buffer) bool
  9. Overhead() int
  10. }
  11. type AuthenticatorFactory interface {
  12. Create(AuthenticatorConfig) Authenticator
  13. }
  14. type AuthenticatorConfig interface {
  15. }
  16. var (
  17. authenticatorCache = make(map[string]AuthenticatorFactory)
  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 AuthenticatorConfig) (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. }