blob: ed5ddce9727eb7fcfd747d629384a72c65cd2b3b [file] [log] [blame]
Jean-Paul Calderonecbb68cc2015-04-11 12:41:30 -04001import sys
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
Jean-Paul Calderonecbb68cc2015-04-11 12:41:30 -040050def path_string(s):
51 """
52 Convert a Python string to a :py:class:`bytes` string identifying the same
53 path and which can be passed into an OpenSSL API accepting a filename.
54
55 :param s: An instance of :py:class:`bytes` or :py:class:`unicode`.
56
57 :return: An instance of :py:class:`bytes`.
58 """
59 if isinstance(s, binary_type):
60 return s
61 elif isinstance(s, text_type):
62 return s.encode(sys.getfilesystemencoding())
63 else:
64 raise TypeError("Path must be represented as bytes or unicode string")
65
66
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050067if PY3:
68 def byte_string(s):
69 return s.encode("charmap")
70else:
71 def byte_string(s):
72 return s