_raw_api.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. import abc
  31. import sys
  32. from Crypto.Util.py3compat import byte_string
  33. from Crypto.Util._file_system import pycryptodome_filename
  34. #
  35. # List of file suffixes for Python extensions
  36. #
  37. if sys.version_info[0] < 3:
  38. import imp
  39. extension_suffixes = []
  40. for ext, mod, typ in imp.get_suffixes():
  41. if typ == imp.C_EXTENSION:
  42. extension_suffixes.append(ext)
  43. else:
  44. from importlib import machinery
  45. extension_suffixes = machinery.EXTENSION_SUFFIXES
  46. # Which types with buffer interface we support (apart from byte strings)
  47. _buffer_type = (bytearray, memoryview)
  48. class _VoidPointer(object):
  49. @abc.abstractmethod
  50. def get(self):
  51. """Return the memory location we point to"""
  52. return
  53. @abc.abstractmethod
  54. def address_of(self):
  55. """Return a raw pointer to this pointer"""
  56. return
  57. try:
  58. # Starting from v2.18, pycparser (used by cffi for in-line ABI mode)
  59. # stops working correctly when PYOPTIMIZE==2 or the parameter -OO is
  60. # passed. In that case, we fall back to ctypes.
  61. # Note that PyPy ships with an old version of pycparser so we can keep
  62. # using cffi there.
  63. # See https://github.com/Legrandin/pycryptodome/issues/228
  64. if '__pypy__' not in sys.builtin_module_names and sys.flags.optimize == 2:
  65. raise ImportError("CFFI with optimize=2 fails due to pycparser bug.")
  66. from cffi import FFI
  67. ffi = FFI()
  68. null_pointer = ffi.NULL
  69. uint8_t_type = ffi.typeof(ffi.new("const uint8_t*"))
  70. _Array = ffi.new("uint8_t[1]").__class__.__bases__
  71. def load_lib(name, cdecl):
  72. """Load a shared library and return a handle to it.
  73. @name, either an absolute path or the name of a library
  74. in the system search path.
  75. @cdecl, the C function declarations.
  76. """
  77. lib = ffi.dlopen(name)
  78. ffi.cdef(cdecl)
  79. return lib
  80. def c_ulong(x):
  81. """Convert a Python integer to unsigned long"""
  82. return x
  83. c_ulonglong = c_ulong
  84. c_uint = c_ulong
  85. def c_size_t(x):
  86. """Convert a Python integer to size_t"""
  87. return x
  88. def create_string_buffer(init_or_size, size=None):
  89. """Allocate the given amount of bytes (initially set to 0)"""
  90. if isinstance(init_or_size, bytes):
  91. size = max(len(init_or_size) + 1, size)
  92. result = ffi.new("uint8_t[]", size)
  93. result[:] = init_or_size
  94. else:
  95. if size:
  96. raise ValueError("Size must be specified once only")
  97. result = ffi.new("uint8_t[]", init_or_size)
  98. return result
  99. def get_c_string(c_string):
  100. """Convert a C string into a Python byte sequence"""
  101. return ffi.string(c_string)
  102. def get_raw_buffer(buf):
  103. """Convert a C buffer into a Python byte sequence"""
  104. return ffi.buffer(buf)[:]
  105. def c_uint8_ptr(data):
  106. if isinstance(data, _buffer_type):
  107. # This only works for cffi >= 1.7
  108. return ffi.cast(uint8_t_type, ffi.from_buffer(data))
  109. elif byte_string(data) or isinstance(data, _Array):
  110. return data
  111. else:
  112. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  113. class VoidPointer_cffi(_VoidPointer):
  114. """Model a newly allocated pointer to void"""
  115. def __init__(self):
  116. self._pp = ffi.new("void *[1]")
  117. def get(self):
  118. return self._pp[0]
  119. def address_of(self):
  120. return self._pp
  121. def VoidPointer():
  122. return VoidPointer_cffi()
  123. backend = "cffi"
  124. except ImportError:
  125. import ctypes
  126. from ctypes import (CDLL, c_void_p, byref, c_ulong, c_ulonglong, c_size_t,
  127. create_string_buffer, c_ubyte, c_uint)
  128. from ctypes.util import find_library
  129. from ctypes import Array as _Array
  130. null_pointer = None
  131. cached_architecture = []
  132. def load_lib(name, cdecl):
  133. if not cached_architecture:
  134. # platform.architecture() creates a subprocess, so caching the
  135. # result makes successive imports faster.
  136. import platform
  137. cached_architecture[:] = platform.architecture()
  138. bits, linkage = cached_architecture
  139. if "." not in name and not linkage.startswith("Win"):
  140. full_name = find_library(name)
  141. if full_name is None:
  142. raise OSError("Cannot load library '%s'" % name)
  143. name = full_name
  144. return CDLL(name)
  145. def get_c_string(c_string):
  146. return c_string.value
  147. def get_raw_buffer(buf):
  148. return buf.raw
  149. # ---- Get raw pointer ---
  150. _c_ssize_t = ctypes.c_ssize_t
  151. _PyBUF_SIMPLE = 0
  152. _PyObject_GetBuffer = ctypes.pythonapi.PyObject_GetBuffer
  153. _PyBuffer_Release = ctypes.pythonapi.PyBuffer_Release
  154. _py_object = ctypes.py_object
  155. _c_ssize_p = ctypes.POINTER(_c_ssize_t)
  156. # See Include/object.h for CPython
  157. # and https://github.com/pallets/click/blob/master/click/_winconsole.py
  158. class _Py_buffer(ctypes.Structure):
  159. _fields_ = [
  160. ('buf', c_void_p),
  161. ('obj', ctypes.py_object),
  162. ('len', _c_ssize_t),
  163. ('itemsize', _c_ssize_t),
  164. ('readonly', ctypes.c_int),
  165. ('ndim', ctypes.c_int),
  166. ('format', ctypes.c_char_p),
  167. ('shape', _c_ssize_p),
  168. ('strides', _c_ssize_p),
  169. ('suboffsets', _c_ssize_p),
  170. ('internal', c_void_p)
  171. ]
  172. # Extra field for CPython 2.6/2.7
  173. if sys.version_info[0] == 2:
  174. _fields_.insert(-1, ('smalltable', _c_ssize_t * 2))
  175. def c_uint8_ptr(data):
  176. if byte_string(data) or isinstance(data, _Array):
  177. return data
  178. elif isinstance(data, _buffer_type):
  179. obj = _py_object(data)
  180. buf = _Py_buffer()
  181. _PyObject_GetBuffer(obj, byref(buf), _PyBUF_SIMPLE)
  182. try:
  183. buffer_type = c_ubyte * buf.len
  184. return buffer_type.from_address(buf.buf)
  185. finally:
  186. _PyBuffer_Release(byref(buf))
  187. else:
  188. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  189. # ---
  190. class VoidPointer_ctypes(_VoidPointer):
  191. """Model a newly allocated pointer to void"""
  192. def __init__(self):
  193. self._p = c_void_p()
  194. def get(self):
  195. return self._p
  196. def address_of(self):
  197. return byref(self._p)
  198. def VoidPointer():
  199. return VoidPointer_ctypes()
  200. backend = "ctypes"
  201. del ctypes
  202. class SmartPointer(object):
  203. """Class to hold a non-managed piece of memory"""
  204. def __init__(self, raw_pointer, destructor):
  205. self._raw_pointer = raw_pointer
  206. self._destructor = destructor
  207. def get(self):
  208. return self._raw_pointer
  209. def release(self):
  210. rp, self._raw_pointer = self._raw_pointer, None
  211. return rp
  212. def __del__(self):
  213. try:
  214. if self._raw_pointer is not None:
  215. self._destructor(self._raw_pointer)
  216. self._raw_pointer = None
  217. except AttributeError:
  218. pass
  219. def load_pycryptodome_raw_lib(name, cdecl):
  220. """Load a shared library and return a handle to it.
  221. @name, the name of the library expressed as a PyCryptodome module,
  222. for instance Crypto.Cipher._raw_cbc.
  223. @cdecl, the C function declarations.
  224. """
  225. split = name.split(".")
  226. dir_comps, basename = split[:-1], split[-1]
  227. attempts = []
  228. for ext in extension_suffixes:
  229. try:
  230. filename = basename + ext
  231. return load_lib(pycryptodome_filename(dir_comps, filename),
  232. cdecl)
  233. except OSError as exp:
  234. attempts.append("Trying '%s': %s" % (filename, str(exp)))
  235. raise OSError("Cannot load native module '%s': %s" % (name, ", ".join(attempts)))
  236. def is_buffer(x):
  237. """Return True if object x supports the buffer interface"""
  238. return isinstance(x, (bytes, bytearray, memoryview))
  239. def is_writeable_buffer(x):
  240. return (isinstance(x, bytearray) or
  241. (isinstance(x, memoryview) and not x.readonly))