common.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- test-case-name: twisted.conch.test.test_ssh -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Common functions for the SSH classes.
  6. Maintainer: Paul Swartz
  7. """
  8. import struct
  9. from cryptography.utils import int_to_bytes
  10. from twisted.python.deprecate import deprecated
  11. from twisted.python.versions import Version
  12. __all__ = ["NS", "getNS", "MP", "getMP", "ffs"]
  13. def NS(t):
  14. """
  15. net string
  16. """
  17. if isinstance(t, str):
  18. t = t.encode("utf-8")
  19. return struct.pack("!L", len(t)) + t
  20. def getNS(s, count=1):
  21. """
  22. get net string
  23. """
  24. ns = []
  25. c = 0
  26. for i in range(count):
  27. (l,) = struct.unpack("!L", s[c : c + 4])
  28. ns.append(s[c + 4 : 4 + l + c])
  29. c += 4 + l
  30. return tuple(ns) + (s[c:],)
  31. def MP(number):
  32. if number == 0:
  33. return b"\000" * 4
  34. assert number > 0
  35. bn = int_to_bytes(number)
  36. if ord(bn[0:1]) & 128:
  37. bn = b"\000" + bn
  38. return struct.pack(">L", len(bn)) + bn
  39. def getMP(data, count=1):
  40. """
  41. Get multiple precision integer out of the string. A multiple precision
  42. integer is stored as a 4-byte length followed by length bytes of the
  43. integer. If count is specified, get count integers out of the string.
  44. The return value is a tuple of count integers followed by the rest of
  45. the data.
  46. """
  47. mp = []
  48. c = 0
  49. for i in range(count):
  50. (length,) = struct.unpack(">L", data[c : c + 4])
  51. mp.append(int.from_bytes(data[c + 4 : c + 4 + length], "big"))
  52. c += 4 + length
  53. return tuple(mp) + (data[c:],)
  54. def ffs(c, s):
  55. """
  56. first from second
  57. goes through the first list, looking for items in the second, returns the first one
  58. """
  59. for i in c:
  60. if i in s:
  61. return i
  62. @deprecated(Version("Twisted", 16, 5, 0))
  63. def install():
  64. # This used to install gmpy, but is technically public API, so just do
  65. # nothing.
  66. pass