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