config.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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(pathOverride string) (*Config, error) {
  47. log.Print("Loading configuration")
  48. c := New()
  49. c.v.SetConfigType("yml")
  50. if pathOverride != "" {
  51. c.v.SetConfigFile(pathOverride)
  52. } else {
  53. c.v.SetConfigName("config")
  54. c.v.AddConfigPath(".")
  55. c.v.AddConfigPath("$XDG_CONFIG_HOME/coredhcp/")
  56. c.v.AddConfigPath("$HOME/.coredhcp/")
  57. c.v.AddConfigPath("/etc/coredhcp/")
  58. }
  59. if err := c.v.ReadInConfig(); err != nil {
  60. return nil, err
  61. }
  62. if err := c.parseConfig(protocolV6); err != nil {
  63. return nil, err
  64. }
  65. if err := c.parseConfig(protocolV4); err != nil {
  66. return nil, err
  67. }
  68. if c.Server6 == nil && c.Server4 == nil {
  69. return nil, ConfigErrorFromString("need at least one valid config for DHCPv6 or DHCPv4")
  70. }
  71. return c, nil
  72. }
  73. func protoVersionCheck(v protocolVersion) error {
  74. if v != protocolV6 && v != protocolV4 {
  75. return fmt.Errorf("invalid protocol version: %d", v)
  76. }
  77. return nil
  78. }
  79. func parsePlugins(pluginList []interface{}) ([]PluginConfig, error) {
  80. plugins := make([]PluginConfig, 0, len(pluginList))
  81. for idx, val := range pluginList {
  82. conf := cast.ToStringMap(val)
  83. if conf == nil {
  84. return nil, ConfigErrorFromString("dhcpv6: plugin #%d is not a string map", idx)
  85. }
  86. // make sure that only one item is specified, since it's a
  87. // map name -> args
  88. if len(conf) != 1 {
  89. return nil, ConfigErrorFromString("dhcpv6: exactly one plugin per item can be specified")
  90. }
  91. var (
  92. name string
  93. args []string
  94. )
  95. // only one item, as enforced above, so read just that
  96. for k, v := range conf {
  97. name = k
  98. args = strings.Fields(cast.ToString(v))
  99. break
  100. }
  101. plugins = append(plugins, PluginConfig{Name: name, Args: args})
  102. }
  103. return plugins, nil
  104. }
  105. // BUG(Natolumin): listen specifications of the form `[ip6]%iface:port` or
  106. // `[ip6]%iface` are not supported, even though they are the default format of
  107. // the `ss` utility in linux. Use `[ip6%iface]:port` instead
  108. // splitHostPort splits an address of the form ip%zone:port into ip,zone and port.
  109. // It still returns if any of these are unset (unlike net.SplitHostPort which
  110. // returns an error if there is no port)
  111. func splitHostPort(hostport string) (ip string, zone string, port string, err error) {
  112. ip, port, err = net.SplitHostPort(hostport)
  113. if err != nil {
  114. // Either there is no port, or a more serious error.
  115. // Supply a synthetic port to differentiate cases
  116. var altErr error
  117. if ip, _, altErr = net.SplitHostPort(hostport + ":0"); altErr != nil {
  118. // Invalid even with a fake port. Return the original error
  119. return
  120. }
  121. err = nil
  122. }
  123. if i := strings.LastIndexByte(ip, '%'); i >= 0 {
  124. ip, zone = ip[:i], ip[i+1:]
  125. }
  126. return
  127. }
  128. func (c *Config) getListenAddress(addr string, ver protocolVersion) (*net.UDPAddr, error) {
  129. if err := protoVersionCheck(ver); err != nil {
  130. return nil, err
  131. }
  132. ipStr, ifname, portStr, err := splitHostPort(addr)
  133. if err != nil {
  134. return nil, ConfigErrorFromString("dhcpv%d: %v", ver, err)
  135. }
  136. ip := net.ParseIP(ipStr)
  137. if ipStr == "" {
  138. switch ver {
  139. case protocolV4:
  140. ip = net.IPv4zero
  141. case protocolV6:
  142. ip = net.IPv6unspecified
  143. default:
  144. panic("BUG: Unknown protocol version")
  145. }
  146. }
  147. if ip == nil {
  148. return nil, ConfigErrorFromString("dhcpv%d: invalid IP address in `listen` directive: %s", ver, ipStr)
  149. }
  150. if ip4 := ip.To4(); (ver == protocolV6 && ip4 != nil) || (ver == protocolV4 && ip4 == nil) {
  151. return nil, ConfigErrorFromString("dhcpv%d: not a valid IPv%d address in `listen` directive: '%s'", ver, ver, ipStr)
  152. }
  153. var port int
  154. if portStr == "" {
  155. switch ver {
  156. case protocolV4:
  157. port = dhcpv4.ServerPort
  158. case protocolV6:
  159. port = dhcpv6.DefaultServerPort
  160. default:
  161. panic("BUG: Unknown protocol version")
  162. }
  163. } else {
  164. port, err = strconv.Atoi(portStr)
  165. if err != nil {
  166. return nil, ConfigErrorFromString("dhcpv%d: invalid `listen` port '%s'", ver, portStr)
  167. }
  168. }
  169. listener := net.UDPAddr{
  170. IP: ip,
  171. Port: port,
  172. Zone: ifname,
  173. }
  174. return &listener, nil
  175. }
  176. func (c *Config) getPlugins(ver protocolVersion) ([]PluginConfig, error) {
  177. if err := protoVersionCheck(ver); err != nil {
  178. return nil, err
  179. }
  180. pluginList := cast.ToSlice(c.v.Get(fmt.Sprintf("server%d.plugins", ver)))
  181. if pluginList == nil {
  182. return nil, ConfigErrorFromString("dhcpv%d: invalid plugins section, not a list or no plugin specified", ver)
  183. }
  184. return parsePlugins(pluginList)
  185. }
  186. func (c *Config) parseConfig(ver protocolVersion) error {
  187. if err := protoVersionCheck(ver); err != nil {
  188. return err
  189. }
  190. if exists := c.v.Get(fmt.Sprintf("server%d", ver)); exists == nil {
  191. // it is valid to have no server configuration defined
  192. return nil
  193. }
  194. // read plugin configuration
  195. plugins, err := c.getPlugins(ver)
  196. if err != nil {
  197. return err
  198. }
  199. for _, p := range plugins {
  200. log.Printf("DHCPv%d: found plugin `%s` with %d args: %v", ver, p.Name, len(p.Args), p.Args)
  201. }
  202. listeners, err := c.parseListen(ver)
  203. if err != nil {
  204. return err
  205. }
  206. sc := ServerConfig{
  207. Addresses: listeners,
  208. Plugins: plugins,
  209. }
  210. if ver == protocolV6 {
  211. c.Server6 = &sc
  212. } else if ver == protocolV4 {
  213. c.Server4 = &sc
  214. }
  215. return nil
  216. }
  217. // BUG(Natolumin): When listening on link-local multicast addresses without
  218. // binding to a specific interface, new interfaces coming up after the server
  219. // starts will not be taken into account.
  220. func expandLLMulticast(addr *net.UDPAddr) ([]net.UDPAddr, error) {
  221. if !addr.IP.IsLinkLocalMulticast() && !addr.IP.IsInterfaceLocalMulticast() {
  222. return nil, errors.New("Address is not multicast")
  223. }
  224. if addr.Zone != "" {
  225. return nil, errors.New("Address is already zoned")
  226. }
  227. var needFlags = net.FlagMulticast
  228. if addr.IP.To4() != nil {
  229. // We need to be able to send broadcast responses in ipv4
  230. needFlags |= net.FlagBroadcast
  231. }
  232. ifs, err := net.Interfaces()
  233. ret := make([]net.UDPAddr, 0, len(ifs))
  234. if err != nil {
  235. return nil, fmt.Errorf("Could not list network interfaces: %v", err)
  236. }
  237. for _, iface := range ifs {
  238. if (iface.Flags & needFlags) != needFlags {
  239. continue
  240. }
  241. caddr := *addr
  242. caddr.Zone = iface.Name
  243. ret = append(ret, caddr)
  244. }
  245. if len(ret) == 0 {
  246. return nil, errors.New("No suitable interface found for multicast listener")
  247. }
  248. return ret, nil
  249. }
  250. func defaultListen(ver protocolVersion) ([]net.UDPAddr, error) {
  251. switch ver {
  252. case protocolV4:
  253. return []net.UDPAddr{{Port: dhcpv4.ServerPort}}, nil
  254. case protocolV6:
  255. l, err := expandLLMulticast(&net.UDPAddr{IP: dhcpv6.AllDHCPRelayAgentsAndServers, Port: dhcpv6.DefaultServerPort})
  256. if err != nil {
  257. return nil, err
  258. }
  259. l = append(l,
  260. net.UDPAddr{IP: dhcpv6.AllDHCPServers, Port: dhcpv6.DefaultServerPort},
  261. // XXX: Do we want to listen on [::] as default ?
  262. )
  263. return l, nil
  264. }
  265. return nil, errors.New("defaultListen: Incorrect protocol version")
  266. }
  267. func (c *Config) parseListen(ver protocolVersion) ([]net.UDPAddr, error) {
  268. if err := protoVersionCheck(ver); err != nil {
  269. return nil, err
  270. }
  271. listen := c.v.Get(fmt.Sprintf("server%d.listen", ver))
  272. // Provide an emulation of the old keyword "interface" to avoid breaking config files
  273. if iface := c.v.Get(fmt.Sprintf("server%d.interface", ver)); iface != nil && listen != nil {
  274. return nil, ConfigErrorFromString("interface is a deprecated alias for listen, " +
  275. "both cannot be used at the same time. Choose one and remove the other.")
  276. } else if iface != nil {
  277. listen = "%" + cast.ToString(iface)
  278. }
  279. if listen == nil {
  280. return defaultListen(ver)
  281. }
  282. addrs, err := cast.ToStringSliceE(listen)
  283. if err != nil {
  284. addrs = []string{cast.ToString(listen)}
  285. }
  286. listeners := []net.UDPAddr{}
  287. for _, a := range addrs {
  288. l, err := c.getListenAddress(a, ver)
  289. if err != nil {
  290. return nil, err
  291. }
  292. if l.Zone == "" && (l.IP.IsLinkLocalMulticast() || l.IP.IsInterfaceLocalMulticast()) {
  293. // link-local multicast specified without interface gets expanded to listen on all interfaces
  294. expanded, err := expandLLMulticast(l)
  295. if err != nil {
  296. return nil, err
  297. }
  298. listeners = append(listeners, expanded...)
  299. continue
  300. }
  301. listeners = append(listeners, *l)
  302. }
  303. return listeners, nil
  304. }