zeroconf.py 11.6 KB
Newer Older
sb's avatar
sb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
##      common/zeroconf/zeroconf.py
##
## Copyright (C) 2006 Stefan Bethge <stefan@lanpartei.de>
##
## This program 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 2 only.
##
## This program 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.
##

sb's avatar
sb committed
15 16
import os
import sys
17
import socket
18
from common import gajim
19 20
from common import xmpp

21 22 23
try:
	import avahi, gobject, dbus
except ImportError:
sb's avatar
sb committed
24
	gajim.log.debug('Error: python-avahi and python-dbus need to be installed. No zeroconf support.')
25 26 27 28 29 30

try:
	import dbus.glib
except ImportError, e:
	pass

31 32 33 34

C_NAME, C_DOMAIN, C_INTERFACE, C_PROTOCOL, C_HOST, \
C_ADDRESS, C_PORT, C_BARE_NAME, C_TXT = range(9)

35
class Zeroconf:
36 37
	def __init__(self, new_serviceCB, remove_serviceCB, name_conflictCB, 
		disconnected_CB, name, host, port):
38
		self.server = None
39
		self.domain = None   # specific domain to browse
sb's avatar
sb committed
40
		self.stype = '_presence._tcp'	
41 42 43
		self.port = port  # listening port that gets announced	
		self.username = name
		self.host = host
sb's avatar
sb committed
44
		self.txt = {}		# service data
45
		
46 47
		#XXX these CBs should be set to None when we destroy the object 
		# (go offline), because they create a circular reference 
48 49
		self.new_serviceCB = new_serviceCB
		self.remove_serviceCB = remove_serviceCB
50
		self.name_conflictCB = name_conflictCB
51
		self.disconnected_CB = disconnected_CB
52
		
sb's avatar
sb committed
53
		self.service_browser = None
54 55
		self.domain_browser = None
		self.server = None
56
		self.contacts = {}    # all current local contacts with data
57
		self.entrygroup = None
58
		self.connected = False
59
		self.announced = False
60 61
		self.invalid_self_contact = {}

62

63
	## handlers for dbus callbacks
64 65 66 67 68
	def entrygroup_commit_error_CB(self, err):
		# left for eventual later use
		pass
	
	def error_callback(self, err):
69
		gajim.log.debug(str(err))
70 71 72 73
		# timeouts are non-critical
		if str(err) != 'Timeout reached':
			self.disconnect()
			self.disconnected_CB()
74 75

	def new_service_callback(self, interface, protocol, name, stype, domain, flags):
sb's avatar
sb committed
76
		gajim.log.debug('Found service %s in domain %s on %i.%i.' % (name, domain, interface, protocol))
77 78
		# if not self.connected:
		# 	return
sb's avatar
sb committed
79
		
80
		# synchronous resolving
81 82
		self.server.ResolveService( int(interface), int(protocol), name, stype, \
					domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), \
83
					reply_handler=self.service_resolved_callback, error_handler=self.error_callback)
84 85

	def remove_service_callback(self, interface, protocol, name, stype, domain, flags):
sb's avatar
sb committed
86
		gajim.log.debug('Service %s in domain %s on %i.%i disappeared.' % (name, domain, interface, protocol))
87 88
		# if not self.connected:
		# 	return
89
		if name != self.name:
90 91 92 93 94
			for key in self.contacts.keys():
				if self.contacts[key][C_BARE_NAME] == name:
					del self.contacts[key]
					self.remove_serviceCB(key)
					return
95 96 97

	def new_service_type(self, interface, protocol, stype, domain, flags):
		# Are we already browsing this domain for this type? 
sb's avatar
sb committed
98
		if self.service_browser:
99 100
			return

101 102 103
		object_path = self.server.ServiceBrowserNew(interface, protocol, \
				stype, domain, dbus.UInt32(0))
		
sb's avatar
sb committed
104
		self.service_browser = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, \
105
			object_path) , avahi.DBUS_INTERFACE_SERVICE_BROWSER)
sb's avatar
sb committed
106 107
		self.service_browser.connect_to_signal('ItemNew', self.new_service_callback)
		self.service_browser.connect_to_signal('ItemRemove', self.remove_service_callback)
108
		self.service_browser.connect_to_signal('Failure', self.error_callback)
109 110 111 112 113

	def new_domain_callback(self,interface, protocol, domain, flags):
		if domain != "local":
			self.browse_domain(interface, protocol, domain)

dkirov's avatar
dkirov committed
114 115
	def txt_array_to_dict(self,txt_array):
		items = {}
sb's avatar
sb committed
116

dkirov's avatar
dkirov committed
117 118 119 120 121 122
		for byte_array in txt_array:
			# 'str' is used for string type in python
			value = avahi.byte_array_to_string(byte_array)
			poseq = value.find('=')
			items[value[:poseq]] = value[poseq+1:]
		return items
sb's avatar
sb committed
123
	
124
	def service_resolved_callback(self, interface, protocol, name, stype, domain, host, aprotocol, address, port, txt, flags):	
sb's avatar
sb committed
125 126
		gajim.log.debug('Service data for service %s in domain %s on %i.%i:' % (name, domain, interface, protocol))
		gajim.log.debug('Host %s (%s), port %i, TXT data: %s' % (host, address, port, avahi.txt_array_to_string_array(txt)))
127 128
		if not self.connected:
			return
129 130 131 132
		bare_name = name
		if name.find('@') == -1:
			name = name + '@' + name
		
133 134 135
		# we don't want to see ourselves in the list
		if name != self.name:
			self.contacts[name] = (name, domain, interface, protocol, host, address, port, 
136
					bare_name, txt)
137 138 139 140 141 142 143 144
			self.new_serviceCB(name)
		else:
			# remember data
			# In case this is not our own record but of another
			# gajim instance on the same machine,
			# it will be used when we get a new name.
			self.invalid_self_contact[name] = (name, domain, interface, protocol, host, address, port, bare_name, txt)

145 146 147

	# different handler when resolving all contacts
	def service_resolved_all_callback(self, interface, protocol, name, stype, domain, host, aprotocol, address, port, txt, flags):
148 149
		if not self.connected:
			return
150 151 152 153
		bare_name = name
		if name.find('@') == -1:
			name = name + '@' + name
		self.contacts[name] = (name, domain, interface, protocol, host, address, port, bare_name, txt)
154 155

	def service_added_callback(self):
sb's avatar
sb committed
156
		gajim.log.debug('Service successfully added')
157

158
	def service_committed_callback(self):
sb's avatar
sb committed
159
		gajim.log.debug('Service successfully committed')
160

161
	def service_updated_callback(self):
sb's avatar
sb committed
162
		gajim.log.debug('Service successfully updated')
163 164

	def service_add_fail_callback(self, err):
165 166 167 168
		gajim.log.debug('Error while adding service. %s' % str(err))
		alternative_name = self.server.GetAlternativeServiceName(self.username)
		self.disconnect()
		self.name_conflictCB(alternative_name)
169

170
	def server_state_changed_callback(self, state, error):
sb's avatar
sb committed
171
		print 'server.state %s' % state
172 173 174 175
		if state == avahi.SERVER_RUNNING:
			self.create_service()
		elif state == avahi.SERVER_COLLISION:
			self.entrygroup.Reset()
176 177
		elif state == avahi.CLIENT_FAILURE:           # TODO: add error handling (avahi daemon dies...?)
			print 'CLIENT FAILURE'
178

179
	def entrygroup_state_changed_callback(self, state, error):
sb's avatar
sb committed
180
		# the name is already present, so recreate
181
		if state == avahi.ENTRY_GROUP_COLLISION:
sb's avatar
sb committed
182
			self.service_add_fail_callback('Local name collision, recreating.')
183 184
		elif state == avahi.ENTRY_GROUP_FAILURE:
			print 'zeroconf.py: ENTRY_GROUP_FAILURE reached(that should not happen)'
185

186 187
	# make zeroconf-valid names
	def replace_show(self, show):
188 189
		if show in ['chat', 'online', '']:
			return 'avail'
190
		elif show == 'xa':
191
			return 'away'
192
		return show
193 194

	def create_service(self):
195 196 197 198 199 200
		try:
			if not self.entrygroup:
				# create an EntryGroup for publishing
				self.entrygroup = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP)
				self.entrygroup.connect_to_signal('StateChanged', self.entrygroup_state_changed_callback)
			
201 202 203 204 205 206 207 208 209 210 211
			txt = {}
			
			#remove empty keys
			for key,val in self.txt.iteritems():
				if val:
					txt[key] = val
			
			txt['port.p2pj'] = self.port
			txt['version'] = 1
			txt['txtvers'] = 1

212 213
			# replace gajim's show messages with compatible ones
			if self.txt.has_key('status'):
214 215 216 217 218 219
				txt['status'] = self.replace_show(self.txt['status'])
			else:
				txt['status'] = 'avail'


			self.txt = txt
220

sb's avatar
sb committed
221
			gajim.log.debug('Publishing service %s of type %s' % (self.name, self.stype))
222
			self.entrygroup.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), self.name, self.stype, '', '', self.port, avahi.dict_to_txt_array(self.txt), reply_handler=self.service_added_callback, error_handler=self.service_add_fail_callback)
223 224
			self.entrygroup.Commit(reply_handler=self.service_committed_callback, 
				error_handler=self.entrygroup_commit_error_CB)
225

226 227 228 229 230 231
			return True
		
		except dbus.dbus_bindings.DBusException, e:
			gajim.log.debug(str(e))
			return False
			
sb's avatar
sb committed
232
	def announce(self):
233
		if not self.connected:
234
			return False
235

236 237 238 239 240 241
		state = self.server.GetState()
		if state == avahi.SERVER_RUNNING:
			self.create_service()
			self.announced = True
			return True

242
	def remove_announce(self):
243 244
		if self.announced == False:
			return False
245 246 247 248 249
		try:
			if self.entrygroup.GetState() != avahi.ENTRY_GROUP_FAILURE:
				self.entrygroup.Reset()
				self.entrygroup.Free()
				self.entrygroup = None
250
				self.announced = False
251 252 253 254
				return True
			else:
				return False
		except dbus.dbus_bindings.DBusException, e:
sb's avatar
sb committed
255
			gajim.log.debug("Can't remove service. That should not happen")
256 257 258

	def browse_domain(self, interface, protocol, domain):
		self.new_service_type(interface, protocol, self.stype, domain, '')
259

260
	# connect to dbus
261 262 263
	def connect_dbus(self):
		if self.server:
			return True
264
		try:
265
			self.bus = dbus.SystemBus()
266
			# is there any way to check if a dbus name exists?
267 268 269
			# that might make the Introspect Error go away...
			self.server = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, \
			avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
270 271 272
			self.server.connect_to_signal('StateChanged', self.server_state_changed_callback)
		except dbus.dbus_bindings.DBusException, e:
			# Avahi service is not present
273
			self.server = None
274
			gajim.log.debug(str(e))
275
			return False
276 277
		else:
			return True
278

279 280 281 282
	def connect(self):
		self.name = self.username + '@' + self.host # service name
		if not self.connect_dbus():
			return False
283 284
		self.connected = True
		
285 286 287 288 289 290
		# start browsing
		if self.domain is None:
			# Explicitly browse .local
			self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "local")

			# Browse for other browsable domains
291
			self.domain_browser = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, \
292 293 294
					self.server.DomainBrowserNew(avahi.IF_UNSPEC, \
					avahi.PROTO_UNSPEC, '', avahi.DOMAIN_BROWSER_BROWSE,\
					dbus.UInt32(0))), avahi.DBUS_INTERFACE_DOMAIN_BROWSER)
295 296
			self.domain_browser.connect_to_signal('ItemNew', self.new_domain_callback)
			self.domain_browser.connect_to_signal('Failure', self.error_callback)
297 298
		else:
			self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, domain)
299
		
300 301
		return True

sb's avatar
sb committed
302
	def disconnect(self):
303 304
		if self.connected:
			self.connected = False
305 306 307 308 309 310
			if self.service_browser:
				self.service_browser.Free()
				self.service_browser = None
			if self.domain_browser:
				self.domain_browser.Free()
				self.domain_browser = None
311
			self.remove_announce()
312
		self.server = None
313

314
	# refresh txt data of all contacts manually (no callback available)
315
	def resolve_all(self):
sb's avatar
sb committed
316
		for val in self.contacts.values():
317 318
			self.server.ResolveService(int(val[C_INTERFACE]), int(val[C_PROTOCOL]), val[C_BARE_NAME], \
				self.stype, val[C_DOMAIN], avahi.PROTO_UNSPEC, dbus.UInt32(0),\
319
				reply_handler=self.service_resolved_all_callback, error_handler=self.error_callback)
320

321 322 323
	def get_contacts(self):
		return self.contacts

324
	def get_contact(self, jid):
325
		return self.contacts[jid]
326
		
sb's avatar
sb committed
327
	def update_txt(self, txt):
328
		# update only new non-empty keys
sb's avatar
sb committed
329
		for key in txt.keys():
330 331
			if txt[key]:
				self.txt[key]=txt[key]
332

333 334
		if txt.has_key('status'):
			self.txt['status'] = self.replace_show(txt['status'])
335

336
		txt = avahi.dict_to_txt_array(self.txt)
337
		if self.connected and self.entrygroup:
338
			self.entrygroup.UpdateServiceTxt(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), self.name, self.stype,'', txt, reply_handler=self.service_updated_callback, error_handler=self.error_callback)
339 340 341
			return True
		else:
			return False
342

343

sb's avatar
sb committed
344 345 346
# END Zeroconf

'''
347
# how to use
sb's avatar
sb committed
348
		
sb's avatar
sb committed
349 350
	zeroconf = Zeroconf()
	zeroconf.connect()				
351 352
	zeroconf.txt['1st'] = 'foo'
	zeroconf.txt['last'] = 'bar'
353
	zeroconf.txt['email'] = foo@bar.org
sb's avatar
sb committed
354 355 356 357
	zeroconf.announce()

	# updating after announcing
	txt = {}
sb's avatar
sb committed
358
	txt['status'] = 'avail'
sb's avatar
sb committed
359 360
	txt['msg'] = 'Here I am'
	zeroconf.update_txt(txt)
sb's avatar
sb committed
361
'''