-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer.py
2143 lines (1738 loc) · 84 KB
/
peer.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
The peer class is really a lot bigger than I was expecting.
"""
import socket
import ssl
import os
import cPickle # Supposed to be orders of magnitude faster than `pickle`, but with some limitations limitations on (esoteric) subclassing of `Pickler`/`Unpickler`.
import hashlib
import random
import shutil
import struct
import inspect
import json
import copy
from urllib2 import urlopen
from collections import namedtuple
import threading
import time
import Crypto.Signature.PKCS1_v1_5, Crypto.Hash, Crypto.Cipher.AES, Crypto.PublicKey.RSA, Crypto.Random
import base64
import directory_merkel_tree
import subprocess
import argparse
# Named tuples have (immutable) class-like semantics for accessing fields, but are straightforward to pickle/unpickle.
# The following types are for important data whose contents and format should be relatively stable at this point.
PeerData = namedtuple('PeerData', 'ip_address, store_revisions')
StoreData = namedtuple('StoreData', 'revision_data, peers')
RevisionData = namedtuple('RevisionData', 'revision_number, store_hash, signature')
Metadata = namedtuple('Metadata', 'peer_id, peer_dict, store_id, store_dict, aes_key, aes_iv, merkel_tree')
# A needed constant for unpacking messages
HEADER_SIZE = struct.calcsize('!I')
INVALID_REVISION = None #RevisionData(revision_number=0, store_hash=None, signature=None)
class ManualDisconnectException(Exception):
pass
class Peer:
#########################
# Primary functionality #
#########################
# These are the goods, implemented at a higher level than the lower methods.
def __init__(self,
own_store_directory=os.path.join(os.getcwd(), 'own_store'),
root_directory=os.getcwd(),
debug_verbosity=0,
debug_preamble=None,
_metadata=None,
lock=threading.RLock()
):
"""Initialize a `Peer` object."""
# Set any incoming overrides
self.own_store_directory = own_store_directory
self.root_directory = root_directory
self.debug_verbosity = debug_verbosity
self.debug_preamble = debug_preamble
self._metadata = _metadata
self.lock = lock
self.initialize_directory_structure()
self.initialize_keys()
self.load_metadata_file()
def run(self, client_sleep_time=5):
"""Start operating as a both a peer client and peer server."""
# Do preliminary updates before coming online
self.update_ip_address()
self.check_store()
peer_client_thread = threading.Thread(target=self.run_peer_server, args=())
peer_client_thread.start()
self.run_peer_client()
def run_peer_client(self, sleep_time=5, timeout=2):
self.debug_print( (1, 'Peer client mode running.'))
while True:
# Find a peer to connect to and initiate a session.
server_peer_id = self.select_sync_peer()
if server_peer_id:
try:
self.debug_print( [(1, 'Attempting to connect to peer server.'),
(2, 'server_peer_id = {}'.format([server_peer_id])),
(2, 'ip_address = {}'.format(self.peer_dict[server_peer_id].ip_address))] )
# self.lock.acquire()
skt_ssl = self.connect_to_peer(server_peer_id, timeout)
try:
self.debug_print( (1, 'Successfully connected to peer server. Initiating peer client session.') )
self.peer_client_session(skt_ssl)
except socket.error:
self.debug_print( (1, 'Disconnected from peer server due to socket error.') )
except ManualDisconnectException:
self.debug_print( (2, 'The peer client session did not complete in a successful sync.') )
finally:
# self.lock.release()
try:
skt_ssl.shutdown(socket.SHUT_RDWR)
skt_ssl.close()
except socket.error:
self.debug_print( (3, 'Socket already closed by peer server.') )
self.debug_print( (1, 'Disconnected from peer server.') )
except (socket.timeout, socket.error):
self.debug_print( (2, 'Could not connect to peer server.') )
# Sleep a while before iterating the loop again.
self.debug_print( (1, 'Peer client mode going to sleep.') )
time.sleep(sleep_time)
self.debug_print( (1, 'Peer client mode waking up.') )
self.check_store() # FIXME: This is an intensive operation. Instead watch the filesystem for changes and mark with a "dirty" flag.
self.update_ip_address()
def run_peer_server(self):
self.debug_print( (1, 'Peer server mode running.'))
skt_listener = self.create_listening_socket(timeout=5)
while True:
self.debug_print( (1, 'Waiting for a peer client to connect.') )
# TODO: Will want to deal with multiple peer clients eventually.
try:
skt_raw, (peer_ip, _) = skt_listener.accept()
self.debug_print( (1, 'Connected to a peer client from \'{}\'. Initiating peer server session.'.format(peer_ip)))
skt_ssl = ssl.wrap_socket(skt_raw, server_side=True, keyfile=self.private_key_file, certfile=self.x509_cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
# self.lock.acquire()
try:
self.peer_server_session(skt_ssl, peer_ip)
except socket.error:
self.debug_print( (1, 'Disconnected from peer client due to socket error.') )
except ManualDisconnectException:
self.debug_print( (2, 'The peer server session did not complete in a successful sync.') )
finally:
# self.lock.release()
try:
skt_ssl.shutdown(socket.SHUT_RDWR)
skt_ssl.close()
except socket.error:
self.debug_print( (3, 'Socket already closed by peer client.') )
self.debug_print( (1, 'Disconnected from peer client.') )
except (socket.timeout, socket.error):
pass
def peer_server_session(self, skt_ssl, peer_ip):
self.debug_print( (2, 'Waiting for peer client\'s handshake message.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'handshake_msg')
(client_peer_id, client_peer_dict) = self.unpickle('handshake_msg', pickled_payload)
self.debug_print( [(1, 'Handshake message received from peer client.'),
(2, 'client_peer_id = {}'.format([client_peer_id])),
(3, 'client_peer_dict = {}'.format([client_peer_dict]))] )
self.debug_print( (1, 'Attempting to learn from peer client\'s reports about itself.'))
self.record_peer_data(client_peer_id, client_peer_dict[client_peer_id])
# If the peer client is of interest, handshake back.
if client_peer_id in self.peer_dict.keys():
self.debug_print( (1, 'Sending handshake message to peer client.'))
self.send_handshake_msg(skt_ssl)
# Otherwise, disconnect.
else:
self.debug_print( (1, 'No stores in common with peer client. Disconnecting.'))
self.send_disconnect_req(skt_ssl, 'No stores in common.')
raise ManualDisconnectException()
self.debug_print( (1, 'Store match!') )
# FIXME: For known client peers, will want to verify the public key provided to the SSL.
# TODO: Should only ask for peer's public key when it's unknown (?)
# Receive and record the peer client's public key file.
self.debug_print( (2, 'Waiting for peer client\'s public key.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'public_key_msg')
public_key_file_contents = self.unpickle('public_key_msg', pickled_payload)
# If the peer client is of interest to us and we don't have their public key, record it.
if (client_peer_id in self.peer_dict.keys()) \
and (not os.path.isfile(self.get_peer_key_path(client_peer_id))):
self.debug_print( [(1, 'Recording public key for new peer.'),
(4, 'public_key_file_contents = {}'.format([public_key_file_contents]))] )
with open(self.get_peer_key_path(client_peer_id), 'w') as f:
f.write(public_key_file_contents)
# Otherwise, check the supplied key against what we have on record.
# FIXME: We should really be getting this from the SSL socket.
elif (client_peer_id in self.peer_dict.keys()) \
and (self.get_peer_key(client_peer_id) != Crypto.PublicKey.RSA.importKey(public_key_file_contents)):
self.debug_print( (1, 'Public key supplied by peer client does not match what we have on record. Disconnecting.') )
self.send_disconnect_req(skt_ssl, 'Public key failed verification.')
raise ManualDisconnectException()
self.debug_print( (1, 'Parsing useful gossip from peer client.'))
self.learn_peer_gossip(client_peer_dict)
# Get the peer client's sync request.
self.debug_print( (2, 'Waiting for peer client\'s sync request.') )
pickled_payload = self.receive_expected_message(skt_ssl, 'sync_req')
sync_store_id = self.unpickle('sync_req', pickled_payload)
self.debug_print( [(1, 'Peer client sync request received.'),
(2, 'sync_store_id = {}'.format([sync_store_id]))] )
# Figure out what type of sync we'll be conducting.
sync_type = self.determine_sync_type(client_peer_id, sync_store_id)
# Sync
self.debug_print( (1, 'Executing sync of type \'{}\' with peer client.'.format(sync_type)) )
self.do_sync(skt_ssl, sync_type, client_peer_id, sync_store_id)
self.debug_print( (1, 'Successfully completed sync with peer client.'))
# Session over, send the peer client a disconnect request.
self.debug_print( (1, 'Peer server session complete. Disconnecting.'))
self.send_disconnect_req(skt_ssl, 'Session complete.')
def peer_client_session(self, skt_ssl):
# Initiate handshake with the peer server, providing pertinent metadata about ourselves and gossip.
self.debug_print( (1, 'Sending handshake message to peer server.'))
self.send_handshake_msg(skt_ssl)
self.debug_print( (2, 'Waiting for peer server\'s handshake message.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'handshake_msg')
(server_peer_id, server_peer_dict) = self.unpickle('handshake_msg', pickled_payload)
self.debug_print( [(1, 'Handshake message received from peer server.'),
(2, 'server_peer_id = {}'.format([server_peer_id])),
(3, 'server_peer_dict = {}'.format([server_peer_dict]))] )
# The peer server's knowledge of itself is at least as up to date as ours, so trust what it says.
self.record_peer_data(server_peer_id, server_peer_dict[server_peer_id])
self.debug_print( (1, 'Parsing useful gossip from peer server.'))
self.learn_peer_gossip(server_peer_dict)
# FIXME
# Always send public key file to server
self.debug_print( (1, 'Sending public key to peer server'))
self.send_public_key_msg(skt_ssl)
# Select a store to sync with the peer server.
sync_store_id = self.select_sync_store(server_peer_id)
# Quit the session if we couldn't find a store to sync.
if not sync_store_id:
self.debug_print( (1, 'No valid mutual stores to sync or check. Disconnecting.') )
self.send_disconnect_req(skt_ssl, 'No valid mutual stores to sync or check.')
raise ManualDisconnectException()
# Initiate a sync.
self.debug_print( [(1, 'Requesting sync with peer server.'),
(2, 'sync_store_id = {}'.format([sync_store_id]))] )
self.send_sync_req(skt_ssl, sync_store_id)
# Figure out what type of sync we'll be conducting.
sync_type = self.determine_sync_type(server_peer_id, sync_store_id)
# Sync
self.debug_print( (1, 'Executing sync of type \'{}\' with peer server.'.format(sync_type)))
self.do_sync(skt_ssl, sync_type, server_peer_id, sync_store_id)
self.debug_print( (1, 'Successfully completed sync with peer server.') )
self.debug_print( (1, 'Session complete.') )
self.debug_print( (2, 'Waiting for peer server\'s disconnect request.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'disconnect_req')
disconnect_message = self.unpickle('disconnect_req', pickled_payload)
self.debug_print( [(1, 'Peer requested disconnect reporting the following:'),
(1, disconnect_message)] )
def do_sync(self, skt, sync_type, peer_id, store_id):
if sync_type == 'receive':
self.sync_receive(skt, peer_id, store_id)
elif sync_type == 'send':
self.sync_send(skt, peer_id, store_id)
elif sync_type == 'check':
self.sync_check(skt, peer_id, store_id)
else:
# TODO: Raise a meaningful exception.
raise Exception()
####################
# Class attributes #
####################
# FIXME: Beware the unsafety if accessing mutable fields from multiple threads.
listening_port = 51338 # TODO: Magic number. Ideally would want listening listening_port number to be configurable per peer.
##########################
# Initialization methods #
##########################
def generate_initial_metadata(self):
"""
Generate a peer's important metadata the first time it is instantiated.
"""
# FIXME: Just do full initialization here (i.e. including revision and tree data).
peer_id = self.generate_peer_id()
store_id = self.generate_store_id()
ip_address = None # Automatically set upon running the peer
own_revision_data = INVALID_REVISION # Automatically updated upon running the peer.
merkel_tree = None # Running the peer will cause a check of the store which will populate this and sign a new revision
initial_peers = set([peer_id])
aes_key = Crypto.Random.new().read(Crypto.Cipher.AES.block_size)
aes_iv = Crypto.Random.new().read(Crypto.Cipher.AES.block_size)
# FIXME: Idempotently initialize/ensure personal directory structure here including initial revision number.
peer_dict = {peer_id: PeerData(ip_address, {store_id: own_revision_data})}
store_dict = {store_id: StoreData(own_revision_data, initial_peers)}
# Load the initial values into a `Metadata` object.
metadata = Metadata(peer_id, peer_dict, store_id, store_dict, aes_key, aes_iv, merkel_tree)
return metadata
def generate_peer_id(self):
"""
Generate a quasi-unique ID for this peer using a hash (SHA-256, which
currently has no known collisions) of the owner's public key "salted" with
32 random bits.
"""
cipher = hashlib.sha256(self.public_key.exportKey())
cipher.update(Crypto.Random.new().read(4))
peer_id = cipher.digest()
self.debug_print( (2, 'Generated new peer ID: {}'.format([peer_id])) )
return peer_id
def generate_store_id(self, public_key=None):
"""
Store IDs are meant to uniquely identify a store/user. They are essentially
the RSA public key, but we use use their SHA-256 hash to "flatten" them to
a shorter, predictable length.
"""
# Default to using own public key.
if not public_key:
public_key = self.public_key
store_id = hashlib.sha256(public_key.exportKey()).digest()
self.debug_print( (2, 'Generated new store ID: {}'.format([store_id])) )
return store_id
#######################
# Config file methods #
#######################
def initialize_directory_structure(self):
"""
Produce the directory structure to store keys, stores, and config files.
"""
if not os.path.exists(self.own_store_directory):
os.makedirs(self.own_store_directory)
self.config_directory = os.path.join(self.root_directory, '.config')
self.key_directory = os.path.join(self.config_directory, 'keys')
self.own_keys_directory = os.path.join(self.key_directory, 'own_keys')
if not os.path.exists(self.own_keys_directory):
os.makedirs(self.own_keys_directory)
self.peer_keys_directory = os.path.join(self.key_directory, 'peer_keys')
if not os.path.exists(self.peer_keys_directory):
os.makedirs(self.peer_keys_directory)
self.store_keys_directory = os.path.join(self.key_directory, 'store_keys')
if not os.path.exists(self.store_keys_directory):
os.makedirs(self.store_keys_directory)
self.stores_directory = os.path.join(self.root_directory, 'stores')
if not os.path.exists(self.stores_directory):
os.makedirs(self.stores_directory)
def initialize_keys(self):
"""
Produce public and private keys if they don't exist. Then, load the public
and private keys.
"""
self.private_key_file = os.path.join(self.own_keys_directory, 'private_key.pem')
if os.path.isfile(self.private_key_file):
with open(self.private_key_file, 'r') as f:
self.private_key = Crypto.PublicKey.RSA.importKey(f.read())
else:
self.private_key = Crypto.PublicKey.RSA.generate(2048)
with open(self.private_key_file, 'w') as f:
f.write(self.private_key.exportKey())
# Not sure we actually need to use the public key file...
self.public_key_file = os.path.join(self.own_keys_directory, 'public_key.pem')
if os.path.isfile(self.public_key_file):
with open(self.public_key_file, 'r') as f:
self.public_key = Crypto.PublicKey.RSA.importKey(f.read())
else:
self.public_key = self.private_key.publickey()
with open(self.public_key_file, 'w') as f:
f.write(self.public_key.exportKey())
self.x509_cert_file = os.path.join(self.own_keys_directory, 'x509.pem')
if not os.path.isfile(self.x509_cert_file):
# Use OpenSSL's CLI to generate an X.509 from the existing RSA private key
# Adapted from http://stackoverflow.com/a/12921889 and http://stackoverflow.com/a/12921889
subprocess.check_call('openssl req -new -batch -x509 -nodes -days 3650 -key ' +
self.private_key_file +
' -out ' + self.x509_cert_file,
shell=True)
# TODO: De-uglify
# FIXME: PyDoc
# Use a file to permanently store certain metadata.
def load_metadata_file(self):
"""
Load the metadata into the workspace. If neither a metadata file nor
backup file exists, then produce a metadata file. Finally, update
the metadata.
"""
# Create a null metadata object to update against
self._metadata = Metadata(None, None, None, None, None, None, None)
self.metadata_file = os.path.join(self.config_directory, 'metadata_file.pickle')
self.backup_metadata_file = self.metadata_file + '.bak'
try:
# Load the metadata file
if os.path.isfile(self.metadata_file):
self.debug_print( (2,'Metadata file found, loading.') )
with open(self.metadata_file, 'r') as f:
metadata = cPickle.load(f)
else:
raise Exception()
except:
try:
self.debug_print( (2,'Metadata file not found. Attempting to load backup.') )
# Load the backup file
if os.path.isfile(self.backup_metadata_file):
self.debug_print( (2,'Backup metadata file found, loading.') )
with open(self.backup_metadata_file, 'r') as f:
metadata = cPickle.load(f)
shutil.copyfile(self.backup_metadata_file, self.metadata_file)
else:
raise Exception()
except:
self.debug_print( (2,'Backup metadata file not found. Generating new file.') )
metadata = self.generate_initial_metadata()
# Immediately write out to non-volatile storage since `update_metadata()` expects a pre-existing file to be made the backup.
with open(self.metadata_file, 'w') as f:
cPickle.dump(metadata, f)
finally:
# Bring the new values into effect.
self.update_metadata(metadata)
def get_peer_key_path(self, peer_id):
"""
Return the file path for the public key given the peer id.
"""
if peer_id == self.peer_id:
key_path = self.public_key_file
else:
peer_filename = self.compute_safe_filename(peer_id)
key_path = os.path.join(self.peer_keys_directory, peer_filename+'.pem')
return key_path
def get_peer_key(self, peer_id):
"""
Return a public key given the peer id.
"""
if peer_id == self.peer_id:
return self.public_key
with open(self.get_peer_key_path(peer_id), 'r') as f:
public_key = Crypto.PublicKey.RSA.importKey(f.read())
return public_key
def get_store_key_path(self, store_id):
"""
Return the file path for the public key given the store id.
"""
if store_id == self.store_id:
key_path = self.public_key_file
else:
store_filename = self.compute_safe_filename(store_id)
key_path = os.path.join(self.store_keys_directory, store_filename+'.pem')
return key_path
def get_store_key(self, store_id):
"""
Return a public key given the peer id.
"""
if store_id == self.store_id:
return self.public_key
with open(self.get_store_key_path(store_id), 'r') as f:
public_key = Crypto.PublicKey.RSA.importKey(f.read())
return public_key
def _get_store_path(self, store_id):
"""Unsafe reference to a store's absolute path meant for internals only."""
if store_id == self.store_id:
return self.own_store_directory
store_filename = self.compute_safe_filename(store_id)
return os.path.join(self.stores_directory, store_filename)
def compute_safe_filename(self, input_string):
return base64.urlsafe_b64encode(input_string)
######################
# Metadata accessors #
######################
@property
def peer_id(self):
"""A quasi-unique identifier for this particular peer."""
return self.metadata.peer_id
@property
def peer_dict(self):
"""
A mapping from the IDs of other peers who serve as backups to this peer to
important metadata such as their IP address and what revisions they had for
stores of interest upon last contact.
"""
return self.metadata.peer_dict
@property
def store_id(self):
"""A quasi-unique identifier for this peer's store."""
return self.metadata.store_id
@property
def store_dict(self):
"""
A mapping from store IDs to important metadata such as this peer's current
revision for the store and the IDs of peers known to be associated with the
store.
"""
return self.metadata.store_dict
@property
def merkel_tree(self):
return self.metadata.merkel_tree
@property
def aes_key(self):
return self.metadata.aes_key
@property
def aes_iv(self):
return self.metadata.aes_iv
# FIXME: This is returning `None` even though `self._metadata` gives the correct output.
@property
def metadata(self):
"""
Important metadata about peers and stores. Access is controlled to ensure
that all changes are backed up to primary storage.
"""
return self._metadata
def get_revision_data(self, peer_id, store_id):
"""
Return the revision data given a peer id and store id.
"""
revision_data = self.peer_dict[peer_id].store_revisions[store_id]
return revision_data
#####################
# Metadata mutators #
#####################
# Trying out weaving a lock through these calls (akin to priority inversion)
# so only one thread can access the metadata at a time. Hope it works.
def update_metadata(self, metadata, lock_acquired=False):
"""
All updates to a peer's stored metadata occur through this function so
we can ensure that changes are backed up to primary storage before coming
into effect.
"""
# Make sure we have the lock before proceeding
# if not lock_acquired:
# self.lock.acquire()
# Only update if necessary.
if metadata == self.metadata:
self.debug_print( (2, 'No new metadata; update skipped.') )
return
# Accumulate and squawk out reports of changes.
print_tuples = [(2, 'Updating metadata configuration.')]
if metadata.peer_id != self.peer_id:
print_tuples.append( (2, 'peer_id = {}'.format([metadata.peer_id])) )
if metadata.peer_dict != self.peer_dict:
print_tuples.append( (2, '`peer_dict` updated') )
print_tuples.append( (3, 'peer_dict = {}'.format(metadata.peer_dict)) )
if metadata.store_id != self.store_id:
print_tuples.append( (2, 'store_id = {}'.format([metadata.store_id])) )
if metadata.store_dict != self.store_dict:
print_tuples.append( (2, '`store_dict` updated') )
print_tuples.append( (3, 'store_dict = {}'.format(metadata.store_dict)) )
if metadata.aes_key != self.aes_key:
print_tuples.append( (2, '`aes_key` updated') )
print_tuples.append( (4, '!!!! SOOOoo INSECURE !!!!') )
print_tuples.append( (4, 'aes_key = {}'.format([metadata.aes_key])) )
if metadata.aes_iv != self.aes_iv:
print_tuples.append( (2, '`aes_iv` updated') )
print_tuples.append( (4, '!!!! SOOOoo INSECURE !!!!') )
print_tuples.append( (4, 'aes_iv = {}'.format([metadata.aes_iv])) )
if metadata.merkel_tree != self.merkel_tree:
print_tuples.append( (2, '`merkel_tree` updated') )
print_tuples.append( (4, 'merkel_tree:') )
self.debug_print( print_tuples )
if (metadata.merkel_tree != self.merkel_tree) and (self.debug_verbosity >= 4):
directory_merkel_tree.print_tree(self.merkel_tree)
# Copy the previous metadata file to the backup location.
shutil.copyfile(self.metadata_file, self.backup_metadata_file)
# Write the new metadata to primary storage.
with open(self.metadata_file, 'w') as f:
cPickle.dump(metadata, f)
# Refer to the new metadata now that it's been stored to disk
self._metadata = metadata
# Release the lock if we personally acquired it
# if not lock_acquired:
# self.lock.release()
# # FIXME: Would want similar functionality for server requested associations
# def record_store_association(self, peer_id, store_id, lock=False):
# """
# Permanently record the list of stores that other peers are associated
# with. Also, if the connecting peer is a backup for a store that this peer is
# also a backup for, update that store's metadata accordingly.
# """
# # Do nothing if this peer's associations were already known
# if (store_id in self.store_dict.keys()) and \
# (peer_id in self.store_dict[store_id].peers) and \
# (peer_id in self.peer_dict.keys()) and \
# (store_id in self.peer_dict[peer_id].stores):
# return
#
# # Make sure we have the lock before proceeding
# if not lock:
# self.lock.acquire()
# lock = True
#
# self.debug_print( [(1, 'Recording new store association.'),
# (2, 'peer_id = ' + peer_id + ', store_id=' + store_id)])
#
# # Create a copy of the peer metadata to stage the new changes.
# peer_dict = self.peer_dict.copy()
# peer_dict[peer_id].stores.add(store_id)
#
# # Create a copy of the store metadata to stage the new changes.
# store_dict = self.store_dict.copy()
#
# # Creating a new store
# if store_id not in self.store_dict.keys():
# store_data = StoreData(0, set()) # FIXME: Will need actual revision number format rather than `0`.
# # The previously known store only needs to be amended.
# else:
# store_data = copy.deepcopy(self.store_dict[store_id]) # Named tuples (and tuples in general) require deep copying... I think.
# store_data.peers.add(peer_id)
# # FIXME: Will also want to record this peer's revision number.
# store_dict[store_id] = store_data
#
# metadata = Metadata(self.peer_id, peer_dict, self.store_id, store_dict)
# self.update_metadata(metadata)
def record_peer_data(self, peer_id, peer_data, lock_acquired=False):
"""
Update the recorded metadata for an individual peer.
"""
# Make sure we have the lock before proceeding
# if not lock_acquired:
# self.lock.acquire()
peer_mutual_stores = set(peer_data.store_revisions.keys()).intersection(set(self.store_dict.keys()))
# Only want to track peers that are associated with at least one store we're concerned with.
if not peer_mutual_stores:
return
# Only want new data.
if (peer_id in self.peer_dict.keys()) and (peer_data == self.peer_dict[peer_id]):
return
# Create copies data for staging changes.
peer_dict = copy.deepcopy(self.peer_dict)
store_dict = copy.deepcopy(self.store_dict)
# Prepare an empty record if the peer wasn't already known.
if not (peer_id in self.peer_dict.keys()):
ip_address = None
store_revisions = dict()
# Otherwise, work from existing knowledge of the peer.
else:
ip_address = peer_dict[peer_id].ip_address
store_revisions = peer_dict[peer_id].store_revisions
# Record the peer's associations with only the stores we care about.
for mutual_store_id in peer_mutual_stores:
# Verify the reported revision data before recording.
if self.verify_revision_data(mutual_store_id, peer_data.store_revisions[mutual_store_id]):
store_revisions[mutual_store_id] = peer_data.store_revisions[mutual_store_id]
else:
store_revisions[mutual_store_id] = INVALID_REVISION
# Simultaneously ensure the store's association with the peer to maintain the bidirectional mapping.
store_dict[mutual_store_id].peers.add(peer_id)
# FIXME
# Again, peers are unaware of their own IP addresses, so only take valid changes thereof
if peer_data.ip_address:
ip_address = peer_data.ip_address
# Enact the update.
peer_dict[peer_id] = PeerData(ip_address, store_revisions)
metadata = Metadata(self.peer_id, peer_dict, self.store_id, store_dict, self.aes_key, self.aes_iv, self.merkel_tree)
self.update_metadata(metadata, True)
# Release the lock if we personally acquired it
# if not lock_acquired:
# self.lock.release()
def learn_peer_gossip(self, gossip_peer_dict, lock=False):
"""
Update our knowledge of peers based on gossip from another peer.
"""
# Thoroughly checked. (besides locking)
# Make sure we have the lock before proceeding
# if not lock:
# self.lock.acquire()
# Limit our considerations to mutual peers.
mutual_peers = set(gossip_peer_dict.keys()).intersection(set(self.peer_dict.keys()))
our_stores = set(self.store_dict.keys())
for peer_id in mutual_peers:
# Only update if information about received about a peer is newer than our
# records. Currently, the ways of detecting this are somewhat indirect.
# TODO: Without signing `PeerData` objects, malicious peers
# can manipulate the state of another peer. (versioning too?)
gossip_peer_stores = set(gossip_peer_dict[peer_id].store_revisions.keys())
recorded_peer_stores = set(self.peer_dict[peer_id].store_revisions.keys())
# See if the gossip indicates the peer is newly associated with a store we also have.
if gossip_peer_stores.intersection(our_stores).difference(recorded_peer_stores):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
break
# See if the gossip reports the peer to be more current with any mutual
# store than we knew about.
peer_mutual_stores = gossip_peer_stores.intersection(our_stores)
gossip_peer_revision_data = gossip_peer_dict[peer_id].store_revisions
recorded_peer_revision_data = self.peer_dict[peer_id].store_revisions
gossip_revisions = [gossip_peer_revision_data[store_id] for store_id in peer_mutual_stores]
recorded_revisions = [recorded_peer_revision_data[store_id] for store_id in peer_mutual_stores]
if any( self.gt_revision_data(s_id, g_rev, r_rev) \
for s_id, g_rev, r_rev in zip(peer_mutual_stores, gossip_revisions, recorded_revisions) ):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
break
# Learn new peers associated with our stores of interest.
unknown_peers = set(gossip_peer_dict.keys()).difference(set(self.peer_dict.keys()))
for peer_id in unknown_peers:
gossip_peer_stores = set(gossip_peer_dict[peer_id].store_revisions.keys())
if set(gossip_peer_stores).intersection(our_stores):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
# Release the lock if we personally acquired it
# if not lock:
# self.lock.release()
def update_ip_address(self, lock=False):
"""Update this peer's already existing IP address data."""
# Make sure we have the lock before proceeding
if not lock:
self.lock.acquire()
# Create staging copy of data to be changed
peer_dict = copy.deepcopy(self.peer_dict)
# Get and store the IP address
# FIXME: Would like to sign this data (probably the whole `PeerData` object).
ip_address = json.load(urlopen('http://httpbin.org/ip'))['origin']
peer_data = PeerData(ip_address, peer_dict[self.peer_id].store_revisions)
peer_dict[self.peer_id] = peer_data
# Enact the change.
metadata = Metadata(self.peer_id, peer_dict, self.store_id, self.store_dict, self.aes_key, self.aes_iv, self.merkel_tree)
self.update_metadata(metadata, True)
# Release the lock if we personally acquired it
# if not lock:
# self.lock.release()
def update_peer_revision(self, peer_id, store_id, invalid=False, lock=None):
"""
After sending a peer synchronization data and verifying their store contents,
update our recording of their revision for the store in question to match
ours.
"""
# Make sure we have the lock before proceeding
# if not lock:
# self.lock.acquire()
# If the peer had a more recent revision than us, no need to update.
our_revision = self.get_revision_data(self.peer_id, store_id)
their_revision = self.get_revision_data(peer_id, store_id)
if self.gt_revision_data(store_id, their_revision, our_revision):
return
# Create a copy of the pertinent data in which to stage our changes.
peer_store_revisions = copy.deepcopy(self.peer_dict[peer_id].store_revisions)
if not invalid:
# Set the peer's revision for the store to match ours.
self.debug_print( (1, 'Syncing peer is now at revision {}'.format(self.store_dict[store_id].revision_data.revision_number)) )
peer_store_revisions[store_id] = self.store_dict[store_id].revision_data
else:
# Record the peer's revision for the store as `None`
peer_store_revisions[store_id] = INVALID_REVISION
# Enact the changes
peer_data = PeerData(self.peer_dict[peer_id].ip_address, peer_store_revisions)
self.record_peer_data(peer_id, peer_data, True)
# Release the lock if we personally acquired it
# if not lock:
# self.lock.release()
def update_own_store_revision(self, store_id, revision_data, lock=None):
"""
Update the store dictionary for a given store id with new revision data.
"""
# Make sure we have the lock before proceeding
# if not lock:
# self.lock.acquire()
# Create a copy of the pertinent data in which to stage our changes.
store_dict = copy.deepcopy(self.store_dict)
store_dict[store_id] = StoreData(revision_data=revision_data, peers=store_dict[store_id].peers.union(set([self.peer_id])))
# Also modify our own entry in the peer dictionary so we can gossip to other peers about the new revision.
ip_address = self.peer_dict[self.peer_id].ip_address
store_revisions = copy.deepcopy(self.peer_dict[self.peer_id].store_revisions)
store_revisions[store_id] = revision_data
peer_data = PeerData(ip_address, store_revisions)
self.record_peer_data(self.peer_id, peer_data)
# Enact the change
metadata = Metadata(self.peer_id, self.peer_dict, self.store_id, store_dict, self.aes_key, self.aes_iv, self.merkel_tree)
self.update_metadata(metadata, True)
# Release the lock if we personally acquired it
# if not lock:
# self.lock.release()
def check_store(self):
"""
Check this peer's own store for changes generating new revision data and a
new Merkel tree upon updates.
"""
# Compute new Merkel tree from scratch.
new_merkel_tree = directory_merkel_tree.make_dmt(self.own_store_directory, encrypter=self)
if (self.merkel_tree) and (self.merkel_tree == new_merkel_tree):
return
if (self.store_dict[self.store_id].revision_data == INVALID_REVISION):
revision_number = 1
else:
revision_number = self.store_dict[self.store_id].revision_data.revision_number + 1
# Our store has changed so get, sign, and record the new revision data.
store_hash = new_merkel_tree.dmt_hash
pickled_payload = cPickle.dumps( (revision_number, store_hash) )
signature = self.sign(pickled_payload)
# Update our revision data for this store (and for our association to it).
revision_data = RevisionData(revision_number=revision_number, store_hash=store_hash, signature=signature)
self.update_own_store_revision(self.store_id, revision_data)
# Also store the new Merkel tree.
metadata = Metadata(self.peer_id, self.peer_dict, self.store_id, self.store_dict, self.aes_key, self.aes_iv, new_merkel_tree)
self.update_metadata(metadata)
self.debug_print( (1, 'Change detected in own store. New signed revision number: {}'.format(revision_number)) )
def store_put_item(self, store_id, relative_path, file_contents=None):
"""
Store data to the gen relative path for a store id.
"""
if relative_path[-1] == '/':
isdir = True
else:
isdir = False
if store_id == self.store_id:
# Undo the path encryption done while creating our Merkel tree.
relative_path = self.decrypt_own_store_path(relative_path)
self.debug_print( [(2, 'relative_path (decrypted) = {}'.format(relative_path))] )
# If a file, decrypt the contents
if not isdir:
file_contents = self.decrypt(file_contents)
self.debug_print( [(5, 'file_contents (decrypted) = {}'.format(file_contents))] )
path = os.path.join(self._get_store_path(store_id), relative_path)
if isdir:
self.debug_print( [(1, 'Writing directory to store.')] )
# (2, 'store_id = {}'.format(store_id))
# (2, 'relative_path = {}'.format(relative_path))])
if not os.path.exists(path):
os.makedirs(path)
else:
# Create subdirectory levels as needed.
file_directory = os.path.dirname(path)
if not os.path.isdir(file_directory):
os.makedirs(file_directory)
self.debug_print( [(1, 'Writing file to store.')] )
# (2, 'store_id = {}'.format(store_id))
# (2, 'relative_path = {}'.format(relative_path)),
# (5, 'file_contents:'),
# (5, file_contents)])
with open(path, 'w') as f:
f.write(file_contents)
def store_delete_item(self, store_id, relative_path):
"""
Delete data at the given relative path for a store id
"""
if store_id == self.store_id:
# Undo the path encryption done while creating our Merkel tree.
relative_path = self.decrypt_own_store_path(relative_path)
self.debug_print( [(2, 'relative_path (decrypted) = {}'.format(relative_path))] )
path = os.path.join(self._get_store_path(store_id), relative_path)
if os.path.isfile(path):
self.debug_print( (1, 'Deleting file from store.') )
os.remove(path)
elif os.path.isdir(path):
self.debug_print( (1, 'Deleting directory (and contents) from store.') )
# Note that this deletes the non-empty directories, so depending on the
# ordering of delete items we might preemptively delete files or folders
# that still have pending delete requests.
shutil.rmtree(path)
def decrypt_own_store_path(self, encrypted_relative_path):
"""
Take a given encrypted relative path and decrypt it directory by directory
"""
print_tuples = [ (1, 'DEBUG: Decrypting path: {}'.format(encrypted_relative_path)) ]
encrypted_path_elements = encrypted_relative_path.split('/')
decrypted_path_elements = [self.decrypt_filename(e) for e in encrypted_path_elements]
decrypted_relative_path = '/'.join(decrypted_path_elements)
print_tuples.append( (1, 'DEBUG: Decrypted to: {}'.format(decrypted_relative_path)) )