config.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package config
  5. import (
  6. "fmt"
  7. "net"
  8. "strconv"
  9. "strings"
  10. "github.com/coredhcp/coredhcp/logger"
  11. "github.com/insomniacslk/dhcp/dhcpv4"
  12. "github.com/insomniacslk/dhcp/dhcpv6"
  13. "github.com/spf13/cast"
  14. "github.com/spf13/viper"
  15. )
  16. var log = logger.GetLogger("config")
  17. type protocolVersion int
  18. const (
  19. protocolV6 protocolVersion = 6
  20. protocolV4 protocolVersion = 4
  21. )
  22. // Config holds the DHCPv6/v4 server configuration
  23. type Config struct {
  24. v *viper.Viper
  25. Server6 *ServerConfig
  26. Server4 *ServerConfig
  27. }
  28. // New returns a new initialized instance of a Config object
  29. func New() *Config {
  30. return &Config{v: viper.New()}
  31. }
  32. // ServerConfig holds a server configuration that is specific to either the
  33. // DHCPv6 server or the DHCPv4 server.
  34. type ServerConfig struct {
  35. Addresses []*net.UDPAddr
  36. Plugins []*PluginConfig
  37. }
  38. // PluginConfig holds the configuration of a plugin
  39. type PluginConfig struct {
  40. Name string
  41. Args []string
  42. }
  43. // Load reads a configuration file and returns a Config object, or an error if
  44. // any.
  45. func Load() (*Config, error) {
  46. log.Print("Loading configuration")
  47. c := New()
  48. c.v.SetConfigType("yml")
  49. c.v.SetConfigName("config")
  50. c.v.AddConfigPath(".")
  51. c.v.AddConfigPath("$HOME/.coredhcp/")
  52. c.v.AddConfigPath("/etc/coredhcp/")
  53. if err := c.v.ReadInConfig(); err != nil {
  54. return nil, err
  55. }
  56. if err := c.parseConfig(protocolV6); err != nil {
  57. return nil, err
  58. }
  59. if err := c.parseConfig(protocolV4); err != nil {
  60. return nil, err
  61. }
  62. if c.Server6 == nil && c.Server4 == nil {
  63. return nil, ConfigErrorFromString("need at least one valid config for DHCPv6 or DHCPv4")
  64. }
  65. return c, nil
  66. }
  67. func protoVersionCheck(v protocolVersion) error {
  68. if v != protocolV6 && v != protocolV4 {
  69. return fmt.Errorf("invalid protocol version: %d", v)
  70. }
  71. return nil
  72. }
  73. func parsePlugins(pluginList []interface{}) ([]*PluginConfig, error) {
  74. plugins := make([]*PluginConfig, 0)
  75. for idx, val := range pluginList {
  76. conf := cast.ToStringMap(val)
  77. if conf == nil {
  78. return nil, ConfigErrorFromString("dhcpv6: plugin #%d is not a string map", idx)
  79. }
  80. // make sure that only one item is specified, since it's a
  81. // map name -> args
  82. if len(conf) != 1 {
  83. return nil, ConfigErrorFromString("dhcpv6: exactly one plugin per item can be specified")
  84. }
  85. var (
  86. name string
  87. args []string
  88. )
  89. // only one item, as enforced above, so read just that
  90. for k, v := range conf {
  91. name = k
  92. args = strings.Fields(cast.ToString(v))
  93. break
  94. }
  95. plugins = append(plugins, &PluginConfig{Name: name, Args: args})
  96. }
  97. return plugins, nil
  98. }
  99. // BUG(Natolumin): listen specifications of the form `[ip6]%iface:port` or
  100. // `[ip6]%iface` are not supported, even though they are the default format of
  101. // the `ss` utility in linux. Use `[ip6%iface]:port` instead
  102. // splitHostPort splits an address of the form ip%zone:port into ip,zone and port.
  103. // It still returns if any of these are unset (unlike net.SplitHostPort which
  104. // returns an error if there is no port)
  105. func splitHostPort(hostport string) (ip string, zone string, port string, err error) {
  106. ip, port, err = net.SplitHostPort(hostport)
  107. if err != nil {
  108. // Either there is no port, or a more serious error.
  109. // Supply a synthetic port to differentiate cases
  110. var altErr error
  111. if ip, _, altErr = net.SplitHostPort(hostport + ":0"); altErr != nil {
  112. // Invalid even with a fake port. Return the original error
  113. return
  114. }
  115. err = nil
  116. }
  117. if i := strings.LastIndexByte(ip, '%'); i >= 0 {
  118. ip, zone = ip[:i], ip[i+1:]
  119. }
  120. return
  121. }
  122. func (c *Config) getListenAddress(addr string, ver protocolVersion) (*net.UDPAddr, error) {
  123. if err := protoVersionCheck(ver); err != nil {
  124. return nil, err
  125. }
  126. ipStr, ifname, portStr, err := splitHostPort(addr)
  127. if err != nil {
  128. return nil, ConfigErrorFromString("dhcpv%d: %v", ver, err)
  129. }
  130. ip := net.ParseIP(ipStr)
  131. if ipStr == "" {
  132. switch ver {
  133. case protocolV4:
  134. ip = net.IPv4zero
  135. case protocolV6:
  136. ip = net.IPv6unspecified
  137. default:
  138. panic("BUG: Unknown protocol version")
  139. }
  140. }
  141. if ip == nil {
  142. return nil, ConfigErrorFromString("dhcpv%d: invalid IP address in `listen` directive: %s", ver, ipStr)
  143. }
  144. if ip4 := ip.To4(); (ver == protocolV6 && ip4 != nil) || (ver == protocolV4 && ip4 == nil) {
  145. return nil, ConfigErrorFromString("dhcpv%d: not a valid IPv%d address in `listen` directive: '%s'", ver, ver, ipStr)
  146. }
  147. var port int
  148. if portStr == "" {
  149. switch ver {
  150. case protocolV4:
  151. port = dhcpv4.ServerPort
  152. case protocolV6:
  153. port = dhcpv6.DefaultServerPort
  154. default:
  155. panic("BUG: Unknown protocol version")
  156. }
  157. } else {
  158. port, err = strconv.Atoi(portStr)
  159. if err != nil {
  160. return nil, ConfigErrorFromString("dhcpv%d: invalid `listen` port '%s'", ver, portStr)
  161. }
  162. }
  163. listener := net.UDPAddr{
  164. IP: ip,
  165. Port: port,
  166. Zone: ifname,
  167. }
  168. return &listener, nil
  169. }
  170. func (c *Config) getPlugins(ver protocolVersion) ([]*PluginConfig, error) {
  171. if err := protoVersionCheck(ver); err != nil {
  172. return nil, err
  173. }
  174. pluginList := cast.ToSlice(c.v.Get(fmt.Sprintf("server%d.plugins", ver)))
  175. if pluginList == nil {
  176. return nil, ConfigErrorFromString("dhcpv%d: invalid plugins section, not a list or no plugin specified", ver)
  177. }
  178. return parsePlugins(pluginList)
  179. }
  180. func (c *Config) parseConfig(ver protocolVersion) error {
  181. if err := protoVersionCheck(ver); err != nil {
  182. return err
  183. }
  184. if exists := c.v.Get(fmt.Sprintf("server%d", ver)); exists == nil {
  185. // it is valid to have no server configuration defined
  186. return nil
  187. }
  188. // read plugin configuration
  189. plugins, err := c.getPlugins(ver)
  190. if err != nil {
  191. return err
  192. }
  193. for _, p := range plugins {
  194. log.Printf("DHCPv%d: found plugin `%s` with %d args: %v", ver, p.Name, len(p.Args), p.Args)
  195. }
  196. listen := c.v.Get(fmt.Sprintf("server%d.listen", ver))
  197. addrs, err := cast.ToStringSliceE(listen)
  198. if err != nil {
  199. addrs = []string{cast.ToString(listen)}
  200. }
  201. listeners := []*net.UDPAddr{}
  202. for _, a := range addrs {
  203. listenAddr, err := c.getListenAddress(a, ver)
  204. if err != nil {
  205. return err
  206. }
  207. listeners = append(listeners, listenAddr)
  208. }
  209. sc := ServerConfig{
  210. Addresses: listeners,
  211. Plugins: plugins,
  212. }
  213. if ver == protocolV6 {
  214. c.Server6 = &sc
  215. } else if ver == protocolV4 {
  216. c.Server4 = &sc
  217. }
  218. return nil
  219. }