-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_dir.go
249 lines (218 loc) · 5.98 KB
/
host_dir.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
"github.com/seancfoley/ipaddress-go/ipaddr"
)
type reservationData struct {
Tags []string `json:"tags"`
IPv4 string `json:"ipv4" binding:"required"`
Hostname string `json:"hostname,omitempty"`
LeaseTime string `json:"lease_time,omitempty"`
}
type reservation struct {
MAC string `json:"mac" binding:"required"`
reservationData
}
func validateMAC(mac string) (*ipaddr.MACAddress, error) {
addr, err := ipaddr.NewMACAddressString(mac).ToAddress()
if err != nil {
return nil, err
}
return addr, nil
}
func validateIPv4(ipv4 string) (*ipaddr.IPAddress, error) {
addr, err := ipaddr.NewIPAddressString(ipv4).ToAddress()
if err != nil {
return nil, err
}
return addr, nil
}
func createReservationFile(input reservation, c *gin.Context, hostDir string, overwrite bool) {
mac, err := validateMAC(input.MAC)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid MAC address"})
return
}
content := mac.ToColonDelimitedString()
if len(input.Tags) > 0 {
content += "," + strings.Join(prefixTags(input.Tags), ",")
}
if ipv4, err := validateIPv4(input.IPv4); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid IPv4 address"})
return
} else {
content += "," + ipv4.String()
}
if input.Hostname != "" {
content += "," + input.Hostname
}
if input.LeaseTime != "" {
content += "," + input.LeaseTime
}
content += "\n"
filePath := filepath.Join(hostDir, mac.ToNormalizedString())
if _, err := os.Stat(filePath); err == nil && !overwrite {
c.JSON(http.StatusConflict, gin.H{"error": "exists"})
return
}
if err := os.WriteFile(filePath, []byte(content), 0640); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "success"})
}
func updateReservationFile(input reservationData, mac string, c *gin.Context, hostDir string) {
createReservationFile(reservation{MAC: mac, reservationData: input}, c, hostDir, true)
}
func deleteReservationFile(c *gin.Context, hostDir string) {
mac, err := validateMAC(c.Param("mac"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid MAC address"})
return
}
filePath := filepath.Join(hostDir, mac.ToNormalizedString())
if err := os.Remove(filePath); err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "no such reservation"})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
c.JSON(http.StatusOK, gin.H{"message": "success"})
}
func readReservationFile(mac string, hostDir string) (reservation, error) {
filePath := filepath.Join(hostDir, mac)
file, err := os.Open(filePath)
if err != nil {
return reservation{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
line := scanner.Text()
parts := strings.Split(line, ",")
if len(parts) < 3 {
return reservation{}, fmt.Errorf("invalid file format")
}
res := reservation{
MAC: parts[0],
reservationData: reservationData{
Tags: []string{},
IPv4: parts[1],
Hostname: "",
LeaseTime: "",
},
}
if strings.HasPrefix(parts[1], "set:") {
res.Tags = strings.Split(strings.Replace(parts[1], "set:", "", 1), ",")
res.IPv4 = parts[2]
if len(parts) > 3 {
res.Hostname = parts[3]
}
if len(parts) > 4 {
res.LeaseTime = parts[4]
}
} else {
if len(parts) > 2 {
res.Hostname = parts[2]
}
if len(parts) > 3 {
res.LeaseTime = parts[3]
}
}
return res, nil
}
if err := scanner.Err(); err != nil {
return reservation{}, err
}
return reservation{}, nil
}
func getReservationFile(c *gin.Context, hostDir string) {
macParam := c.Param("mac")
if macParam != "" {
mac, err := validateMAC(macParam)
if err != nil || !mac.ToAddressString().IsValid() {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid MAC address"})
} else {
if res, err := readReservationFile(mac.ToNormalizedString(), hostDir); err == nil {
c.JSON(http.StatusOK, res)
} else {
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "no such reservation"})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
}
} else {
var reservations []reservation
err := filepath.Walk(hostDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
macAddr, err := validateMAC(info.Name())
if err == nil {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
if res, err := readReservationFile(macAddr.ToNormalizedString(), hostDir); err == nil {
reservations = append(reservations, res)
}
}
}
return nil
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, reservations)
}
}
func prefixTags(tags []string) []string {
for i, tag := range tags {
tags[i] = "set:" + tag
}
return tags
}
func DhcpHostDir(r *gin.Engine, hostDir string) *gin.Engine {
r.POST("/reservations", func(c *gin.Context) {
var input struct {
MAC string `json:"mac" binding:"required"`
reservationData
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
createReservationFile(input, c, hostDir, false)
})
r.PUT("/reservations/:mac", func(c *gin.Context) {
var input reservationData
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
updateReservationFile(input, c.Param("mac"), c, hostDir)
})
r.DELETE("/reservations/:mac", func(c *gin.Context) {
deleteReservationFile(c, hostDir)
})
r.GET("/reservations", func(c *gin.Context) {
getReservationFile(c, hostDir)
})
r.GET("/reservations/:mac", func(c *gin.Context) {
getReservationFile(c, hostDir)
})
return r
}