Improve localhost address validation (#9634)

* 🎨 Improv localhost address validation

* 🐛 Compatible with browser extension
This commit is contained in:
Yingyi / 颖逸 2023-11-12 08:52:34 +08:00 committed by GitHub
parent 8a8fc17d21
commit c90072c3cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 81 additions and 44 deletions

View file

@ -17,6 +17,7 @@
package util
import (
"net"
"net/http"
"net/url"
"strings"
@ -31,6 +32,58 @@ import (
"github.com/siyuan-note/logging"
)
func ValidOptionalPort(port string) bool {
if port == "" {
return true
}
if port[0] != ':' {
return false
}
for _, b := range port[1:] {
if b < '0' || b > '9' {
return false
}
}
return true
}
func SplitHost(host string) (hostname, port string) {
hostname = host
colon := strings.LastIndexByte(hostname, ':')
if colon != -1 && ValidOptionalPort(hostname[colon:]) {
hostname, port = hostname[:colon], hostname[colon+1:]
}
if strings.HasPrefix(hostname, "[") && strings.HasSuffix(hostname, "]") {
hostname = hostname[1 : len(hostname)-1]
}
return
}
func IsLocalHostname(hostname string) bool {
if "localhost" == hostname {
return true
}
if ip := net.ParseIP(hostname); nil != ip {
return ip.IsLoopback()
}
return false
}
func IsLocalHost(host string) bool {
hostname, _ := SplitHost(host)
return IsLocalHostname(hostname)
}
func IsLocalOrigin(origin string) bool {
if url, err := url.Parse(origin); nil == err {
return IsLocalHostname(url.Hostname())
}
return false
}
func IsOnline(checkURL string, skipTlsVerify bool) bool {
_, err := url.Parse(checkURL)
if nil != err {