From a0fd6cfeeab71eb2861f8e8ea672a3091f3642f3 Mon Sep 17 00:00:00 2001 From: Adlyq <2833154405@qq.com> Date: Mon, 4 Sep 2023 13:31:18 +0800 Subject: [PATCH] fix: regexp --- rewrite/handler.go | 22 +++++++++++----------- rewrite/rewrite.go | 35 +++++++++++++++++++++-------------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/rewrite/handler.go b/rewrite/handler.go index aa611751..52e16412 100644 --- a/rewrite/handler.go +++ b/rewrite/handler.go @@ -6,7 +6,6 @@ import ( "errors" log "github.com/sirupsen/logrus" "io" - "io/ioutil" "net/http" "net/textproto" "strconv" @@ -150,19 +149,20 @@ func (*RewriteHandler) HandleResponse(session *mitm.Session) *http.Response { return nil } - body, err := mitm.DecodeLatin1(bytes.NewReader(b)) - if err != nil { - return nil - } + //body, err := mitm.DecodeLatin1(bytes.NewReader(b)) + //if err != nil { + // return nil + //} - newBody := rule.ReplaceSubPayload(body) + newBody := rule.ReplaceSubPayload(string(b)) - modifiedBody, err := mitm.EncodeLatin1(newBody) - if err != nil { - return nil - } + //modifiedBody, err := mitm.EncodeLatin1(newBody) + //if err != nil { + // return nil + //} + modifiedBody := []byte(newBody) - response.Body = ioutil.NopCloser(bytes.NewReader(modifiedBody)) + response.Body = io.NopCloser(bytes.NewReader(modifiedBody)) response.Header.Del("Content-Encoding") response.ContentLength = int64(len(modifiedBody)) default: diff --git a/rewrite/rewrite.go b/rewrite/rewrite.go index 1128f23a..28ff4ca3 100644 --- a/rewrite/rewrite.go +++ b/rewrite/rewrite.go @@ -61,27 +61,34 @@ func (r *RewriteRule) ReplaceURLPayload(matchSub []string) string { func (r *RewriteRule) ReplaceSubPayload(oldData string) string { payload := r.rulePayload + if r.ruleRegx == nil { return oldData } sub, err := r.ruleRegx.FindStringMatch(oldData) - if err != nil { - return oldData + + for err == nil && sub != nil { + var ( + groups []string + sPayload = payload + ) + for _, fg := range sub.Groups() { + groups = append(groups, fg.String()) + } + + l := len(groups) + + for i := 1; i < l; i++ { + sPayload = strings.Replace(payload, "$"+strconv.Itoa(i), groups[i], 1) + } + + oldData = strings.Replace(oldData, groups[0], sPayload, 1) + + sub, err = r.ruleRegx.FindNextMatch(sub) } - var groups []string - for _, fg := range sub.Groups() { - groups = append(groups, fg.String()) - } - - l := len(groups) - - for i := 1; i < l; i++ { - payload = strings.ReplaceAll(payload, "$"+strconv.Itoa(i), groups[i]) - } - - return strings.ReplaceAll(oldData, groups[0], payload) + return oldData } func NewRewriteRule(urlRegx *regexp.Regexp, ruleType C.RewriteType, ruleRegx *regexp.Regexp, rulePayload string) *RewriteRule {