gajim-plural/src/common/jingle_ft.py

353 lines
13 KiB
Python
Raw Normal View History

# -*- coding:utf-8 -*-
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
##
"""
Handles Jingle File Transfer (XEP 0234)
"""
import gajim
import xmpp
from jingle_content import contents, JingleContent
from jingle_transport import *
from common import helpers
2011-11-18 05:55:44 +01:00
from common.socks5 import Socks5ReceiverClient, Socks5SenderClient
2011-06-24 18:24:42 +02:00
from common.connection_handlers_events import FileRequestReceivedEvent
2012-01-16 01:37:00 +01:00
import threading
import logging
from jingle_ftstates import *
log = logging.getLogger('gajim.c.jingle_ft')
2010-07-15 07:38:53 +02:00
STATE_NOT_STARTED = 0
STATE_INITIALIZED = 1
# We send the candidates and we are waiting for a reply
2012-04-07 06:56:44 +02:00
STATE_CAND_SENT = 2
# We received the candidates and we are waiting to reply
2012-04-07 06:56:44 +02:00
STATE_CAND_RECEIVED = 3
# We have sent and received the candidates
# This also includes any candidate-error received or sent
2012-04-07 06:56:44 +02:00
STATE_CAND_SENT_AND_RECEIVED = 4
STATE_TRANSPORT_REPLACE = 5
# We are transfering the file
2012-04-07 06:56:44 +02:00
STATE_TRANSFERING = 6
class JingleFileTransfer(JingleContent):
2010-08-24 23:12:34 +02:00
def __init__(self, session, transport=None, file_props=None,
use_security=False):
JingleContent.__init__(self, session, transport)
2010-08-24 23:12:34 +02:00
log.info("transport value: %s" % transport)
2010-08-24 23:12:34 +02:00
# events we might be interested in
self.callbacks['session-initiate'] += [self.__on_session_initiate]
2012-01-16 01:37:00 +01:00
self.callbacks['session-initiate-sent'] += [self.__on_session_initiate_sent]
self.callbacks['content-add'] += [self.__on_session_initiate]
self.callbacks['session-accept'] += [self.__on_session_accept]
2012-01-16 01:37:00 +01:00
self.callbacks['session-terminate'] += [self.__on_session_terminate]
self.callbacks['session-info'] += [self.__on_session_info]
self.callbacks['transport-accept'] += [self.__on_transport_accept]
2010-08-24 23:12:34 +02:00
self.callbacks['transport-replace'] += [self.__on_transport_replace]
self.callbacks['session-accept-sent'] += [self.__transport_setup]
2010-08-24 23:12:34 +02:00
# fallback transport method
self.callbacks['transport-reject'] += [self.__on_transport_reject]
self.callbacks['transport-info'] += [self.__on_transport_info]
self.callbacks['iq-result'] += [self.__on_iq_result]
self.use_security = use_security
2010-08-24 23:12:34 +02:00
self.file_props = file_props
if file_props is None:
self.weinitiate = False
else:
self.weinitiate = True
if self.file_props is not None:
self.file_props['sender'] = session.ourjid
self.file_props['receiver'] = session.peerjid
self.file_props['session-type'] = 'jingle'
self.file_props['session-sid'] = session.sid
self.file_props['transfered_size'] = []
2010-08-24 23:12:34 +02:00
log.info("FT request: %s" % file_props)
if transport is None:
self.transport = JingleTransportSocks5()
2011-07-18 00:28:38 +02:00
self.transport.set_connection(session.connection)
self.transport.set_file_props(self.file_props)
self.transport.set_our_jid(session.ourjid)
log.info('ourjid: %s' % session.ourjid)
if self.file_props is not None:
self.file_props['sid'] = self.transport.sid
self.session = session
self.media = 'file'
self.nominated_cand = {}
self.state = STATE_NOT_STARTED
self.states = {STATE_INITIALIZED : StateInitialized(self),
STATE_CAND_SENT : StateCandSent(self),
STATE_CAND_RECEIVED : StateCandReceived(self),
STATE_TRANSFERING : StateTransfering(self),
STATE_TRANSPORT_REPLACE : StateTransportReplace(self),
STATE_CAND_SENT_AND_RECEIVED : StateCandSentAndRecv(self)
}
def __state_changed(self, nextstate, args=None):
# Executes the next state action and sets the next state
st = self.states[nextstate]
st.action(args)
self.state = nextstate
2010-08-24 23:12:34 +02:00
def __on_session_initiate(self, stanza, content, error, action):
2011-06-24 18:24:42 +02:00
gajim.nec.push_incoming_event(FileRequestReceivedEvent(None,
conn=self.session.connection, stanza=stanza, jingle_content=content,
FT_content=self))
2012-01-16 01:37:00 +01:00
def __on_session_initiate_sent(self, stanza, content, error, action):
# Calculate file_hash in a new thread
self.hashThread = threading.Thread(target=self.__calcHash)
self.hashThread.start()
def __calcHash(self):
if self.session.hash_algo == None:
2012-01-16 01:37:00 +01:00
return
try:
file_ = open(self.file_props['file-name'], 'r')
2012-01-16 01:37:00 +01:00
except:
# can't open file
2012-01-16 01:37:00 +01:00
return
h = xmpp.Hashes()
hash_ = h.calculateHash(self.session.hash_algo, file_)
2012-05-28 03:05:43 +02:00
# DEBUG
#hash_ = '1294809248109223'
if not hash_:
# Hash alogrithm not supported
return
2012-01-24 16:04:14 +01:00
self.file_props['hash'] = hash_
h.addHash(hash_, self.session.hash_algo)
2012-01-16 01:37:00 +01:00
checksum = xmpp.Node(tag='checksum',
payload=[xmpp.Node(tag='file', payload=[h])])
checksum.setNamespace(xmpp.NS_JINGLE_FILE_TRANSFER)
# Send hash in a session info
self.session.__session_info(checksum )
def __on_session_accept(self, stanza, content, error, action):
log.info("__on_session_accept")
con = self.session.connection
security = content.getTag('security')
if not security: # responder can not verify our fingerprint
self.use_security = False
2011-06-29 00:31:07 +02:00
if self.state == STATE_TRANSPORT_REPLACE:
# We ack the session accept
response = stanza.buildReply('result')
2011-12-29 14:08:35 +01:00
response.delChild(response.getQuery())
2011-06-29 00:31:07 +02:00
con.connection.send(response)
# We send the file
self.__state_changed(STATE_TRANSFERING)
2011-06-29 00:31:07 +02:00
raise xmpp.NodeProcessed
self.file_props['streamhosts'] = self.transport.remote_candidates
for host in self.file_props['streamhosts']:
2012-01-08 20:44:15 +01:00
host['initiator'] = self.session.initiator
host['target'] = self.session.responder
host['sid'] = self.file_props['sid']
response = stanza.buildReply('result')
2011-12-29 14:08:35 +01:00
response.delChild(response.getQuery())
con.connection.send(response)
if not gajim.socks5queue.get_file_props(
self.session.connection.name, self.file_props['sid']):
gajim.socks5queue.add_file_props(self.session.connection.name,
2012-01-08 20:44:15 +01:00
self.file_props)
fingerprint = None
if self.use_security:
fingerprint = 'client'
if self.transport.type == TransportType.SOCKS5:
gajim.socks5queue.connect_to_hosts(self.session.connection.name,
self.file_props['sid'], self.on_connect,
2012-01-08 20:44:15 +01:00
self._on_connect_error, fingerprint=fingerprint,
receiving=False)
return
self.__state_changed(STATE_TRANSFERING)
raise xmpp.NodeProcessed
def __on_session_terminate(self, stanza, content, error, action):
log.info("__on_session_terminate")
2012-01-16 01:37:00 +01:00
def __on_session_info(self, stanza, content, error, action):
pass
def __on_transport_accept(self, stanza, content, error, action):
log.info("__on_transport_accept")
def __on_transport_replace(self, stanza, content, error, action):
log.info("__on_transport_replace")
2010-08-24 23:12:34 +02:00
def __on_transport_reject(self, stanza, content, error, action):
log.info("__on_transport_reject")
def __on_transport_info(self, stanza, content, error, action):
log.info("__on_transport_info")
2010-08-24 23:12:34 +02:00
2011-07-05 20:05:16 +02:00
if content.getTag('transport').getTag('candidate-error'):
self.nominated_cand['peer-cand'] = False
2012-02-13 01:36:20 +01:00
if self.state == STATE_CAND_SENT:
if not self.nominated_cand['our-cand'] and \
not self.nominated_cand['peer-cand']:
if not self.weinitiate:
return
self.__state_changed(STATE_TRANSPORT_REPLACE)
else:
response = stanza.buildReply('result')
2011-12-29 14:08:35 +01:00
response.delChild(response.getQuery())
self.session.connection.connection.send(response)
self.__state_changed(STATE_TRANSFERING)
raise xmpp.NodeProcessed
else:
args = {'candError' : True}
self.__state_changed(STATE_CAND_RECEIVED, args)
2011-07-05 20:05:16 +02:00
return
2011-10-29 06:09:45 +02:00
if content.getTag('transport').getTag('activated'):
self.state = STATE_TRANSFERING
jid = gajim.get_jid_without_resource(self.session.ourjid)
gajim.socks5queue.send_file(self.file_props,
self.session.connection.name, 'client')
return
args = {'content' : content,
'sendCand' : False}
2012-02-13 01:36:20 +01:00
if self.state == STATE_CAND_SENT:
self.__state_changed(STATE_CAND_SENT_AND_RECEIVED, args)
response = stanza.buildReply('result')
2011-12-29 14:08:35 +01:00
response.delChild(response.getQuery())
self.session.connection.connection.send(response)
self.__state_changed(STATE_TRANSFERING)
raise xmpp.NodeProcessed
2010-07-13 04:38:31 +02:00
else:
self.__state_changed(STATE_CAND_RECEIVED, args)
2010-08-24 23:12:34 +02:00
def __on_iq_result(self, stanza, content, error, action):
log.info("__on_iq_result")
2010-08-24 23:12:34 +02:00
if self.state == STATE_NOT_STARTED:
self.__state_changed(STATE_INITIALIZED)
elif self.state == STATE_CAND_SENT_AND_RECEIVED:
if not self.nominated_cand['our-cand'] and \
not self.nominated_cand['peer-cand']:
if not self.weinitiate:
return
self.__state_changed(STATE_TRANSPORT_REPLACE)
return
# initiate transfer
self.__state_changed(STATE_TRANSFERING)
2012-01-08 20:44:15 +01:00
def __transport_setup(self, stanza=None, content=None, error=None,
action=None):
# Sets up a few transport specific things for the file transfer
if self.transport.type == TransportType.IBB:
2012-04-07 06:56:44 +02:00
# No action required, just set the state to transfering
self.state = STATE_TRANSFERING
def on_connect(self, streamhost):
"""
send candidate-used stanza
"""
2010-08-24 23:12:34 +02:00
log.info('send_candidate_used')
if streamhost is None:
return
args = {'streamhost' : streamhost,
'sendCand' : True}
self.nominated_cand['our-cand'] = streamhost
2012-04-07 06:56:44 +02:00
self.__sendCand(args)
2011-10-29 06:09:45 +02:00
def _on_connect_error(self, sid):
log.info('connect error, sid=' + sid)
2012-04-18 02:57:34 +02:00
args = {'candError' : True,
2012-04-18 02:47:52 +02:00
'sendCand' : True}
2012-04-07 06:56:44 +02:00
self.__sendCand(args)
def __sendCand(self, args):
2012-02-13 01:36:20 +01:00
if self.state == STATE_CAND_RECEIVED:
self.__state_changed(STATE_CAND_SENT_AND_RECEIVED, args)
else:
self.__state_changed(STATE_CAND_SENT, args)
def _store_socks5_sid(self, sid, hash_id):
# callback from socsk5queue.start_listener
self.file_props['hash'] = hash_id
def _listen_host(self):
2011-08-09 01:43:07 +02:00
receiver = self.file_props['receiver']
sender = self.file_props['sender']
sha_str = helpers.get_auth_sha(self.file_props['sid'], sender,
2012-01-08 20:44:15 +01:00
receiver)
2011-08-09 01:43:07 +02:00
self.file_props['sha_str'] = sha_str
port = gajim.config.get('file_transfers_port')
fingerprint = None
if self.use_security:
fingerprint = 'server'
2011-08-09 01:43:07 +02:00
if self.weinitiate:
listener = gajim.socks5queue.start_listener(port, sha_str,
2012-01-08 20:44:15 +01:00
self._store_socks5_sid, self.file_props,
fingerprint=fingerprint, type='sender')
2011-08-09 01:43:07 +02:00
else:
listener = gajim.socks5queue.start_listener(port, sha_str,
2012-01-08 20:44:15 +01:00
self._store_socks5_sid, self.file_props,
fingerprint=fingerprint, type='receiver')
2011-08-09 01:43:07 +02:00
if not listener:
2012-01-08 20:44:15 +01:00
# send error message, notify the user
2011-08-09 01:43:07 +02:00
return
def isOurCandUsed(self):
'''
If this method returns true then the candidate we nominated will be
used, if false, the candidate nominated by peer will be used
'''
if self.nominated_cand['peer-cand'] == False:
return True
if self.nominated_cand['our-cand'] == False:
return False
peer_pr = int(self.nominated_cand['peer-cand']['priority'])
our_pr = int(self.nominated_cand['our-cand']['priority'])
if peer_pr != our_pr:
2011-08-23 05:57:29 +02:00
return our_pr > peer_pr
else:
return self.weinitiate
def get_content(desc):
return JingleFileTransfer
contents[xmpp.NS_JINGLE_FILE_TRANSFER] = get_content