Skip to content

Commit

Permalink
BS server aut and restore
Browse files Browse the repository at this point in the history
  • Loading branch information
Fdrph committed Oct 10, 2018
1 parent 667d453 commit a04d2be
Show file tree
Hide file tree
Showing 3 changed files with 152 additions and 51 deletions.
150 changes: 116 additions & 34 deletions bs/BS.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,103 @@
cmd_line_args = vars(parser.parse_args())


# hostname = [(s.connect(('10.255.255.255', 1)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
hostname = '127.0.0.1'
hostname = [(s.connect(('10.255.255.255', 1)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
# hostname = '127.0.0.1'
sel = selectors.DefaultSelector()

def aut(args, sock, cred):
response = b'AUR '
success = False
username = args[0]
password = args[1]
filename = 'user_'+username+'.txt'

if os.path.isfile(filename):
# user exists
with open(filename, 'r+') as f:
if f.read() == password:
# user exists and pass is correct
response += b' OK\n'
print("User: " + username)
success = True
else:
# user exists and pass is wrong
response += b' NOK\n'
# print(users)
# print(response)

sock.sendall(response)
return success

def upl(args, sock, cred):
print(args)


def rsb(args, sock, cred):
print(args)
path = os.getcwd()+'/user_'+cred[0]+'/'+args[0]
try:
files = os.listdir(path)
except OSError:
sock.sendall(b'RBR EOF\n')
return
resp = 'RBR '+str(len(files))+' '
resp = resp.encode()
for file in files:
filepath = path+'/'+file
size = str(os.path.getsize(filepath))
date_time = time.strftime('%d.%m.%Y %H:%M:%S', time.gmtime(os.path.getmtime(filepath)) )
with open(filepath, 'rb') as f: data = f.read()
file_b = ' '.join([file,date_time,size])+' '
file_b = file_b.encode() + data
resp += file_b
# resp += b' '.join([file.encode(),date_time.encode(),size.encode(),data]) + b' '

resp += b'\n'
sock.sendall(resp)

# get tcp message until \n is found
def get_msg(sock):
msg = b''
while True:
try:
slic = sock.recv(1024)
if not slic:
msg = b''
break
msg += slic
if msg.find(b'\n') != -1: break
except socket.error as e:
print(e)
exit()
return msg.decode().rstrip('\n')

# TCP session with user
def tcp_session(sock, udp_sock):
data, addr = sock.recvfrom(1024)
if data:
print('received ', repr(data))
sock.sendall(b'AUR OK\n')
else:
print('closing ', sock.getsockname())
sel.unregister(sock)
sock.close()
def tcp_session(sock):
sel.unregister(sock)
sock.setblocking(True)

cred = ()

actions = {
'AUT':aut,
'UPL':upl,
'RSB':rsb,
}
while True:
message = get_msg(sock)
if not message: break
args = message.split()
callable = actions.get(args[0])
if callable is None:
sock.sendall(b'ERR\n')
break
if callable(args[1:], sock, cred):
cred = (args[1], args[2])


print('closing ', sock.getsockname())
sock.close()

def tcp_accept(sock):
connection, client_address = sock.accept()
Expand Down Expand Up @@ -145,25 +228,27 @@ def register_with_cs():
else:
print("Registered sucessfully with central server!")


# UDP
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# addr = (local ip, cmd_line_args['bsport'])
addr = ('localhost', cmd_line_args['bsport'])
udp_sock.bind( addr )
udp_sock.setblocking(False)
sel.register(udp_sock, selectors.EVENT_READ, udp_cs)

# TCP
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# server_address = (hostname, cmd_line_args["csport"])
server_address = ('localhost', cmd_line_args['bsport'])
tcp_sock.bind(server_address)
print('listening for users...')
tcp_sock.listen(1)
tcp_sock.setblocking(False)
sel.register(tcp_sock, selectors.EVENT_READ, tcp_accept)

try:
# UDP
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
addr = (hostname, cmd_line_args['bsport'])
# addr = ('localhost', cmd_line_args['bsport'])
udp_sock.bind( addr )
udp_sock.setblocking(False)
sel.register(udp_sock, selectors.EVENT_READ, udp_cs)

# TCP
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (hostname, cmd_line_args["bsport"])
# server_address = ('localhost', cmd_line_args['bsport'])
tcp_sock.bind(server_address)
print('listening for users...')
tcp_sock.listen(1)
tcp_sock.setblocking(False)
sel.register(tcp_sock, selectors.EVENT_READ, tcp_accept)
except OSError as e:
print('Error starting the server: '+ str(e))
exit()

# Receives ctrl^C and sends unregister
# request to CS, exits afterwards
Expand Down Expand Up @@ -192,7 +277,4 @@ def sig_handler(sig, frame):
events = sel.select()
for key, mask in events:
callback = key.data
if callback == tcp_session:
callback(key.fileobj, udp_sock)
else:
callback(key.fileobj)
callback(key.fileobj)
22 changes: 8 additions & 14 deletions cs/CS.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
parser.add_argument('-p', '--csport', type=int, default=58008, help='Central Server port')
cmd_line_args = vars(parser.parse_args())


hostname = [(s.connect(('10.255.255.255', 1)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
sel = selectors.DefaultSelector()
registered_BS = [] # registered backup servers online
logged_in_users = set()
Expand Down Expand Up @@ -280,7 +280,7 @@ def get_msg(sock):
return msg.decode().rstrip('\n')

# TCP session with user
def tcp_session(sock, udp_sock):
def tcp_session(sock):
sel.unregister(sock)
sock.setblocking(True)

Expand All @@ -301,7 +301,7 @@ def tcp_session(sock, udp_sock):
args = message.split()
callable = actions.get(args[0])
if callable is None:
udp_sock.sendall(b'ERR\n')
sock.sendall(b'ERR\n')
break
if callable(args[1:], sock, cred):
cred = (args[1], args[2])
Expand Down Expand Up @@ -347,16 +347,16 @@ def udp_rgr(udp_sock):

print("Server starting up on: %s port: %s" % ('localhost', cmd_line_args['csport']))
try:
ip = [(s.connect(('10.255.255.255', 1)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
# UDP socket for bs registration
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.bind( ('localhost', cmd_line_args['csport']) )
udp_sock.bind( (hostname, cmd_line_args['csport']) )
# udp_sock.bind( ('localhost', cmd_line_args['csport']) )
udp_sock.setblocking(False)
sel.register(udp_sock, selectors.EVENT_READ, udp_rgr)
# TCP for user connections
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# tcp_sock.bind((ip, cmd_line_args['csport']))
tcp_sock.bind(('localhost', cmd_line_args['csport']))
tcp_sock.bind((hostname, cmd_line_args['csport']))
# tcp_sock.bind(('localhost', cmd_line_args['csport']))
tcp_sock.listen(1)
tcp_sock.setblocking(False)
sel.register(tcp_sock, selectors.EVENT_READ, tcp_accept)
Expand All @@ -376,10 +376,4 @@ def sig_handler(sig, frame):
events = sel.select()
for key, mask in events:
callback = key.data
if callback == tcp_session:
callback(key.fileobj, udp_sock)
else:
callback(key.fileobj)



callback(key.fileobj)
31 changes: 28 additions & 3 deletions user.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,40 @@ def backup(args, credentials, server_info):

def restore(args, credentials, server_info):

# we ask the cs for bs ip and port
sock = create_tcp_socket(server_info)

if not authenticate(credentials['user'], credentials['password'], sock):
sock.close()
return

response = send_msg_sock('RST '+args[0], sock).split()
sock.close()
print(response)
if response[1] == 'EOF' or response[1] == 'ERR':
print("Cant restore this directory")
return
# now we talk to bs
bsname = response[1]
bsport = response[2]
bs_sock = create_tcp_socket({"csname":bsname, "csport":int(bsport)})
if not authenticate(credentials['user'], credentials['password'], bs_sock):
print("Couldn't authenticate with BS!")
bs_sock.close()
return

tosend = 'RSB '+args[0]+'\n'
bs_sock.sendall(tosend.encode())
resp = b''
while True:
slic = bs_sock.recv(512)
if not slic:
break
resp += slic
# response = send_msg_sock('RSB '+args[0], bs_sock).split()
bs_sock.close()

print(resp)





def dirlist(args, credentials, server_info):
Expand Down

0 comments on commit a04d2be

Please sign in to comment.