Jean-Paul Calderone | 4f0467a | 2014-01-11 11:58:41 -0500 | [diff] [blame] | 1 | from six import PY3, binary_type, text_type |
| 2 | |
Jean-Paul Calderone | e36b31a | 2014-01-08 16:55:06 -0500 | [diff] [blame] | 3 | from cryptography.hazmat.bindings.openssl.binding import Binding |
| 4 | binding = Binding() |
| 5 | ffi = binding.ffi |
| 6 | lib = binding.lib |
Jean-Paul Calderone | c86bb7d | 2013-12-29 10:25:59 -0500 | [diff] [blame] | 7 | |
| 8 | def exception_from_error_queue(exceptionType): |
Jean-Paul Calderone | de07546 | 2014-01-18 10:34:12 -0500 | [diff] [blame] | 9 | def text(charp): |
| 10 | return native(ffi.string(charp)) |
| 11 | |
Jean-Paul Calderone | c86bb7d | 2013-12-29 10:25:59 -0500 | [diff] [blame] | 12 | errors = [] |
| 13 | while True: |
| 14 | error = lib.ERR_get_error() |
| 15 | if error == 0: |
| 16 | break |
| 17 | errors.append(( |
Jean-Paul Calderone | de07546 | 2014-01-18 10:34:12 -0500 | [diff] [blame] | 18 | 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 Calderone | c86bb7d | 2013-12-29 10:25:59 -0500 | [diff] [blame] | 21 | |
| 22 | raise exceptionType(errors) |
Jean-Paul Calderone | 4f0467a | 2014-01-11 11:58:41 -0500 | [diff] [blame] | 23 | |
| 24 | |
| 25 | |
| 26 | def native(s): |
| 27 | """ |
| 28 | Convert :py:class:`bytes` or :py:class:`unicode` to the native |
Jean-Paul Calderone | aca50f4 | 2014-01-11 14:43:37 -0500 | [diff] [blame] | 29 | :py:class:`str` type, using UTF-8 encoding if conversion is necessary. |
Jean-Paul Calderone | 4f0467a | 2014-01-11 11:58:41 -0500 | [diff] [blame] | 30 | |
| 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 | |
| 48 | if PY3: |
| 49 | def byte_string(s): |
| 50 | return s.encode("charmap") |
| 51 | else: |
| 52 | def byte_string(s): |
| 53 | return s |