-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
264 lines (218 loc) · 7.33 KB
/
api.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/go-ini/ini"
"github.com/gorilla/mux"
"github.com/inverse-inc/packetfence/go/api-frontend/unifiedapierrors"
dhcp "github.com/krolaw/dhcp4"
)
// Node struct
type Node struct {
Mac string `json:"mac"`
IP string `json:"ip"`
EndsAt time.Time `json:"ends_at"`
}
// Stats struct
type Stats struct {
EthernetName string `json:"interface"`
Net string `json:"network"`
Free int `json:"free"`
PercentFree int `json:"percentfree"`
Used int `json:"used"`
PercentUsed int `json:"percentused"`
Category string `json:"category"`
Options map[string]string `json:"options"`
Members []Node `json:"members"`
Status string `json:"status"`
Size int `json:"size"`
}
type Items struct {
Items []Stats `json:"items"`
Status string `json:"status"`
}
type ApiReq struct {
Req string
NetInterface string
NetWork string
Mac string
Role string
}
type Options struct {
Option dhcp.OptionCode `json:"option"`
Value string `json:"value"`
Type string `json:"type"`
}
type Info struct {
Status string `json:"status"`
Mac string `json:"mac,omitempty"`
Network string `json:"network,omitempty"`
}
func handleIP2Mac(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if index, expiresAt, found := GlobalIpCache.GetWithExpiration(vars["ip"]); found {
var node = &Node{Mac: index.(string), IP: vars["ip"], EndsAt: expiresAt}
outgoingJSON, err := json.Marshal(node)
if err != nil {
unifiedapierrors.Error(res, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(res, string(outgoingJSON))
return
}
unifiedapierrors.Error(res, "Cannot find match for this IP address", http.StatusNotFound)
return
}
func handleMac2Ip(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if index, expiresAt, found := GlobalMacCache.GetWithExpiration(vars["mac"]); found {
var node = &Node{Mac: vars["mac"], IP: index.(string), EndsAt: expiresAt}
outgoingJSON, err := json.Marshal(node)
if err != nil {
unifiedapierrors.Error(res, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(res, string(outgoingJSON))
return
}
unifiedapierrors.Error(res, "Cannot find match for this MAC address", http.StatusNotFound)
return
}
func handleAllStats(res http.ResponseWriter, req *http.Request) {
var result Items
cfg, err := ini.Load("/usr/local/etc/godhcp.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
Interfaces := cfg.Section("interfaces").Key("listen").String()
NetInterfaces := strings.Split(Interfaces, ",")
if len(Interfaces) == 0 {
result.Items = append(result.Items, Stats{})
}
for _, i := range NetInterfaces {
if h, ok := intNametoInterface[i]; ok {
stat := h.handleApiReq(ApiReq{Req: "stats", NetInterface: i, NetWork: ""})
for _, s := range stat.([]Stats) {
result.Items = append(result.Items, s)
}
}
}
result.Status = "200"
outgoingJSON, error := json.Marshal(result)
if error != nil {
unifiedapierrors.Error(res, error.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(res, string(outgoingJSON))
return
}
func handleStats(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if h, ok := intNametoInterface[vars["int"]]; ok {
stat := h.handleApiReq(ApiReq{Req: "stats", NetInterface: vars["int"], NetWork: vars["network"]})
outgoingJSON, err := json.Marshal(stat)
if err != nil {
unifiedapierrors.Error(res, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(res, string(outgoingJSON))
return
}
unifiedapierrors.Error(res, "Interface not found", http.StatusNotFound)
return
}
func handleDebug(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
if h, ok := intNametoInterface[vars["int"]]; ok {
stat := h.handleApiReq(ApiReq{Req: "debug", NetInterface: vars["int"], Role: vars["role"]})
outgoingJSON, err := json.Marshal(stat)
if err != nil {
unifiedapierrors.Error(res, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprint(res, string(outgoingJSON))
return
}
unifiedapierrors.Error(res, "Interface not found", http.StatusNotFound)
return
}
func handleReleaseIP(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
_ = InterfaceScopeFromMac(vars["mac"])
var result = &Info{Mac: vars["mac"], Status: "ACK"}
res.Header().Set("Content-Type", "application/json; charset=UTF-8")
res.WriteHeader(http.StatusOK)
if err := json.NewEncoder(res).Encode(result); err != nil {
panic(err)
}
}
func (h *Interface) handleApiReq(Request ApiReq) interface{} {
var stats []Stats
// Send back stats
if Request.Req == "stats" {
for _, v := range h.network {
ipv4Addr, _, erro := net.ParseCIDR(Request.NetWork + "/32")
if erro == nil {
if !(v.network.Contains(ipv4Addr)) {
continue
}
}
var Options map[string]string
Options = make(map[string]string)
Options["optionIPAddressLeaseTime"] = v.dhcpHandler.leaseDuration.String()
for option, value := range v.dhcpHandler.options {
key := []byte(option.String())
key[0] = key[0] | ('a' - 'A')
Options[string(key)] = Tlv.Tlvlist[int(option)].Decode.String(value)
}
var Members []Node
id, _ := GlobalTransactionLock.Lock()
members := v.dhcpHandler.hwcache.Items()
GlobalTransactionLock.Unlock(id)
var Status string
var Count int
Count = 0
for i, item := range members {
Count++
result := make(net.IP, 4)
binary.BigEndian.PutUint32(result, binary.BigEndian.Uint32(v.dhcpHandler.start.To4())+uint32(item.Object.(int)))
Members = append(Members, Node{IP: result.String(), Mac: i, EndsAt: time.Unix(0, item.Expiration)})
}
_, reserved := IPsFromRange(v.dhcpHandler.ipReserved)
if reserved != 1 {
Count = Count + reserved
}
availableCount := int(v.dhcpHandler.available.FreeIPsRemaining())
usedCount := (v.dhcpHandler.leaseRange - availableCount)
percentfree := int((float64(availableCount) / float64(v.dhcpHandler.leaseRange)) * 100)
percentused := int((float64(usedCount) / float64(v.dhcpHandler.leaseRange)) * 100)
if Count == (v.dhcpHandler.leaseRange - availableCount) {
Status = "Normal"
} else {
Status = "Calculated available IP " + strconv.Itoa(v.dhcpHandler.leaseRange-Count) + " is different than what we have available in the pool " + strconv.Itoa(availableCount)
}
stats = append(stats, Stats{EthernetName: Request.NetInterface, Net: v.network.String(), Free: availableCount, Category: v.dhcpHandler.role, Options: Options, Members: Members, Status: Status, Size: v.dhcpHandler.leaseRange, Used: usedCount, PercentFree: percentfree, PercentUsed: percentused})
}
return stats
}
// Debug
if Request.Req == "debug" {
for _, v := range h.network {
if Request.Role == v.dhcpHandler.role {
spew.Dump(v.dhcpHandler.hwcache)
stats = append(stats, Stats{EthernetName: Request.NetInterface, Net: v.network.String(), Free: int(v.dhcpHandler.available.FreeIPsRemaining()), Category: v.dhcpHandler.role, Status: "Debug finished"})
}
}
return stats
}
return nil
}