utils.py
1.83 KB
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
# -*- 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