-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathacnode.py
executable file
·434 lines (320 loc) · 11 KB
/
acnode.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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#!/usr/bin/env python
import re
import sys, os
import logging
import time
import json
import socket
import urlparse
import BaseHTTPServer
import ConfigParser
SERVICE = 'acnode'
config = ConfigParser.ConfigParser()
configs = [
'%(service)s.conf',
'/etc/%(service)s.conf',
'%(scriptdir)s/%(service)s.conf'
]
if not sys.path[0]:
sys.path[0] = '.'
config.read(map(lambda x: x % {'scriptdir': sys.path[0], 'service': SERVICE}, configs))
PORT = config.getint(SERVICE, 'tcpport')
DOCSPAGE = config.get(SERVICE, 'docspage')
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG)
logging.info('Starting %s' % SERVICE)
cardFile = 'carddb.json'
mTime = 0
cards = {}
perms = {}
nodes = {}
class NotFoundError(Exception):
pass
class NoLengthError(Exception):
pass
class Node(object):
def __init__(self, nodeid, perm):
self.nodeid = nodeid
self.perm = perm
self.perms = {}
self.cards = []
self.status = 1
self.tooluse = 0
self.case = 0
self.newperms = {}
def updatePerms(self, perms):
self.perms = {}
for card, userperms in perms.items():
if self.perm in userperms:
self.perms[card] = 1
if '%s-maintainer' % self.perm in userperms:
self.perms[card] = 2
self.perms.update(self.newperms)
def checkCard(self, uid):
reloadCardTable()
return self.perms.get(uid, 0)
def getCard(self, uid=None):
if uid is None:
reloadCardTable()
self.cards = sorted(self.perms.keys())
index = 0
else:
# ValueError if unknown card
index = self.cards.index(uid) + 1
try:
return self.cards[index]
except IndexError, e:
return None
def addCard(self, uid):
self.newperms[uid] = 1
self.perms.update(self.newperms)
for nodeid, perm in config.items('nodeperm'):
nodes[nodeid] = Node(nodeid, perm)
def reloadCardTable():
global mTime
global cards
try:
currentMtime = os.path.getmtime(cardFile)
except IOError, e:
logging.critical('Cannot read card file: %s', repr(e))
raise
if mTime != currentMtime:
logging.debug('Loading card table, mtime %d', currentMtime)
mTime = currentMtime
cards = {}
file = open(cardFile)
users = json.load(file)
for user in users:
for card in user['cards']:
card = card.encode('utf-8')
nick = user['nick'].encode('utf-8')
cards[card] = nick
perms[card] = user['perms']
for node in nodes.values():
node.updatePerms(perms)
logging.info('Loaded %d cards', len(cards))
def broadcast(event, card, name):
try:
logging.debug('Broadcasting %s to network', event)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
data = "%s\n%s\n%s" % (event, card, name)
s.sendto(data, ('<broadcast>', 50000))
except Exception, e:
logging.warn('Exception during broadcast: %s', repr(e))
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
error_content_type = 'text/plain'
# Disable logging DNS lookups
def address_string(self):
return str(self.client_address[0])
def route(self, dispatches):
start = time.time()
self.url = urlparse.urlparse(self.path)
self.params = urlparse.parse_qs(self.url.query)
if 'Accept' in self.headers:
# FIXME: parse properly
for t in self.headers['Accept'].split(','):
t, _, p = t.partition(';')
if 'text/plain' in t or '*/*' in t:
break
else:
html_notacceptable()
self.wfile.write('Sorted types: text/plain\n')
return
for pattern, dispatch in dispatches:
m = re.match(pattern, self.path)
if m:
try:
dispatch(*m.groups())
except NotFoundError, e:
self.text_notfound()
self.wfile.write('%s\n' % repr(e))
except NoLengthError, e:
self.text_nolength()
self.wfile.write('%s\n' % repr(e))
except ValueError, e:
self.text_bad()
self.wfile.write('%s\n' % repr(e))
except Exception, e:
self.text_error()
self.wfile.write('%s\n' % repr(e))
logging.debug(repr(e))
break
else:
self.text_bad()
end = time.time()
logging.debug('Time taken: %0.3f ms' % ((end - start) * 1000))
def text_response(self, code):
self.send_response(code)
self.send_header('Content-type', 'text/plain')
self.end_headers()
def text_ok(self):
self.text_response(200)
def text_added(self):
self.text_response(201)
def text_nocontent(self):
self.text_response(204)
def text_partial(self):
self.text_response(206)
def text_bad(self):
self.text_response(400)
def text_unauth(self):
self.text_response(401)
def text_forbidden(self):
self.text_response(403)
def text_notfound(self):
self.text_response(404)
def text_badmethod(self, valid_methods):
self.send_response(405)
self.send_header('Content-type', 'text/plain')
self.send_header('Accept', ','.join(valid_methods))
self.end_headers()
def text_notacceptable(self):
self.text_response(406)
def text_conflict(self):
self.text_response(409)
def text_nolength(self):
self.text_response(411)
def text_error(self):
self.send_error(500)
def text_notimplemented(self):
self.send_error(501)
def urlnode(self, nodeid):
try:
return nodes[nodeid]
except KeyError, e:
raise NotFoundError(nodeid)
def content(self):
try:
length = self.headers['Content-length']
length = int(length)
return self.rfile.read(length)
except Exception, e:
raise NoLengthException(str(e))
def do_GET(self):
def do_index():
self.text_ok()
self.wfile.write('Path: %s\n' % repr(self.path))
self.wfile.write('Params: %s\n' % repr(self.params))
self.wfile.write('%s\n' % DOCSPAGE)
def do_card(nodeid, uid):
node = self.urlnode(nodeid)
access = node.checkCard(uid)
if access:
self.text_ok()
self.wfile.write(access)
else:
self.text_notfound()
self.wfile.write(access)
def do_sync(nodeid, uid=None):
node = self.urlnode(nodeid)
card = node.getCard(uid)
if card:
self.text_partial()
self.wfile.write(card)
else:
self.text_nocontent()
def do_status(nodeid):
node = self.urlnode(nodeid)
self.text_ok()
self.wfile.write(node.status)
self.route([
('^/(\d+)/card(?:/?|/([A-Z0-9]+)/?)$', do_card),
('^/(\d+)/sync(?:/?|/([A-Z0-9]+)/?)$', do_sync),
('^/(\d+)/status/?$', do_status),
('^/$', do_index),
('', self.text_notfound),
])
def do_POST(self):
def do_index():
self.text_badmethod(['GET'])
self.wfile.write('Path: %s\n' % repr(self.path))
self.wfile.write('Params: %s\n' % repr(self.params))
self.wfile.write('%s\n' % DOCSPAGE)
def do_card(nodeid):
node = self.urlnode(nodeid)
uids = self.content()
m = re.match('^([A-Z0-9]+),([A-Z0-9]+)$', uids)
if not m:
self.text_bad()
return
maintainer_uid, user_uid = m.groups()
maintainer_access = node.checkCard(maintainer_uid)
if maintainer_access < 2:
self.text_forbidden()
return
user_access = node.checkCard(user_uid)
if user_access: # no change
self.text_ok()
self.wfile.write('OK (was %s)' % user_access)
else:
node.addCard(user_uid)
self.text_added()
self.wfile.write('OK')
self.route([
('^/(\d+)/card/?$', do_card),
('^/$', do_index),
('', self.text_notfound),
])
def do_PUT(self):
def do_index():
self.text_badmethod(['GET'])
self.wfile.write('Path: %s\n' % repr(self.path))
self.wfile.write('Params: %s\n' % repr(self.params))
self.wfile.write('%s\n' % DOCSPAGE)
def do_card(nodeid, uid):
node = self.urlnode(nodeid)
node.newperms[uid] = 1
self.text_ok()
self.wfile.write('OK')
def do_status(nodeid):
node = self.urlnode(nodeid)
status = self.content()
if status.strip() in ('1', '0'):
node.status = int(status)
self.text_ok()
self.wfile.write('OK')
else:
self.text_bad()
self.wfile.write('Invalid status\n')
def do_tooluse(nodeid):
node = self.urlnode(nodeid)
args = self.content()
m = re.match('^([0-9]+),([A-Z0-9]+)$', args)
if not m:
self.text_bad()
self.wfile.write('Invalid arguments\n')
return
tooluse, uid = m.groups()
access = node.checkCard(uid)
if not access:
self.text_forbidden()
return
if tooluse.strip() in ('1', '0'):
node.tooluse = int(tooluse)
self.text_ok()
self.wfile.write('OK')
else:
self.text_bad()
self.wfile.write('Invalid tooluse\n')
def do_case(nodeid):
node = self.urlnode(nodeid)
case = self.content()
if case.strip() in ('1', '0'):
node.case = int(case)
self.text_ok()
self.wfile.write('OK')
else:
self.text_bad()
self.wfile.write('Invalid case\n')
self.route([
('^/(\d+)/status/?$', do_status),
('^/(\d+)/tooluse/?$', do_tooluse),
('^/(\d+)/case/?$', do_case),
('^/$', do_index),
('', self.text_notfound),
])
reloadCardTable()
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
logging.info('Started on port %s', PORT)
httpd.serve_forever()