blob: da8270b371d1c122ca909c1b0b239cb4f8b82be4 [file] [log] [blame]
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04001from warnings import warn
2
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003from six import PY3, binary_type, text_type
4
Jean-Paul Calderonee36b31a2014-01-08 16:55:06 -05005from cryptography.hazmat.bindings.openssl.binding import Binding
6binding = Binding()
7ffi = binding.ffi
8lib = binding.lib
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05009
10def exception_from_error_queue(exceptionType):
Jean-Paul Calderonede075462014-01-18 10:34:12 -050011 def text(charp):
12 return native(ffi.string(charp))
13
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014 errors = []
15 while True:
16 error = lib.ERR_get_error()
17 if error == 0:
18 break
19 errors.append((
Jean-Paul Calderonede075462014-01-18 10:34:12 -050020 text(lib.ERR_lib_error_string(error)),
21 text(lib.ERR_func_error_string(error)),
22 text(lib.ERR_reason_error_string(error))))
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050023
24 raise exceptionType(errors)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050025
26
27
28def native(s):
29 """
30 Convert :py:class:`bytes` or :py:class:`unicode` to the native
Jean-Paul Calderoneaca50f42014-01-11 14:43:37 -050031 :py:class:`str` type, using UTF-8 encoding if conversion is necessary.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050032
33 :raise UnicodeError: The input string is not UTF-8 decodeable.
34
35 :raise TypeError: The input is neither :py:class:`bytes` nor
36 :py:class:`unicode`.
37 """
38 if not isinstance(s, (binary_type, text_type)):
39 raise TypeError("%r is neither bytes nor unicode" % s)
40 if PY3:
41 if isinstance(s, binary_type):
42 return s.decode("utf-8")
43 else:
44 if isinstance(s, text_type):
45 return s.encode("utf-8")
46 return s
47
48
49
50if PY3:
51 def byte_string(s):
52 return s.encode("charmap")
53else:
54 def byte_string(s):
55 return s
Jean-Paul Calderone6462b072015-03-29 07:03:11 -040056
57_TEXT_WARNING = u"{} for {{}} is no longer accepted, use bytes".format(
58 text_type.__name__
59)
60
61def warn_text(label, obj):
62 if isinstance(obj, text_type):
63 warn(
64 _TEXT_WARNING.format(label),
65 category=DeprecationWarning,
66 stacklevel=3
67 )
68 return obj.encode('utf-8')
69 return obj