common.py 2.2 KB

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