utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """miscellaneous zmq_utils wrapping"""
  2. # Copyright (C) PyZMQ Developers
  3. # Distributed under the terms of the Modified BSD License.
  4. from zmq.error import InterruptedSystemCall, _check_rc, _check_version
  5. from ._cffi import ffi
  6. from ._cffi import lib as C
  7. def has(capability):
  8. """Check for zmq capability by name (e.g. 'ipc', 'curve')
  9. .. versionadded:: libzmq-4.1
  10. .. versionadded:: 14.1
  11. """
  12. _check_version((4, 1), 'zmq.has')
  13. if isinstance(capability, str):
  14. capability = capability.encode('utf8')
  15. return bool(C.zmq_has(capability))
  16. def curve_keypair():
  17. """generate a Z85 key pair for use with zmq.CURVE security
  18. Requires libzmq (≥ 4.0) to have been built with CURVE support.
  19. Returns
  20. -------
  21. (public, secret) : two bytestrings
  22. The public and private key pair as 40 byte z85-encoded bytestrings.
  23. """
  24. public = ffi.new('char[64]')
  25. private = ffi.new('char[64]')
  26. rc = C.zmq_curve_keypair(public, private)
  27. _check_rc(rc)
  28. return ffi.buffer(public)[:40], ffi.buffer(private)[:40]
  29. def curve_public(private):
  30. """Compute the public key corresponding to a private key for use
  31. with zmq.CURVE security
  32. Requires libzmq (≥ 4.2) to have been built with CURVE support.
  33. Parameters
  34. ----------
  35. private
  36. The private key as a 40 byte z85-encoded bytestring
  37. Returns
  38. -------
  39. bytestring
  40. The public key as a 40 byte z85-encoded bytestring.
  41. """
  42. if isinstance(private, str):
  43. private = private.encode('utf8')
  44. _check_version((4, 2), "curve_public")
  45. public = ffi.new('char[64]')
  46. rc = C.zmq_curve_public(public, private)
  47. _check_rc(rc)
  48. return ffi.buffer(public)[:40]
  49. def _retry_sys_call(f, *args, **kwargs):
  50. """make a call, retrying if interrupted with EINTR"""
  51. while True:
  52. rc = f(*args)
  53. try:
  54. _check_rc(rc)
  55. except InterruptedSystemCall:
  56. continue
  57. else:
  58. break
  59. return rc
  60. PYZMQ_DRAFT_API: bool = bool(C.PYZMQ_DRAFT_API)
  61. __all__ = ['has', 'curve_keypair', 'curve_public', 'PYZMQ_DRAFT_API']