package main import ( "errors" "regexp" "strconv" ) func setNetwork(env map[string]string) error { if ok := validateEthernetAddr(env["ethaddr"]); !ok { return errors.New("invalid ethernet address") } if ok := validateIpAddr(env["ipaddr"]); !ok { return errors.New("invalid ip address") } if ok := validateIpAddr(env["netmask"]); !ok { return errors.New("invalid netmask") } if ok := validateIpAddr(env["gateway"]); !ok { return errors.New("invalid gateway") } if hasDualNetwork { if ok := validateEthernetAddr(env["ethaddr2"]); !ok { return errors.New("invalid ethernet address 2") } if ok := validateIpAddr(env["ipaddr2"]); !ok { return errors.New("invalid ip address 2") } if ok := validateIpAddr(env["netmask2"]); !ok { return errors.New("invalid netmask 2") } if ok := validateIpAddr(env["gateway2"]); !ok { return errors.New("invalid gateway 2") } } return setEnv(0, env) } func validateEthernetAddr(addr string) (ok bool) { r := regexp.MustCompile(`([0-9a-fA-F]{2}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2}):([0-9a-fA-F]{2})`) s := r.FindStringSubmatch(addr) if len(s) != 7 || s[0] != addr { return false } for i, v := range s { if i == 0 { continue } u, err := strconv.ParseUint(v, 16, 8) if err != nil { return false } if u > 255 { return false } } return true } func validateIpAddr(addr string) (ok bool) { r := regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)`) s := r.FindStringSubmatch(addr) if len(s) != 5 || s[0] != addr { return false } for i, v := range s { if i == 0 { continue } u, err := strconv.ParseUint(v, 10, 8) if err != nil { return false } if u > 255 { return false } } return true }