github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/components/shunt/rule.go (about)

     1  package shunt
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"io"
     7  	"log/slog"
     8  	"os"
     9  	"strings"
    10  
    11  	"github.com/Asutorufa/yuhaiin/pkg/log"
    12  	"github.com/Asutorufa/yuhaiin/pkg/protos/config/bypass"
    13  	"github.com/Asutorufa/yuhaiin/pkg/utils/yerror"
    14  	"github.com/yuhaiin/kitte"
    15  )
    16  
    17  func rangeRule(path string, ranger func(string, bypass.ModeEnum)) {
    18  	var reader io.ReadCloser
    19  	var err error
    20  	reader, err = os.Open(path)
    21  	if err != nil {
    22  		log.Error("open bypass file failed, fallback to use internal bypass data",
    23  			slog.String("filepath", path), slog.Any("err", err))
    24  
    25  		reader = io.NopCloser(bytes.NewReader(kitte.Content))
    26  	}
    27  	defer reader.Close()
    28  
    29  	br := bufio.NewScanner(reader)
    30  
    31  	for br.Scan() {
    32  		fields := bytes.Fields(yerror.Ignore2(bytes.Cut(br.Bytes(), []byte{'#'})))
    33  		if len(fields) < 2 {
    34  			continue
    35  		}
    36  
    37  		hostname := strings.ToLower(string(fields[0]))
    38  		args := fields[1]
    39  
    40  		fs := bytes.FieldsFunc(args, func(r rune) bool {
    41  			return r == ','
    42  		})
    43  
    44  		if len(fs) < 1 {
    45  			continue
    46  		}
    47  
    48  		modestr := strings.ToLower(string(fs[0]))
    49  
    50  		mode := bypass.Mode(bypass.Mode_value[modestr])
    51  
    52  		if mode.Unknown() {
    53  			continue
    54  		}
    55  
    56  		f := &bypass.ModeConfig{Mode: mode}
    57  		f.StoreKV(fs[1:])
    58  		ranger(hostname, f.ToModeEnum())
    59  	}
    60  }