coding standards

This commit is contained in:
Yann Leboulanger 2011-08-24 10:36:00 +02:00
parent 19bc86d9a3
commit a3d772e505
1 changed files with 107 additions and 111 deletions

View File

@ -67,7 +67,7 @@ class SocksQueue:
""" """
def __init__(self, idlequeue, complete_transfer_cb=None, def __init__(self, idlequeue, complete_transfer_cb=None,
progress_transfer_cb=None, error_cb=None): progress_transfer_cb=None, error_cb=None):
self.connected = 0 self.connected = 0
self.readers = {} self.readers = {}
self.files_props = {} self.files_props = {}
@ -85,7 +85,7 @@ class SocksQueue:
self.on_failure = {} # {id: cb} self.on_failure = {} # {id: cb}
def start_listener(self, port, sha_str, sha_handler, fp, fingerprint=None, def start_listener(self, port, sha_str, sha_handler, fp, fingerprint=None,
type='sender'): type='sender'):
""" """
Start waiting for incomming connections on (host, port) and do a socks5 Start waiting for incomming connections on (host, port) and do a socks5
authentication using sid for generated SHA authentication using sid for generated SHA
@ -95,15 +95,15 @@ class SocksQueue:
self.sha_handlers[sha_str] = (sha_handler, sid) self.sha_handlers[sha_str] = (sha_handler, sid)
if self.listener is None: if self.listener is None:
self.listener = Socks5Listener(self.idlequeue, port, fp, self.listener = Socks5Listener(self.idlequeue, port, fp,
fingerprint=fingerprint) fingerprint=fingerprint)
self.listener.queue = self self.listener.queue = self
self.listener.bind() self.listener.bind()
if self.listener.started is False: if self.listener.started is False:
self.listener = None self.listener = None
# We cannot bind port, call error callback and fail # We cannot bind port, call error callback and fail
self.error_cb(_('Unable to bind to port %s.') % port, self.error_cb(_('Unable to bind to port %s.') % port,
_('Maybe you have another running instance of Gajim. File ' _('Maybe you have another running instance of Gajim. File '
'Transfer will be cancelled.')) 'Transfer will be cancelled.'))
return None return None
self.connected += 1 self.connected += 1
return self.listener return self.listener
@ -142,16 +142,14 @@ class SocksQueue:
if receiving: if receiving:
self.type = 'receiver' self.type = 'receiver'
socks5obj = Socks5Receiver(self.idlequeue, streamhost, sid, socks5obj = Socks5Receiver(self.idlequeue, streamhost, sid,
'client', file_props, 'client', file_props, fingerprint=fp)
fingerprint=fp)
self.add_sockobj(account, socks5obj) self.add_sockobj(account, socks5obj)
else: else:
self.type = 'sender' self.type = 'sender'
socks5obj = Socks5Sender(self.idlequeue, socks5obj = Socks5Sender(self.idlequeue, file_props['sha_str'],
file_props['sha_str'], self, mode='client' , self, mode='client' , _sock=None,
_sock=None, host=str(streamhost['host']), host=str(streamhost['host']), port=int(streamhost['port']),
port=int(streamhost['port']), fingerprint=fp, fingerprint=fp, connected=False, file_props=file_props)
connected=False, file_props=file_props)
socks5obj.streamhost = streamhost socks5obj.streamhost = streamhost
self.add_sockobj(account, socks5obj, type='sender') self.add_sockobj(account, socks5obj, type='sender')
@ -206,7 +204,7 @@ class SocksQueue:
# FIXME: make the sender reconnect also # FIXME: make the sender reconnect also
print 'reconnecting using socks receiver' print 'reconnecting using socks receiver'
client = Socks5Receiver(self.idlequeue, host, host['sid'], client = Socks5Receiver(self.idlequeue, host, host['sid'],
'client',file_props) 'client',file_props)
self.add_sockobj(client.account, client) self.add_sockobj(client.account, client)
host['idx'] = client.queue_idx host['idx'] = client.queue_idx
# we still have chances to connect # we still have chances to connect
@ -235,7 +233,7 @@ class SocksQueue:
# failure_cb exists - this means that it has never been called # failure_cb exists - this means that it has never been called
if 'failure_cb' in file_props and file_props['failure_cb']: if 'failure_cb' in file_props and file_props['failure_cb']:
file_props['failure_cb'](streamhost['initiator'], None, file_props['failure_cb'](streamhost['initiator'], None,
file_props['sid'], code = 404) file_props['sid'], code = 404)
del(file_props['failure_cb']) del(file_props['failure_cb'])
def add_sockobj(self, account, sockobj, type='receiver'): def add_sockobj(self, account, sockobj, type='receiver'):
@ -266,7 +264,6 @@ class SocksQueue:
keys = (fp['sid'], fp['name'], hash) keys = (fp['sid'], fp['name'], hash)
sockobjects[keys] = sockobj sockobjects[keys] = sockobj
def result_sha(self, sha_str, idx): def result_sha(self, sha_str, idx):
if sha_str in self.sha_handlers: if sha_str in self.sha_handlers:
props = self.sha_handlers[sha_str] props = self.sha_handlers[sha_str]
@ -303,7 +300,7 @@ class SocksQueue:
def send_file(self, file_props, account, type): def send_file(self, file_props, account, type):
for key in self.senders.keys(): for key in self.senders.keys():
if file_props['name'] in key and file_props['sid'] in key \ if file_props['name'] in key and file_props['sid'] in key \
and self.senders[key].mode == type: and self.senders[key].mode == type:
log.info("socks5: sending file") log.info("socks5: sending file")
sender = self.senders[key] sender = self.senders[key]
@ -319,7 +316,6 @@ class SocksQueue:
file_props['received-len'] = 0 file_props['received-len'] = 0
sender.file_props = file_props sender.file_props = file_props
def add_file_props(self, account, file_props): def add_file_props(self, account, file_props):
""" """
File_prop to the dict of current file_props. It is identified by account File_prop to the dict of current file_props. It is identified by account
@ -367,11 +363,11 @@ class SocksQueue:
def on_connection_accepted(self, sock, listener): def on_connection_accepted(self, sock, listener):
sock_hash = sock.__hash__() sock_hash = sock.__hash__()
if self.type == 'sender' and \ if self.type == 'sender' and \
not self.isHashInSockObjs(self.senders, sock_hash): not self.isHashInSockObjs(self.senders, sock_hash):
sockobj = Socks5Sender(self.idlequeue, sock_hash, self, sockobj = Socks5Sender(self.idlequeue, sock_hash, self, 'server',
'server', sock[0], sock[1][0], sock[1][1], sock[0], sock[1][0], sock[1][1], fingerprint='server',
fingerprint='server', file_props=listener.file_props) file_props=listener.file_props)
self._add(sockobj, self.senders, listener.file_props, sock_hash) self._add(sockobj, self.senders, listener.file_props, sock_hash)
# Start waiting for data # Start waiting for data
self.idlequeue.plug_idle(sockobj, False, True) self.idlequeue.plug_idle(sockobj, False, True)
@ -386,9 +382,8 @@ class SocksQueue:
sh['target'] = None sh['target'] = None
sockobj = Socks5Receiver(idlequeue=self.idlequeue, sockobj = Socks5Receiver(idlequeue=self.idlequeue,
streamhost=sh,sid=None, streamhost=sh,sid=None, file_props=listener.file_props,
file_props=listener.file_props, mode='server',fingerprint='server')
mode='server',fingerprint='server')
self._add(sockobj, self.readers, listener.file_props, sock_hash) self._add(sockobj, self.readers, listener.file_props, sock_hash)
@ -461,7 +456,7 @@ class Socks5:
try: try:
self.host = host self.host = host
self.ais = socket.getaddrinfo(host, port, socket.AF_UNSPEC, self.ais = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM) socket.SOCK_STREAM)
except socket.gaierror: except socket.gaierror:
self.ais = None self.ais = None
self.idlequeue = idlequeue self.idlequeue = idlequeue
@ -532,8 +527,8 @@ class Socks5:
errnum = ee[0] errnum = ee[0]
self.connect_timeout += 1 self.connect_timeout += 1
if errnum == 111 or self.connect_timeout > 1000: if errnum == 111 or self.connect_timeout > 1000:
self.queue._connection_refused(self.streamhost, self.queue._connection_refused(self.streamhost, self.file_props,
self.file_props, self.queue_idx) self.queue_idx)
self.connected = False self.connected = False
return None return None
# win32 needs this # win32 needs this
@ -615,7 +610,7 @@ class Socks5:
self.state = 5 # for senders: init file_props and send '\n' self.state = 5 # for senders: init file_props and send '\n'
if self.queue.on_success: if self.queue.on_success:
result = self.queue.send_success_reply(self.file_props, result = self.queue.send_success_reply(self.file_props,
self.streamhost) self.streamhost)
if result == 0: if result == 0:
self.state = 8 self.state = 8
@ -704,7 +699,7 @@ class Socks5:
self.queue.process_result(result, self) self.queue.process_result(result, self)
return return
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('caught SSL exception, ignored') log.info('caught SSL exception, ignored')
return return
self.state += 1 self.state += 1
@ -714,7 +709,6 @@ class Socks5:
def pollin(self): def pollin(self):
if self.mode == 'client': if self.mode == 'client':
self.clnt_pollin() self.clnt_pollin()
elif self.mode == 'server': elif self.mode == 'server':
@ -731,15 +725,15 @@ class Socks5:
self.disconnect() self.disconnect()
elif self.state == 5: elif self.state == 5:
self.state = 7 self.state = 7
if self.type == 'sender': if self.type == 'sender':
# We wait for the end of the negotiation to # We wait for the end of the negotiation to
# send the file # send the file
self.idlequeue.plug_idle(self, False, False) self.idlequeue.plug_idle(self, False, False)
else: else:
# We plug for reading # We plug for reading
self.idlequeue.plug_idle(self, False, True) self.idlequeue.plug_idle(self, False, True)
return return
elif self.state == 7: elif self.state == 7:
if self.file_props['paused']: if self.file_props['paused']:
@ -750,7 +744,7 @@ class Socks5:
result = self.start_transfer() # send result = self.start_transfer() # send
self.queue.process_result(result, self) self.queue.process_result(result, self)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('caught SSL exception, ignored') log.info('caught SSL exception, ignored')
else: else:
self.disconnect() self.disconnect()
@ -773,7 +767,7 @@ class Socks5:
result = self.start_transfer() # receive result = self.start_transfer() # receive
self.queue.process_result(result, self) self.queue.process_result(result, self)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('caught SSL exception, ignored') log.info('caught SSL exception, ignored')
return return
else: else:
@ -781,7 +775,6 @@ class Socks5:
def pollend(self): def pollend(self):
if self.mode == 'client': if self.mode == 'client':
self.clnt_pollend() self.clnt_pollend()
elif self.mode == 'server': elif self.mode == 'server':
@ -879,7 +872,7 @@ class Socks5:
try: try:
add = self._recv(64) add = self._recv(64)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('SSL rehandshake request : ' + repr(e)) log.info('SSL rehandshake request : ' + repr(e))
raise e raise e
except Exception: except Exception:
@ -896,7 +889,7 @@ class Socks5:
try: try:
self._send(raw_data) self._send(raw_data)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('SSL rehandshake request :' + repr(e)) log.info('SSL rehandshake request :' + repr(e))
raise e raise e
except Exception, e: except Exception, e:
@ -921,7 +914,7 @@ class Socks5:
try: try:
lenn = self._send(buff) lenn = self._send(buff)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('SSL rehandshake request :' + repr(e)) log.info('SSL rehandshake request :' + repr(e))
raise e raise e
except Exception, e: except Exception, e:
@ -934,7 +927,7 @@ class Socks5:
self.size += lenn self.size += lenn
current_time = self.idlequeue.current_time() current_time = self.idlequeue.current_time()
self.file_props['elapsed-time'] += current_time - \ self.file_props['elapsed-time'] += current_time - \
self.file_props['last-time'] self.file_props['last-time']
self.file_props['last-time'] = current_time self.file_props['last-time'] = current_time
self.file_props['received-len'] = self.size self.file_props['received-len'] = self.size
if self.size >= int(self.file_props['size']): if self.size >= int(self.file_props['size']):
@ -975,7 +968,7 @@ class Socks5:
lenn = len(self.remaining_buff) lenn = len(self.remaining_buff)
current_time = self.idlequeue.current_time() current_time = self.idlequeue.current_time()
self.file_props['elapsed-time'] += current_time - \ self.file_props['elapsed-time'] += current_time - \
self.file_props['last-time'] self.file_props['last-time']
self.file_props['last-time'] = current_time self.file_props['last-time'] = current_time
self.file_props['received-len'] += lenn self.file_props['received-len'] += lenn
self.remaining_buff = '' self.remaining_buff = ''
@ -995,14 +988,14 @@ class Socks5:
try: try:
buff = self._recv(MAX_BUFF_LEN) buff = self._recv(MAX_BUFF_LEN)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError, except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantWriteError,
OpenSSL.SSL.WantX509LookupError), e: OpenSSL.SSL.WantX509LookupError), e:
log.info('SSL rehandshake request :' + repr(e)) log.info('SSL rehandshake request :' + repr(e))
raise e raise e
except Exception: except Exception:
buff = '' buff = ''
current_time = self.idlequeue.current_time() current_time = self.idlequeue.current_time()
self.file_props['elapsed-time'] += current_time - \ self.file_props['elapsed-time'] += current_time - \
self.file_props['last-time'] self.file_props['last-time']
self.file_props['last-time'] = current_time self.file_props['last-time'] = current_time
self.file_props['received-len'] += len(buff) self.file_props['received-len'] += len(buff)
if len(buff) == 0: if len(buff) == 0:
@ -1081,10 +1074,12 @@ class Socks5:
return struct.pack('!BB', 0x05, 0x00) return struct.pack('!BB', 0x05, 0x00)
def _get_connect_buff(self): def _get_connect_buff(self):
''' Connect request by domain name ''' """
Connect request by domain name
"""
buff = struct.pack('!BBBBB%dsBB' % len(self.host), buff = struct.pack('!BBBBB%dsBB' % len(self.host),
0x05, 0x01, 0x00, 0x03, len(self.host), self.host, 0x05, 0x01, 0x00, 0x03, len(self.host), self.host, self.port >> 8,
self.port >> 8, self.port & 0xff) self.port & 0xff)
return buff return buff
def _get_request_buff(self, msg, command = 0x01): def _get_request_buff(self, msg, command = 0x01):
@ -1151,8 +1146,8 @@ class Socks5:
if 'is_a_proxy' in self.file_props: if 'is_a_proxy' in self.file_props:
del(self.file_props['is_a_proxy']) del(self.file_props['is_a_proxy'])
return hashlib.sha1('%s%s%s' % (self.sid, return hashlib.sha1('%s%s%s' % (self.sid,
self.file_props['proxy_sender'], self.file_props['proxy_sender'],
self.file_props['proxy_receiver'])).hexdigest() self.file_props['proxy_receiver'])).hexdigest()
return hashlib.sha1('%s%s%s' % (self.sid, self.initiator, self.target)).\ return hashlib.sha1('%s%s%s' % (self.sid, self.initiator, self.target)).\
hexdigest() hexdigest()
@ -1162,8 +1157,7 @@ class Socks5Sender(Socks5, IdleObject):
""" """
def __init__(self, idlequeue, sock_hash, parent, mode,_sock, host=None, def __init__(self, idlequeue, sock_hash, parent, mode,_sock, host=None,
port=None, fingerprint = None, connected=True, port=None, fingerprint = None, connected=True, file_props={}):
file_props={}):
self.fingerprint = fingerprint self.fingerprint = fingerprint
self.queue_idx = sock_hash self.queue_idx = sock_hash
@ -1261,7 +1255,8 @@ class Socks5Listener(IdleObject):
This class implements IdleObject, but we will expect This class implements IdleObject, but we will expect
only pollin events though only pollin events though
fingerprint: fingerprint of certificates we shall use, set to None if TLS connection not desired fingerprint: fingerprint of certificates we shall use, set to None if
TLS connection not desired
""" """
self.port = port self.port = port
self.ais = socket.getaddrinfo(None, port, socket.AF_UNSPEC, self.ais = socket.getaddrinfo(None, port, socket.AF_UNSPEC,
@ -1354,9 +1349,10 @@ class Socks5Listener(IdleObject):
class Socks5Receiver(Socks5, IdleObject): class Socks5Receiver(Socks5, IdleObject):
def __init__(self, idlequeue, streamhost, sid, mode, file_props = None, def __init__(self, idlequeue, streamhost, sid, mode, file_props = None,
fingerprint=None): fingerprint=None):
""" """
fingerprint: fingerprint of certificates we shall use, set to None if TLS connection not desired fingerprint: fingerprint of certificates we shall use, set to None if
TLS connection not desired
""" """
self.queue_idx = -1 self.queue_idx = -1
self.streamhost = streamhost self.streamhost = streamhost