blob: cf136663ef4faa5b3f3537694f840ac046089d5f [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
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07008
9
10def text(charp):
11 return native(ffi.string(charp))
12
13
14
15def exception_from_error_queue(exception_type):
16 """
17 Convert an OpenSSL library failure into a Python exception.
18
19 When a call to the native OpenSSL library fails, this is usually signalled
20 by the return value, and an error code is stored in an error queue
21 associated with the current thread. The err library provides functions to
22 obtain these error codes and textual error messages.
23 """
Jean-Paul Calderonede075462014-01-18 10:34:12 -050024
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050025 errors = []
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070026
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050027 while True:
28 error = lib.ERR_get_error()
29 if error == 0:
30 break
31 errors.append((
Jean-Paul Calderonede075462014-01-18 10:34:12 -050032 text(lib.ERR_lib_error_string(error)),
33 text(lib.ERR_func_error_string(error)),
34 text(lib.ERR_reason_error_string(error))))
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050035
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070036 raise exception_type(errors)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050037
38
39
40def native(s):
41 """
42 Convert :py:class:`bytes` or :py:class:`unicode` to the native
Jean-Paul Calderoneaca50f42014-01-11 14:43:37 -050043 :py:class:`str` type, using UTF-8 encoding if conversion is necessary.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050044
45 :raise UnicodeError: The input string is not UTF-8 decodeable.
46
47 :raise TypeError: The input is neither :py:class:`bytes` nor
48 :py:class:`unicode`.
49 """
50 if not isinstance(s, (binary_type, text_type)):
51 raise TypeError("%r is neither bytes nor unicode" % s)
52 if PY3:
53 if isinstance(s, binary_type):
54 return s.decode("utf-8")
55 else:
56 if isinstance(s, text_type):
57 return s.encode("utf-8")
58 return s
59
60
61
62if PY3:
63 def byte_string(s):
64 return s.encode("charmap")
65else:
66 def byte_string(s):
67 return s