pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/knf/validators/network/validators.go (about) 1 // Package network provides KNF validators for checking items related to network 2 package network 3 4 // ////////////////////////////////////////////////////////////////////////////////// // 5 // // 6 // Copyright (c) 2022 ESSENTIAL KAOS // 7 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 8 // // 9 // ////////////////////////////////////////////////////////////////////////////////// // 10 11 import ( 12 "fmt" 13 "net" 14 "net/url" 15 16 "pkg.re/essentialkaos/ek.v12/knf" 17 ) 18 19 // ////////////////////////////////////////////////////////////////////////////////// // 20 21 var ( 22 // IP returns error if config property isn't a valid IP address 23 IP = validateIP 24 25 // Port returns error if config property isn't a valid port number 26 Port = validatePort 27 28 // MAC returns error if config property isn't a valid MAC address 29 MAC = validateMAC 30 31 // CIDR returns error if config property isn't a valid CIDR address 32 CIDR = validateCIDR 33 34 // URL returns error if config property isn't a valid URL 35 URL = validateURL 36 ) 37 38 // ////////////////////////////////////////////////////////////////////////////////// // 39 40 func validateIP(config *knf.Config, prop string, value interface{}) error { 41 ipStr := config.GetS(prop) 42 43 if ipStr == "" { 44 return nil 45 } 46 47 ip := net.ParseIP(ipStr) 48 49 if ip == nil { 50 return fmt.Errorf("%s is not a valid IP address", ipStr) 51 } 52 53 return nil 54 } 55 56 func validatePort(config *knf.Config, prop string, value interface{}) error { 57 portStr := config.GetS(prop) 58 59 if portStr == "" { 60 return nil 61 } 62 63 portInt := config.GetI(prop) 64 65 if portInt == 0 || portInt > 65535 { 66 return fmt.Errorf("%s is not a valid port number", portStr) 67 } 68 69 return nil 70 } 71 72 func validateMAC(config *knf.Config, prop string, value interface{}) error { 73 macStr := config.GetS(prop) 74 75 if macStr == "" { 76 return nil 77 } 78 79 _, err := net.ParseMAC(macStr) 80 81 if err != nil { 82 return fmt.Errorf("%s is not a valid MAC address: %v", macStr, err) 83 } 84 85 return err 86 } 87 88 func validateCIDR(config *knf.Config, prop string, value interface{}) error { 89 cidrStr := config.GetS(prop) 90 91 if cidrStr == "" { 92 return nil 93 } 94 95 _, _, err := net.ParseCIDR(cidrStr) 96 97 if err != nil { 98 return fmt.Errorf("%s is not a valid CIDR address: %v", cidrStr, err) 99 } 100 101 return err 102 } 103 104 func validateURL(config *knf.Config, prop string, value interface{}) error { 105 urlStr := config.GetS(prop) 106 107 if urlStr == "" { 108 return nil 109 } 110 111 _, err := url.ParseRequestURI(urlStr) 112 113 if err != nil { 114 return fmt.Errorf("%s is not a valid URL address: %v", urlStr, err) 115 } 116 117 return err 118 }