-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.py
499 lines (347 loc) · 14.5 KB
/
client.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import socket
import sys
import os
import time
import helperFunctions as helper
import ledgerFunctions as ledger
import encryption
BYTES_TO_SEND = 1024
REQUEST_MAX_LENGTH = 128
#
# Creates a socket that has a connection with the specied host and port
#
def run_client(host, port=12345):
#creates a new socket
s = socket.socket()
#connect the socket to the given host
s.connect((host, port))
#return the socket once created
return s
#
# Lock all servers
#
def lock_servers():
# logging
print("Locking All Servers")
# go through the ips and lock them
for ip in ledger.get_ips():
# get the key of the server we want to send to
serverPubkey = ledger.get_pubkey(ip)
# connect to the host you want to send file to
s = run_client(ip)
# create a push request for the server and encode it to bytes
cmd = "lock " + helper.find_ip()
# Encrypt cmd using servers public key
encrypted_cmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
s.send(encrypted_cmd)
# recieve response from server
recv = s.recv(REQUEST_MAX_LENGTH).decode()
# if error then stop
if(recv.split()[0] == "Error"):
# return false
print(recv)
return False
# if everything goes smoothly
return True
#
# Function to send out bytes of data from filename
#
def send_file(filename):
# going to start locking all servers for a send file
if(lock_servers() == False):
return
print("Began writing to all nodes in the network")
print("******************************")
print("******************************")
# opening a file in binary
f = open(filename, 'rb')
# get rid of the path
filename = filename.split("/")[-1]
# getting all the data in a byte string
byteString = f.read()
# seperate it into files
byteArray = helper.split_data_chunk_number(byteString, len(ledger.get_ips()))
# get clients public key
myPubkey = ledger.get_pubkey(helper.find_ip())
# going through the list of ips and making the request
for index, ip in enumerate(ledger.get_ips()):
# get the key of the server we want to send the file to
serverPubkey = ledger.get_pubkey(ip)
# check if the ip is same as our ip
if(ip == helper.find_ip()):
# open a temporary file to store the received bytes
try:
file = open("directory/" + filename + str(index), 'wb')
except:
os.mkdir("directory")
file = open("directory/" + filename + str(index), 'wb')
# write to the file and exncrypt the data
file.write(byteArray[index])
# move forward in the for loop
continue
# connect to the host you want to send file to
s = run_client(ip)
print(filename)
# create a push request for the server and encode it to bytes
cmd = "push " + filename + str(index)
# Encrypt cmd using servers public key
encryptedCmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
s.send(encryptedCmd)
# recieve response from server
recv = s.recv(REQUEST_MAX_LENGTH).decode()
# check if the servor responded with an error
if(recv.split()[0] != "Error"):
# get the string we want to send
toSend = byteArray[index]
byteCount = 0
# logging
print("Starting to send", len(toSend),"bytes to", ip)
# get the range of things to send at a time
for i in range(0, len(toSend), BYTES_TO_SEND):
# if its too big then only till the end
if(i + BYTES_TO_SEND >= len(toSend)):
byte = toSend[int(i):]
else:
byte = toSend[int(i):int(i + BYTES_TO_SEND)]
# encrypting whatever data we need to
byte = encryption.encrypt_using_public_key(byte, myPubkey)
# send the bytes
s.send(byte)
byteCount += BYTES_TO_SEND
# print("Sent", byteCount, "bytes")
# logging
print("Finished sending file")
print("******************************")
# server did respond with error
else:
print("Something went wrong")
s.close()
# logging end of command
print("******************************")
# updating the ledger locally
ledger.add_file(filename, helper.find_ip())
# sending the update ledger command to everyone
update_ledger()
#
# Receives a file
#
def receive_file(filename):
# check if the client is the owner of the file
if not ledger.check_owner(filename, helper.find_ip()):
print("File not owned by this client")
return
# create the downloaded directory if it doesnt exist, and open a file to write in
try:
file = open("directory/" + filename, 'wb')
except:
os.mkdir("directory")
file = open("directory/" + filename, 'wb')
# going through the list of ips and making the request
for index, ip in enumerate(ledger.get_ips_for_file(filename)):
# get the key of the server we want to send the file to
serverPubkey = ledger.get_pubkey(ip)
print(helper.find_ip(), ip)
# check if the current ip in the ledger is the clients
if(ip == helper.find_ip()):
# get the shard name for the file that is stored on the clients computer
shard = ledger.get_shard(filename, ip)
# open the shard to combine it with the rest of the file
tempFile = open("directory/" + shard, 'rb')
# copy the contents of the shard to the new file and decrypt the data
file.write(tempFile.read())
print("here")
# continue iterating through the loop
continue
# connect to the host you want to receive files from
s = run_client(ip)
# gets the shard filename as stored on the host computer
shard = ledger.get_shard(filename, ip)
# create a pull request for the server and encode it to bytes
cmd = helper.pad_string("pull " + shard)
# Encrypt cmd using servers public key
encryptedCmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
s.send(encryptedCmd)
# recieve confirmation response from server
receivedMessage = s.recv(REQUEST_MAX_LENGTH).decode()
# check if the servor responded with an error
if(receivedMessage.split()[0] != "Error"):
print("Receiving shard from", ip)
while True:
#receive 1024 bytes at a time and decrypt the data
bytes = s.recv(1024)
bytes = encryption.decrypt_using_private_key(bytes)
#write the decrypted data to a file
file.write(bytes)
#break infinite loop once all bytes are transferred
if not bytes:
break
# Server responded with an error
else:
print("Something went wrong while receiving the file.")
# try to remove the original sharded message
try:
os.remove("directory/" + ledger.get_shard(filename, helper.find_ip()))
except:
print("Unable to remove shard from local directory")
#close the file once transfer is complete
file.close()
#
# Gets a copy of the current ledger from a known host, adds itself,
# and broadcasts to all servers
#
def pull_ledger(ip, serverPubkey):
# connect to the ip
s = run_client(ip)
helper.clean_directory()
# create a new node request for the server and encode it to bytes
cmd = "pull_ledger ledger.json"
# Encrypt cmd using servers public key
encrypted_cmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
#Send the encrypted command to the server in bytes
s.send(encrypted_cmd)
# recieve confirmation response from server
receivedMessage = s.recv(REQUEST_MAX_LENGTH).decode()
print(receivedMessage)
if(receivedMessage.split(' ', 1)[0] != "Error"):
# generate a public and private key for the host computer
pubkey = encryption.create_keys()
#Encrypt the public key using server public key
encrypted_pubkey = encryption.encrypt_using_public_key(pubkey.encode(), serverPubkey)
#Encrypted public key is split into
pubkey_split = []
pubkey_split.append(encrypted_pubkey[0:REQUEST_MAX_LENGTH])
pubkey_split.append(encrypted_pubkey[REQUEST_MAX_LENGTH:])
print(pubkey)
print(pubkey_split)
for pubkey_part in pubkey_split:
s.send(pubkey_part)
print("Downloading ledger")
#open a new ledger and store the received bytes
file = open(ledger.LEDGER_PATH, 'wb')
start = time.time()
while True:
#receive 1024 bytes at a time and write them to a file
encrypted_bytes = s.recv(1024)
bytes = encryption.decrypt_using_private_key(encrypted_bytes)
file.write(bytes)
#break infinite loop once all bytes are transferred
if not bytes:
break
#close the file once transfer is complete
file.close()
end = time.time()
print("Finished running download of ledger in %.2f seconds" % float(end - start))
# Server responded with an error
else:
print("Something went wrong while getting the ledger.")
s.close()
return
s.close()
# update ledger with ip of client and public key
ledger.add_node(helper.find_ip(), pubkey)
# send updated ledger to all serversin the network
update_ledger()
#
# Sends a request to server for updating the ledger
#
def update_ledger():
# logging
print("******************************")
print("******************************")
print("Beginning to send updated ledger to all servers")
# going through all the ips
for ip in ledger.get_ips():
# get the key of the server we want to send to
serverPubkey = ledger.get_pubkey(ip)
# run the client
s = run_client(ip)
# create a push request for the server and encode it to bytes
cmd = "update_ledger ledger.json"
encryptedCmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
s.send(encryptedCmd)
# recieve response from server
recv = s.recv(REQUEST_MAX_LENGTH).decode()
# check if the servor responded with an error
if(recv.split(' ', 1)[0] != "Error"):
# opening a file
f = open(ledger.LEDGER_PATH, 'rb')
# read bytes and set up counter "byte"
l = f.read(BYTES_TO_SEND)
byte = BYTES_TO_SEND
# a forever loop untill file gets sent
while (l):
# encrypt the data with the pubkey of the server
encrypted_l = encryption.encrypt_using_public_key(l, serverPubkey)
# send the bytes
s.send(encrypted_l)
# read more bytes and incrementing counter
l = f.read(BYTES_TO_SEND)
byte += BYTES_TO_SEND
print(byte, "bytes sent")
# server did respond with error
else:
print("Something went wrong while updating the ledger to", recv)
print("Finished sending the ledger to everyone")
print("******************************")
print("******************************")
def load_balance():
# logging
print("******************************")
print("******************************")
print("Beginning load balancing ")
# going through each ip
for ip in ledger.get_ips():
# get the key of the server we want to send to
serverPubkey = ledger.get_pubkey(ip)
# run the client
s = run_client(ip)
# create a push request for the server and encode it to bytes
cmd = "load_balance garbage"
encryptedCmd = encryption.encrypt_using_public_key(cmd.encode(), serverPubkey)
s.send(encryptedCmd)
# recieve response from server
recv = s.recv(REQUEST_MAX_LENGTH).decode()
# check if the servor responded with an error
if(recv.split(' ', 1)[0] != "Error"):
recv = s.recv(REQUEST_MAX_LENGTH).decode()
if(recv.split(' ', 1)[0] != "Error"):
print()
# server did respond with error
else:
print("Something went wrong while sending a load balance request", s.gethostname())
print("Finished load balancing")
print("******************************")
print("******************************")
#
# Creates a new network with the IP of the client as the first node
#
def start_network():
# create a private key on the local host and its public key for the ledger
pubkey = encryption.create_keys()
# clean the directory for a fresh network
helper.clean_directory()
# create the first node in the ledger
ledger.add_first_node(helper.find_ip(), pubkey)
#
# Deals with creating the client node as well as providing the main command line interface for the program
#
def main():
pubKey = "MIGJAoGBAIyRlQ56E/7rsQmsulYp/2+FOMd3/B11wOY7WP0blJUaO1mBJwUSKWs0\nFCr49jbc2g1LROCENXS864IQozcS3Z+o+VKPd/oGnwnhx0PXIBhPaQ3o/b9Hm8nu\ndHakdI1nnu7rq5gug068tNK/L00BBWVtsTGHHfs1ClOvkoShZSSFAgMBAAE="
try:
if(sys.argv[1] == "push"):
send_file(sys.argv[2])
elif(sys.argv[1] == "pull"):
receive_file(sys.argv[2])
elif(sys.argv[1] == "pull_ledger"):
pull_ledger(sys.argv[2], pubKey)
elif(sys.argv[1] == "update_ledger"):
update_ledger()
elif(sys.argv[1] == "start_network"):
start_network()
elif(sys.argv[1] == "load_balance"):
load_balance()
else:
print("Unrecognized command entered")
except:
print("Oopsies")
main()