blob: 8e304879bca7cfb0d666b5cea930a16b43151378 [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):
Alex Gaynora268f6c2014-08-12 09:26:18 -070010 if not charp:
11 return ""
Jean-Paul Calderonede075462014-01-18 10:34:12 -050012 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