Skip to content

Commit

Permalink
Merge pull request #4 from vinted/fix/create_empty_hash_if_no_options…
Browse files Browse the repository at this point in the history
…_present

rest-dhcpd: create emty maps if no configuration is present
  • Loading branch information
Seitanas authored Mar 1, 2023
2 parents 015d581 + 7f53837 commit 49cf204
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
14 changes: 11 additions & 3 deletions pkg/configdb/configdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,17 @@ var DB *Clients
var Config *GlobalOptions

func Init(configPath string) error {
content, err := os.ReadFile(path.Join(configPath, "rest-dhcpd-clients.json"))
if err != nil {
return err
content := []byte(`{}`)
dataFile := path.Join(configPath, "rest-dhcpd-clients.json")
_, err := os.Stat(dataFile)
if !os.IsNotExist(err) {
content, err = os.ReadFile(dataFile)
if err != nil {
return err
}
}
if len(content) == 0 {
content = []byte(`{}`)
}
err = json.Unmarshal(content, &DB)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/dhcpd/dhcpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (h *DHCPHandler) ServeDHCP(p dhcp.Packet, msgType dhcp.MessageType, options
client, id := rest.SearchForClientByMac(p.CHAddr().String())
if id != -1 { // If client exists in configdb, send a DHCPOFFER
h.options = lo.Assign(h.options, BuildOptions(client.Options)) // Merge global and client DHCP options
h.options[dhcp.OptionHostName] = []byte(client.Hostname) // Set hostname via DHCP options
h.options[dhcp.OptionHostName] = []byte(client.Hostname) // Set hostname via DHCP options
log.Printf("Sending DHCPOFFER to %s with IP: %s.", p.CHAddr().String(), client.IP)
return dhcp.ReplyPacket(p, dhcp.Offer, h.ip, net.ParseIP(client.IP), h.leaseDuration,
h.options.SelectOrderOrAll(options[dhcp.OptionParameterRequestList]))
Expand Down
6 changes: 6 additions & 0 deletions pkg/rest/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ func addClientConfig(config configdb.Client) {
log.Printf("Adding client config for: %s\n", config.MAC)
m := configdb.Mu{}
m.Mu.Lock()
if config.Options == nil {
config.Options = make(map[string]interface{})
}
configdb.DB.Clients = append(configdb.DB.Clients, config)
m.Mu.Unlock()
err := m.Save()
Expand All @@ -125,6 +128,9 @@ func updateClientConfig(id int, config configdb.Client) {
log.Printf("Updating client config for: %s\n", config.MAC)
m := configdb.Mu{}
m.Mu.Lock()
if config.Options == nil {
config.Options = make(map[string]interface{})
}
configdb.DB.Clients[id].IP = config.IP
configdb.DB.Clients[id].Hostname = config.Hostname
configdb.DB.Clients[id].Options = config.Options
Expand Down

0 comments on commit 49cf204

Please sign in to comment.