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

More pep8

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