]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/exception.py
Begin to implement python3 support. Now tests for oid, bio, cipher, digest, mac and...
[oss/ctypescrypto.git] / ctypescrypto / exception.py
1 """
2 Exception which extracts libcrypto error information
3 """
4 from ctypes import c_ulong, c_char_p, create_string_buffer
5 from ctypescrypto import libcrypto, strings_loaded, pyver
6
7 __all__ = ['LibCryptoError', 'clear_err_stack']
8
9 if pyver == 2:
10     def _get_error_str(err_code,buf):
11         return libcrypto.ERR_error_string(err_code,buf)
12 else:
13     def _get_error_str(err_code,buf):
14         return libcrypto.ERR_error_string(err_code,buf).decode('utf-8')
15 class LibCryptoError(Exception):
16     """
17     Exception for libcrypto errors. Adds all the info, which can be
18     extracted from internal (per-thread) libcrypto error stack to the message,
19     passed to the constructor.
20     """
21     def __init__(self, msg):
22         global strings_loaded
23         if not strings_loaded:
24             libcrypto.ERR_load_crypto_strings()
25             strings_loaded = True
26         err_code = libcrypto.ERR_get_error()
27         mesg = msg
28         buf = create_string_buffer(128)
29         while err_code != 0:
30             mesg += "\n\t" + _get_error_str(err_code, buf)
31             err_code = libcrypto.ERR_get_error()
32         super(LibCryptoError, self).__init__(mesg)
33
34 def clear_err_stack():
35     """
36     Clears internal libcrypto err stack. Call it if you've checked
37     return code and processed exceptional situation, so subsequent
38     raising of the LibCryptoError wouldn't list already handled errors
39     """
40     libcrypto.ERR_clear_error()
41
42 libcrypto.ERR_get_error.restype = c_ulong
43 libcrypto.ERR_error_string.restype = c_char_p
44 libcrypto.ERR_error_string.argtypes = (c_ulong, c_char_p)