Fix pep8 support in src/plugins.

This commit is contained in:
Emmanuel Gil Peyrot 2013-01-18 17:55:35 +01:00
commit 0dca274360

View file

@ -78,30 +78,28 @@ from wokkel import disco, iwokkel
IQ_SET = '/iq[@type="set"]'
NS_BS = 'http://jabber.org/protocol/bytestreams'
BS_REQUEST = IQ_SET + '/query[@xmlns="' + NS_BS + '"]'
TIMEOUT = 60 #timeout for workflow
TIMEOUT = 60 # timeout for workflow
PLUGIN_INFO = {
"name": "XEP 0065 Plugin",
"import_name": "XEP-0065",
"type": "XEP",
"protocols": ["XEP-0065"],
"main": "XEP_0065",
"handler": "yes",
"description": _("""Implementation of SOCKS5 Bytestreams""")
"name": "XEP 0065 Plugin",
"import_name": "XEP-0065",
"type": "XEP",
"protocols": ["XEP-0065"],
"main": "XEP_0065",
"handler": "yes",
"description": _("""Implementation of SOCKS5 Bytestreams""")
}
STATE_INITIAL = 0
STATE_AUTH = 1
STATE_AUTH = 1
STATE_REQUEST = 2
STATE_READY = 3
STATE_READY = 3
STATE_AUTH_USERPASS = 4
STATE_TARGET_INITIAL = 5
STATE_TARGET_AUTH = 6
STATE_TARGET_AUTH = 6
STATE_TARGET_REQUEST = 7
STATE_TARGET_READY = 8
STATE_LAST = 9
STATE_TARGET_READY = 8
STATE_LAST = 9
STATE_CONNECT_PENDING = STATE_LAST + 1
@ -139,15 +137,14 @@ def calculateHash(from_jid, to_jid, sid):
return hashlib.sha1((sid + from_jid.full() + to_jid.full()).encode('utf-8')).hexdigest()
class SOCKSv5(protocol.Protocol, FileSender):
def __init__(self):
debug(_("Protocol init"))
self.state = STATE_INITIAL
self.buf = ""
self.supportedAuthMechs = [ AUTHMECH_ANON ]
self.supportedAddrs = [ ADDR_DOMAINNAME ]
self.enabledCommands = [ CMD_CONNECT ]
self.supportedAuthMechs = [AUTHMECH_ANON]
self.supportedAddrs = [ADDR_DOMAINNAME]
self.enabledCommands = [CMD_CONNECT]
self.peersock = None
self.addressType = 0
self.requestType = 0
@ -162,7 +159,7 @@ class SOCKSv5(protocol.Protocol, FileSender):
try:
# Parse out data
ver, nmethod = struct.unpack('!BB', self.buf[:2])
methods = struct.unpack('%dB' % nmethod, self.buf[2:nmethod+2])
methods = struct.unpack('%dB' % nmethod, self.buf[2:nmethod + 2])
# Ensure version is correct
if ver != 5:
@ -171,7 +168,7 @@ class SOCKSv5(protocol.Protocol, FileSender):
return
# Trim off front of the buffer
self.buf = self.buf[nmethod+2:]
self.buf = self.buf[nmethod + 2:]
# Check for supported auth mechs
for m in self.supportedAuthMechs:
@ -320,7 +317,7 @@ class SOCKSv5(protocol.Protocol, FileSender):
debug("connectRequested")
# Check that this session is expected
if not self.factory.hash_sid_map.has_key(addr):
if addr not in self.factory.hash_sid_map:
#no: we refuse it
self.sendErrorReply(REPLY_CONN_REFUSED)
return
@ -374,14 +371,13 @@ class SOCKSv5(protocol.Protocol, FileSender):
if self.state == STATE_TARGET_AUTH:
ver, method = struct.unpack('!BB', buf)
self.buf = self.buf[2:]
if ver!=SOCKS5_VER or method!=AUTHMECH_ANON:
if ver != SOCKS5_VER or method != AUTHMECH_ANON:
self.transport.loseConnection()
else:
self._makeRequest()
if self.state == STATE_TARGET_REQUEST:
self._parseRequestReply()
def clientConnectionLost(self, reason):
debug("clientConnectionLost")
self.transport.loseConnection()
@ -390,7 +386,7 @@ class SOCKSv5(protocol.Protocol, FileSender):
debug("connectionLost")
if self.state != STATE_CONNECT_PENDING:
self.transport.unregisterProducer()
if self.peersock != None:
if self.peersock is not None:
self.peersock.peersock = None
self.peersock.transport.unregisterProducer()
self.peersock = None
@ -405,10 +401,11 @@ class Socks5ServerFactory(protocol.ServerFactory):
self.finishedCb = finishedCb
def startedConnecting(self, connector):
debug (_("Socks 5 server connection started"))
debug(_("Socks 5 server connection started"))
def clientConnectionLost(self, connector, reason):
debug (_("Socks 5 server connection lost (reason: %s)"), reason)
debug(_("Socks 5 server connection lost (reason: %s)"), reason)
class Socks5ClientFactory(protocol.ClientFactory):
protocol = SOCKSv5
@ -432,11 +429,11 @@ class Socks5ClientFactory(protocol.ClientFactory):
self.profile = profile
def startedConnecting(self, connector):
debug (_("Socks 5 client connection started"))
debug(_("Socks 5 client connection started"))
def clientConnectionLost(self, connector, reason):
debug (_("Socks 5 client connection lost (reason: %s)"), reason)
self.finishedCb(self.sid, reason.type == jab_error.ConnectionDone, self.profile) #TODO: really check if the state is actually successful
debug(_("Socks 5 client connection lost (reason: %s)"), reason)
self.finishedCb(self.sid, reason.type == jab_error.ConnectionDone, self.profile) # TODO: really check if the state is actually successful
class XEP_0065(object):
@ -465,7 +462,7 @@ class XEP_0065(object):
info(_("Plugin XEP_0065 initialization"))
#session data
self.hash_sid_map = {} #key: hash of the transfer session, value: (session id, profile)
self.hash_sid_map = {} # key: hash of the transfer session, value: (session id, profile)
self.host = host
debug(_("registering"))
@ -486,7 +483,7 @@ class XEP_0065(object):
client = self.host.getClient(profile)
if not client:
raise ProfileNotInCacheError
client.xep_0065_current_stream = {} #key: stream_id, value: data(dict)
client.xep_0065_current_stream = {} # key: stream_id, value: data(dict)
def getExternalIP(self):
"""Return IP visible from outside, by asking to a website"""
@ -518,15 +515,15 @@ class XEP_0065(object):
if not client:
warning(_("Client no more in cache"))
return
if not client.xep_0065_current_stream.has_key(sid):
if sid not in client.xep_0065_current_stream:
warning(_("kill id called on a non existant id"))
return
if client.xep_0065_current_stream[sid].has_key("observer_cb"):
if "observer_cb" in client.xep_0065_current_stream[sid]:
xmlstream = client.xep_0065_current_stream[sid]["xmlstream"]
xmlstream.removeObserver(client.xep_0065_current_stream[sid]["event_data"], client.xep_0065_current_stream[sid]["observer_cb"])
if client.xep_0065_current_stream[sid]['timer'].active():
client.xep_0065_current_stream[sid]['timer'].cancel()
if client.xep_0065_current_stream[sid].has_key("size"):
if "size" in client.xep_0065_current_stream[sid]:
self.host.removeProgressCB(sid, profile)
file_obj = client.xep_0065_current_stream[sid]['file_obj']
@ -544,7 +541,7 @@ class XEP_0065(object):
else:
failure_cb(sid, file_obj, NS_BS, failure_reason, profile)
def startStream(self, file_obj, to_jid, sid, length, successCb, failureCb, size = None, profile=None):
def startStream(self, file_obj, to_jid, sid, length, successCb, failureCb, size=None, profile=None):
"""Launch the stream workflow
@param file_obj: file_obj to send
@param to_jid: JID of the recipient
@ -559,7 +556,7 @@ class XEP_0065(object):
error(_("Unknown profile, this should not happen"))
raise ProfileNotInCacheError
if length != None:
if length is not None:
error(_('stream length not managed yet'))
return
@ -579,7 +576,7 @@ class XEP_0065(object):
if size:
data["size"] = size
self.host.registerProgressCB(sid, self.getProgress, profile)
iq_elt = jabber_client.IQ(xmlstream,'set')
iq_elt = jabber_client.IQ(xmlstream, 'set')
iq_elt["from"] = profile_jid.full()
iq_elt["to"] = to_jid.full()
query_elt = iq_elt.addElement('query', NS_BS)
@ -638,7 +635,7 @@ class XEP_0065(object):
factory = Socks5ClientFactory(client.xep_0065_current_stream, sid, None, self.activateProxyStream, lambda sid, success, profile: self._killId(sid, success, profile=profile), True, profile)
reactor.connectTCP(proxy_host, int(proxy_port), factory)
else:
data["start_transfer_cb"](file_obj) #We now activate the stream
data["start_transfer_cb"](file_obj) # We now activate the stream
def activateProxyStream(self, sid, iq_id, start_transfer_cb, profile):
debug(_("activating stream"))
@ -648,7 +645,7 @@ class XEP_0065(object):
data = client.xep_0065_current_stream[sid]
profile_jid, xmlstream = self.host.getJidNStream(profile)
iq_elt = client.IQ(xmlstream,'set')
iq_elt = client.IQ(xmlstream, 'set')
iq_elt["from"] = profile_jid.full()
iq_elt["to"] = self.host.memory.getParamA("Proxy", "File Transfer", profile_key=profile)
query_elt = iq_elt.addElement('query', NS_BS)
@ -687,7 +684,6 @@ class XEP_0065(object):
data["success_cb"] = success_cb
data["failure_cb"] = failure_cb
def streamQuery(self, iq_elt, profile):
"""Get file using byte stream"""
debug(_("BS stream query"))
@ -717,7 +713,7 @@ class XEP_0065(object):
self.sendBadRequestError(iq_elt['id'], iq_elt['from'], xmlstream)
return
streamhost_elt = streamhost_elts[0] #TODO: manage several streamhost elements case
streamhost_elt = streamhost_elts[0] # TODO: manage several streamhost elements case
sh_host = streamhost_elt.getAttribute("host")
sh_port = streamhost_elt.getAttribute("port")
sh_jid = streamhost_elt.getAttribute("jid")
@ -728,7 +724,7 @@ class XEP_0065(object):
client.xep_0065_current_stream[sid]["streamhost"] = (sh_host, sh_port, sh_jid)
info (_("Stream proposed: host=[%(host)s] port=[%(port)s]") % {'host':sh_host, 'port':sh_port})
info(_("Stream proposed: host=[%(host)s] port=[%(port)s]") % {'host': sh_host, 'port': sh_port})
factory = Socks5ClientFactory(client.xep_0065_current_stream, sid, iq_elt["id"], self.activateStream, lambda sid, success, profile: self._killId(sid, success, profile=profile), profile=profile)
reactor.connectTCP(sh_host, int(sh_port), factory)
@ -760,7 +756,7 @@ class XEP_0065(object):
result['to'] = to_jid
error_el = result.addElement('error')
error_el['type'] = 'modify'
error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas','not-acceptable'))
error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas', 'not-acceptable'))
xmlstream.send(result)
def sendBadRequestError(self, iq_id, to_jid, xmlstream):
@ -774,9 +770,10 @@ class XEP_0065(object):
result['to'] = to_jid
error_el = result.addElement('error')
error_el['type'] = 'cancel'
error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas','bad-request'))
error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas', 'bad-request'))
xmlstream.send(result)
class XEP_0065_handler(XMPPHandler):
implements(iwokkel.IDisco)
@ -801,10 +798,9 @@ class XEP_0065_handler(XMPPHandler):
if len(streamhost_elts) != 1:
warning(_("Multiple streamhost elements in proxy not managed, keeping only the first one"))
streamhost_elt = streamhost_elts[0]
proxy = self.host.memory.setParam("Proxy", streamhost_elt.getAttribute("jid",""), "File Transfer", self.parent.profile)
proxy = self.host.memory.setParam("Proxy host", streamhost_elt.getAttribute("host",""), "File Transfer", self.parent.profile)
proxy = self.host.memory.setParam("Proxy port", streamhost_elt.getAttribute("port",""), "File Transfer", self.parent.profile)
proxy = self.host.memory.setParam("Proxy", streamhost_elt.getAttribute("jid", ""), "File Transfer", self.parent.profile)
proxy = self.host.memory.setParam("Proxy host", streamhost_elt.getAttribute("host", ""), "File Transfer", self.parent.profile)
proxy = self.host.memory.setParam("Proxy port", streamhost_elt.getAttribute("port", ""), "File Transfer", self.parent.profile)
def connectionInitialized(self):
def after_init(ignore):
@ -812,20 +808,17 @@ class XEP_0065_handler(XMPPHandler):
if not proxy_ent:
debug(_("No proxy found on this server"))
return
iq_elt = jabber_client.IQ(self.parent.xmlstream,'get')
iq_elt = jabber_client.IQ(self.parent.xmlstream, 'get')
iq_elt["to"] = proxy_ent.full()
query_elt = iq_elt.addElement('query', NS_BS)
iq_elt.addCallback(self._proxyDataResult)
iq_elt.send()
self.xmlstream.addObserver(BS_REQUEST, self.plugin_parent.streamQuery, profile = self.parent.profile)
proxy = self.host.memory.getParamA("Proxy", "File Transfer", profile_key = self.parent.profile)
self.xmlstream.addObserver(BS_REQUEST, self.plugin_parent.streamQuery, profile=self.parent.profile)
proxy = self.host.memory.getParamA("Proxy", "File Transfer", profile_key=self.parent.profile)
if not proxy:
self.parent.client_initialized.addCallback(after_init)
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
return [disco.DiscoFeature(NS_BS)]