1
0

rule_user_id.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 warnUserIDOnNonLinux = warning.New(
  10. func() bool { return !C.IsLinux },
  11. "rule item `user_id` is only supported on Linux",
  12. )
  13. var _ RuleItem = (*UserIdItem)(nil)
  14. type UserIdItem struct {
  15. userIds []int32
  16. userIdMap map[int32]bool
  17. }
  18. func NewUserIDItem(userIdList []int32) *UserIdItem {
  19. warnUserIDOnNonLinux.Check()
  20. rule := &UserIdItem{
  21. userIds: userIdList,
  22. userIdMap: make(map[int32]bool),
  23. }
  24. for _, userId := range userIdList {
  25. rule.userIdMap[userId] = true
  26. }
  27. return rule
  28. }
  29. func (r *UserIdItem) Match(metadata *adapter.InboundContext) bool {
  30. if metadata.ProcessInfo == nil || metadata.ProcessInfo.UserId == -1 {
  31. return false
  32. }
  33. return r.userIdMap[metadata.ProcessInfo.UserId]
  34. }
  35. func (r *UserIdItem) String() string {
  36. var description string
  37. pLen := len(r.userIds)
  38. if pLen == 1 {
  39. description = "user_id=" + F.ToString(r.userIds[0])
  40. } else {
  41. description = "user_id=[" + strings.Join(F.MapToString(r.userIds), " ") + "]"
  42. }
  43. return description
  44. }