rewritten socks5.py, added support for proxy65
connect to host don;t block, FT in both directions if only one real ip, or proxy
This commit is contained in:
parent
d82dab9fbf
commit
650440fc1d
2 changed files with 668 additions and 320 deletions
|
@ -127,6 +127,7 @@ class Connection:
|
||||||
'GC_SUBJECT': [], 'GC_CONFIG': [], 'BAD_PASSPHRASE': [],
|
'GC_SUBJECT': [], 'GC_CONFIG': [], 'BAD_PASSPHRASE': [],
|
||||||
'ROSTER_INFO': [], 'ERROR_ANSWER': [], 'BOOKMARKS': [], 'CON_TYPE': [],
|
'ROSTER_INFO': [], 'ERROR_ANSWER': [], 'BOOKMARKS': [], 'CON_TYPE': [],
|
||||||
'FILE_REQUEST': [], 'FILE_RCV_COMPLETED': [], 'FILE_PROGRESS': [],
|
'FILE_REQUEST': [], 'FILE_RCV_COMPLETED': [], 'FILE_PROGRESS': [],
|
||||||
|
'FILE_REQUEST_ERROR': [], 'FILE_SEND_ERROR': [],
|
||||||
'STANZA_ARRIVED': [], 'STANZA_SENT': [], 'HTTP_AUTH': []
|
'STANZA_ARRIVED': [], 'STANZA_SENT': [], 'HTTP_AUTH': []
|
||||||
}
|
}
|
||||||
self.name = name
|
self.name = name
|
||||||
|
@ -378,7 +379,23 @@ class Connection:
|
||||||
(_('Connection with account "%s" has been lost') % self.name,
|
(_('Connection with account "%s" has been lost') % self.name,
|
||||||
_('To continue sending and receiving messages, you will need to reconnect.')))
|
_('To continue sending and receiving messages, you will need to reconnect.')))
|
||||||
self.on_purpose = False
|
self.on_purpose = False
|
||||||
|
|
||||||
# END disconenctedCB
|
# END disconenctedCB
|
||||||
|
def _bytestreamErrorCB(self, con, iq_obj):
|
||||||
|
gajim.log.debug('_bytestreamErrorCB')
|
||||||
|
frm = str(iq_obj.getFrom())
|
||||||
|
id = str(iq_obj.getAttr('id'))
|
||||||
|
query = iq_obj.getTag('query')
|
||||||
|
streamhost = query.getTag('streamhost')
|
||||||
|
host = streamhost.getAttr('host')
|
||||||
|
port = streamhost.getAttr('port')
|
||||||
|
jid = iq_obj.getFrom().getStripped().encode('utf8')
|
||||||
|
id = id[3:]
|
||||||
|
if not self.files_props.has_key(id):
|
||||||
|
return
|
||||||
|
file_props = self.files_props[id]
|
||||||
|
self.dispatch('FILE_REQUEST_ERROR', (jid, file_props))
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
|
|
||||||
def _bytestreamSetCB(self, con, iq_obj):
|
def _bytestreamSetCB(self, con, iq_obj):
|
||||||
gajim.log.debug('_bytestreamSetCB')
|
gajim.log.debug('_bytestreamSetCB')
|
||||||
|
@ -388,13 +405,15 @@ class Connection:
|
||||||
sid = str(query.getAttr('sid'))
|
sid = str(query.getAttr('sid'))
|
||||||
file_props = gajim.socks5queue.get_file_props(
|
file_props = gajim.socks5queue.get_file_props(
|
||||||
self.name, sid)
|
self.name, sid)
|
||||||
if file_props is None:
|
|
||||||
raise common.xmpp.NodeProcessed
|
|
||||||
# todo - error
|
|
||||||
streamhosts=[]
|
streamhosts=[]
|
||||||
for item in query.getChildren():
|
for item in query.getChildren():
|
||||||
if item.getName() == 'streamhost':
|
if item.getName() == 'streamhost':
|
||||||
host_dict={}
|
host_dict={
|
||||||
|
'state' : 0,
|
||||||
|
'target' : target,
|
||||||
|
'id' : id,
|
||||||
|
'initiator' : str(iq_obj.getFrom())
|
||||||
|
}
|
||||||
for attr in item.getAttrs():
|
for attr in item.getAttrs():
|
||||||
val = item.getAttr(attr)
|
val = item.getAttr(attr)
|
||||||
if type(val) == unicode:
|
if type(val) == unicode:
|
||||||
|
@ -403,36 +422,163 @@ class Connection:
|
||||||
attr = attr.encode('utf-8')
|
attr = attr.encode('utf-8')
|
||||||
host_dict[attr] = val
|
host_dict[attr] = val
|
||||||
streamhosts.append(host_dict)
|
streamhosts.append(host_dict)
|
||||||
|
if file_props is None:
|
||||||
for streamhost in streamhosts:
|
if self.files_props.has_key(sid):
|
||||||
sock5 = socks5.Socks5Receiver(host = streamhost['host'], \
|
file_props = self.files_props[sid]
|
||||||
port = int(streamhost['port']), initiator = streamhost['jid'],
|
file_props['fast'] = streamhosts
|
||||||
target = target, sid = sid, file_props = file_props)
|
|
||||||
iq = common.xmpp.Iq(to = streamhost['jid'], typ = 'result', frm = target)
|
# this is not good, but the only way to work with psi!
|
||||||
iq.setAttr('id', id)
|
if len(gajim.socks5queue.readers) == 0 and \
|
||||||
query = iq.setTag('query')
|
len(gajim.socks5queue.senders) == 0:
|
||||||
query.setNamespace(common.xmpp.NS_BYTESTREAM)
|
self._connect_error(str(iq_obj.getFrom()), id, code = 406)
|
||||||
stream_tag = query.setTag('streamhost-used')
|
# END not good
|
||||||
stream_tag.setAttr('jid', streamhost['jid'])
|
|
||||||
ret = gajim.socks5queue.add_receiver(self.name, sock5,
|
raise common.xmpp.NodeProcessed
|
||||||
self.to_be_sent.append, iq)
|
fast = None
|
||||||
if ret is None:
|
try:
|
||||||
continue
|
fast = query.getTag('fast')
|
||||||
raise common.xmpp.NodeProcessed
|
except Exception, e:
|
||||||
|
pass
|
||||||
|
if fast is not None:
|
||||||
|
if fast.getNamespace() == 'http://affinix.com/jabber/stream':
|
||||||
|
self.send_socks5_info(file_props, fast = False, \
|
||||||
|
receiver = file_props['sender'], sender = file_props['receiver'])
|
||||||
|
self.files_props[sid] = file_props
|
||||||
|
file_props['streamhosts'] = streamhosts
|
||||||
|
conn_err = False
|
||||||
|
if file_props['type'] == 'r':
|
||||||
|
gajim.socks5queue.connect_to_hosts(self.name, sid,
|
||||||
|
self.send_success_connect_reply, self._connect_error)
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
|
|
||||||
|
def send_success_connect_reply(self, streamhost):
|
||||||
|
''' send reply to the initiator of FT that we
|
||||||
|
made a connection
|
||||||
|
'''
|
||||||
|
if streamhost is None:
|
||||||
|
return None
|
||||||
|
iq = common.xmpp.Iq(to = streamhost['initiator'], typ = 'result', \
|
||||||
|
frm = streamhost['target'])
|
||||||
|
iq.setAttr('id', streamhost['id'])
|
||||||
|
query = iq.setTag('query')
|
||||||
|
query.setNamespace(common.xmpp.NS_BYTESTREAM)
|
||||||
|
stream_tag = query.setTag('streamhost-used')
|
||||||
|
stream_tag.setAttr('jid', streamhost['jid'])
|
||||||
|
self.to_be_sent.append(iq)
|
||||||
|
|
||||||
|
def _connect_error(self, to, id, code = 404):
|
||||||
|
msg_dict = {
|
||||||
|
404 : 'Could not connect to given hosts',
|
||||||
|
405 : 'Cancel',
|
||||||
|
406 : 'Not acceptable',
|
||||||
|
}
|
||||||
|
msg = msg_dict[code]
|
||||||
|
iq = None
|
||||||
|
iq = common.xmpp.Protocol(name = 'iq', to = to,
|
||||||
|
typ = 'error')
|
||||||
|
iq.setAttr('id', id)
|
||||||
|
err = iq.setTag('error')
|
||||||
|
err.setAttr('code', str(code))
|
||||||
|
err.setData(msg)
|
||||||
|
self.to_be_sent.append(iq)
|
||||||
|
|
||||||
def _bytestreamResultCB(self, con, iq_obj):
|
def _bytestreamResultCB(self, con, iq_obj):
|
||||||
gajim.log.debug('_bytestreamResultCB')
|
gajim.log.debug('_bytestreamResultCB')
|
||||||
frm = str(iq_obj.getFrom())
|
frm = str(iq_obj.getFrom())
|
||||||
id = str(iq_obj.getAttr('id'))
|
real_id = str(iq_obj.getAttr('id'))
|
||||||
query = iq_obj.getTag('query')
|
query = iq_obj.getTag('query')
|
||||||
|
id = real_id[3:]
|
||||||
|
if not self.files_props.has_key(id):
|
||||||
|
file_props = gajim.socks5queue.get_file_props(
|
||||||
|
self.name, id)
|
||||||
|
gajim.socks5queue.get_file_from_sender(file_props, self.name)
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
|
file_props = self.files_props[id]
|
||||||
|
if real_id[:3] == 'au_':
|
||||||
|
gajim.socks5queue.send_file(file_props, self.name)
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
|
elif real_id[:3] == 'px_':
|
||||||
|
proxyhosts = []
|
||||||
|
for item in query.getChildren():
|
||||||
|
if item.getName() == 'streamhost':
|
||||||
|
host_dict={
|
||||||
|
'state' : 0,
|
||||||
|
'target' : str(iq_obj.getAttr('to')),
|
||||||
|
'id' : id,
|
||||||
|
'initiator' : str(iq_obj.getFrom())
|
||||||
|
}
|
||||||
|
for attr in item.getAttrs():
|
||||||
|
val = item.getAttr(attr)
|
||||||
|
host_dict[str(attr)] = str(val)
|
||||||
|
proxyhosts.append(host_dict)
|
||||||
|
file_props['proxyhosts'] = proxyhosts
|
||||||
|
iq = common.xmpp.Protocol(name = 'iq', to = \
|
||||||
|
str(file_props['proxy_receiver']), typ = 'set')
|
||||||
|
port = gajim.config.get('file_transfers_port')
|
||||||
|
file_props['request-id'] = 'id_' + file_props['sid']
|
||||||
|
iq.setID(file_props['request-id'])
|
||||||
|
query = iq.setTag('query')
|
||||||
|
query.setNamespace(common.xmpp.NS_BYTESTREAM)
|
||||||
|
query.setAttr('mode', 'tcp')
|
||||||
|
query.setAttr('sid', file_props['sid'])
|
||||||
|
streamhost = query.setTag('streamhost')
|
||||||
|
streamhost.setAttr('port', str(port))
|
||||||
|
streamhost.setAttr('host', self.peerhost[0])
|
||||||
|
streamhost.setAttr('jid', str(file_props['proxy_sender']))
|
||||||
|
for proxyhost in proxyhosts:
|
||||||
|
streamhost = common.xmpp.Node(tag = 'streamhost')
|
||||||
|
query.addChild(node=streamhost)
|
||||||
|
streamhost.setAttr('port', proxyhost['port'])
|
||||||
|
streamhost.setAttr('host', proxyhost['host'])
|
||||||
|
streamhost.setAttr('jid', proxyhost['jid'])
|
||||||
|
proxy = streamhost.setTag('proxy')
|
||||||
|
proxy.setNamespace(common.xmpp.NS_STREAM)
|
||||||
|
fast_tag = query.setTag('fast')
|
||||||
|
fast_tag.setNamespace(common.xmpp.NS_STREAM)
|
||||||
|
self.to_be_sent.append(iq)
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
streamhost = query.getTag('streamhost-used')
|
streamhost = query.getTag('streamhost-used')
|
||||||
jid = streamhost.getAttr('jid')
|
jid = streamhost.getAttr('jid')
|
||||||
id = id[3:]
|
proxy = None
|
||||||
if not self.files_props.has_key(id):
|
if file_props.has_key('proxyhosts'):
|
||||||
return
|
for proxyhost in file_props['proxyhosts']:
|
||||||
file_props = self.files_props[id]
|
if proxyhost['jid'] == jid:
|
||||||
gajim.socks5queue.send_file(file_props, self.name)
|
proxy = proxyhost
|
||||||
|
if proxy != None:
|
||||||
|
if not file_props.has_key('streamhosts'):
|
||||||
|
file_props['streamhosts'] =[]
|
||||||
|
file_props['streamhosts'].append(proxy)
|
||||||
|
file_props['is_a_proxy'] = True
|
||||||
|
receiver = socks5.Socks5Receiver(proxy, file_props['sid'], file_props)
|
||||||
|
gajim.socks5queue.add_receiver(self.name, receiver)
|
||||||
|
proxy['idx'] = receiver.queue_idx
|
||||||
|
gajim.socks5queue.on_success = self.proxy_auth_ok
|
||||||
|
raise common.xmpp.NodeProcessed
|
||||||
|
|
||||||
|
elif not file_props.has_key('connected') or \
|
||||||
|
file_props['connected'] is False:
|
||||||
|
gajim.socks5queue.send_file(file_props, self.name)
|
||||||
|
if file_props.has_key('fast'):
|
||||||
|
fasts = file_props['fast']
|
||||||
|
if len(fasts) > 0:
|
||||||
|
self._connect_error(str(iq_obj.getFrom()), fasts[0]['id'],
|
||||||
|
code = 406)
|
||||||
raise common.xmpp.NodeProcessed
|
raise common.xmpp.NodeProcessed
|
||||||
|
|
||||||
|
def proxy_auth_ok(self, proxy):
|
||||||
|
''' cb, called after authentication to proxy server '''
|
||||||
|
file_props = self.files_props[proxy['id']]
|
||||||
|
iq = common.xmpp.Protocol(name = 'iq', to = proxy['initiator'],
|
||||||
|
typ = 'set')
|
||||||
|
auth_id = "au_" + proxy['id']
|
||||||
|
iq.setID(auth_id)
|
||||||
|
query = iq.setTag('query')
|
||||||
|
query.setNamespace(common.xmpp.NS_BYTESTREAM)
|
||||||
|
query.setAttr('sid', proxy['id'])
|
||||||
|
activate = query.setTag('activate')
|
||||||
|
activate.setData(file_props['proxy_receiver'])
|
||||||
|
iq.setID(auth_id)
|
||||||
|
self.to_be_sent.append(iq)
|
||||||
|
|
||||||
def _discoGetCB(self, con, iq_obj):
|
def _discoGetCB(self, con, iq_obj):
|
||||||
''' get disco info '''
|
''' get disco info '''
|
||||||
|
@ -480,7 +626,7 @@ class Connection:
|
||||||
field = form.getField('stream-method')
|
field = form.getField('stream-method')
|
||||||
if field.getValue() != common.xmpp.NS_BYTESTREAM:
|
if field.getValue() != common.xmpp.NS_BYTESTREAM:
|
||||||
return
|
return
|
||||||
self.send_socks5_info(file_props)
|
self.send_socks5_info(file_props, fast = True)
|
||||||
raise common.xmpp.NodeProcessed
|
raise common.xmpp.NodeProcessed
|
||||||
|
|
||||||
def _get_sha(self, sid, initiator, target):
|
def _get_sha(self, sid, initiator, target):
|
||||||
|
@ -488,25 +634,47 @@ class Connection:
|
||||||
return sha.new("%s%s%s" % (sid, initiator, target)).hexdigest()
|
return sha.new("%s%s%s" % (sid, initiator, target)).hexdigest()
|
||||||
|
|
||||||
def result_socks5_sid(self, sid, hash_id):
|
def result_socks5_sid(self, sid, hash_id):
|
||||||
|
''' store the result of sha message from auth '''
|
||||||
if not self.files_props.has_key(sid):
|
if not self.files_props.has_key(sid):
|
||||||
return
|
return
|
||||||
file_props = self.files_props[sid]
|
file_props = self.files_props[sid]
|
||||||
file_props['hash'] = hash_id
|
file_props['hash'] = hash_id
|
||||||
return
|
return
|
||||||
|
|
||||||
def send_socks5_info(self, file_props):
|
def send_socks5_info(self, file_props, fast = True, receiver = None,
|
||||||
|
sender = None):
|
||||||
if type(self.peerhost) != tuple:
|
if type(self.peerhost) != tuple:
|
||||||
return
|
return
|
||||||
port = gajim.config.get('file_transfers_port')
|
port = gajim.config.get('file_transfers_port')
|
||||||
sha_str = self._get_sha(file_props['sid'], file_props['sender'],
|
proxy = gajim.config.get_per('accounts', self.name, 'file_transfers_proxy')
|
||||||
file_props['receiver'])
|
#~ proxy = 'proxy.jabber.org'
|
||||||
|
if receiver is None:
|
||||||
|
receiver = file_props['receiver']
|
||||||
|
if sender is None:
|
||||||
|
sender = file_props['sender']
|
||||||
|
|
||||||
|
sha_str = self._get_sha(file_props['sid'], sender,
|
||||||
|
receiver)
|
||||||
file_props['sha_str'] = sha_str
|
file_props['sha_str'] = sha_str
|
||||||
listener = gajim.socks5queue.start_listener(self.peerhost[0], port,
|
listener = gajim.socks5queue.start_listener(self.peerhost[0], port,
|
||||||
sha_str, self.result_socks5_sid, file_props['sid'])
|
sha_str, self.result_socks5_sid, file_props['sid'])
|
||||||
if listener == None:
|
if listener == None:
|
||||||
# FIXME - raise error dialog that address is in use
|
# FIXME - raise error dialog that address is in use
|
||||||
return
|
return
|
||||||
iq = common.xmpp.Protocol(name = 'iq', to = str(file_props['receiver']),
|
|
||||||
|
if proxy:
|
||||||
|
iq = common.xmpp.Protocol(name = 'iq', to = str(proxy),
|
||||||
|
typ = 'get')
|
||||||
|
proxy_id = 'px_' + file_props['sid']
|
||||||
|
iq.setID(proxy_id)
|
||||||
|
query = iq.setTag('query')
|
||||||
|
query.setNamespace(common.xmpp.NS_BYTESTREAM)
|
||||||
|
self.to_be_sent.append(iq)
|
||||||
|
file_props['proxy_receiver'] = str(receiver)
|
||||||
|
file_props['proxy_sender'] = str(sender)
|
||||||
|
return
|
||||||
|
|
||||||
|
iq = common.xmpp.Protocol(name = 'iq', to = str(receiver),
|
||||||
typ = 'set')
|
typ = 'set')
|
||||||
file_props['request-id'] = 'id_' + file_props['sid']
|
file_props['request-id'] = 'id_' + file_props['sid']
|
||||||
iq.setID(file_props['request-id'])
|
iq.setID(file_props['request-id'])
|
||||||
|
@ -517,7 +685,12 @@ class Connection:
|
||||||
streamhost = query.setTag('streamhost')
|
streamhost = query.setTag('streamhost')
|
||||||
streamhost.setAttr('port', str(port))
|
streamhost.setAttr('port', str(port))
|
||||||
streamhost.setAttr('host', self.peerhost[0])
|
streamhost.setAttr('host', self.peerhost[0])
|
||||||
streamhost.setAttr('jid', str(file_props['sender']))
|
streamhost.setAttr('jid', sender)
|
||||||
|
|
||||||
|
if fast:
|
||||||
|
fast_tag = query.setTag('fast')
|
||||||
|
fast_tag.setNamespace(common.xmpp.NS_STREAM)
|
||||||
|
|
||||||
self.to_be_sent.append(iq)
|
self.to_be_sent.append(iq)
|
||||||
|
|
||||||
def _siSetCB(self, con, iq_obj):
|
def _siSetCB(self, con, iq_obj):
|
||||||
|
@ -546,7 +719,10 @@ class Connection:
|
||||||
|
|
||||||
if mime_type is not None:
|
if mime_type is not None:
|
||||||
file_props['mime-type'] = mime_type
|
file_props['mime-type'] = mime_type
|
||||||
|
name = gajim.config.get_per('accounts', self.name, 'name')
|
||||||
|
hostname = gajim.config.get_per('accounts', self.name, 'hostname')
|
||||||
|
resource = gajim.config.get_per('accounts', self.name, 'resource')
|
||||||
|
file_props['receiver'] = name + '@' + hostname + '/' + resource
|
||||||
file_props['sender'] = iq_obj.getFrom()
|
file_props['sender'] = iq_obj.getFrom()
|
||||||
file_props['request-id'] = str(iq_obj.getAttr('id'))
|
file_props['request-id'] = str(iq_obj.getAttr('id'))
|
||||||
file_props['sid'] = str(si.getAttr('id'))
|
file_props['sid'] = str(si.getAttr('id'))
|
||||||
|
@ -994,6 +1170,8 @@ class Connection:
|
||||||
common.xmpp.NS_BYTESTREAM)
|
common.xmpp.NS_BYTESTREAM)
|
||||||
con.RegisterHandler('iq', self._bytestreamResultCB, 'result',
|
con.RegisterHandler('iq', self._bytestreamResultCB, 'result',
|
||||||
common.xmpp.NS_BYTESTREAM)
|
common.xmpp.NS_BYTESTREAM)
|
||||||
|
con.RegisterHandler('iq', self._bytestreamErrorCB, 'error',
|
||||||
|
common.xmpp.NS_BYTESTREAM)
|
||||||
con.RegisterHandler('iq', self._BrowseResultCB, 'result',
|
con.RegisterHandler('iq', self._BrowseResultCB, 'result',
|
||||||
common.xmpp.NS_BROWSE)
|
common.xmpp.NS_BROWSE)
|
||||||
con.RegisterHandler('iq', self._DiscoverItemsCB, 'result',
|
con.RegisterHandler('iq', self._DiscoverItemsCB, 'result',
|
||||||
|
|
|
@ -44,6 +44,8 @@ class SocksQueue:
|
||||||
self.sha_handlers = {}
|
self.sha_handlers = {}
|
||||||
self.complete_transfer_cb = complete_transfer_cb
|
self.complete_transfer_cb = complete_transfer_cb
|
||||||
self.progress_transfer_cb = progress_transfer_cb
|
self.progress_transfer_cb = progress_transfer_cb
|
||||||
|
self.on_success = None
|
||||||
|
self.on_failure = None
|
||||||
|
|
||||||
def start_listener(self, host, port, sha_str, sha_handler, sid):
|
def start_listener(self, host, port, sha_str, sha_handler, sid):
|
||||||
self.sha_handlers[sha_str] = (sha_handler, sid)
|
self.sha_handlers[sha_str] = (sha_handler, sid)
|
||||||
|
@ -54,41 +56,88 @@ class SocksQueue:
|
||||||
return None
|
return None
|
||||||
self.connected += 1
|
self.connected += 1
|
||||||
return self.listener
|
return self.listener
|
||||||
|
|
||||||
|
def connect_to_hosts(self, account, sid, on_success = None,
|
||||||
|
on_failure = None):
|
||||||
|
self.on_success = on_success
|
||||||
|
self.on_failure = on_failure
|
||||||
|
if not self.files_props.has_key(account):
|
||||||
|
pass
|
||||||
|
# FIXME ---- show error dialog
|
||||||
|
else:
|
||||||
|
file_props = self.files_props[account][sid]
|
||||||
|
file_props['success_cb'] = on_success
|
||||||
|
file_props['failure_cb'] = on_failure
|
||||||
|
for streamhost in file_props['streamhosts']:
|
||||||
|
receiver = Socks5Receiver(streamhost, sid, file_props)
|
||||||
|
self.add_receiver(account, receiver)
|
||||||
|
streamhost['idx'] = receiver.queue_idx
|
||||||
|
def _socket_connected(self, streamhost, file_props):
|
||||||
|
streamhost['state'] = 0
|
||||||
|
for host in file_props['streamhosts']:
|
||||||
|
if host != streamhost and host.has_key('idx'):
|
||||||
|
host['state'] = -1
|
||||||
|
self.remove_receiver(host['idx'])
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _connection_refused(self, streamhost, file_props, idx):
|
||||||
|
if file_props is None:
|
||||||
|
return
|
||||||
|
streamhost['state'] = -1
|
||||||
|
self.remove_receiver(idx)
|
||||||
|
if file_props['failure_cb']:
|
||||||
|
file_props['failure_cb'](streamhost['initiator'], streamhost['id'],
|
||||||
|
code = 404)
|
||||||
|
else:
|
||||||
|
# show error dialog, it seems to be the laast try
|
||||||
|
pass
|
||||||
|
|
||||||
|
def add_receiver(self, account, sock5_receiver):
|
||||||
|
''' add new file request '''
|
||||||
|
self.readers[self.idx] = sock5_receiver
|
||||||
|
sock5_receiver.queue_idx = self.idx
|
||||||
|
sock5_receiver.queue = self
|
||||||
|
sock5_receiver.account = account
|
||||||
|
self.idx += 1
|
||||||
|
result = sock5_receiver.connect()
|
||||||
|
if result != None:
|
||||||
|
self.connected += 1
|
||||||
|
result = sock5_receiver.main()
|
||||||
|
self.process_result(result, sock5_receiver)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_file_from_sender(self, file_props, account):
|
||||||
|
if file_props.has_key('hash') and \
|
||||||
|
self.senders.has_key(file_props['hash']):
|
||||||
|
sender = self.senders[file_props['hash']]
|
||||||
|
sender.account = account
|
||||||
|
result = get_file_contents(0)
|
||||||
|
self.process_result(result, sender)
|
||||||
|
|
||||||
def result_sha(self, sha_str, idx):
|
def result_sha(self, sha_str, idx):
|
||||||
if self.sha_handlers.has_key(sha_str):
|
if self.sha_handlers.has_key(sha_str):
|
||||||
props = self.sha_handlers[sha_str]
|
props = self.sha_handlers[sha_str]
|
||||||
props[0](props[1], idx)
|
props[0](props[1], idx)
|
||||||
|
|
||||||
def send_file(self, file_props, account):
|
def send_file(self, file_props, account):
|
||||||
if self.senders.has_key(file_props['hash']):
|
if file_props.has_key('hash') and \
|
||||||
|
self.senders.has_key(file_props['hash']):
|
||||||
sender = self.senders[file_props['hash']]
|
sender = self.senders[file_props['hash']]
|
||||||
sender.account = account
|
sender.account = account
|
||||||
result = sender.send_file(file_props)
|
if file_props['type'] == 's':
|
||||||
self.process_result(result, sender)
|
sender.file_props = file_props
|
||||||
|
result = sender.send_file()
|
||||||
def add_receiver(self, account, sock5_receiver, auth_cb, auth_param):
|
self.process_result(result, sender)
|
||||||
''' add new file request '''
|
else:
|
||||||
self.readers[self.idx] = sock5_receiver
|
file_props['received-len'] = 0
|
||||||
sock5_receiver.queue_idx = self.idx
|
sender.file_props = file_props
|
||||||
sock5_receiver.queue = self
|
|
||||||
sock5_receiver.account = account
|
|
||||||
sock5_receiver.auth_cb = auth_cb
|
|
||||||
sock5_receiver.auth_param = auth_param
|
|
||||||
self.idx += 1
|
|
||||||
result = sock5_receiver.connect()
|
|
||||||
if result != None:
|
|
||||||
sock5_receiver._sock.setblocking(False)
|
|
||||||
result = sock5_receiver.main()
|
|
||||||
self.process_result(result, sock5_receiver)
|
|
||||||
self.connected += 1
|
|
||||||
return 1
|
|
||||||
# we don't need blocking sockets anymore
|
|
||||||
# this unblocks ui!
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
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 name and sid
|
||||||
|
'''
|
||||||
if file_props is None or \
|
if file_props is None or \
|
||||||
file_props.has_key('sid') is False:
|
file_props.has_key('sid') is False:
|
||||||
return
|
return
|
||||||
|
@ -96,7 +145,9 @@ class SocksQueue:
|
||||||
if not self.files_props.has_key(account):
|
if not self.files_props.has_key(account):
|
||||||
self.files_props[account] = {}
|
self.files_props[account] = {}
|
||||||
self.files_props[account][id] = file_props
|
self.files_props[account][id] = file_props
|
||||||
|
|
||||||
def get_file_props(self, account, sid):
|
def get_file_props(self, account, sid):
|
||||||
|
''' get fil_prop by account name and session id '''
|
||||||
if self.files_props.has_key(account):
|
if self.files_props.has_key(account):
|
||||||
fl_props = self.files_props[account]
|
fl_props = self.files_props[account]
|
||||||
if fl_props.has_key(sid):
|
if fl_props.has_key(sid):
|
||||||
|
@ -104,7 +155,9 @@ class SocksQueue:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def process(self, timeout=0):
|
def process(self, timeout=0):
|
||||||
''' process all file requests '''
|
''' Process all registered connection.
|
||||||
|
they can be receivers, senders and one listener
|
||||||
|
'''
|
||||||
if self.listener is not None:
|
if self.listener is not None:
|
||||||
if self.listener.pending_connection():
|
if self.listener.pending_connection():
|
||||||
_sock = self.listener.accept_conn()
|
_sock = self.listener.accept_conn()
|
||||||
|
@ -117,9 +170,8 @@ class SocksQueue:
|
||||||
for idx in self.senders.keys():
|
for idx in self.senders.keys():
|
||||||
sender = self.senders[idx]
|
sender = self.senders[idx]
|
||||||
if sender.connected:
|
if sender.connected:
|
||||||
|
|
||||||
if sender.state < 5:
|
if sender.state < 5:
|
||||||
if sender.pending_data():
|
if sender.pending_data(timeout):
|
||||||
result = sender.main()
|
result = sender.main()
|
||||||
if sender.state == 4:
|
if sender.state == 4:
|
||||||
self.result_sha(sender.sha_msg, idx)
|
self.result_sha(sender.sha_msg, idx)
|
||||||
|
@ -127,41 +179,57 @@ class SocksQueue:
|
||||||
continue
|
continue
|
||||||
if result == -1:
|
if result == -1:
|
||||||
sender.disconnect()
|
sender.disconnect()
|
||||||
elif sender.state == 7:
|
elif sender.state == 5:
|
||||||
for i in range(5):
|
if sender.file_props is not None and \
|
||||||
if sender.file_props['paused']:
|
sender.file_props['type'] == 'r':
|
||||||
break
|
result = sender.get_file_contents(0)
|
||||||
if not sender.connected:
|
|
||||||
self.process_result(-1, sender)
|
|
||||||
break
|
|
||||||
if sender.state == 8:
|
|
||||||
self.remove_sender(idx)
|
|
||||||
break
|
|
||||||
result = sender.write_next()
|
|
||||||
self.process_result(result, sender)
|
self.process_result(result, sender)
|
||||||
if sender.file_props['stalled']:
|
elif sender.state == 7 and not sender.file_props['paused']:
|
||||||
break
|
if not sender.connected:
|
||||||
|
self.process_result(-1, sender)
|
||||||
|
break
|
||||||
|
if sender.state == 8:
|
||||||
|
self.remove_sender(idx)
|
||||||
|
break
|
||||||
|
result = sender.write_next()
|
||||||
|
self.process_result(result, sender)
|
||||||
|
if sender.file_props['stalled']:
|
||||||
|
break
|
||||||
elif sender.state == 8:
|
elif sender.state == 8:
|
||||||
self.remove_sender(idx)
|
self.remove_sender(idx)
|
||||||
else:
|
else:
|
||||||
self.remove_sender(idx)
|
self.remove_sender(idx)
|
||||||
for idx in self.readers.keys():
|
keys = self.readers.keys()
|
||||||
|
for idx in keys:
|
||||||
|
if not self.readers.has_key(idx):
|
||||||
|
continue
|
||||||
receiver = self.readers[idx]
|
receiver = self.readers[idx]
|
||||||
|
if receiver.state == 0:
|
||||||
|
res = receiver.do_connect()
|
||||||
|
continue
|
||||||
if receiver.connected:
|
if receiver.connected:
|
||||||
if receiver.file_props['paused']:
|
if receiver.file_props['paused']:
|
||||||
continue
|
continue
|
||||||
if receiver.state == 5:
|
if receiver.state < 5:
|
||||||
result = receiver.get_file_contents(timeout)
|
pd = receiver.pending_data(0)
|
||||||
self.process_result(result, receiver)
|
|
||||||
else:
|
|
||||||
pd = receiver.pending_data()
|
|
||||||
if pd:
|
if pd:
|
||||||
result = receiver.main(timeout)
|
result = receiver.main(0)
|
||||||
self.process_result(result, receiver)
|
self.process_result(result, receiver)
|
||||||
|
else:
|
||||||
|
if receiver.file_props['type'] == 'r':
|
||||||
|
result = receiver.get_file_contents(timeout)
|
||||||
|
else:
|
||||||
|
result = receiver.write_next()
|
||||||
|
self.process_result(result, receiver)
|
||||||
else:
|
else:
|
||||||
self.remove_receiver(idx)
|
self.remove_receiver(idx)
|
||||||
|
|
||||||
def process_result(self, result, actor):
|
def process_result(self, result, actor):
|
||||||
|
''' Take appropriate actions upon the result:
|
||||||
|
[ 0, - 1 ] complete/end transfer
|
||||||
|
[ > 0 ] send progress message
|
||||||
|
[ None ] do nothing
|
||||||
|
'''
|
||||||
if result is None:
|
if result is None:
|
||||||
return
|
return
|
||||||
if result in [0, -1] and \
|
if result in [0, -1] and \
|
||||||
|
@ -173,12 +241,17 @@ class SocksQueue:
|
||||||
actor.file_props)
|
actor.file_props)
|
||||||
|
|
||||||
def remove_receiver(self, idx):
|
def remove_receiver(self, idx):
|
||||||
|
''' Remove reciver from the list and decrease
|
||||||
|
the number of active connections with 1'''
|
||||||
if idx != -1:
|
if idx != -1:
|
||||||
if self.readers.has_key(idx):
|
if self.readers.has_key(idx):
|
||||||
|
if self.readers[idx].streamhost is not None:
|
||||||
|
self.readers[idx].streamhost['state'] = -1
|
||||||
del(self.readers[idx])
|
del(self.readers[idx])
|
||||||
if self.connected > 0:
|
|
||||||
self.connected -= 1
|
|
||||||
def remove_sender(self, idx):
|
def remove_sender(self, idx):
|
||||||
|
''' Remove reciver from the list of senders and decrease the
|
||||||
|
number of active connections with 1'''
|
||||||
if idx != -1:
|
if idx != -1:
|
||||||
if self.senders.has_key(idx):
|
if self.senders.has_key(idx):
|
||||||
del(self.senders[idx])
|
del(self.senders[idx])
|
||||||
|
@ -196,159 +269,69 @@ class Socks5:
|
||||||
self._sock = None
|
self._sock = None
|
||||||
self.account = None
|
self.account = None
|
||||||
self.state = 0 # not connected
|
self.state = 0 # not connected
|
||||||
|
self.pauses = 0
|
||||||
def connect(self):
|
self.size = 0
|
||||||
self._sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
self.remaining_buff = ''
|
||||||
try:
|
|
||||||
self._sock.connect((self.host, self.port))
|
|
||||||
self._sock.setblocking(False)
|
|
||||||
self._send=self._sock.send
|
|
||||||
self._recv=self._sock.recv
|
|
||||||
except Exception, e:
|
|
||||||
return None
|
|
||||||
self.buff = ''
|
|
||||||
self.connected = True
|
|
||||||
self.state = 1 # connected
|
|
||||||
return 1
|
|
||||||
|
|
||||||
def receive(self):
|
|
||||||
''' Reads small pending incoming data.
|
|
||||||
Calls owner's disconnected() method if appropriate.'''
|
|
||||||
|
|
||||||
|
def get_fd(self):
|
||||||
|
''' Test if file is already open and return its fd,
|
||||||
|
or just open the file and return the fd.
|
||||||
|
'''
|
||||||
|
if self.file_props.has_key('fd'):
|
||||||
|
fd = self.file_props['fd']
|
||||||
|
else:
|
||||||
|
fd = open(self.file_props['file-name'],'w')
|
||||||
|
self.file_props['fd'] = fd
|
||||||
|
self.file_props['received-len'] = 0
|
||||||
|
return fd
|
||||||
|
|
||||||
|
def rem_fd(self, fd):
|
||||||
|
if self.file_props.has_key('fd'):
|
||||||
|
del(self.file_props['fd'])
|
||||||
|
try:
|
||||||
|
fd.close()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def receive(self):
|
||||||
|
''' Reads small chunks of data.
|
||||||
|
Calls owner's disconnected() method if appropriate.'''
|
||||||
if self.pending_read():
|
if self.pending_read():
|
||||||
received = ''
|
received = ''
|
||||||
while self.pending_read():
|
try:
|
||||||
try:
|
add = self._recv(64)
|
||||||
add = self._recv(64)
|
except Exception, e:
|
||||||
except Exception, e:
|
add=''
|
||||||
add=''
|
received +=add
|
||||||
received +=add
|
if len(add) == 0:
|
||||||
if not add:
|
|
||||||
break
|
|
||||||
if len(received) == 0:
|
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
return received
|
return add
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def send_raw(self,raw_data):
|
def send_raw(self,raw_data):
|
||||||
''' Writes raw outgoing data. Blocks until done.
|
''' Writes raw outgoing data. '''
|
||||||
If supplied data is unicode string, encodes it to utf-8 before send.'''
|
|
||||||
try:
|
try:
|
||||||
lenn = self._send(raw_data)
|
lenn = self._send(raw_data)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
return len(raw_data)
|
return len(raw_data)
|
||||||
|
|
||||||
def disconnect(self):
|
|
||||||
''' Closes the socket. '''
|
|
||||||
self._sock.close()
|
|
||||||
self.connected = False
|
|
||||||
|
|
||||||
def pending_read(self,timeout=0):
|
|
||||||
''' Returns true if there is a data ready to be read. '''
|
|
||||||
if self._sock is None:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return select.select([self._sock],[],[],timeout)[0]
|
|
||||||
except Exception, e:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def pending_write(self,timeout=0):
|
|
||||||
''' Returns true if there is a data ready to be read. '''
|
|
||||||
if self._sock is None:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return select.select([],[self._sock],[],timeout)[0]
|
|
||||||
except Exception, e:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def pending_connection(self,timeout=0):
|
|
||||||
''' Returns true if there is a data ready to be read. '''
|
|
||||||
if self._sock is None:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return select.select([],[self._sock],[],timeout)[0]
|
|
||||||
except Exception, e:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _get_auth_buff(self):
|
def write_next(self, initial = False):
|
||||||
''' Message, that we support 1 one auth mechanism:
|
if initial:
|
||||||
the 'no auth' mechanism. '''
|
try:
|
||||||
return struct.pack('!BBB', 0x05, 0x01, 0x00)
|
# send
|
||||||
|
lenn = self._send(self._get_nl_byte())
|
||||||
def _parse_auth_buff(self, buff):
|
except Exception, e:
|
||||||
''' Parse the initial message and create a list of auth
|
# peer cannot read
|
||||||
mechanisms '''
|
if e.args[0] != 11:
|
||||||
auth_mechanisms = []
|
self.state = 8
|
||||||
ver, num_auth = struct.unpack('!BB', buff[:2])
|
self.disconnect()
|
||||||
for i in range(num_auth):
|
self.file_props['error'] = -1
|
||||||
mechanism, = struct.unpack('!B', buff[1 + i])
|
return -1
|
||||||
auth_mechanisms.append(mechanism)
|
self.state = 7
|
||||||
return auth_mechanisms
|
return 1
|
||||||
def _get_auth_response(self):
|
|
||||||
return struct.pack('!BB', 0x05, 0x00)
|
|
||||||
|
|
||||||
def _get_connect_buff(self):
|
|
||||||
''' Connect request by domain name '''
|
|
||||||
buff = struct.pack('!BBBBB%dsBB' % len(self.host), \
|
|
||||||
0x05, 0x01, 0x00, 0x03, len(self.host), self.host, \
|
|
||||||
self.port >> 8, self.port & 0xff)
|
|
||||||
return buff
|
|
||||||
|
|
||||||
def _get_request_buff(self, msg, command = 0x01):
|
|
||||||
''' Connect request by domain name,
|
|
||||||
sid sha, instead of domain name (jep 0096) '''
|
|
||||||
buff = struct.pack('!BBBBB%dsBB' % len(msg), \
|
|
||||||
0x05, command, 0x00, 0x03, len(msg), msg, 0, 0)
|
|
||||||
return buff
|
|
||||||
|
|
||||||
def _parse_request_buff(self, buff):
|
|
||||||
version, req_type, reserved, host_type, = \
|
|
||||||
struct.unpack('!BBBB', buff[:4])
|
|
||||||
if host_type == 0x01:
|
|
||||||
host_arr = struct.unpack('!iiii', buff[4:8])
|
|
||||||
host, = reduce(lambda e1, e2: str(e1) + "." + str(e2), host_arr)
|
|
||||||
host_len = len(host)
|
|
||||||
elif host_type == 0x03:
|
|
||||||
host_len, = struct.unpack('!B' , buff[4])
|
|
||||||
host, = struct.unpack('!%ds' % host_len, buff[5:5 + host_len])
|
|
||||||
portlen = len(buff[host_len + 5])
|
|
||||||
if portlen == 1: # Gaim bug :)
|
|
||||||
port, = struct.unpack('!B', buff[host_len + 5])
|
|
||||||
else:
|
|
||||||
port, = struct.unpack('!H', buff[host_len + 5])
|
|
||||||
return (req_type, host, port)
|
|
||||||
|
|
||||||
|
|
||||||
def read_connect(self):
|
|
||||||
buff = self._recv()
|
|
||||||
version, method = struct.unpack('!BB', buff)
|
|
||||||
|
|
||||||
if version != 0x05 or method == 0xff:
|
|
||||||
self.disconnect()
|
|
||||||
|
|
||||||
def _get_sha1_auth(self):
|
|
||||||
return sha.new("%s%s%s" % (self.sid, self.initiator, self.target)).hexdigest()
|
|
||||||
|
|
||||||
class Socks5Sender(Socks5):
|
|
||||||
''' class for sending file to socket over socks5 '''
|
|
||||||
def __init__(self, sock_hash, parent, _sock, host = None, port = None):
|
|
||||||
self.queue_idx = sock_hash
|
|
||||||
self.queue = parent
|
|
||||||
Socks5.__init__(self, host, port, None, None, None)
|
|
||||||
self._sock = _sock
|
|
||||||
self._sock.setblocking(False)
|
|
||||||
self._recv = _sock.recv
|
|
||||||
self._send = _sock.send
|
|
||||||
self.connected = True
|
|
||||||
self.state = 1 # waiting for first bytes
|
|
||||||
self.file_props = None
|
|
||||||
self.remaining_buff = ''
|
|
||||||
|
|
||||||
def write_next(self):
|
|
||||||
if self.remaining_buff != '':
|
if self.remaining_buff != '':
|
||||||
buff = self.remaining_buff
|
buff = self.remaining_buff
|
||||||
self.remaining_buff = ''
|
self.remaining_buff = ''
|
||||||
|
@ -360,6 +343,7 @@ class Socks5Sender(Socks5):
|
||||||
lenn = self._send(buff)
|
lenn = self._send(buff)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
if e.args[0] != 11:
|
if e.args[0] != 11:
|
||||||
|
# peer stopped reading
|
||||||
self.state = 8
|
self.state = 8
|
||||||
self.fd.close()
|
self.fd.close()
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
@ -393,57 +377,253 @@ class Socks5Sender(Socks5):
|
||||||
self.state = 8
|
self.state = 8
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_file_contents(self, timeout):
|
||||||
|
''' read file contents from socket and write them to file ''', \
|
||||||
|
self.file_props['type'], self.file_props['sid']
|
||||||
|
if self.file_props is None or \
|
||||||
|
self.file_props.has_key('file-name') is False:
|
||||||
|
self.file_props['error'] = -2
|
||||||
|
return None
|
||||||
|
fd = None
|
||||||
|
if self.remaining_buff != '':
|
||||||
|
fd = self.get_fd()
|
||||||
|
fd.write(self.remaining_buff)
|
||||||
|
lenn = len(self.remaining_buff)
|
||||||
|
self.file_props['received-len'] += lenn
|
||||||
|
self.remaining_buff = ''
|
||||||
|
if self.file_props['received-len'] == int(self.file_props['size']):
|
||||||
|
self.rem_fd(fd)
|
||||||
|
self.disconnect()
|
||||||
|
self.file_props['error'] = 0
|
||||||
|
self.file_props['completed'] = True
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
while self.pending_read(timeout):
|
||||||
|
fd = self.get_fd()
|
||||||
|
try:
|
||||||
|
buff = self._recv(MAX_BUFF_LEN)
|
||||||
|
except Exception, e:
|
||||||
|
buff = ''
|
||||||
|
first_byte = False
|
||||||
|
if self.file_props['received-len'] == 0:
|
||||||
|
if len(buff) > 0:
|
||||||
|
# delimiter between auth and data
|
||||||
|
if ord(buff[0]) == 0xD:
|
||||||
|
first_byte = True
|
||||||
|
buff = buff[1:]
|
||||||
|
self.file_props['received-len'] += len(buff)
|
||||||
|
fd.write(buff)
|
||||||
|
if len(buff) == 0 and first_byte is False:
|
||||||
|
# Transfer stopped somehow:
|
||||||
|
# reset, paused or network error
|
||||||
|
self.rem_fd(fd)
|
||||||
|
try:
|
||||||
|
# file is not complete, remove it
|
||||||
|
os.remove(self.file_props['file-name'])
|
||||||
|
except Exception, e:
|
||||||
|
# unable to remove the incomplete file
|
||||||
|
pass
|
||||||
|
self.disconnect(False)
|
||||||
|
self.file_props['error'] = -1
|
||||||
|
return 0
|
||||||
|
if self.file_props['received-len'] == int(self.file_props['size']):
|
||||||
|
# transfer completed
|
||||||
|
self.rem_fd(fd)
|
||||||
|
self.disconnect()
|
||||||
|
self.file_props['error'] = 0
|
||||||
|
self.file_props['completed'] = True
|
||||||
|
return 0
|
||||||
|
# return number of read bytes. It can be used in progressbar
|
||||||
|
if fd == None:
|
||||||
|
self.pauses +=1
|
||||||
|
else:
|
||||||
|
self.pauses = 0
|
||||||
|
if self.pauses > 24:
|
||||||
|
self.file_props['stalled'] = True
|
||||||
|
else:
|
||||||
|
self.file_props['stalled'] = False
|
||||||
|
if fd == None and self.file_props['stalled'] is False:
|
||||||
|
return None
|
||||||
|
if self.file_props.has_key('received-len'):
|
||||||
|
if self.file_props['received-len'] != 0:
|
||||||
|
return self.file_props['received-len']
|
||||||
|
return None
|
||||||
|
|
||||||
|
def disconnect(self, cb = True):
|
||||||
|
''' Closes the socket. '''
|
||||||
|
self._sock.close()
|
||||||
|
self.connected = False
|
||||||
|
|
||||||
def send_file(self, file_props):
|
def pending_read(self,timeout=0):
|
||||||
self.fd = open(file_props['file-name'])
|
''' Returns true if there is a data ready to be read. '''
|
||||||
file_props['error'] = 0
|
if self._sock is None:
|
||||||
file_props['disconnect_cb'] = self.disconnect
|
return False
|
||||||
file_props['started'] = True
|
try:
|
||||||
file_props['completed'] = False
|
return select.select([self._sock],[],[],timeout)[0]
|
||||||
file_props['paused'] = False
|
except Exception, e:
|
||||||
file_props['stalled'] = False
|
return False
|
||||||
file_props['received-len'] = 0
|
|
||||||
|
def pending_connection(self,timeout=0):
|
||||||
|
''' Returns true if there is a data ready to be read. '''
|
||||||
|
if self._sock is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return select.select([],[self._sock],[],timeout)[0]
|
||||||
|
except Exception, e:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _get_auth_buff(self):
|
||||||
|
''' Message, that we support 1 one auth mechanism:
|
||||||
|
the 'no auth' mechanism. '''
|
||||||
|
return struct.pack('!BBB', 0x05, 0x01, 0x00)
|
||||||
|
|
||||||
|
def _parse_auth_buff(self, buff):
|
||||||
|
''' Parse the initial message and create a list of auth
|
||||||
|
mechanisms '''
|
||||||
|
auth_mechanisms = []
|
||||||
|
ver, num_auth = struct.unpack('!BB', buff[:2])
|
||||||
|
for i in range(num_auth):
|
||||||
|
mechanism, = struct.unpack('!B', buff[1 + i])
|
||||||
|
auth_mechanisms.append(mechanism)
|
||||||
|
return auth_mechanisms
|
||||||
|
def _get_auth_response(self):
|
||||||
|
''' socks version(5), number of extra auth methods (we send
|
||||||
|
0x00 - no auth
|
||||||
|
) '''
|
||||||
|
return struct.pack('!BB', 0x05, 0x00)
|
||||||
|
|
||||||
|
def _get_connect_buff(self):
|
||||||
|
''' Connect request by domain name '''
|
||||||
|
buff = struct.pack('!BBBBB%dsBB' % len(self.host), \
|
||||||
|
0x05, 0x01, 0x00, 0x03, len(self.host), self.host, \
|
||||||
|
self.port >> 8, self.port & 0xff)
|
||||||
|
return buff
|
||||||
|
|
||||||
|
def _get_request_buff(self, msg, command = 0x01):
|
||||||
|
''' Connect request by domain name,
|
||||||
|
sid sha, instead of domain name (jep 0096) '''
|
||||||
|
buff = struct.pack('!BBBBB%dsBB' % len(msg), \
|
||||||
|
0x05, command, 0x00, 0x03, len(msg), msg, 0, 0)
|
||||||
|
return buff
|
||||||
|
|
||||||
|
def _get_nl_byte(self):
|
||||||
|
''' This is sent between auth and real data '''
|
||||||
|
return struct.pack('!B', 0x0D)
|
||||||
|
|
||||||
|
def _parse_request_buff(self, buff):
|
||||||
|
try: # don't trust on what comes from the outside
|
||||||
|
version, req_type, reserved, host_type, = \
|
||||||
|
struct.unpack('!BBBB', buff[:4])
|
||||||
|
if host_type == 0x01:
|
||||||
|
host_arr = struct.unpack('!iiii', buff[4:8])
|
||||||
|
host, = reduce(lambda e1, e2: str(e1) + "." + str(e2), host_arr)
|
||||||
|
host_len = len(host)
|
||||||
|
elif host_type == 0x03:
|
||||||
|
host_len, = struct.unpack('!B' , buff[4])
|
||||||
|
host, = struct.unpack('!%ds' % host_len, buff[5:5 + host_len])
|
||||||
|
portlen = len(buff[host_len + 5:])
|
||||||
|
if portlen == 1:
|
||||||
|
port, = struct.unpack('!B', buff[host_len + 5])
|
||||||
|
elif portlen == 2:
|
||||||
|
port, = struct.unpack('!H', buff[host_len + 5:])
|
||||||
|
# file data, comes with auth message (Gaim bug)
|
||||||
|
else:
|
||||||
|
port, = struct.unpack('!H', buff[host_len + 5 : host_len + 7])
|
||||||
|
self.remaining_buff = buff[host_len + 7:]
|
||||||
|
except:
|
||||||
|
return (None, None, None)
|
||||||
|
return (req_type, host, port)
|
||||||
|
|
||||||
|
def read_connect(self):
|
||||||
|
''' connect responce: version, auth method '''
|
||||||
|
buff = self._recv()
|
||||||
|
try:
|
||||||
|
version, method = struct.unpack('!BB', buff)
|
||||||
|
except:
|
||||||
|
version, method = None, None
|
||||||
|
if version != 0x05 or method == 0xff:
|
||||||
|
self.disconnect()
|
||||||
|
|
||||||
|
def _get_sha1_auth(self):
|
||||||
|
''' get sha of sid + Initiator jid + Target jid '''
|
||||||
|
if self.file_props.has_key('is_a_proxy'):
|
||||||
|
return sha.new('%s%s%s' % (self.sid, \
|
||||||
|
self.file_props['proxy_sender'], \
|
||||||
|
self.file_props['proxy_receiver'])).hexdigest()
|
||||||
|
return sha.new('%s%s%s' % (self.sid, self.initiator, self.target)).hexdigest()
|
||||||
|
|
||||||
|
class Socks5Sender(Socks5):
|
||||||
|
''' class for sending file to socket over socks5 '''
|
||||||
|
def __init__(self, sock_hash, parent, _sock, host = None, port = None):
|
||||||
|
self.queue_idx = sock_hash
|
||||||
|
self.queue = parent
|
||||||
|
Socks5.__init__(self, host, port, None, None, None)
|
||||||
|
self._sock = _sock
|
||||||
|
self._sock.setblocking(False)
|
||||||
|
self._recv = _sock.recv
|
||||||
|
self._send = _sock.send
|
||||||
|
self.connected = True
|
||||||
|
self.state = 1 # waiting for first bytes
|
||||||
|
self.file_props = None
|
||||||
|
|
||||||
|
def send_file(self):
|
||||||
|
''' start sending the file over verified connection '''
|
||||||
|
self.fd = open(self.file_props['file-name'])
|
||||||
|
self.file_props['error'] = 0
|
||||||
|
self.file_props['disconnect_cb'] = self.disconnect
|
||||||
|
self.file_props['started'] = True
|
||||||
|
self.file_props['completed'] = False
|
||||||
|
self.file_props['paused'] = False
|
||||||
|
self.file_props['stalled'] = False
|
||||||
|
self.file_props['connected'] = True
|
||||||
|
self.file_props['received-len'] = 0
|
||||||
self.pauses = 0
|
self.pauses = 0
|
||||||
self.file_props = file_props
|
return self.write_next(initial = True) # initial for nl byte
|
||||||
self.size = 0
|
|
||||||
return self.write_next()
|
|
||||||
|
|
||||||
def main(self):
|
def main(self):
|
||||||
|
''' initial requests for verifying the connection '''
|
||||||
if self.state == 1:
|
if self.state == 1:
|
||||||
buff = self.receive()
|
buff = self.receive()
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return -1
|
return -1
|
||||||
mechs = self._parse_auth_buff(buff)
|
mechs = self._parse_auth_buff(buff)
|
||||||
|
if mechs is None:
|
||||||
|
return -1 # invalid auth methods received
|
||||||
elif self.state == 2:
|
elif self.state == 2:
|
||||||
self.send_raw(self._get_auth_response())
|
self.send_raw(self._get_auth_response())
|
||||||
elif self.state == 3:
|
elif self.state == 3:
|
||||||
buff = self.receive()
|
buff = self.receive()
|
||||||
(req_type, self.sha_msg, port) = self._parse_request_buff(buff)
|
(req_type, self.sha_msg, port) = self._parse_request_buff(buff)
|
||||||
|
if req_type != 0x01:
|
||||||
|
return -1 # request is not of type 'connect'
|
||||||
elif self.state == 4:
|
elif self.state == 4:
|
||||||
self.send_raw(self._get_request_buff(self.sha_msg, 0x00))
|
self.send_raw(self._get_request_buff(self.sha_msg, 0x00))
|
||||||
self.state += 1
|
self.state += 1 # go to the next step
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def pending_data(self,timeout=0):
|
def pending_data(self,timeout=0.01):
|
||||||
''' Returns true if there is a data ready to be read. '''
|
''' return true if there is a data ready to be read '''
|
||||||
if self._sock is None:
|
if self._sock is None:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
if self.state in [1, 3]:
|
if self.state in [1, 3, 5]:
|
||||||
return self.pending_read()
|
return self.pending_read(timeout)
|
||||||
elif self.state in [2, 4, 5]:
|
elif self.state in [2, 4]:
|
||||||
return True
|
return True
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
return False
|
return False
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self, cb = True):
|
||||||
''' Closes the socket. '''
|
''' Closes the socket. '''
|
||||||
# close connection and remove us from the queue
|
# close connection and remove us from the queue
|
||||||
self._sock.close()
|
self._sock.close()
|
||||||
self.connected = False
|
self.connected = False
|
||||||
if self.file_props is not None:
|
if self.file_props is not None:
|
||||||
|
self.file_props['connected'] = False
|
||||||
self.file_props['disconnect_cb'] = None
|
self.file_props['disconnect_cb'] = None
|
||||||
if self.queue is not None:
|
if self.queue is not None:
|
||||||
self.queue.remove_sender(self.queue_idx)
|
self.queue.remove_sender(self.queue_idx)
|
||||||
|
@ -475,7 +655,7 @@ class Socks5Listener:
|
||||||
_sock[0].setblocking(False)
|
_sock[0].setblocking(False)
|
||||||
return _sock
|
return _sock
|
||||||
|
|
||||||
def pending_connection(self,timeout=0):
|
def pending_connection(self,timeout=0.005):
|
||||||
''' Returns true if there is a data ready to be read. '''
|
''' Returns true if there is a data ready to be read. '''
|
||||||
if self._serv is None:
|
if self._serv is None:
|
||||||
return False
|
return False
|
||||||
|
@ -487,10 +667,12 @@ class Socks5Listener:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
class Socks5Receiver(Socks5):
|
class Socks5Receiver(Socks5):
|
||||||
def __init__(self, host, port, initiator, target, sid, file_props = None):
|
def __init__(self, streamhost, sid, file_props = None):
|
||||||
self.queue_idx = -1
|
self.queue_idx = -1
|
||||||
|
self.streamhost = streamhost
|
||||||
self.queue = None
|
self.queue = None
|
||||||
self.file_props = file_props
|
self.file_props = file_props
|
||||||
|
|
||||||
self.connected = False
|
self.connected = False
|
||||||
self.pauses = 0
|
self.pauses = 0
|
||||||
if not self.file_props:
|
if not self.file_props:
|
||||||
|
@ -501,10 +683,38 @@ class Socks5Receiver(Socks5):
|
||||||
self.file_props['completed'] = False
|
self.file_props['completed'] = False
|
||||||
self.file_props['paused'] = False
|
self.file_props['paused'] = False
|
||||||
self.file_props['stalled'] = False
|
self.file_props['stalled'] = False
|
||||||
self.file_props['started'] = True
|
Socks5.__init__(self, streamhost['host'], int(streamhost['port']),
|
||||||
Socks5.__init__(self, host, port, initiator, target, sid)
|
streamhost['initiator'], streamhost['target'], sid)
|
||||||
|
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
|
''' create the socket and start the connect loop '''
|
||||||
|
self._sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
self._sock.settimeout(5)
|
||||||
|
# this will not block the GUI
|
||||||
|
self._sock.setblocking(False)
|
||||||
|
self.state = 0 # about to be connected
|
||||||
|
res = self.do_connect()
|
||||||
|
return res
|
||||||
|
|
||||||
|
def do_connect(self):
|
||||||
|
try:
|
||||||
|
self._sock.connect((self.host, self.port))
|
||||||
|
self._sock.setblocking(False)
|
||||||
|
self._send=self._sock.send
|
||||||
|
self._recv=self._sock.recv
|
||||||
|
except Exception, ee:
|
||||||
|
(errnum, errstr) = ee
|
||||||
|
if errnum == 111:
|
||||||
|
self.queue._connection_refused(self.streamhost,
|
||||||
|
self.file_props, self.queue_idx)
|
||||||
|
return None
|
||||||
|
self.buff = ''
|
||||||
|
self.connected = True
|
||||||
|
self.file_props['connected'] = True
|
||||||
|
self.state = 1 # connected
|
||||||
|
self.queue._socket_connected(self.streamhost, self.file_props)
|
||||||
|
return 1
|
||||||
|
|
||||||
def main(self, timeout = 0):
|
def main(self, timeout = 0):
|
||||||
''' begin negotiation. on success 'address' != 0 '''
|
''' begin negotiation. on success 'address' != 0 '''
|
||||||
if self.state == 1:
|
if self.state == 1:
|
||||||
|
@ -522,103 +732,63 @@ class Socks5Receiver(Socks5):
|
||||||
buff = self.receive()
|
buff = self.receive()
|
||||||
if buff == None:
|
if buff == None:
|
||||||
return None
|
return None
|
||||||
|
sub_buff = buff[:4]
|
||||||
|
if len(sub_buff) < 4:
|
||||||
|
return None
|
||||||
version, command, rsvd, address_type = struct.unpack('!BBBB', buff[:4])
|
version, command, rsvd, address_type = struct.unpack('!BBBB', buff[:4])
|
||||||
addrlen, address, port = 0, 0, 0
|
addrlen, address, port = 0, 0, 0
|
||||||
if address_type == 0x03:
|
if address_type == 0x03:
|
||||||
addrlen = ord(buff[4])
|
addrlen = ord(buff[4])
|
||||||
address = struct.unpack('!%ds' % addrlen, buff[5:addrlen + 5])
|
address = struct.unpack('!%ds' % addrlen, buff[5:addrlen + 5])
|
||||||
portlen = len(buff[addrlen + 5])
|
portlen = len(buff[addrlen + 5:])
|
||||||
if portlen == 1: # Gaim bug :)
|
if portlen == 1: # Gaim bug :)
|
||||||
port, = struct.unpack('!B', buff[addrlen + 5])
|
port, = struct.unpack('!B', buff[addrlen + 5])
|
||||||
|
elif portlen == 2:
|
||||||
|
port, = struct.unpack('!H', buff[addrlen + 5:])
|
||||||
else:
|
else:
|
||||||
port, = struct.unpack('!H', buff[addrlen + 5])
|
port, = struct.unpack('!H', buff[addrlen + 5:addrlen + 7])
|
||||||
|
self.remaining_buff = buff[addrlen + 7:]
|
||||||
self.state = 5
|
self.state = 5
|
||||||
self.auth_cb(self.auth_param)
|
if self.queue.on_success:
|
||||||
return None
|
self.queue.on_success(self.streamhost)
|
||||||
if self.state < 5:
|
if self.state == 5:
|
||||||
|
if self.file_props['type'] == 's':
|
||||||
|
self.fd = open(self.file_props['file-name'])
|
||||||
|
self.file_props['error'] = 0
|
||||||
|
self.file_props['disconnect_cb'] = self.disconnect
|
||||||
|
self.file_props['started'] = True
|
||||||
|
self.file_props['completed'] = False
|
||||||
|
self.file_props['paused'] = False
|
||||||
|
self.file_props['stalled'] = False
|
||||||
|
self.file_props['received-len'] = 0
|
||||||
|
self.pauses = 0
|
||||||
|
self.send_raw(self._get_nl_byte())
|
||||||
|
self.state = 6
|
||||||
|
if self.state < 6:
|
||||||
self.state += 1
|
self.state += 1
|
||||||
return None
|
return None
|
||||||
# we have set the connection, retrieve file
|
# we have set the connection set up, next - retrieve file
|
||||||
|
|
||||||
return self.get_file_contents(timeout)
|
|
||||||
|
|
||||||
|
|
||||||
def pending_data(self, timeout=0):
|
def pending_data(self, timeout=0):
|
||||||
''' Returns true if there is a data ready to be read. ''', self.state
|
''' Returns true if there is a data ready to be read. ''', self.state
|
||||||
if self._sock is None:
|
if self._sock is None:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
if self.state in [2, 4]:
|
if self.state in [2, 4, 6]:
|
||||||
return self.pending_read()
|
return self.pending_read(0.01)
|
||||||
elif self.state in [1, 3, 5]:
|
elif self.state in [1, 3, 5]:
|
||||||
return True
|
return True
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
return False
|
return False
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_file_contents(self, timeout):
|
def disconnect(self, cb = True):
|
||||||
''' read file contents from socket and write them to file '''
|
|
||||||
if self.file_props is None or \
|
|
||||||
self.file_props.has_key('file-name') is False:
|
|
||||||
self.file_props['error'] = -2
|
|
||||||
return None
|
|
||||||
fd = None
|
|
||||||
while self.pending_read(timeout):
|
|
||||||
if self.file_props.has_key('fd'):
|
|
||||||
fd = self.file_props['fd']
|
|
||||||
else:
|
|
||||||
fd = open(self.file_props['file-name'],'w')
|
|
||||||
self.file_props['fd'] = fd
|
|
||||||
self.file_props['received-len'] = 0
|
|
||||||
try:
|
|
||||||
buff = self._recv(MAX_BUFF_LEN)
|
|
||||||
except Exception, e:
|
|
||||||
buff = ''
|
|
||||||
self.file_props['received-len'] += len(buff)
|
|
||||||
fd.write(buff)
|
|
||||||
if len(buff) == 0:
|
|
||||||
# Transfer stopped somehow:
|
|
||||||
# reset, paused or network error
|
|
||||||
fd.close()
|
|
||||||
try:
|
|
||||||
# file is not complete, remove it
|
|
||||||
os.remove(self.file_props['file-name'])
|
|
||||||
except Exception, e:
|
|
||||||
# unable to remove the incomplete file
|
|
||||||
pass
|
|
||||||
self.disconnect()
|
|
||||||
self.file_props['error'] = -1
|
|
||||||
return -1
|
|
||||||
|
|
||||||
if self.file_props['received-len'] == int(self.file_props['size']):
|
|
||||||
# transfer completed
|
|
||||||
fd.close()
|
|
||||||
self.disconnect()
|
|
||||||
self.file_props['error'] = 0
|
|
||||||
self.file_props['completed'] = True
|
|
||||||
return 0
|
|
||||||
# return number of read bytes. It can be used in progressbar
|
|
||||||
if fd == None:
|
|
||||||
self.pauses +=1
|
|
||||||
else:
|
|
||||||
self.pauses = 0
|
|
||||||
if self.pauses > 24:
|
|
||||||
self.file_props['stalled'] = True
|
|
||||||
else:
|
|
||||||
self.file_props['stalled'] = False
|
|
||||||
if fd == None and self.file_props['stalled'] is False:
|
|
||||||
return None
|
|
||||||
if self.file_props.has_key('received-len'):
|
|
||||||
if self.file_props['received-len'] != 0:
|
|
||||||
return self.file_props['received-len']
|
|
||||||
return None
|
|
||||||
|
|
||||||
def disconnect(self):
|
|
||||||
''' Closes the socket. '''
|
''' Closes the socket. '''
|
||||||
# close connection and remove us from the queue
|
# close connection and remove us from the queue
|
||||||
self._sock.close()
|
if self._sock:
|
||||||
|
self._sock.close()
|
||||||
self.connected = False
|
self.connected = False
|
||||||
self.file_props['disconnect_cb'] = None
|
if cb is True:
|
||||||
|
self.file_props['disconnect_cb'] = None
|
||||||
if self.queue is not None:
|
if self.queue is not None:
|
||||||
self.queue.remove_receiver(self.queue_idx)
|
self.queue.remove_receiver(self.queue_idx)
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue