chg: [isNet] silly bug -- remastered

d4forward v0.1.2
Jean-Louis Huynen 2020-02-25 15:54:10 +01:00
parent 0ef9aada6f
commit f30d3c1b52
No known key found for this signature in database
GPG Key ID: 64799157F4BD6B93
2 changed files with 55 additions and 11 deletions

View File

@ -23,11 +23,11 @@ func IsNet(host string) (bool, string) {
// E.g., "[fe80::1]:80". // E.g., "[fe80::1]:80".
i := strings.LastIndex(host, "]") i := strings.LastIndex(host, "]")
if i < 0 { if i < 0 {
log.Fatal("Unmatched [ in destination config") log.Println("Unmatched [ in destination config")
return false, "" return false, ""
} }
if !validPort(host[i+1:]) { if !validPort(host[i+1:]) {
log.Fatal("No valid port specified") log.Println("No valid port specified")
return false, "" return false, ""
} }
// trim brackets // trim brackets
@ -36,19 +36,25 @@ func IsNet(host string) (bool, string) {
} }
} else { } else {
// Ipv4 or DNS name // Ipv4 or DNS name
ss := strings.Split(string(host), ":") ss := strings.Split(host, ":")
if len(ss) > 1 { if len(ss) > 1 {
if !validPort(":" + ss[1]) { if !validPort(":" + ss[1]) {
log.Fatal("No valid port specified") log.Println("No valid port specified")
return false, "" return false, ""
} }
// if not nil, its a valid IP adress
if net.ParseIP(ss[0]) != nil { if net.ParseIP(ss[0]) != nil {
return true, host return true, host
} }
// if "localhost", its valid
if strings.Compare("localhost", ss[0]) == 0 {
return true, host
}
// check against the regex
if validDNS.MatchString(ss[0]) { if validDNS.MatchString(ss[0]) {
return true, host return true, host
} else { } else {
log.Fatal(fmt.Sprintf("DNS/IP: %s, Server Port: %s\n", ss[0], ss[1])) log.Println(fmt.Sprintf("DNS/IP: %s, Server Port: %s", ss[0], ss[1]))
return false, "" return false, ""
} }
} }

38
d4-golang-utils_test.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"testing"
config "github.com/D4-project/d4-golang-utils/config"
)
var testCases = []struct {
name string
str string
expected bool
}{
{"Well-formed IPv4 with port", "127.0.0.1:4443", true},
{"Well-formed IPv4 without port", "127.0.0.1", false},
{"Malformed IPv4 with port", "127..0.1:4443", false},
{"Malformed IPv4 without port", "127..0.1", false},
{"Well-formed IPv6 with port - 2", "[::1]:4443", true},
{"Well-formed IPv6 without port", "[fe80::1%25en0]", false},
{"Malformed IPv6 with port", "[::::1]:4443", false},
{"Malformed IPv6 without port", "[::::::::1]", false},
{"Malformed IPv6 : missing square brackets", "::::::::1:4443", false},
{"Well-formed DNS name with port", "toto.circl.lu:4443", true},
{"Well-formed DNS name without port", "toto.circl.lu", false},
{"Malformed DNS name with port", ".:4443", false},
{"Localhost with port", "localhost:4443", true},
}
func TestIsNet(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
b, _ := config.IsNet(tc.str)
if b != tc.expected {
t.Fail()
}
})
}
}