config.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. "errors"
  7. "fmt"
  8. "net"
  9. "strconv"
  10. "strings"
  11. "github.com/coredhcp/coredhcp/logger"
  12. "github.com/insomniacslk/dhcp/dhcpv4"
  13. "github.com/insomniacslk/dhcp/dhcpv6"
  14. "github.com/spf13/cast"
  15. "github.com/spf13/viper"
  16. )
  17. var log = logger.GetLogger("config")
  18. type protocolVersion int
  19. const (
  20. protocolV6 protocolVersion = 6
  21. protocolV4 protocolVersion = 4
  22. )
  23. // Config holds the DHCPv6/v4 server configuration
  24. type Config struct {
  25. v *viper.Viper
  26. Server6 *ServerConfig
  27. Server4 *ServerConfig
  28. }
  29. // New returns a new initialized instance of a Config object
  30. func New() *Config {
  31. return &Config{v: viper.New()}
  32. }
  33. // ServerConfig holds a server configuration that is specific to either the
  34. // DHCPv6 server or the DHCPv4 server.
  35. type ServerConfig struct {
  36. Addresses []net.UDPAddr
  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, len(pluginList))
  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(addr string, ver protocolVersion) (*net.UDPAddr, error) {
  124. if err := protoVersionCheck(ver); err != nil {
  125. return nil, err
  126. }
  127. ipStr, ifname, portStr, err := splitHostPort(addr)
  128. if err != nil {
  129. return nil, ConfigErrorFromString("dhcpv%d: %v", ver, err)
  130. }
  131. ip := net.ParseIP(ipStr)
  132. if ipStr == "" {
  133. switch ver {
  134. case protocolV4:
  135. ip = net.IPv4zero
  136. case protocolV6:
  137. ip = net.IPv6unspecified
  138. default:
  139. panic("BUG: Unknown protocol version")
  140. }
  141. }
  142. if ip == nil {
  143. return nil, ConfigErrorFromString("dhcpv%d: invalid IP address in `listen` directive: %s", ver, ipStr)
  144. }
  145. if ip4 := ip.To4(); (ver == protocolV6 && ip4 != nil) || (ver == protocolV4 && ip4 == nil) {
  146. return nil, ConfigErrorFromString("dhcpv%d: not a valid IPv%d address in `listen` directive: '%s'", ver, ver, ipStr)
  147. }
  148. var port int
  149. if portStr == "" {
  150. switch ver {
  151. case protocolV4:
  152. port = dhcpv4.ServerPort
  153. case protocolV6:
  154. port = dhcpv6.DefaultServerPort
  155. default:
  156. panic("BUG: Unknown protocol version")
  157. }
  158. } else {
  159. port, err = strconv.Atoi(portStr)
  160. if err != nil {
  161. return nil, ConfigErrorFromString("dhcpv%d: invalid `listen` port '%s'", ver, portStr)
  162. }
  163. }
  164. listener := net.UDPAddr{
  165. IP: ip,
  166. Port: port,
  167. Zone: ifname,
  168. }
  169. return &listener, nil
  170. }
  171. func (c *Config) getPlugins(ver protocolVersion) ([]PluginConfig, error) {
  172. if err := protoVersionCheck(ver); err != nil {
  173. return nil, err
  174. }
  175. pluginList := cast.ToSlice(c.v.Get(fmt.Sprintf("server%d.plugins", ver)))
  176. if pluginList == nil {
  177. return nil, ConfigErrorFromString("dhcpv%d: invalid plugins section, not a list or no plugin specified", ver)
  178. }
  179. return parsePlugins(pluginList)
  180. }
  181. func (c *Config) parseConfig(ver protocolVersion) error {
  182. if err := protoVersionCheck(ver); err != nil {
  183. return err
  184. }
  185. if exists := c.v.Get(fmt.Sprintf("server%d", ver)); exists == nil {
  186. // it is valid to have no server configuration defined
  187. return nil
  188. }
  189. // read plugin configuration
  190. plugins, err := c.getPlugins(ver)
  191. if err != nil {
  192. return err
  193. }
  194. for _, p := range plugins {
  195. log.Printf("DHCPv%d: found plugin `%s` with %d args: %v", ver, p.Name, len(p.Args), p.Args)
  196. }
  197. listeners, err := c.parseListen(ver)
  198. if err != nil {
  199. return err
  200. }
  201. sc := ServerConfig{
  202. Addresses: listeners,
  203. Plugins: plugins,
  204. }
  205. if ver == protocolV6 {
  206. c.Server6 = &sc
  207. } else if ver == protocolV4 {
  208. c.Server4 = &sc
  209. }
  210. return nil
  211. }
  212. // BUG(Natolumin): When listening on link-local multicast addresses without
  213. // binding to a specific interface, new interfaces coming up after the server
  214. // starts will not be taken into account.
  215. func expandLLMulticast(addr *net.UDPAddr) ([]net.UDPAddr, error) {
  216. if !addr.IP.IsLinkLocalMulticast() && !addr.IP.IsInterfaceLocalMulticast() {
  217. return nil, errors.New("Address is not multicast")
  218. }
  219. if addr.Zone != "" {
  220. return nil, errors.New("Address is already zoned")
  221. }
  222. var needFlags = net.FlagMulticast
  223. if addr.IP.To4() != nil {
  224. // We need to be able to send broadcast responses in ipv4
  225. needFlags |= net.FlagBroadcast
  226. }
  227. ifs, err := net.Interfaces()
  228. ret := make([]net.UDPAddr, 0, len(ifs))
  229. if err != nil {
  230. return nil, fmt.Errorf("Could not list network interfaces: %v", err)
  231. }
  232. for _, iface := range ifs {
  233. if (iface.Flags & needFlags) != needFlags {
  234. continue
  235. }
  236. caddr := *addr
  237. caddr.Zone = iface.Name
  238. ret = append(ret, caddr)
  239. }
  240. if len(ret) == 0 {
  241. return nil, errors.New("No suitable interface found for multicast listener")
  242. }
  243. return ret, nil
  244. }
  245. func (c *Config) parseListen(ver protocolVersion) ([]net.UDPAddr, error) {
  246. if err := protoVersionCheck(ver); err != nil {
  247. return nil, err
  248. }
  249. listen := c.v.Get(fmt.Sprintf("server%d.listen", ver))
  250. addrs, err := cast.ToStringSliceE(listen)
  251. if err != nil {
  252. addrs = []string{cast.ToString(listen)}
  253. }
  254. listeners := []net.UDPAddr{}
  255. for _, a := range addrs {
  256. l, err := c.getListenAddress(a, ver)
  257. if err != nil {
  258. return nil, err
  259. }
  260. if l.Zone == "" && (l.IP.IsLinkLocalMulticast() || l.IP.IsInterfaceLocalMulticast()) {
  261. // link-local multicast specified without interface gets expanded to listen on all interfaces
  262. expanded, err := expandLLMulticast(l)
  263. if err != nil {
  264. return nil, err
  265. }
  266. listeners = append(listeners, expanded...)
  267. continue
  268. }
  269. listeners = append(listeners, *l)
  270. }
  271. return listeners, nil
  272. }