]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/exception.py
30c138e43aa5ba52651243267abe0cdf974244fa
[oss/ctypescrypto.git] / ctypescrypto / exception.py
1 """
2 Exception which extracts libcrypto error information
3 """
4 from ctypes import *
5 from ctypescrypto import libcrypto
6 strings_loaded=False
7
8 __all__ = ['LibCryptoError','clear_err_stack']
9
10 def _check_null(s):
11         """
12         Handle transparently NULL returned from error reporting functions
13         instead of strings
14         """
15         if s is None:   
16                 return ""
17         return s
18
19 class LibCryptoError(Exception):
20         """
21                 Exception for libcrypto errors. Adds all the info, which can be
22                 extracted from internal (per-thread) libcrypto error stack to the message,
23                 passed to the constructor.
24         """
25         def __init__(self,msg):
26                 global strings_loaded
27                 if not strings_loaded:
28                         libcrypto.ERR_load_crypto_strings()
29                         strings_loaded = True
30                 e=libcrypto.ERR_get_error()
31                 m = msg
32                 while e != 0:
33                         m+="\n\t"+_check_null(libcrypto.ERR_lib_error_string(e))+":"+\
34                           _check_null(libcrypto.ERR_func_error_string(e))+":"+\
35                           _check_null(libcrypto.ERR_reason_error_string(e))
36                         e=libcrypto.ERR_get_error()
37                 self.args=(m,)
38
39 def clear_err_stack():
40         """
41           Clears internal libcrypto err stack. Call it if you've checked
42           return code and processed exceptional situation, so subsequent
43           raising of the LibCryptoError wouldn't list already handled errors
44         """
45         libcrypto.ERR_clear_error()
46
47
48 libcrypto.ERR_lib_error_string.restype=c_char_p
49 libcrypto.ERR_func_error_string.restype=c_char_p
50 libcrypto.ERR_reason_error_string.restype=c_char_p