Simplify pageant implementation by using an anonymous mmap instead of an explicit file. Requires Python 2.5.

This commit is contained in:
Jason R. Coombs 2012-11-23 13:07:28 -05:00
parent 45aa88b530
commit 64d6734086
1 changed files with 13 additions and 17 deletions

View File

@ -21,9 +21,8 @@
Functions for communicating with Pageant, the basic windows ssh agent program. Functions for communicating with Pageant, the basic windows ssh agent program.
""" """
import os
import struct import struct
import tempfile import threading
import mmap import mmap
import array import array
import platform import platform
@ -67,35 +66,32 @@ def _query_pageant(msg):
# Raise a failure to connect exception, pageant isn't running anymore! # Raise a failure to connect exception, pageant isn't running anymore!
return None return None
# Write our pageant request string into the file (pageant will read this to determine what to do) map_name = 'PageantRequest%08x' % threading.current_thread().ident
filename = tempfile.mktemp('.pag')
map_filename = os.path.basename(filename)
f = open(filename, 'w+b') # Create the shared memory from which Pageant will read the request
f.write(msg ) pymap = mmap.mmap(-1, _AGENT_MAX_MSGLEN, tagname=map_name,
# Ensure the rest of the file is empty, otherwise pageant will read this access=mmap.ACCESS_WRITE)
f.write('\0' * (_AGENT_MAX_MSGLEN - len(msg)))
# Create the shared file map that pageant will use to read from
pymap = mmap.mmap(f.fileno(), _AGENT_MAX_MSGLEN, tagname=map_filename, access=mmap.ACCESS_WRITE)
try: try:
pymap.write(msg)
# Create an array buffer containing the mapped filename # Create an array buffer containing the mapped filename
char_buffer = array.array("c", map_filename + '\0') char_buffer = array.array("c", map_name + '\0')
char_buffer_address, char_buffer_size = char_buffer.buffer_info() char_buffer_address, char_buffer_size = char_buffer.buffer_info()
# Create a string to use for the SendMessage function call # Create a string to use for the SendMessage function call
cds = COPYDATASTRUCT(_AGENT_COPYDATA_ID, char_buffer_size, char_buffer_address) cds = COPYDATASTRUCT(_AGENT_COPYDATA_ID, char_buffer_size,
char_buffer_address)
response = ctypes.windll.user32.SendMessageA(hwnd, win32con_WM_COPYDATA, ctypes.sizeof(cds), ctypes.byref(cds)) response = ctypes.windll.user32.SendMessageA(hwnd,
win32con_WM_COPYDATA, ctypes.sizeof(cds), ctypes.byref(cds))
if response > 0: if response > 0:
pymap.seek(0)
datalen = pymap.read(4) datalen = pymap.read(4)
retlen = struct.unpack('>I', datalen)[0] retlen = struct.unpack('>I', datalen)[0]
return datalen + pymap.read(retlen) return datalen + pymap.read(retlen)
return None return None
finally: finally:
pymap.close() pymap.close()
f.close()
# Remove the file, it was temporary only
os.unlink(filename)
class PageantConnection (object): class PageantConnection (object):