utils.py 1.83 KB
# -*- coding: utf-8 -*-
import hashlib

from msg.stream import accept_msg, write_msg
from msg.message import Message, OkMessage, KoMessage, NumMessage

class UserInvalid(Exception):
    pass

def validate_user(conns, pass_file):
    pass_dict = parse_passwd(pass_file)
    login = accept_msg(conns, Message).get_contents()
    passwd = accept_msg(conns, Message).get_contents()
    if pass_dict.has_key(login) and pass_dict[login] == passwd:
        write_msg(conns, OkMessage())
        return login
    else:
        write_msg(conns, KoMessage())
        raise UserInvalid(login)

def parse_passwd(pass_file):
    result = {}
    with open(pass_file) as f:
        for line in f:
            login, passwd = line.split("=")
            login = login.strip()
            passwd = passwd.strip()
            result[login] = passwd
    return result

def _check_sum(*args):
    m = hashlib.sha256()
    for arg in args:
        m.update(arg)
    return m

def check_sum(*args):
    return _check_sum(*args).digest()

def check_hexsum(*args):
    return _check_sum(*args).hexdigest()

def send_contents(stream, contents):
    write_msg(stream, NumMessage(len(contents)))
    for ext, data in contents.iteritems():
        write_msg(stream, Message(ext))
        write_msg(stream, Message(data))
        write_msg(stream, Message(check_sum(ext, data)))
        accept_msg(stream, OkMessage)

def receive_contents(stream):
    contents = {}
    n = accept_msg(stream, NumMessage).get_number()
    for _ in range(n):
        ext = accept_msg(stream, Message).get_contents()
        data = accept_msg(stream, Message).get_contents()
        csum = accept_msg(stream, Message).get_contents()
        if csum == check_sum(ext, data):
            write_msg(stream, OkMessage())
        else:
            write_msg(stream, KoMessage())
        contents[ext] = data
    return contents