Example #1
0
def checkRecipient(recipient):
    """Do we serve mail for user or domain"""
    we_serve = False
    
    if recipient:
        """
            Lookup user or domain in:
                database vmail.mailbox
                database vmail.domain
                ldap.mailbox
                ldap.domain
        """
        addr = is_valid_amavisd_address(recipient)
        if addr in ['subdomain', 'domain', 'top_level_domain']:
            validate = 'domain'
        elif addr == 'email':
            validate = 'email'
        else:
            validate = None
        
        if validate:
            we_serve = auth.checkUser(validate, recipient)
        else:
            we_serve = True
    else:
        we_serve = True
    
    return we_serve
Example #2
0
def add_wblist(conn, account, wl_senders=[], bl_senders=[], flush_before_import=False):
    if not is_valid_amavisd_address(account):
        return (False, "INVALID_ACCOUNT")

    # Remove duplicate.
    wl_senders = set([str(s).lower() for s in wl_senders if is_valid_amavisd_address(s)])
    # Whitelist has higher priority, don't include whitelisted sender.
    bl_senders = set([str(s).lower() for s in bl_senders if is_valid_amavisd_address(s)])

    if flush_before_import and wl_senders:
        bl_senders = set([s for s in bl_senders if s not in wl_senders])

    addresses = list(wl_senders | bl_senders)

    # Get current user's id from `amavisd.users`
    qr = get_user_record(conn, account)

    if qr[0]:
        user_id = qr[1].id
    else:
        return qr

    # Delete old records
    if flush_before_import:
        conn.delete("wblist", vars={"rid": user_id}, where="rid=$rid")

    if not addresses:
        return (True,)

    # Insert all senders into `amavisd.mailaddr`
    create_mailaddr(conn, addresses)

    # Get `mailaddr.id` of senders
    sender_records = {}
    qr = conn.select("mailaddr", vars={"addresses": addresses}, what="id, email", where="email IN $addresses")
    for r in qr:
        sender_records[str(r.email)] = r.id
    del qr

    # Remove existing records of current submitted records then insert new.
    try:
        conn.delete("wblist", vars={"rid": user_id, "sid": sender_records.values()}, where="rid=$rid AND sid IN $sid")
    except Exception, e:
        return (False, str(e))
Example #3
0
def create_mailaddr(conn, addresses):
    for addr in addresses:
        addr_type = is_valid_amavisd_address(addr)
        if addr_type in MAILADDR_PRIORITIES:
            try:
                conn.insert("mailaddr", priority=MAILADDR_PRIORITIES[addr_type], email=addr)
            except:
                pass

    return True
Example #4
0
def getPriority(address):
    res = {}
    
    try:
        if not address:
            res['priority'] = MAILADDR_PRIORITIES['catchall']
            res['email'] = '@.'
        else:
            res['priority'] = MAILADDR_PRIORITIES[is_valid_amavisd_address(address)]
            res['email'] = address
    except KeyError,  e:
        print str(e)
        res = {}
Example #5
0
def create_user(conn, account, policy_id=0, return_record=True):
    # Create a new record in `amavisd.users`
    addr_type = is_valid_amavisd_address(account)
    try:
        # Use policy_id=0 to make sure it's not linked to any policy.
        conn.insert("users", policy_id=0, email=account, priority=MAILADDR_PRIORITIES[addr_type])

        if return_record:
            qr = conn.select("users", vars={"account": account}, what="*", where="email=$account", limit=1)
            return (True, qr[0])
        else:
            return (True,)
    except Exception, e:
        return (False, str(e))
Example #6
0
def main():
    blacklist = None
    whitelist = None
    recipient = None
    show      = False
    delete    = False

    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:],
        "hbdr:sw", ["help", "blacklist", "delete", "recipient=", "show", "whitelist"])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        print USAGE
        sys.exit(2)
    for option,  argument in opts:
        if option in ("-h",  "--help"):
            print USAGE
            sys.exit(0)
        elif option in ("-b", "--blacklist"):
            blacklist = True
        elif option in ("-d", "--delete"):
            delete = True
        elif option in ("-r", "--recipient"):
            if is_valid_amavisd_address(argument):
                recipient = argument
            else:
                print "%s: Invalid recipient" % argument
                sys.exit(1)
        elif option in ("-s", "--show"):
            show = True
        elif option in ("-w", "--whitelist"):
            whitelist = True
        else:
            assert False, "%s: unhandled option" % option

    if blacklist and whitelist:
        print "Error: whitelist and blacklist is mutual exclusive"
        print USAGE
        sys.exit(1)
    if show and delete:
        print "Error: show and delete is mutual exclusive"
        print USAGE
        sys.exit(1)
    if (blacklist or whitelist) and not show:
        if args:
            a = args[0].split()
            s = set(a)
            if blacklist:
                blacklist = [v for v in a if is_valid_amavisd_address(v)]
                bad = [x for x in s if x not in blacklist]
            else:
                whitelist = [v for v in a if is_valid_amavisd_address(v)]
                bad = [x for x in s if x not in whitelist]
            if bad:
                s = "Skipping: %s" % ' '.join(bad)
                logging.warning(s)
                print "Warning: %s" % s
        else:
            print "Error: whitelist or blacklist needs arguments"
            print USAGE
            sys.exit(1)

    logging.info('Excecuting request')

    try:
        if show:
            show_wb(blacklist, whitelist, recipient)
        elif delete:
            if blacklist or whitelist:
                delete_wb(blacklist, whitelist, recipient)
            else:
                print "blacklist and whitelist cannot be empty"
                sys.exit(1)
        else:
            if blacklist or whitelist:
                add_wb(blacklist, whitelist, recipient)
            else:
                print "blacklist and whitelist cannot be empty"
                sys.exit(1)
    except Exception, e:
        logging.error(str(e))
        print str(e)
        sys.exit(1)
Example #7
0
    
def str2Dict(string, delim = '=', group = '&'):
    try:
        params = dict([p.split(delim) for p in string.split(group)])
    except:
        params = {}

    return params

def json2List(string):
    try:
        data = json.loads(string)
    except ValueError, e:
        return str(e)

    list = [v for v in data if is_valid_amavisd_address(v)]

    return list

def cleanSessionsFiles(expire, dir):
    pattern = dir + '/*'
    now = time.time()
    
    logging.info("Timer: %s, dir: %s" % (expire, dir))
    files = glob.glob(pattern)
    for file in files:
        logging.debug('Consider %s for cleaning' % file)
        if now > os.stat(file).st_ctime + expire:
            logging.info("Remove %s" % file)
            os.remove(file)
        else: