fix: waf condition

This commit is contained in:
naiba
2024-11-23 10:21:01 +08:00
parent 867f840265
commit cd42b1b9d5
8 changed files with 154 additions and 131 deletions

View File

@@ -2,7 +2,9 @@ package utils
import (
"crypto/rand"
"errors"
"math/big"
"net/netip"
"os"
"regexp"
"strconv"
@@ -37,6 +39,35 @@ func IPDesensitize(ipAddr string) string {
return ipAddr
}
func IPStringToBinary(ip string) ([]byte, error) {
addr, err := netip.ParseAddr(ip)
if err != nil {
return nil, err
}
b := addr.As16()
return b[:], nil
}
func BinaryToIPString(b []byte) string {
var addr16 [16]byte
copy(addr16[:], b)
addr := netip.AddrFrom16(addr16)
return addr.Unmap().String()
}
func GetIPFromHeader(headerValue string) (string, error) {
a := strings.Split(headerValue, ",")
h := strings.TrimSpace(a[len(a)-1])
ip, err := netip.ParseAddrPort(h)
if err != nil {
return "", err
}
if !ip.IsValid() {
return "", errors.New("invalid ip")
}
return ip.Addr().String(), nil
}
// SplitIPAddr 传入/分割的v4v6混合地址返回v4和v6地址与有效地址
func SplitIPAddr(v4v6Bundle string) (string, string, string) {
ipList := strings.Split(v4v6Bundle, "/")

View File

@@ -1,6 +1,7 @@
package utils
import (
"reflect"
"testing"
)
@@ -56,3 +57,80 @@ func TestGenerGenerateRandomString(t *testing.T) {
generatedString[str] = true
}
}
func TestIPStringToBinary(t *testing.T) {
cases := []struct {
ip string
want []byte
expectError bool
}{
// 有效的 IPv4 地址
{
ip: "192.168.1.1",
want: []byte{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 192, 168, 1, 1,
},
expectError: false,
},
// 有效的 IPv6 地址
{
ip: "2001:db8::68",
want: []byte{
32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104,
},
expectError: false,
},
// 无效的 IP 地址
{
ip: "invalid_ip",
want: []byte{},
expectError: true,
},
}
for _, c := range cases {
got, err := IPStringToBinary(c.ip)
if (err != nil) != c.expectError {
t.Errorf("IPStringToBinary(%q) error = %v, expect error = %v", c.ip, err, c.expectError)
continue
}
if err == nil && !reflect.DeepEqual(got, c.want) {
t.Errorf("IPStringToBinary(%q) = %v, want %v", c.ip, got, c.want)
}
}
}
func TestBinaryToIPString(t *testing.T) {
cases := []struct {
binary []byte
want string
}{
// IPv4 地址IPv4 映射的 IPv6 地址格式)
{
binary: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 192, 168, 1, 1},
want: "192.168.1.1",
},
// 其他测试用例
{
binary: []byte{32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104},
want: "2001:db8::68",
},
// 全零值
{
binary: []byte{},
want: "::",
},
// IPv4 映射的 IPv6 地址
{
binary: []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 0, 0, 1},
want: "127.0.0.1",
},
}
for _, c := range cases {
got := BinaryToIPString(c.binary)
if got != c.want {
t.Errorf("BinaryToIPString(%v) = %q, 期望 %q", c.binary, got, c.want)
}
}
}