2022-07-17 15:11:26 +08:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2022-07-24 22:54:16 +08:00
|
|
|
"github.com/sagernet/sing-box/common/warning"
|
|
|
|
C "github.com/sagernet/sing-box/constant"
|
2022-07-17 15:11:26 +08:00
|
|
|
F "github.com/sagernet/sing/common/format"
|
|
|
|
)
|
|
|
|
|
2022-07-24 22:54:16 +08:00
|
|
|
var (
|
|
|
|
warnUserOnNonLinux = warning.New(
|
|
|
|
func() bool { return !C.IsLinux },
|
|
|
|
"rule item `user` is only supported on Linux",
|
|
|
|
)
|
|
|
|
warnUserOnCGODisabled = warning.New(
|
|
|
|
func() bool { return !C.CGO_ENABLED },
|
|
|
|
"rule item `user` is only supported with CGO enabled, rebuild with CGO_ENABLED=1",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2022-07-17 15:11:26 +08:00
|
|
|
var _ RuleItem = (*UserItem)(nil)
|
|
|
|
|
|
|
|
type UserItem struct {
|
|
|
|
users []string
|
|
|
|
userMap map[string]bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewUserItem(users []string) *UserItem {
|
2022-07-24 22:54:16 +08:00
|
|
|
warnUserOnNonLinux.Check()
|
|
|
|
warnUserOnCGODisabled.Check()
|
2022-07-17 15:11:26 +08:00
|
|
|
userMap := make(map[string]bool)
|
|
|
|
for _, protocol := range users {
|
|
|
|
userMap[protocol] = true
|
|
|
|
}
|
|
|
|
return &UserItem{
|
|
|
|
users: users,
|
|
|
|
userMap: userMap,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *UserItem) Match(metadata *adapter.InboundContext) bool {
|
2022-07-23 19:01:41 +08:00
|
|
|
if metadata.ProcessInfo == nil || metadata.ProcessInfo.User == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return r.userMap[metadata.ProcessInfo.User]
|
2022-07-17 15:11:26 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *UserItem) String() string {
|
|
|
|
if len(r.users) == 1 {
|
|
|
|
return F.ToString("user=", r.users[0])
|
|
|
|
}
|
|
|
|
return F.ToString("user=[", strings.Join(r.users, " "), "]")
|
|
|
|
}
|