plugin.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 netmask
  5. import (
  6. "encoding/binary"
  7. "errors"
  8. "net"
  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/netmask")
  15. // Plugin wraps plugin registration information
  16. var Plugin = plugins.Plugin{
  17. Name: "netmask",
  18. Setup4: setup4,
  19. }
  20. var (
  21. netmask net.IPMask
  22. )
  23. func setup4(args ...string) (handler.Handler4, error) {
  24. log.Printf("loaded plugin for DHCPv4.")
  25. if len(args) != 1 {
  26. return nil, errors.New("need at least one netmask IP address")
  27. }
  28. netmaskIP := net.ParseIP(args[0])
  29. if netmaskIP.IsUnspecified() {
  30. return nil, errors.New("netmask is not valid, got: " + args[0])
  31. }
  32. netmaskIP = netmaskIP.To4()
  33. if netmaskIP == nil {
  34. return nil, errors.New("expected an netmask address, got: " + args[0])
  35. }
  36. netmask = net.IPv4Mask(netmaskIP[0], netmaskIP[1], netmaskIP[2], netmaskIP[3])
  37. if !checkValidNetmask(netmask) {
  38. return nil, errors.New("netmask is not valid, got: " + args[0])
  39. }
  40. log.Printf("loaded client netmask")
  41. return Handler4, nil
  42. }
  43. //Handler4 handles DHCPv4 packets for the netmask plugin
  44. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  45. resp.Options.Update(dhcpv4.OptSubnetMask(netmask))
  46. return resp, false
  47. }
  48. func checkValidNetmask(netmask net.IPMask) bool {
  49. netmaskInt := binary.BigEndian.Uint32(netmask)
  50. x := ^netmaskInt
  51. y := x + 1
  52. return (y & x) == 0
  53. }