-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
executable file
·99 lines (70 loc) · 2.27 KB
/
api.py
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
#!/usr/bin/env python2
# Contributers:
# sphinx
# themind (jpypi on Github)
import flask
import dhcpreg
from re import compile as re_compile
app = flask.Flask(__name__)
FAIL = 'failure'
FAILURE = (FAIL, 400, [])
valid_mac_patt = re_compile("[:\-]".join(("[0-9a-fA-F]{2}",)*6))
def ValidateMac(mac_string):
if valid_mac_patt.match(mac_string):
return mac_string.replace("-", ":").lower()
return False
@app.route('/reg', methods=['POST'])
def reg():
mac_addr = ValidateMac(flask.request.form.get('mac', ''))
nick = flask.request.form.get('nick', '')
if mac_addr and nick:
# The following may fail if someone tries to register over
# someone else's MAC/nick
if dhcpreg.RegisterMac(mac_addr, nick):
return 'success'
return FAILURE
@app.route('/dereg', methods=['POST'])
def dereg():
mac_addr = ValidateMac(flask.request.form.get('mac', ''))
nick = flask.request.form.get('nick', '')
# dhcpreg.DeregisterMac returns True if it succeeded
if mac_addr and nick and dhcpreg.DeregisterMac(mac_addr, nick):
return 'success'
if nick:
return FAIL #'success'
return FAIL
@app.route('/list', methods=['POST'])
def list_nick_macs():
nick = flask.request.form.get('nick', '')
if nick:
mac_addresses = dhcpreg.LookupNick(nick)
if mac_addresses:
return flask.json.dumps(mac_addresses)
return FAILURE
# @app.route('/list/<nick>', methods=['GET'])
# def list_nick_macs(nick):
# if nick:
# mac_addresses = dhcpreg.LookupNick(nick)
# if mac_addresses:
# return flask.json.dumps(mac_addresses)
# return FAILURE
@app.route('/json')
def json_resp():
leases = get_leases()
response = {"registered": leases[0], "others": len(leases[1])}
return flask.json.dumps(response)
@app.route('/plain')
def plain_resp():
l = get_leases()
non_registered = len(l[1])
extra = ""
if non_registered > 0:
extra = " - Unregistered: %d"%non_registered
return ", ".join(l[0])+extra
def get_leases():
# Common usage is via:
# ln -s /var/dhcpd/var/db/dhcpd.leases dhcpd.leases
with open('dhcpd.leases') as f:
return dhcpreg.GetActive(f)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)