Debian Codegraph @

src/OpenSSL/_util.py

raw
1 from __future__ import annotations
2
3 import os
4 import sys
5 import warnings
6 from typing import Any, Callable, NoReturn, Union
7
8 from cryptography.hazmat.bindings.openssl.binding import Binding
9
10 StrOrBytesPath = Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]
11
12 binding = Binding()
13 ffi = binding.ffi
14 lib: Any = binding.lib
15
16
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.
20 no_zero_allocator = ffi.new_allocator(should_clear_after_alloc=False)
21
22
23 def text(charp: Any) -> str:
24 """
25 Get a native string type representing of the given CFFI ``char*`` object.
26
27 :param charp: A C-style string represented using CFFI.
28
29 :return: :class:`str`
30 """
31 if not charp:
32 return ""
33 return ffi.string(charp).decode("utf-8")
34
35
36 def exception_from_error_queue(exception_type: type[Exception]) -> NoReturn:
37 """
38 Convert an OpenSSL library failure into a Python exception.
39
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 = []
46
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 )
58
59 raise exception_type(errors)
60
61
62 def 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 """
67
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)
74
75 return openssl_assert
76
77
78 def 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.
82
83 :param s: A path (valid for os.fspath).
84
85 :return: An instance of :py:class:`bytes`.
86 """
87 b = os.fspath(s)
88
89 if isinstance(b, str):
90 return b.encode(sys.getfilesystemencoding())
91 else:
92 return b
93
94
95 def byte_string(s: str) -> bytes:
96 return s.encode("charmap")
97
98
99 # A marker object to observe whether some optional arguments are passed any
100 # value or not.
101 UNSPECIFIED = object()
102
103 _TEXT_WARNING = "str for {0} is no longer accepted, use bytes"
104
105
106 def 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.
110
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).
114
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