authenticator.go 1.4 KB

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