add all files from Hong

This commit is contained in:
zhangsz
2025-06-30 09:23:28 +08:00
parent ceb1fe2640
commit 9b7d32fbd9
69 changed files with 7280 additions and 0 deletions

193
plugins/range/plugin.go Normal file
View File

@@ -0,0 +1,193 @@
// Copyright 2018-present the CoreDHCP Authors. All rights reserved
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package rangeplugin
import (
"database/sql"
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/coredhcp/coredhcp/grpc_server/dhcpServer"
"github.com/coredhcp/coredhcp/handler"
"github.com/coredhcp/coredhcp/logger"
"github.com/coredhcp/coredhcp/plugins"
"github.com/coredhcp/coredhcp/plugins/allocators"
"github.com/coredhcp/coredhcp/plugins/allocators/bitmap"
"github.com/insomniacslk/dhcp/dhcpv4"
)
var log = logger.GetLogger("plugins/range")
// Plugin wraps plugin registration information
var Plugin = plugins.Plugin{
Name: "range",
Setup4: setupRange,
}
//Record holds an IP lease record
type Record struct {
IP net.IP
Static bool
Expires int
Hostname string
}
// PluginState is the data held by an instance of the range plugin
type PluginState struct {
// Rough lock for the whole plugin, we'll get better performance once we use leasestorage
sync.Mutex
// Recordsv4 holds a MAC -> IP address and lease time mapping
Recordsv4 map[string]*Record
LeaseTime time.Duration
leasedb *sql.DB
allocator allocators.Allocator
}
var p PluginState
// Handler4 handles DHCPv4 packets for the range plugin
func (p *PluginState) Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
p.Lock()
defer p.Unlock()
record, ok := p.Recordsv4[req.ClientHWAddr.String()]
hostname := req.HostName()
if !ok {
// Allocating new address since there isn't one allocated
log.Printf("MAC address %s is new, leasing new IPv4 address", req.ClientHWAddr.String())
var netIp net.IP
var isStatic bool
if addr := GetStaticIp(req.ClientHWAddr.String()); addr != "" {
netIp = net.ParseIP(addr)
isStatic = true
} else {
ip, err := p.allocator.Allocate(net.IPNet{})
if err != nil {
log.Errorf("Could not allocate IP for MAC %s: %v", req.ClientHWAddr.String(), err)
return nil, true
}
netIp = ip.IP.To4()
}
rec := Record{
IP: netIp,
Static: isStatic,
Expires: int(time.Now().Add(p.LeaseTime).Unix()),
Hostname: hostname,
}
err := p.saveIPAddress(req.ClientHWAddr, &rec)
if err != nil {
log.Errorf("SaveIPAddress for MAC %s failed: %v", req.ClientHWAddr.String(), err)
}
p.Recordsv4[req.ClientHWAddr.String()] = &rec
record = &rec
} else {
if addr := GetStaticIp(req.ClientHWAddr.String()); addr != "" {
record.IP = net.ParseIP(addr)
record.Static = true
}
// Ensure we extend the existing lease at least past when the one we're giving expires
expiry := time.Unix(int64(record.Expires), 0)
if expiry.Before(time.Now().Add(p.LeaseTime)) {
record.Expires = int(time.Now().Add(p.LeaseTime).Round(time.Second).Unix())
record.Hostname = hostname
err := p.saveIPAddress(req.ClientHWAddr, record)
if err != nil {
log.Errorf("Could not persist lease for MAC %s: %v", req.ClientHWAddr.String(), err)
}
}
}
resp.YourIPAddr = record.IP
resp.Options.Update(dhcpv4.OptIPAddressLeaseTime(p.LeaseTime.Round(time.Second)))
log.Printf("found IP address %s for MAC %s", record.IP, req.ClientHWAddr.String())
return resp, false
}
func GetRecord(clientHWAddr string) *Record {
p.Lock()
defer p.Unlock()
return p.Recordsv4[clientHWAddr]
}
func GetDhcpInfo() (*dhcpServer.DhcpInfo, error) {
p.Lock()
defer p.Unlock()
var dhcpInfo dhcpServer.DhcpInfo
for mac, record := range p.Recordsv4 {
if record.Static { continue }
endTime := time.Unix(int64(record.Expires), 0)
startTime := endTime.Add(-p.LeaseTime)
dhcpInfo.UeInfo = append(dhcpInfo.UeInfo, &dhcpServer.UeInfo{
Ip: record.IP.String(),
Mac: mac,
Hostname: record.Hostname,
StartTime: startTime.Format(time.DateTime),
EndTime: endTime.Format(time.DateTime),
})
}
return &dhcpInfo, nil
}
func setupRange(args ...string) (handler.Handler4, error) {
var err error
if len(args) < 4 {
return nil, fmt.Errorf("invalid number of arguments, want: 4 (file name, start IP, end IP, lease time), got: %d", len(args))
}
filename := args[0]
if filename == "" {
return nil, errors.New("file name cannot be empty")
}
ipRangeStart := net.ParseIP(args[1])
if ipRangeStart.To4() == nil {
return nil, fmt.Errorf("invalid IPv4 address: %v", args[1])
}
ipRangeEnd := net.ParseIP(args[2])
if ipRangeEnd.To4() == nil {
return nil, fmt.Errorf("invalid IPv4 address: %v", args[2])
}
if binary.BigEndian.Uint32(ipRangeStart.To4()) >= binary.BigEndian.Uint32(ipRangeEnd.To4()) {
return nil, errors.New("start of IP range has to be lower than the end of an IP range")
}
p.allocator, err = bitmap.NewIPv4Allocator(ipRangeStart, ipRangeEnd)
if err != nil {
return nil, fmt.Errorf("could not create an allocator: %w", err)
}
p.LeaseTime, err = time.ParseDuration(args[3])
if err != nil {
return nil, fmt.Errorf("invalid lease duration: %v", args[3])
}
if err := p.registerBackingDB(filename); err != nil {
return nil, fmt.Errorf("could not setup lease storage: %w", err)
}
p.Recordsv4, err = loadRecords(p.leasedb)
if err != nil {
return nil, fmt.Errorf("could not load records from file: %v", err)
}
log.Printf("Loaded %d DHCPv4 leases from %s", len(p.Recordsv4), filename)
for _, v := range p.Recordsv4 {
if v.Static {
continue
}
ip, err := p.allocator.Allocate(net.IPNet{IP: v.IP})
if err != nil {
return nil, fmt.Errorf("failed to re-allocate leased ip %v: %v", v.IP.String(), err)
}
if ip.IP.String() != v.IP.String() {
return nil, fmt.Errorf("allocator did not re-allocate requested leased ip %v: %v", v.IP.String(), ip.String())
}
}
importStaticIpFile()
return p.Handler4, nil
}

169
plugins/range/plugin.go.new Normal file
View File

@@ -0,0 +1,169 @@
// Copyright 2018-present the CoreDHCP Authors. All rights reserved
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package rangeplugin
import (
"database/sql"
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/coredhcp/coredhcp/handler"
"github.com/coredhcp/coredhcp/logger"
"github.com/coredhcp/coredhcp/plugins"
"github.com/coredhcp/coredhcp/plugins/allocators"
"github.com/coredhcp/coredhcp/plugins/allocators/bitmap"
"github.com/insomniacslk/dhcp/dhcpv4"
)
var log = logger.GetLogger("plugins/range")
// Plugin wraps plugin registration information
var Plugin = plugins.Plugin{
Name: "range",
Setup4: setupRange,
}
//Record holds an IP lease record
type Record struct {
IP net.IP
expires int
hostname string
}
// PluginState is the data held by an instance of the range plugin
type PluginState struct {
// Rough lock for the whole plugin, we'll get better performance once we use leasestorage
sync.Mutex
// Recordsv4 holds a MAC -> IP address and lease time mapping
Recordsv4 map[string]*Record
LeaseTime time.Duration
leasedb *sql.DB
allocator allocators.Allocator
}
var p PluginState
// Handler4 handles DHCPv4 packets for the range plugin
func (p *PluginState) Handler4(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
p.Lock()
defer p.Unlock()
if ip := GetStaticIp(req.ClientHWAddr.String()); ip != "" {
resp.YourIPAddr = net.ParseIP(ip)
resp.Options.Update(dhcpv4.OptIPAddressLeaseTime(p.LeaseTime.Round(time.Second)))
log.Printf("found static IP address %s for MAC %s", ip, req.ClientHWAddr.String())
return resp, false
}
record, ok := p.Recordsv4[req.ClientHWAddr.String()]
hostname := req.HostName()
if !ok {
// Allocating new address since there isn't one allocated
log.Printf("MAC address %s is new, leasing new IPv4 address", req.ClientHWAddr.String())
ip, err := p.allocator.Allocate(net.IPNet{})
if err != nil {
log.Errorf("Could not allocate IP for MAC %s: %v", req.ClientHWAddr.String(), err)
return nil, true
}
rec := Record{
IP: ip.IP.To4(),
expires: int(time.Now().Add(p.LeaseTime).Unix()),
hostname: hostname,
}
err = p.saveIPAddress(req.ClientHWAddr, &rec)
if err != nil {
log.Errorf("SaveIPAddress for MAC %s failed: %v", req.ClientHWAddr.String(), err)
}
p.Recordsv4[req.ClientHWAddr.String()] = &rec
record = &rec
} else {
// Ensure we extend the existing lease at least past when the one we're giving expires
expiry := time.Unix(int64(record.expires), 0)
if expiry.Before(time.Now().Add(p.LeaseTime)) {
record.expires = int(time.Now().Add(p.LeaseTime).Round(time.Second).Unix())
record.hostname = hostname
err := p.saveIPAddress(req.ClientHWAddr, record)
if err != nil {
log.Errorf("Could not persist lease for MAC %s: %v", req.ClientHWAddr.String(), err)
}
}
}
resp.YourIPAddr = record.IP
resp.Options.Update(dhcpv4.OptIPAddressLeaseTime(p.LeaseTime.Round(time.Second)))
log.Printf("found IP address %s for MAC %s", record.IP, req.ClientHWAddr.String())
return resp, false
}
func GetRecord(clientHWAddr string) (string, string) {
p.Lock()
defer p.Unlock()
record := p.Recordsv4[clientHWAddr]
if record != nil {
return record.IP.String(), record.hostname
} else {
return "-", "-"
}
}
func setupRange(args ...string) (handler.Handler4, error) {
var err error
if len(args) < 4 {
return nil, fmt.Errorf("invalid number of arguments, want: 4 (file name, start IP, end IP, lease time), got: %d", len(args))
}
filename := args[0]
if filename == "" {
return nil, errors.New("file name cannot be empty")
}
ipRangeStart := net.ParseIP(args[1])
if ipRangeStart.To4() == nil {
return nil, fmt.Errorf("invalid IPv4 address: %v", args[1])
}
ipRangeEnd := net.ParseIP(args[2])
if ipRangeEnd.To4() == nil {
return nil, fmt.Errorf("invalid IPv4 address: %v", args[2])
}
if binary.BigEndian.Uint32(ipRangeStart.To4()) >= binary.BigEndian.Uint32(ipRangeEnd.To4()) {
return nil, errors.New("start of IP range has to be lower than the end of an IP range")
}
p.allocator, err = bitmap.NewIPv4Allocator(ipRangeStart, ipRangeEnd)
if err != nil {
return nil, fmt.Errorf("could not create an allocator: %w", err)
}
p.LeaseTime, err = time.ParseDuration(args[3])
if err != nil {
return nil, fmt.Errorf("invalid lease duration: %v", args[3])
}
if err := p.registerBackingDB(filename); err != nil {
return nil, fmt.Errorf("could not setup lease storage: %w", err)
}
p.Recordsv4, err = loadRecords(p.leasedb)
if err != nil {
return nil, fmt.Errorf("could not load records from file: %v", err)
}
log.Printf("Loaded %d DHCPv4 leases from %s", len(p.Recordsv4), filename)
for _, v := range p.Recordsv4 {
ip, err := p.allocator.Allocate(net.IPNet{IP: v.IP})
if err != nil {
return nil, fmt.Errorf("failed to re-allocate leased ip %v: %v", v.IP.String(), err)
}
if ip.IP.String() != v.IP.String() {
return nil, fmt.Errorf("allocator did not re-allocate requested leased ip %v: %v", v.IP.String(), ip.String())
}
}
importStaticIpFile()
return p.Handler4, nil
}

View File

@@ -0,0 +1,50 @@
package rangeplugin
import (
"encoding/csv"
"fmt"
"io"
"os"
)
const staticIpFile string = "./static_ip.csv"
var staticIpPool map[string]string // mac as key
var macPool map[string]string // ip as key
func importStaticIpFile() {
fs, err := os.Open(staticIpFile)
if err != nil {
//fmt.Println(err)
return
}
defer fs.Close()
staticIpPool = make(map[string]string)
macPool = make(map[string]string)
r := csv.NewReader(fs)
for {
row, err := r.Read()
if err != nil && err != io.EOF {
fmt.Printf("Can not read, err is %+v", err)
}
if err == io.EOF {
break
}
//fmt.Println(row)
if len(row) > 1 {
staticIpPool[row[0]] = row[1]
macPool[row[1]] = row[0]
}
}
}
func GetStaticIp(mac string) string {
return staticIpPool[mac]
}
func IsStaticIp(ip string) bool {
_, ok := macPool[ip]
return ok
}

93
plugins/range/storage.go Normal file
View File

@@ -0,0 +1,93 @@
// Copyright 2018-present the CoreDHCP Authors. All rights reserved
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package rangeplugin
import (
"database/sql"
"errors"
"fmt"
"net"
_ "github.com/mattn/go-sqlite3"
)
func loadDB(path string) (*sql.DB, error) {
db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s", path))
if err != nil {
return nil, fmt.Errorf("failed to open database (%T): %w", err, err)
}
if _, err := db.Exec("create table if not exists leases4 (mac string not null, ip string not null, static bool, expiry int, hostname string not null, primary key (mac, ip))"); err != nil {
return nil, fmt.Errorf("table creation failed: %w", err)
}
return db, nil
}
// loadRecords loads the DHCPv6/v4 Records global map with records stored on
// the specified file. The records have to be one per line, a mac address and an
// IP address.
func loadRecords(db *sql.DB) (map[string]*Record, error) {
rows, err := db.Query("select mac, ip, static, expiry, hostname from leases4")
if err != nil {
return nil, fmt.Errorf("failed to query leases database: %w", err)
}
defer rows.Close()
var (
mac, ip, hostname string
static bool
expiry int
records = make(map[string]*Record)
)
for rows.Next() {
if err := rows.Scan(&mac, &ip, &static, &expiry, &hostname); err != nil {
return nil, fmt.Errorf("failed to scan row: %w", err)
}
hwaddr, err := net.ParseMAC(mac)
if err != nil {
return nil, fmt.Errorf("malformed hardware address: %s", mac)
}
ipaddr := net.ParseIP(ip)
if ipaddr.To4() == nil {
return nil, fmt.Errorf("expected an IPv4 address, got: %v", ipaddr)
}
records[hwaddr.String()] = &Record{IP: ipaddr, Static: static, Expires: expiry, Hostname: hostname}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("failed lease database row scanning: %w", err)
}
return records, nil
}
// saveIPAddress writes out a lease to storage
func (p *PluginState) saveIPAddress(mac net.HardwareAddr, record *Record) error {
stmt, err := p.leasedb.Prepare(`insert or replace into leases4(mac, ip, static, expiry, hostname) values (?, ?, ?, ?, ?)`)
if err != nil {
return fmt.Errorf("statement preparation failed: %w", err)
}
defer stmt.Close()
if _, err := stmt.Exec(
mac.String(),
record.IP.String(),
record.Static,
record.Expires,
record.Hostname,
); err != nil {
return fmt.Errorf("record insert/update failed: %w", err)
}
return nil
}
// registerBackingDB installs a database connection string as the backing store for leases
func (p *PluginState) registerBackingDB(filename string) error {
if p.leasedb != nil {
return errors.New("cannot swap out a lease database while running")
}
// We never close this, but that's ok because plugins are never stopped/unregistered
newLeaseDB, err := loadDB(filename)
if err != nil {
return fmt.Errorf("failed to open lease database %s: %w", filename, err)
}
p.leasedb = newLeaseDB
return nil
}

View File

@@ -0,0 +1,99 @@
// Copyright 2018-present the CoreDHCP Authors. All rights reserved
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package rangeplugin
import (
"database/sql"
"fmt"
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func testDBSetup() (*sql.DB, error) {
db, err := loadDB(":memory:")
if err != nil {
return nil, err
}
for _, record := range records {
stmt, err := db.Prepare("insert into leases4(mac, ip, expiry, hostname) values (?, ?, ?, ?)")
if err != nil {
return nil, fmt.Errorf("failed to prepare insert statement: %w", err)
}
defer stmt.Close()
if _, err := stmt.Exec(record.mac, record.ip.IP.String(), record.ip.expires, record.ip.hostname); err != nil {
return nil, fmt.Errorf("failed to insert record into test db: %w", err)
}
}
return db, nil
}
var expire = int(time.Date(2000, 01, 01, 00, 00, 00, 00, time.UTC).Unix())
var records = []struct {
mac string
ip *Record
}{
{"02:00:00:00:00:00", &Record{IP: net.IPv4(10, 0, 0, 0), expires: expire, hostname: "zero"}},
{"02:00:00:00:00:01", &Record{IP: net.IPv4(10, 0, 0, 1), expires: expire, hostname: "one"}},
{"02:00:00:00:00:02", &Record{IP: net.IPv4(10, 0, 0, 2), expires: expire, hostname: "two"}},
{"02:00:00:00:00:03", &Record{IP: net.IPv4(10, 0, 0, 3), expires: expire, hostname: "three"}},
{"02:00:00:00:00:04", &Record{IP: net.IPv4(10, 0, 0, 4), expires: expire, hostname: "four"}},
{"02:00:00:00:00:05", &Record{IP: net.IPv4(10, 0, 0, 5), expires: expire, hostname: "five"}},
}
func TestLoadRecords(t *testing.T) {
db, err := testDBSetup()
if err != nil {
t.Fatalf("Failed to set up test DB: %v", err)
}
parsedRec, err := loadRecords(db)
if err != nil {
t.Fatalf("Failed to load records from file: %v", err)
}
mapRec := make(map[string]*Record)
for _, rec := range records {
var (
ip, mac, hostname string
expiry int
)
if err := db.QueryRow("select mac, ip, expiry, hostname from leases4 where mac = ?", rec.mac).Scan(&mac, &ip, &expiry, &hostname); err != nil {
t.Fatalf("record not found for mac=%s: %v", rec.mac, err)
}
mapRec[mac] = &Record{IP: net.ParseIP(ip), expires: expiry, hostname: hostname}
}
assert.Equal(t, mapRec, parsedRec, "Loaded records differ from what's in the DB")
}
func TestWriteRecords(t *testing.T) {
pl := PluginState{}
if err := pl.registerBackingDB(":memory:"); err != nil {
t.Fatalf("Could not setup file")
}
mapRec := make(map[string]*Record)
for _, rec := range records {
hwaddr, err := net.ParseMAC(rec.mac)
if err != nil {
// bug in testdata
panic(err)
}
if err := pl.saveIPAddress(hwaddr, rec.ip); err != nil {
t.Errorf("Failed to save ip for %s: %v", hwaddr, err)
}
mapRec[hwaddr.String()] = &Record{IP: rec.ip.IP, expires: rec.ip.expires, hostname: rec.ip.hostname}
}
parsedRec, err := loadRecords(pl.leasedb)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, mapRec, parsedRec, "Loaded records differ from what's in the DB")
}