github.com/yaling888/clash@v1.53.0/mitm/parser.go (about)

     1  package mitm
     2  
     3  import (
     4  	"strings"
     5  
     6  	regexp "github.com/dlclark/regexp2"
     7  
     8  	C "github.com/yaling888/clash/constant"
     9  )
    10  
    11  const payloadSeparator = "<and>"
    12  
    13  func ParseRewrite(line string) (C.Rewrite, error) {
    14  	url, others, found := strings.Cut(strings.TrimSpace(line), "url")
    15  	if !found {
    16  		return nil, errInvalid
    17  	}
    18  
    19  	var (
    20  		ruleType    *C.RewriteType
    21  		ruleRegx    []*regexp.Regexp
    22  		rulePayload []string
    23  	)
    24  
    25  	urlRegx, err := regexp.Compile(strings.Trim(url, " "), 0)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	others = strings.Trim(others, " ")
    31  	first := strings.Split(others, " ")[0]
    32  	for k, v := range C.RewriteTypeMapping {
    33  		if k == others {
    34  			ruleType = &v
    35  			break
    36  		}
    37  
    38  		if k != first {
    39  			continue
    40  		}
    41  
    42  		rs := trimArr(strings.Split(others, k))
    43  		l := len(rs)
    44  		if l > 2 {
    45  			continue
    46  		}
    47  
    48  		if l == 1 {
    49  			ruleType = &v
    50  			rulePayload = trimArr(strings.Split(rs[0], payloadSeparator))
    51  			break
    52  		} else {
    53  			for _, str := range trimArr(strings.Split(rs[0], payloadSeparator)) {
    54  				regx, err := regexp.Compile(str, 0)
    55  				if err != nil {
    56  					return nil, err
    57  				}
    58  				ruleRegx = append(ruleRegx, regx)
    59  			}
    60  
    61  			ruleType = &v
    62  			rulePayload = trimArr(strings.Split(rs[1], payloadSeparator))
    63  			break
    64  		}
    65  	}
    66  
    67  	if ruleType == nil {
    68  		return nil, errInvalid
    69  	}
    70  
    71  	return NewRewriteRule(urlRegx, *ruleType, ruleRegx, rulePayload), nil
    72  }
    73  
    74  func trimArr(arr []string) (r []string) {
    75  	for _, e := range arr {
    76  		if s := strings.Trim(e, " "); s != "" {
    77  			r = append(r, s)
    78  		}
    79  	}
    80  	return
    81  }