rule_user.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package route
  2. import (
  3. "strings"
  4. "github.com/sagernet/sing-box/adapter"
  5. "github.com/sagernet/sing-box/common/warning"
  6. C "github.com/sagernet/sing-box/constant"
  7. F "github.com/sagernet/sing/common/format"
  8. )
  9. var warnUserOnNonLinux = warning.New(
  10. func() bool { return !C.IsLinux },
  11. "rule item `user` is only supported on Linux",
  12. )
  13. var _ RuleItem = (*UserItem)(nil)
  14. type UserItem struct {
  15. users []string
  16. userMap map[string]bool
  17. }
  18. func NewUserItem(users []string) *UserItem {
  19. warnUserOnNonLinux.Check()
  20. userMap := make(map[string]bool)
  21. for _, protocol := range users {
  22. userMap[protocol] = true
  23. }
  24. return &UserItem{
  25. users: users,
  26. userMap: userMap,
  27. }
  28. }
  29. func (r *UserItem) Match(metadata *adapter.InboundContext) bool {
  30. if metadata.ProcessInfo == nil || metadata.ProcessInfo.User == "" {
  31. return false
  32. }
  33. return r.userMap[metadata.ProcessInfo.User]
  34. }
  35. func (r *UserItem) String() string {
  36. if len(r.users) == 1 {
  37. return F.ToString("user=", r.users[0])
  38. }
  39. return F.ToString("user=[", strings.Join(r.users, " "), "]")
  40. }