]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/exception.py
d2866a020c050f4ddf5d5a105b91c60a529f128e
[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
6
7 __all__ = ['LibCryptoError', 'clear_err_stack']
8
9 class LibCryptoError(Exception):
10     """
11     Exception for libcrypto errors. Adds all the info, which can be
12     extracted from internal (per-thread) libcrypto error stack to the message,
13     passed to the constructor.
14     """
15     def __init__(self, msg):
16         global strings_loaded
17         if not strings_loaded:
18             libcrypto.ERR_load_crypto_strings()
19             strings_loaded = True
20         err_code = libcrypto.ERR_get_error()
21         mesg = msg
22         buf = create_string_buffer(128)
23         while err_code != 0:
24             mesg += "\n\t" + libcrypto.ERR_error_string(err_code, buf)
25             err_code = libcrypto.ERR_get_error()
26         super(LibCryptoError, self).__init__(mesg)
27
28 def clear_err_stack():
29     """
30     Clears internal libcrypto err stack. Call it if you've checked
31     return code and processed exceptional situation, so subsequent
32     raising of the LibCryptoError wouldn't list already handled errors
33     """
34     libcrypto.ERR_clear_error()
35
36 libcrypto.ERR_get_error.restype = c_ulong
37 libcrypto.ERR_error_string.restype = c_char_p
38 libcrypto.ERR_error_string.argtypes = (c_ulong, c_char_p)