db.py 19.1 KB
Newer Older
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
"""
    Copyright (c) 2015 Ad Schellevis
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

"""
import os
import base64
import time
import sqlite3


class DB(object):
34
    database_filename = '/var/captiveportal/captiveportal.sqlite'
35 36

    def __init__(self):
37
        """ construct new database connection, open and make sure the sqlite file exists
38 39
        :return:
        """
40
        self._connection = None
41
        self.open()
42 43
        self.create()

44 45 46
    def __del__(self):
        """ destruct, close database handle
        """
47 48 49 50 51
        self.close()

    def close(self):
        """ close database
        """
52 53
        self._connection.close()

54 55 56 57 58
    def open(self):
        """ open database
        """
        self._connection = sqlite3.connect(self.database_filename)

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    def create(self, force_recreate=False):
        """ create/initialize new database
        :param force_recreate: if database already exists, remove old one first
        :return: None
        """
        if force_recreate:
            if os.path.isfile(self.database_filename):
                os.remove(self.database_filename)
            self._connection = sqlite3.connect(self.database_filename)

        cur = self._connection.cursor()
        cur.execute('SELECT count(*) FROM sqlite_master')
        if cur.fetchall()[0][0] == 0:
            # empty database, initialize database
            init_script_filename = '%s/../sql/init.sql' % os.path.dirname(os.path.abspath(__file__))
74
            cur.executescript(open(init_script_filename, 'rb').read())
75 76
        cur.close()

77
    def sessions_per_address(self, zoneid, ip_address=None, mac_address=None):
78
        """ fetch session(s) per (mac) address
79
        :param zoneid: cp zone number
80
        :param ip_address: ip address
81 82 83
        :return: active status (boolean)
        """
        cur = self._connection.cursor()
84
        request = {'zoneid': zoneid, 'ip_address': ip_address, 'mac_address': mac_address}
85 86 87 88 89 90 91 92 93 94 95 96 97
        cur.execute("""select   cc.sessionid         sessionId
                        ,       cc.authenticated_via authenticated_via
                       from     cp_clients cc
                       where    cc.deleted = 0
                       and      cc.zoneid = :zoneid
                       and   (
                                cc.ip_address = :ip_address
                                or
                                cc.mac_address = :mac_address
                             )""", request)

        result = []
        for row in cur.fetchall():
98
            result.append({'sessionId': row[0], 'authenticated_via': row[1]})
99
        return result
100

101
    def add_client(self, zoneid, authenticated_via, username, ip_address, mac_address):
102 103
        """ add a new client to the captive portal administration
        :param zoneid: cp zone number
104
        :param authenticated_via: name/id of the authenticator or ---ip--- / ---mac--- for authentication by address
105 106 107 108 109 110 111
        :param username: username, maybe empty
        :param ip_address: ip address (to unlock)
        :param mac_address: physical address of this ip
        :return: dictionary with session info
        """
        response = dict()
        response['zoneid'] = zoneid
112
        response['authenticated_via'] = authenticated_via
113 114 115 116 117
        response['userName'] = username
        response['ipAddress'] = ip_address
        response['macAddress'] = mac_address
        response['startTime'] = time.time()  # record creation = sign-in time
        response['sessionId'] = base64.b64encode(os.urandom(16))  # generate a new random session id
118 119

        cur = self._connection.cursor()
120
        # set cp_client as deleted in case there's already a user logged-in at this ip address.
121 122 123 124 125 126
        if ip_address is not None and ip_address != '':
            cur.execute("""UPDATE cp_clients
                           SET    deleted = 1
                           WHERE  zoneid = :zoneid
                           AND    ip_address = :ipAddress
                        """, response)
127

128
        # add new session
129 130
        cur.execute("""INSERT INTO cp_clients(zoneid, authenticated_via, sessionid, username,  ip_address, mac_address, created)
                       VALUES (:zoneid, :authenticated_via, :sessionId, :userName, :ipAddress, :macAddress, :startTime)
131
                    """, response)
132 133 134 135

        self._connection.commit()
        return response

136 137 138 139
    def update_client_ip(self, zoneid, sessionid, ip_address):
        """ change client ip address
        """
        cur = self._connection.cursor()
140 141 142
        cur.execute("""update cp_clients
                       set    ip_address = :ip_address
                       where  deleted = 0
143
                       and    zoneid = :zoneid
144
                       and    sessionid = :sessionid
145 146 147
                    """, {'zoneid': zoneid, 'sessionid': sessionid, 'ip_address': ip_address})
        self._connection.commit()

148 149 150 151 152 153 154
    def del_client(self, zoneid, sessionid):
        """ mark (administrative) client for removal
        :param zoneid: zone id
        :param sessionid: session id
        :return: client info before removal or None if client not found
        """
        cur = self._connection.cursor()
155 156 157 158 159
        cur.execute(""" select  *
                        from    cp_clients
                        where   sessionid = :sessionid
                        and     zoneid = :zoneid
                        and     deleted = 0
160 161 162 163 164 165 166
                    """, {'zoneid': zoneid, 'sessionid': sessionid})
        data = cur.fetchall()
        if len(data) > 0:
            session_info = dict()
            for fields in cur.description:
                session_info[fields[0]] = data[0][len(session_info)]
            # remove client
167
            cur.execute("update cp_clients set deleted = 1 where sessionid = :sessionid and zoneid = :zoneid",
168 169 170 171 172 173 174
                        {'zoneid': zoneid, 'sessionid': sessionid})
            self._connection.commit()

            return session_info
        else:
            return None

175
    def list_clients(self, zoneid):
176
        """ return list of (administrative) connected clients and usage statistics
177 178 179 180 181 182
        :param zoneid: zone id
        :return: list of clients
        """
        result = list()
        fieldnames = list()
        cur = self._connection.cursor()
183
        # rename fields for API
184
        cur.execute(""" select  cc.zoneid
185
                        ,       cc.sessionid   sessionId
186
                        ,       cc.authenticated_via authenticated_via
187 188 189 190
                        ,       cc.username    userName
                        ,       cc.created     startTime
                        ,       cc.ip_address  ipAddress
                        ,       cc.mac_address macAddress
191 192 193 194 195 196 197 198 199 200 201 202 203 204
                        ,       case when si.packets_in is null then 0 else si.packets_in end packets_in
                        ,       case when si.packets_out is null then 0 else si.packets_out end packets_out
                        ,       case when si.bytes_in is null then 0 else si.bytes_in end bytes_in
                        ,       case when si.bytes_out is null then 0 else si.bytes_out end bytes_out
                        ,       case when si.last_accessed is null or si.last_accessed = 0
                                        then cc.created
                                        else si.last_accessed
                                end last_accessed
                        ,       sr.session_timeout acc_session_timeout
                        from    cp_clients cc
                        left join session_info si on si.zoneid = cc.zoneid and si.sessionid = cc.sessionid
                        left join session_restrictions sr on sr.zoneid = cc.zoneid and sr.sessionid = cc.sessionid
                        where   cc.zoneid = :zoneid
                        and     cc.deleted = 0
205 206
                        order by case when cc.username is not null then cc.username else cc.ip_address end
                        ,        cc.created desc
207
                        """, {'zoneid': zoneid})
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        while True:
            # fetch field names
            if len(fieldnames) == 0:
                for fields in cur.description:
                    fieldnames.append(fields[0])

            row = cur.fetchone()
            if row is None:
                break
            else:
                record = dict()
                for idx in range(len(row)):
                    record[fieldnames[idx]] = row[idx]
                result.append(record)
        return result
224

225 226 227 228 229 230 231 232
    def find_concurrent_user_sessions(self, zoneid):
        """ query zone database for concurrent user sessions
        :param zoneid: zone id
        :return: dictionary containing duplicate sessions
        """
        result = dict()
        cur = self._connection.cursor()
        # rename fields for API
233
        cur.execute(""" select   cc.sessionid   sessionId
234
                        ,        cc.username    userName
235 236 237 238
                        from     cp_clients cc
                        where   cc.zoneid = :zoneid
                        and     cc.deleted = 0
                        and     cc.username is not null
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                        and     cc.username <> ""
                        order by case when cc.username is not null then cc.username else cc.ip_address end
                        ,        cc.created desc
                        """, {'zoneid': zoneid})

        prev_user = None
        while True:
            row = cur.fetchone()
            if row is None:
                break
            elif prev_user is not None and prev_user == row[1]:
                result[row[0]] = row[1]
            prev_user = row[1]
        return result

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
    def update_accounting_info(self, details):
        """ update internal accounting database with given ipfw info (not per zone)
        :param details: ipfw accounting details
        """
        if type(details) == dict:
            # query registered data
            sql = """ select    cc.ip_address, cc.zoneid, cc.sessionid
                      ,         si.rowid si_rowid, si.prev_packets_in, si.prev_bytes_in
                      ,         si.prev_packets_out, si.prev_bytes_out, si.last_accessed
                      from      cp_clients cc
                      left join session_info si on si.zoneid = cc.zoneid and si.sessionid = cc.sessionid
                      order by  cc.ip_address, cc.deleted
                  """
            cur = self._connection.cursor()
            cur2 = self._connection.cursor()
            cur.execute(sql)
            prev_record = {'ip_address': None}
            for row in cur.fetchall():
                # map fieldnumbers to names
                record = {}
                for fieldId in range(len(row)):
                    record[cur.description[fieldId][0]] = row[fieldId]
                # search unique hosts from dataset, both disabled and enabled.
                if prev_record['ip_address'] != record['ip_address'] and record['ip_address'] in details:
                    if record['si_rowid'] is None:
                        # new session, add info object
                        sql_new = """ insert into session_info(zoneid, sessionid, prev_packets_in, prev_bytes_in,
                                                               prev_packets_out, prev_bytes_out,
                                                               packets_in, packets_out, bytes_in, bytes_out,
                                                               last_accessed)
                                      values (:zoneid, :sessionid, :packets_in, :bytes_in, :packets_out, :bytes_out,
                                              :packets_in, :packets_out, :bytes_in, :bytes_out, :last_accessed)
                        """
                        record['packets_in'] = details[record['ip_address']]['in_pkts']
                        record['bytes_in'] = details[record['ip_address']]['in_bytes']
                        record['packets_out'] = details[record['ip_address']]['out_pkts']
                        record['bytes_out'] = details[record['ip_address']]['out_bytes']
                        record['last_accessed'] = details[record['ip_address']]['last_accessed']
                        cur2.execute(sql_new, record)
                    else:
                        # update session
                        sql_update = """ update session_info
                                         set    last_accessed = :last_accessed
                                         ,      prev_packets_in = :prev_packets_in
                                         ,      prev_packets_out = :prev_packets_out
                                         ,      prev_bytes_in = :prev_bytes_in
                                         ,      prev_bytes_out = :prev_bytes_out
                                         ,      packets_in = packets_in + :packets_in
                                         ,      packets_out = packets_out + :packets_out
                                         ,      bytes_in = bytes_in + :bytes_in
                                         ,      bytes_out = bytes_out + :bytes_out
                                         where  rowid = :si_rowid
                        """
                        # add usage to session
                        record['last_accessed'] = details[record['ip_address']]['last_accessed']
                        if record['prev_packets_in'] <= details[record['ip_address']]['in_pkts'] and \
310
                           record['prev_packets_out'] <= details[record['ip_address']]['out_pkts']:
311
                            # ipfw data is still valid, add difference to use
312 313 314 315 316 317 318
                            record['packets_in'] = (
                                details[record['ip_address']]['in_pkts'] - record['prev_packets_in'])
                            record['packets_out'] = (
                                details[record['ip_address']]['out_pkts'] - record['prev_packets_out'])
                            record['bytes_in'] = (details[record['ip_address']]['in_bytes'] - record['prev_bytes_in'])
                            record['bytes_out'] = (
                                details[record['ip_address']]['out_bytes'] - record['prev_bytes_out'])
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                        else:
                            # the data has been reset (reloading rules), add current packet count
                            record['packets_in'] = details[record['ip_address']]['in_pkts']
                            record['packets_out'] = details[record['ip_address']]['out_pkts']
                            record['bytes_in'] = details[record['ip_address']]['in_bytes']
                            record['bytes_out'] = details[record['ip_address']]['out_bytes']

                        record['prev_packets_in'] = details[record['ip_address']]['in_pkts']
                        record['prev_packets_out'] = details[record['ip_address']]['out_pkts']
                        record['prev_bytes_in'] = details[record['ip_address']]['in_bytes']
                        record['prev_bytes_out'] = details[record['ip_address']]['out_bytes']
                        cur2.execute(sql_update, record)

                prev_record = record
            self._connection.commit()
334 335 336 337 338 339 340 341 342

    def update_session_restrictions(self, zoneid, sessionid, session_timeout):
        """ upsert session restrictions
        :param zoneid: zone id
        :param sessionid: session id
        :param session_timeout: timeout in seconds
        :return: string "add"/"update" to signal the performed action to the client
        """
        cur = self._connection.cursor()
343
        qry_params = {'zoneid': zoneid, 'sessionid': sessionid, 'session_timeout': session_timeout}
344 345 346 347 348 349 350 351 352 353 354 355 356 357
        sql_update = """update session_restrictions
                        set session_timeout = :session_timeout
                        where zoneid = :zoneid and sessionid = :sessionid"""

        cur.execute(sql_update, qry_params)
        if cur.rowcount == 0:
            sql_insert = """insert into session_restrictions(zoneid, sessionid, session_timeout)
                            values (:zoneid, :sessionid, :session_timeout)"""
            cur.execute(sql_insert, qry_params)
            self._connection.commit()
            return 'add'
        else:
            self._connection.commit()
            return 'update'
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

    def cleanup_sessions(self):
        """ cleanup removed sessions, but wait for accounting to finish when busy
        """
        cur = self._connection.cursor()
        cur.execute(""" delete
                        from cp_clients
                        where cp_clients.deleted = 1
                        and not exists (
                            select  1
                            from    accounting_state
                            where   accounting_state.zoneid = cp_clients.zoneid
                            and     accounting_state.sessionid = cp_clients.sessionid
                            and     accounting_state.state <> 'STOPPED'
                        )
                        """)
        cur.execute(""" delete
                        from    accounting_state
                        where   not exists (
                            select  1
                            from    cp_clients
                            where   cp_clients.zoneid = accounting_state.zoneid
                            and     cp_clients.sessionid = accounting_state.sessionid
                        )
                    """)
        cur.execute(""" delete
                        from    session_info
                        where   not exists (
                            select  1
                            from    cp_clients
                            where   session_info.zoneid = cp_clients.zoneid
                            and     session_info.sessionid = cp_clients.sessionid
                        )
                    """)

        cur.execute(""" delete
                        from    session_restrictions
                        where   not exists (
                            select  1
                            from    cp_clients
                            where   session_restrictions.zoneid = cp_clients.zoneid
                            and     session_restrictions.sessionid = cp_clients.sessionid
                        )
                    """)

        self._connection.commit()