Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/OpenSSL/_util.py: 52%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import os
4import sys
5import warnings
6from typing import Any, Callable, NoReturn, Union
8from cryptography.hazmat.bindings.openssl.binding import Binding
10StrOrBytesPath = Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]
12binding = Binding()
13ffi = binding.ffi
14lib: Any = binding.lib
17# This is a special CFFI allocator that does not bother to zero its memory
18# after allocation. This has vastly better performance on large allocations and
19# so should be used whenever we don't need the memory zeroed out.
20no_zero_allocator = ffi.new_allocator(should_clear_after_alloc=False)
23def text(charp: Any) -> str:
24 """
25 Get a native string type representing of the given CFFI ``char*`` object.
27 :param charp: A C-style string represented using CFFI.
29 :return: :class:`str`
30 """
31 if not charp:
32 return ""
33 return ffi.string(charp).decode("utf-8")
36def exception_from_error_queue(exception_type: type[Exception]) -> NoReturn:
37 """
38 Convert an OpenSSL library failure into a Python exception.
40 When a call to the native OpenSSL library fails, this is usually signalled
41 by the return value, and an error code is stored in an error queue
42 associated with the current thread. The err library provides functions to
43 obtain these error codes and textual error messages.
44 """
45 errors = []
47 while True:
48 error = lib.ERR_get_error()
49 if error == 0:
50 break
51 errors.append(
52 (
53 text(lib.ERR_lib_error_string(error)),
54 text(lib.ERR_func_error_string(error)),
55 text(lib.ERR_reason_error_string(error)),
56 )
57 )
59 raise exception_type(errors)
62def make_assert(error: type[Exception]) -> Callable[[bool], Any]:
63 """
64 Create an assert function that uses :func:`exception_from_error_queue` to
65 raise an exception wrapped by *error*.
66 """
68 def openssl_assert(ok: bool) -> None:
69 """
70 If *ok* is not True, retrieve the error from OpenSSL and raise it.
71 """
72 if ok is not True:
73 exception_from_error_queue(error)
75 return openssl_assert
78def path_bytes(s: StrOrBytesPath) -> bytes:
79 """
80 Convert a Python path to a :py:class:`bytes` for the path which can be
81 passed into an OpenSSL API accepting a filename.
83 :param s: A path (valid for os.fspath).
85 :return: An instance of :py:class:`bytes`.
86 """
87 b = os.fspath(s)
89 if isinstance(b, str):
90 return b.encode(sys.getfilesystemencoding())
91 else:
92 return b
95def byte_string(s: str) -> bytes:
96 return s.encode("charmap")
99# A marker object to observe whether some optional arguments are passed any
100# value or not.
101UNSPECIFIED = object()
103_TEXT_WARNING = "str for {0} is no longer accepted, use bytes"
106def text_to_bytes_and_warn(label: str, obj: Any) -> Any:
107 """
108 If ``obj`` is text, emit a warning that it should be bytes instead and try
109 to convert it to bytes automatically.
111 :param str label: The name of the parameter from which ``obj`` was taken
112 (so a developer can easily find the source of the problem and correct
113 it).
115 :return: If ``obj`` is the text string type, a ``bytes`` object giving the
116 UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is
117 returned.
118 """
119 if isinstance(obj, str):
120 warnings.warn(
121 _TEXT_WARNING.format(label),
122 category=DeprecationWarning,
123 stacklevel=3,
124 )
125 return obj.encode("utf-8")
126 return obj