Commit 0559e618 authored by Mark Peek's avatar Mark Peek

More pep8

parent 0f1bbe6a
...@@ -15,13 +15,15 @@ class simple_test (ber_test_case): ...@@ -15,13 +15,15 @@ class simple_test (ber_test_case):
def runTest (self): def runTest (self):
x = SEQUENCE ( x = SEQUENCE (
SET (INTEGER(34), INTEGER(19), OCTET_STRING('fishing line')), SET (INTEGER(34), INTEGER(19), OCTET_STRING('fishing line')),
OBJID ([2,3,4,5,6,88]), OBJID ([2, 3, 4, 5, 6, 88]),
OCTET_STRING ("spaghetti"), OCTET_STRING ("spaghetti"),
BOOLEAN(True), BOOLEAN(True),
BOOLEAN(False), BOOLEAN(False),
) )
self.assertEqual (x, '0.1\x14\x02\x01"\x02\x01\x13\x04\x0cfishing line\x06\x05S\x04\x05\x06X\x04\tspaghetti\x01\x01\xff\x01\x01\x00') self.assertEqual (
self.assertEqual (decode (x), ([[34, 19, 'fishing line'], ('oid', [2, 3, 4, 5, 6, 88]), 'spaghetti', True, False], 48)) x, '0.1\x14\x02\x01"\x02\x01\x13\x04\x0cfishing line\x06\x05S\x04\x05\x06X\x04\tspaghetti\x01\x01\xff\x01\x01\x00') # noqa
self.assertEqual (
decode (x), ([[34, 19, 'fishing line'], ('oid', [2, 3, 4, 5, 6, 88]), 'spaghetti', True, False], 48))
# www.google.com cert # www.google.com cert
google_cert = """-----BEGIN CERTIFICATE----- google_cert = """-----BEGIN CERTIFICATE-----
...@@ -58,62 +60,62 @@ class x509_test (ber_test_case): ...@@ -58,62 +60,62 @@ class x509_test (ber_test_case):
[[[('oid', [2, 5, 4, 6]), ('PRINTABLE_STRING', 19, 'ZA')]], [[[('oid', [2, 5, 4, 6]), ('PRINTABLE_STRING', 19, 'ZA')]],
[[('oid', [2, 5, 4, 10]), [[('oid', [2, 5, 4, 10]),
('PRINTABLE_STRING', 19, 'Thawte Consulting (Pty) Ltd.')]], ('PRINTABLE_STRING', 19, 'Thawte Consulting (Pty) Ltd.')]],
[[('oid', [2, 5, 4, 3]), ('PRINTABLE_STRING', 19, 'Thawte SGC CA')]]], [[('oid', [2, 5, 4, 3]), ('PRINTABLE_STRING', 19, 'Thawte SGC CA')]]],
[('UTC_TIME', 23, '111026000000Z'), ('UTC_TIME', 23, '130930235959Z')], [('UTC_TIME', 23, '111026000000Z'), ('UTC_TIME', 23, '130930235959Z')],
[[[('oid', [2, 5, 4, 6]), ('PRINTABLE_STRING', 19, 'US')]], [[[('oid', [2, 5, 4, 6]), ('PRINTABLE_STRING', 19, 'US')]],
[[('oid', [2, 5, 4, 8]), ('PRINTABLE_STRING', 19, 'California')]], [[('oid', [2, 5, 4, 8]), ('PRINTABLE_STRING', 19, 'California')]],
[[('oid', [2, 5, 4, 7]), ('T61_STRING', 20, 'Mountain View')]], [[('oid', [2, 5, 4, 7]), ('T61_STRING', 20, 'Mountain View')]],
[[('oid', [2, 5, 4, 10]), ('T61_STRING', 20, 'Google Inc')]], [[('oid', [2, 5, 4, 10]), ('T61_STRING', 20, 'Google Inc')]],
[[('oid', [2, 5, 4, 3]), ('T61_STRING', 20, 'www.google.com')]]], [[('oid', [2, 5, 4, 3]), ('T61_STRING', 20, 'www.google.com')]]],
[[('oid', [1, 2, 840, 113549, 1, 1, 1]), None], [[('oid', [1, 2, 840, 113549, 1, 1, 1]), None],
('bitstring', ('bitstring',
(0, (0,
"0\x81\x89\x02\x81\x81\x00\xde\xb7&C\xa6\x99\x85\xcd8\xa7\x15\t\xb9\xcf\x0f" "0\x81\x89\x02\x81\x81\x00\xde\xb7&C\xa6\x99\x85\xcd8\xa7\x15\t\xb9\xcf\x0f"
"\xc9\xc3U\x8c\x88\xee\x8c\x8d('$K*^\xa0\xd8\x16\xfaa\x18K\xcfm`\x80\xd35@2r" "\xc9\xc3U\x8c\x88\xee\x8c\x8d('$K*^\xa0\xd8\x16\xfaa\x18K\xcfm`\x80\xd35@2r"
"\xc0\x8f\x12\xd8\xe5N\x8f\xb9\xb2\xf6\xd9\x15^Z\x861\xa3\xba\x86\xaak\xc8\xd9" "\xc0\x8f\x12\xd8\xe5N\x8f\xb9\xb2\xf6\xd9\x15^Z\x861\xa3\xba\x86\xaak\xc8\xd9"
"q\x8c\xcc\xcd'\x13\x1e\x9dB]8\xf6\xa7\xac\xef\xfab\xf3\x18\x81\xd4$F\x7f\x01w|" "q\x8c\xcc\xcd'\x13\x1e\x9dB]8\xf6\xa7\xac\xef\xfab\xf3\x18\x81\xd4$F\x7f\x01w|"
"\xc6*\x89\x14\x99\xbb\x989\x1d\xa8\x19\xfb9\x00D}\x1b\x94jx-i\xad\xc0z,\xfa\xd0" "\xc6*\x89\x14\x99\xbb\x989\x1d\xa8\x19\xfb9\x00D}\x1b\x94jx-i\xad\xc0z,\xfa\xd0"
"\xda \x12\x98\xd3\x02\x03\x01\x00\x01"))], "\xda \x12\x98\xd3\x02\x03\x01\x00\x01"))],
('context', ('context',
3, 3,
[[[('oid', [2, 5, 29, 19]), True, '0\x00'], [[[('oid', [2, 5, 29, 19]), True, '0\x00'],
[('oid', [2, 5, 29, 31]), [('oid', [2, 5, 29, 31]),
"0-0+\xa0)\xa0'\x86%http://crl.thawte.com/ThawteSGCCA.crl"], "0-0+\xa0)\xa0'\x86%http://crl.thawte.com/ThawteSGCCA.crl"],
[('oid', [2, 5, 29, 37]), [('oid', [2, 5, 29, 37]),
'0\x1f\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03' '0\x1f\x06\x08+\x06\x01\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03'
'\x02\x06\t`\x86H\x01\x86\xf8B\x04\x01'], '\x02\x06\t`\x86H\x01\x86\xf8B\x04\x01'],
[('oid', [1, 3, 6, 1, 5, 5, 7, 1, 1]), [('oid', [1, 3, 6, 1, 5, 5, 7, 1, 1]),
'0d0"\x06\x08+\x06\x01\x05\x05\x070\x01\x86\x16http://ocsp.thawte.com0>\x06' '0d0"\x06\x08+\x06\x01\x05\x05\x070\x01\x86\x16http://ocsp.thawte.com0>\x06'
'\x08+\x06\x01\x05\x05\x070\x02\x862http://www.thawte.com/repository/Thawte_SGC_CA.crt']]])], '\x08+\x06\x01\x05\x05\x070\x02\x862http://www.thawte.com/repository/Thawte_SGC_CA.crt']]])],
[('oid', [1, 2, 840, 113549, 1, 1, 5]), None], [('oid', [1, 2, 840, 113549, 1, 1, 5]), None],
('bitstring', ('bitstring',
(0, (0,
"!\xac\xd5\xae\xca4\x89Z\xc2\xabR\xd2\xb24f\x9dz\xab\xee\xe6|\xd5~\xc2\\(" "!\xac\xd5\xae\xca4\x89Z\xc2\xabR\xd2\xb24f\x9dz\xab\xee\xe6|\xd5~\xc2\\("
"\xbbt\x00\xc9\x10\x1fB\x13\xfci\x8a\x1e$\xa0\x02\x00\xe9\xba[\xca\x19\x04" "\xbbt\x00\xc9\x10\x1fB\x13\xfci\x8a\x1e$\xa0\x02\x00\xe9\xba[\xca\x19\x04"
"\xb2\xd3\xaf\x01\xb2~_\x14\xdb\xa6\xdbR\xb9\x9a\xf3\x12\x7f|\xa2\x9c;o\x99" "\xb2\xd3\xaf\x01\xb2~_\x14\xdb\xa6\xdbR\xb9\x9a\xf3\x12\x7f|\xa2\x9c;o\x99"
"}\xeaP\rv#\x12\xff\xf7fs)\xb7\x95\n\xad\xd8\x8b\xb2\xde \xe9\npd\x11\x08" "}\xeaP\rv#\x12\xff\xf7fs)\xb7\x95\n\xad\xd8\x8b\xb2\xde \xe9\npd\x11\x08"
"\xc8Z\xf1}\x9e\xeci\xa5\xa5\xd5\x82\xd7'\x1e\x9eV\xcd\xd2v\xd5y+\xf7%C\x1c" "\xc8Z\xf1}\x9e\xeci\xa5\xa5\xd5\x82\xd7'\x1e\x9eV\xcd\xd2v\xd5y+\xf7%C\x1c"
"i\xf0\xb8\xf9"))], "i\xf0\xb8\xf9"))],
805) 805)
) )
dec, length = decode (enc) dec, length = decode (enc)
public_key = dec[0][6][1][1][1] public_key = dec[0][6][1][1][1]
self.assertEqual ( self.assertEqual (
decode (public_key), decode (public_key),
([156396091895984667473837837332877995558144703880815901117439532534031286131520903863087599986938779606924811933611903716377206837300122262900786662124968110191717844999183338594373129421417536020806373385428322642107305024162536996222164292639147591878860587271770855626780464602884552232097424473091745159379L, 65537], 140) ([156396091895984667473837837332877995558144703880815901117439532534031286131520903863087599986938779606924811933611903716377206837300122262900786662124968110191717844999183338594373129421417536020806373385428322642107305024162536996222164292639147591878860587271770855626780464602884552232097424473091745159379L, 65537], 140) # noqa
) )
class bignum_test (ber_test_case): class bignum_test (ber_test_case):
def runTest (self): def runTest (self):
self.assertEquals ( self.assertEquals (
decode ('\x02\x82\x04\xe3\x01' + '\x00' * 1250), decode ('\x02\x82\x04\xe3\x01' + '\x00' * 1250),
(1<<10000, 1255) (1 << 10000, 1255)
) )
self.assertEquals ( self.assertEquals (
INTEGER (1<<10000), INTEGER (1 << 10000),
'\x02\x82\x04\xe3\x01' + '\x00' * 1250, '\x02\x82\x04\xe3\x01' + '\x00' * 1250,
) )
class bignum_test_2 (ber_test_case): class bignum_test_2 (ber_test_case):
...@@ -123,7 +125,7 @@ class bignum_test_2 (ber_test_case): ...@@ -123,7 +125,7 @@ class bignum_test_2 (ber_test_case):
self.assertEquals ( self.assertEquals (
decode (INTEGER (n))[0], decode (INTEGER (n))[0],
n n
) )
class bignum_test_3 (ber_test_case): class bignum_test_3 (ber_test_case):
...@@ -133,7 +135,7 @@ class bignum_test_3 (ber_test_case): ...@@ -133,7 +135,7 @@ class bignum_test_3 (ber_test_case):
for x in range (10000): for x in range (10000):
n = n * 10 + random.randint (0, 10) n = n * 10 + random.randint (0, 10)
print n print n
self.assertEquals (decode (INTEGER (n))[0], n) self.assertEquals (decode (INTEGER (n))[0], n)
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
......
...@@ -20,4 +20,3 @@ print go (1e300) ...@@ -20,4 +20,3 @@ print go (1e300)
print go (-1e300) print go (-1e300)
print go (1e-5) print go (1e-5)
print go (-1e-5) print go (-1e-5)
This diff is collapsed.
...@@ -18,8 +18,8 @@ class writer: ...@@ -18,8 +18,8 @@ class writer:
self.size = 0 self.size = 0
self.chunk_size = chunk_size self.chunk_size = chunk_size
self.append ('PGCOPY\n\xff\r\n\x00') self.append ('PGCOPY\n\xff\r\n\x00')
self.append (struct.pack ('>L', 0)) # flags self.append (struct.pack ('>L', 0)) # flags
self.append (struct.pack ('>L', 0)) # ext len self.append (struct.pack ('>L', 0)) # ext len
self.count = 0 self.count = 0
def append (self, data): def append (self, data):
...@@ -45,7 +45,7 @@ class writer: ...@@ -45,7 +45,7 @@ class writer:
row_data.append (data) row_data.append (data)
self.count += 1 self.count += 1
self.append (''.join (row_data,)) self.append (''.join (row_data,))
def done (self): def done (self):
self.append (struct.pack ('>h', -1)) self.append (struct.pack ('>h', -1))
self.flush() self.flush()
...@@ -61,7 +61,7 @@ def t0(): ...@@ -61,7 +61,7 @@ def t0():
db.query ('copy squares from stdin binary;') db.query ('copy squares from stdin binary;')
w = writer (('i', 'i'), db.putline) w = writer (('i', 'i'), db.putline)
for i in range (1000): for i in range (1000):
w.write_row ([i, i*i]) w.write_row ([i, i * i])
w.done() w.done()
db.endcopy() db.endcopy()
......
This diff is collapsed.
...@@ -39,20 +39,22 @@ class DNS_Soft_Error (DNS_Error): ...@@ -39,20 +39,22 @@ class DNS_Soft_Error (DNS_Error):
"""DNS_Soft_Error(qname, qtype, ip, error_string)""" """DNS_Soft_Error(qname, qtype, ip, error_string)"""
DNS_Error.__init__ (*args) DNS_Error.__init__ (*args)
self, self.qname, self.qtype, self.nameserver, self.error_string = args self, self.qname, self.qtype, self.nameserver, self.error_string = args
def __str__(self): def __str__(self):
return 'DNS Soft Error looking up %s (%s) while asking %s. Error was: %s' % ( return 'DNS Soft Error looking up %s (%s) while asking %s. Error was: %s' % (
self.qname, self.qtype, self.nameserver, self.error_string self.qname, self.qtype, self.nameserver, self.error_string
) )
class DNS_Hard_Error (DNS_Error): class DNS_Hard_Error (DNS_Error):
def __init__(*args): def __init__(*args):
"""DNS_Hard_Error(qname, qtype, (dnsrcode, error_string))""" """DNS_Hard_Error(qname, qtype, (dnsrcode, error_string))"""
DNS_Error.__init__ (*args) DNS_Error.__init__ (*args)
self, self.qname, self.qtype, (self.dnsrcode, self.error_string) = args self, self.qname, self.qtype, (self.dnsrcode, self.error_string) = args
def __str__(self): def __str__(self):
return 'DNS Hard Error looking up %s (%s): %s' % ( return 'DNS Hard Error looking up %s (%s): %s' % (
self.qname, self.qtype, self.error_string self.qname, self.qtype, self.error_string
) )
class DNS_Many_Errors (DNS_Error): class DNS_Many_Errors (DNS_Error):
"""A container class for multiple DNS errors. """A container class for multiple DNS errors.
...@@ -65,6 +67,7 @@ class DNS_Many_Errors (DNS_Error): ...@@ -65,6 +67,7 @@ class DNS_Many_Errors (DNS_Error):
system (and mainly to log files) that there were two queries attempted and system (and mainly to log files) that there were two queries attempted and
they both failed. they both failed.
""" """
def __init__(self, exceptions): def __init__(self, exceptions):
"""Initialize ourselves. """Initialize ourselves.
...@@ -135,14 +138,15 @@ class DNS_Lame_Error (DNS_Soft_Error): ...@@ -135,14 +138,15 @@ class DNS_Lame_Error (DNS_Soft_Error):
self.ns_names = ', '.join(map(lambda x: x[1], ns_names)) self.ns_names = ', '.join(map(lambda x: x[1], ns_names))
DNS_Soft_Error.__init__ ( DNS_Soft_Error.__init__ (
self, qname, qtype, self.ns_names, 'Lame Delegation Error' self, qname, qtype, self.ns_names, 'Lame Delegation Error'
) )
def __str__(self): def __str__(self):
return ( return (
'DNS Lame Delegation Error looking up %s (%s).' 'DNS Lame Delegation Error looking up %s (%s).'
' Nameserver list was: %s.' % ( ' Nameserver list was: %s.' % (
self.qname, self.qtype, self.ns_names self.qname, self.qtype, self.ns_names
)
) )
)
class DNS_Runaway_Query_Error(DNS_Soft_Error): class DNS_Runaway_Query_Error(DNS_Soft_Error):
def __init__(self, qname, qtype, ns_name): def __init__(self, qname, qtype, ns_name):
...@@ -150,12 +154,13 @@ class DNS_Runaway_Query_Error(DNS_Soft_Error): ...@@ -150,12 +154,13 @@ class DNS_Runaway_Query_Error(DNS_Soft_Error):
self.ns_name = ns_name self.ns_name = ns_name
DNS_Soft_Error.__init__ ( DNS_Soft_Error.__init__ (
self, qname, qtype, ns_name, 'Runaway Error' self, qname, qtype, ns_name, 'Runaway Error'
) )
def __str__(self): def __str__(self):
return ( return (
'DNS Runaway Error looking up %s (%s).' 'DNS Runaway Error looking up %s (%s).'
' Nameserver was: %s.' % (self.qname, self.qtype, self.ns_name) ' Nameserver was: %s.' % (self.qname, self.qtype, self.ns_name)
) )
class DNS_Malformed_Qname_Error (DNS_Hard_Error): class DNS_Malformed_Qname_Error (DNS_Hard_Error):
def __str__(self): def __str__(self):
...@@ -164,11 +169,13 @@ class DNS_Malformed_Qname_Error (DNS_Hard_Error): ...@@ -164,11 +169,13 @@ class DNS_Malformed_Qname_Error (DNS_Hard_Error):
class DNS_Missing_Root_Data_Error (DNS_Soft_Error): class DNS_Missing_Root_Data_Error (DNS_Soft_Error):
def __init__(self): def __init__(self):
DNS_Soft_Error.__init__ (self, '', '', '', 'Missing Root Data Error') DNS_Soft_Error.__init__ (self, '', '', '', 'Missing Root Data Error')
def __str__(self): def __str__(self):
return 'Failed to get root nameserver.' return 'Failed to get root nameserver.'
class DNS_No_Local_Resolvers (DNS_Soft_Error): class DNS_No_Local_Resolvers (DNS_Soft_Error):
def __init__(self): def __init__(self):
DNS_Soft_Error.__init__ (self, '', '', '', 'No local DNS resolvers are running') DNS_Soft_Error.__init__ (self, '', '', '', 'No local DNS resolvers are running')
def __str__(self): def __str__(self):
return 'No local DNS resolvers are running.' return 'No local DNS resolvers are running.'
...@@ -32,6 +32,7 @@ class dns_reply: ...@@ -32,6 +32,7 @@ class dns_reply:
self.ar -> List of additional record tuples (typename, name, ttl, DATA) self.ar -> List of additional record tuples (typename, name, ttl, DATA)
DATA depends on the type of the RR entry. DATA depends on the type of the RR entry.
""" """
def __init__ (self): def __init__ (self):
self.rcode = 0 self.rcode = 0
self.q = [] self.q = []
...@@ -45,7 +46,7 @@ class dns_reply: ...@@ -45,7 +46,7 @@ class dns_reply:
def __repr__ (self): def __repr__ (self):
return '<dns_reply rcode=%d q:%s an:%s ns:%s ar:%s>' % ( return '<dns_reply rcode=%d q:%s an:%s ns:%s ar:%s>' % (
self.rcode, self.q, self.an, self.ns, self.ar self.rcode, self.q, self.an, self.ns, self.ar
) )
def get_rr (u, use_actual_ttl=0, ttl_min=1800): def get_rr (u, use_actual_ttl=0, ttl_min=1800):
...@@ -99,7 +100,7 @@ def unpack_reply (reply, use_actual_ttl=0, ttl_min=1800): ...@@ -99,7 +100,7 @@ def unpack_reply (reply, use_actual_ttl=0, ttl_min=1800):
else: else:
__pychecker__ = 'unusednames=x' __pychecker__ = 'unusednames=x'
r.q = [u.getQuestion() for x in range (h.qdcount)] r.q = [u.getQuestion() for x in range (h.qdcount)]
r.an = filter (None, [ get_rr (u, use_actual_ttl, ttl_min) for x in range (h.ancount) ]) r.an = filter (None, [get_rr (u, use_actual_ttl, ttl_min) for x in range (h.ancount)])
r.ns = filter (None, [ get_rr (u, use_actual_ttl, ttl_min) for x in range (h.nscount) ]) r.ns = filter (None, [get_rr (u, use_actual_ttl, ttl_min) for x in range (h.nscount)])
r.ar = filter (None, [ get_rr (u, use_actual_ttl, ttl_min) for x in range (h.arcount) ]) r.ar = filter (None, [get_rr (u, use_actual_ttl, ttl_min) for x in range (h.arcount)])
return r return r
...@@ -75,4 +75,4 @@ def install (nameserver_ips): ...@@ -75,4 +75,4 @@ def install (nameserver_ips):
"install a stub resolver into the coro socket layer" "install a stub resolver into the coro socket layer"
coro.set_resolver ( coro.set_resolver (
stub_resolver (nameserver_ips) stub_resolver (nameserver_ips)
) )
...@@ -19,7 +19,7 @@ def testpacker(): ...@@ -19,7 +19,7 @@ def testpacker():
'********************\x01f\x03ISI\x04ARPA\x00' '********************\x01f\x03ISI\x04ARPA\x00'
'********\x03Foo\xc0\x14******************\xc0\x1a' '********\x03Foo\xc0\x14******************\xc0\x1a'
'**************************\x00' '**************************\x00'
) )
u = dns.Unpacker (packet) u = dns.Unpacker (packet)
res = ( res = (
u.getbytes(20), u.getbytes(20),
...@@ -30,7 +30,7 @@ def testpacker(): ...@@ -30,7 +30,7 @@ def testpacker():
u.getname(), u.getname(),
u.getbytes(26), u.getbytes(26),
u.getname(), u.getname(),
) )
assert res == ( assert res == (
'********************', '********************',
'f.isi.arpa', 'f.isi.arpa',
...@@ -40,7 +40,7 @@ def testpacker(): ...@@ -40,7 +40,7 @@ def testpacker():
'arpa', 'arpa',
'**************************', '**************************',
'' ''
) )
def test_packer_2 (): def test_packer_2 ():
p = dns.Packer() p = dns.Packer()
...@@ -96,7 +96,7 @@ def t2(): ...@@ -96,7 +96,7 @@ def t2():
# XXX make this into a real unit test. # XXX make this into a real unit test.
if __name__ == '__main__': if __name__ == '__main__':
#import coro.backdoor # import coro.backdoor
#coro.spawn (coro.backdoor.serve, unix_path='/tmp/xx.bd') # coro.spawn (coro.backdoor.serve, unix_path='/tmp/xx.bd')
#coro.event_loop() # coro.event_loop()
test_packer_2() test_packer_2()
...@@ -233,7 +233,7 @@ class socket(object): ...@@ -233,7 +233,7 @@ class socket(object):
pass pass
else: else:
# non-blocking # non-blocking
#self.timeout = 0 # self.timeout = 0
raise AssertionError('Non-blocking mode not yet supported.') raise AssertionError('Non-blocking mode not yet supported.')
def settimeout(self, value): def settimeout(self, value):
...@@ -280,7 +280,7 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=N ...@@ -280,7 +280,7 @@ def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=N
if sock is not None: if sock is not None:
sock.close() sock.close()
raise error, msg raise error(msg)
def fromfd(fd, family, type, proto=0): def fromfd(fd, family, type, proto=0):
with _error_converter: with _error_converter:
......
...@@ -107,6 +107,7 @@ class Semaphore(object): ...@@ -107,6 +107,7 @@ class Semaphore(object):
self._sem.release(1) self._sem.release(1)
__enter__ = acquire __enter__ = acquire
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):
self.release() self.release()
......
...@@ -111,6 +111,7 @@ class client: ...@@ -111,6 +111,7 @@ class client:
self.conn.close() self.conn.close()
response_re = re.compile ('([^ ]+) ([0-9][0-9][0-9]) (.+)') response_re = re.compile ('([^ ]+) ([0-9][0-9][0-9]) (.+)')
def _read_message (self, req): def _read_message (self, req):
line = self.stream.read_line() line = self.stream.read_line()
if not line: if not line:
...@@ -155,7 +156,7 @@ class client: ...@@ -155,7 +156,7 @@ class client:
req = ( req = (
'%s %s HTTP/1.1\r\n' '%s %s HTTP/1.1\r\n'
'%s\r\n' % (method, uri, headers) '%s\r\n' % (method, uri, headers)
) )
self.conn.send (req) self.conn.send (req)
# XXX 100 continue # XXX 100 continue
if content: if content:
...@@ -202,5 +203,3 @@ class client: ...@@ -202,5 +203,3 @@ class client:
req = self.send_request ('POST', uri, headers, content, force=True) req = self.send_request ('POST', uri, headers, content, force=True)
req.wait() req.wait()
return req return req
...@@ -16,7 +16,7 @@ class grid_handler: ...@@ -16,7 +16,7 @@ class grid_handler:
self.w = w self.w = w
self.h = h self.h = h
self.grid = [['.' for x in range (w)] for y in range (h)] self.grid = [['.' for x in range (w)] for y in range (h)]
self.pos = [w/2, h/2] self.pos = [w / 2, h / 2]
self.grid[self.pos[1]][self.pos[0]] = 'X' self.grid[self.pos[1]][self.pos[0]] = 'X'
def match (self, request): def match (self, request):
...@@ -33,19 +33,19 @@ class grid_handler: ...@@ -33,19 +33,19 @@ class grid_handler:
request.set_deflate() request.set_deflate()
if request.file: if request.file:
data = request.file.read() data = request.file.read()
pairs = [ x.split('=') for x in data.split ('&') ] pairs = [x.split('=') for x in data.split ('&')]
for k, v in pairs: for k, v in pairs:
if k == 'dir': if k == 'dir':
x0, y0 = self.pos x0, y0 = self.pos
x1, y1 = self.pos x1, y1 = self.pos
if v == 'left': if v == 'left':
x1 = max (x0-1, 0) x1 = max (x0 - 1, 0)
elif v == 'right': elif v == 'right':
x1 = min (x0+1, self.w-1) x1 = min (x0 + 1, self.w - 1)
elif v == 'up': elif v == 'up':
y1 = max (y0-1, 0) y1 = max (y0 - 1, 0)
elif v == 'down': elif v == 'down':
y1 = min (y0+1, self.h-1) y1 = min (y0 + 1, self.h - 1)
else: else:
pass pass
self.grid[y0][x0] = '*' self.grid[y0][x0] = '*'
...@@ -67,7 +67,7 @@ class grid_handler: ...@@ -67,7 +67,7 @@ class grid_handler:
'<input type="submit" name="dir" value="down" />' '<input type="submit" name="dir" value="down" />'
'</form>' '</form>'
'<a href="/grid/source">source for this handler</a>' '<a href="/grid/source">source for this handler</a>'
) )
request.done() request.done()
server = coro.http.server() server = coro.http.server()
......
...@@ -3,8 +3,7 @@ from coro.http.json_rpc import json_rpc_remote as JR ...@@ -3,8 +3,7 @@ from coro.http.json_rpc import json_rpc_remote as JR
def go(): def go():
r = JR ('http://127.0.0.1:9001/jsonrpc') r = JR ('http://127.0.0.1:9001/jsonrpc')
print r.invoke ('sum', 1,2,3) print r.invoke ('sum', 1, 2, 3)
coro.spawn (go) coro.spawn (go)
coro.event_loop() coro.event_loop()
...@@ -8,9 +8,9 @@ import coro.backdoor ...@@ -8,9 +8,9 @@ import coro.backdoor
from coro.ssl import openssl from coro.ssl import openssl
ctx = coro.ssl.new_ctx ( ctx = coro.ssl.new_ctx (
cert = openssl.x509 (open('../cert/server.crt').read()), cert=openssl.x509 (open('../cert/server.crt').read()),
key = openssl.pkey (open('../cert/server.key').read(), private=True), key=openssl.pkey (open('../cert/server.key').read(), private=True),
) )
server = coro.http.openssl_server (ctx) server = coro.http.openssl_server (ctx)
server.push_handler (coro.http.handlers.coro_status_handler()) server.push_handler (coro.http.handlers.coro_status_handler())
......
...@@ -24,7 +24,7 @@ def session (sid, fifo): ...@@ -24,7 +24,7 @@ def session (sid, fifo):
'<html><h1>Session Over! Bye!</h1>' '<html><h1>Session Over! Bye!</h1>'
'<a href="session">start over</a>' '<a href="session">start over</a>'
'</html>' '</html>'
) )
request.done() request.done()
break break
else: else:
...@@ -32,7 +32,7 @@ def session (sid, fifo): ...@@ -32,7 +32,7 @@ def session (sid, fifo):
'<html><h1>Session Demo</h1><br><h2>Hit=%d</h2>' '<html><h1>Session Demo</h1><br><h2>Hit=%d</h2>'
'<a href="session">hit me!</a>' '<a href="session">hit me!</a>'
'</html>' % (i,) '</html>' % (i,)
) )
request.done() request.done()
i += 1 i += 1
......
...@@ -10,15 +10,15 @@ from coro.http.protocol import header_set ...@@ -10,15 +10,15 @@ from coro.http.protocol import header_set
W = coro.write_stderr W = coro.write_stderr
ctx = coro.ssl.new_ctx ( ctx = coro.ssl.new_ctx (
#cert=coro.ssl.x509 (open ('cert/server.crt').read()), # cert=coro.ssl.x509 (open ('cert/server.crt').read()),
#key=coro.ssl.pkey (open ('cert/server.key').read(), '', True), # key=coro.ssl.pkey (open ('cert/server.key').read(), '', True),
next_protos=['spdy/2', 'http/1.1'], next_protos=['spdy/2', 'http/1.1'],
proto='tlsv1', proto='tlsv1',
) )
def t0(): def t0():
global ctx, s, c global ctx, s, c
#ctx = coro.ssl.new_ctx (proto='tlsv1', next_protos=['spdy/2', 'http/1.1']) # ctx = coro.ssl.new_ctx (proto='tlsv1', next_protos=['spdy/2', 'http/1.1'])
s = coro.ssl.sock (ctx) s = coro.ssl.sock (ctx)
c = spdy_client ('127.0.0.1', 9443, s) c = spdy_client ('127.0.0.1', 9443, s)
W ('negotiated: %r\n' % (s.ssl.get_next_protos_negotiated(),)) W ('negotiated: %r\n' % (s.ssl.get_next_protos_negotiated(),))
......
...@@ -8,7 +8,7 @@ ctx = coro.ssl.new_ctx ( ...@@ -8,7 +8,7 @@ ctx = coro.ssl.new_ctx (
key=coro.ssl.pkey (open ('cert/server.key').read(), '', True), key=coro.ssl.pkey (open ('cert/server.key').read(), '', True),
next_protos=['spdy/3', 'http/1.1'], next_protos=['spdy/3', 'http/1.1'],
proto='tlsv1', proto='tlsv1',
) )
server = coro.http.spdy.spdy_openssl_server (ctx) server = coro.http.spdy.spdy_openssl_server (ctx)
server.push_handler (coro.http.handlers.favicon_handler()) server.push_handler (coro.http.handlers.favicon_handler())
......
...@@ -9,7 +9,7 @@ from coro.http.protocol import header_set ...@@ -9,7 +9,7 @@ from coro.http.protocol import header_set
def t0(): def t0():
c = http_client ('127.0.0.1', 80) c = http_client ('127.0.0.1', 80)
h = header_set() h = header_set()
l = [ c.send_request ('GET', '/postgresql/html/', h, content=None, force=True) for x in range (10) ] l = [c.send_request ('GET', '/postgresql/html/', h, content=None, force=True) for x in range (10)]
for req in l: for req in l:
req.wait() req.wait()
W ('%s\n' % (req.response,)) W ('%s\n' % (req.response,))
...@@ -26,4 +26,3 @@ if __name__ == '__main__': ...@@ -26,4 +26,3 @@ if __name__ == '__main__':
coro.spawn (t0) coro.spawn (t0)
coro.spawn (coro.backdoor.serve, unix_path='/tmp/xx.bd') coro.spawn (coro.backdoor.serve, unix_path='/tmp/xx.bd')
coro.event_loop() coro.event_loop()
...@@ -12,7 +12,7 @@ import coro.backdoor ...@@ -12,7 +12,7 @@ import coro.backdoor
server = coro.http.tlslite_server ( server = coro.http.tlslite_server (
'cert/server.crt', 'cert/server.crt',
'cert/server.key', 'cert/server.key',
) )
server.push_handler (coro.http.handlers.coro_status_handler()) server.push_handler (coro.http.handlers.coro_status_handler())
server.push_handler (coro.http.handlers.favicon_handler()) server.push_handler (coro.http.handlers.favicon_handler())
coro.spawn (server.start, ('0.0.0.0', 9443)) coro.spawn (server.start, ('0.0.0.0', 9443))
......
...@@ -45,7 +45,7 @@ class connection (websocket): ...@@ -45,7 +45,7 @@ class connection (websocket):
payload = p.unpack() payload = p.unpack()
if p.opcode == 0x01: if p.opcode == 0x01:
if self.name is None: if self.name is None:
reply = json.dumps ({'type':'color', 'data':self.color}) reply = json.dumps ({'type': 'color', 'data': self.color})
self.send_text (reply) self.send_text (reply)
self.name = payload self.name = payload
else: else:
...@@ -53,18 +53,18 @@ class connection (websocket): ...@@ -53,18 +53,18 @@ class connection (websocket):
return False return False
def send_message (self, name, color, message): def send_message (self, name, color, message):
#W ('send_message %r %r %r\n' % (name, color, message)) # W ('send_message %r %r %r\n' % (name, color, message))
self.send_text ( self.send_text (
json.dumps ({ json.dumps ({
'type':'message', 'type': 'message',
'data': { 'data': {
'time' : int (coro.now_usec / 1000000), 'time': int (coro.now_usec / 1000000),
'text' : message, 'text': message,
'author' : name, 'author': name,
'color' : color 'color': color
} }
}) })
) )
if __name__ == '__main__': if __name__ == '__main__':
import coro.http import coro.http
...@@ -79,7 +79,7 @@ if __name__ == '__main__': ...@@ -79,7 +79,7 @@ if __name__ == '__main__':
fh = coro.http.handlers.file_handler (cwd) fh = coro.http.handlers.file_handler (cwd)
wh = handler ('/chat', chat_server.new_session) wh = handler ('/chat', chat_server.new_session)
handlers = [ih, sh, fh, wh] handlers = [ih, sh, fh, wh]
#http_server = coro.http.server (('0.0.0.0', 9001)) # http_server = coro.http.server (('0.0.0.0', 9001))
http_server = coro.http.server () http_server = coro.http.server ()
for h in handlers: for h in handlers:
http_server.push_handler (h) http_server.push_handler (h)
......
...@@ -12,7 +12,7 @@ class echo_server (websocket): ...@@ -12,7 +12,7 @@ class echo_server (websocket):
websocket.__init__ (self, *args, **kwargs) websocket.__init__ (self, *args, **kwargs)
def handle_packet (self, p): def handle_packet (self, p):
#W ('packet=%r\n' % (p,)) # W ('packet=%r\n' % (p,))
self.pending.append (p.unpack()) self.pending.append (p.unpack())
if p.fin: if p.fin:
data, self.pending = self.pending, [] data, self.pending = self.pending, []
...@@ -26,11 +26,11 @@ if __name__ == '__main__': ...@@ -26,11 +26,11 @@ if __name__ == '__main__':
sh = coro.http.handlers.coro_status_handler() sh = coro.http.handlers.coro_status_handler()
wh = handler ('/echo', echo_server) wh = handler ('/echo', echo_server)
handlers = [fh, sh, wh] handlers = [fh, sh, wh]
#server = coro.http.server (('0.0.0.0', 9001)) # server = coro.http.server (('0.0.0.0', 9001))
server = coro.http.server () server = coro.http.server ()
for h in handlers: for h in handlers:
server.push_handler (h) server.push_handler (h)
#coro.spawn (server.start) # coro.spawn (server.start)
coro.spawn (server.start, ('0.0.0.0', 9001)) coro.spawn (server.start, ('0.0.0.0', 9001))
coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd') coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd')
coro.event_loop (30.0) coro.event_loop (30.0)
...@@ -26,18 +26,21 @@ colors = ['red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange'] ...@@ -26,18 +26,21 @@ colors = ['red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange']
# sample 'box' object. # sample 'box' object.
class box (quadtree.ob): class box (quadtree.ob):
def __init__ (self, color, (l,t,r,b)): def __init__ (self, color, (l, t, r, b)):
self.color = color self.color = color
self.set_rect (l,t,r,b) self.set_rect (l, t, r, b)
def move (self, dx, dy): def move (self, dx, dy):
x0, y0, x1, y1 = self.get_rect() x0, y0, x1, y1 = self.get_rect()
self.set_rect ( self.set_rect (
int(x0 + dx), int(y0 + dy), int(x1 + dx), int(y0 + dy) int(x0 + dx), int(y0 + dy), int(x1 + dx), int(y0 + dy)
) )
def cmd (self, xoff, yoff): def cmd (self, xoff, yoff):
# command to draw me relative to <xoff,yoff>? # command to draw me relative to <xoff,yoff>?
x0, y0, x1, y1 = self.get_rect() x0, y0, x1, y1 = self.get_rect()
return 'B,%s,%d,%d,%d,%d' % (self.color, x0-xoff, y0-yoff, x1-x0, y1-y0) return 'B,%s,%d,%d,%d,%d' % (self.color, x0 - xoff, y0 - yoff, x1 - x0, y1 - y0)
def __repr__ (self): def __repr__ (self):
return '<box (%d,%d,%d,%d)>' % self.get_rect() return '<box (%d,%d,%d,%d)>' % self.get_rect()
...@@ -49,18 +52,22 @@ class circle (box): ...@@ -49,18 +52,22 @@ class circle (box):
self.center = center self.center = center
self.radius = radius self.radius = radius
self.set_rect (*self.get_rect()) self.set_rect (*self.get_rect())
def get_rect (self): def get_rect (self):
x, y = self.center x, y = self.center
r = self.radius r = self.radius
return x-r, y-r, x+r, y+r return x - r, y - r, x + r, y + r
def move (self, dx, dy): def move (self, dx, dy):
x, y = self.center x, y = self.center
self.center = int(x + dx), int(y + dy) self.center = int(x + dx), int(y + dy)
self.set_rect (*self.get_rect()) self.set_rect (*self.get_rect())
def cmd (self, xoff, yoff): def cmd (self, xoff, yoff):
# command to draw me relative to <xoff,yoff>? # command to draw me relative to <xoff,yoff>?
x, y = self.center x, y = self.center
return 'C,%s,%d,%d,%d' % (self.color, x-xoff, y-yoff, self.radius) return 'C,%s,%d,%d,%d' % (self.color, x - xoff, y - yoff, self.radius)
def __repr__ (self): def __repr__ (self):
return '<circle (%d,%d) radius=%d)>' % (self.center[0], self.center[1], self.radius) return '<circle (%d,%d) radius=%d)>' % (self.center[0], self.center[1], self.radius)
...@@ -70,7 +77,7 @@ class circle (box): ...@@ -70,7 +77,7 @@ class circle (box):
# 3) for moving objects # 3) for moving objects
class field: class field:
def __init__ (self, w=1024*20, h=1024*20): def __init__ (self, w=1024 * 20, h=1024 * 20):
self.w = w self.w = w
self.h = h self.h = h
self.Q_views = quadtree.quadtree() self.Q_views = quadtree.quadtree()
...@@ -85,7 +92,7 @@ class field: ...@@ -85,7 +92,7 @@ class field:
y = random.randint (0, self.h - 100) y = random.randint (0, self.h - 100)
w = random.randint (50, 300) w = random.randint (50, 300)
h = random.randint (50, 300) h = random.randint (50, 300)
b = box (c, (x, y, x+w, y+h)) b = box (c, (x, y, x + w, y + h))
self.Q_back.insert (b) self.Q_back.insert (b)
for i in range (1000): for i in range (1000):
coro.spawn (self.wanderer) coro.spawn (self.wanderer)
...@@ -96,8 +103,8 @@ class field: ...@@ -96,8 +103,8 @@ class field:
def new_ob (self, ob): def new_ob (self, ob):
self.Q_obs.insert (ob) self.Q_obs.insert (ob)
#W ('new ob %r\n' % (self.Q_obs,)) # W ('new ob %r\n' % (self.Q_obs,))
#self.Q_obs.dump() # self.Q_obs.dump()
def move_ob (self, ob, dx, dy): def move_ob (self, ob, dx, dy):
r0 = ob.get_rect() r0 = ob.get_rect()
...@@ -105,13 +112,14 @@ class field: ...@@ -105,13 +112,14 @@ class field:
ob.move (dx, dy) ob.move (dx, dy)
r1 = ob.get_rect() r1 = ob.get_rect()
self.Q_obs.insert (ob) self.Q_obs.insert (ob)
#self.Q_obs.dump() # self.Q_obs.dump()
# notify any viewers # notify any viewers
r2 = region.union (r0, r1) r2 = region.union (r0, r1)
for client in self.Q_views.search (r2): for client in self.Q_views.search (r2):
client.draw_window() client.draw_window()
sleep = 0.1 sleep = 0.1
def wanderer (self): def wanderer (self):
# spawn me! # spawn me!
x = random.randint (100, self.w - 100) x = random.randint (100, self.w - 100)
...@@ -129,11 +137,11 @@ class field: ...@@ -129,11 +137,11 @@ class field:
for i in range (20): for i in range (20):
self.move_ob (ob, dx, dy) self.move_ob (ob, dx, dy)
# not working yet... # not working yet...
## if not ob.range_check (0, 0, self.w, self.h): # if not ob.range_check (0, 0, self.w, self.h):
## W ('%r hit an edge!\n' % (ob,)) # W ('%r hit an edge!\n' % (ob,))
## dx = - (dx * 5) # dx = - (dx * 5)
## dy = - (dy * 5) # dy = - (dy * 5)
## self.move_ob (ob, dx, dy) # self.move_ob (ob, dx, dy)
coro.sleep_relative (self.sleep) coro.sleep_relative (self.sleep)
class field_conn (websocket, quadtree.ob): class field_conn (websocket, quadtree.ob):
...@@ -142,25 +150,31 @@ class field_conn (websocket, quadtree.ob): ...@@ -142,25 +150,31 @@ class field_conn (websocket, quadtree.ob):
websocket.__init__ (self, *args, **kwargs) websocket.__init__ (self, *args, **kwargs)
self.send_mutex = coro.mutex() self.send_mutex = coro.mutex()
self.field = field self.field = field
rx = random.randint (0, self.field.w-1024) rx = random.randint (0, self.field.w - 1024)
ry = random.randint (0, self.field.h-1024) ry = random.randint (0, self.field.h - 1024)
self.set_rect (rx, ry, rx+1024, ry+1024) self.set_rect (rx, ry, rx + 1024, ry + 1024)
self.draw_window() self.draw_window()
self.mouse_down = None, None self.mouse_down = None, None
def move_window (self, mx, my): def move_window (self, mx, my):
self.field.Q_views.delete (self) self.field.Q_views.delete (self)
x0, y0, x1, y1 = self.get_rect() x0, y0, x1, y1 = self.get_rect()
x0 = x0 + mx; y0 = y0 + my x0 = x0 + mx
x1 = x1 + mx; y1 = y1 + my y0 = y0 + my
x1 = x1 + mx
y1 = y1 + my
if x0 < 0: if x0 < 0:
x0 = 0; x1 = 1024 x0 = 0
x1 = 1024
if y0 < 0: if y0 < 0:
y0 = 0; y1 = 1024 y0 = 0
if x1 > self.field.w-1024: y1 = 1024
x1 = self.field.w-1024; x0 = x1 - 1024 if x1 > self.field.w - 1024:
if y1 > self.field.h-1024: x1 = self.field.w - 1024
y1 = self.field.h-1024; y0 = y1 - 1024 x0 = x1 - 1024
if y1 > self.field.h - 1024:
y1 = self.field.h - 1024
y0 = y1 - 1024
self.set_rect (x0, y0, x1, y1) self.set_rect (x0, y0, x1, y1)
self.field.Q_views.insert (self) self.field.Q_views.insert (self)
self.draw_window() self.draw_window()
...@@ -187,18 +201,18 @@ class field_conn (websocket, quadtree.ob): ...@@ -187,18 +201,18 @@ class field_conn (websocket, quadtree.ob):
def handle_packet (self, p): def handle_packet (self, p):
data = p.unpack() data = p.unpack()
event = p.unpack().split (',') event = p.unpack().split (',')
#W ('packet = %r event=%r\n' % (p, event)) # W ('packet = %r event=%r\n' % (p, event))
if event[0] == 'KD': if event[0] == 'KD':
ascii = int (event[1]) ascii = int (event[1])
if ascii == 87: # W if ascii == 87: # W
self.move_window (0, -10) self.move_window (0, -10)
elif ascii == 65: # A elif ascii == 65: # A
self.move_window (-10, 0) self.move_window (-10, 0)
elif ascii == 83: # S elif ascii == 83: # S
self.move_window (0, 10) self.move_window (0, 10)
elif ascii == 68: # D elif ascii == 68: # D
self.move_window (10, 0) self.move_window (10, 0)
elif ascii == 82: # R elif ascii == 82: # R
x0, y0 = self.get_rect()[:2] x0, y0 = self.get_rect()[:2]
self.move_window (-x0, -y0) self.move_window (-x0, -y0)
elif event[0] == 'MD': elif event[0] == 'MD':
...@@ -226,25 +240,25 @@ class field_conn (websocket, quadtree.ob): ...@@ -226,25 +240,25 @@ class field_conn (websocket, quadtree.ob):
return False return False
def unpack_touch_list (self, tl): def unpack_touch_list (self, tl):
return [ [int(y) for y in x.split('.')] for x in tl ] return [[int(y) for y in x.split('.')] for x in tl]
def on_mouse_down (self, x, y): def on_mouse_down (self, x, y):
self.mouse_down = x, y self.mouse_down = x, y
def on_mouse_up (self, x1, y1): def on_mouse_up (self, x1, y1):
x0, y0 = self.mouse_down x0, y0 = self.mouse_down
self.mouse_down = None, None self.mouse_down = None, None
if x0 is not None: if x0 is not None:
self.move_window (x0-x1, y0-y1) self.move_window (x0 - x1, y0 - y1)
self.draw_window() self.draw_window()
def on_mouse_move (self, x1, y1): def on_mouse_move (self, x1, y1):
x0, y0 = self.mouse_down x0, y0 = self.mouse_down
if x0: if x0:
if abs(x1-x0) > 10 or abs(y1-y0) > 10: if abs(x1 - x0) > 10 or abs(y1 - y0) > 10:
# moved enough to redraw # moved enough to redraw
self.mouse_down = x1, y1 self.mouse_down = x1, y1
self.move_window (x0-x1, y0-y1) self.move_window (x0 - x1, y0 - y1)
if __name__ == '__main__': if __name__ == '__main__':
import coro.http import coro.http
...@@ -261,11 +275,11 @@ if __name__ == '__main__': ...@@ -261,11 +275,11 @@ if __name__ == '__main__':
mimetypes.init() mimetypes.init()
mimetypes.add_type ('text/plain', '.py') mimetypes.add_type ('text/plain', '.py')
handlers = [th, ih, sh, fh] handlers = [th, ih, sh, fh]
#server = coro.http.server (('0.0.0.0', 9001)) # server = coro.http.server (('0.0.0.0', 9001))
server = coro.http.server() server = coro.http.server()
for h in handlers: for h in handlers:
server.push_handler (h) server.push_handler (h)
#coro.spawn (server.start) # coro.spawn (server.start)
coro.spawn (server.start, ('0.0.0.0', 9001)) coro.spawn (server.start, ('0.0.0.0', 9001))
coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd') coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd')
coro.event_loop (30.0) coro.event_loop (30.0)
...@@ -23,15 +23,15 @@ intersects = region.region_intersect_p ...@@ -23,15 +23,15 @@ intersects = region.region_intersect_p
# split a rect into four quadrants # split a rect into four quadrants
def split (rect): def split (rect):
l,t,r,b = rect l, t, r, b = rect
w2 = ((r-l)/2)+l w2 = ((r - l) / 2) + l
h2 = ((b-t)/2)+t h2 = ((b - t) / 2) + t
return ( return (
(l,t,w2,h2), (l, t, w2, h2),
(w2,t,r,h2), (w2, t, r, h2),
(l,h2,w2,b), (l, h2, w2, b),
(w2,h2,r,b) (w2, h2, r, b)
) )
# insert an object into the tree. The object must have a # insert an object into the tree. The object must have a
# 'get_rect()' method in order to support searching. # 'get_rect()' method in order to support searching.
...@@ -45,7 +45,7 @@ def insert (tree, tree_rect, ob, ob_rect): ...@@ -45,7 +45,7 @@ def insert (tree, tree_rect, ob, ob_rect):
for i in range(4): for i in range(4):
if contains (quads[i], ob_rect): if contains (quads[i], ob_rect):
if not tree[i]: if not tree[i]:
tree[i] = [None,None,None,None,set()] tree[i] = [None, None, None, None, set()]
insert (tree[i], quads[i], ob, ob_rect) insert (tree[i], quads[i], ob, ob_rect)
return return
tree[4].add (ob) tree[4].add (ob)
...@@ -91,31 +91,31 @@ def gen_all (tree): ...@@ -91,31 +91,31 @@ def gen_all (tree):
yield x yield x
def dump (rect, tree, depth=0): def dump (rect, tree, depth=0):
print ' ' * depth, rect, tree[4] print ' ' * depth, rect, tree[4]
quads = split (rect) quads = split (rect)
for i in range (4): for i in range (4):
if tree[i]: if tree[i]:
dump (quads[i], tree[i], depth+1) dump (quads[i], tree[i], depth + 1)
# wrapper for a quadtree, maintains bounds, keeps track of the # wrapper for a quadtree, maintains bounds, keeps track of the
# number of objects, etc... # number of objects, etc...
class quadtree: class quadtree:
def __init__ (self, rect=(0,0,16,16)): def __init__ (self, rect=(0, 0, 16, 16)):
self.rect = rect self.rect = rect
self.tree = [None,None,None,None,set()] self.tree = [None, None, None, None, set()]
self.num_obs = 0 self.num_obs = 0
self.bounds = (0,0,0,0) self.bounds = (0, 0, 0, 0)
def __repr__ (self): def __repr__ (self):
return '<quad tree (objects:%d) bounds:%s >' % ( return '<quad tree (objects:%d) bounds:%s >' % (
self.num_obs, self.num_obs,
repr(self.bounds) repr(self.bounds)
) )
def check_bounds (self, rect): def check_bounds (self, rect):
l,t,r,b = self.bounds l, t, r, b = self.bounds
L,T,R,B = rect L, T, R, B = rect
if L < l: if L < l:
l = L l = L
if T < t: if T < t:
...@@ -124,7 +124,7 @@ class quadtree: ...@@ -124,7 +124,7 @@ class quadtree:
r = R r = R
if B > b: if B > b:
b = B b = B
self.bounds = l,t,r,b self.bounds = l, t, r, b
def get_bounds (self): def get_bounds (self):
return self.bounds return self.bounds
...@@ -132,22 +132,22 @@ class quadtree: ...@@ -132,22 +132,22 @@ class quadtree:
def insert (self, ob): def insert (self, ob):
rect = ob.get_rect() rect = ob.get_rect()
while not contains (self.rect, rect): while not contains (self.rect, rect):
l,t,r,b = self.rect l, t, r, b = self.rect
w, h = r-l, b-t w, h = r - l, b - t
# favor growing right and down # favor growing right and down
if (rect[2] > r) or (rect[3] > b): if (rect[2] > r) or (rect[3] > b):
# resize, placing original in the upper left # resize, placing original in the upper left
self.rect = l, t, (r+w), (b+h) self.rect = l, t, (r + w), (b + h)
self.tree = [self.tree, None, None, None, set()] self.tree = [self.tree, None, None, None, set()]
elif (rect[0] < l) or (rect[1] < t): elif (rect[0] < l) or (rect[1] < t):
# resize, placing original in lower right # resize, placing original in lower right
self.rect = (l-w,t-h,r,b) self.rect = (l - w, t - h, r, b)
self.tree = [None, None, None, self.tree, set()] self.tree = [None, None, None, self.tree, set()]
# we know the target rect fits in our space # we know the target rect fits in our space
insert (self.tree, self.rect, ob, rect) insert (self.tree, self.rect, ob, rect)
self.check_bounds (rect) self.check_bounds (rect)
self.num_obs += 1 self.num_obs += 1
def gen_all (self): def gen_all (self):
for ob in gen_all (self.tree): for ob in gen_all (self.tree):
yield ob yield ob
...@@ -171,7 +171,9 @@ class quadtree: ...@@ -171,7 +171,9 @@ class quadtree:
class box: class box:
def __init__ (self, rect): def __init__ (self, rect):
self.rect = rect self.rect = rect
def get_rect (self): def get_rect (self):
return self.rect return self.rect
def __repr__ (self): def __repr__ (self):
return '<box (%d,%d,%d,%d)>' % self.rect return '<box (%d,%d,%d,%d)>' % self.rect
...@@ -25,17 +25,17 @@ ...@@ -25,17 +25,17 @@
# (there are six) and then generalize. simplify the # (there are six) and then generalize. simplify the
# expression and you get this. (trust me 8^) # expression and you get this. (trust me 8^)
def region_intersect_p (a,b): def region_intersect_p (a, b):
return (a[2] >= b[0]) and \ return (a[2] >= b[0]) and \
(b[2] >= a[0]) and \ (b[2] >= a[0]) and \
(a[3] >= b[1]) and \ (a[3] >= b[1]) and \
(b[3] >= a[1]) (b[3] >= a[1])
def point_in_region_p (x,y,r): def point_in_region_p (x, y, r):
return (r[0] <= x <= r[2]) and (r[1] <= y <= r[3]) return (r[0] <= x <= r[2]) and (r[1] <= y <= r[3])
# does region <a> fully contain region <b>? # does region <a> fully contain region <b>?
def region_contains_region_p (a,b): def region_contains_region_p (a, b):
return (a[0] <= b[0]) and \ return (a[0] <= b[0]) and \
(a[2] >= b[2]) and \ (a[2] >= b[2]) and \
(a[1] <= b[1]) and \ (a[1] <= b[1]) and \
...@@ -49,4 +49,4 @@ def union (a, b): ...@@ -49,4 +49,4 @@ def union (a, b):
min (y0, y2), min (y0, y2),
max (x1, x3), max (x1, x3),
max (y1, y3) max (y1, y3)
) )
...@@ -5,6 +5,6 @@ from Cython.Distutils import build_ext ...@@ -5,6 +5,6 @@ from Cython.Distutils import build_ext
setup ( setup (
name='quadtree', name='quadtree',
description='Quad Tree - Spatial Search Data Structure', description='Quad Tree - Spatial Search Data Structure',
cmdclass = {'build_ext': build_ext}, cmdclass={'build_ext': build_ext},
ext_modules = [Extension ("quadtree", ["quadtree.pyx"],)] ext_modules=[Extension ("quadtree", ["quadtree.pyx"],)]
) )
...@@ -124,7 +124,7 @@ class sketch_conn (websocket): ...@@ -124,7 +124,7 @@ class sketch_conn (websocket):
def handle_packet (self, p): def handle_packet (self, p):
event = p.unpack().split (',') event = p.unpack().split (',')
#W ('packet = %r event=%r\n' % (p, event)) # W ('packet = %r event=%r\n' % (p, event))
if event[0] == 'MD': if event[0] == 'MD':
self.mouse_down = True self.mouse_down = True
self.line_start = int (event[1]), int (event[2]) self.line_start = int (event[1]), int (event[2])
...@@ -136,8 +136,8 @@ class sketch_conn (websocket): ...@@ -136,8 +136,8 @@ class sketch_conn (websocket):
self.server.broadcast ( self.server.broadcast (
'D,%d,%d,%s,%s' % ( 'D,%d,%d,%s,%s' % (
self.line_start[0], self.line_start[1], x1, y1 self.line_start[0], self.line_start[1], x1, y1
)
) )
)
self.line_start = x1, y1 self.line_start = x1, y1
elif event[0] == 'CD': elif event[0] == 'CD':
self.server.clear_drawing() self.server.clear_drawing()
...@@ -146,9 +146,9 @@ class sketch_conn (websocket): ...@@ -146,9 +146,9 @@ class sketch_conn (websocket):
elif event[0] == 'PD': elif event[0] == 'PD':
self.server.prev_drawing() self.server.prev_drawing()
elif event[0] == 'KD': elif event[0] == 'KD':
if event[1] == '85': # 'U' if event[1] == '85': # 'U'
self.server.undo() self.server.undo()
elif event[1] == '82': # 'R' elif event[1] == '82': # 'R'
self.server.set_drawing (self.server.timestamp) self.server.set_drawing (self.server.timestamp)
else: else:
W ('unknown event: %r\n' % (event,)) W ('unknown event: %r\n' % (event,))
...@@ -165,11 +165,11 @@ if __name__ == '__main__': ...@@ -165,11 +165,11 @@ if __name__ == '__main__':
wh = handler ('/sketch', sketch_server.new_session) wh = handler ('/sketch', sketch_server.new_session)
fh = coro.http.handlers.file_handler (cwd) fh = coro.http.handlers.file_handler (cwd)
handlers = [wh, ih, sh, fh] handlers = [wh, ih, sh, fh]
#server = coro.http.server (('0.0.0.0', 9001)) # server = coro.http.server (('0.0.0.0', 9001))
server = coro.http.server() server = coro.http.server()
for h in handlers: for h in handlers:
server.push_handler (h) server.push_handler (h)
#coro.spawn (server.start) # coro.spawn (server.start)
coro.spawn (server.start, ('0.0.0.0', 9001)) coro.spawn (server.start, ('0.0.0.0', 9001))
coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd') coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd')
coro.event_loop (30.0) coro.event_loop (30.0)
...@@ -36,11 +36,11 @@ class terminal (websocket): ...@@ -36,11 +36,11 @@ class terminal (websocket):
def handle_packet (self, p): def handle_packet (self, p):
data = p.unpack() data = p.unpack()
event = p.unpack().split (',') event = p.unpack().split (',')
#W ('packet = %r event=%r\n' % (p, event)) # W ('packet = %r event=%r\n' % (p, event))
if event[0] == 'K': if event[0] == 'K':
ascii = int (event[1]) ascii = int (event[1])
#W ('ascii=%d\n' % (ascii,)) # W ('ascii=%d\n' % (ascii,))
if ascii in (10, 13): # lf cr if ascii in (10, 13): # lf cr
ascii = 10 ascii = 10
line = ''.join (self.line) line = ''.join (self.line)
self.history.append (line) self.history.append (line)
...@@ -48,9 +48,9 @@ class terminal (websocket): ...@@ -48,9 +48,9 @@ class terminal (websocket):
self.send_text ('C') self.send_text ('C')
self.send_text ('D' + escape (line) + '\n') self.send_text ('D' + escape (line) + '\n')
self.repl.inlines.push (line) self.repl.inlines.push (line)
elif ascii == 4: # ctrl-d elif ascii == 4: # ctrl-d
self.repl.inlines.push (None) self.repl.inlines.push (None)
elif ascii in (16, 14): # ctrl-p, ctrl-n elif ascii in (16, 14): # ctrl-p, ctrl-n
if ascii == 16: if ascii == 16:
self.history_index = (self.history_index + 1) % len(self.history) self.history_index = (self.history_index + 1) % len(self.history)
else: else:
...@@ -115,26 +115,26 @@ if __name__ == '__main__': ...@@ -115,26 +115,26 @@ if __name__ == '__main__':
ih = coro.http.handlers.favicon_handler() ih = coro.http.handlers.favicon_handler()
sh = coro.http.handlers.coro_status_handler() sh = coro.http.handlers.coro_status_handler()
th = handler ('/term', terminal) th = handler ('/term', terminal)
th.auth_dict = {'foo':'bar'} th.auth_dict = {'foo': 'bar'}
# serve files out of this directory # serve files out of this directory
fh = coro.http.handlers.file_handler (os.getcwd()) fh = coro.http.handlers.file_handler (os.getcwd())
handlers = [th, ih, sh, fh] handlers = [th, ih, sh, fh]
#server = coro.http.server() # server = coro.http.server()
#server = coro.http.tlslite_server ( # server = coro.http.tlslite_server (
# # should point to the test cert in coro/http/cert/ # should point to the test cert in coro/http/cert/
# '../../../cert/server.crt', # '../../../cert/server.crt',
# '../../../cert/server.key', # '../../../cert/server.key',
# ) # )
import coro.ssl import coro.ssl
from coro.ssl import openssl from coro.ssl import openssl
ctx = coro.ssl.new_ctx ( ctx = coro.ssl.new_ctx (
cert = openssl.x509 (open('../../../cert/server.crt').read()), cert=openssl.x509 (open('../../../cert/server.crt').read()),
key = openssl.pkey (open('../../../cert/server.key').read(), private=True), key=openssl.pkey (open('../../../cert/server.key').read(), private=True),
) )
server = coro.http.openssl_server (ctx) server = coro.http.openssl_server (ctx)
for h in handlers: for h in handlers:
server.push_handler (h) server.push_handler (h)
#coro.spawn (server.start) # coro.spawn (server.start)
coro.spawn (server.start, ('0.0.0.0', 9001)) coro.spawn (server.start, ('0.0.0.0', 9001))
coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd') coro.spawn (coro.backdoor.serve, unix_path='/tmp/ws.bd')
coro.event_loop (30.0) coro.event_loop (30.0)
...@@ -49,8 +49,8 @@ class coro_status_handler: ...@@ -49,8 +49,8 @@ class coro_status_handler:
return request.path.split ('/')[1] == 'status' return request.path.split ('/')[1] == 'status'
def clean (self, s): def clean (self, s):
s = s.replace ('<','&lt;') s = s.replace ('<', '&lt;')
s = s.replace ('>','&gt;') s = s.replace ('>', '&gt;')
return s return s
def handle_request (self, request): def handle_request (self, request):
...@@ -60,13 +60,13 @@ class coro_status_handler: ...@@ -60,13 +60,13 @@ class coro_status_handler:
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
'<html xmlns="http://www.w3.org/1999/xhtml">\r\n' '<html xmlns="http://www.w3.org/1999/xhtml">\r\n'
) )
request.push ('<head><title>status</title></head><body>\r\n') request.push ('<head><title>status</title></head><body>\r\n')
request.push ('<p>Listening on\r\n') request.push ('<p>Listening on\r\n')
request.push (repr (request.server.addr)) request.push (repr (request.server.addr))
request.push ('</p>\r\n') request.push ('</p>\r\n')
request.push ('<table border="1">\r\n') request.push ('<table border="1">\r\n')
all_threads = ( (x, coro.where(x)) for x in coro.all_threads.values() ) all_threads = ((x, coro.where(x)) for x in coro.all_threads.values())
for thread, traceback in all_threads: for thread, traceback in all_threads:
request.push ('<tr><td>%s\r\n' % self.clean (repr(thread))) request.push ('<tr><td>%s\r\n' % self.clean (repr(thread)))
request.push ('<pre>\r\n') request.push ('<pre>\r\n')
...@@ -139,7 +139,7 @@ class file_handler: ...@@ -139,7 +139,7 @@ class file_handler:
f = open (filename, 'rb') f = open (filename, 'rb')
block = f.read (self.block_size) block = f.read (self.block_size)
if not block: if not block:
request.error (204) # no content request.error (204) # no content
else: else:
while 1: while 1:
request.push (block) request.push (block)
...@@ -169,7 +169,7 @@ sample = ( ...@@ -169,7 +169,7 @@ sample = (
'AAAAAAAAAAAAAAD/+K///8AH//+iI///QAH//r4g//x3AH//Z6J//UABP/ovgD/458Ef+u+wv/Tn' 'AAAAAAAAAAAAAAD/+K///8AH//+iI///QAH//r4g//x3AH//Z6J//UABP/ovgD/458Ef+u+wv/Tn'
'0R/+79if9OXZH/6gCJ/2BwAf/u/8n/h33R/7Z7kf/ReQH/+qu7//BUW//7vrv//RR3//7r///80d' '0R/+79if9OXZH/6gCJ/2BwAf/u/8n/h33R/7Z7kf/ReQH/+qu7//BUW//7vrv//RR3//7r///80d'
'///pq///8EP//+rH///d9///6j///9Af/w==' '///pq///8EP//+rH///d9///6j///9Af/w=='
).decode ('base64') ).decode ('base64')
zsample = zlib.compress (sample, 9) zsample = zlib.compress (sample, 9)
...@@ -219,7 +219,7 @@ class auth_handler: ...@@ -219,7 +219,7 @@ class auth_handler:
def match (self, request): def match (self, request):
# by default, use the given handler's matcher # by default, use the given handler's matcher
return self.handler.match (request) return self.handler.match (request)
def parse_authorization (self, h): def parse_authorization (self, h):
parts = h.split() parts = h.split()
kind = parts[0].lower() kind = parts[0].lower()
...@@ -239,7 +239,7 @@ class auth_handler: ...@@ -239,7 +239,7 @@ class auth_handler:
return {} return {}
else: else:
key = part[:i] key = part[:i]
val = part[i+1:] val = part[i + 1:]
# strip quotes # strip quotes
val = val.replace ('"', ' ').strip() val = val.replace ('"', ' ').strip()
d[key.lower()] = val d[key.lower()] = val
...@@ -262,7 +262,7 @@ class auth_handler: ...@@ -262,7 +262,7 @@ class auth_handler:
return True return True
else: else:
return False return False
def handle_request (self, request): def handle_request (self, request):
# authorize a request before handling it... # authorize a request before handling it...
h = request['authorization'] h = request['authorization']
...@@ -274,7 +274,7 @@ class auth_handler: ...@@ -274,7 +274,7 @@ class auth_handler:
self.handle_unauthorized (request) self.handle_unauthorized (request)
else: else:
self.handle_unauthorized (request) self.handle_unauthorized (request)
def get_nonce (self): def get_nonce (self):
return hashlib.sha1 (os.urandom(16)).hexdigest()[:16] return hashlib.sha1 (os.urandom(16)).hexdigest()[:16]
...@@ -286,5 +286,5 @@ class auth_handler: ...@@ -286,5 +286,5 @@ class auth_handler:
request['WWW-Authenticate'] = ','.join ([ request['WWW-Authenticate'] = ','.join ([
'Digest realm="%s"' % self.realm, 'Digest realm="%s"' % self.realm,
'nonce="%s"' % (nonce,), 'nonce="%s"' % (nonce,),
]) ])
request.error (401) request.error (401)
...@@ -13,8 +13,8 @@ def join (seq, field=' '): ...@@ -13,8 +13,8 @@ def join (seq, field=' '):
def group (s): def group (s):
return '(' + s + ')' return '(' + s + ')'
short_days = ['sun','mon','tue','wed','thu','fri','sat'] short_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
long_days = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'] long_days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
short_day_reg = group (join (short_days, '|')) short_day_reg = group (join (short_days, '|'))
long_day_reg = group (join (long_days, '|')) long_day_reg = group (join (long_days, '|'))
...@@ -26,11 +26,11 @@ for i in range(7): ...@@ -26,11 +26,11 @@ for i in range(7):
hms_reg = join (3 * [group('[0-9][0-9]')], ':') hms_reg = join (3 * [group('[0-9][0-9]')], ':')
months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'] months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
monmap = {} monmap = {}
for i in range(12): for i in range(12):
monmap[months[i]] = i+1 monmap[months[i]] = i + 1
months_reg = group (join (months, '|')) months_reg = group (join (months, '|'))
...@@ -41,7 +41,7 @@ months_reg = group (join (months, '|')) ...@@ -41,7 +41,7 @@ months_reg = group (join (months, '|'))
# rfc822 format # rfc822 format
rfc822_date = join ( rfc822_date = join (
[concat (short_day_reg,','), # day [concat (short_day_reg, ','), # day
group('[0-9][0-9]?'), # date group('[0-9][0-9]?'), # date
months_reg, # month months_reg, # month
group('[0-9]+'), # year group('[0-9]+'), # year
...@@ -49,7 +49,7 @@ rfc822_date = join ( ...@@ -49,7 +49,7 @@ rfc822_date = join (
'gmt' 'gmt'
], ],
' ' ' '
) )
rfc822_reg = re.compile (rfc822_date) rfc822_reg = re.compile (rfc822_date)
...@@ -66,23 +66,23 @@ def unpack_rfc822 (m): ...@@ -66,23 +66,23 @@ def unpack_rfc822 (m):
0, 0,
0, 0,
0 0
) )
# rfc850 format # rfc850 format
rfc850_date = join ( rfc850_date = join (
[concat (long_day_reg,','), [concat (long_day_reg, ','),
join ( join (
[group ('[0-9][0-9]?'), [group ('[0-9][0-9]?'),
months_reg, months_reg,
group ('[0-9]+') group ('[0-9]+')
], ],
'-' '-'
), ),
hms_reg, hms_reg,
'gmt' 'gmt'
], ],
' ' ' '
) )
rfc850_reg = re.compile (rfc850_date) rfc850_reg = re.compile (rfc850_date)
# they actually unpack the same way # they actually unpack the same way
...@@ -99,7 +99,7 @@ def unpack_rfc850 (m): ...@@ -99,7 +99,7 @@ def unpack_rfc850 (m):
0, 0,
0, 0,
0 0
) )
# parsdate.parsedate - ~700/sec. # parsdate.parsedate - ~700/sec.
# parse_http_date - ~1333/sec. # parse_http_date - ~1333/sec.
...@@ -111,9 +111,9 @@ monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...@@ -111,9 +111,9 @@ monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
def build_http_date(when): def build_http_date(when):
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when)
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
weekdayname[wd], weekdayname[wd],
day, monthname[month], year, day, monthname[month], year,
hh, mm, ss) hh, mm, ss)
def parse_http_date (d): def parse_http_date (d):
d = string.lower (d) d = string.lower (d)
......
...@@ -22,9 +22,9 @@ class json_rpc_handler: ...@@ -22,9 +22,9 @@ class json_rpc_handler:
result = self.root.handle_json_rpc (qd['method'], qd['params']) result = self.root.handle_json_rpc (qd['method'], qd['params'])
request['content-type'] = 'application/json' request['content-type'] = 'application/json'
if v2: if v2:
rd = {'jsonrpc':'2.0', 'result':result, 'id':qd['id']} rd = {'jsonrpc': '2.0', 'result': result, 'id': qd['id']}
else: else:
rd = {'result':result, 'error':None, 'id':qd['id']} rd = {'result': result, 'error': None, 'id': qd['id']}
request.push (json.dumps (rd)) request.push (json.dumps (rd))
request.done() request.done()
...@@ -58,11 +58,11 @@ class json_rpc_remote: ...@@ -58,11 +58,11 @@ class json_rpc_remote:
if self.conn is None: if self.conn is None:
self.conn = http_client (self.url_ob.hostname, self.url_ob.port) self.conn = http_client (self.url_ob.hostname, self.url_ob.port)
if kwargs: if kwargs:
assert (not args) # no way to mix positional & named args assert (not args) # no way to mix positional & named args
params = kwargs params = kwargs
else: else:
params = list (args) params = list (args)
jreq = json.dumps ({'method': name, 'params':params, 'id':self.counter}) jreq = json.dumps ({'method': name, 'params': params, 'id': self.counter})
self.counter += 1 self.counter += 1
if self.auth: if self.auth:
req = self.conn.POST (self.url_ob.path, jreq, Authorization='Basic %s' % (self.auth,)) req = self.conn.POST (self.url_ob.path, jreq, Authorization='Basic %s' % (self.auth,))
...@@ -72,8 +72,8 @@ class json_rpc_remote: ...@@ -72,8 +72,8 @@ class json_rpc_remote:
jrep = json.loads (req.content) jrep = json.loads (req.content)
return jrep['result'] return jrep['result']
else: else:
raise Error ((req.reply_code, req.content)) raise Error ((req.reply_code, req.content))
def close (self): def close (self):
if self.conn is not None: if self.conn is not None:
self.conn.close() self.conn.close()
......
...@@ -52,7 +52,7 @@ class http_file: ...@@ -52,7 +52,7 @@ class http_file:
self.streamo = read_stream.buffered_stream (self._gen_read_all().next) self.streamo = read_stream.buffered_stream (self._gen_read_all().next)
else: else:
raise HTTP_Protocol_Error ("no way to determine length of HTTP data") raise HTTP_Protocol_Error ("no way to determine length of HTTP data")
def _gen_read_chunked (self): def _gen_read_chunked (self):
"generator: decodes chunked transfer-encoding." "generator: decodes chunked transfer-encoding."
s = self.streami s = self.streami
...@@ -127,7 +127,8 @@ class header_set: ...@@ -127,7 +127,8 @@ class header_set:
self.crack (h) self.crack (h)
def from_keywords (self, kwds): def from_keywords (self, kwds):
"Populate this header set from a dictionary of keyword arguments (e.g., 'content_length' becomes 'content-length')" """Populate this header set from a dictionary of keyword arguments
(e.g., 'content_length' becomes 'content-length')"""
r = [] r = []
for k, v in kwds.items(): for k, v in kwds.items():
k = k.replace ('_', '-') k = k.replace ('_', '-')
...@@ -139,14 +140,15 @@ class header_set: ...@@ -139,14 +140,15 @@ class header_set:
# deliberately ignoring 822 crap like continuation lines. # deliberately ignoring 822 crap like continuation lines.
try: try:
i = h.index (': ') i = h.index (': ')
name, value = h[:i], h[i+2:] name, value = h[:i], h[i + 2:]
self[name] = value self[name] = value
except ValueError: except ValueError:
coro.write_stderr ('dropping bogus header %r\n' % (h,)) coro.write_stderr ('dropping bogus header %r\n' % (h,))
pass pass
def get_one (self, key): def get_one (self, key):
"Get the value of a header expected to have at most one value. If not present, return None. If more than one, raise ValueError." """Get the value of a header expected to have at most one value.
If not present, return None. If more than one, raise ValueError."""
r = self.headers.get (key, None) r = self.headers.get (key, None)
if r is None: if r is None:
return r return r
......
...@@ -28,7 +28,7 @@ class request_stream: ...@@ -28,7 +28,7 @@ class request_stream:
self.timeout = conn.server.client_timeout self.timeout = conn.server.client_timeout
self.conn = conn self.conn = conn
self.stream = stream self.stream = stream
def get_request (self): def get_request (self):
request_line = self.stream.read_line() request_line = self.stream.read_line()
if not request_line: if not request_line:
...@@ -142,7 +142,7 @@ class http_request: ...@@ -142,7 +142,7 @@ class http_request:
self.request_headers = headers self.request_headers = headers
self.client = client self.client = client
self.server = client.server self.server = client.server
self.tstart = time.time() # XXX use coro.now self.tstart = time.time() # XXX use coro.now
self.peer = client.peer self.peer = client.peer
self.output = buffered_output (self.client.conn) self.output = buffered_output (self.client.conn)
self.done_cv = latch() self.done_cv = latch()
...@@ -260,7 +260,7 @@ class http_request: ...@@ -260,7 +260,7 @@ class http_request:
ho = self.reply_headers ho = self.reply_headers
connection = hi.get_one('connection') connection = hi.get_one('connection')
if connection: if connection:
connection_tokens = [ x.strip() for x in connection.split(',') ] connection_tokens = [x.strip() for x in connection.split(',')]
else: else:
connection_tokens = () connection_tokens = ()
close_it = False close_it = False
...@@ -319,7 +319,7 @@ class http_request: ...@@ -319,7 +319,7 @@ class http_request:
self.reply_code, self.reply_code,
self.output.sent, self.output.sent,
now - self.tstart, now - self.tstart,
) )
responses = { responses = {
100: "Continue", 100: "Continue",
...@@ -359,7 +359,7 @@ class http_request: ...@@ -359,7 +359,7 @@ class http_request:
503: "Service Unavailable", 503: "Service Unavailable",
504: "Gateway Time-out", 504: "Gateway Time-out",
505: "HTTP Version not supported" 505: "HTTP Version not supported"
} }
# Default error message # Default error message
DEFAULT_ERROR_MESSAGE = '\r\n'.join ([ DEFAULT_ERROR_MESSAGE = '\r\n'.join ([
...@@ -375,7 +375,7 @@ class http_request: ...@@ -375,7 +375,7 @@ class http_request:
'</body>', '</body>',
'</html>', '</html>',
'' ''
]) ])
# chunking works thus: # chunking works thus:
# <data> # <data>
...@@ -494,10 +494,10 @@ class server: ...@@ -494,10 +494,10 @@ class server:
self.thread_id = coro.current().thread_id() self.thread_id = coro.current().thread_id()
while not self.shutdown_flag: while not self.shutdown_flag:
try: try:
conn, addr = self.accept() conn, addr = self.accept()
client = self.create_connection (conn, addr) client = self.create_connection (conn, addr)
c = coro.spawn (client.run) c = coro.spawn (client.run)
c.set_name ('%s connection on %r' % (self.__class__.__name__, addr,)) c.set_name ('%s connection on %r' % (self.__class__.__name__, addr,))
except coro.Shutdown: except coro.Shutdown:
break break
except: except:
...@@ -527,7 +527,7 @@ class server: ...@@ -527,7 +527,7 @@ class server:
thread = coro.get_thread_by_id (self.thread_id) thread = coro.get_thread_by_id (self.thread_id)
thread.shutdown() thread.shutdown()
except KeyError: except KeyError:
return # already exited return # already exited
class tlslite_server (server): class tlslite_server (server):
...@@ -569,7 +569,7 @@ class tlslite_server (server): ...@@ -569,7 +569,7 @@ class tlslite_server (server):
self.private = tlslite.parsePEMKey ( self.private = tlslite.parsePEMKey (
open (self.key_path).read(), open (self.key_path).read(),
private=True private=True
) )
class openssl_server (server): class openssl_server (server):
......
# -*- Mode: Python -*- # -*- Mode: Python -*-
import struct import struct
import coro import coro
import sys import sys
from coro.http import connection, tlslite_server, openssl_server, http_request from coro.http import connection, tlslite_server, openssl_server, http_request
from coro.http.protocol import header_set, http_file from coro.http.protocol import header_set, http_file
from coro.http.zspdy import inflator, deflator, unpack_control_frame, pack_control_frame, pack_data_frame, pack_http_header, unpack_http_header from coro.http.zspdy import inflator, deflator, unpack_control_frame, pack_control_frame
from coro.http.zspdy import pack_data_frame, pack_http_header, unpack_http_header
W = coro.write_stderr W = coro.write_stderr
...@@ -37,7 +38,7 @@ class spdy_file (http_file): ...@@ -37,7 +38,7 @@ class spdy_file (http_file):
while 1: while 1:
block = self.content_fifo.pop() block = self.content_fifo.pop()
if block is None: if block is None:
#W ('gen_spdy: end of content\n') # W ('gen_spdy: end of content\n')
self.done_cv.wake_all() self.done_cv.wake_all()
break break
else: else:
...@@ -59,7 +60,7 @@ class spdy_server_request (http_request): ...@@ -59,7 +60,7 @@ class spdy_server_request (http_request):
path = headers.get_one (':path') path = headers.get_one (':path')
version = headers.get_one (':version') version = headers.get_one (':version')
# XXX proxy # XXX proxy
#url = '%s://%s/%s' % (scheme, host, path) # url = '%s://%s/%s' % (scheme, host, path)
url = path url = path
# XXX consider changing the api to take these as separate arguments # XXX consider changing the api to take these as separate arguments
request = '%s %s %s' % (method, url, version) request = '%s %s %s' % (method, url, version)
...@@ -115,17 +116,17 @@ class spdy_server_request (http_request): ...@@ -115,17 +116,17 @@ class spdy_server_request (http_request):
class spdy_protocol: class spdy_protocol:
frame_types = { frame_types = {
1 : 'syn_stream', 1: 'syn_stream',
2 : 'syn_reply', 2: 'syn_reply',
3 : 'rst_stream', 3: 'rst_stream',
4 : 'settings', 4: 'settings',
# removed in draft3 # removed in draft3
5 : 'noop', 5: 'noop',
6 : 'ping', 6: 'ping',
7 : 'goaway', 7: 'goaway',
8 : 'headers', 8: 'headers',
9 : 'window_update', 9: 'window_update',
} }
status_codes = { status_codes = {
1: 'protocol_error', 1: 'protocol_error',
...@@ -135,7 +136,7 @@ class spdy_protocol: ...@@ -135,7 +136,7 @@ class spdy_protocol:
5: 'cancel', 5: 'cancel',
6: 'internal_error', 6: 'internal_error',
7: 'flow_control_error', 7: 'flow_control_error',
} }
protocol = 'spdy/3' protocol = 'spdy/3'
...@@ -167,7 +168,7 @@ class spdy_protocol: ...@@ -167,7 +168,7 @@ class spdy_protocol:
def read_control_frame (self, head): def read_control_frame (self, head):
fversion, ftype, flags, length = unpack_control_frame (head) fversion, ftype, flags, length = unpack_control_frame (head)
data = self.read_exact (length) data = self.read_exact (length)
#W ('control: version=%d type=%d flags=%x length=%d\n' % (fversion, ftype, flags, length, )) # W ('control: version=%d type=%d flags=%x length=%d\n' % (fversion, ftype, flags, length, ))
assert (fversion == 3) assert (fversion == 3)
method_name = 'frame_%s' % (self.frame_types.get (ftype, ''),) method_name = 'frame_%s' % (self.frame_types.get (ftype, ''),)
if method_name == 'frame_': if method_name == 'frame_':
...@@ -179,7 +180,7 @@ class spdy_protocol: ...@@ -179,7 +180,7 @@ class spdy_protocol:
def read_data_frame (self, head): def read_data_frame (self, head):
stream_id, flags, length = unpack_data_frame (head) stream_id, flags, length = unpack_data_frame (head)
data = self.read_exact (length) data = self.read_exact (length)
#W ('data: stream_id=%d flags=%x length=%d\n' % (stream_id, flags, length)) # W ('data: stream_id=%d flags=%x length=%d\n' % (stream_id, flags, length))
self.handle_data_frame (stream_id, flags, data) self.handle_data_frame (stream_id, flags, data)
spdy_version = 3 spdy_version = 3
...@@ -221,7 +222,7 @@ class spdy_connection (spdy_protocol, connection): ...@@ -221,7 +222,7 @@ class spdy_connection (spdy_protocol, connection):
self.read_frames() self.read_frames()
finally: finally:
self.ofifo.push (None) self.ofifo.push (None)
def close (self): def close (self):
self.ofifo.push (None) self.ofifo.push (None)
self.conn.close() self.conn.close()
...@@ -236,7 +237,7 @@ class spdy_connection (spdy_protocol, connection): ...@@ -236,7 +237,7 @@ class spdy_connection (spdy_protocol, connection):
self.obuf.release (len(block)) self.obuf.release (len(block))
def send_frame (self, frame): def send_frame (self, frame):
#self.conn.send (frame) # self.conn.send (frame)
self.obuf.acquire (len(frame)) self.obuf.acquire (len(frame))
self.ofifo.push (frame) self.ofifo.push (frame)
...@@ -256,13 +257,13 @@ class spdy_connection (spdy_protocol, connection): ...@@ -256,13 +257,13 @@ class spdy_connection (spdy_protocol, connection):
flags = 0x01 flags = 0x01
else: else:
flags = 0x00 flags = 0x00
#W ('req.reply_headers=%r\n' % (str(req.reply_headers),)) # W ('req.reply_headers=%r\n' % (str(req.reply_headers),))
name_vals = self.pack_http_header (req.reply_headers) name_vals = self.pack_http_header (req.reply_headers)
#W ('compressed name_vals=%r\n' % (name_vals,)) # W ('compressed name_vals=%r\n' % (name_vals,))
frame = self.pack_control_frame ( frame = self.pack_control_frame (
0x02, flags, 0x02, flags,
''.join ([struct.pack ('>L', req.stream_id), name_vals]) ''.join ([struct.pack ('>L', req.stream_id), name_vals])
) )
self.send_frame (frame) self.send_frame (frame)
req.output.sent += len (frame) req.output.sent += len (frame)
...@@ -271,13 +272,13 @@ class spdy_connection (spdy_protocol, connection): ...@@ -271,13 +272,13 @@ class spdy_connection (spdy_protocol, connection):
# XXX do something with priority # XXX do something with priority
sid &= 0x7fffffff sid &= 0x7fffffff
asid &= 0x7fffffff asid &= 0x7fffffff
#W ('syn_stream: sid=%d asid=%d pri=%x ' % (sid, asid, pri)) # W ('syn_stream: sid=%d asid=%d pri=%x ' % (sid, asid, pri))
headers = self.unpack_http_header (data[10:]) headers = self.unpack_http_header (data[10:])
req = spdy_server_request (flags, sid, self, headers) req = spdy_server_request (flags, sid, self, headers)
#W ('%s\n' % req.request,) # W ('%s\n' % req.request,)
self.streams[sid] = req self.streams[sid] = req
coro.spawn (self.handle_request, req) coro.spawn (self.handle_request, req)
def handle_data_frame (self, stream_id, flags, data): def handle_data_frame (self, stream_id, flags, data):
probe = self.streams.get (stream_id, None) probe = self.streams.get (stream_id, None)
if probe is not None: if probe is not None:
...@@ -303,18 +304,18 @@ class spdy_connection (spdy_protocol, connection): ...@@ -303,18 +304,18 @@ class spdy_connection (spdy_protocol, connection):
def frame_rst_stream (self, flags, data): def frame_rst_stream (self, flags, data):
stream_id, status_code = struct.unpack ('>LL', data) stream_id, status_code = struct.unpack ('>LL', data)
#W ('reset: %x status=%d %s\n' % (stream_id, status_code, self.status_codes.get (status_code, 'unknown'))) # W ('reset: %x status=%d %s\n' % (stream_id, status_code, self.status_codes.get (status_code, 'unknown')))
del self.streams[stream_id] del self.streams[stream_id]
def frame_goaway (self, flags, data): def frame_goaway (self, flags, data):
last_stream_id, = struct.unpack ('>L', data) last_stream_id, = struct.unpack ('>L', data)
#W ('goaway last_stream_id=%d\n' % (last_stream_id,)) # W ('goaway last_stream_id=%d\n' % (last_stream_id,))
# XXX arrange for the connection to close # XXX arrange for the connection to close
self.close() self.close()
def frame_ping (self, flags, data): def frame_ping (self, flags, data):
ping_id, = struct.unpack ('>L', data) ping_id, = struct.unpack ('>L', data)
#W ('ping_id=%x\n' % (ping_id,)) # W ('ping_id=%x\n' % (ping_id,))
self.send_frame (self.pack_control_frame (6, 0, data)) self.send_frame (self.pack_control_frame (6, 0, data))
def frame_settings (self, flags, data): def frame_settings (self, flags, data):
...@@ -327,7 +328,7 @@ class spdy_tlslite_server (tlslite_server): ...@@ -327,7 +328,7 @@ class spdy_tlslite_server (tlslite_server):
def __init__ (self, addr, cert_path, key_path, settings=None): def __init__ (self, addr, cert_path, key_path, settings=None):
tlslite_server.__init__ (self, addr, cert_path, key_path, nextProtos=['spdy/3', 'http/1.1'], settings=settings) tlslite_server.__init__ (self, addr, cert_path, key_path, nextProtos=['spdy/3', 'http/1.1'], settings=settings)
def create_connection (self, conn, addr): def create_connection (self, conn, addr):
if conn.next_proto == b'spdy/3': if conn.next_proto == b'spdy/3':
return spdy_connection (self, conn, addr) return spdy_connection (self, conn, addr)
...@@ -376,7 +377,7 @@ class spdy_client (spdy_protocol, http_client.client): ...@@ -376,7 +377,7 @@ class spdy_client (spdy_protocol, http_client.client):
http_client.client.__init__ (self, host, port, conn, inflight) http_client.client.__init__ (self, host, port, conn, inflight)
# replace the fifo with a dictionary (spdy is not serialized) # replace the fifo with a dictionary (spdy is not serialized)
self.pending = {} self.pending = {}
def read_thread (self): def read_thread (self):
try: try:
self.read_frames() self.read_frames()
...@@ -399,7 +400,7 @@ class spdy_client (spdy_protocol, http_client.client): ...@@ -399,7 +400,7 @@ class spdy_client (spdy_protocol, http_client.client):
frame = self.pack_control_frame ( frame = self.pack_control_frame (
0x01, flags, 0x01, flags,
''.join ([struct.pack ('>LLH', sid, asid, pri), name_vals]) ''.join ([struct.pack ('>LLH', sid, asid, pri), name_vals])
) )
with self.send_mutex: with self.send_mutex:
self.send_frame (frame) self.send_frame (frame)
return sid return sid
......
...@@ -28,7 +28,7 @@ def do_mask (data, mask): ...@@ -28,7 +28,7 @@ def do_mask (data, mask):
r = bytearray (n) r = bytearray (n)
i = 0 i = 0
while i < len (data): while i < len (data):
r[i] = chr (ord (data[i]) ^ mask[i%4]) r[i] = chr (ord (data[i]) ^ mask[i % 4])
i += 1 i += 1
return bytes (r) return bytes (r)
...@@ -39,6 +39,7 @@ class ws_packet: ...@@ -39,6 +39,7 @@ class ws_packet:
plen = 0 plen = 0
masking = [] masking = []
payload = '' payload = ''
def __repr__ (self): def __repr__ (self):
return '<fin=%r opcode=%r mask=%r plen=%r masking=%r payload=%d bytes>' % ( return '<fin=%r opcode=%r mask=%r plen=%r masking=%r payload=%d bytes>' % (
self.fin, self.fin,
...@@ -47,7 +48,7 @@ class ws_packet: ...@@ -47,7 +48,7 @@ class ws_packet:
self.plen, self.plen,
self.masking, self.masking,
len (self.payload), len (self.payload),
) )
def unpack (self): def unpack (self):
if self.mask: if self.mask:
...@@ -62,7 +63,7 @@ class handler: ...@@ -62,7 +63,7 @@ class handler:
def __init__ (self, path, factory): def __init__ (self, path, factory):
self.path = path self.path = path
self.factory = factory self.factory = factory
def match (self, request): def match (self, request):
# try to catch both versions of the protocol # try to catch both versions of the protocol
return ( return (
...@@ -70,10 +71,10 @@ class handler: ...@@ -70,10 +71,10 @@ class handler:
and request.method == 'get' and request.method == 'get'
and request['upgrade'] and request['upgrade']
and request['upgrade'].lower() == 'websocket' and request['upgrade'].lower() == 'websocket'
) )
def h76_frob (self, key): def h76_frob (self, key):
digits = int (''.join ([ x for x in key if x in '0123456789' ])) digits = int (''.join ([x for x in key if x in '0123456789']))
spaces = key.count (' ') spaces = key.count (' ')
return digits / spaces return digits / spaces
...@@ -90,14 +91,14 @@ class handler: ...@@ -90,14 +91,14 @@ class handler:
'Upgrade: websocket', 'Upgrade: websocket',
'Connection: Upgrade', 'Connection: Upgrade',
'Sec-WebSocket-Accept: %s' % (reply,), 'Sec-WebSocket-Accept: %s' % (reply,),
] ]
if rh.has_key ('sec-websocket-protocol'): if rh.has_key ('sec-websocket-protocol'):
# XXX verify this # XXX verify this
r.append ( r.append (
'Sec-WebSocket-Protocol: %s' % ( 'Sec-WebSocket-Protocol: %s' % (
rh.get_one ('sec-websocket-protocol') rh.get_one ('sec-websocket-protocol')
)
) )
)
conn.send ('\r\n'.join (r) + '\r\n\r\n') conn.send ('\r\n'.join (r) + '\r\n\r\n')
protocol = 'rfc6455' protocol = 'rfc6455'
else: else:
...@@ -117,7 +118,7 @@ class handler: ...@@ -117,7 +118,7 @@ class handler:
'Connection: Upgrade', 'Connection: Upgrade',
'Sec-WebSocket-Origin: http://%s' % (host,), 'Sec-WebSocket-Origin: http://%s' % (host,),
'Sec-WebSocket-Location: ws://%s%s' % (host, request.uri), 'Sec-WebSocket-Location: ws://%s%s' % (host, request.uri),
] ]
all = '\r\n'.join (r) + '\r\n\r\n' + reply all = '\r\n'.join (r) + '\r\n\r\n' + reply
conn.send (all) conn.send (all)
protocol = 'hixie_76' protocol = 'hixie_76'
...@@ -160,7 +161,7 @@ class websocket: ...@@ -160,7 +161,7 @@ class websocket:
finally: finally:
self.handle_close() self.handle_close()
self.conn.close() self.conn.close()
def read_packet (self): def read_packet (self):
head = self.stream.read_exact (2) head = self.stream.read_exact (2)
if not head: if not head:
...@@ -175,10 +176,10 @@ class websocket: ...@@ -175,10 +176,10 @@ class websocket:
pass pass
elif plen == 126: elif plen == 126:
plen, = struct.unpack ('>H', self.stream.read_exact (2)) plen, = struct.unpack ('>H', self.stream.read_exact (2))
else: # plen == 127: else: # plen == 127:
plen, = struct.unpack ('>Q', self.stream.read_exact (8)) plen, = struct.unpack ('>Q', self.stream.read_exact (8))
p.plen = plen p.plen = plen
if plen > 1<<20: if plen > 1 << 20:
raise TooMuchData (plen) raise TooMuchData (plen)
if p.mask: if p.mask:
p.masking = struct.unpack ('>BBBB', self.stream.read_exact (4)) p.masking = struct.unpack ('>BBBB', self.stream.read_exact (4))
...@@ -192,7 +193,7 @@ class websocket: ...@@ -192,7 +193,7 @@ class websocket:
return True return True
elif p.opcode == 9: elif p.opcode == 9:
# ping # ping
assert (p.fin) # probably up to no good... assert (p.fin) # probably up to no good...
self.send_pong (self, p.payload) self.send_pong (self, p.payload)
return False return False
else: else:
...@@ -212,7 +213,7 @@ class websocket: ...@@ -212,7 +213,7 @@ class websocket:
break break
finally: finally:
self.conn.close() self.conn.close()
def read_packet_hixie_76 (self): def read_packet_hixie_76 (self):
ftype = self.stream.read_exact (1) ftype = self.stream.read_exact (1)
if not ftype: if not ftype:
...@@ -225,7 +226,7 @@ class websocket: ...@@ -225,7 +226,7 @@ class websocket:
length = (length << 7) | (b & 0x7f) length = (length << 7) | (b & 0x7f)
if not b & 0x80: if not b & 0x80:
break break
if length > 1<<20: if length > 1 << 20:
raise TooMuchData (length) raise TooMuchData (length)
if length: if length:
payload = self.stream.read_exact (length) payload = self.stream.read_exact (length)
...@@ -240,7 +241,7 @@ class websocket: ...@@ -240,7 +241,7 @@ class websocket:
p.mask = None p.mask = None
p.payload = data[:-1] p.payload = data[:-1]
self.handle_packet (p) self.handle_packet (p)
# --- # ---
def handle_packet (self, p): def handle_packet (self, p):
...@@ -270,13 +271,13 @@ class websocket: ...@@ -270,13 +271,13 @@ class websocket:
ld = len (data) ld = len (data)
if ld < 126: if ld < 126:
head |= ld head |= ld
p = [ struct.pack ('>H', head), data ] p = [struct.pack ('>H', head), data]
elif ld < 1<<16: elif ld < 1 << 16:
head |= 126 head |= 126
p = [ struct.pack ('>HH', head, ld), data ] p = [struct.pack ('>HH', head, ld), data]
elif ld < 1<<32: elif ld < 1 << 32:
head |= 127 head |= 127
p = [ struct.pack ('>HQ', head, ld), data ] p = [struct.pack ('>HQ', head, ld), data]
else: else:
raise TooMuchData (ld) raise TooMuchData (ld)
# RFC6455: A server MUST NOT mask any frames that it sends to the client. # RFC6455: A server MUST NOT mask any frames that it sends to the client.
......
...@@ -45,7 +45,7 @@ class LDAP: ...@@ -45,7 +45,7 @@ class LDAP:
SearchRequest = 3 SearchRequest = 3
SearchResultEntry = 4 SearchResultEntry = 4
SearchResultDone = 5 SearchResultDone = 5
SearchResultReference = 19 # <--- NOT IN SEQUENCE SearchResultReference = 19 # <--- NOT IN SEQUENCE
ModifyRequest = 6 ModifyRequest = 6
ModifyResponse = 7 ModifyResponse = 7
AddRequest = 8 AddRequest = 8
...@@ -57,7 +57,7 @@ class LDAP: ...@@ -57,7 +57,7 @@ class LDAP:
CompareRequest = 14 CompareRequest = 14
CompareResponse = 15 CompareResponse = 15
AbandonRequest = 16 AbandonRequest = 16
ExtendedRequest = 23 # <--- NOT IN SEQUENCE ExtendedRequest = 23 # <--- NOT IN SEQUENCE
ExtendedResponse = 24 ExtendedResponse = 24
class SCOPE: class SCOPE:
...@@ -81,7 +81,7 @@ def encode_search_request ( ...@@ -81,7 +81,7 @@ def encode_search_request (
filter, filter,
which_attrs=None, which_attrs=None,
compatibility={} compatibility={}
): ):
if scope is None: if scope is None:
scope = compatibility.get('scope', SCOPE.SUBTREE) scope = compatibility.get('scope', SCOPE.SUBTREE)
if which_attrs is None: if which_attrs is None:
...@@ -95,7 +95,7 @@ def encode_search_request ( ...@@ -95,7 +95,7 @@ def encode_search_request (
# different here, hence the lookup in the compatibility dict. # different here, hence the lookup in the compatibility dict.
which_attrs = SEQUENCE ( which_attrs = SEQUENCE (
OCTET_STRING (compatibility.get ('no_attr_attr', '1.1')) OCTET_STRING (compatibility.get ('no_attr_attr', '1.1'))
) )
else: else:
which_attrs = SEQUENCE (*[OCTET_STRING (x) for x in which_attrs]) which_attrs = SEQUENCE (*[OCTET_STRING (x) for x in which_attrs])
return TLV ( return TLV (
...@@ -108,7 +108,7 @@ def encode_search_request ( ...@@ -108,7 +108,7 @@ def encode_search_request (
BOOLEAN (types_only), BOOLEAN (types_only),
parse_query (filter), parse_query (filter),
which_attrs, which_attrs,
) )
class AUTH: class AUTH:
# 1 and 2 are reserved # 1 and 2 are reserved
...@@ -195,7 +195,7 @@ class Error (Exception): ...@@ -195,7 +195,7 @@ class Error (Exception):
RESULT._reverse_map = r = {} RESULT._reverse_map = r = {}
for attr in dir(RESULT): for attr in dir(RESULT):
value = getattr (RESULT, attr) value = getattr (RESULT, attr)
if (type(value) == type(0)): if isinstance(value, type(0)):
r[value] = attr r[value] = attr
def result_string (result): def result_string (result):
...@@ -211,7 +211,7 @@ def encode_bind_request (version, name, auth_data): ...@@ -211,7 +211,7 @@ def encode_bind_request (version, name, auth_data):
INTEGER (version), INTEGER (version),
OCTET_STRING (name), OCTET_STRING (name),
auth_data auth_data
) )
def encode_simple_bind (version, name, login): def encode_simple_bind (version, name, login):
return encode_bind_request ( return encode_bind_request (
...@@ -220,8 +220,8 @@ def encode_simple_bind (version, name, login): ...@@ -220,8 +220,8 @@ def encode_simple_bind (version, name, login):
TLV ( TLV (
CHOICE (AUTH.simple, 0), CHOICE (AUTH.simple, 0),
login login
)
) )
)
def encode_sasl_bind (version, name, mechanism, credentials=''): def encode_sasl_bind (version, name, mechanism, credentials=''):
if credentials: if credentials:
...@@ -235,15 +235,15 @@ def encode_sasl_bind (version, name, mechanism, credentials=''): ...@@ -235,15 +235,15 @@ def encode_sasl_bind (version, name, mechanism, credentials=''):
CHOICE (AUTH.sasl), CHOICE (AUTH.sasl),
OCTET_STRING (mechanism), OCTET_STRING (mechanism),
cred cred
)
) )
)
def encode_starttls (): def encode_starttls ():
# encode STARTTLS request: RFC 2830, 2.1 # encode STARTTLS request: RFC 2830, 2.1
return TLV ( return TLV (
APPLICATION (LDAP.ExtendedRequest), APPLICATION (LDAP.ExtendedRequest),
TLV (CHOICE (0, 0), '1.3.6.1.4.1.1466.20037') TLV (CHOICE (0, 0), '1.3.6.1.4.1.1466.20037')
) )
class client: class client:
...@@ -286,7 +286,7 @@ class client: ...@@ -286,7 +286,7 @@ class client:
if not tl: if not tl:
return [None, None] return [None, None]
tag = tl[0] tag = tl[0]
if tag != '0': # SEQUENCE | STRUCTURED if tag != '0': # SEQUENCE | STRUCTURED
raise ProtocolError ('bad tag byte: %r' % (tag,)) raise ProtocolError ('bad tag byte: %r' % (tag,))
l = ord (tl[1]) l = ord (tl[1])
p = [tl] p = [tl]
...@@ -338,9 +338,9 @@ class client: ...@@ -338,9 +338,9 @@ class client:
del self.pending[msgid] del self.pending[msgid]
# server replies NO: # server replies NO:
#starttls decoded=[1, ('application', 24, [2, '', 'unsupported extended operation'])] # starttls decoded=[1, ('application', 24, [2, '', 'unsupported extended operation'])]
# server replies YES: # server replies YES:
#starttls decoded=[1, ('application', 24, [0, '', ''])] # starttls decoded=[1, ('application', 24, [0, '', ''])]
exit_recv_thread = False exit_recv_thread = False
...@@ -360,6 +360,7 @@ class client: ...@@ -360,6 +360,7 @@ class client:
return reply return reply
ldap_protocol_version = 3 ldap_protocol_version = 3
def simple_bind (self, name, login): def simple_bind (self, name, login):
return self.send_message (encode_simple_bind (self.ldap_protocol_version, name, login)) return self.send_message (encode_simple_bind (self.ldap_protocol_version, name, login))
...@@ -377,11 +378,11 @@ def t0(): ...@@ -377,11 +378,11 @@ def t0():
0, 0,
0, 0,
'(&(objectclass=inetorgperson)(userid=srushing))', '(&(objectclass=inetorgperson)(userid=srushing))',
#'(&(objectclass=inetorgperson)(userid=newton))', # '(&(objectclass=inetorgperson)(userid=newton))',
# ask for these specific attributes only # ask for these specific attributes only
['mailAlternateAddress', 'rfc822ForwardingMailbox'] ['mailAlternateAddress', 'rfc822ForwardingMailbox']
)
) )
)
import pprint import pprint
import socket import socket
......
...@@ -18,7 +18,7 @@ pq_tests = [ ...@@ -18,7 +18,7 @@ pq_tests = [
15)), 15)),
# nary expressions # nary expressions
('(|(a=b)(b=c)(c=d)(e=f)(f=g)(h=i))', ('(|(a=b)(b=c)(c=d)(e=f)(f=g)(h=i))',
((C, 1, [(C, 3, ['a', 'b']), (C, 3, ['b', 'c']), (C, 3, ['c', 'd']), (C, 3, ['e', 'f']), (C, 3, ['f', 'g']), (C, 3, ['h', 'i'])]), ((C, 1, [(C, 3, ['a', 'b']), (C, 3, ['b', 'c']), (C, 3, ['c', 'd']), (C, 3, ['e', 'f']), (C, 3, ['f', 'g']), (C, 3, ['h', 'i'])]), # noqa
50)), 50)),
('(|(!(a=*))(&(b=c)(d=e))(x<=y))', ('(|(!(a=*))(&(b=c)(d=e))(x<=y))',
((C, 1, [(C, 2, [(C, 7, 'a')]), (C, 0, [(C, 3, ['b', 'c']), (C, 3, ['d', 'e'])]), (C, 6, ['x', 'y'])]), ((C, 1, [(C, 2, [(C, 7, 'a')]), (C, 0, [(C, 3, ['b', 'c']), (C, 3, ['d', 'e'])]), (C, 6, ['x', 'y'])]),
...@@ -37,7 +37,7 @@ pq_tests = [ ...@@ -37,7 +37,7 @@ pq_tests = [
('(a=', QuerySyntaxError), ('(a=', QuerySyntaxError),
('(a<b)', QuerySyntaxError), ('(a<b)', QuerySyntaxError),
# good hex escape # good hex escape
('(a=some\\AAthing)',((C, 3, ['a', 'some\252thing']), 17)), ('(a=some\\AAthing)', ((C, 3, ['a', 'some\252thing']), 17)),
# bad hex escape # bad hex escape
('(a=some\\AZthing)', QuerySyntaxError), ('(a=some\\AZthing)', QuerySyntaxError),
# upper/lower case hex escape # upper/lower case hex escape
...@@ -49,14 +49,14 @@ pq_tests = [ ...@@ -49,14 +49,14 @@ pq_tests = [
# junk/illegal # junk/illegal
('junk', QuerySyntaxError), ('junk', QuerySyntaxError),
# lots of parens # lots of parens
(('('*100), QuerySyntaxError), (('(' * 100), QuerySyntaxError),
# expression too complex # expression too complex
(('(!' * 55) + '(x=y)' + (')' * 55), QuerySyntaxError), (('(!' * 55) + '(x=y)' + (')' * 55), QuerySyntaxError),
# expression not too complex # expression not too complex
(('(!' * 10) + '(x=y)' + (')' * 10), (('(!' * 10) + '(x=y)' + (')' * 10),
((C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 3, ['x', 'y'])])])])])])])])])])]), ((C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 2, [(C, 3, ['x', 'y'])])])])])])])])])])]), # noqa
28)), 28)),
] ]
class parse_query_test (unittest.TestCase): class parse_query_test (unittest.TestCase):
def runTest (self): def runTest (self):
......
This diff is collapsed.
This diff is collapsed.
...@@ -65,7 +65,7 @@ class Connection_Service(SSH_Service): ...@@ -65,7 +65,7 @@ class Connection_Service(SSH_Service):
SSH_MSG_CHANNEL_OPEN_FAILURE: self.msg_channel_open_failure, SSH_MSG_CHANNEL_OPEN_FAILURE: self.msg_channel_open_failure,
# server side # server side
SSH_MSG_CHANNEL_OPEN: self.msg_channel_open, SSH_MSG_CHANNEL_OPEN: self.msg_channel_open,
} }
self.transport.register_callbacks('ssh-connection', callbacks) self.transport.register_callbacks('ssh-connection', callbacks)
def register_channel(self, channel): def register_channel(self, channel):
...@@ -74,7 +74,7 @@ class Connection_Service(SSH_Service): ...@@ -74,7 +74,7 @@ class Connection_Service(SSH_Service):
local_channels dictionary and to set the channel id. local_channels dictionary and to set the channel id.
""" """
channel.channel_id = self.next_channel_id channel.channel_id = self.next_channel_id
assert not self.local_channels.has_key(channel.channel_id) assert channel.channel_id not in self.local_channels
self.next_channel_id += 1 # XXX: Overflow? self.next_channel_id += 1 # XXX: Overflow?
self.local_channels[channel.channel_id] = channel self.local_channels[channel.channel_id] = channel
...@@ -88,7 +88,9 @@ class Connection_Service(SSH_Service): ...@@ -88,7 +88,9 @@ class Connection_Service(SSH_Service):
msg, channel_id, bytes_to_add = ssh_packet.unpack_payload(SSH_MSG_CHANNEL_WINDOW_ADJUST_PAYLOAD, pkt) msg, channel_id, bytes_to_add = ssh_packet.unpack_payload(SSH_MSG_CHANNEL_WINDOW_ADJUST_PAYLOAD, pkt)
channel = self.local_channels[channel_id] channel = self.local_channels[channel_id]
channel.remote_channel.window_data_left += bytes_to_add channel.remote_channel.window_data_left += bytes_to_add
self.transport.debug.write(ssh_debug.DEBUG_3, 'channel %i window increased by %i to %i', (channel.remote_channel.channel_id, bytes_to_add, channel.remote_channel.window_data_left)) self.transport.debug.write(ssh_debug.DEBUG_3, 'channel %i window increased by %i to %i',
(channel.remote_channel.channel_id, bytes_to_add,
channel.remote_channel.window_data_left))
channel.window_data_added_cv.wake_all() channel.window_data_added_cv.wake_all()
def msg_channel_data(self, pkt): def msg_channel_data(self, pkt):
...@@ -96,7 +98,8 @@ class Connection_Service(SSH_Service): ...@@ -96,7 +98,8 @@ class Connection_Service(SSH_Service):
channel = self.local_channels[channel_id] channel = self.local_channels[channel_id]
# XXX: In theory, we should verify that len(data) <= channel.max_packet_size # XXX: In theory, we should verify that len(data) <= channel.max_packet_size
if len(data) > channel.window_data_left: if len(data) > channel.window_data_left:
self.transport.debug.write(ssh_debug.WARNING, 'channel %i %i bytes overflowed window of %i', (channel.channel_id, len(data), channel.remote_channel.window_data_left)) self.transport.debug.write(ssh_debug.WARNING, 'channel %i %i bytes overflowed window of %i',
(channel.channel_id, len(data), channel.remote_channel.window_data_left))
# Data is ignored. # Data is ignored.
else: else:
channel.window_data_left -= len(data) channel.window_data_left -= len(data)
...@@ -106,7 +109,8 @@ class Connection_Service(SSH_Service): ...@@ -106,7 +109,8 @@ class Connection_Service(SSH_Service):
msg, channel_id, data_type_code, data = ssh_packet.unpack_payload(SSH_MSG_CHANNEL_EXTENDED_DATA_PAYLOAD, pkt) msg, channel_id, data_type_code, data = ssh_packet.unpack_payload(SSH_MSG_CHANNEL_EXTENDED_DATA_PAYLOAD, pkt)
channel = self.local_channels[channel_id] channel = self.local_channels[channel_id]
if len(data) > channel.window_data_left: if len(data) > channel.window_data_left:
self.transport.debug.write(ssh_debug.WARNING, 'channel %i %i bytes overflowed window of %i', (channel.channel_id, len(data), channel.remote_channel.window_data_left)) self.transport.debug.write(ssh_debug.WARNING, 'channel %i %i bytes overflowed window of %i',
(channel.channel_id, len(data), channel.remote_channel.window_data_left))
# Data is ignored. # Data is ignored.
else: else:
channel.window_data_left -= len(data) channel.window_data_left -= len(data)
...@@ -149,14 +153,17 @@ class Connection_Service(SSH_Service): ...@@ -149,14 +153,17 @@ class Connection_Service(SSH_Service):
def msg_channel_open_confirmation(self, pkt): def msg_channel_open_confirmation(self, pkt):
data, offset = ssh_packet.unpack_payload_get_offset(SSH_MSG_CHANNEL_OPEN_CONFIRMATION_PAYLOAD, pkt) data, offset = ssh_packet.unpack_payload_get_offset(SSH_MSG_CHANNEL_OPEN_CONFIRMATION_PAYLOAD, pkt)
msg, recipient_channel, sender_channel, window_size, max_packet_size = data msg, recipient_channel, sender_channel, window_size, max_packet_size = data
self.transport.debug.write(ssh_debug.DEBUG_1, 'channel %i open confirmation sender_channel=%i window_size=%i max_packet_size=%i', (recipient_channel, sender_channel, window_size, max_packet_size)) self.transport.debug.write(
ssh_debug.DEBUG_1,
'channel %i open confirmation sender_channel=%i window_size=%i max_packet_size=%i',
(recipient_channel, sender_channel, window_size, max_packet_size))
channel = self.local_channels[recipient_channel] channel = self.local_channels[recipient_channel]
# XXX: Assert that the channel is not already open? # XXX: Assert that the channel is not already open?
channel.closed = 0 channel.closed = 0
channel.eof = 0 channel.eof = 0
channel.remote_channel.closed = 0 channel.remote_channel.closed = 0
channel.remote_channel.channel_id = sender_channel channel.remote_channel.channel_id = sender_channel
assert not self.remote_channels.has_key(sender_channel) assert sender_channel not in self.remote_channels
self.remote_channels[sender_channel] = channel.remote_channel self.remote_channels[sender_channel] = channel.remote_channel
channel.remote_channel.window_size = window_size channel.remote_channel.window_size = window_size
channel.remote_channel.window_data_left = window_size channel.remote_channel.window_data_left = window_size
...@@ -165,7 +172,8 @@ class Connection_Service(SSH_Service): ...@@ -165,7 +172,8 @@ class Connection_Service(SSH_Service):
channel.channel_open_success(additional_data) channel.channel_open_success(additional_data)
def msg_channel_open_failure(self, pkt): def msg_channel_open_failure(self, pkt):
msg, channel_id, reason_code, reason_text, language = ssh_packet.unpack_payload(SSH_MSG_CHANNEL_OPEN_FAILURE_PAYLOAD, pkt) msg, channel_id, reason_code, reason_text, language = ssh_packet.unpack_payload(
SSH_MSG_CHANNEL_OPEN_FAILURE_PAYLOAD, pkt)
channel = self.local_channels[channel_id] channel = self.local_channels[channel_id]
# XXX: Assert that the channel is not already open? # XXX: Assert that the channel is not already open?
channel.channel_open_failure(reason_code, reason_text, language) channel.channel_open_failure(reason_code, reason_text, language)
...@@ -174,7 +182,8 @@ class Connection_Service(SSH_Service): ...@@ -174,7 +182,8 @@ class Connection_Service(SSH_Service):
# server side # server side
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
def msg_channel_open (self, pkt): def msg_channel_open (self, pkt):
_, channel_type, remote_id, initial_window, max_packet_size = ssh_packet.unpack_payload (SSH_MSG_CHANNEL_OPEN_PAYLOAD, pkt) _, channel_type, remote_id, initial_window, max_packet_size = ssh_packet.unpack_payload (
SSH_MSG_CHANNEL_OPEN_PAYLOAD, pkt)
channel = self.new_channel_class (self) channel = self.new_channel_class (self)
self.register_channel (channel) self.register_channel (channel)
channel.remote_channel.closed = 0 channel.remote_channel.closed = 0
...@@ -185,11 +194,11 @@ class Connection_Service(SSH_Service): ...@@ -185,11 +194,11 @@ class Connection_Service(SSH_Service):
channel.channel_id, channel.channel_id,
initial_window, initial_window,
max_packet_size, max_packet_size,
)
) )
)
self.transport.debug.write ( self.transport.debug.write (
ssh_debug.DEBUG_1, ssh_debug.DEBUG_1,
'channel %i open confirmation sender_channel=%i window_size=%i max_packet_size=%i', ( 'channel %i open confirmation sender_channel=%i window_size=%i max_packet_size=%i', (
remote_id, channel.channel_id, initial_window, max_packet_size remote_id, channel.channel_id, initial_window, max_packet_size
)
) )
)
...@@ -51,10 +51,10 @@ SSH_MSG_CHANNEL_OPEN_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN ...@@ -51,10 +51,10 @@ SSH_MSG_CHANNEL_OPEN_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN
# This is the basic confirmation payload. Different session types may add # This is the basic confirmation payload. Different session types may add
# addition information to this. # addition information to this.
SSH_MSG_CHANNEL_OPEN_CONFIRMATION_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN_CONFIRMATION, SSH_MSG_CHANNEL_OPEN_CONFIRMATION_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN_CONFIRMATION,
packet.UINT32, # recipient channel packet.UINT32, # recipient channel
packet.UINT32, # sender channel packet.UINT32, # sender channel
packet.UINT32, # initial window size packet.UINT32, # initial window size
packet.UINT32) # maximum packet size packet.UINT32) # maximum packet size
SSH_MSG_CHANNEL_OPEN_FAILURE_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN_FAILURE SSH_MSG_CHANNEL_OPEN_FAILURE_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_OPEN_FAILURE
packet.UINT32, # recipient channel packet.UINT32, # recipient channel
...@@ -77,17 +77,17 @@ SSH_MSG_GLOBAL_REQUEST_SUCCESS_PAYLOAD = (packet.BYTE) # SSH_MSG_GLOBAL_REQU ...@@ -77,17 +77,17 @@ SSH_MSG_GLOBAL_REQUEST_SUCCESS_PAYLOAD = (packet.BYTE) # SSH_MSG_GLOBAL_REQU
SSH_MSG_GLOBAL_REQUEST_FAILURE_PAYLOAD = (packet.BYTE) # SSH_MSG_GLOBAL_REQUEST_FAILURE SSH_MSG_GLOBAL_REQUEST_FAILURE_PAYLOAD = (packet.BYTE) # SSH_MSG_GLOBAL_REQUEST_FAILURE
SSH_MSG_CHANNEL_WINDOW_ADJUST_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_WINDOW_ADJUST SSH_MSG_CHANNEL_WINDOW_ADJUST_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_WINDOW_ADJUST
packet.UINT32, # recipient channel packet.UINT32, # recipient channel
packet.UINT32) # bytes to add packet.UINT32) # bytes to add
SSH_MSG_CHANNEL_DATA_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_DATA SSH_MSG_CHANNEL_DATA_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_DATA
packet.UINT32, # recipient channel packet.UINT32, # recipient channel
packet.STRING) # data packet.STRING) # data
SSH_MSG_CHANNEL_EXTENDED_DATA_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_EXTENDED_DATA SSH_MSG_CHANNEL_EXTENDED_DATA_PAYLOAD = (packet.BYTE, # SSH_MSG_CHANNEL_EXTENDED_DATA
packet.UINT32, # recipient channel packet.UINT32, # recipient channel
packet.UINT32, # data_type_code packet.UINT32, # data_type_code
packet.STRING) # data packet.STRING) # data
SSH_EXTENDED_DATA_STDERR = 1 SSH_EXTENDED_DATA_STDERR = 1
......
This diff is collapsed.
...@@ -40,15 +40,15 @@ class Term_Mode_Builder: ...@@ -40,15 +40,15 @@ class Term_Mode_Builder:
TTY_OP_END = 0 # Indicates end of options. TTY_OP_END = 0 # Indicates end of options.
VINTR = 1 # Interrupt character; 255 if none. Similarly for the VINTR = 1 # Interrupt character; 255 if none. Similarly for the
# other characters. Not all of these characters are # other characters. Not all of these characters are
# supported on all systems. # supported on all systems.
VQUIT = 2 # The quit character (sends SIGQUIT signal on POSIX VQUIT = 2 # The quit character (sends SIGQUIT signal on POSIX
# systems). # systems).
VERASE = 3 # Erase the character to left of the cursor. VERASE = 3 # Erase the character to left of the cursor.
VKILL = 4 # Kill the current input line. VKILL = 4 # Kill the current input line.
VEOF = 5 # End-of-file character (sends EOF from the terminal). VEOF = 5 # End-of-file character (sends EOF from the terminal).
VEOL = 6 # End-of-line character in addition to carriage return VEOL = 6 # End-of-line character in addition to carriage return
# and/or linefeed. # and/or linefeed.
VEOL2 = 7 # Additional end-of-line character. VEOL2 = 7 # Additional end-of-line character.
VSTART = 8 # Continues paused output (normally control-Q). VSTART = 8 # Continues paused output (normally control-Q).
VSTOP = 9 # Pauses output (normally control-S). VSTOP = 9 # Pauses output (normally control-S).
...@@ -57,13 +57,13 @@ VDSUSP = 11 # Another suspend character. ...@@ -57,13 +57,13 @@ VDSUSP = 11 # Another suspend character.
VREPRINT = 12 # Reprints the current input line. VREPRINT = 12 # Reprints the current input line.
VWERASE = 13 # Erases a word left of cursor. VWERASE = 13 # Erases a word left of cursor.
VLNEXT = 14 # Enter the next character typed literally, even if it VLNEXT = 14 # Enter the next character typed literally, even if it
# is a special character # is a special character
VFLUSH = 15 # Character to flush output. VFLUSH = 15 # Character to flush output.
VSWTCH = 16 # Switch to a different shell layer. VSWTCH = 16 # Switch to a different shell layer.
VSTATUS = 17 # Prints system status line (load, command, pid etc). VSTATUS = 17 # Prints system status line (load, command, pid etc).
VDISCARD = 18 # Toggles the flushing of terminal output. VDISCARD = 18 # Toggles the flushing of terminal output.
IGNPAR = 30 # The ignore parity flag. The parameter SHOULD be 0 if IGNPAR = 30 # The ignore parity flag. The parameter SHOULD be 0 if
# this flag is FALSE set, and 1 if it is TRUE. # this flag is FALSE set, and 1 if it is TRUE.
PARMRK = 31 # Mark parity and framing errors. PARMRK = 31 # Mark parity and framing errors.
INPCK = 32 # Enable checking of parity errors. INPCK = 32 # Enable checking of parity errors.
ISTRIP = 33 # Strip 8th bit off characters. ISTRIP = 33 # Strip 8th bit off characters.
...@@ -78,7 +78,7 @@ IMAXBEL = 41 # Ring bell on input queue full. ...@@ -78,7 +78,7 @@ IMAXBEL = 41 # Ring bell on input queue full.
ISIG = 50 # Enable signals INTR, QUIT, [D]SUSP. ISIG = 50 # Enable signals INTR, QUIT, [D]SUSP.
ICANON = 51 # Canonicalize input lines. ICANON = 51 # Canonicalize input lines.
XCASE = 52 # Enable input and output of uppercase characters by XCASE = 52 # Enable input and output of uppercase characters by
# preceding their lowercase equivalents with `\'. # preceding their lowercase equivalents with `\'.
ECHO = 53 # Enable echoing. ECHO = 53 # Enable echoing.
ECHOE = 54 # Visually erase chars. ECHOE = 54 # Visually erase chars.
ECHOK = 55 # Kill character discards current line. ECHOK = 55 # Kill character discards current line.
...@@ -100,5 +100,5 @@ CS8 = 91 # 8 bit mode. ...@@ -100,5 +100,5 @@ CS8 = 91 # 8 bit mode.
PARENB = 92 # Parity enable. PARENB = 92 # Parity enable.
PARODD = 93 # Odd parity, else even. PARODD = 93 # Odd parity, else even.
TTY_OP_ISPEED = 128 # Specifies the input baud rate in bits per second. TTY_OP_ISPEED = 128 # Specifies the input baud rate in bits per second.
TTY_OP_OSPEED = 129 # Specifies the output baud rate in bits per second. TTY_OP_OSPEED = 129 # Specifies the output baud rate in bits per second.
...@@ -33,8 +33,9 @@ OekNfzzIBr6QkMvmIOuL ...@@ -33,8 +33,9 @@ OekNfzzIBr6QkMvmIOuL
ks = OpenSSH_Key_Storage() ks = OpenSSH_Key_Storage()
server_key_ob = ks.parse_private_key (server_key_pri) server_key_ob = ks.parse_private_key (server_key_pri)
# will authentication user 'foo' with password 'bar' for the 'ssh-connection' service [the only service currently supported] # will authentication user 'foo' with password 'bar' for the
pwd_auth = coro.ssh.auth.userauth.Password_Authenticator ({'foo' : { 'ssh-connection' : 'bar' } }) # 'ssh-connection' service [the only service currently supported]
pwd_auth = coro.ssh.auth.userauth.Password_Authenticator ({'foo': {'ssh-connection': 'bar'}})
# how to add public-key authentication: # how to add public-key authentication:
# #
...@@ -61,11 +62,11 @@ def main(): ...@@ -61,11 +62,11 @@ def main():
sys.exit(1) sys.exit(1)
for option, value in optlist: for option, value in optlist:
if option=='-p': if option == '-p':
port = int (value) port = int (value)
coro.spawn (coro.backdoor.ssh_server, port, '', server_key_ob, [pwd_auth]) coro.spawn (coro.backdoor.ssh_server, port, '', server_key_ob, [pwd_auth])
coro.event_loop() coro.event_loop()
if __name__=='__main__': if __name__ == '__main__':
main() main()
...@@ -20,7 +20,7 @@ class client: ...@@ -20,7 +20,7 @@ class client:
self.ip = ip self.ip = ip
self.port = port self.port = port
self.username = username self.username = username
def open (self): def open (self):
client = SSH_Client_Transport() client = SSH_Client_Transport()
transport = coro_socket_transport (self.ip, port=self.port, hostname=self.hostname) transport = coro_socket_transport (self.ip, port=self.port, hostname=self.hostname)
...@@ -60,4 +60,3 @@ if __name__ == '__main__': ...@@ -60,4 +60,3 @@ if __name__ == '__main__':
else: else:
coro.spawn (go, *sys.argv[1:]) coro.spawn (go, *sys.argv[1:])
coro.event_loop() coro.event_loop()
...@@ -118,10 +118,10 @@ class SSH_Key_Exchange: ...@@ -118,10 +118,10 @@ class SSH_Key_Exchange:
""" """
shared_secret = ssh_packet.pack_payload((ssh_packet.MPINT,), (self.shared_secret,)) shared_secret = ssh_packet.pack_payload((ssh_packet.MPINT,), (self.shared_secret,))
key = self.get_hash_object( key = self.get_hash_object(
shared_secret, shared_secret,
self.exchange_hash, self.exchange_hash,
letter, letter,
self.session_id).digest() self.session_id).digest()
if len(key) > required_size: if len(key) > required_size:
# Key is too big...return only what is needed. # Key is too big...return only what is needed.
key = key[:required_size] key = key[:required_size]
...@@ -132,11 +132,14 @@ class SSH_Key_Exchange: ...@@ -132,11 +132,14 @@ class SSH_Key_Exchange:
# K3 = HASH(K || H || K1 || K2) # K3 = HASH(K || H || K1 || K2)
# ... # ...
# key = K1 || K2 || K3 || ... # key = K1 || K2 || K3 || ...
self.transport.debug.write(ssh_debug.DEBUG_2, 'get_encryption_key: computed key is too small len(key)=%i required_size=%i', (len(key), required_size)) self.transport.debug.write(
ssh_debug.DEBUG_2, 'get_encryption_key: computed key is too small len(key)=%i required_size=%i',
(len(key), required_size))
key_data = [key] key_data = [key]
key_data_len = len(key) key_data_len = len(key)
while key_data_len < required_size: while key_data_len < required_size:
additional_key_data = self.get_hash_object(shared_secret, self.exchange_hash, ''.join(key_data)).digest() additional_key_data = self.get_hash_object(
shared_secret, self.exchange_hash, ''.join(key_data)).digest()
key_data.append(additional_key_data) key_data.append(additional_key_data)
key_data_len += len(additional_key_data) key_data_len += len(additional_key_data)
key = ''.join(key_data)[:required_size] key = ''.join(key_data)[:required_size]
...@@ -145,7 +148,8 @@ class SSH_Key_Exchange: ...@@ -145,7 +148,8 @@ class SSH_Key_Exchange:
pass pass
return key return key
def set_info(self, c2s_version_string, s2c_version_string, c2s_kexinit_packet, s2c_kexinit_packet, supported_server_keys): def set_info(self, c2s_version_string, s2c_version_string,
c2s_kexinit_packet, s2c_kexinit_packet, supported_server_keys):
self.c2s_version_string = c2s_version_string self.c2s_version_string = c2s_version_string
self.s2c_version_string = s2c_version_string self.s2c_version_string = s2c_version_string
self.c2s_kexinit_packet = c2s_kexinit_packet self.c2s_kexinit_packet = c2s_kexinit_packet
...@@ -153,8 +157,8 @@ class SSH_Key_Exchange: ...@@ -153,8 +157,8 @@ class SSH_Key_Exchange:
self.supported_server_keys = supported_server_keys self.supported_server_keys = supported_server_keys
def get_key_algorithm(self, key): def get_key_algorithm(self, key):
name = ssh_packet.unpack_payload( (ssh_packet.STRING,), key)[0] name = ssh_packet.unpack_payload((ssh_packet.STRING,), key)[0]
for key_alg in self.supported_server_keys: for key_alg in self.supported_server_keys:
if key_alg.name == name: if key_alg.name == name:
return key_alg return key_alg
raise ValueError, name raise ValueError(name)
...@@ -39,7 +39,7 @@ from coro.ssh.keys import parse_public_key ...@@ -39,7 +39,7 @@ from coro.ssh.keys import parse_public_key
from coro.ssh.util.mpint import pack_mpint from coro.ssh.util.mpint import pack_mpint
# 2**1024 - 2**960 - 1 + 2**64 * floor( 2**894 Pi + 129093 ) # 2**1024 - 2**960 - 1 + 2**64 * floor( 2**894 Pi + 129093 )
DH_PRIME = 179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194467627007L DH_PRIME = 179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194467627007L # noqa
DH_GENERATOR = 2L DH_GENERATOR = 2L
SSH_MSG_KEXDH_INIT = 30 SSH_MSG_KEXDH_INIT = 30
...@@ -49,10 +49,10 @@ def hexdump(src, length=16): ...@@ -49,10 +49,10 @@ def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)]) FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = [] lines = []
for c in xrange(0, len(src), length): for c in xrange(0, len(src), length):
chars = src[c:c+length] chars = src[c:c + length]
hex = ' '.join(["%02x" % ord(x) for x in chars]) hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars]) printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable)) lines.append("%04x %-*s %s\n" % (c, length * 3, hex, printable))
return ''.join(lines) return ''.join(lines)
class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
...@@ -65,7 +65,7 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -65,7 +65,7 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
client_random_value = '' # x client_random_value = '' # x
client_exchange_value = 0L # e client_exchange_value = 0L # e
server_public_host_key = None # k_s server_public_host_key = None # k_s
server_random_value = '' # y server_random_value = '' # y
server_exchange_value = 0L # f server_exchange_value = 0L # f
...@@ -80,9 +80,9 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -80,9 +80,9 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
# compute e=g**x mod p # compute e=g**x mod p
self.client_exchange_value = pow(DH_GENERATOR, self.client_random_value, DH_PRIME) self.client_exchange_value = pow(DH_GENERATOR, self.client_random_value, DH_PRIME)
return ssh_packet.pack_payload(KEXDH_INIT_PAYLOAD, return ssh_packet.pack_payload(KEXDH_INIT_PAYLOAD,
(SSH_MSG_KEXDH_INIT, (SSH_MSG_KEXDH_INIT,
self.client_exchange_value) self.client_exchange_value)
) )
def get_initial_server_kex_packet(self): def get_initial_server_kex_packet(self):
return None return None
...@@ -122,7 +122,7 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -122,7 +122,7 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
self.client_exchange_value, self.client_exchange_value,
self.server_exchange_value, self.server_exchange_value,
self.shared_secret self.shared_secret
) )
H = ssh_packet.pack_payload (KEXDH_HASH_PAYLOAD, payload_inputs) H = ssh_packet.pack_payload (KEXDH_HASH_PAYLOAD, payload_inputs)
self.exchange_hash = hashlib.sha1(H).digest() self.exchange_hash = hashlib.sha1(H).digest()
if self.session_id is None: if self.session_id is None:
...@@ -135,15 +135,16 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -135,15 +135,16 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
K_S, K_S,
self.server_exchange_value, self.server_exchange_value,
H_sig H_sig
)
) )
)
self.transport.send_packet (packet) self.transport.send_packet (packet)
def msg_kexdh_reply(self, packet): def msg_kexdh_reply(self, packet):
# string server public host key and certificates (K_S) # string server public host key and certificates (K_S)
# mpint f # mpint f
# string signature of H # string signature of H
msg, public_host_key, server_exchange_value, signature_of_h = ssh_packet.unpack_payload(KEXDH_REPLY_PAYLOAD, packet) msg, public_host_key, server_exchange_value, signature_of_h = ssh_packet.unpack_payload(
KEXDH_REPLY_PAYLOAD, packet)
# Create a SSH_Public_Private_Key instance from the packed string. # Create a SSH_Public_Private_Key instance from the packed string.
self.server_public_host_key = parse_public_key(public_host_key) self.server_public_host_key = parse_public_key(public_host_key)
...@@ -152,8 +153,10 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -152,8 +153,10 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
self.transport.verify_public_host_key(self.server_public_host_key) self.transport.verify_public_host_key(self.server_public_host_key)
# Make sure f is a valid number # Make sure f is a valid number
if server_exchange_value <= 1 or server_exchange_value >= DH_PRIME-1: if server_exchange_value <= 1 or server_exchange_value >= DH_PRIME - 1:
self.transport.send_disconnect(constants.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, 'Key exchange did not succeed: Server exchange value not valid.') self.transport.send_disconnect(
constants.SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
'Key exchange did not succeed: Server exchange value not valid.')
# K = f**x mod p # K = f**x mod p
self.shared_secret = pow(server_exchange_value, self.client_random_value, DH_PRIME) self.shared_secret = pow(server_exchange_value, self.client_random_value, DH_PRIME)
...@@ -167,14 +170,14 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -167,14 +170,14 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
# mpint f, exchange value sent by the server # mpint f, exchange value sent by the server
# mpint K, the shared secret # mpint K, the shared secret
H = ssh_packet.pack_payload(KEXDH_HASH_PAYLOAD, H = ssh_packet.pack_payload(KEXDH_HASH_PAYLOAD,
(self.c2s_version_string, (self.c2s_version_string,
self.s2c_version_string, self.s2c_version_string,
self.c2s_kexinit_packet, self.c2s_kexinit_packet,
self.s2c_kexinit_packet, self.s2c_kexinit_packet,
public_host_key, public_host_key,
self.client_exchange_value, self.client_exchange_value,
server_exchange_value, server_exchange_value,
self.shared_secret)) self.shared_secret))
# Double check that the signature from the server matches our signature. # Double check that the signature from the server matches our signature.
hash = hashlib.sha1(H) hash = hashlib.sha1(H)
self.exchange_hash = hash.digest() self.exchange_hash = hash.digest()
...@@ -183,27 +186,28 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange): ...@@ -183,27 +186,28 @@ class Diffie_Hellman_Group1_SHA1(SSH_Key_Exchange):
self.session_id = self.exchange_hash self.session_id = self.exchange_hash
if not self.server_public_host_key.verify(self.exchange_hash, signature_of_h): if not self.server_public_host_key.verify(self.exchange_hash, signature_of_h):
self.transport.send_disconnect(constants.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, 'Key exchange did not succeed: Signature did not match.') self.transport.send_disconnect(
constants.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, 'Key exchange did not succeed: Signature did not match.')
# Finished... # Finished...
#self.transport.send_newkeys() # self.transport.send_newkeys()
KEXDH_REPLY_PAYLOAD = (ssh_packet.BYTE, KEXDH_REPLY_PAYLOAD = (ssh_packet.BYTE,
ssh_packet.STRING, # public host key and certificates (K_S) ssh_packet.STRING, # public host key and certificates (K_S)
ssh_packet.MPINT, # f ssh_packet.MPINT, # f
ssh_packet.STRING # signature of H ssh_packet.STRING # signature of H
) )
KEXDH_INIT_PAYLOAD = (ssh_packet.BYTE, KEXDH_INIT_PAYLOAD = (ssh_packet.BYTE,
ssh_packet.MPINT # e ssh_packet.MPINT # e
) )
KEXDH_HASH_PAYLOAD = (ssh_packet.STRING, # V_C, the client's version string (CR and NL excluded) KEXDH_HASH_PAYLOAD = (ssh_packet.STRING, # V_C, the client's version string (CR and NL excluded)
ssh_packet.STRING, # V_S, the server's version string (CR and NL excluded) ssh_packet.STRING, # V_S, the server's version string (CR and NL excluded)
ssh_packet.STRING, # I_C, the payload of the client's SSH_MSG_KEXINIT ssh_packet.STRING, # I_C, the payload of the client's SSH_MSG_KEXINIT
ssh_packet.STRING, # I_S, the payload of the server's SSH_MSG_KEXINIT ssh_packet.STRING, # I_S, the payload of the server's SSH_MSG_KEXINIT
ssh_packet.STRING, # K_S, the host key ssh_packet.STRING, # K_S, the host key
ssh_packet.MPINT, # e, exchange value sent by the client ssh_packet.MPINT, # e, exchange value sent by the client
ssh_packet.MPINT, # f, exchange value sent by the server ssh_packet.MPINT, # f, exchange value sent by the server
ssh_packet.MPINT # K, the shared secret ssh_packet.MPINT # K, the shared secret
) )
...@@ -52,7 +52,7 @@ def parse_public_key(public_key): ...@@ -52,7 +52,7 @@ def parse_public_key(public_key):
""" """
data, offset = packet.unpack_payload_get_offset((packet.STRING,), public_key) data, offset = packet.unpack_payload_get_offset((packet.STRING,), public_key)
keytype = data[0] keytype = data[0]
if not keytypes.has_key(keytype): if keytype not in keytypes:
raise Unknown_Key_Type(keytype) raise Unknown_Key_Type(keytype)
key_obj = keytypes[keytype]() key_obj = keytypes[keytype]()
......
...@@ -44,7 +44,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -44,7 +44,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
def set_public_key(self, public_key): def set_public_key(self, public_key):
dss, p, q, g, y = packet.unpack_payload(DSS_PUBLIC_KEY_PAYLOAD, public_key) dss, p, q, g, y = packet.unpack_payload(DSS_PUBLIC_KEY_PAYLOAD, public_key)
if dss != 'ssh-dss': if dss != 'ssh-dss':
raise ValueError, dss raise ValueError(dss)
self.public_key = (p, q, g, y) self.public_key = (p, q, g, y)
set_public_key.__doc__ = public_private_key.SSH_Public_Private_Key.set_public_key.__doc__ set_public_key.__doc__ = public_private_key.SSH_Public_Private_Key.set_public_key.__doc__
...@@ -52,7 +52,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -52,7 +52,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
def set_private_key(self, private_key): def set_private_key(self, private_key):
dss, p, q, g, y, x = packet.unpack_payload(DSS_PRIVATE_KEY_PAYLOAD, private_key) dss, p, q, g, y, x = packet.unpack_payload(DSS_PRIVATE_KEY_PAYLOAD, private_key)
if dss != 'ssh-dss': if dss != 'ssh-dss':
raise ValueError, dss raise ValueError(dss)
self.private_key = (p, q, g, y, x) self.private_key = (p, q, g, y, x)
set_private_key.__doc__ = public_private_key.SSH_Public_Private_Key.set_private_key.__doc__ set_private_key.__doc__ = public_private_key.SSH_Public_Private_Key.set_private_key.__doc__
...@@ -63,16 +63,16 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -63,16 +63,16 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
else: else:
p, q, g, y, x = self.private_key p, q, g, y, x = self.private_key
return packet.pack_payload(DSS_PUBLIC_KEY_PAYLOAD, return packet.pack_payload(DSS_PUBLIC_KEY_PAYLOAD,
('ssh-dss', ('ssh-dss',
p, q, g, y)) p, q, g, y))
get_public_key_blob.__doc__ = public_private_key.SSH_Public_Private_Key.get_public_key_blob.__doc__ get_public_key_blob.__doc__ = public_private_key.SSH_Public_Private_Key.get_public_key_blob.__doc__
def get_private_key_blob(self): def get_private_key_blob(self):
p, q, g, y, x = self.private_key p, q, g, y, x = self.private_key
return packet.pack_payload(DSS_PRIVATE_KEY_PAYLOAD, return packet.pack_payload(DSS_PRIVATE_KEY_PAYLOAD,
('ssh-dss', ('ssh-dss',
p, q, g, y, x)) p, q, g, y, x))
get_private_key_blob.__doc__ = public_private_key.SSH_Public_Private_Key.get_private_key_blob.__doc__ get_private_key_blob.__doc__ = public_private_key.SSH_Public_Private_Key.get_private_key_blob.__doc__
...@@ -83,7 +83,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -83,7 +83,7 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
def sign(self, message): def sign(self, message):
p, q, g, y, x = self.private_key p, q, g, y, x = self.private_key
dsa_obj = DSA.construct( (y, g, p, q, x) ) dsa_obj = DSA.construct((y, g, p, q, x))
message_hash = hashlib.sha1(message).digest() message_hash = hashlib.sha1(message).digest()
# Get a random number that is greater than 2 and less than q. # Get a random number that is greater than 2 and less than q.
random_number = random.get_random_number_from_range(2, q) random_number = random.get_random_number_from_range(2, q)
...@@ -91,8 +91,8 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -91,8 +91,8 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
r, s = dsa_obj.sign(message_hash, random_data) r, s = dsa_obj.sign(message_hash, random_data)
signature = number.long_to_bytes(r, 20) + number.long_to_bytes(s, 20) signature = number.long_to_bytes(r, 20) + number.long_to_bytes(s, 20)
return packet.pack_payload(DSS_SIG_PAYLOAD, return packet.pack_payload(DSS_SIG_PAYLOAD,
('ssh-dss', ('ssh-dss',
signature)) signature))
sign.__doc__ = public_private_key.SSH_Public_Private_Key.sign.__doc__ sign.__doc__ = public_private_key.SSH_Public_Private_Key.sign.__doc__
...@@ -100,13 +100,13 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key): ...@@ -100,13 +100,13 @@ class SSH_DSS(public_private_key.SSH_Public_Private_Key):
p, q, g, y = self.public_key p, q, g, y = self.public_key
dss, blob = packet.unpack_payload(DSS_SIG_PAYLOAD, signature) dss, blob = packet.unpack_payload(DSS_SIG_PAYLOAD, signature)
if dss != 'ssh-dss': if dss != 'ssh-dss':
raise ValueError, dss raise ValueError(dss)
# blob is the concatenation of r and s # blob is the concatenation of r and s
# r and s are 160-bit (20-byte) integers in network-byte-order # r and s are 160-bit (20-byte) integers in network-byte-order
assert( len(blob) == 40 ) assert(len(blob) == 40)
r = number.bytes_to_long(blob[:20]) r = number.bytes_to_long(blob[:20])
s = number.bytes_to_long(blob[20:]) s = number.bytes_to_long(blob[20:])
dsa_obj = DSA.construct( (y, g, p, q) ) dsa_obj = DSA.construct((y, g, p, q))
hash_of_message = hashlib.sha1(message).digest() hash_of_message = hashlib.sha1(message).digest()
return dsa_obj.verify(hash_of_message, (r, s)) return dsa_obj.verify(hash_of_message, (r, s))
...@@ -117,7 +117,7 @@ DSS_PUBLIC_KEY_PAYLOAD = (packet.STRING, # "ssh-dss" ...@@ -117,7 +117,7 @@ DSS_PUBLIC_KEY_PAYLOAD = (packet.STRING, # "ssh-dss"
packet.MPINT, # q packet.MPINT, # q
packet.MPINT, # g packet.MPINT, # g
packet.MPINT # y packet.MPINT # y
) )
DSS_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-dss" DSS_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-dss"
packet.MPINT, # p packet.MPINT, # p
...@@ -125,9 +125,9 @@ DSS_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-dss" ...@@ -125,9 +125,9 @@ DSS_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-dss"
packet.MPINT, # g packet.MPINT, # g
packet.MPINT, # y packet.MPINT, # y
packet.MPINT, # x packet.MPINT, # x
) )
DSS_SIG_PAYLOAD = (packet.STRING, # "ssh-dss" DSS_SIG_PAYLOAD = (packet.STRING, # "ssh-dss"
packet.STRING # signature_key_blob packet.STRING # signature_key_blob
) )
...@@ -71,13 +71,13 @@ ssh1_key = CONCAT('^', ...@@ -71,13 +71,13 @@ ssh1_key = CONCAT('^',
) )
ssh1_key_w_options = CONCAT('^', ssh1_key_w_options = CONCAT('^',
SPLAT(SPACE), SPLAT(SPACE),
OPTIONS, PLUS(SPACE), OPTIONS, PLUS(SPACE),
BITS, PLUS(SPACE), BITS, PLUS(SPACE),
EXPONENT, PLUS(SPACE), EXPONENT, PLUS(SPACE),
MODULUS, SPLAT(SPACE), MODULUS, SPLAT(SPACE),
COMMENT COMMENT
) )
# The man page for OpenSSH specifies that "ssh-dss" and "ssh-rsa" are the only # The man page for OpenSSH specifies that "ssh-dss" and "ssh-rsa" are the only
...@@ -97,12 +97,12 @@ ssh2_key = CONCAT('^', ...@@ -97,12 +97,12 @@ ssh2_key = CONCAT('^',
) )
ssh2_key_w_options = CONCAT('^', ssh2_key_w_options = CONCAT('^',
SPLAT(SPACE), SPLAT(SPACE),
OPTIONS, PLUS(SPACE), OPTIONS, PLUS(SPACE),
KEYTYPE, PLUS(SPACE), KEYTYPE, PLUS(SPACE),
BASE64_KEY, SPLAT(SPACE), BASE64_KEY, SPLAT(SPACE),
COMMENT COMMENT
) )
ssh1_key_re = re.compile(ssh1_key) ssh1_key_re = re.compile(ssh1_key)
ssh2_key_re = re.compile(ssh2_key) ssh2_key_re = re.compile(ssh2_key)
...@@ -158,18 +158,17 @@ class OpenSSH_Authorized_Keys: ...@@ -158,18 +158,17 @@ class OpenSSH_Authorized_Keys:
if not m: if not m:
m = ssh2_key_w_options_re.match(key) m = ssh2_key_w_options_re.match(key)
if not m: if not m:
raise ValueError, key raise ValueError(key)
values = m.groupdict() values = m.groupdict()
if ((values.has_key('keytype') and not values['keytype']) or if (('keytype' in values and not values['keytype']) or
(values.has_key('base64_key') and not values['base64_key']) or ('base64_key' in values and not values['base64_key']) or
(values.has_key('bits') and not values['bits']) or ('bits' in values and not values['bits']) or
(values.has_key('exponent') and not values['exponent']) or ('exponent' in values and not values['exponent']) or
(values.has_key('modulus') and not values['modulus']) ('modulus' in values and not values['modulus'])):
): raise ValueError(key)
raise ValueError, key
self._value_strip(values) self._value_strip(values)
if not values.has_key('options') or not values['options']: if 'options' not in values or not values['options']:
# If it doesn't exist, or it exists as None, set it to the empty string. # If it doesn't exist, or it exists as None, set it to the empty string.
values['options'] = '' values['options'] = ''
if not values['comment']: if not values['comment']:
...@@ -190,20 +189,20 @@ class OpenSSH_Authorized_Keys: ...@@ -190,20 +189,20 @@ class OpenSSH_Authorized_Keys:
Checks if key (which is dict-format) is a duplicate. Checks if key (which is dict-format) is a duplicate.
Raises DuplicateKeyError if it is. Raises DuplicateKeyError if it is.
""" """
if key.has_key('bits'): if 'bits' in key:
# SSH1 # SSH1
for x in self.keys: for x in self.keys:
if (x.has_key('bits') and if ('bits' in x and
x['bits'] == key['bits'] and x['bits'] == key['bits'] and
x['exponent'] == key['exponent'] and x['exponent'] == key['exponent'] and
x['modulus'] == key['modulus']): x['modulus'] == key['modulus']):
raise DuplicateKeyError raise DuplicateKeyError
else: else:
# SSH2 # SSH2
for x in self.keys: for x in self.keys:
if (x.has_key('keytype') and if ('keytype' in x and
x['keytype'] == key['keytype'] and x['keytype'] == key['keytype'] and
x['base64_key'] == key['base64_key']): x['base64_key'] == key['base64_key']):
raise DuplicateKeyError raise DuplicateKeyError
def write(self): def write(self):
...@@ -213,8 +212,8 @@ class OpenSSH_Authorized_Keys: ...@@ -213,8 +212,8 @@ class OpenSSH_Authorized_Keys:
""" """
# Avoid concurrent races here? # Avoid concurrent races here?
tmp_filename = self.filename + '.tmp' tmp_filename = self.filename + '.tmp'
fd = os.open(tmp_filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0644) fd = os.open(tmp_filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0644)
write = lambda x,y=fd: os.write(y, x) write = lambda x, y=fd: os.write(y, x)
map(write, map(self.keydict_to_string, self.keys)) map(write, map(self.keydict_to_string, self.keys))
os.close(fd) os.close(fd)
os.rename(tmp_filename, self.filename) os.rename(tmp_filename, self.filename)
...@@ -230,7 +229,7 @@ class OpenSSH_Authorized_Keys: ...@@ -230,7 +229,7 @@ class OpenSSH_Authorized_Keys:
else: else:
options = key['options'] options = key['options']
comment = key['comment'] comment = key['comment']
if key.has_key('bits'): if 'bits' in key:
# SSH1 # SSH1
bits = key['bits'] bits = key['bits']
exponent = key['exponent'] exponent = key['exponent']
......
...@@ -31,22 +31,22 @@ SPACE = '[ \t]' ...@@ -31,22 +31,22 @@ SPACE = '[ \t]'
NUMBER = '\d' NUMBER = '\d'
LIST_OF_HOSTS = NAME('list_of_hosts', PLUS('[^ \t]')) LIST_OF_HOSTS = NAME('list_of_hosts', PLUS('[^ \t]'))
COMMENT = OPTIONAL( COMMENT = OPTIONAL(
PLUS(SPACE), PLUS(SPACE),
NAME('comment', PLUS('.')) NAME('comment', PLUS('.'))
) )
ssh1_key = re.compile( ssh1_key = re.compile(
CONCAT('^', CONCAT('^',
LIST_OF_HOSTS, LIST_OF_HOSTS,
PLUS(SPACE), PLUS(SPACE),
NAME('number_of_bits', PLUS(NUMBER)), NAME('number_of_bits', PLUS(NUMBER)),
PLUS(SPACE), PLUS(SPACE),
NAME('exponent', PLUS(NUMBER)), NAME('exponent', PLUS(NUMBER)),
PLUS(SPACE), PLUS(SPACE),
NAME('modulus', PLUS(NUMBER)), NAME('modulus', PLUS(NUMBER)),
COMMENT COMMENT
) )
) )
# The man page for OpenSSH specifies that "ssh-dss" and "ssh-rsa" are the only # The man page for OpenSSH specifies that "ssh-dss" and "ssh-rsa" are the only
# valid types, but the code actually checks for this list of types. Let's # valid types, but the code actually checks for this list of types. Let's
...@@ -58,21 +58,21 @@ KEYTYPE = NAME('keytype', OR('ssh-dss', 'ssh-rsa', 'rsa1', 'rsa', 'dsa')) ...@@ -58,21 +58,21 @@ KEYTYPE = NAME('keytype', OR('ssh-dss', 'ssh-rsa', 'rsa1', 'rsa', 'dsa'))
BASE64_KEY = NAME('base64_key', PLUS('[a-zA-Z0-9+/=]')) BASE64_KEY = NAME('base64_key', PLUS('[a-zA-Z0-9+/=]'))
ssh2_key = re.compile( ssh2_key = re.compile(
CONCAT('^', CONCAT('^',
KEYTYPE, KEYTYPE,
PLUS(SPACE), PLUS(SPACE),
BASE64_KEY, BASE64_KEY,
COMMENT COMMENT
) )
) )
ssh2_known_hosts_entry = re.compile( ssh2_known_hosts_entry = re.compile(
CONCAT('^', CONCAT('^',
LIST_OF_HOSTS, LIST_OF_HOSTS,
PLUS(SPACE), PLUS(SPACE),
KEYTYPE, KEYTYPE,
PLUS(SPACE), PLUS(SPACE),
BASE64_KEY, BASE64_KEY,
COMMENT COMMENT
) )
) )
This diff is collapsed.
This diff is collapsed.
...@@ -70,7 +70,7 @@ class SSH_Public_Private_Key: ...@@ -70,7 +70,7 @@ class SSH_Public_Private_Key:
m = hashlib.md5(self.get_public_key_blob()) m = hashlib.md5(self.get_public_key_blob())
# hexdigest returns lowercase already, but I just wanted to be careful. # hexdigest returns lowercase already, but I just wanted to be careful.
fingerprint = m.hexdigest().lower() fingerprint = m.hexdigest().lower()
pieces = [ fingerprint[x]+fingerprint[x+1] for x in xrange(0, len(fingerprint), 2) ] pieces = [fingerprint[x] + fingerprint[x + 1] for x in xrange(0, len(fingerprint), 2)]
return ':'.join(pieces) return ':'.join(pieces)
# XXX: encrypt functions... # XXX: encrypt functions...
...@@ -44,26 +44,26 @@ class SSH_RSA(public_private_key.SSH_Public_Private_Key): ...@@ -44,26 +44,26 @@ class SSH_RSA(public_private_key.SSH_Public_Private_Key):
def set_public_key(self, public_key): def set_public_key(self, public_key):
rsa, e, n = packet.unpack_payload(RSA_PUBLIC_KEY_PAYLOAD, public_key) rsa, e, n = packet.unpack_payload(RSA_PUBLIC_KEY_PAYLOAD, public_key)
if rsa != 'ssh-rsa': if rsa != 'ssh-rsa':
raise ValueError, rsa raise ValueError(rsa)
self.public_key = (e, n) self.public_key = (e, n)
def set_private_key(self, private_key): def set_private_key(self, private_key):
rsa, n, e, d, p, q = packet.unpack_payload(RSA_PRIVATE_KEY_PAYLOAD, private_key) rsa, n, e, d, p, q = packet.unpack_payload(RSA_PRIVATE_KEY_PAYLOAD, private_key)
if rsa != 'ssh-rsa': if rsa != 'ssh-rsa':
raise ValueError, rsa raise ValueError(rsa)
self.public_key = (n, e, d, p, q) self.public_key = (n, e, d, p, q)
def get_public_key_blob(self): def get_public_key_blob(self):
e, n = self.public_key e, n = self.public_key
return packet.pack_payload(RSA_PUBLIC_KEY_PAYLOAD, return packet.pack_payload(RSA_PUBLIC_KEY_PAYLOAD,
('ssh-rsa', ('ssh-rsa',
e, n)) e, n))
def get_private_key_blob(self): def get_private_key_blob(self):
n, e, d, p, q = self.public_key n, e, d, p, q = self.public_key
return packet.pack_payload(RSA_PRIVATE_KEY_PAYLOAD, return packet.pack_payload(RSA_PRIVATE_KEY_PAYLOAD,
('ssh-rsa', ('ssh-rsa',
n, e, d, p, q)) n, e, d, p, q))
def emsa_pkcs1_v1_5_encode(self, message, n_len): def emsa_pkcs1_v1_5_encode(self, message, n_len):
"""emsa_pkcs1_v1_5_encode(self, message, n_len) -> encoded_message """emsa_pkcs1_v1_5_encode(self, message, n_len) -> encoded_message
...@@ -75,39 +75,39 @@ class SSH_RSA(public_private_key.SSH_Public_Private_Key): ...@@ -75,39 +75,39 @@ class SSH_RSA(public_private_key.SSH_Public_Private_Key):
hash = hashlib.sha1(message).digest() hash = hashlib.sha1(message).digest()
T = SHA1_Digest_Info + hash T = SHA1_Digest_Info + hash
if __debug__: if __debug__:
assert n_len >= len(T)+11 assert n_len >= len(T) + 11
# PKCS spec says that it's -3...I do not understand why that doesn't work. # PKCS spec says that it's -3...I do not understand why that doesn't work.
PS = '\xff'*(n_len - len(T) - 2) PS = '\xff' * (n_len - len(T) - 2)
if __debug__: if __debug__:
assert len(PS) >= 8 assert len(PS) >= 8
return '\x00\x01' + PS + '\x00' + T return '\x00\x01' + PS + '\x00' + T
def sign(self, message): def sign(self, message):
n, e, d, p, q = self.private_key n, e, d, p, q = self.private_key
rsa_obj = RSA.construct( (n, e, d, p, q) ) rsa_obj = RSA.construct((n, e, d, p, q))
modulus_n_length_in_octets = rsa_obj.size()/8 modulus_n_length_in_octets = rsa_obj.size() / 8
encoded_message = self.emsa_pkcs1_v1_5_encode(message, modulus_n_length_in_octets) encoded_message = self.emsa_pkcs1_v1_5_encode(message, modulus_n_length_in_octets)
signature = rsa_obj.sign(encoded_message, '')[0] # Returns tuple of 1 element. signature = rsa_obj.sign(encoded_message, '')[0] # Returns tuple of 1 element.
signature = number.long_to_bytes(signature) signature = number.long_to_bytes(signature)
return packet.pack_payload(RSA_SIG_PAYLOAD, return packet.pack_payload(RSA_SIG_PAYLOAD,
('ssh-rsa', ('ssh-rsa',
signature)) signature))
def verify(self, message, signature): def verify(self, message, signature):
e, n = self.public_key e, n = self.public_key
rsa, blob = packet.unpack_payload(RSA_SIG_PAYLOAD, signature) rsa, blob = packet.unpack_payload(RSA_SIG_PAYLOAD, signature)
if rsa != 'ssh-rsa': if rsa != 'ssh-rsa':
raise ValueError, rsa raise ValueError(rsa)
s = number.bytes_to_long(blob) s = number.bytes_to_long(blob)
rsa_obj = RSA.construct( (n, e) ) rsa_obj = RSA.construct((n, e))
modulus_n_length_in_octets = rsa_obj.size()/8 modulus_n_length_in_octets = rsa_obj.size() / 8
encoded_message = self.emsa_pkcs1_v1_5_encode(message, modulus_n_length_in_octets) encoded_message = self.emsa_pkcs1_v1_5_encode(message, modulus_n_length_in_octets)
return rsa_obj.verify(encoded_message, (s,)) return rsa_obj.verify(encoded_message, (s,))
RSA_PUBLIC_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa" RSA_PUBLIC_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa"
packet.MPINT, # e packet.MPINT, # e
packet.MPINT # n packet.MPINT # n
) )
RSA_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa" RSA_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa"
packet.MPINT, # n packet.MPINT, # n
...@@ -115,8 +115,8 @@ RSA_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa" ...@@ -115,8 +115,8 @@ RSA_PRIVATE_KEY_PAYLOAD = (packet.STRING, # "ssh-rsa"
packet.MPINT, # d packet.MPINT, # d
packet.MPINT, # p packet.MPINT, # p
packet.MPINT, # q packet.MPINT, # q
) )
RSA_SIG_PAYLOAD = (packet.STRING, # "ssh-rsa" RSA_SIG_PAYLOAD = (packet.STRING, # "ssh-rsa"
packet.STRING # signature_key_blob packet.STRING # signature_key_blob
) )
...@@ -73,7 +73,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage): ...@@ -73,7 +73,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage):
self.known_hosts.append((hosts, key_objs)) self.known_hosts.append((hosts, key_objs))
def load_keys(self, username=None): def load_keys(self, username=None):
if not self.public_key.has_key(username) or not self.private_key.has_key(username): if username not in self.public_key or username not in self.private_key:
return None return None
if username is None: if username is None:
username = os.getlogin() username = os.getlogin()
...@@ -85,7 +85,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage): ...@@ -85,7 +85,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage):
load_keys.__doc__ = key_storage.SSH_Key_Storage.load_keys.__doc__ load_keys.__doc__ = key_storage.SSH_Key_Storage.load_keys.__doc__
def load_private_keys(self, username=None): def load_private_keys(self, username=None):
if not self.private_key.has_key(username): if username not in self.private_key:
return [] return []
if username is None: if username is None:
username = os.getlogin() username = os.getlogin()
...@@ -94,7 +94,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage): ...@@ -94,7 +94,7 @@ class Static_Key_Storage(key_storage.SSH_Key_Storage):
load_private_keys.__doc__ = key_storage.SSH_Key_Storage.load_private_keys.__doc__ load_private_keys.__doc__ = key_storage.SSH_Key_Storage.load_private_keys.__doc__
def load_public_keys(self, username=None): def load_public_keys(self, username=None):
if not self.public_key.has_key(username): if username not in self.public_key:
return [] return []
if username is None: if username is None:
username = os.getlogin() username = os.getlogin()
......
...@@ -80,7 +80,7 @@ class coro_socket_transport(l4_transport.Transport): ...@@ -80,7 +80,7 @@ class coro_socket_transport(l4_transport.Transport):
raise raise
except coro.ClosedError: except coro.ClosedError:
raise EOFError raise EOFError
if len(chunk)==0: if len(chunk) == 0:
raise EOFError raise EOFError
count -= len(chunk) count -= len(chunk)
result.append(chunk) result.append(chunk)
......
...@@ -56,7 +56,7 @@ class SSH_HMAC(SSH_MAC_Method): ...@@ -56,7 +56,7 @@ class SSH_HMAC(SSH_MAC_Method):
ipad = '\x36' * self.block_size ipad = '\x36' * self.block_size
opad = '\x5C' * self.block_size opad = '\x5C' * self.block_size
padded_key = self.key + '\0' * (self.block_size-len(self.key)) padded_key = self.key + '\0' * (self.block_size - len(self.key))
self._enc_ipad = str_xor(padded_key, ipad) self._enc_ipad = str_xor(padded_key, ipad)
self._enc_opad = str_xor(padded_key, opad) self._enc_opad = str_xor(padded_key, opad)
......
...@@ -46,15 +46,16 @@ class hmac_md5_test_case(ssh_hmac_md5_test_case): ...@@ -46,15 +46,16 @@ class hmac_md5_test_case(ssh_hmac_md5_test_case):
def runTest(self): def runTest(self):
# From RFC2104 # From RFC2104
a = HMAC_MD5() a = HMAC_MD5()
a.set_key('\x0b'*16) a.set_key('\x0b' * 16)
self.assertEqual(a.hmac('Hi There'), '\x92\x94\x72\x7a\x36\x38\xbb\x1c\x13\xf4\x8e\xf8\x15\x8b\xfc\x9d') self.assertEqual(a.hmac('Hi There'), '\x92\x94\x72\x7a\x36\x38\xbb\x1c\x13\xf4\x8e\xf8\x15\x8b\xfc\x9d')
a = HMAC_MD5() a = HMAC_MD5()
a.set_key('Jefe' + '\0'*12) a.set_key('Jefe' + '\0' * 12)
self.assertEqual(a.hmac('what do ya want for nothing?'), '\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38') self.assertEqual(a.hmac('what do ya want for nothing?'),
'\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38')
a = HMAC_MD5() a = HMAC_MD5()
a.set_key('\xAA'*16) a.set_key('\xAA' * 16)
self.assertEqual(a.hmac('\xDD' * 50), '\x56\xbe\x34\x52\x1d\x14\x4c\x88\xdb\xb8\xc7\x33\xf0\xe8\xb3\xf6') self.assertEqual(a.hmac('\xDD' * 50), '\x56\xbe\x34\x52\x1d\x14\x4c\x88\xdb\xb8\xc7\x33\xf0\xe8\xb3\xf6')
def suite(): def suite():
......
...@@ -83,7 +83,6 @@ class CLI: ...@@ -83,7 +83,6 @@ class CLI:
print usage print usage
sys.exit(0) sys.exit(0)
if options.action_from: if options.action_from:
scp = self._get_scp() scp = self._get_scp()
scp.verbosity = options.verbosity scp.verbosity = options.verbosity
...@@ -92,7 +91,7 @@ class CLI: ...@@ -92,7 +91,7 @@ class CLI:
scp.send(options.preserve, scp.send(options.preserve,
options.recursive, options.recursive,
arguments arguments
) )
sys.exit(int(scp.had_errors)) sys.exit(int(scp.had_errors))
elif options.action_to: elif options.action_to:
...@@ -105,7 +104,7 @@ class CLI: ...@@ -105,7 +104,7 @@ class CLI:
options.recursive, options.recursive,
options.target_should_be_dir, options.target_should_be_dir,
arguments[0] arguments[0]
) )
sys.exit(int(scp.had_errors)) sys.exit(int(scp.had_errors))
else: else:
print 'Function unavailable.' print 'Function unavailable.'
...@@ -115,7 +114,7 @@ class CLI: ...@@ -115,7 +114,7 @@ class CLI:
options.recursive, options.recursive,
options.verbosity, options.verbosity,
arguments arguments
) )
def _get_scp(self): def _get_scp(self):
return core.SCP() return core.SCP()
......
...@@ -76,12 +76,12 @@ class SCP: ...@@ -76,12 +76,12 @@ class SCP:
root_slash = None root_slash = None
def __init__(self, input=None, def __init__(self, input=None,
output=None, output=None,
path_filter=None, path_filter=None,
filter_recursive_only=False, filter_recursive_only=False,
root=None, root=None,
shell_globbing=False shell_globbing=False
): ):
if input: if input:
self.input = input self.input = input
else: else:
...@@ -217,7 +217,7 @@ class SCP: ...@@ -217,7 +217,7 @@ class SCP:
size = int(result[5:end]) size = int(result[5:end])
except ValueError: except ValueError:
self.hard_error('Invalid size (%r)' % (result,)) self.hard_error('Invalid size (%r)' % (result,))
filename = result[end+1:] filename = result[end + 1:]
if not filename: if not filename:
self.hard_error('Filename not specified (%r)' % (result,)) self.hard_error('Filename not specified (%r)' % (result,))
if '/' in filename or filename == '..': if '/' in filename or filename == '..':
...@@ -251,7 +251,8 @@ class SCP: ...@@ -251,7 +251,8 @@ class SCP:
try: try:
os.chmod(absolute_pathname, mode) os.chmod(absolute_pathname, mode)
except OSError, e: except OSError, e:
self.debug(DEBUG_NORMAL, 'Failed to chmod %r to %o: %s', relative_pathname, mode, e.strerror) self.debug(
DEBUG_NORMAL, 'Failed to chmod %r to %o: %s', relative_pathname, mode, e.strerror)
# Continue, this is not critical. # Continue, this is not critical.
else: else:
try: try:
...@@ -266,13 +267,14 @@ class SCP: ...@@ -266,13 +267,14 @@ class SCP:
try: try:
os.utime(absolute_pathname, timestamp) os.utime(absolute_pathname, timestamp)
except OSError, e: except OSError, e:
self.soft_error('Failed to set timestamp (%r) on %r: %s' % (timestamp, relative_pathname, e.strerror)) self.soft_error('Failed to set timestamp (%r) on %r: %s' %
(timestamp, relative_pathname, e.strerror))
continue continue
else: else:
# code == 'C' # code == 'C'
# Creating a file. # Creating a file.
try: try:
fd = os.open(absolute_pathname, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, mode) fd = os.open(absolute_pathname, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
except OSError, e: except OSError, e:
self.soft_error('Failed to create %r: %s' % (relative_pathname, e.strerror)) self.soft_error('Failed to create %r: %s' % (relative_pathname, e.strerror))
continue continue
...@@ -284,7 +286,8 @@ class SCP: ...@@ -284,7 +286,8 @@ class SCP:
while bytes_left > 0: while bytes_left > 0:
block = self.input.read(min(bytes_left, self.blocksize)) block = self.input.read(min(bytes_left, self.blocksize))
if not block: if not block:
self.hard_error('End of file, but expected more data while ready %r.' % (relative_pathname,)) self.hard_error('End of file, but expected more data while ready %r.' %
(relative_pathname,))
bytes_left -= len(block) bytes_left -= len(block)
if not error: if not error:
try: try:
...@@ -301,7 +304,8 @@ class SCP: ...@@ -301,7 +304,8 @@ class SCP:
try: try:
os.utime(absolute_pathname, timestamp) os.utime(absolute_pathname, timestamp)
except OSError, e: except OSError, e:
self.soft_error('Failed to set timestamp (%r) on %r: %s' % (timestamp, relative_pathname, e.strerror)) self.soft_error('Failed to set timestamp (%r) on %r: %s' %
(timestamp, relative_pathname, e.strerror))
continue continue
if error: if error:
self.soft_error('Error while writing %r: %s' % (relative_pathname, error.strerror)) self.soft_error('Error while writing %r: %s' % (relative_pathname, error.strerror))
...@@ -355,7 +359,7 @@ class SCP: ...@@ -355,7 +359,7 @@ class SCP:
recursive, recursive,
more_relative_pathname, more_relative_pathname,
more_absolute_pathname more_absolute_pathname
) )
def _send(self, preserve, recursive, relative_pathname, absolute_pathname): def _send(self, preserve, recursive, relative_pathname, absolute_pathname):
...@@ -392,8 +396,8 @@ class SCP: ...@@ -392,8 +396,8 @@ class SCP:
self.output.write('C%04o %i %s\n' % (stat.S_IMODE(st.st_mode), self.output.write('C%04o %i %s\n' % (stat.S_IMODE(st.st_mode),
st.st_size, st.st_size,
base base
) )
) )
self.output.flush() self.output.flush()
if not self.read_response(): if not self.read_response():
return return
...@@ -449,8 +453,8 @@ class SCP: ...@@ -449,8 +453,8 @@ class SCP:
self.output.write('D%04o %i %s\n' % (stat.S_IMODE(st.st_mode), self.output.write('D%04o %i %s\n' % (stat.S_IMODE(st.st_mode),
0, 0,
base base
) )
) )
self.output.flush() self.output.flush()
if not self.read_response(): if not self.read_response():
return return
...@@ -554,7 +558,6 @@ class SCP: ...@@ -554,7 +558,6 @@ class SCP:
self.hard_error('Command line too long (%i)' % (self.max_line_size,)) self.hard_error('Command line too long (%i)' % (self.max_line_size,))
return True return True
def _report_error(self, message): def _report_error(self, message):
"""Report an error message. """Report an error message.
......
...@@ -81,7 +81,7 @@ def transport_thread(channel): ...@@ -81,7 +81,7 @@ def transport_thread(channel):
data = channel.read(1024) data = channel.read(1024)
if data: if data:
stdout.send (data) stdout.send (data)
#os.write(1, data) # os.write(1, data)
except EOFError: except EOFError:
break break
coro.set_exit() coro.set_exit()
...@@ -119,9 +119,9 @@ def main(): ...@@ -119,9 +119,9 @@ def main():
sys.exit(1) sys.exit(1)
for option, value in optlist: for option, value in optlist:
if option=='-l': if option == '-l':
login_username = value login_username = value
elif option=='-p': elif option == '-p':
port = int (value) port = int (value)
if len(args) != 1: if len(args) != 1:
...@@ -140,5 +140,5 @@ def main(): ...@@ -140,5 +140,5 @@ def main():
termios.tcsetattr(0, termios.TCSAFLUSH, oldterm) termios.tcsetattr(0, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(0, fcntl.F_SETFL, oldflags) fcntl.fcntl(0, fcntl.F_SETFL, oldflags)
if __name__=='__main__': if __name__ == '__main__':
main() main()
...@@ -32,7 +32,7 @@ OekNfzzIBr6QkMvmIOuL ...@@ -32,7 +32,7 @@ OekNfzzIBr6QkMvmIOuL
-----END DSA PRIVATE KEY----- -----END DSA PRIVATE KEY-----
""" """
user_key_pub = """ssh-dss AAAAB3NzaC1kc3MAAACBAPawYoOY758V46mBep5i3pRQSuXnmYLiwBWH06NMXfMKkncZE4eWIVVoDqZmeMfCSHP8uY2gS+QDfdMCGtqu9sX8noPx5SG6gzUnadhFKU2+o7tbJ9WkQX7TPHB2GLBk5SNn6MFfLlLwlLv+OFnO0jcBD81fkCZp19BoZt1CCMGLAAAAFQCCSKBZHEoXw7Y1jiT0GFuqGgPMaQAAAIB2EjHBcrMa6jvmNI1DLYEHrYlQ30cDvnYYIyunMsp6SybE1sLN2W3UqGLjqB2i3FgWh7o1yUVWdImBvFz4kdYVhlEcYUeTgu8IWH2YNFcr7/Q4IpF9h20pu/ASuR9aK/D8sA4s7JqVfkS/mIaOZ8W2aZiOSaqvJXQPee9tiKgLDAAAAIEA6jTTFwh0wBlLdzALSaxf+A4IPGwE3mlmVmzt+A+a+EqL2ZRmAZ2puQH3NKckqrAlHDY7gGuF5XlHUTiTbVanuv6vCRlPwHWCPNNZhYFqGLpMEqRNPV2cMlU0gaPn69DMZwbDNCJghZI6C2uejoh3agHvHq8jgm9q4e3X3nEjStc= rushing@beast.local\n""" user_key_pub = """ssh-dss AAAAB3NzaC1kc3MAAACBAPawYoOY758V46mBep5i3pRQSuXnmYLiwBWH06NMXfMKkncZE4eWIVVoDqZmeMfCSHP8uY2gS+QDfdMCGtqu9sX8noPx5SG6gzUnadhFKU2+o7tbJ9WkQX7TPHB2GLBk5SNn6MFfLlLwlLv+OFnO0jcBD81fkCZp19BoZt1CCMGLAAAAFQCCSKBZHEoXw7Y1jiT0GFuqGgPMaQAAAIB2EjHBcrMa6jvmNI1DLYEHrYlQ30cDvnYYIyunMsp6SybE1sLN2W3UqGLjqB2i3FgWh7o1yUVWdImBvFz4kdYVhlEcYUeTgu8IWH2YNFcr7/Q4IpF9h20pu/ASuR9aK/D8sA4s7JqVfkS/mIaOZ8W2aZiOSaqvJXQPee9tiKgLDAAAAIEA6jTTFwh0wBlLdzALSaxf+A4IPGwE3mlmVmzt+A+a+EqL2ZRmAZ2puQH3NKckqrAlHDY7gGuF5XlHUTiTbVanuv6vCRlPwHWCPNNZhYFqGLpMEqRNPV2cMlU0gaPn69DMZwbDNCJghZI6C2uejoh3agHvHq8jgm9q4e3X3nEjStc= rushing@beast.local\n""" # noqa
ks = OpenSSH_Key_Storage() ks = OpenSSH_Key_Storage()
server_key_ob = ks.parse_private_key (server_key_pri) server_key_ob = ks.parse_private_key (server_key_pri)
...@@ -53,6 +53,7 @@ class echo_server (coro.ssh.connection.interactive_session.Interactive_Session_S ...@@ -53,6 +53,7 @@ class echo_server (coro.ssh.connection.interactive_session.Interactive_Session_S
def __init__ (self, connection_service): def __init__ (self, connection_service):
coro.ssh.connection.interactive_session.Interactive_Session_Server.__init__ (self, connection_service) coro.ssh.connection.interactive_session.Interactive_Session_Server.__init__ (self, connection_service)
coro.spawn (self.go) coro.spawn (self.go)
def go (self): def go (self):
self.send ('Welcome to the echo server.\n') self.send ('Welcome to the echo server.\n')
while 1: while 1:
...@@ -68,8 +69,8 @@ def go (conn, addr): ...@@ -68,8 +69,8 @@ def go (conn, addr):
debug.level = coro.ssh.util.debug.DEBUG_3 debug.level = coro.ssh.util.debug.DEBUG_3
transport = coro.ssh.l4_transport.coro_socket_transport.coro_socket_transport(sock=conn) transport = coro.ssh.l4_transport.coro_socket_transport.coro_socket_transport(sock=conn)
server = coro.ssh.transport.server.SSH_Server_Transport (server_key_ob, debug=debug) server = coro.ssh.transport.server.SSH_Server_Transport (server_key_ob, debug=debug)
pubkey_auth = coro.ssh.auth.userauth.Public_Key_Authenticator ({'rushing': { 'ssh-connection' : [user_key_ob]}}) pubkey_auth = coro.ssh.auth.userauth.Public_Key_Authenticator ({'rushing': {'ssh-connection': [user_key_ob]}})
pwd_auth = coro.ssh.auth.userauth.Password_Authenticator ({'foo' : { 'ssh-connection' : 'bar' } }) pwd_auth = coro.ssh.auth.userauth.Password_Authenticator ({'foo': {'ssh-connection': 'bar'}})
authenticator = coro.ssh.auth.userauth.Authenticator (server, [pubkey_auth, pwd_auth]) authenticator = coro.ssh.auth.userauth.Authenticator (server, [pubkey_auth, pwd_auth])
server.connect (transport, authenticator) server.connect (transport, authenticator)
service = coro.ssh.connection.connect.Connection_Service (server, echo_server) service = coro.ssh.connection.connect.Connection_Service (server, echo_server)
...@@ -88,11 +89,11 @@ def main(): ...@@ -88,11 +89,11 @@ def main():
sys.exit(1) sys.exit(1)
for option, value in optlist: for option, value in optlist:
if option=='-p': if option == '-p':
port = int (value) port = int (value)
coro.spawn (serve, port) coro.spawn (serve, port)
coro.event_loop() coro.event_loop()
if __name__=='__main__': if __name__ == '__main__':
main() main()
This diff is collapsed.
...@@ -75,17 +75,19 @@ class SSH_Client_Transport(transport.SSH_Transport): ...@@ -75,17 +75,19 @@ class SSH_Client_Transport(transport.SSH_Transport):
self.s2c.version_string = line self.s2c.version_string = line
# See if there are any optional comments. # See if there are any optional comments.
i = line.find(' ') i = line.find(' ')
if i!=-1: if i != -1:
self.s2c.comments = line[i+1:] self.s2c.comments = line[i + 1:]
line = line[:i] line = line[:i]
# Break up the identification string into its parts. # Break up the identification string into its parts.
parts = line.split('-') parts = line.split('-')
if len(parts) != 3: if len(parts) != 3:
self.send_disconnect(transport.SSH_DISCONNECT_PROTOCOL_ERROR, 'server identification invalid: %r' % line) self.send_disconnect(
transport.SSH_DISCONNECT_PROTOCOL_ERROR, 'server identification invalid: %r' % line)
self.s2c.protocol_version = parts[1] self.s2c.protocol_version = parts[1]
self.s2c.software_version = parts[2] self.s2c.software_version = parts[2]
if self.s2c.protocol_version not in ('1.99', '2.0'): if self.s2c.protocol_version not in ('1.99', '2.0'):
self.send_disconnect(transport.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, 'protocol version not supported: %r' % self.s2c.protocol_version) self.send_disconnect(transport.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
'protocol version not supported: %r' % self.s2c.protocol_version)
break break
self.send_kexinit() self.send_kexinit()
...@@ -130,8 +132,8 @@ class SSH_Client_Transport(transport.SSH_Transport): ...@@ -130,8 +132,8 @@ class SSH_Client_Transport(transport.SSH_Transport):
# Ask the remote side if it is OK to use this authentication service. # Ask the remote side if it is OK to use this authentication service.
self.debug.write(debug.DEBUG_3, 'authenticate: sending service request (%s)', (authentication_method.name,)) self.debug.write(debug.DEBUG_3, 'authenticate: sending service request (%s)', (authentication_method.name,))
service_request_packet = ssh_packet.pack_payload(ssh_packet.PAYLOAD_MSG_SERVICE_REQUEST, service_request_packet = ssh_packet.pack_payload(ssh_packet.PAYLOAD_MSG_SERVICE_REQUEST,
(transport.SSH_MSG_SERVICE_REQUEST, (transport.SSH_MSG_SERVICE_REQUEST,
authentication_method.name)) authentication_method.name))
self.send_packet(service_request_packet) self.send_packet(service_request_packet)
# Server will disconnect if it doesn't like our service request. # Server will disconnect if it doesn't like our service request.
self.debug.write(debug.DEBUG_3, 'authenticate: waiting for SERVICE_ACCEPT') self.debug.write(debug.DEBUG_3, 'authenticate: waiting for SERVICE_ACCEPT')
...@@ -139,7 +141,9 @@ class SSH_Client_Transport(transport.SSH_Transport): ...@@ -139,7 +141,9 @@ class SSH_Client_Transport(transport.SSH_Transport):
msg, accepted_service_name = ssh_packet.unpack_payload(ssh_packet.PAYLOAD_MSG_SERVICE_ACCEPT, packet) msg, accepted_service_name = ssh_packet.unpack_payload(ssh_packet.PAYLOAD_MSG_SERVICE_ACCEPT, packet)
self.debug.write(debug.DEBUG_3, 'authenticate: got SERVICE_ACCEPT') self.debug.write(debug.DEBUG_3, 'authenticate: got SERVICE_ACCEPT')
if accepted_service_name != authentication_method.name: if accepted_service_name != authentication_method.name:
self.send_disconnect(transport.SSH_DISCONNECT_PROTOCOL_ERROR, 'accepted service does not match requested service "%s"!="%s"' % (authentication_method.name, accepted_service_name)) self.send_disconnect(transport.SSH_DISCONNECT_PROTOCOL_ERROR,
'accepted service does not match requested service "%s"!="%s"' %
(authentication_method.name, accepted_service_name))
# This authetnication service is OK, try to authenticate. # This authetnication service is OK, try to authenticate.
authentication_method.authenticate(service_name) authentication_method.authenticate(service_name)
...@@ -149,7 +153,7 @@ class SSH_Client_Transport(transport.SSH_Transport): ...@@ -149,7 +153,7 @@ class SSH_Client_Transport(transport.SSH_Transport):
If the service is not available, then a disconnect will be sent. If the service is not available, then a disconnect will be sent.
<service_instance> is a SSH_Service class instance. <service_instance> is a SSH_Service class instance.
""" """
#SSH_MSG_SERVICE_REQUEST # SSH_MSG_SERVICE_REQUEST
pass pass
def msg_service_request_response(self, packet): def msg_service_request_response(self, packet):
......
...@@ -55,8 +55,8 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport): ...@@ -55,8 +55,8 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport):
self.c2s.version_string = line self.c2s.version_string = line
# See if there are any optional comments. # See if there are any optional comments.
i = line.find(' ') i = line.find(' ')
if i!=-1: if i != -1:
self.c2s.comments = line[i+1:] self.c2s.comments = line[i + 1:]
line = line[:i] line = line[:i]
# Break up the identification string into its parts. # Break up the identification string into its parts.
parts = line.split('-') parts = line.split('-')
...@@ -64,14 +64,14 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport): ...@@ -64,14 +64,14 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport):
self.send_disconnect ( self.send_disconnect (
ssh_transport.SSH_DISCONNECT_PROTOCOL_ERROR, ssh_transport.SSH_DISCONNECT_PROTOCOL_ERROR,
'server identification invalid: %r' % line 'server identification invalid: %r' % line
) )
self.c2s.protocol_version = parts[1] self.c2s.protocol_version = parts[1]
self.c2s.software_version = parts[2] self.c2s.software_version = parts[2]
if self.c2s.protocol_version not in ('1.99', '2.0'): if self.c2s.protocol_version not in ('1.99', '2.0'):
self.send_disconnect ( self.send_disconnect (
ssh_transport.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, ssh_transport.SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
'protocol version not supported: %r' % self.c2s.protocol_version 'protocol version not supported: %r' % self.c2s.protocol_version
) )
break break
self.send_kexinit() self.send_kexinit()
...@@ -113,7 +113,7 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport): ...@@ -113,7 +113,7 @@ class SSH_Server_Transport (ssh_transport.SSH_Transport):
ssh_packet.PAYLOAD_MSG_SERVICE_ACCEPT, ( ssh_packet.PAYLOAD_MSG_SERVICE_ACCEPT, (
ssh_transport.SSH_MSG_SERVICE_ACCEPT, ssh_transport.SSH_MSG_SERVICE_ACCEPT,
'ssh-userauth', 'ssh-userauth',
)
) )
)
) )
authenticator.authenticate (service_name) authenticator.authenticate (service_name)
This diff is collapsed.
...@@ -48,7 +48,7 @@ def pick_from_list(name, algorithms): ...@@ -48,7 +48,7 @@ def pick_from_list(name, algorithms):
return None return None
nonprintable = ''.join ([x for x in map (chr, range(256)) if x not in string.printable]) nonprintable = ''.join ([x for x in map (chr, range(256)) if x not in string.printable])
nonprintable_replacement = '$'*len(nonprintable) nonprintable_replacement = '$' * len(nonprintable)
nonprintable_table = string.maketrans(nonprintable, nonprintable_replacement) nonprintable_table = string.maketrans(nonprintable, nonprintable_replacement)
def safe_string(s): def safe_string(s):
......
...@@ -48,7 +48,7 @@ level_text = {ERROR: 'Error', ...@@ -48,7 +48,7 @@ level_text = {ERROR: 'Error',
DEBUG_1: 'Debug 1', DEBUG_1: 'Debug 1',
DEBUG_2: 'Debug 2', DEBUG_2: 'Debug 2',
DEBUG_3: 'Debug 3', DEBUG_3: 'Debug 3',
} }
import sys import sys
......
...@@ -51,13 +51,13 @@ def pack_mpint(n): ...@@ -51,13 +51,13 @@ def pack_mpint(n):
break break
x = x >> 32 x = x >> 32
else: else:
while x>0: while x > 0:
s.append(struct.pack('>L', x & 0xffffffffL)) s.append(struct.pack('>L', x & 0xffffffffL))
x = x >> 32 x = x >> 32
s.reverse() s.reverse()
s = ''.join(s) s = ''.join(s)
if s[0]=='\0': if s[0] == '\0':
# Remove extra leading zeros. # Remove extra leading zeros.
# This is a positive number. # This is a positive number.
count = 0 count = 0
...@@ -66,11 +66,11 @@ def pack_mpint(n): ...@@ -66,11 +66,11 @@ def pack_mpint(n):
break break
count += 1 count += 1
# If the MSB is set, pad with a zero byte. # If the MSB is set, pad with a zero byte.
if ord(s[count])&128: if ord(s[count]) & 128:
s = s[count-1:] s = s[count - 1:]
else: else:
s = s[count:] s = s[count:]
elif s[0]=='\377' and n < 0: elif s[0] == '\377' and n < 0:
# Remove extra leading ones. # Remove extra leading ones.
# This is a negative number. # This is a negative number.
for x in xrange(len(s)): for x in xrange(len(s)):
...@@ -79,13 +79,13 @@ def pack_mpint(n): ...@@ -79,13 +79,13 @@ def pack_mpint(n):
break break
# If the MSB is not set, then we need to sign-extend and make sure # If the MSB is not set, then we need to sign-extend and make sure
# there is another byte of all ones. # there is another byte of all ones.
if ord(s[x])&128: if ord(s[x]) & 128:
s = s[x:] s = s[x:]
else: else:
s = s[x-1:] s = s[x - 1:]
# If the MSB is set and this is a positive number, pad with a zero. # If the MSB is set and this is a positive number, pad with a zero.
if n > 0 and ord(s[0])&128: if n > 0 and ord(s[0]) & 128:
s = '\0' + s s = '\0' + s
return s return s
...@@ -113,7 +113,7 @@ def unpack_mpint(mpint): ...@@ -113,7 +113,7 @@ def unpack_mpint(mpint):
struct_format = '>I' struct_format = '>I'
result = 0L result = 0L
for x in xrange(0, len(mpint), 4): for x in xrange(0, len(mpint), 4):
result = (result << 32) | struct.unpack(struct_format, mpint[x: x+4])[0] result = (result << 32) | struct.unpack(struct_format, mpint[x: x + 4])[0]
return result return result
import unittest import unittest
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -11,8 +11,8 @@ ctx = openssl.ssl_ctx() ...@@ -11,8 +11,8 @@ ctx = openssl.ssl_ctx()
ctx.use_cert (openssl.x509 (open ('../../http/cert/server.crt').read())) ctx.use_cert (openssl.x509 (open ('../../http/cert/server.crt').read()))
ctx.use_key (openssl.pkey (open ('../../http/cert/server.key').read(), '', True)) ctx.use_key (openssl.pkey (open ('../../http/cert/server.key').read(), '', True))
ctx.set_ciphers ('RC4-SHA:RC4-MD5:ALL') ctx.set_ciphers ('RC4-SHA:RC4-MD5:ALL')
#ctx.set_tmp_dh (openssl.dh_param (open ('../../http/cert/dh_param_1024.pem').read())) # ctx.set_tmp_dh (openssl.dh_param (open ('../../http/cert/dh_param_1024.pem').read()))
#ctx.set_next_protos (['spdy/2', 'http/1.1']) # ctx.set_next_protos (['spdy/2', 'http/1.1'])
def session (conn, addr): def session (conn, addr):
conn.ssl.set_fd (conn.fd) conn.ssl.set_fd (conn.fd)
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment