Fix Zeroconf
- Port pybonjour code from gajim_0.16 branch - Fix some other small things that broke zeroconf
This commit is contained in:
parent
cfd64926b9
commit
d0ec9812a6
6 changed files with 295 additions and 175 deletions
|
@ -1069,7 +1069,10 @@ class ConnectionHandlersBase:
|
||||||
if not jid_to:
|
if not jid_to:
|
||||||
reply = True
|
reply = True
|
||||||
else:
|
else:
|
||||||
fjid_to = helpers.parse_jid(str(jid_to))
|
fjid_to = str(jid_to)
|
||||||
|
if self.name != 'Local':
|
||||||
|
# Dont check precis for zeroconf
|
||||||
|
fjid_to = helpers.parse_jid(str(jid_to))
|
||||||
jid_to = app.get_jid_without_resource(fjid_to)
|
jid_to = app.get_jid_without_resource(fjid_to)
|
||||||
if jid_to == app.get_jid_from_account(self.name):
|
if jid_to == app.get_jid_from_account(self.name):
|
||||||
reply = True
|
reply = True
|
||||||
|
|
|
@ -885,6 +885,7 @@ class ZeroconfPresenceReceivedEvent(nec.NetworkIncomingEvent):
|
||||||
self.resource = 'local'
|
self.resource = 'local'
|
||||||
self.prio = 0
|
self.prio = 0
|
||||||
self.keyID = None
|
self.keyID = None
|
||||||
|
self.idle_time = None
|
||||||
self.timestamp = 0
|
self.timestamp = 0
|
||||||
self.contact_nickname = None
|
self.contact_nickname = None
|
||||||
self.avatar_sha = None
|
self.avatar_sha = None
|
||||||
|
@ -1528,7 +1529,7 @@ class ZeroconfMessageReceivedEvent(MessageReceivedEvent):
|
||||||
base_network_events = []
|
base_network_events = []
|
||||||
|
|
||||||
def get_jid_resource(self):
|
def get_jid_resource(self):
|
||||||
self.fjid =self.stanza.getFrom()
|
self.fjid = str(self.stanza.getFrom())
|
||||||
|
|
||||||
if self.fjid is None:
|
if self.fjid is None:
|
||||||
for key in self.conn.connection.zeroconf.contacts:
|
for key in self.conn.connection.zeroconf.contacts:
|
||||||
|
@ -1833,7 +1834,12 @@ class MessageErrorEvent(nec.NetworkIncomingEvent, HelperEvent):
|
||||||
name = 'message-error'
|
name = 'message-error'
|
||||||
base_network_events = []
|
base_network_events = []
|
||||||
|
|
||||||
|
def init(self):
|
||||||
|
self.zeroconf = False
|
||||||
|
|
||||||
def generate(self):
|
def generate(self):
|
||||||
|
if self.zeroconf:
|
||||||
|
return True
|
||||||
self.get_id()
|
self.get_id()
|
||||||
#only alert for errors of explicitly sent messages (see https://trac.gajim.org/ticket/8222)
|
#only alert for errors of explicitly sent messages (see https://trac.gajim.org/ticket/8222)
|
||||||
if self.id_ in self.conn.sent_message_ids:
|
if self.id_ in self.conn.sent_message_ids:
|
||||||
|
|
|
@ -442,7 +442,7 @@ class P2PConnection(IdleObject, PlugIn):
|
||||||
if self.state <= 0:
|
if self.state <= 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
r = packet
|
r = str(packet).encode('utf-8')
|
||||||
|
|
||||||
if now:
|
if now:
|
||||||
self.sendqueue.insert(0, (r, is_message))
|
self.sendqueue.insert(0, (r, is_message))
|
||||||
|
@ -532,6 +532,9 @@ class P2PConnection(IdleObject, PlugIn):
|
||||||
|
|
||||||
if self.state < 0:
|
if self.state < 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
received = received.decode('utf-8')
|
||||||
|
|
||||||
if self.on_receive:
|
if self.on_receive:
|
||||||
if self._owner.sock_type == TYPE_CLIENT:
|
if self._owner.sock_type == TYPE_CLIENT:
|
||||||
self.set_timeout(ACTIVITY_TIMEOUT_SECONDS)
|
self.set_timeout(ACTIVITY_TIMEOUT_SECONDS)
|
||||||
|
@ -609,7 +612,8 @@ class P2PConnection(IdleObject, PlugIn):
|
||||||
if self.sent_data and self.sent_data.strip():
|
if self.sent_data and self.sent_data.strip():
|
||||||
log.debug('sent: %s' % self.sent_data)
|
log.debug('sent: %s' % self.sent_data)
|
||||||
if hasattr(self._owner, 'Dispatcher'):
|
if hasattr(self._owner, 'Dispatcher'):
|
||||||
self._owner.Dispatcher.Event('', DATA_SENT, self.sent_data)
|
self._owner.Dispatcher.Event(
|
||||||
|
'', DATA_SENT, self.sent_data.decode('utf-8'))
|
||||||
self.sent_data = None
|
self.sent_data = None
|
||||||
if self.buff_is_message:
|
if self.buff_is_message:
|
||||||
self._owner.on_message_sent(self.fd)
|
self._owner.on_message_sent(self.fd)
|
||||||
|
@ -662,7 +666,7 @@ class ClientZeroconf:
|
||||||
|
|
||||||
def resolve_all(self):
|
def resolve_all(self):
|
||||||
if self.zeroconf:
|
if self.zeroconf:
|
||||||
self.zeroconf.resolve_all()
|
return self.zeroconf.resolve_all()
|
||||||
|
|
||||||
def reannounce(self, txt):
|
def reannounce(self, txt):
|
||||||
self.remove_announce()
|
self.remove_announce()
|
||||||
|
@ -711,7 +715,7 @@ class ClientZeroconf:
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
|
|
||||||
def kill_all_connections(self):
|
def kill_all_connections(self):
|
||||||
for connection in self.connections.values():
|
for connection in list(self.connections.values()):
|
||||||
connection.force_disconnect()
|
connection.force_disconnect()
|
||||||
|
|
||||||
def add_connection(self, connection, ip, port, recipient):
|
def add_connection(self, connection, ip, port, recipient):
|
||||||
|
|
|
@ -69,6 +69,8 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
CommonConnection.__init__(self, name)
|
CommonConnection.__init__(self, name)
|
||||||
self.is_zeroconf = True
|
self.is_zeroconf = True
|
||||||
|
|
||||||
|
app.ged.register_event_handler('message-outgoing', ged.OUT_CORE,
|
||||||
|
self._nec_message_outgoing)
|
||||||
app.ged.register_event_handler('stanza-message-outgoing', ged.OUT_CORE,
|
app.ged.register_event_handler('stanza-message-outgoing', ged.OUT_CORE,
|
||||||
self._nec_stanza_message_outgoing)
|
self._nec_stanza_message_outgoing)
|
||||||
|
|
||||||
|
@ -107,7 +109,7 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
def check_jid(self, jid):
|
def check_jid(self, jid):
|
||||||
return jid
|
return jid
|
||||||
|
|
||||||
def get_own_jid(self):
|
def get_own_jid(self, *args, **kwargs):
|
||||||
return nbxmpp.JID(self.username + '@' + self.host)
|
return nbxmpp.JID(self.username + '@' + self.host)
|
||||||
|
|
||||||
def reconnect(self):
|
def reconnect(self):
|
||||||
|
@ -123,7 +125,9 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
|
|
||||||
def _on_resolve_timeout(self):
|
def _on_resolve_timeout(self):
|
||||||
if self.connected:
|
if self.connected:
|
||||||
self.connection.resolve_all()
|
if not self.connection.resolve_all():
|
||||||
|
self._on_disconnected()
|
||||||
|
return False
|
||||||
diffs = self.roster.getDiffs()
|
diffs = self.roster.getDiffs()
|
||||||
for key in diffs:
|
for key in diffs:
|
||||||
self.roster.setItem(key)
|
self.roster.setItem(key)
|
||||||
|
@ -205,7 +209,7 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
else: # result is None
|
else: # result is None
|
||||||
app.nec.push_incoming_event(ConnectionLostEvent(None,
|
app.nec.push_incoming_event(ConnectionLostEvent(None,
|
||||||
conn=self, title=_('Could not start local service'),
|
conn=self, title=_('Could not start local service'),
|
||||||
msg=_('Please check if avahi-daemon is running.')))
|
msg=_('Please check if avahi/bonjour-daemon is running.')))
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
|
@ -321,23 +325,24 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
title=_('Could not change status of account "%s"') % self.name,
|
title=_('Could not change status of account "%s"') % self.name,
|
||||||
msg=_('Please check if avahi-daemon is running.')))
|
msg=_('Please check if avahi-daemon is running.')))
|
||||||
|
|
||||||
|
def _nec_message_outgoing(self, obj):
|
||||||
|
if obj.account != self.name:
|
||||||
|
return
|
||||||
|
self._prepare_message(obj)
|
||||||
|
|
||||||
def _nec_stanza_message_outgoing(self, obj):
|
def _nec_stanza_message_outgoing(self, obj):
|
||||||
if obj.conn.name != self.name:
|
if obj.conn.name != self.name:
|
||||||
return
|
return
|
||||||
|
|
||||||
def on_send_ok(stanza_id):
|
def on_send_ok(stanza_id):
|
||||||
app.nec.push_incoming_event(MessageSentEvent(None, conn=self,
|
app.nec.push_incoming_event(MessageSentEvent(None, **vars(obj)))
|
||||||
jid=obj.jid, message=obj.message, keyID=obj.keyID,
|
|
||||||
automatic_message=obj.automatic_message, chatstate=None,
|
|
||||||
stanza_id=stanza_id))
|
|
||||||
|
|
||||||
self.log_message(obj, obj.jid)
|
self.log_message(obj, obj.jid)
|
||||||
|
|
||||||
def on_send_not_ok(reason):
|
def on_send_not_ok(reason):
|
||||||
reason += ' ' + _('Your message could not be sent.')
|
reason += ' ' + _('Your message could not be sent.')
|
||||||
app.nec.push_incoming_event(MessageErrorEvent(None, conn=self,
|
app.nec.push_incoming_event(MessageErrorEvent(
|
||||||
fjid=obj.jid, error_code=-1, error_msg=reason, msg=None,
|
None, conn=self, fjid=obj.jid, error_code=-1, error_msg=reason,
|
||||||
time_=None, session=obj.session))
|
msg=None, time_=None, session=obj.session, zeroconf=True))
|
||||||
# Dont propagate event
|
# Dont propagate event
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
@ -347,10 +352,12 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
|
|
||||||
if ret == -1:
|
if ret == -1:
|
||||||
# Contact Offline
|
# Contact Offline
|
||||||
app.nec.push_incoming_event(MessageErrorEvent(None, conn=self,
|
error_message = _(
|
||||||
fjid=obj.jid, error_code=-1, error_msg=_(
|
'Contact is offline. Your message could not be sent.')
|
||||||
'Contact is offline. Your message could not be sent.'),
|
app.nec.push_incoming_event(MessageErrorEvent(
|
||||||
msg=None, time_=None, session=obj.session))
|
None, conn=self, fjid=obj.jid, error_code=-1,
|
||||||
|
error_msg=error_message, msg=None, time_=None,
|
||||||
|
session=obj.session, zeroconf=True))
|
||||||
# Dont propagate event
|
# Dont propagate event
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
@ -369,9 +376,12 @@ class ConnectionZeroconf(CommonConnection, ConnectionHandlersZeroconf):
|
||||||
thread_id = data[1]
|
thread_id = data[1]
|
||||||
frm = data[0]
|
frm = data[0]
|
||||||
session = self.get_or_create_session(frm, thread_id)
|
session = self.get_or_create_session(frm, thread_id)
|
||||||
|
error_message = _(
|
||||||
|
'Connection to host could not be established: '
|
||||||
|
'Timeout while sending data.')
|
||||||
app.nec.push_incoming_event(MessageErrorEvent(
|
app.nec.push_incoming_event(MessageErrorEvent(
|
||||||
None, conn=self, fjid=frm, error_code=-1, error_msg=_(
|
None, conn=self, fjid=frm, error_code=-1,
|
||||||
'Connection to host could not be established: Timeout while '
|
error_msg=error_message, msg=None, time_=None,
|
||||||
'sending data.'), msg=None, time_=None, session=session))
|
session=session, zeroconf=True))
|
||||||
|
|
||||||
# END ConnectionZeroconf
|
# END ConnectionZeroconf
|
||||||
|
|
|
@ -160,7 +160,7 @@ class Zeroconf:
|
||||||
|
|
||||||
# we don't want to see ourselves in the list
|
# we don't want to see ourselves in the list
|
||||||
if name != self.name:
|
if name != self.name:
|
||||||
resolved_info = [(interface, protocol, host, aprotocol, address, port)]
|
resolved_info = [(interface, protocol, host, aprotocol, address, int(port))]
|
||||||
if name in self.contacts:
|
if name in self.contacts:
|
||||||
# Decide whether to try to merge with existing resolved info:
|
# Decide whether to try to merge with existing resolved info:
|
||||||
old_name, old_domain, old_resolved_info, old_bare_name, old_txt = self.contacts[name]
|
old_name, old_domain, old_resolved_info, old_bare_name, old_txt = self.contacts[name]
|
||||||
|
@ -186,7 +186,7 @@ class Zeroconf:
|
||||||
# gajim instance on the same machine,
|
# gajim instance on the same machine,
|
||||||
# it will be used when we get a new name.
|
# it will be used when we get a new name.
|
||||||
self.invalid_self_contact[name] = (name, domain,
|
self.invalid_self_contact[name] = (name, domain,
|
||||||
(interface, protocol, host, aprotocol, address, port),
|
(interface, protocol, host, aprotocol, address, int(port)),
|
||||||
bare_name, txt)
|
bare_name, txt)
|
||||||
|
|
||||||
|
|
||||||
|
@ -445,7 +445,7 @@ class Zeroconf:
|
||||||
# refresh txt data of all contacts manually (no callback available)
|
# refresh txt data of all contacts manually (no callback available)
|
||||||
def resolve_all(self):
|
def resolve_all(self):
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return False
|
||||||
for val in self.contacts.values():
|
for val in self.contacts.values():
|
||||||
# get txt data from last recorded resolved info
|
# get txt data from last recorded resolved info
|
||||||
# TODO: Better try to get it from last IPv6 mDNS, then last IPv4?
|
# TODO: Better try to get it from last IPv6 mDNS, then last IPv4?
|
||||||
|
@ -456,6 +456,8 @@ class Zeroconf:
|
||||||
reply_handler=self.service_resolved_all_callback,
|
reply_handler=self.service_resolved_all_callback,
|
||||||
error_handler=self.error_callback)
|
error_handler=self.error_callback)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
def get_contacts(self):
|
def get_contacts(self):
|
||||||
return self.contacts
|
return self.contacts
|
||||||
|
|
||||||
|
|
|
@ -1,28 +1,27 @@
|
||||||
## common/zeroconf/zeroconf_bonjour.py
|
# Copyright (C) 2006 Stefan Bethge <stefan@lanpartei.de>
|
||||||
##
|
# Copyright (C) 2006 Philipp Hörist <philipp@hoerist.com>
|
||||||
## Copyright (C) 2006 Stefan Bethge <stefan@lanpartei.de>
|
#
|
||||||
##
|
# This file is part of Gajim.
|
||||||
## This file is part of Gajim.
|
#
|
||||||
##
|
# Gajim is free software; you can redistribute it and/or modify
|
||||||
## Gajim is free software; you can redistribute it and/or modify
|
# it under the terms of the GNU General Public License as published
|
||||||
## it under the terms of the GNU General Public License as published
|
# by the Free Software Foundation; version 3 only.
|
||||||
## by the Free Software Foundation; version 3 only.
|
#
|
||||||
##
|
# Gajim is distributed in the hope that it will be useful,
|
||||||
## Gajim is distributed in the hope that it will be useful,
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
## but WITHOUT ANY WARRANTY; without even the implied warranty of
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
# GNU General Public License for more details.
|
||||||
## GNU General Public License for more details.
|
#
|
||||||
##
|
# You should have received a copy of the GNU General Public License
|
||||||
## You should have received a copy of the GNU General Public License
|
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
|
||||||
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
##
|
|
||||||
|
|
||||||
from gajim.common import app
|
|
||||||
import select
|
|
||||||
import re
|
|
||||||
import logging
|
import logging
|
||||||
|
import select
|
||||||
|
import socket
|
||||||
|
import re
|
||||||
from gajim.common.zeroconf.zeroconf import Constant
|
from gajim.common.zeroconf.zeroconf import Constant
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger('gajim.c.z.zeroconf_bonjour')
|
log = logging.getLogger('gajim.c.z.zeroconf_bonjour')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -30,18 +29,17 @@ try:
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
resolve_timeout = 1
|
resolve_timeout = 1
|
||||||
|
|
||||||
|
|
||||||
class Zeroconf:
|
class Zeroconf:
|
||||||
def __init__(self, new_serviceCB, remove_serviceCB, name_conflictCB,
|
def __init__(self, new_serviceCB, remove_serviceCB, name_conflictCB,
|
||||||
disconnected_CB, error_CB, name, host, port):
|
disconnected_CB, error_CB, name, host, port):
|
||||||
self.domain = None # specific domain to browse
|
|
||||||
self.stype = '_presence._tcp'
|
self.stype = '_presence._tcp'
|
||||||
self.port = port # listening port that gets announced
|
self.port = port # listening port that gets announced
|
||||||
self.username = name
|
self.username = name
|
||||||
self.host = host
|
self.host = host
|
||||||
self.txt = pybonjour.TXTRecord() # service data
|
self.txt = {} # service data
|
||||||
|
|
||||||
# XXX these CBs should be set to None when we destroy the object
|
# XXX these CBs should be set to None when we destroy the object
|
||||||
# (go offline), because they create a circular reference
|
# (go offline), because they create a circular reference
|
||||||
|
@ -51,67 +49,76 @@ class Zeroconf:
|
||||||
self.disconnected_CB = disconnected_CB
|
self.disconnected_CB = disconnected_CB
|
||||||
self.error_CB = error_CB
|
self.error_CB = error_CB
|
||||||
|
|
||||||
self.contacts = {} # all current local contacts with data
|
self.contacts = {} # all current local contacts with data
|
||||||
self.connected = False
|
self.connected = False
|
||||||
self.announced = False
|
self.announced = False
|
||||||
self.invalid_self_contact = {}
|
self.invalid_self_contact = {}
|
||||||
|
self.resolved_contacts = {}
|
||||||
self.resolved = []
|
self.resolved = []
|
||||||
|
self.queried = []
|
||||||
|
|
||||||
|
def browse_callback(self, sdRef, flags, interfaceIndex, errorCode,
|
||||||
def browse_callback(self, sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain):
|
serviceName, regtype, replyDomain):
|
||||||
log.debug('Found service %s in domain %s on %i(type: %s).' % (serviceName, replyDomain, interfaceIndex, regtype))
|
log.debug('Found service %s in domain %s on %i(type: %s).',
|
||||||
|
serviceName, replyDomain, interfaceIndex, regtype)
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return
|
||||||
if errorCode != pybonjour.kDNSServiceErr_NoError:
|
if errorCode != pybonjour.kDNSServiceErr_NoError:
|
||||||
|
log.debug('Error in browse_callback: %s', str(errorCode))
|
||||||
return
|
return
|
||||||
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
||||||
self.remove_service_callback(serviceName)
|
self.remove_service_callback(serviceName)
|
||||||
return
|
return
|
||||||
|
|
||||||
# asynchronous resolving
|
|
||||||
resolve_sdRef = pybonjour.DNSServiceResolve(0, interfaceIndex, serviceName, regtype, replyDomain, self.service_resolved_callback)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
# asynchronous resolving
|
||||||
|
resolve_sdRef = None
|
||||||
|
resolve_sdRef = pybonjour.DNSServiceResolve(
|
||||||
|
0, interfaceIndex, serviceName,
|
||||||
|
regtype, replyDomain, self.service_resolved_callback)
|
||||||
|
|
||||||
while not self.resolved:
|
while not self.resolved:
|
||||||
ready = select.select([resolve_sdRef], [], [], resolve_timeout)
|
ready = select.select([resolve_sdRef], [], [], resolve_timeout)
|
||||||
if resolve_sdRef not in ready[0]:
|
if resolve_sdRef not in ready[0]:
|
||||||
log.debug('Resolve timed out')
|
log.info('Resolve timed out')
|
||||||
break
|
break
|
||||||
pybonjour.DNSServiceProcessResult(resolve_sdRef)
|
pybonjour.DNSServiceProcessResult(resolve_sdRef)
|
||||||
else:
|
else:
|
||||||
self.resolved.pop()
|
self.resolved.pop()
|
||||||
|
|
||||||
|
except pybonjour.BonjourError as error:
|
||||||
|
log.info('Error when resolving DNS: %s', error)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
resolve_sdRef.close()
|
if resolve_sdRef:
|
||||||
|
resolve_sdRef.close()
|
||||||
|
|
||||||
def remove_service_callback(self, name):
|
def remove_service_callback(self, name):
|
||||||
log.debug('Service %s disappeared.' % name)
|
log.info('Service %s disappeared.' % name)
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return
|
||||||
if name != self.name:
|
if name != self.name:
|
||||||
for key in self.contacts.keys():
|
for key in self.contacts.keys():
|
||||||
if self.contacts[key][Constant.BARE_NAME] == name:
|
if self.contacts[key][Constant.NAME] == name:
|
||||||
del self.contacts[key]
|
del self.contacts[key]
|
||||||
self.remove_serviceCB(key)
|
self.remove_serviceCB(key)
|
||||||
return
|
return
|
||||||
|
|
||||||
def new_domain_callback(self, interface, protocol, domain, flags):
|
|
||||||
if domain != "local":
|
|
||||||
self.browse_domain(domain)
|
|
||||||
|
|
||||||
# takes a TXTRecord instance
|
|
||||||
def txt_array_to_dict(self, txt):
|
def txt_array_to_dict(self, txt):
|
||||||
items = pybonjour.TXTRecord.parse(txt)._items
|
if isinstance(txt, pybonjour.TXTRecord):
|
||||||
|
items = txt._items
|
||||||
|
else:
|
||||||
|
items = pybonjour.TXTRecord.parse(txt)._items
|
||||||
return dict((v[0], v[1]) for v in items.values())
|
return dict((v[0], v[1]) for v in items.values())
|
||||||
|
|
||||||
def service_resolved_callback(self, sdRef, flags, interfaceIndex, errorCode, fullname,
|
@staticmethod
|
||||||
hosttarget, port, txtRecord):
|
def _parse_name(fullname):
|
||||||
|
log.debug('Parse name: %s', fullname)
|
||||||
# TODO: do proper decoding...
|
# TODO: do proper decoding...
|
||||||
escaping= {
|
escaping = {r'\.': '.',
|
||||||
r'\.': '.',
|
r'\032': ' ',
|
||||||
r'\032': ' ',
|
r'\064': '@',
|
||||||
r'\064': '@',
|
}
|
||||||
}
|
|
||||||
|
|
||||||
# Split on '.' but do not split on '\.'
|
# Split on '.' but do not split on '\.'
|
||||||
result = re.split('(?<!\\\\)\.', fullname)
|
result = re.split('(?<!\\\\)\.', fullname)
|
||||||
|
@ -122,21 +129,59 @@ class Zeroconf:
|
||||||
for src, trg in escaping.items():
|
for src, trg in escaping.items():
|
||||||
name = name.replace(src, trg)
|
name = name.replace(src, trg)
|
||||||
|
|
||||||
txt = pybonjour.TXTRecord.parse(txtRecord)
|
bare_name = name
|
||||||
|
if '@' not in name:
|
||||||
|
name = name + '@' + name
|
||||||
|
log.debug('End parse: %s %s %s %s',
|
||||||
|
name, bare_name, protocol, domain)
|
||||||
|
|
||||||
log.debug('Service data for service %s on %i:' % (fullname, interfaceIndex))
|
return name, bare_name, protocol, domain
|
||||||
log.debug('Host %s, port %i, TXT data: %s' % (hosttarget, port, txt._items))
|
|
||||||
|
def query_txt_callback(self, sdRef, flags, interfaceIndex, errorCode,
|
||||||
|
hosttarget, rrtype, rrclass, rdata, ttl):
|
||||||
|
# Callback from DNSServiceQueryRecord, it does not call decode()
|
||||||
|
# on rdata
|
||||||
|
rdata = rdata.decode()
|
||||||
|
|
||||||
|
if errorCode != pybonjour.kDNSServiceErr_NoError:
|
||||||
|
log.error('Error in query_record_callback: %s', str(errorCode))
|
||||||
|
return
|
||||||
|
|
||||||
|
name, bare_name, protocol, domain = self._parse_name(hosttarget)
|
||||||
|
|
||||||
|
if name != self.name:
|
||||||
|
# update TXT data only, as intended according to
|
||||||
|
# resolve_all comment
|
||||||
|
old_contact = self.contacts[name]
|
||||||
|
self.contacts[name] = old_contact[0:Constant.TXT] + (rdata,) + old_contact[Constant.TXT+1:]
|
||||||
|
log.debug(self.contacts[name])
|
||||||
|
|
||||||
|
self.queried.append(True)
|
||||||
|
|
||||||
|
def query_record_callback(self, sdRef, flags, interfaceIndex, errorCode,
|
||||||
|
hosttarget, rrtype, rrclass, rdata, ttl):
|
||||||
|
if errorCode != pybonjour.kDNSServiceErr_NoError:
|
||||||
|
log.error('Error in query_record_callback: %s', str(errorCode))
|
||||||
|
return
|
||||||
|
|
||||||
|
fullname, port, txtRecord = self.resolved_contacts[hosttarget]
|
||||||
|
|
||||||
|
txt = pybonjour.TXTRecord.parse(txtRecord)
|
||||||
|
ip = socket.inet_ntoa(rdata)
|
||||||
|
|
||||||
|
name, bare_name, protocol, domain = self._parse_name(fullname)
|
||||||
|
|
||||||
|
log.info('Service data for service %s on %i:',
|
||||||
|
fullname, interfaceIndex)
|
||||||
|
log.info('Host %s, ip %s, port %i, TXT data: %s',
|
||||||
|
hosttarget, ip, port, txt._items)
|
||||||
|
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return
|
||||||
|
|
||||||
bare_name = name
|
|
||||||
if '@' not in name:
|
|
||||||
name = name + '@' + name
|
|
||||||
|
|
||||||
# we don't want to see ourselves in the list
|
# we don't want to see ourselves in the list
|
||||||
if name != self.name:
|
if name != self.name:
|
||||||
resolved_info = [(interfaceIndex, protocol, hosttarget, -1, port)]
|
resolved_info = [(interfaceIndex, protocol, hosttarget, fullname, ip, port)]
|
||||||
self.contacts[name] = (name, domain, resolved_info, bare_name, txtRecord)
|
self.contacts[name] = (name, domain, resolved_info, bare_name, txtRecord)
|
||||||
|
|
||||||
self.new_serviceCB(name)
|
self.new_serviceCB(name)
|
||||||
|
@ -145,57 +190,71 @@ class Zeroconf:
|
||||||
# In case this is not our own record but of another
|
# In case this is not our own record but of another
|
||||||
# gajim instance on the same machine,
|
# gajim instance on the same machine,
|
||||||
# it will be used when we get a new name.
|
# it will be used when we get a new name.
|
||||||
self.invalid_self_contact[name] = (name, domain, (interfaceIndex, protocol, hosttarget, -1, port), bare_name, txtRecord)
|
self.invalid_self_contact[name] = \
|
||||||
# count services
|
(name, domain,
|
||||||
self.resolved.append(True)
|
(interfaceIndex, protocol, hosttarget, fullname, ip, port),
|
||||||
|
bare_name, txtRecord)
|
||||||
|
|
||||||
# different handler when resolving all contacts
|
self.queried.append(True)
|
||||||
def service_resolved_all_callback(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord):
|
|
||||||
if not self.connected:
|
def service_resolved_callback(self, sdRef, flags, interfaceIndex,
|
||||||
|
errorCode, fullname, hosttarget, port,
|
||||||
|
txtRecord):
|
||||||
|
|
||||||
|
if errorCode != pybonjour.kDNSServiceErr_NoError:
|
||||||
|
log.error('Error in service_resolved_callback: %s', str(errorCode))
|
||||||
return
|
return
|
||||||
|
|
||||||
escaping= {
|
self.resolved_contacts[hosttarget] = (fullname, port, txtRecord)
|
||||||
r'\.': '.',
|
|
||||||
r'\032': ' ',
|
|
||||||
r'\064': '@',
|
|
||||||
}
|
|
||||||
|
|
||||||
name, stype, protocol, domain, dummy = fullname.split('.')
|
try:
|
||||||
|
query_sdRef = None
|
||||||
|
query_sdRef = \
|
||||||
|
pybonjour.DNSServiceQueryRecord(
|
||||||
|
interfaceIndex=interfaceIndex,
|
||||||
|
fullname=hosttarget,
|
||||||
|
rrtype=pybonjour.kDNSServiceType_A,
|
||||||
|
callBack=self.query_record_callback)
|
||||||
|
|
||||||
# Replace the escaped values
|
while not self.queried:
|
||||||
for src, trg in escaping.items():
|
ready = select.select([query_sdRef], [], [], resolve_timeout)
|
||||||
name = name.replace(src, trg)
|
if query_sdRef not in ready[0]:
|
||||||
|
log.warning('Query record timed out')
|
||||||
|
break
|
||||||
|
pybonjour.DNSServiceProcessResult(query_sdRef)
|
||||||
|
else:
|
||||||
|
self.queried.pop()
|
||||||
|
|
||||||
bare_name = name
|
except pybonjour.BonjourError as error:
|
||||||
if name.find('@') == -1:
|
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
|
||||||
name = name + '@' + name
|
log.info('Service not running')
|
||||||
|
else:
|
||||||
|
self.error_CB(_('Error while adding service. %s') % error)
|
||||||
|
|
||||||
# we don't want to see ourselves in the list
|
finally:
|
||||||
if name != self.name:
|
if query_sdRef:
|
||||||
# update TXT data only, as intended according to resolve_all comment
|
query_sdRef.close()
|
||||||
old_contact = self.contacts[name]
|
|
||||||
self.contacts[name] = old_contact[0:Constant.TXT] + (self.txt,) + old_contact[Constant.TXT+1:]
|
|
||||||
|
|
||||||
|
self.resolved.append(True)
|
||||||
|
|
||||||
def service_added_callback(self, sdRef, flags, errorCode, name, regtype, domain):
|
def service_added_callback(self, sdRef, flags, errorCode,
|
||||||
|
name, regtype, domain):
|
||||||
if errorCode == pybonjour.kDNSServiceErr_NoError:
|
if errorCode == pybonjour.kDNSServiceErr_NoError:
|
||||||
log.debug('Service successfully added')
|
log.info('Service successfully added')
|
||||||
|
|
||||||
def service_add_fail_callback(self, err):
|
elif errorCode == pybonjour.kDNSServiceErr_NameConflict:
|
||||||
if err[0][0] == pybonjour.kDNSServiceErr_NameConflict:
|
log.error('Error while adding service. %s', errorCode)
|
||||||
log.debug('Error while adding service. %s' % str(err))
|
|
||||||
parts = self.username.split(' ')
|
parts = self.username.split(' ')
|
||||||
|
|
||||||
#check if last part is a number and if, increment it
|
# check if last part is a number and if, increment it
|
||||||
try:
|
try:
|
||||||
stripped = str(int(parts[-1]))
|
stripped = str(int(parts[-1]))
|
||||||
except Exception:
|
except Exception:
|
||||||
stripped = 1
|
stripped = 1
|
||||||
alternative_name = self.username + str(stripped+1)
|
alternative_name = self.username + str(stripped + 1)
|
||||||
self.name_conflictCB(alternative_name)
|
self.name_conflictCB(alternative_name)
|
||||||
return
|
else:
|
||||||
self.error_CB(_('Error while adding service. %s') % str(err))
|
self.error_CB(_('Error while adding service. %s') % str(errorCode))
|
||||||
self.disconnect()
|
|
||||||
|
|
||||||
# make zeroconf-valid names
|
# make zeroconf-valid names
|
||||||
def replace_show(self, show):
|
def replace_show(self, show):
|
||||||
|
@ -208,8 +267,8 @@ class Zeroconf:
|
||||||
def create_service(self):
|
def create_service(self):
|
||||||
txt = {}
|
txt = {}
|
||||||
|
|
||||||
#remove empty keys
|
# remove empty keys
|
||||||
for key, val in self.txt:
|
for key, val in self.txt.items():
|
||||||
if val:
|
if val:
|
||||||
txt[key] = val
|
txt[key] = val
|
||||||
|
|
||||||
|
@ -222,22 +281,27 @@ class Zeroconf:
|
||||||
txt['status'] = self.replace_show(self.txt['status'])
|
txt['status'] = self.replace_show(self.txt['status'])
|
||||||
else:
|
else:
|
||||||
txt['status'] = 'avail'
|
txt['status'] = 'avail'
|
||||||
|
self.txt = txt
|
||||||
self.txt = pybonjour.TXTRecord(txt, strict=True)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
sdRef = pybonjour.DNSServiceRegister(name = self.name,
|
self.service_sdRef = pybonjour.DNSServiceRegister(
|
||||||
regtype = self.stype, port = self.port, txtRecord = self.txt,
|
name=self.name,
|
||||||
callBack = self.service_added_callback)
|
regtype=self.stype,
|
||||||
self.service_sdRef = sdRef
|
port=self.port,
|
||||||
except pybonjour.BonjourError as e:
|
txtRecord=pybonjour.TXTRecord(self.txt, strict=True),
|
||||||
self.service_add_fail_callback(e)
|
callBack=self.service_added_callback)
|
||||||
else:
|
|
||||||
log.debug('Publishing service %s of type %s' % (self.name, self.stype))
|
|
||||||
|
|
||||||
ready = select.select([sdRef], [], [], resolve_timeout)
|
log.info('Publishing service %s of type %s', self.name, self.stype)
|
||||||
if sdRef in ready[0]:
|
|
||||||
pybonjour.DNSServiceProcessResult(sdRef)
|
ready = select.select([self.service_sdRef], [], [])
|
||||||
|
if self.service_sdRef in ready[0]:
|
||||||
|
pybonjour.DNSServiceProcessResult(self.service_sdRef)
|
||||||
|
|
||||||
|
except pybonjour.BonjourError as error:
|
||||||
|
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
|
||||||
|
log.info('Service not running')
|
||||||
|
else:
|
||||||
|
self.error_CB(_('Error while adding service. %s') % error)
|
||||||
|
self.disconnect()
|
||||||
|
|
||||||
def announce(self):
|
def announce(self):
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
|
@ -254,28 +318,21 @@ class Zeroconf:
|
||||||
self.service_sdRef.close()
|
self.service_sdRef.close()
|
||||||
self.announced = False
|
self.announced = False
|
||||||
return True
|
return True
|
||||||
except pybonjour.BonjourError as e:
|
except pybonjour.BonjourError as error:
|
||||||
log.debug(e)
|
log.error('Error when removing announce: %s', error)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def connect(self):
|
def connect(self):
|
||||||
self.name = self.username + '@' + self.host # service name
|
self.name = self.username + '@' + self.host # service name
|
||||||
|
|
||||||
self.connected = True
|
self.connected = True
|
||||||
|
|
||||||
# start browsing
|
# start browsing
|
||||||
if self.domain is None:
|
if self.browse_domain():
|
||||||
# Explicitly browse .local
|
return True
|
||||||
self.browse_domain()
|
|
||||||
|
|
||||||
# Browse for other browsable domains
|
|
||||||
#self.domain_sdRef = pybonjour.DNSServiceEnumerateDomains(flags, interfaceIndex=0, callBack=self.new_domain_callback)
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
self.browse_domain(self.domain)
|
self.disconnect()
|
||||||
|
return False
|
||||||
return True
|
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
if self.connected:
|
if self.connected:
|
||||||
|
@ -285,54 +342,92 @@ class Zeroconf:
|
||||||
self.remove_announce()
|
self.remove_announce()
|
||||||
|
|
||||||
def browse_domain(self, domain=None):
|
def browse_domain(self, domain=None):
|
||||||
log.debug('starting to browse')
|
|
||||||
try:
|
try:
|
||||||
self.browse_sdRef = pybonjour.DNSServiceBrowse(regtype=self.stype, domain=domain, callBack=self.browse_callback)
|
self.browse_sdRef = pybonjour.DNSServiceBrowse(
|
||||||
except pybonjour.BonjourError as e:
|
regtype=self.stype,
|
||||||
self.error_CB("Error while browsing: %s" % str(e))
|
domain=domain,
|
||||||
|
callBack=self.browse_callback)
|
||||||
|
log.info('Starting to browse .local')
|
||||||
|
return True
|
||||||
|
except pybonjour.BonjourError as error:
|
||||||
|
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
|
||||||
|
log.info('Service not running')
|
||||||
|
else:
|
||||||
|
log.error('Error while browsing for services. %s', error)
|
||||||
|
return False
|
||||||
|
|
||||||
def browse_loop(self):
|
def browse_loop(self):
|
||||||
ready = select.select([self.browse_sdRef], [], [], 0)
|
try:
|
||||||
if self.browse_sdRef in ready[0]:
|
ready = select.select([self.browse_sdRef], [], [], 0)
|
||||||
pybonjour.DNSServiceProcessResult(self.browse_sdRef)
|
if self.browse_sdRef in ready[0]:
|
||||||
|
pybonjour.DNSServiceProcessResult(self.browse_sdRef)
|
||||||
|
except pybonjour.BonjourError as error:
|
||||||
|
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
|
||||||
|
log.info('Service not running')
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
log.error('Error while browsing for services. %s', error)
|
||||||
|
return True
|
||||||
|
|
||||||
# refresh txt data of all contacts manually (no callback available)
|
# resolve_all() is called every X seconds and querys for new clients
|
||||||
|
# and monitors TXT records for changed status
|
||||||
def resolve_all(self):
|
def resolve_all(self):
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return
|
return False
|
||||||
|
|
||||||
# for now put here as this is synchronous
|
# for now put here as this is synchronous
|
||||||
self.browse_loop()
|
if not self.browse_loop():
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Monitor TXT Records with DNSServiceQueryRecord because
|
||||||
|
# its more efficient (see pybonjour documentation)
|
||||||
for val in self.contacts.values():
|
for val in self.contacts.values():
|
||||||
resolve_sdRef = pybonjour.DNSServiceResolve(0,
|
|
||||||
pybonjour.kDNSServiceInterfaceIndexAny, val[Constant.BARE_NAME],
|
|
||||||
self.stype + '.', val[Constant.DOMAIN] + '.',
|
|
||||||
self.service_resolved_all_callback)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ready = select.select([resolve_sdRef], [], [], resolve_timeout)
|
query_sdRef = None
|
||||||
if resolve_sdRef not in ready[0]:
|
query_sdRef = \
|
||||||
log.debug('Resolve timed out (in resolve_all)')
|
pybonjour.DNSServiceQueryRecord(
|
||||||
break
|
interfaceIndex=pybonjour.kDNSServiceInterfaceIndexAny,
|
||||||
pybonjour.DNSServiceProcessResult(resolve_sdRef)
|
fullname=val[Constant.RESOLVED_INFO][0][Constant.BARE_NAME],
|
||||||
|
rrtype=pybonjour.kDNSServiceType_TXT,
|
||||||
|
callBack=self.query_txt_callback)
|
||||||
|
|
||||||
|
while not self.queried:
|
||||||
|
ready = select.select(
|
||||||
|
[query_sdRef], [], [], resolve_timeout)
|
||||||
|
if query_sdRef not in ready[0]:
|
||||||
|
log.info('Query record timed out')
|
||||||
|
break
|
||||||
|
pybonjour.DNSServiceProcessResult(query_sdRef)
|
||||||
|
else:
|
||||||
|
self.queried.pop()
|
||||||
|
|
||||||
|
except pybonjour.BonjourError as error:
|
||||||
|
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
|
||||||
|
log.info('Service not running')
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
log.error('Error in query for TXT records. %s', error)
|
||||||
finally:
|
finally:
|
||||||
resolve_sdRef.close()
|
if query_sdRef:
|
||||||
|
query_sdRef.close()
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
def get_contacts(self):
|
def get_contacts(self):
|
||||||
return self.contacts
|
return self.contacts
|
||||||
|
|
||||||
def get_contact(self, jid):
|
def get_contact(self, jid):
|
||||||
if not jid in self.contacts:
|
if jid not in self.contacts:
|
||||||
return None
|
return None
|
||||||
return self.contacts[jid]
|
return self.contacts[jid]
|
||||||
|
|
||||||
def update_txt(self, show = None):
|
def update_txt(self, show=None):
|
||||||
if show:
|
if show:
|
||||||
self.txt['status'] = self.replace_show(show)
|
self.txt['status'] = self.replace_show(show)
|
||||||
|
|
||||||
|
txt = pybonjour.TXTRecord(self.txt, strict=True)
|
||||||
try:
|
try:
|
||||||
pybonjour.DNSServiceUpdateRecord(self.service_sdRef, None, 0, self.txt)
|
pybonjour.DNSServiceUpdateRecord(self.service_sdRef, None, 0, txt)
|
||||||
except pybonjour.BonjourError:
|
except pybonjour.BonjourError as e:
|
||||||
|
log.error('Error when updating TXT Record: %s', e)
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
Loading…
Add table
Reference in a new issue