-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdpropman.py
1190 lines (1040 loc) · 47.4 KB
/
dpropman.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
#!/usr/bin/env python
import sys
import os
import socket
import httplib
import re
import urllib
import random
from optparse import OptionParser
from urlparse import urlparse
import gobject
import dbus, dbus.service
from dbus.mainloop.glib import DBusGMainLoop
import twisted.internet.glib2reactor
if __name__ == '__main__':
twisted.internet.glib2reactor.install()
from twisted.web.error import NoResource
from twisted.web.resource import Resource
from twisted.web.server import Site as TwistedSite
from twisted.web.http import parse_qs
from twisted.internet.reactor import listenTCP, listenSSL
import OpenSSL.SSL
import netifaces
import threading
from dpropjson import Nothing
import dpropjson
SYNC_INTERVAL = 30000
DEBUG = True
def pdebug(s):
if DEBUG:
print s
def ipAddresses():
addrs = []
for iface in netifaces.interfaces():
try:
ifaddrs = netifaces.ifaddresses(iface)
except ValueError:
continue
for type in ifaddrs:
for item in ifaddrs[type]:
if 'addr' in item:
addrs.append(item['addr'])
return addrs
def makeEtag(data):
"""Generate an ETag."""
myHash = hash(data) & 0xFFFFFFFF
if myHash < 0:
return "%08X" % (myHash + 2 * (sys.maxint + 1))
else:
return "%08X" % (myHash)
def formatCertName(cert):
"""Generate the string for the given X509Name."""
return "/C=%s/ST=%s/L=%s/O=%s/OU=%s/CN=%s/emailAddress=%s" % (cert.C, cert.ST, cert.L, cert.O, cert.OU, cert.CN, cert.emailAddress)
def pathifyURL(url):
parsed = urlparse(url)
return parsed.netloc + '/' + parsed.path
def urandomGenForgeryKey():
"""Generates a new forgery key using a cryptographically secure random
number generator."""
c = '0123456789ABCDEF'
bytes = os.urandom(16)
string = ''
for byte in bytes:
string += c[ord(byte) & 0x0F] + c[(ord(byte) >> 4) & 0x0F]
return string
def randomGenForgeryKey():
"""Generates a new forgery key using the default Mersenne twister
algorithm included with Python."""
c = '0123456789ABCDEF'
bytes = [random.randint(0, 255) for x in range(16)]
string = ''
for byte in bytes:
string += c[byte & 0x0F] + c[(byte >> 4) & 0x0F]
return string
def genForgeryKey():
raise NotImplementedError
class DPropManCellPeer(Resource):
"""HTTP collection representing a peer of a single cell."""
def __init__(self, dpropman, path, peer):
Resource.__init__(self)
self.dpropman = dpropman
self.path = path
self.peer = peer
def render_GET(self, request):
# Just some filler if someone pulls the peer list.
request.setResponseCode(httplib.OK)
request.setHeader('content-type', 'text/html')
return """<html>
<head><title>DProp Cell Peer</title></head>
<body>
<h1>DProp Cell Peer</h1>
<p>Hi! I'm a cell peer!</p>
</body>
</html>"""
def render_POST(self, request):
if request.args['_method'].upper() == 'PUT':
return self.render_DELETE(request)
else:
request.setResponseCode(httplib.METHOD_NOT_ALLOWED)
return ""
def render_DELETE(self, request):
# Extract the certificate for access control purposes.
cert = False
if self.dpropman.useSSL:
cert = request.channel.transport.getPeerCertificate()
# Get the cell data.
cell = self.dpropman.cells[self.path]
# Perform access control (simple read/write limits for now)
if cell.accessForCert(cert) == 'r':
request.setHeader('X-Access', 'read')
elif cell.accessForCert(cert) == 'w':
request.setHeader('X-Access', 'write')
else:
# Do not return the data if the certificate lacks access.
request.setResponseCode(httplib.FORBIDDEN)
return ""
if cell.peers[self.peer] != cert:
# Do not return the data if the certificate lacks access.
request.setResponseCode(httplib.FORBIDDEN)
return ""
# Remove the peer from the peers collection.
del cell.peers[request.args['peer']]
request.setResponseCode(httplib.OK)
return ""
class DPropManCellPeers(Resource):
"""HTTP collection representing the peers of a single cell."""
def __init__(self, dpropman, path):
Resource.__init__(self)
self.dpropman = dpropman
self.path = path
# def getChild(self, path, request):
# child = request.postpath
# if child in self.dpropman.cells[self.path].peers:
# return DPropManCellPeer(self.dpropman, path, child)
# elif child == '':
# return self
# else:
# return twisted.web.error.NoResource("No such resource.")
def render_GET(self, request):
pdebug("Received GET for Peers of %s" % (self.path))
cert = False
if self.dpropman.useSSL:
cert = request.channel.transport.getPeerCertificate()
cell = self.dpropman.cells[self.path]
# Require a certificate?
if self.dpropman.useSSL and not cell.requireCert and not cert:
request.setResponseCode(httplib.FORBIDDEN)
return ""
cell.peerLock.acquire()
if request.getHeader('If-None-Match') == cell.peersEtag:
pdebug("Responding with NOT MODIFIED")
request.setResponseCode(httplib.NOT_MODIFIED)
cell.peerLock.release()
return ""
else:
# Return the data and ETag if updated...
pdebug("Responding with OK")
request.setResponseCode(httplib.OK)
request.setETag(cell.peersEtag)
data = dpropjson.dumps(cell.peers).encode('utf-8')
cell.peerLock.release()
return data
def render_PUT(self, request):
# Extract the certificate for access control purposes.
pdebug("Received PUT for Peers of %s" % (self.path))
parameters = parse_qs(request.content.read(), 1)
cert = False
if self.dpropman.useSSL:
cert = request.channel.transport.getPeerCertificate()
# Get the cell data.
cell = self.dpropman.cells[self.path]
# # Perform access control (simple read/write limits for now)
# if cell.accessForCert(cert) == 'r':
# request.setHeader('X-Access', 'read')
# elif cell.accessForCert(cert) == 'w':
# request.setHeader('X-Access', 'write')
# else:
# # Do not return the data if the certificate lacks access.
# request.setResponseCode(httplib.FORBIDDEN)
# return ""
# Add the peer to the peers collection.
# To make this idempotent, shouldn't this require the cert to
# be part of the request itself?
url = dpropjson.loads(parameters['peer'][0])['url']
path = pathifyURL(url)
pdebug("Adding %s as peer" % (url))
cell.peerLock.acquire()
cell.peers[url] = {'cert': False, 'url': url}
cell.peersEtag = makeEtag(dpropjson.dumps(cell.peers))
pdebug("New peersEtag: %s" % (cell.peersEtag))
cell.peerLock.release()
request.setResponseCode(httplib.OK)
return ""
class DPropManCell(Resource):
"""HTTP resource representing a single cell."""
maxMem = 100 * 1024
maxFields = 1024
maxSize = 10 * 1024 * 1024
def __init__(self, dpropman, path):
Resource.__init__(self)
self.dpropman = dpropman
self.path = path
self.peers = DPropManCellPeers(dpropman, path)
self.putChild('Peers', self.peers)
self.putChild('', self)
def render_GET(self, request):
# Extract the certificate for access control purposes.
pdebug("Received GET for %s" % (self.path))
cert = False
if self.dpropman.useSSL:
cert = request.channel.transport.getPeerCertificate()
# Get the cell data.
cell = self.dpropman.cells[self.path]
# Require a certificate?
if self.dpropman.useSSL and not cell.requireCert and not cert:
request.setResponseCode(httplib.FORBIDDEN)
return ""
# # Perform access control (simple read/write limits for now)
# if cell.accessForCert(cert) == 'r':
# request.setHeader('X-Access', 'read')
# elif cell.accessForCert(cert) == 'w':
# request.setHeader('X-Access', 'write')
# else:
# # Do not return the data if the certificate lacks access.
# request.setResponseCode(httplib.FORBIDDEN)
# return ""
# Check the ETag.
cell.dataLock.acquire()
if request.getHeader('If-None-Match') == cell.etag:
pdebug("Responding with NOT MODIFIED")
request.setResponseCode(httplib.NOT_MODIFIED)
cell.dataLock.release()
return ""
else:
# Return the data and ETag if updated...
pdebug("Responding with OK")
request.setResponseCode(httplib.OK)
request.setETag(cell.etag)
data = cell.data
cell.dataLock.release()
return data
def render_PUT(self, request):
# Extract the certificate for access control purposes.
pdebug("Received PUT for %s" % (self.path))
parameters = parse_qs(request.content.read(), 1)
cert = False
if self.dpropman.useSSL:
cert = request.channel.transport.getPeerCertificate()
# Is the client allowed to update this cell?
# For now, they can if they're in the list of peers.
cell = self.dpropman.cells[self.path]
if request.getHeader('Referer') not in cell.peers:
# if cell.accessForCert(cert) != 'w':
pdebug("PUT came from unrecognized referer! FORBIDDEN!")
request.setResponseCode(httplib.FORBIDDEN)
return ""
# If so, forward the update to the cell so it can do the merge.
pdebug("PUT was ACCEPTED! Forwarding Update!")
cell.doUpdate(parameters['data'][0], request.getHeader('Referer'),
False)
# And let the client know that it was accepted.
request.setResponseCode(httplib.ACCEPTED)
return ""
def render_POST(self, request):
pdebug("Received POST for %s" % (self.path))
if request.args['_method'].upper() == 'PUT':
pdebug("But it's actually a PUT!")
return self.render_PUT(request)
else:
pdebug("But it's not actually a PUT.")
request.setResponseCode(httplib.METHOD_NOT_ALLOWED)
return ""
class DPropManCells(Resource):
"""Top-level of cell access."""
def __init__(self, dpropman):
Resource.__init__(self)
self.dpropman = dpropman
def getChild(self, path, request):
# path = '/' + '/'.join([path] + request.postpath)
pdebug("Attempting to find cell for %s" % (path))
# pdebug("Possible paths include %s" % (`self.dpropman.cells.keys()`))
if path in self.dpropman.cells:
pdebug("Found it!")
return DPropManCell(self.dpropman, path)
elif path == '':
pdebug("Oh, well I wasn't looking for a cell anyway.")
return self
else:
pdebug("Couldn't find cell!")
return twisted.web.error.NoResource("No such resource.")
def render_GET(self, request):
# Just some filler if someone pulls the cell list.
request.setResponseCode(httplib.OK)
request.setHeader('content-type', 'text/html')
return """<html>
<head><title>DProp Cells</title></head>
<body>
<h1>DProp Cells</h1>
<p>Hi! Cells live under me!</p>
</body>
</html>"""
class DPropManTopLevel(Resource):
"""Top-level of the HTTP server (no cells)"""
def __init__(self, dpropman):
Resource.__init__(self)
self.dpropman = dpropman
self.cells = DPropManCells(dpropman)
self.putChild('Cells', self.cells)
self.putChild('', self)
def render_GET(self, request):
# Just some filler if someone pulls the main list.
request.setResponseCode(httplib.OK)
request.setHeader('content-type', 'text/html')
return """<html>
<head><title>DProp Server</title></head>
<body>
<h1>DProp Server</h1>
<p>Hi! I'm a DProp server set up on %s!</p>
</body>
</html>""" % (self.dpropman.hostname)
class InvalidURLException(dbus.DBusException):
"""An invalid URL has been specified."""
_dbus_error_name = 'edu.mit.csail.dig.DPropMan.InvalidURLException'
#class NonExistantCellPathException(dbus.DBusException):
# """No cell with the given path exists."""
# _dbus_error_name = 'edu.mit.csail.dig.DPropMan.InvalidURLException'
#class BadAccessTypeException(dbus.DBusException):
# """The access type provided was not recognized."""
# _dbus_error_name = 'edu.mit.csail.dig.DPropMan.BadAccessTypeException'
class UUIDMismatchException(dbus.DBusException):
"""The UUID provided when creating the cell does not match the UUID in
the URL being used for synchronization."""
_dbus_error_name = 'edu.mit.csail.dig.DPropMan.UUIDMismatchException'
class Cell(dbus.service.Object):
"""A local cell in a propagator network."""
def __init__(self, conn, object_path, uuid, referer, cert, key):
"""Initialize the Cell."""
pdebug("Setting up cell %s" % (uuid))
self.object_path = object_path
self.uuid = uuid
self.data = dpropjson.dumps(Nothing())
self.etag = makeEtag(self.data)
self.dataLock = threading.Lock()
self.referer = referer
self.cert = cert
# self.forgeryKey = genForgeryKey()
# self.key = key
# self.readAccess = set()
# self.writeAccess = set()
self.peers = {self.referer: {'cert': None, 'url': self.referer}}
self.peersEtag = makeEtag(dpropjson.dumps(self.peers))
self.peerLock = threading.Lock()
self.dpropSync = True
self.requireCert = True
pdebug("New peersEtag: %s" % (self.peersEtag))
# Set up synchronization
def startSyncThunk():
# A thunk to start synchronization mechanisms.
pdebug("Attempting to start synchronization thunks")
def thunkifyPeerSync(peer):
# Make the thunk to sync with the given peer.
def thunk():
pdebug("Attempting to sync %s to peer %s" % (self.uuid,
peer['url']))
if not self.dpropSync:
# Send out the signal to do synchronization.
pdebug("Sending out signal for delegation...")
self.SyncSignal(self.referer, dpropjson.dumps(peer),
self.etag, self.peersEtag)
return False
try:
url = urlparse(peer['url'])
if url.scheme == 'http':
h = httplib.HTTPConnection(url.netloc)
elif url.scheme == 'https':
# TODO: Is it safe to keep these keys and
# certs around???
h = httplib.HTTPSConnection(url.netloc)
# key_file=self.key,
# cert_file=self.cert)
pdebug("Attempting to sync data")
h.request('GET', url.path,
headers={'Referer': self.referer,
'If-None-Match': self.etag})
resp = h.getresponse()
if resp.status == httplib.OK:
# Got a response. Time to merge.
pdebug("Got new data in sync. Merging...")
self.doUpdate(resp.read(), peer['url'], False)
elif resp.status == httplib.NOT_MODIFIED:
pdebug("Sync resulted in no new data.")
# Dummy resp.read() to make sure we can reuse h.
resp.read()
else:
# TODO: Handle errors
pdebug("Unexpected HTTP response!")
# Next, sync peers.
pdebug("Attempting to sync peers")
h.request('GET', url.path + '/Peers',
headers={'Referer': self.referer,
'If-None-Match': self.peersEtag})
# Why do I get a ResponseNotReady error?
# Why are the peers a bad eTag?
resp = h.getresponse()
if resp.status == httplib.OK:
# Got a response. Time to merge.
pdebug("Got new data in sync. Merging...")
self.peerLock.acquire()
self.peers.update(dpropjson.loads(resp.read()))
self.peersEtag = makeEtag(dpropjson.dumps(self.peers))
pdebug("New etag: %s" % (self.peersEtag))
self.peerLock.release()
elif resp.status == httplib.NOT_MODIFIED:
pdebug("Sync resulted in no new data.")
else:
# TODO: Handle errors
pdebug("Unexpected HTTP response!")
h.close()
except httplib.HTTPException, exc:
# TODO: Handle exceptions
pdebug("Caught HTTPException: %s: %s" % (type(exc).__name__,
str(exc)))
return False
return thunk
for peerKey in self.peers:
if peerKey == self.referer:
continue
# We now use threading.
t = threading.Thread(target=thunkifyPeerSync(self.peers[peerKey]))
t.start()
# gobject.idle_add(thunkifyPeerSync(self.peers[peerKey]))
pdebug("Done adding thunks.")
# TODO: Ehm, what if we delete this cell???
return True
# Enable syncing
gobject.timeout_add(SYNC_INTERVAL, startSyncThunk)
dbus.service.Object.__init__(self, conn, object_path)
@dbus.service.method('edu.mit.csail.dig.DPropMan',
in_signature='s', out_signature='s')
def escapePath(self, cellPath):
"""[DBUS METHOD] Escape a cell path."""
canonical = ''
for char in cellPath:
if ObjectPathRegexp.match(char):
canonical += char
else:
canonical += "_%02X" % (ord(char))
return canonical
def doUpdate(self, message, peer, isLocal):
"""Handles sending out an update signal and then maybe updating
peers. Call me with a Python string containing JSON."""
# Push the update along if it was a local update attempt.
pdebug("%s sending out UpdateSignal" % (self.uuid))
self.UpdateSignal(message, peer)
if isLocal:
self.updatePeers(message)
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def UpdateSignal(self, message, peer):
"""[DBUS SIGNAL] Signals a requested update from peer in the cell's
content."""
pass
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def SyncSignal(self, referer, peer, etag):
"""[DBUS SIGNAL] Signals that a synchronization should be attempted
with the given peer."""
pass
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def SendUpdateSignal(self, referer, peer, message):
"""[DBUS SIGNAL] Signals that an update should be sent to the given
peer."""
pass
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def PeerAddSignal(self, referer, peer):
"""[DBUS SIGNAL] Signals that an update should be sent to the given
peer to add us."""
pass
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def DoInitSignal(self, referer, url):
"""[DBUS SIGNAL] Signals that the cell should be initialized from the
peer."""
pass
@dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
def NotifyPropagatorsSignal(self):
"""[DBUS SIGNAL] Signals that a cell has changed its content and
connected propagators should wake up."""
pass
# @dbus.service.signal('edu.mit.csail.dig.DPropMan.Cell')
# def DestroySignal(self):
# """[DBUS SIGNAL] Signals the destruction of the cell."""
# pass
def updatePeers(self, message):
"""Notify all peer cells of any updates."""
pdebug("%s attempting to update peers" % (self.uuid))
def thunkifyPeerUpdate(peer, message):
# Make the thunk to send the update.
def thunk():
pdebug("%s attempting to update peer %s" % (self.uuid,
peer['url']))
if not self.dpropSync:
# Send out the signal to forward an update.
pdebug("Sending out signal for delegation...")
self.SendUpdateSignal(self.referer, peer, message)
return False
try:
url = urlparse(peer['url'])
if url.scheme == 'http':
h = httplib.HTTPConnection(url.netloc)
elif url.scheme == 'https':
# TODO: Is it safe to keep these keys and
# certs around???
h = httplib.HTTPSConnection(url.netloc)
# key_file=self.key,
# cert_file=self.cert)
# We don't dpropjson encode here, as the data
# should already be in JSON.
h.request('PUT', url.path,
urllib.urlencode(
{'data': message}),
{'Referer': self.referer,
'Content-Type':
'application/x-www-form-urlencoded'})
resp = h.getresponse()
if resp.status != httplib.ACCEPTED:
# TODO: Handle errors
pdebug("Didn't get ACCEPTED response!!")
else:
pdebug("PeerUpdate was ACCEPTED!!")
h.close()
except httplib.HTTPException, exc:
# TODO: Handle exceptions
pdebug("Caught HTTPException: %s: %s" % (type(exc).__name__,
str(exc)))
return False
return thunk
pdebug("Setting up peerUpdate thunks...")
for peerKey in self.peers:
if peerKey == self.referer:
continue
# For each peer, add a thunk to update it to the runloop
# We now use threading.
t = threading.Thread(target=thunkifyPeerUpdate(self.peers[peerKey],
message))
t.start()
# gobject.idle_add(thunkifyPeerUpdate(self.peers[peerKey], message))
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='')
def changePeers(self, data):
"""[DBUS METHOD] Locally change the cell's peers based on data."""
pdebug("%s received changePeers() call" % (self.uuid))
self.peerLock.acquire()
self.peers.update(dpropjson.loads(str(data)))
self.peersEtag = makeEtag(dpropjson.dumps(self.peers))
pdebug("New etag: %s" % (self.peersEtag))
self.peerLock.release()
# self.NewContentsSignal(str(data))
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='')
def changeCell(self, data):
"""[DBUS METHOD] Locally change the cell's contents to data."""
pdebug("%s received changeCell() call" % (self.uuid))
if self.data != str(data):
self.dataLock.acquire()
self.data = str(data)
self.etag = makeEtag(self.data)
self.dataLock.release()
self.NotifyPropagatorsSignal()
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='')
def updateCell(self, data):
"""[DBUS METHOD] Locally attempt to update the cell's contents with
data."""
pdebug("%s received updateCell() call" % (self.uuid))
self.doUpdate(str(data), self.referer, True)
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='', out_signature='s')
def data(self):
"""[DBUS METHOD] Return the cell's data."""
pdebug("%s received data() call" % (self.uuid))
return self.data
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='', out_signature='s')
def url(self):
"""[DBUS METHOD] Return the cell's url."""
return self.referer
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='b', out_signature='')
def setDPropDoesSyncing(self, dpropSync):
"""[DBUS METHOD] Set whether DPropMan should do syncing for this cell
(e.g. if you don't want to use SSL to make connections
yourself to hide your personal certificate)."""
self.dpropSync = dpropSync
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='', out_signature='b')
def dPropDoesSyncing(self):
"""[DBUS METHOD] Returns whether DPropMan is currently handling
syncing for this cell."""
return self.dpropSync
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='')
def setCert(self, cert):
"""[DBUS METHOD] Set the certificate (PEM format) associated with this
cell."""
self.peerLock.acquire()
self.cert = str(cert)
self.peers[self.referer]['cert'] = self.cert
self.peersEtag = makeEtag(dpropjson.dumps(self.peers))
pdebug("New peers etag: %s" % (self.peersEtag))
self.peerLock.release()
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='', out_signature='s')
def cert(self):
"""[DBUS METHOD] Returns the certificate (PEM format) associated with
this cell."""
return self.cert
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='b', out_signature='')
def setRequireCert(self, requireCert):
"""[DBUS METHOD] Set whether DPropMan should allow connections made
without a client certificate to this cell."""
self.requireCert = requireCert
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='', out_signature='b')
def requireCert(self):
"""[DBUS METHOD] Returns whether DPropMan allows connections made
without a client certificate to this cell."""
# TODO: Should remote "require cert" override this require
# cert???
return self.requireCert
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='s')
def certForPeer(self, peer):
"""[DBUS METHOD] Returns the certificate associated with a given
peer."""
peer = str(peer)
if peer not in peers or 'cert' not in peers[peer]:
return ''
else:
return peers[peer]['cert']
# @dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
# in_signature='s', out_signature='b')
# def checkForgeryKey(self, possibleKey):
# """[DBUS METHOD] Returns whether the given key matches the expected
# forgery key."""
# return str(possibleKey) == forgeryKey
@dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
in_signature='s', out_signature='')
def connectToRemote(self, url):
"""[DBUS METHOD] Connect to a remote URL and join it for
synchronization."""
pdebug("%s received connectToRemote() call" % (self.uuid))
def thunkifyAddToPeer(peer):
# Make the thunk to send the update.
def thunk():
pdebug("Attempting to add %s to peer %s" % (self.uuid,
peer['url']))
if not self.dpropSync:
# Send out the signal to add to a peer.
pdebug("Sending out signal for delegation...")
self.PeerAddSignal(self.referer, peer)
return False
try:
url = urlparse(peer['url'])
if url.scheme == 'http':
h = httplib.HTTPConnection(url.netloc)
elif url.scheme == 'https':
# TODO: Is it safe to keep these keys and
# certs around???
h = httplib.HTTPSConnection(url.netloc)
# key_file=self.key,
# cert_file=self.cert)
h.request('PUT', url.path + '/Peers',
urllib.urlencode(
{'peer': dpropjson.dumps({'url': self.referer,
'cert': self.cert})}),
{'Referer': self.referer,
'Content-Type':
'application/x-www-form-urlencoded'})
resp = h.getresponse()
if resp.status != httplib.OK:
# TODO: Handle errors
pdebug("Didn't get OK response!!")
else:
pdebug("PeerAdd was OK!!")
h.close()
except httplib.HTTPException, exc:
# TODO: Handle exceptions
pdebug("Caught HTTPException: %s: %s" % (type(exc).__name__,
str(exc)))
return False
return thunk
parsed_url = urlparse(url)
if parsed_url.scheme != 'http' and parsed_url.scheme != 'https':
# Balk at non-HTTP addresses.
pdebug("Uh oh! Didn't get an HTTP URL!")
raise InvalidURLException(
'The remote cell URL %s is not a valid HTTP URL.' % (url))
uuid = parsed_url.path.split('/')
if uuid[-1] == '':
uuid = self.escapePath(uuid[-2].replace('-', ''))
else:
uuid = self.escapePath(uuid[-1].replace('-', ''))
pdebug("Okay, the UUID must be %s" % (uuid))
if uuid != self.uuid:
# Raise an exception if the UUIDs don't match.
pdebug("But the UUID of this cell is %s!" % (self.uuid))
raise UUIDMismatchException(
'The UUID in the provided URL (%s) does not match the one ' +
'on record for this cell (%s)' % (uuid, self.uuid))
def initThunk():
if not self.dpropSync:
# Send out the signal to add to a peer.
pdebug("Sending out signal for delegation of initial data sync...")
self.DoInitSignal(self.referer, url)
pdebug("Setting up addToPeer thunks...")
for peerKey in self.peers:
if peerKey == self.referer:
continue
# We now use threading.
t = threading.Thread(target=thunkifyAddToPeer(self.peers[peerKey]))
t.start()
# gobject.idle_add(thunkifyAddToPeer(self.peers[peerKey]))
return
try:
parsed_url = urlparse(url)
if parsed_url.scheme == 'http':
h = httplib.HTTPConnection(parsed_url.netloc)
elif parsed_url.scheme == 'https':
# TODO: Is it safe to keep these keys and
# certs around???
h = httplib.HTTPSConnection(parsed_url.netloc)
# key_file=self.key,
# cert_file=self.cert)
pdebug("Performing initial data sync.")
h.request('GET', parsed_url.path,
headers={'Referer': self.referer})
resp = h.getresponse()
if resp.status != httplib.OK:
# TODO: Handle errors
pdebug("Didn't get OK response!!")
else:
# Send the response out for a local merge.
pdebug("Performing merge...")
self.doUpdate(resp.read(), url, False)
pdebug("Performing initial peers sync.")
h.request('GET', parsed_url.path + '/Peers',
headers={'Referer': self.referer})
resp = h.getresponse()
if resp.status != httplib.OK:
# TODO: Handle errors
pdebug("Didn't get OK response!!")
else:
pdebug("Merging peers...")
# Add the peer we connect to before the update.
# self.peers[str(url)] = {'cert': False, 'url': str(url)}
self.peerLock.acquire()
self.peers.update(dpropjson.loads(resp.read()))
self.peersEtag = makeEtag(dpropjson.dumps(self.peers))
pdebug("New etag: %s" % (self.peersEtag))
self.peerLock.release()
h.close()
pdebug("Setting up addToPeer thunks...")
for peerKey in self.peers:
if peerKey == self.referer:
continue
# We now use threading.
t = threading.Thread(target=thunkifyAddToPeer(self.peers[peerKey]))
t.start()
# gobject.idle_add(thunkifyAddToPeer(self.peers[peerKey]))
except httplib.HTTPException, exc:
# TODO: Handle exceptions
# e.g. BadStatusError, which might happen when crossing HTTPS and HTTP
pdebug("Caught HTTPException: %s: %s" % (type(exc).__name__,
str(exc)))
pass
# Run initThunk in a thread so as to not block HTTP connections
# due to the HTTP requests within.
t = threading.Thread(target=initThunk())
t.start()
# @dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
# in_signature='ass', out_signature='')
# def grantAccessTo(self, certs, accessType):
# """[DBUS METHOD] Grant remote access of type accessType to a cell to
# people bearing any of the provided certificates."""
# if accessType == 'r':
# # Read Access
# for cert in certs:
# self.readAccess.add(cert)
# elif accessType == 'w':
# # Read/Write Access
# for cert in certs:
# self.writeAccess.add(cert)
# for cert in certs:
# if cert in self.readAccess:
# self.readAccess.remove(cert)
# else:
# raise BadAccessTypeException(
# "Don't understand access type '%s'" % (accessType))
# @dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
# in_signature='', out_signature='s')
# def accessType(self):
# """[DBUS METHOD] Return the type of access granted (always 'w' for
# local cells)."""
# return 'w'
# def accessForCert(self, cert):
# """Return the type of access granted to the certificate provided."""
# cert = formatCertName(cert.get_subject())
# if cert in self.readAccess:
# return 'r'
# elif cert in self.writeAccess or cert == False:
# # TODO: Actually test for UseSSL.
# return 'w'
# else:
# return ''
# def destroyNeighbors(self):
# """Notify all peers that we no longer care about the cell."""
# for peer in self.peers:
# # Need to forward the destruction along to the remote cells.
# try:
# url = urlparse(self.peers[peer]['url'] + '/Peers/' +
# pathifyURL(self.referer))
# if url.scheme == 'http':
# h = httplib.HTTPConnection(url.netloc)
# elif url.scheme == 'https':
# h = httplib.HTTPSConnection(url.netloc,
# key_file=self.key,
# cert_file=self.cert)
# h.request('DELETE', url.path,
# header={'Referer': self.referer})
# resp = h.getresponse()
# if resp.status != httplib.ACCEPTED:
# # TODO: Handle errors
# pass
# h.close()
# except httplib.HTTPException:
# # TODO: Handle exceptions
# pass
# @dbus.service.method('edu.mit.csail.dig.DPropMan.Cell',
# in_signature='', out_signature='b')
# def exists(self):
# """[DBUS METHOD] A hack to test for a claim on a cell."""
# return True
# def destroy(self):
# """Destroy the cell."""
# self.DestroySignal()
# self.destroyNeighbors()
# self.remove_from_connection()
ObjectPathRegexp = re.compile('[A-Za-z0-9/]')
class DPropMan(dbus.service.Object):
"""The DProp manager. Contains functions accessible by DBus."""
def __init__(self, conn, object_path, port, hostname,
useSSL=False, cert=None, key=None):
"""Initializes the DPropMan object."""
pdebug("Initializing DPropMan object")
dbus.service.Object.__init__(self, conn, object_path)
self.cells = {}
self.conn = conn
self.port = port
self.hostname = hostname
self.useSSL = useSSL
self.cert = cert
self.key = key
@dbus.service.method('edu.mit.csail.dig.DPropMan',
in_signature='s', out_signature='s')
def escapePath(self, cellPath):
"""[DBUS METHOD] Escape a cell path."""
canonical = ''
for char in cellPath:
if ObjectPathRegexp.match(char):
canonical += char
else:
canonical += "_%02X" % (ord(char))
return canonical
@dbus.service.method('edu.mit.csail.dig.DPropMan',
in_signature='', out_signature='b')
def useSSL(self):
"""[DBUS METHOD] Returns True if this DPropMan daemon is using SSL."""