11
11
# "AvahiService" class, and some lines in "main".
13
13
# Everything else is
14
# Copyright © 2008-2012 Teddy Hogeborn
15
# Copyright © 2008-2012 Björn Påhlsson
14
# Copyright © 2008-2011 Teddy Hogeborn
15
# Copyright © 2008-2011 Björn Påhlsson
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
177
175
def encrypt(self, data, password):
178
176
self.gnupg.passphrase = self.password_encode(password)
179
with open(os.devnull, "w") as devnull:
177
with open(os.devnull) as devnull:
181
179
proc = self.gnupg.run(['--symmetric'],
182
180
create_fhs=['stdin', 'stdout'],
194
192
def decrypt(self, data, password):
195
193
self.gnupg.passphrase = self.password_encode(password)
196
with open(os.devnull, "w") as devnull:
194
with open(os.devnull) as devnull:
198
196
proc = self.gnupg.run(['--decrypt'],
199
197
create_fhs=['stdin', 'stdout'],
200
198
attach_fhs={'stderr': devnull})
201
with contextlib.closing(proc.handles['stdin']) as f:
199
with contextlib.closing(proc.handles['stdin'] ) as f:
203
201
with contextlib.closing(proc.handles['stdout']) as f:
204
202
decrypted_plaintext = f.read()
322
320
elif state == avahi.ENTRY_GROUP_FAILURE:
323
321
logger.critical("Avahi: Error in group state changed %s",
325
raise AvahiGroupError("State changed: {0!s}"
323
raise AvahiGroupError("State changed: %s"
327
325
def cleanup(self):
328
326
"""Derived from the Avahi example code"""
329
327
if self.group is not None:
375
373
"""Add the new name to the syslog messages"""
376
374
ret = AvahiService.rename(self)
377
375
syslogger.setFormatter(logging.Formatter
378
('Mandos ({0}) [%(process)d]:'
379
' %(levelname)s: %(message)s'
376
('Mandos (%s) [%%(process)d]:'
377
' %%(levelname)s: %%(message)s'
383
381
def timedelta_to_milliseconds(td):
416
414
last_checked_ok: datetime.datetime(); (UTC) or None
417
415
last_checker_status: integer between 0 and 255 reflecting exit
418
416
status of last checker. -1 reflects crashed
419
checker, -2 means no checker completed yet.
420
418
last_enabled: datetime.datetime(); (UTC) or None
421
419
name: string; from the config file, used in log messages and
422
420
D-Bus identifiers
423
421
secret: bytestring; sent verbatim (over TLS) to client
424
422
timeout: datetime.timedelta(); How long from last_checked_ok
425
423
until this client is disabled
426
extended_timeout: extra long timeout when secret has been sent
424
extended_timeout: extra long timeout when password has been sent
427
425
runtime_expansions: Allowed attributes for runtime expansion.
428
426
expires: datetime.datetime(); time (UTC) when a client will be
429
427
disabled, or None
463
461
def config_parser(config):
464
"""Construct a new dict of client settings of this form:
462
""" Construct a new dict of client settings of this form:
465
463
{ client_name: {setting_name: value, ...}, ...}
466
with exceptions for any special settings as defined above.
467
NOTE: Must be a pure function. Must return the same result
468
value given the same arguments.
464
with exceptions for any special settings as defined above"""
471
466
for client_name in config.sections():
472
467
section = dict(config.items(client_name))
476
471
# Reformat values from string types to Python types
477
472
client["approved_by_default"] = config.getboolean(
478
473
client_name, "approved_by_default")
479
client["enabled"] = config.getboolean(client_name,
474
client["enabled"] = config.getboolean(client_name, "enabled")
482
476
client["fingerprint"] = (section["fingerprint"].upper()
483
477
.replace(" ", ""))
489
483
"rb") as secfile:
490
484
client["secret"] = secfile.read()
492
raise TypeError("No secret or secfile for section {0}"
486
raise TypeError("No secret or secfile for section %s"
494
488
client["timeout"] = string_to_delta(section["timeout"])
495
489
client["extended_timeout"] = string_to_delta(
496
490
section["extended_timeout"])
502
496
client["checker_command"] = section["checker"]
503
497
client["last_approval_request"] = None
504
498
client["last_checked_ok"] = None
505
client["last_checker_status"] = -2
499
client["last_checker_status"] = None
500
if client["enabled"]:
501
client["last_enabled"] = datetime.datetime.utcnow()
502
client["expires"] = (datetime.datetime.utcnow()
505
client["last_enabled"] = None
506
client["expires"] = None
516
517
for setting, value in settings.iteritems():
517
518
setattr(self, setting, value)
520
if not hasattr(self, "last_enabled"):
521
self.last_enabled = datetime.datetime.utcnow()
522
if not hasattr(self, "expires"):
523
self.expires = (datetime.datetime.utcnow()
526
self.last_enabled = None
529
520
logger.debug("Creating client %r", self.name)
530
521
# Uppercase and remove spaces from fingerprint for later
531
522
# comparison purposes with return value from the fingerprint()
533
524
logger.debug(" Fingerprint: %s", self.fingerprint)
534
self.created = settings.get("created",
535
datetime.datetime.utcnow())
525
self.created = settings.get("created", datetime.datetime.utcnow())
537
527
# attributes specific for this server instance
538
528
self.checker = None
627
617
logger.warning("Checker for %(name)s crashed?",
630
def checked_ok(self):
631
"""Assert that the client has been seen, alive and well."""
632
self.last_checked_ok = datetime.datetime.utcnow()
633
self.last_checker_status = 0
636
def bump_timeout(self, timeout=None):
637
"""Bump up the timeout for this client."""
620
def checked_ok(self, timeout=None):
621
"""Bump up the timeout for this client.
623
This should only be called when the client has been seen,
638
626
if timeout is None:
639
627
timeout = self.timeout
628
self.last_checked_ok = datetime.datetime.utcnow()
640
629
if self.disable_initiator_tag is not None:
641
630
gobject.source_remove(self.disable_initiator_tag)
642
631
if getattr(self, "enabled", False):
694
683
command = self.checker_command % escaped_attrs
695
684
except TypeError as error:
696
logger.error('Could not format string "%s"',
697
self.checker_command, exc_info=error)
685
logger.error('Could not format string "%s":'
686
' %s', self.checker_command, error)
698
687
return True # Try again later
699
688
self.current_checker_command = command
718
707
gobject.source_remove(self.checker_callback_tag)
719
708
self.checker_callback(pid, status, command)
720
709
except OSError as error:
721
logger.error("Failed to start subprocess",
710
logger.error("Failed to start subprocess: %s",
723
712
# Re-run this periodically if run by gobject.timeout_add
733
722
logger.debug("Stopping checker for %(name)s", vars(self))
735
self.checker.terminate()
724
os.kill(self.checker.pid, signal.SIGTERM)
737
726
#if self.checker.poll() is None:
738
# self.checker.kill()
727
# os.kill(self.checker.pid, signal.SIGKILL)
739
728
except OSError as error:
740
729
if error.errno != errno.ESRCH: # No such process
758
747
# "Set" method, so we fail early here:
759
748
if byte_arrays and signature != "ay":
760
749
raise ValueError("Byte arrays not supported for non-'ay'"
761
" signature {0!r}".format(signature))
750
" signature %r" % signature)
762
751
def decorator(func):
763
752
func._dbus_is_property = True
764
753
func._dbus_interface = dbus_interface
775
def dbus_interface_annotations(dbus_interface):
776
"""Decorator for marking functions returning interface annotations.
780
@dbus_interface_annotations("org.example.Interface")
781
def _foo(self): # Function name does not matter
782
return {"org.freedesktop.DBus.Deprecated": "true",
783
"org.freedesktop.DBus.Property.EmitsChangedSignal":
787
func._dbus_is_interface = True
788
func._dbus_interface = dbus_interface
789
func._dbus_name = dbus_interface
794
def dbus_annotations(annotations):
795
"""Decorator to annotate D-Bus methods, signals or properties
798
@dbus_service_property("org.example.Interface", signature="b",
800
@dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
801
"org.freedesktop.DBus.Property."
802
"EmitsChangedSignal": "false"})
803
def Property_dbus_property(self):
804
return dbus.Boolean(False)
807
func._dbus_annotations = annotations
812
764
class DBusPropertyException(dbus.exceptions.DBusException):
813
765
"""A base class for D-Bus property-related exceptions
840
def _is_dbus_thing(thing):
841
"""Returns a function testing if an attribute is a D-Bus thing
843
If called like _is_dbus_thing("method") it returns a function
844
suitable for use as predicate to inspect.getmembers().
846
return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
792
def _is_dbus_property(obj):
793
return getattr(obj, "_dbus_is_property", False)
849
def _get_all_dbus_things(self, thing):
795
def _get_all_dbus_properties(self):
850
796
"""Returns a generator of (name, attribute) pairs
852
return ((getattr(athing.__get__(self), "_dbus_name",
854
athing.__get__(self))
798
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
855
799
for cls in self.__class__.__mro__
857
inspect.getmembers(cls,
858
self._is_dbus_thing(thing)))
801
inspect.getmembers(cls, self._is_dbus_property))
860
803
def _get_dbus_property(self, interface_name, property_name):
861
804
"""Returns a bound method if one exists which is a D-Bus
864
807
for cls in self.__class__.__mro__:
865
808
for name, value in (inspect.getmembers
867
self._is_dbus_thing("property"))):
809
(cls, self._is_dbus_property)):
868
810
if (value._dbus_name == property_name
869
811
and value._dbus_interface == interface_name):
870
812
return value.__get__(self)
899
841
# signatures other than "ay".
900
842
if prop._dbus_signature != "ay":
902
value = dbus.ByteArray(b''.join(chr(byte)
844
value = dbus.ByteArray(''.join(unichr(byte)
906
848
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
912
854
Note: Will not include properties with access="write".
915
for name, prop in self._get_all_dbus_things("property"):
857
for name, prop in self._get_all_dbus_properties():
916
858
if (interface_name
917
859
and interface_name != prop._dbus_interface):
918
860
# Interface non-empty but did not match
933
875
path_keyword='object_path',
934
876
connection_keyword='connection')
935
877
def Introspect(self, object_path, connection):
936
"""Overloading of standard D-Bus method.
938
Inserts property tags and interface annotation tags.
878
"""Standard D-Bus method, overloaded to insert property tags.
940
880
xmlstring = dbus.service.Object.Introspect(self, object_path,
948
888
e.setAttribute("access", prop._dbus_access)
950
890
for if_tag in document.getElementsByTagName("interface"):
952
891
for tag in (make_tag(document, name, prop)
954
in self._get_all_dbus_things("property")
893
in self._get_all_dbus_properties()
955
894
if prop._dbus_interface
956
895
== if_tag.getAttribute("name")):
957
896
if_tag.appendChild(tag)
958
# Add annotation tags
959
for typ in ("method", "signal", "property"):
960
for tag in if_tag.getElementsByTagName(typ):
962
for name, prop in (self.
963
_get_all_dbus_things(typ)):
964
if (name == tag.getAttribute("name")
965
and prop._dbus_interface
966
== if_tag.getAttribute("name")):
967
annots.update(getattr
971
for name, value in annots.iteritems():
972
ann_tag = document.createElement(
974
ann_tag.setAttribute("name", name)
975
ann_tag.setAttribute("value", value)
976
tag.appendChild(ann_tag)
977
# Add interface annotation tags
978
for annotation, value in dict(
980
*(annotations().iteritems()
981
for name, annotations in
982
self._get_all_dbus_things("interface")
983
if name == if_tag.getAttribute("name")
985
ann_tag = document.createElement("annotation")
986
ann_tag.setAttribute("name", annotation)
987
ann_tag.setAttribute("value", value)
988
if_tag.appendChild(ann_tag)
989
897
# Add the names to the return values for the
990
898
# "org.freedesktop.DBus.Properties" methods
991
899
if (if_tag.getAttribute("name")
1006
914
except (AttributeError, xml.dom.DOMException,
1007
915
xml.parsers.expat.ExpatError) as error:
1008
916
logger.error("Failed to override Introspection method",
1010
918
return xmlstring
1026
934
def __new__(mcs, name, bases, attr):
1027
935
# Go through all the base classes which could have D-Bus
1028
936
# methods, signals, or properties in them
1029
old_interface_names = []
1030
937
for base in (b for b in bases
1031
938
if issubclass(b, dbus.service.Object)):
1032
939
# Go though all attributes of the base class
1042
949
alt_interface = (attribute._dbus_interface
1043
950
.replace("se.recompile.Mandos",
1044
951
"se.bsnet.fukt.Mandos"))
1045
if alt_interface != attribute._dbus_interface:
1046
old_interface_names.append(alt_interface)
1047
952
# Is this a D-Bus signal?
1048
953
if getattr(attribute, "_dbus_is_signal", False):
1049
954
# Extract the original non-method function by
1064
969
nonmethod_func.func_name,
1065
970
nonmethod_func.func_defaults,
1066
971
nonmethod_func.func_closure)))
1067
# Copy annotations, if any
1069
new_function._dbus_annotations = (
1070
dict(attribute._dbus_annotations))
1071
except AttributeError:
1073
972
# Define a creator of a function to call both the
1074
973
# old and new functions, so both the old and new
1075
974
# signals gets sent when the function is called
1103
1002
attribute.func_name,
1104
1003
attribute.func_defaults,
1105
1004
attribute.func_closure)))
1106
# Copy annotations, if any
1108
attr[attrname]._dbus_annotations = (
1109
dict(attribute._dbus_annotations))
1110
except AttributeError:
1112
1005
# Is this a D-Bus property?
1113
1006
elif getattr(attribute, "_dbus_is_property", False):
1114
1007
# Create a new, but exactly alike, function
1128
1021
attribute.func_name,
1129
1022
attribute.func_defaults,
1130
1023
attribute.func_closure)))
1131
# Copy annotations, if any
1133
attr[attrname]._dbus_annotations = (
1134
dict(attribute._dbus_annotations))
1135
except AttributeError:
1137
# Is this a D-Bus interface?
1138
elif getattr(attribute, "_dbus_is_interface", False):
1139
# Create a new, but exactly alike, function
1140
# object. Decorate it to be a new D-Bus interface
1141
# with the alternate D-Bus interface name. Add it
1143
attr[attrname] = (dbus_interface_annotations
1146
(attribute.func_code,
1147
attribute.func_globals,
1148
attribute.func_name,
1149
attribute.func_defaults,
1150
attribute.func_closure)))
1151
# Deprecate all old interfaces
1152
basename="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1153
for old_interface_name in old_interface_names:
1154
@dbus_interface_annotations(old_interface_name)
1156
return { "org.freedesktop.DBus.Deprecated": "true" }
1157
# Find an unused name
1158
for aname in (basename.format(i) for i in
1160
if aname not in attr:
1163
1024
return type.__new__(mcs, name, bases, attr)
1179
1040
def __init__(self, bus = None, *args, **kwargs):
1181
1042
Client.__init__(self, *args, **kwargs)
1043
self._approvals_pending = 0
1045
self._approvals_pending = 0
1182
1046
# Only now, when this client is initialized, can it show up on
1184
1048
client_object_name = unicode(self.name).translate(
1230
1094
checker is not None)
1231
1095
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1232
1096
"LastCheckedOK")
1233
last_checker_status = notifychangeproperty(dbus.Int16,
1234
"LastCheckerStatus")
1235
1097
last_approval_request = notifychangeproperty(
1236
1098
datetime_to_dbus, "LastApprovalRequest")
1237
1099
approved_by_default = notifychangeproperty(dbus.Boolean,
1315
1177
## D-Bus methods, signals & properties
1316
1178
_interface = "se.recompile.Mandos.Client"
1320
@dbus_interface_annotations(_interface)
1322
return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1327
1182
# CheckerCompleted - signal
1364
1219
return self.need_approval()
1221
# NeRwequest - signal
1222
@dbus.service.signal(_interface, signature="s")
1223
def NewRequest(self, ip):
1225
Is sent after a client request a password.
1368
1231
# Approve - method
1479
1342
return datetime_to_dbus(self.last_checked_ok)
1481
# LastCheckerStatus - property
1482
@dbus_service_property(_interface, signature="n",
1484
def LastCheckerStatus_dbus_property(self):
1485
return dbus.Int16(self.last_checker_status)
1487
1344
# Expires - property
1488
1345
@dbus_service_property(_interface, signature="s", access="read")
1489
1346
def Expires_dbus_property(self):
1501
1358
if value is None: # get
1502
1359
return dbus.UInt64(self.timeout_milliseconds())
1503
1360
self.timeout = datetime.timedelta(0, 0, 0, value)
1361
if getattr(self, "disable_initiator_tag", None) is None:
1504
1363
# Reschedule timeout
1506
now = datetime.datetime.utcnow()
1507
time_to_die = timedelta_to_milliseconds(
1508
(self.last_checked_ok + self.timeout) - now)
1509
if time_to_die <= 0:
1510
# The timeout has passed
1513
self.expires = (now +
1514
datetime.timedelta(milliseconds =
1516
if (getattr(self, "disable_initiator_tag", None)
1519
gobject.source_remove(self.disable_initiator_tag)
1520
self.disable_initiator_tag = (gobject.timeout_add
1364
gobject.source_remove(self.disable_initiator_tag)
1365
self.disable_initiator_tag = None
1367
time_to_die = timedelta_to_milliseconds((self
1372
if time_to_die <= 0:
1373
# The timeout has passed
1376
self.expires = (datetime.datetime.utcnow()
1377
+ datetime.timedelta(milliseconds =
1379
self.disable_initiator_tag = (gobject.timeout_add
1380
(time_to_die, self.disable))
1524
1382
# ExtendedTimeout - property
1525
1383
@dbus_service_property(_interface, signature="t",
1751
1613
logger.info("Sending secret to %s", client.name)
1752
1614
# bump the timeout using extended_timeout
1753
client.bump_timeout(client.extended_timeout)
1615
client.checked_ok(client.extended_timeout)
1754
1616
if self.server.use_dbus:
1755
1617
# Emit D-Bus signal
1756
1618
client.GotSecret()
2079
1941
elif suffix == "w":
2080
1942
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2082
raise ValueError("Unknown suffix {0!r}"
1944
raise ValueError("Unknown suffix %r" % suffix)
2084
1945
except (ValueError, IndexError) as e:
2085
1946
raise ValueError(*(e.args))
2086
1947
timevalue += delta
2101
1962
if not noclose:
2102
1963
# Close all standard open file descriptors
2103
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
1964
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2104
1965
if not stat.S_ISCHR(os.fstat(null).st_mode):
2105
1966
raise OSError(errno.ENODEV,
2106
"{0} not a character device"
2107
.format(os.devnull))
1967
"%s not a character device"
2108
1969
os.dup2(null, sys.stdin.fileno())
2109
1970
os.dup2(null, sys.stdout.fileno())
2110
1971
os.dup2(null, sys.stderr.fileno())
2120
1981
parser = argparse.ArgumentParser()
2121
1982
parser.add_argument("-v", "--version", action="version",
2122
version = "%(prog)s {0}".format(version),
1983
version = "%%(prog)s %s" % version,
2123
1984
help="show version number and exit")
2124
1985
parser.add_argument("-i", "--interface", metavar="IF",
2125
1986
help="Bind to interface IF")
2229
2090
if server_settings["servicename"] != "Mandos":
2230
2091
syslogger.setFormatter(logging.Formatter
2231
('Mandos ({0}) [%(process)d]:'
2232
' %(levelname)s: %(message)s'
2233
.format(server_settings
2092
('Mandos (%s) [%%(process)d]:'
2093
' %%(levelname)s: %%(message)s'
2094
% server_settings["servicename"]))
2236
2096
# Parse config file with clients
2237
client_config = configparser.SafeConfigParser(Client
2097
client_config = configparser.SafeConfigParser(Client.client_defaults)
2239
2098
client_config.read(os.path.join(server_settings["configdir"],
2240
2099
"clients.conf"))
2258
2117
except IOError:
2259
2118
logger.error("Could not open file %r", pidfilename)
2261
for name in ("_mandos", "mandos", "nobody"):
2121
uid = pwd.getpwnam("_mandos").pw_uid
2122
gid = pwd.getpwnam("_mandos").pw_gid
2263
uid = pwd.getpwnam(name).pw_uid
2264
gid = pwd.getpwnam(name).pw_gid
2125
uid = pwd.getpwnam("mandos").pw_uid
2126
gid = pwd.getpwnam("mandos").pw_gid
2266
2127
except KeyError:
2129
uid = pwd.getpwnam("nobody").pw_uid
2130
gid = pwd.getpwnam("nobody").pw_gid
2290
2153
.gnutls_global_set_log_function(debug_gnutls))
2292
2155
# Redirect stdin so all checkers get /dev/null
2293
null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2156
null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2294
2157
os.dup2(null, sys.stdin.fileno())
2305
2168
global main_loop
2306
2169
# From the Avahi example code
2307
DBusGMainLoop(set_as_default=True)
2170
DBusGMainLoop(set_as_default=True )
2308
2171
main_loop = gobject.MainLoop()
2309
2172
bus = dbus.SystemBus()
2310
2173
# End of Avahi example code
2379
2242
# Clients who has passed its expire date can still be
2380
2243
# enabled if its last checker was successful. Clients
2381
# whose checker succeeded before we stored its state is
2382
# assumed to have successfully run all checkers during
2244
# whose checker failed before we stored its state is
2245
# assumed to have failed all checkers during downtime.
2384
2246
if client["enabled"]:
2385
2247
if datetime.datetime.utcnow() >= client["expires"]:
2386
2248
if not client["last_checked_ok"]:
2387
2249
logger.warning(
2388
2250
"disabling client {0} - Client never "
2389
"performed a successful checker"
2390
.format(client_name))
2251
"performed a successfull checker"
2252
.format(client["name"]))
2391
2253
client["enabled"] = False
2392
2254
elif client["last_checker_status"] != 0:
2393
2255
logger.warning(
2394
2256
"disabling client {0} - Client "
2395
2257
"last checker failed with error code {1}"
2396
.format(client_name,
2258
.format(client["name"],
2397
2259
client["last_checker_status"]))
2398
2260
client["enabled"] = False
2400
2262
client["expires"] = (datetime.datetime
2402
2264
+ client["timeout"])
2403
logger.debug("Last checker succeeded,"
2404
" keeping {0} enabled"
2405
.format(client_name))
2407
2267
client["secret"] = (
2408
2268
pgp.decrypt(client["encrypted_secret"],
2419
2279
# Add/remove clients based on new changes made to config
2420
for client_name in (set(old_client_settings)
2421
- set(client_settings)):
2280
for client_name in set(old_client_settings) - set(client_settings):
2422
2281
del clients_data[client_name]
2423
for client_name in (set(client_settings)
2424
- set(old_client_settings)):
2282
for client_name in set(client_settings) - set(old_client_settings):
2425
2283
clients_data[client_name] = client_settings[client_name]
2427
# Create all client objects
2285
# Create clients all clients
2428
2286
for client_name, client in clients_data.iteritems():
2429
2287
tcp_server.clients[client_name] = client_class(
2430
2288
name = client_name, settings = client)
2451
2309
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2454
class MandosDBusService(DBusObjectWithProperties):
2312
class MandosDBusService(dbus.service.Object):
2455
2313
"""A D-Bus proxy object"""
2456
2314
def __init__(self):
2457
2315
dbus.service.Object.__init__(self, bus, "/")
2458
2316
_interface = "se.recompile.Mandos"
2460
@dbus_interface_annotations(_interface)
2462
return { "org.freedesktop.DBus.Property"
2463
".EmitsChangedSignal":
2466
2318
@dbus.service.signal(_interface, signature="o")
2467
2319
def ClientAdded(self, objpath):
2601
2453
service.port = tcp_server.socket.getsockname()[1]
2603
2455
logger.info("Now listening on address %r, port %d,"
2604
" flowinfo %d, scope_id %d",
2605
*tcp_server.socket.getsockname())
2456
" flowinfo %d, scope_id %d"
2457
% tcp_server.socket.getsockname())
2607
logger.info("Now listening on address %r, port %d",
2608
*tcp_server.socket.getsockname())
2459
logger.info("Now listening on address %r, port %d"
2460
% tcp_server.socket.getsockname())
2610
2462
#service.interface = tcp_server.socket.getsockname()[3]
2615
2467
service.activate()
2616
2468
except dbus.exceptions.DBusException as error:
2617
logger.critical("D-Bus Exception", exc_info=error)
2469
logger.critical("DBusException: %s", error)
2620
2472
# End of Avahi example code
2627
2479
logger.debug("Starting main loop")
2628
2480
main_loop.run()
2629
2481
except AvahiError as error:
2630
logger.critical("Avahi Error", exc_info=error)
2482
logger.critical("AvahiError: %s", error)
2633
2485
except KeyboardInterrupt: