plugin.go 1.9 KB

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