plugin.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 staticroute
  5. import (
  6. "errors"
  7. "net"
  8. "strings"
  9. "github.com/coredhcp/coredhcp/handler"
  10. "github.com/coredhcp/coredhcp/logger"
  11. "github.com/coredhcp/coredhcp/plugins"
  12. "github.com/insomniacslk/dhcp/dhcpv4"
  13. )
  14. var log = logger.GetLogger("plugins/staticroute")
  15. // Plugin wraps the information necessary to register a plugin.
  16. var Plugin = plugins.Plugin{
  17. Name: "staticroute",
  18. Setup4: setup4,
  19. }
  20. var routes dhcpv4.Routes
  21. func setup4(args ...string) (handler.Handler4, error) {
  22. log.Printf("loaded plugin for DHCPv4.")
  23. routes = make(dhcpv4.Routes, 0)
  24. if len(args) < 1 {
  25. return nil, errors.New("need at least one static route")
  26. }
  27. var err error
  28. for _, arg := range args {
  29. fields := strings.Split(arg, ",")
  30. if len(fields) != 2 {
  31. return Handler4, errors.New("expected a destination/gateway pair, got: " + arg)
  32. }
  33. route := &dhcpv4.Route{}
  34. _, route.Dest, err = net.ParseCIDR(fields[0])
  35. if err != nil {
  36. return Handler4, errors.New("expected a destination subnet, got: " + fields[0])
  37. }
  38. route.Router = net.ParseIP(fields[1])
  39. if route.Router == nil {
  40. return Handler4, errors.New("expected a gateway address, got: " + fields[1])
  41. }
  42. routes = append(routes, route)
  43. log.Debugf("adding static route %s", route)
  44. }
  45. log.Printf("loaded %d static routes.", len(routes))
  46. return Handler4, nil
  47. }
  48. // Handler4 handles DHCPv4 packets for the static routes plugin
  49. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  50. if len(routes) > 0 {
  51. resp.Options.Update(dhcpv4.Option{
  52. Code: dhcpv4.OptionCode(dhcpv4.OptionClasslessStaticRoute),
  53. Value: routes,
  54. })
  55. }
  56. return resp, false
  57. }