_util.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import os
  2. import sys
  3. import warnings
  4. from cryptography.hazmat.bindings.openssl.binding import Binding
  5. binding = Binding()
  6. ffi = binding.ffi
  7. lib = binding.lib
  8. # This is a special CFFI allocator that does not bother to zero its memory
  9. # after allocation. This has vastly better performance on large allocations and
  10. # so should be used whenever we don't need the memory zeroed out.
  11. no_zero_allocator = ffi.new_allocator(should_clear_after_alloc=False)
  12. def text(charp):
  13. """
  14. Get a native string type representing of the given CFFI ``char*`` object.
  15. :param charp: A C-style string represented using CFFI.
  16. :return: :class:`str`
  17. """
  18. if not charp:
  19. return ""
  20. return ffi.string(charp).decode("utf-8")
  21. def exception_from_error_queue(exception_type):
  22. """
  23. Convert an OpenSSL library failure into a Python exception.
  24. When a call to the native OpenSSL library fails, this is usually signalled
  25. by the return value, and an error code is stored in an error queue
  26. associated with the current thread. The err library provides functions to
  27. obtain these error codes and textual error messages.
  28. """
  29. errors = []
  30. while True:
  31. error = lib.ERR_get_error()
  32. if error == 0:
  33. break
  34. errors.append(
  35. (
  36. text(lib.ERR_lib_error_string(error)),
  37. text(lib.ERR_func_error_string(error)),
  38. text(lib.ERR_reason_error_string(error)),
  39. )
  40. )
  41. raise exception_type(errors)
  42. def make_assert(error):
  43. """
  44. Create an assert function that uses :func:`exception_from_error_queue` to
  45. raise an exception wrapped by *error*.
  46. """
  47. def openssl_assert(ok):
  48. """
  49. If *ok* is not True, retrieve the error from OpenSSL and raise it.
  50. """
  51. if ok is not True:
  52. exception_from_error_queue(error)
  53. return openssl_assert
  54. def path_bytes(s):
  55. """
  56. Convert a Python path to a :py:class:`bytes` for the path which can be
  57. passed into an OpenSSL API accepting a filename.
  58. :param s: A path (valid for os.fspath).
  59. :return: An instance of :py:class:`bytes`.
  60. """
  61. b = os.fspath(s)
  62. if isinstance(b, str):
  63. return b.encode(sys.getfilesystemencoding())
  64. else:
  65. return b
  66. def byte_string(s):
  67. return s.encode("charmap")
  68. # A marker object to observe whether some optional arguments are passed any
  69. # value or not.
  70. UNSPECIFIED = object()
  71. _TEXT_WARNING = "str for {0} is no longer accepted, use bytes"
  72. def text_to_bytes_and_warn(label, obj):
  73. """
  74. If ``obj`` is text, emit a warning that it should be bytes instead and try
  75. to convert it to bytes automatically.
  76. :param str label: The name of the parameter from which ``obj`` was taken
  77. (so a developer can easily find the source of the problem and correct
  78. it).
  79. :return: If ``obj`` is the text string type, a ``bytes`` object giving the
  80. UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is
  81. returned.
  82. """
  83. if isinstance(obj, str):
  84. warnings.warn(
  85. _TEXT_WARNING.format(label),
  86. category=DeprecationWarning,
  87. stacklevel=3,
  88. )
  89. return obj.encode("utf-8")
  90. return obj