# encoding: utf-8 # Author: Zhang Huangbin import sys import types import web from libs import iredutils from libs.policyd import core session = web.config.get('_session') mapCategoryToTable = { # listcategory: table_name, 'ip': 'blacklist', 'sender': 'blacklist_sender', 'dnsname': 'blacklist_dnsname', 'helo': 'blacklist_helo', } class Blacklist(core.PolicydWrap): def list(self, listcategory='ip', cur_page=1): self.listcategory = web.safestr(listcategory) self.cur_page = int(cur_page) if self.listcategory == 'ip': dbtable = 'blacklist' else: dbtable = 'blacklist_%s' % (self.listcategory) self.count = self.db.query("""SELECT COUNT(*) as total FROM %s""" % (dbtable) ) # Set correct cur_page. self.total = self.count[0].total or 0 if self.cur_page > self.total: self.cur_page = self.total if self.cur_page >= 1: self.entries = self.db.select(dbtable, offset=(int(cur_page) - 1) * session.pageSizeLimit, limit=session.pageSizeLimit, ) else: self.entries = self.db.select(dbtable,) return (self.total, self.entries.list()) def delete(self, listcategory='ip', records=[],): if not isinstance(records, types.ListType): return (False, 'INVALID_RECORD') # column name column = '_blacklist' if listcategory == 'helo': column = '_helo' try: self.db.delete( mapCategoryToTable[listcategory], where=column + ' in ' + web.sqlquote(records), ) return (True,) except Exception, e: return (False, str(e)) def add(self, form): # Get and convert records to set(). records = set(form.get('record', '').splitlines()) heloRecords = set(form.get('helo', []).splitlines()) # Get different whitelist categories. ipAddrs = [] senders = [] dnsnames = [] helos = [] for v in records: if core.isWblistIP(v): ipAddrs += [web.safestr(v)] elif core.isWblistSender(v): senders += [web.safestr(v)] elif core.isWblistDnsName(v): dnsnames += [web.safestr(v)] for v in heloRecords: if v.startswith('[') and v.endswith(']'): if iredutils.isStrictIP(v.lstrip('[').rstrip(']')): helos += [web.safestr(v)] elif iredutils.isDomain(v): helos += [web.safestr(v)] # INSERT records. for entry in ipAddrs: try: self.db.insert('blacklist', _blacklist=entry,) except Exception, e: # Duplicate entry. #if e.args[0] == ER.DUP_ENTRY: pass for entry in senders: try: self.db.insert('blacklist_sender', _blacklist=entry,) except Exception, e: # Duplicate entry. #if e.args[0] == ER.DUP_ENTRY: pass for entry in dnsnames: try: self.db.insert('blacklist_dnsname', _blacklist=entry,) except Exception, e: # Duplicate entry. #if e.args[0] == ER.DUP_ENTRY: pass for entry in helos: try: self.db.insert('blacklist_helo', _helo=entry,) except Exception, e: # Duplicate entry. #if e.args[0] == ER.DUP_ENTRY: pass return (True,)