github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/cmd/android/tools.go (about)

     1  package yuhaiin
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"errors"
     7  	"io"
     8  	"net"
     9  	"strings"
    10  )
    11  
    12  type CIDR struct {
    13  	IP   string
    14  	Mask int32
    15  }
    16  
    17  func ParseCIDR(s string) (*CIDR, error) {
    18  	_, ipNet, err := net.ParseCIDR(s)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	mask, _ := ipNet.Mask.Size()
    24  	ip := ipNet.IP.String()
    25  	return &CIDR{IP: ip, Mask: int32(mask)}, nil
    26  }
    27  
    28  var v4DefaultMask = net.CIDRMask(32, 32)
    29  var v6DefaultMask = net.CIDRMask(128, 128)
    30  
    31  type AddRoute interface {
    32  	Add(*CIDR)
    33  }
    34  
    35  func AddRulesCidr(process AddRoute, rules string) {
    36  	r := bufio.NewReader(strings.NewReader(rules))
    37  	for {
    38  		line, _, err := r.ReadLine()
    39  		if err != nil {
    40  			if errors.Is(err, io.EOF) {
    41  				break
    42  			}
    43  
    44  			continue
    45  		}
    46  
    47  		z := bytes.FieldsFunc(line, func(r rune) bool { return r == ',' })
    48  		if len(z) == 0 {
    49  			continue
    50  		}
    51  
    52  		_, cidr, err := net.ParseCIDR(string(z[0]))
    53  		if err != nil {
    54  			ip := net.ParseIP(string(z[0]))
    55  			if ip == nil {
    56  				continue
    57  			}
    58  
    59  			var mask []byte
    60  			if ip.To4() != nil {
    61  				mask = v4DefaultMask
    62  			} else {
    63  				mask = v6DefaultMask
    64  			}
    65  
    66  			cidr = &net.IPNet{
    67  				IP:   ip,
    68  				Mask: mask,
    69  			}
    70  		}
    71  
    72  		mask, _ := cidr.Mask.Size()
    73  		ip := cidr.IP.String()
    74  
    75  		process.Add(&CIDR{
    76  			IP:   ip,
    77  			Mask: int32(mask),
    78  		})
    79  	}
    80  }