plugin.go 4.4 KB

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