2022-04-10 03:59:27 +08:00
|
|
|
package rewrites
|
|
|
|
|
|
|
|
import (
|
2023-09-03 22:00:37 +08:00
|
|
|
regexp "github.com/dlclark/regexp2"
|
2022-04-10 03:59:27 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
)
|
|
|
|
|
2023-09-03 23:42:27 +08:00
|
|
|
func ParseRewrite(line RawMitmRule) (C.Rewrite, error) {
|
2022-04-10 03:59:27 +08:00
|
|
|
var (
|
|
|
|
urlRegx *regexp.Regexp
|
|
|
|
ruleType *C.RewriteType
|
|
|
|
ruleRegx *regexp.Regexp
|
|
|
|
rulePayload string
|
|
|
|
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
2023-09-03 23:42:27 +08:00
|
|
|
url := line.Url
|
2023-09-03 22:00:37 +08:00
|
|
|
urlRegx, err = regexp.Compile(strings.Trim(url, " "), regexp.None)
|
2022-04-10 03:59:27 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-09-03 23:42:27 +08:00
|
|
|
ruleType = &line.Action
|
|
|
|
switch *ruleType {
|
|
|
|
case C.Mitm302, C.Mitm307:
|
|
|
|
{
|
|
|
|
rulePayload = line.New
|
2022-04-10 03:59:27 +08:00
|
|
|
break
|
|
|
|
}
|
2023-09-03 23:42:27 +08:00
|
|
|
case C.MitmRequestHeader, C.MitmRequestBody, C.MitmResponseHeader, C.MitmResponseBody:
|
|
|
|
{
|
|
|
|
var old string
|
|
|
|
if line.Old == nil {
|
|
|
|
old = ".*"
|
|
|
|
} else {
|
|
|
|
old = *line.Old
|
|
|
|
}
|
2022-04-10 03:59:27 +08:00
|
|
|
|
2023-09-03 23:42:27 +08:00
|
|
|
re, err := regexp.Compile(old, regexp.Singleline)
|
2022-04-10 03:59:27 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-09-03 23:42:27 +08:00
|
|
|
ruleRegx = re
|
2022-04-10 03:59:27 +08:00
|
|
|
|
2023-09-03 23:42:27 +08:00
|
|
|
rulePayload = line.New
|
2022-04-10 03:59:27 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return NewRewriteRule(urlRegx, *ruleType, ruleRegx, rulePayload), nil
|
|
|
|
}
|