blob: baeecc6328ada2477807c5d20066675b2c9aeeff [file] [log] [blame]
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001from six import PY3, binary_type, text_type
2
Jean-Paul Calderonee36b31a2014-01-08 16:55:06 -05003from cryptography.hazmat.bindings.openssl.binding import Binding
4binding = Binding()
5ffi = binding.ffi
6lib = binding.lib
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05007
8def exception_from_error_queue(exceptionType):
Jean-Paul Calderonede075462014-01-18 10:34:12 -05009 def text(charp):
10 return native(ffi.string(charp))
11
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012 errors = []
13 while True:
14 error = lib.ERR_get_error()
15 if error == 0:
16 break
17 errors.append((
Jean-Paul Calderonede075462014-01-18 10:34:12 -050018 text(lib.ERR_lib_error_string(error)),
19 text(lib.ERR_func_error_string(error)),
20 text(lib.ERR_reason_error_string(error))))
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050021
22 raise exceptionType(errors)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050023
24
25
26def native(s):
27 """
28 Convert :py:class:`bytes` or :py:class:`unicode` to the native
Jean-Paul Calderoneaca50f42014-01-11 14:43:37 -050029 :py:class:`str` type, using UTF-8 encoding if conversion is necessary.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050030
31 :raise UnicodeError: The input string is not UTF-8 decodeable.
32
33 :raise TypeError: The input is neither :py:class:`bytes` nor
34 :py:class:`unicode`.
35 """
36 if not isinstance(s, (binary_type, text_type)):
37 raise TypeError("%r is neither bytes nor unicode" % s)
38 if PY3:
39 if isinstance(s, binary_type):
40 return s.decode("utf-8")
41 else:
42 if isinstance(s, text_type):
43 return s.encode("utf-8")
44 return s
45
46
47
48if PY3:
49 def byte_string(s):
50 return s.encode("charmap")
51else:
52 def byte_string(s):
53 return s