You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.py 2.0KB

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