Skip to content

Commit

Permalink
Support regex matching with attr (#2258)
Browse files Browse the repository at this point in the history
* Support regex matching with attr

* Add test case

* Optimizing regex parsing at core start

* simpliy
  • Loading branch information
yuhan6665 authored Jun 27, 2023
1 parent 07389ec commit a6c5c57
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
11 changes: 6 additions & 5 deletions app/router/condition.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package router

import (
"regexp"
"strings"

"github.com/xtls/xray-core/common/net"
Expand Down Expand Up @@ -282,18 +283,18 @@ func (m *ProtocolMatcher) Apply(ctx routing.Context) bool {
}

type AttributeMatcher struct {
configuredKeys map[string]string
configuredKeys map[string]*regexp.Regexp
}

// Match implements attributes matching.
func (m *AttributeMatcher) Match(attrs map[string]string) bool {
// headers are insensitive most likely. So we do a convert
// header keys are case insensitive most likely. So we do a convert
httpHeaders := make(map[string]string)
for key, value := range attrs {
httpHeaders[strings.ToLower(key)] = strings.ToLower(value)
httpHeaders[strings.ToLower(key)] = value
}
for key, value := range m.configuredKeys {
if a, ok := httpHeaders[key]; !ok || !strings.Contains(a, value) {
for key, regex := range m.configuredKeys {
if a, ok := httpHeaders[key]; !ok || !regex.MatchString(a) {
return false
}
}
Expand Down
13 changes: 13 additions & 0 deletions app/router/condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,19 @@ func TestRoutingRule(t *testing.T) {
},
},
},
{
rule: &RoutingRule{
Attributes: map[string]string{
"Custom": "p([a-z]+)ch",
},
},
test: []ruleTest{
{
input: withContent(&session.Content{Attributes: map[string]string{"custom": "peach"}}),
output: true,
},
},
},
}

for _, test := range cases {
Expand Down
5 changes: 3 additions & 2 deletions app/router/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package router

import (
"regexp"
"strings"

"github.com/xtls/xray-core/common/net"
Expand Down Expand Up @@ -145,9 +146,9 @@ func (rr *RoutingRule) BuildCondition() (Condition, error) {
}

if len(rr.Attributes) > 0 {
configuredKeys := make(map[string]string)
configuredKeys := make(map[string]*regexp.Regexp)
for key, value := range rr.Attributes {
configuredKeys[strings.ToLower(key)] = strings.ToLower(value)
configuredKeys[strings.ToLower(key)] = regexp.MustCompile(value)
}
conds.Add(&AttributeMatcher{configuredKeys})
}
Expand Down

0 comments on commit a6c5c57

Please sign in to comment.