plugin.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "github.com/insomniacslk/dhcp/dhcpv6"
  14. )
  15. var log = logger.GetLogger("plugins/netmask")
  16. // Plugin wraps plugin registration information
  17. var Plugin = plugins.Plugin{
  18. Name: "netmask",
  19. Setup6: setup6,
  20. Setup4: setup4,
  21. }
  22. var (
  23. netmask net.IPMask
  24. )
  25. func setup6(args ...string) (handler.Handler6, error) {
  26. // TODO setup function for IPv6
  27. log.Warning("not implemented for IPv6")
  28. return Handler6, nil
  29. }
  30. func setup4(args ...string) (handler.Handler4, error) {
  31. log.Printf("loaded plugin for DHCPv4.")
  32. if len(args) != 1 {
  33. return nil, errors.New("need at least one netmask IP address")
  34. }
  35. netmaskIP := net.ParseIP(args[0])
  36. if netmaskIP.IsUnspecified() {
  37. return nil, errors.New("netmask is not valid, got: " + args[1])
  38. }
  39. netmaskIP = netmaskIP.To4()
  40. if netmaskIP == nil {
  41. return nil, errors.New("expected an netmask address, got: " + args[1])
  42. }
  43. netmask = net.IPv4Mask(netmaskIP[0], netmaskIP[1], netmaskIP[2], netmaskIP[3])
  44. if !checkValidNetmask(netmask) {
  45. return nil, errors.New("netmask is not valid, got: " + args[1])
  46. }
  47. log.Printf("loaded client netmask")
  48. return Handler4, nil
  49. }
  50. // Handler6 not implemented only IPv4
  51. func Handler6(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  52. // TODO add IPv6 netmask to the response
  53. return resp, false
  54. }
  55. //Handler4 handles DHCPv4 packets for the netmask plugin
  56. func Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  57. resp.Options.Update(dhcpv4.OptSubnetMask(netmask))
  58. return resp, false
  59. }
  60. func checkValidNetmask(netmask net.IPMask) bool {
  61. netmaskInt := binary.BigEndian.Uint32(netmask)
  62. x := ^netmaskInt
  63. y := x + 1
  64. return (y & x) == 0
  65. }