config.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. Listener *net.UDPAddr
  36. Interface string
  37. Plugins []*PluginConfig
  38. }
  39. // PluginConfig holds the configuration of a plugin
  40. type PluginConfig struct {
  41. Name string
  42. Args []string
  43. }
  44. // Load reads a configuration file and returns a Config object, or an error if
  45. // any.
  46. func Load() (*Config, error) {
  47. log.Print("Loading configuration")
  48. c := New()
  49. c.v.SetConfigType("yml")
  50. c.v.SetConfigName("config")
  51. c.v.AddConfigPath(".")
  52. c.v.AddConfigPath("$HOME/.coredhcp/")
  53. c.v.AddConfigPath("/etc/coredhcp/")
  54. if err := c.v.ReadInConfig(); err != nil {
  55. return nil, err
  56. }
  57. if err := c.parseConfig(protocolV6); err != nil {
  58. return nil, err
  59. }
  60. if err := c.parseConfig(protocolV4); err != nil {
  61. return nil, err
  62. }
  63. if c.Server6 == nil && c.Server4 == nil {
  64. return nil, ConfigErrorFromString("need at least one valid config for DHCPv6 or DHCPv4")
  65. }
  66. return c, nil
  67. }
  68. func protoVersionCheck(v protocolVersion) error {
  69. if v != protocolV6 && v != protocolV4 {
  70. return fmt.Errorf("invalid protocol version: %d", v)
  71. }
  72. return nil
  73. }
  74. func parsePlugins(pluginList []interface{}) ([]*PluginConfig, error) {
  75. plugins := make([]*PluginConfig, 0)
  76. for idx, val := range pluginList {
  77. conf := cast.ToStringMap(val)
  78. if conf == nil {
  79. return nil, ConfigErrorFromString("dhcpv6: plugin #%d is not a string map", idx)
  80. }
  81. // make sure that only one item is specified, since it's a
  82. // map name -> args
  83. if len(conf) != 1 {
  84. return nil, ConfigErrorFromString("dhcpv6: exactly one plugin per item can be specified")
  85. }
  86. var (
  87. name string
  88. args []string
  89. )
  90. // only one item, as enforced above, so read just that
  91. for k, v := range conf {
  92. name = k
  93. args = strings.Fields(cast.ToString(v))
  94. break
  95. }
  96. plugins = append(plugins, &PluginConfig{Name: name, Args: args})
  97. }
  98. return plugins, nil
  99. }
  100. // BUG(Natolumin): listen specifications of the form `[ip6]%iface:port` or
  101. // `[ip6]%iface` are not supported, even though they are the default format of
  102. // the `ss` utility in linux. Use `[ip6%iface]:port` instead
  103. // splitHostPort splits an address of the form ip%zone:port into ip,zone and port.
  104. // It still returns if any of these are unset (unlike net.SplitHostPort which
  105. // returns an error if there is no port)
  106. func splitHostPort(hostport string) (ip string, zone string, port string, err error) {
  107. ip, port, err = net.SplitHostPort(hostport)
  108. if err != nil {
  109. // Either there is no port, or a more serious error.
  110. // Supply a synthetic port to differentiate cases
  111. var altErr error
  112. if ip, _, altErr = net.SplitHostPort(hostport + ":0"); altErr != nil {
  113. // Invalid even with a fake port. Return the original error
  114. return
  115. }
  116. err = nil
  117. }
  118. if i := strings.LastIndexByte(ip, '%'); i >= 0 {
  119. ip, zone = ip[:i], ip[i+1:]
  120. }
  121. return
  122. }
  123. func (c *Config) getListenAddress(ver protocolVersion) (*net.UDPAddr, error) {
  124. if err := protoVersionCheck(ver); err != nil {
  125. return nil, err
  126. }
  127. addr := c.v.GetString(fmt.Sprintf("server%d.listen", ver))
  128. ipStr, ifname, portStr, err := splitHostPort(addr)
  129. if err != nil {
  130. return nil, ConfigErrorFromString("dhcpv%d: %v", ver, err)
  131. }
  132. ip := net.ParseIP(ipStr)
  133. if ipStr == "" {
  134. switch ver {
  135. case protocolV4:
  136. ip = net.IPv4zero
  137. case protocolV6:
  138. ip = net.IPv6unspecified
  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", ver, ver)
  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. }
  155. } else {
  156. port, err = strconv.Atoi(portStr)
  157. if err != nil {
  158. return nil, ConfigErrorFromString("dhcpv%d: invalid `listen` port", ver)
  159. }
  160. }
  161. listener := net.UDPAddr{
  162. IP: ip,
  163. Port: port,
  164. Zone: ifname,
  165. }
  166. return &listener, nil
  167. }
  168. func (c *Config) getPlugins(ver protocolVersion) ([]*PluginConfig, error) {
  169. if err := protoVersionCheck(ver); err != nil {
  170. return nil, err
  171. }
  172. pluginList := cast.ToSlice(c.v.Get(fmt.Sprintf("server%d.plugins", ver)))
  173. if pluginList == nil {
  174. return nil, ConfigErrorFromString("dhcpv%d: invalid plugins section, not a list or no plugin specified", ver)
  175. }
  176. return parsePlugins(pluginList)
  177. }
  178. func (c *Config) parseConfig(ver protocolVersion) error {
  179. if err := protoVersionCheck(ver); err != nil {
  180. return err
  181. }
  182. if exists := c.v.Get(fmt.Sprintf("server%d", ver)); exists == nil {
  183. // it is valid to have no server configuration defined
  184. return nil
  185. }
  186. listenAddr, err := c.getListenAddress(ver)
  187. if err != nil {
  188. return err
  189. }
  190. if listenAddr == nil {
  191. // no listener is configured, so `c.Server6` (or `c.Server4` if v4)
  192. // will stay nil.
  193. log.Warnf("DHCPv%d: server%d present but no listen address defined. The server will not be started", ver, ver)
  194. return nil
  195. }
  196. // read plugin configuration
  197. plugins, err := c.getPlugins(ver)
  198. if err != nil {
  199. return err
  200. }
  201. for _, p := range plugins {
  202. log.Printf("DHCPv%d: found plugin `%s` with %d args: %v", ver, p.Name, len(p.Args), p.Args)
  203. }
  204. sc := ServerConfig{
  205. Listener: listenAddr,
  206. Interface: listenAddr.Zone,
  207. Plugins: plugins,
  208. }
  209. if ver == protocolV6 {
  210. c.Server6 = &sc
  211. } else if ver == protocolV4 {
  212. c.Server4 = &sc
  213. }
  214. return nil
  215. }