1 From 169e85dbc13dcaae8a699618883e512614f540b7 Mon Sep 17 00:00:00 2001
2 From: Simon McVittie <smcv@debian.org>
3 Date: Fri, 27 Apr 2018 11:09:07 +0100
4 Subject: [PATCH] avahi-python: Encode unicode strings as UTF-8
6 Content-Type: text/plain; charset=UTF-8
7 Content-Transfer-Encoding: 8bit
9 Previously, we would effectively encode anything representable in
10 Latin-1 as Latin-1, and crash on anything not representable in Latin-1:
13 >>> avahi.string_to_byte_array(u'©')
15 >>> avahi.string_to_byte_array(u'\ufeff')
16 Traceback (most recent call last):
17 File "<stdin>", line 1, in <module>
18 File "/usr/lib/python2.7/dist-packages/avahi/__init__.py", line 94, in string_to_byte_array
19 r.append(dbus.Byte(ord(c)))
20 ValueError: Integer outside range 0-255
22 This is particularly important for Python 3, where the str type
25 The b'' syntax for bytestrings is supported since at least Python 2.7.
27 These functions now accept either Unicode strings (Python 2 unicode,
28 Python 3 str), which are encoded in UTF-8, or bytestrings
29 (Python 2 str, Python 3 bytes) which are taken as-is.
31 Signed-off-by: Simon McVittie <smcv@debian.org>
33 avahi-python/avahi/__init__.py | 24 +++++++++++++++++++++---
34 1 file changed, 21 insertions(+), 3 deletions(-)
36 diff --git a/avahi-python/avahi/__init__.py b/avahi-python/avahi/__init__.py
37 index 7b450293..02305b02 100644
38 --- a/avahi-python/avahi/__init__.py
39 +++ b/avahi-python/avahi/__init__.py
42 # Some definitions matching those in avahi-common/defs.h
48 SERVER_INVALID, SERVER_REGISTERING, SERVER_RUNNING, SERVER_COLLISION, SERVER_FAILURE = range(0, 5)
50 DBUS_INTERFACE_SERVICE_RESOLVER = DBUS_NAME + ".ServiceResolver"
51 DBUS_INTERFACE_RECORD_BROWSER = DBUS_NAME + ".RecordBrowser"
53 +if sys.version_info[0] >= 3:
56 def byte_array_to_string(s):
59 @@ -86,12 +91,19 @@ def txt_array_to_string_array(t):
64 def string_to_byte_array(s):
65 + if isinstance(s, unicode):
66 + s = s.encode('utf-8')
71 - r.append(dbus.Byte(ord(c)))
72 + if isinstance(c, int):
73 + # Python 3: iterating over bytes yields ints
74 + r.append(dbus.Byte(c))
76 + # Python 2: iterating over str yields str
77 + r.append(dbus.Byte(ord(c)))
81 @@ -107,6 +119,12 @@ def dict_to_txt_array(txt_dict):
84 for k,v in txt_dict.items():
85 - l.append(string_to_byte_array("%s=%s" % (k,v)))
86 + if isinstance(k, unicode):
87 + k = k.encode('utf-8')
89 + if isinstance(v, unicode):
90 + v = v.encode('utf-8')
92 + l.append(string_to_byte_array(b"%s=%s" % (k,v)))