summaryrefslogtreecommitdiffstats
path: root/at.py
blob: d7e2b38e823f6f915918a2794630bfe8491e8706 (plain)
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import sqlite3
import threading
import traceback
import json
import requests
import os
import logging

from flask import Flask, render_template, abort, g, \
    redirect, session, request, flash, url_for, make_response
from datetime import datetime
from time import sleep, time, mktime
from collections import namedtuple
from urllib import urlencode


app = Flask('at')
app.config.from_pyfile('at.cfg')
app.jinja_env.add_extension('jinja2.ext.i18n')
app.jinja_env.install_null_translations()
app.updater = None


from functools import wraps


def v4addr():
    r_addr = request.remote_addr
    if r_addr.startswith('::ffff:'):
        r_addr = r_addr[7:]
    return r_addr


def restrict_ip(prefix='', exclude=[]):
    def decorator(f):
        @wraps(f)
        def func(*a, **kw):
            r_addr = v4addr()
            if not r_addr.startswith(prefix) or r_addr in exclude:
                abort(403)
            return f(*a, **kw)
        return func
    return decorator


def req_to_ctx():
    return dict(request.form.iteritems())


@app.template_filter('strfts')
def strfts(ts, format='%d/%m/%Y %H:%M'):
    return datetime.fromtimestamp(ts).strftime(format)


@app.template_filter('wikiurl')
def wikiurl(user):
    return app.config['WIKI_URL'] % {'login': user}


@app.before_request
def make_connection():
    conn = sqlite3.connect(app.config['DB'])
    conn.row_factory = sqlite3.Row
    conn.isolation_level = None  # for autocommit mode
    g.db = conn


@app.teardown_request
def close_connection(exception):
    g.db.close()


DeviceInfo = namedtuple('DeviceInfo', ['hwaddr', 'name', 'owner', 'ignored'])


def get_device_info(conn, hwaddr):
    return list(get_device_infos(conn, (hwaddr,)))[0]


def get_device_infos(conn, hwaddrs):
    in_clause = '({})'.format(', '.join(['?'] * len(hwaddrs)))
    stmt = '''select hwaddr, name, ignored, owner from
        devices where devices.hwaddr in ''' + in_clause
    for row in conn.execute(stmt, hwaddrs):
        owner = row['owner'] or ''
        ignored = row['ignored']
        yield DeviceInfo(row['hwaddr'], row['name'], owner, ignored)


class Updater(threading.Thread):
    def __init__(self,  timeout, lease_offset=0, *a, **kw):
        self.timeout = timeout
        self.lock = threading.Lock()
        self.lease_offset = lease_offset
        self.active = {}
        threading.Thread.__init__(self, *a, **kw)
        self.daemon = True

    def purge_stale(self):
        now = time()
        for addr, (atime, ip, name) in self.active.items():
            if now - atime > self.timeout:
                del self.active[addr]

    def get_active_devices(self):
        self.lock.acquire()
        self.purge_stale()
        r = dict(self.active)
        self.lock.release()
        return r

    def get_device(self, ip):
        active_devices = self.get_active_devices().iteritems()
        for hwaddr, (atime, dip, name) in active_devices:
            if ip == dip:
                return hwaddr, name
        return None, None

    def update(self, hwaddr, atime=None, ip=None, name=None):
        if atime:
            atime -= self.lease_offset
        else:
            atime = time()
        self.lock.acquire()
        self.active[hwaddr] = (atime, ip, name)
        self.lock.release()
        app.logger.info('updated %s with atime %s and ip %s',
                        hwaddr, strfts(atime), ip)


class CapUpdater(Updater):
    def __init__(self, cap_file, *a, **kw):
        self.cap_file = cap_file
        Updater.__init__(self, *a, **kw)

    def run(self):
        while True:
            try:
                with open(self.cap_file, 'r', buffering=0) as f:
                    app.logger.info('Updater ready on cap file %s',
                                    self.cap_file)
                    lines = [l.strip() for l in f.read().split('\n')]
                    for hwaddr in lines:
                        if hwaddr:
                            self.update(hwaddr)
                app.logger.warning('Cap file %s closed, reopening',
                                   self.cap_file)
            except Exception as e:
                app.logger.error('Updater got an exception:\n' +
                                 traceback.format_exc(e))
                sleep(10.0)


class MtimeUpdater(Updater):
    def __init__(self, lease_file, *a, **kw):
        self.lease_file = lease_file
        self.last_modified = 0
        Updater.__init__(self, *a, **kw)

    def file_changed(self, f):
        pass

    def run(self):
        while True:
            try:
                mtime = os.stat(self.lease_file).st_mtime
                if mtime > self.last_modified:
                    app.logger.info('Lease file changed, updating')
                    with open(self.lease_file, 'r') as f:
                        self.file_changed(f)
                self.last_modified = mtime
                sleep(3.0)
            except Exception as e:
                app.logger.error('Updater got an exception:\n' +
                                 traceback.format_exc(e))
                sleep(10.0)


class DnsmasqUpdater(MtimeUpdater):
    def file_changed(self, f):
        for line in f:
            ts, hwaddr, ip, name, client_id = line.split(' ')
            self.update(hwaddr, int(ts), ip, name)


class DhcpdUpdater(MtimeUpdater):
    def file_changed(self, f):
        lease = False
        # for use by next-line logic
        ip = None
        for line in f:
            line = line.split('#')[0]
            cmd = line.strip().split()
            if not cmd:
                continue
            if lease:
                field = cmd[0]
                if(field == 'starts'):
                    dt = datetime.strptime(' '.join(cmd[2:]),
                                           '%Y/%m/%d %H:%M:%S;')
                    atime = mktime(dt.utctimetuple())
                if(field == 'client-hostname'):
                    name = cmd[1][1:-2]
                if(field == 'hardware'):
                    hwaddr = cmd[2][:-1]
                if(field.startswith('}')):
                    lease = False
                    if hwaddr:
                        self.update(hwaddr, atime, ip, name)
            elif cmd[0] == 'lease':
                ip = cmd[1]
                name, hwaddr, atime = [None] * 3
                lease = True


@app.route('/')
def main_view():
    return render_template('main.html', **now_at())


@app.route('/api')
def list_all():
    result = now_at()

    def prettify_user((user, atime)):
        return {
            'login': user,
            'timestamp': atime,
            'pretty_time': strfts(atime),
        }
    result['users'] = map(prettify_user, result['users'])
    result['unknown'] = len(result['unknown'])
    res = make_response(json.dumps(result), 200)
    res.headers['Access-Control-Allow-Origin'] = '*'
    return res


def now_at():
    devices = app.updater.get_active_devices()
    device_infos = list(get_device_infos(g.db, devices.keys()))
    device_infos.sort(key=lambda di: devices.__getitem__)
    unknown = set(devices.keys()) - set(d.hwaddr for d in device_infos)

    users = {}
    for info in device_infos:
        if info.owner not in users:
            users[info.owner] = devices[info.hwaddr][0]
    users_sorted = sorted(users.items(), key=lambda (u, a): a, reverse=True)

    return dict(users=users_sorted, unknown=unknown)


restrict_to_hs = restrict_ip(prefix=app.config['CLAIMABLE_PREFIX'],
                             exclude=app.config['CLAIMABLE_EXCLUDE'])


@app.route('/login', methods=['GET'])
def login_form():
    return render_template('login.html', **req_to_ctx())


@app.route('/login', methods=['POST'])
def login():
    login = request.form.get('login', '').lower()
    pwd = request.form.get('password', '')
    goto = request.values.get('goto') or '/'
    data = dict(login=login, password=pwd)
    if requests.post('https://auth.hackerspace.pl', verify=False,
                     data=data).status_code == 200:
        session['login'] = login
        return redirect(goto)
    else:
        flash('Username or password invalid', category='error')
        return login_form()


@app.route('/logout')
def logout():
    session.clear()
    return redirect('/')


def login_required(f):
    @wraps(f)
    def func(*a, **kw):
        if 'login' not in session:
            flash('You must log in to continue', category='error')
            return redirect('/login?' +
                            urlencode({'goto': request.path}))
        return f(*a, **kw)
    return func


@app.route('/claim', methods=['GET'])
@restrict_to_hs
@login_required
def claim_form():
    hwaddr, name = app.updater.get_device(v4addr())
    return render_template('claim.html', hwaddr=hwaddr, name=name)


@app.route('/claim', methods=['POST'])
@restrict_to_hs
@login_required
def claim():
    hwaddr, lease_name = app.updater.get_device(v4addr())
    ctx = None
    if not hwaddr:
        ctx = dict(error='Invalid device.')
    else:
        login = session['login']
        try:
            g.db.execute('''
insert into devices (hwaddr, name, owner, ignored) values (?, ?, ?, ?)''',
                         [hwaddr, request.form['name'], login, False])
            ctx = {}
        except sqlite3.Error:
            error = 'Could not add device! Perhaps someone claimed it?'
            ctx = dict(error=error)
    return render_template('post_claim.html', **ctx)


def get_user_devices(conn, user):
    devs = conn.execute('select hwaddr, name, ignored from devices where\
 owner = ?', [user])
    device_info = []
    for row in devs:
        di = DeviceInfo(row['hwaddr'], row['name'], user, row['ignored'])
        device_info.append(di)
    return device_info


@app.route('/account', methods=['GET'])
@login_required
def account():
    devices = get_user_devices(g.db, session['login'])
    return render_template('account.html', devices=devices)


def set_ignored(conn, hwaddr, user, value):
    return conn.execute('''
update devices set ignored = ? where hwaddr = ? and owner = ?''',
                        [value, hwaddr, user])


def delete_device(conn, hwaddr, user):
    return conn.execute('''
delete from devices where hwaddr = ? and owner = ?''',
                        [hwaddr, user])


@app.route('/devices/<id>/<action>/')
@login_required
def device(id, action):
    user = session['login']
    if action == 'hide':
        set_ignored(g.db, id, user, True)
    if action == 'show':
        set_ignored(g.db, id, user, False)
    if action == 'delete':
        delete_device(g.db, id, user)
    return redirect(url_for('account'))


@app.before_first_request
def setup():
    updater = DhcpdUpdater(app.config['LEASE_FILE'], app.config['TIMEOUT'],
                           app.config['LEASE_OFFSET'])
    updater.start()
    app.updater = updater


port = 8080
if __name__ == '__main__':
    app.logger.setLevel(logging.DEBUG)
    app.run('0.0.0.0', 8080, debug=True)