plugin.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 rangeplugin
  5. import (
  6. "database/sql"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "net"
  11. "sync"
  12. "time"
  13. "github.com/coredhcp/coredhcp/handler"
  14. "github.com/coredhcp/coredhcp/logger"
  15. "github.com/coredhcp/coredhcp/plugins"
  16. "github.com/coredhcp/coredhcp/plugins/allocators"
  17. "github.com/coredhcp/coredhcp/plugins/allocators/bitmap"
  18. "github.com/insomniacslk/dhcp/dhcpv4"
  19. )
  20. var log = logger.GetLogger("plugins/range")
  21. // Plugin wraps plugin registration information
  22. var Plugin = plugins.Plugin{
  23. Name: "range",
  24. Setup4: setupRange,
  25. }
  26. //Record holds an IP lease record
  27. type Record struct {
  28. IP net.IP
  29. expires int
  30. hostname string
  31. }
  32. // PluginState is the data held by an instance of the range plugin
  33. type PluginState struct {
  34. // Rough lock for the whole plugin, we'll get better performance once we use leasestorage
  35. sync.Mutex
  36. // Recordsv4 holds a MAC -> IP address and lease time mapping
  37. Recordsv4 map[string]*Record
  38. LeaseTime time.Duration
  39. leasedb *sql.DB
  40. allocator allocators.Allocator
  41. }
  42. // Handler4 handles DHCPv4 packets for the range plugin
  43. func (p *PluginState) Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  44. p.Lock()
  45. defer p.Unlock()
  46. record, ok := p.Recordsv4[req.ClientHWAddr.String()]
  47. hostname := req.HostName()
  48. if !ok {
  49. // Allocating new address since there isn't one allocated
  50. log.Printf("MAC address %s is new, leasing new IPv4 address", req.ClientHWAddr.String())
  51. ip, err := p.allocator.Allocate(net.IPNet{})
  52. if err != nil {
  53. log.Errorf("Could not allocate IP for MAC %s: %v", req.ClientHWAddr.String(), err)
  54. return nil, true
  55. }
  56. rec := Record{
  57. IP: ip.IP.To4(),
  58. expires: int(time.Now().Add(p.LeaseTime).Unix()),
  59. hostname: hostname,
  60. }
  61. err = p.saveIPAddress(req.ClientHWAddr, &rec)
  62. if err != nil {
  63. log.Errorf("SaveIPAddress for MAC %s failed: %v", req.ClientHWAddr.String(), err)
  64. }
  65. p.Recordsv4[req.ClientHWAddr.String()] = &rec
  66. record = &rec
  67. } else {
  68. // Ensure we extend the existing lease at least past when the one we're giving expires
  69. expiry := time.Unix(int64(record.expires), 0)
  70. if expiry.Before(time.Now().Add(p.LeaseTime)) {
  71. record.expires = int(time.Now().Add(p.LeaseTime).Round(time.Second).Unix())
  72. record.hostname = hostname
  73. err := p.saveIPAddress(req.ClientHWAddr, record)
  74. if err != nil {
  75. log.Errorf("Could not persist lease for MAC %s: %v", req.ClientHWAddr.String(), err)
  76. }
  77. }
  78. }
  79. resp.YourIPAddr = record.IP
  80. resp.Options.Update(dhcpv4.OptIPAddressLeaseTime(p.LeaseTime.Round(time.Second)))
  81. log.Printf("found IP address %s for MAC %s", record.IP, req.ClientHWAddr.String())
  82. return resp, false
  83. }
  84. func setupRange(args ...string) (handler.Handler4, error) {
  85. var (
  86. err error
  87. p PluginState
  88. )
  89. if len(args) < 4 {
  90. return nil, fmt.Errorf("invalid number of arguments, want: 4 (file name, start IP, end IP, lease time), got: %d", len(args))
  91. }
  92. filename := args[0]
  93. if filename == "" {
  94. return nil, errors.New("file name cannot be empty")
  95. }
  96. ipRangeStart := net.ParseIP(args[1])
  97. if ipRangeStart.To4() == nil {
  98. return nil, fmt.Errorf("invalid IPv4 address: %v", args[1])
  99. }
  100. ipRangeEnd := net.ParseIP(args[2])
  101. if ipRangeEnd.To4() == nil {
  102. return nil, fmt.Errorf("invalid IPv4 address: %v", args[2])
  103. }
  104. if binary.BigEndian.Uint32(ipRangeStart.To4()) > binary.BigEndian.Uint32(ipRangeEnd.To4()) {
  105. return nil, errors.New("start of IP range has to be lower than or equal to the end of an IP range")
  106. }
  107. p.allocator, err = bitmap.NewIPv4Allocator(ipRangeStart, ipRangeEnd)
  108. if err != nil {
  109. return nil, fmt.Errorf("could not create an allocator: %w", err)
  110. }
  111. p.LeaseTime, err = time.ParseDuration(args[3])
  112. if err != nil {
  113. return nil, fmt.Errorf("invalid lease duration: %v", args[3])
  114. }
  115. if err := p.registerBackingDB(filename); err != nil {
  116. return nil, fmt.Errorf("could not setup lease storage: %w", err)
  117. }
  118. p.Recordsv4, err = loadRecords(p.leasedb)
  119. if err != nil {
  120. return nil, fmt.Errorf("could not load records from file: %v", err)
  121. }
  122. log.Printf("Loaded %d DHCPv4 leases from %s", len(p.Recordsv4), filename)
  123. for _, v := range p.Recordsv4 {
  124. ip, err := p.allocator.Allocate(net.IPNet{IP: v.IP})
  125. if err != nil {
  126. return nil, fmt.Errorf("failed to re-allocate leased ip %v: %v", v.IP.String(), err)
  127. }
  128. if ip.IP.String() != v.IP.String() {
  129. return nil, fmt.Errorf("allocator did not re-allocate requested leased ip %v: %v", v.IP.String(), ip.String())
  130. }
  131. }
  132. return p.Handler4, nil
  133. }