Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"errors"
"net"
"net/http"
"regexp"
"strings"
net2 "k8s.io/utils/net"
)
const (
domainReg = "^[a-zA-Z0-9][a-zA-Z0-9.-]{1,256}[a-zA-Z0-9]$"
)
func ClientIP(r *http.Request) string {
var ip string
xForwardedFor := r.Header.Get("X-Forwarded-For")
forwardSlice := strings.Split(xForwardedFor, ",")
if len(forwardSlice) >= 1 {
if ip = strings.TrimSpace(forwardSlice[0]); ip != "" {
return ip
}
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
var err error
if ip, _, err = net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
func CheckDomain(domain string, forLocalUsage bool) error {
matched, err := regexp.MatchString(domainReg, domain)
if err != nil {
return err
}
if !matched {
return errors.New("domain does not match allowed regex")
}
if !forLocalUsage {
return nil
}
if IsDigitString(domain) {
return errors.New("domain can not be all digits")
}
if strings.Contains(domain, "localhost") {
return errors.New("domain can not contain localhost")
}
return nil
}
func IsHostValid(host string) (string, error) {
parsedIp := net.ParseIP(host)
if parsedIp != nil {
err := IsIPValid(parsedIp)
if err == nil {
if net2.IsIPv6(parsedIp) {
return "[" + parsedIp.String() + "]", nil
} else {
return parsedIp.String(), nil
}
}
return "", err
}
return host, CheckDomain(host, false)
}
func IsIPValid(parsedIp net.IP) error {
if parsedIp == nil {
return errors.New("parse ip is nil")
}
if parsedIp.To4() == nil && parsedIp.To16() == nil {
return errors.New("not a valid ipv4 or ipv6 ip")
}
if parsedIp.IsUnspecified() {
return errors.New("is all zeros ip")
}
if parsedIp.IsMulticast() {
return errors.New("is multicast ip")
}
return nil
}